http://stackoverflow.com/comment/91964997
comment on: http://stackoverflow.com/q/52512262
score: 0
has text: `set.intersection(set(list1),set(list2))`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92019444
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52539828
score: 0
has text: Can you add more detail to the question, an example possibly of what you're trying to match etc.

http://stackoverflow.com/comment/92099547
comment on: http://stackoverflow.com/a/52582189
score: 0
type: Comment
type: AnswerComment
has text: @Ehsan: the point is that it is strange to define a list of 300 elements, and only fill the first two. In software design the idea is that functions are independent elements, that each solve a specific task, with not much "influence" of the specific use case, or other functions.

http://stackoverflow.com/q/52575873
has title: how parameters are passed around inside `__getattr__`
has answer: http://stackoverflow.com/a/52576092
has body: I understand the basic function and use case of __getattr__ method. But I'm having trouble how parameters are passed around inside __getattr__. I have code class Wrapper: def __init__(self, object): self.wrapped = object def __getattr__(self, attrname): print('trace: ' + attrname) return getattr(self.wrapped, attrname) x = Wrapper([1, 2, 3]) x.append(4) print(x.wrapped) And it prints trace: append [1, 2, 3, 4] Forgive me if my assumption below is incorrect. I assume that the parameter 4 in x.append(4) is somehow passed from the initial call to __getattr__ and then to the call to getattr method and then to the append method of list class. But I'm not sure what exactly is happening. Could someone please clarify the details.
tagged with: delegates
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52576092
downvote count: 0
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52575985
tagged with: python
linked to: http://stackoverflow.com/q/11949808
has comment: http://stackoverflow.com/comment/92087217
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/92087202
upvote count: 1
accepted answer: http://stackoverflow.com/a/52575985

http://stackoverflow.com/q/52540121
has answer: http://stackoverflow.com/a/68628989
type: Question
has answer: http://stackoverflow.com/a/57013889
possible better answer: http://stackoverflow.com/a/60234402
downvote count: 0
accepted answer: http://stackoverflow.com/a/52540270
has body: I want Pipenv to make virtual environment in the same folder with my project (Django). I searched and found the PIPENV_VENV_IN_PROJECT option but I don't know where and how to use this.
has answer: http://stackoverflow.com/a/60234402
has answer: http://stackoverflow.com/a/79200134
upvote count: 96
has answer: http://stackoverflow.com/a/78195043
has answer: http://stackoverflow.com/a/57532697
has title: Make Pipenv create the virtualenv in the same folder
favorite count: 0
answer count: 9
score: 96
tagged with: python
has answer: http://stackoverflow.com/a/75207804
has answer: http://stackoverflow.com/a/52540270
has answer: http://stackoverflow.com/a/74195760
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92019981
tagged with: pipenv
has comment: http://stackoverflow.com/comment/92020105

http://stackoverflow.com/comment/92016974
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52525516
score: 0
has text: It works now, i still get some OOM errors but the trainer start and works.

http://stackoverflow.com/comment/92009149
has text: No problem! :).
comment on: http://stackoverflow.com/a/52534556
score: 0
type: AnswerComment
type: Comment

edit-distance
type: Tag
tags question: http://stackoverflow.com/q/52486140
tag name: edit-distance

http://stackoverflow.com/q/52459850
has title: Labelling data based on two columns
type: Question
type: AnsweredQuestion
tagged with: anaconda
tagged with: dataframe
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52460025
tagged with: python
has answer: http://stackoverflow.com/a/52460025
score: 1
has body: I have a dataframe with several columns that looks like this: id | x1 | text | x2 | num | x3 | class 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | 2nn| TT | word | QQ | 1 | TT | # They don't all have the same vals 2nn| TT | word | QQ | 1 | TT | # This is just to illustrate it I also have the following lists with strings: class1 = ["",...] class2 = ["",...] class3 = ["",...] class4 = ["",...] class5 = ["",...] # Multiple strings, I just used '...' for simplicity I am trying to assign classes in column class such that if the words in a transaction (row)'s text column contains any word found in any of the lists, assign the list name as the class. I am doing this to label some data that I will eventually end up using for classification. I want to perform this labelling only on data starting from row 10,000 onwards. What I'm using is: # last 6000 rows for index, row in df.tail(6000).iterrows(): if df[df['text'].str.contains(class1)==True]: df.loc[row, 'class'] = "class1" if df[df['text'].str.contains(class2)==True]: df.loc[row, 'class'] = "class2" if df[df['text'].str.contains(class3)==True]: df.loc[row, 'class'] = "class3" if df[df['text'].str.contains(class4)==True]: df.loc[row, 'class'] = "class4" if df[df['text'].str.contains(class5)==True]: df.loc[row, 'class'] = "class5" I am getting a response that prints the following error: TypeError: unhashable type: 'list' Below is my code when trying Chris A's response: # Word bins for the various labels complaint = ["sucks", "worst", "doesn't", "didn't", "won't", "bad", "horrible", "unusable", "cannot", "can't", "not", "did not", "waste", "hate", "hated", "awful", "useless", "sucked", "freezing", "freezes", "froze", "does not", "crap",…

http://stackoverflow.com/comment/91951007
type: QuestionComment
score: 1
has text: Have you tried `map` instead of `imap`?
comment on: http://stackoverflow.com/q/52505225
type: Comment

http://stackoverflow.com/comment/91985562
has text: @Kdog: This is not yet an MCVE; it's a full program with no problem specification. What's wrong with your code? This is certainly not the minimal code that exhibits your trouble. Stack Overflow is for specific coding problems, not general tutorial assistance or evaluation of full applications.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52508293
type: QuestionComment

http://stackoverflow.com/q/52488615
has comment: http://stackoverflow.com/comment/92236552
has answer: http://stackoverflow.com/a/52629002
has answer: http://stackoverflow.com/a/52602637
has comment: http://stackoverflow.com/comment/91918742
has comment: http://stackoverflow.com/comment/91918718
has comment: http://stackoverflow.com/comment/92138558
upvote count: 8
has comment: http://stackoverflow.com/comment/92232981
tagged with: python
has answer: http://stackoverflow.com/a/52635789
score: 7
has comment: http://stackoverflow.com/comment/91918622
favorite count: 0
has comment: http://stackoverflow.com/comment/92231939
has comment: http://stackoverflow.com/comment/92231612
has answer: http://stackoverflow.com/a/52545694
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52639324
has comment: http://stackoverflow.com/comment/91991029
has answer: http://stackoverflow.com/a/52636827
type: Question
has comment: http://stackoverflow.com/comment/91918726
has comment: http://stackoverflow.com/comment/91918701
has comment: http://stackoverflow.com/comment/91918677
has comment: http://stackoverflow.com/comment/91918709
has comment: http://stackoverflow.com/comment/92232032
has title: Get top 5 values where key total is less than or equal to X
has comment: http://stackoverflow.com/comment/91918557
has body: Currently I have a list of items someone can buy as follows: my_list = [ ('Candy', 1.0, 20.5), ('Soda', 3.0, 10.25), ('Coffee', 1.2, 20.335), ('Soap', 1.2, 11.5), ('Spoon', 0.2, 2.32), ('Toast', 3.2, 12.335), ('Toothpaste', 3, 20.5), ('Creamer', .1, 5.5), ('Sugar', 2.2, 5.2), ] Each item is set up like this: ('Item Name', ItemCost, ItemValue) I have the list pulling the items with the top 5 ItemValue. print nlargest(5, my_list, key=itemgetter(2)) &gt;&gt;&gt; [ ('Candy', 1.0, 20.5), ('Toothpaste', 3, 20.5), ('Coffee', 1.2, 20.335), ('Toast', 3.2, 12.335), ('Soap', 1.2, 11.5), ] I am trying to retrieve a result where I get the top 5 total ItemValue where the top 5 total ItemCost is equal or less than 6. Any suggestions?
tagged with: python-2.7
answer count: 8
has answer: http://stackoverflow.com/a/52488721
has comment: http://stackoverflow.com/comment/92232747
has answer: http://stackoverflow.com/a/52633540

http://stackoverflow.com/q/52458461
has title: import matplotlib.pyplot as plt failed
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91859321
has comment: http://stackoverflow.com/comment/91859160
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52829786
linked to: http://stackoverflow.com/q/24243203
linked to: http://stackoverflow.com/q/43573248
has comment: http://stackoverflow.com/comment/91860494
has comment: http://stackoverflow.com/comment/91859258
tagged with: python
has body: File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\franc\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 32, in &lt;module&gt; import matplotlib.colorbar File "C:\Users\franc\Anaconda3\lib\site-packages\matplotlib\colorbar.py", line 32, in &lt;module&gt; import matplotlib.contour as contour File "C:\Users\franc\Anaconda3\lib\site-packages\matplotlib\contour.py", line 18, in &lt;module&gt; import matplotlib.font_manager as font_manager File "C:\Users\franc\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1363, in &lt;module&gt; _rebuild() File "C:\Users\franc\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1344, in _rebuild fontManager = FontManager() File "C:\Users\franc\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 978, in __init__ ttffiles = findSystemFonts(paths) + findSystemFonts() File "C:\Users\franc\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 264, in findSystemFonts fontfiles.update(win32InstalledFonts(fontext=fontext)) TypeError: 'NoneType' object is not iterable I've tried to uninstall and reinstall matplotlib in many ways, but I still get the above error.
favorite count: 0
has comment: http://stackoverflow.com/comment/91861382
has comment: http://stackoverflow.com/comment/91859468
accepted answer: http://stackoverflow.com/a/52829786
linked to: http://stackoverflow.com/q/48268935
upvote count: 1
linked to: http://stackoverflow.com/q/24302091
type: Question
has comment: http://stackoverflow.com/comment/91859758
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91859536
has comment: http://stackoverflow.com/comment/91859342
score: 1

http://stackoverflow.com/q/52528278
tagged with: python
has comment: http://stackoverflow.com/comment/91996115
type: AnsweredQuestion
downvote count: 3
type: Question
score: -2
has answer: http://stackoverflow.com/a/52528494
accepted answer: http://stackoverflow.com/a/52528494
tagged with: linux
upvote count: 1
answer count: 1
favorite count: 0
has title: Can I read code from a previously run python script
has body: I ran a python file using the command python file.py and it executed successfully. Right after I managed to delete the file, can I recover the code that was run in the previous command? I still have the terminal open and have not typed anything else into it. Running ubuntu.
tagged with: recovery

http://stackoverflow.com/comment/91938449
has text: Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
score: 4
type: Comment
comment on: http://stackoverflow.com/q/52493328
type: QuestionComment

http://stackoverflow.com/comment/91888111
type: Comment
comment on: http://stackoverflow.com/q/52473178
score: 0
type: QuestionComment
has text: How exactly do you want to compare the dictionaries? What is your desired output?

http://stackoverflow.com/q/52572003
score: 5
upvote count: 5
has body: I have written a code for web scraping using python. The code extracts data of Macbook from amazon using selenium. Now I want to store these values in a Excel or MySql. There are various html/css class in a particular product row and one parent class which includes all the parameters of the product. To be Precise the code is: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException import xlwt from xlwt import Workbook option = webdriver.ChromeOptions() option.add_argument("--incognito") browser = webdriver.Chrome(executable_path='/home/mukesh/Desktop/backup/Programminghub/whatsapp_python_scripts/chromedriver_linux64/chromedriver', chrome_options=option) # go to website of interest browser.get("https://www.amazon.in/s/ref=nb_sb_noss_2?url=search-alias%3Daps&amp;field-keywords=macbook") # wait up to 10 seconds for page to load timeout = 10 try: WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, "//img[@class='s-access-image cfMarker']"))) except TimeoutException: print("Timed out waiting for page to load") browser.quit() titles_element = browser.find_elements_by_xpath("//div[@class='s-item-container']") titles = [] for x in titles_element: value=x.text value=value.encode('ascii', 'ignore') titles.append(value) print(titles) Now the output that I get is highly unstructured and contains some parameters which are there only on certain products. For instance the Parameter: "Maximum Resolution" or "CPU model manufacture" are present only on certain laptops and not on all.I don't want such parameters.I want only these parameters: Product name(Title of the row), Price,Operating System,Cpu model family,computer memory size and display size which are present on all the laptops. I am unable to split the titles list in these sub list. I tried a foolish app…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: selenium
tagged with: web-scraping
tagged with: web-crawler
has answer: http://stackoverflow.com/a/52572688
has title: Storing the results of Web Scraping into Database
accepted answer: http://stackoverflow.com/a/52572688
type: Question

http://stackoverflow.com/q/52492832
tagged with: python
linked to: http://stackoverflow.com/q/49310470
has comment: http://stackoverflow.com/comment/91959634
answer count: 0
tagged with: authentication
duplicate of: http://stackoverflow.com/q/49310470
tagged with: http
type: Question
has body: UPDATE: It looks like the link requires a log in, I updated the title. This is a link for a particular Kaggle data file that I'm trying to download into Python (Google Colab if it makes a difference) This is the link https://www.kaggle.com/azathoth42/myanimelist/downloads/UserAnimeList.csv/9 Which I got from here https://www.kaggle.com/azathoth42/myanimelist#UserAnimeList.csv I tried using wget with the following code !pip install wget !wget -i https://www.kaggle.com/azathoth42/myanimelist/downloads/UserAnimeList.csv/9 Which didn't seem to work I then tried from urllib import request request.urlretrieve('https://www.kaggle.com/azathoth42/myanimelist/downloads/UserAnimeList.csv/9' , 'download.zip') The issue I now know is that it requires a log in. Edit: This link shows how to download Kaggle data into colab complete with an example notebook Using kaggle datasets into Google Colab
has comment: http://stackoverflow.com/comment/91958402
linked to: http://stackoverflow.com/q/31554771
score: 0
duplicate of: http://stackoverflow.com/q/31554771
has title: Download from a link that requires to log in
type: UnansweredQuestion

http://stackoverflow.com/a/52463308
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/52462547
downvote count: 0
has body: "w" == it is checking if w (a string) equals your iterator which is obviously False as your iterator encapsulates a sequence which may or may not contain w. To check for existence of an element using equality you'll have to actually iterate over your iterator and then check if any of the elements encountered during the iteration equals your search element, i.e.: print(any(i == "w" for i in it)) but that's what print("w" in it) internally does, anyway. Keep in mind that the above will exhaust (partially on match, completely if the element is not matched) your iterator, just like "w" in it does, because you need to iterate over an iterator to determine if any of the elements matches your search element, e.g. t = "cawqv" it = iter(t) print("w" in it) # True print("w" in it) # False - we're pass the `w` point by now print("q" in it) # False - we already exhausted our iterator

http://stackoverflow.com/q/52554457
answer count: 1
has title: What are the outputs of the Object Detection API of Tensorflow?
has answer: http://stackoverflow.com/a/55574401
favorite count: 0
tagged with: video-processing
type: UnansweredQuestion
tagged with: python
score: 3
downvote count: 0
tagged with: image-processing
tagged with: tensorflow
type: Question
has body: I used Tensorflow's Object Detection API found in https://github.com/tensorflow/models/tree/master/research/object_detection. I used summarize_graph and verified that the outputs are detection_boxes, detection_scores, detection_classes, and num_detections. What are these? Which of these contains the coordinates of the detection box of the detected objects? I displayed the shape of each of the output and found their sizes: detection_boxes.shape = (1,300,4) detection_scores.shape = (1, 300) detection_classes.shape = (1, 300) num_detections.shape = (1,) when tested on one image that contains 8 playing cards. The classes considered were the numbers A, 2, 3, 4, 5, &amp; 6.
upvote count: 3

http://stackoverflow.com/q/52499074
score: 0
answer count: 2
has title: PHP encode html for json_encode
has comment: http://stackoverflow.com/comment/91939407
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91940637
accepted answer: http://stackoverflow.com/a/52500419
has body: I am getting data of a WordPress post. In WordPress data is present in HTML format as it is tinymce edit field. In this field data is like this Caratteristiche principali: Sistema multimediale Toyota Touch� 2 with Go con display 8'' e telecamera posteriore Sedile guidatore con supporto lombare regolabile elettricamente Sedili anteriori riscaldabili Toyota Safety Sense I have made an array with this field data and with few others. Now I want to encode above content in a way I can get array data in JSON format using json_encode function. When json_encode runs it does not return json because of above html data. Can you please propose me a solution how I can do this correctly. Next, I need to use this JSON data in python and to save in psql. I want to keep data in psql in html formate. here what I am doing <?php //php 7.0.8 $data_arr = Array ( 'post_name' => 'toyota-c-hr-1-8-ibrida-122cv-cvt-business-24-mesi', 'caratteristiche_tecniche' => ' Caratteristiche principali: Sistema multimediale Toyota Touch® 2 with Go con display 8'' e telecamera posteriore Sedile guidatore con supporto lombare regolabile elettricamente Sedili anteriori riscaldabili Toyota Safety Sense ? Sistema Pre-Collisione ? Avviso superamento corsia ? Abbaglianti automatici ? Riconoscimento segnaletica stradale ? Sistema Pre-Collisione con rilevamento pedoni ? Cruise Control adattivo Marca TOYOTA Modello C-HR Allestimento 1.8H (122CV) E-CVT Business Cilindrata Effettiva 1798 Cm3 Cilindrata 1798 L Pacchetto (Tipo Eletta, Sport) 1.8H (122CV) E-CVT Business Model Year 2017 Peso 1455 Kg Portata 405 Kg Tipo Veicolo Manufacturer Vehicle Emissioni C02 86 G/Km Trazione Front Consumo Combinato 3.8 Litri Per 100km Porte 5-Door Posti 5 Alimentazione Unleaded - Electric / Cambio AUT Potenza Massima KW 90 KW Potenza Massima CV 122 CV Cavalli Fiscali 19 Corpo Veicolo Sport Utility Vehicle Codice Ruote Anteriori 215/60 C17 96H Codice Ruote Posteriori 215/60 C17 96H ', 'marca' => 'Toyota' ); echo json_encode($data_arr)…
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/91940526
has comment: http://stackoverflow.com/comment/91940556
has comment: http://stackoverflow.com/comment/91939622
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91943800
type: Question
has comment: http://stackoverflow.com/comment/91939650
possible better answer: http://stackoverflow.com/a/52499608
has answer: http://stackoverflow.com/a/52500419
has answer: http://stackoverflow.com/a/52499608

http://stackoverflow.com/comment/92003086
comment on: http://stackoverflow.com/a/52522364
score: 0
type: AnswerComment
has text: This incorrectly produces many combinations where items have met before. For example, `[3, 10, 13]` appears in both the second and the third combinations in your sample output, and `12` and `14` have met in both `[9, 12, 14]` in the second combination and `[6, 12, 14]` in the third combination..
type: Comment

http://stackoverflow.com/comment/92059264
has text: Can haz confirmed answer? :P
comment on: http://stackoverflow.com/q/52544562
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92035219
score: 0
type: Comment
has text: Yeah, this is the solution I would do but with defaultdict int instead.
type: AnswerComment
comment on: http://stackoverflow.com/a/52547923

http://stackoverflow.com/a/52449135
accepted answer of: http://stackoverflow.com/q/52448510
has comment: http://stackoverflow.com/comment/91844979
type: Answer
answers question: http://stackoverflow.com/q/52448510
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91843106
has comment: http://stackoverflow.com/comment/91841427
has comment: http://stackoverflow.com/comment/91841520
has comment: http://stackoverflow.com/comment/91844951
type: AcceptedAnswer
downvote count: 0
has body: I think it's instructional to break down your attempts one by one and talk about what went wrong in each one. For starters, your input list is a 2-dimensional list of numbers as strings. You'll need to cast them to int, preferably right off the bat. However, I'll assume the input list you're working with in your code is the following: [['1', '1', '-2'], ['-1', '-2', '-3'], ['1', '1', '1']] which needs its elements to be cast to int to avoid crashing. Attempt 1 Your code: row = len(numbers) column = len(numbers[0]) total = 0 for row in numbers: rowtotal = 0 for column in numbers: # &lt;-- are these really columns as advertised or still rows? rowtotal = rowtotal + numbers[row][column] # &lt;-- crash! print(rowtotal) total = total + rowtotal # &lt;-- are you sure you want to do this here? print(total) The primary misunderstanding is that your statement for row in numbers: loops through the actual lists in the numbers list, not the indices of this list. In other words, row is equal to ['1', '1', '-2'] on the first iteration, not 0. Similarly, for column in numbers: is mis-labeled and also iterates over row lists rather than the intended cells in rows. The crash happens when you try to index into the list numbers using these items. Your code is doing: numbers[['1', '1', '-2']][['1', '1', '-2']] # crash You can fix this by not attempting to index into the numbers list, but instead using the row and column elements to compute the total. You also have a logic error that prematurely adds rowtotal to the aggregate total, which over counts. Lastly, the first two lines do nothing because the values are overwritten by the loop variables; remove them. Here's a re-write: total = 0 for row in numbers: rowtotal = 0 for column in row: # &lt;-- iterating cells in rows rowtotal = rowtotal + int(column) # &lt;-- much better total = total + rowtotal # &lt;-- logic error fixed print(total) Attempt 2 Your code: row = len(numbers) column = len(numbers[0]) total = 0 for row in range (len(num…

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

http://stackoverflow.com/comment/91970149
has text: As Chiefir says, the problem is you have defined a single view - CatalogView - and are attempting to include it in a router. Why are you doing that? Are CompanyView and UserView also just views? Routers are for viewsets.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52514856
type: QuestionComment

http://stackoverflow.com/q/52451794
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91847028
upvote count: 3
accepted answer: http://stackoverflow.com/a/52451853
tagged with: scipy
type: Question
has body: I am trying to use scipy's odeint to solve some ordinary differential equations. The only problem is that I only want to define one argument, and it seems that to make a tuple, you need at least two values. My code looks like this: def system(state, t, inputs) x = state[0] u = inputs a = -4 b = 2 dxdt = [a * x + b * u] return dxdt inputs = 5 x_next = odeint(system, x, t, args=(inputs)) This will return an error because args must be a tuple, and (inputs) is a int/float and not a tuple. One way to overcome this is to put a, b as part of the args. But that is just a bandaid on a wound. I was wondering if there is any ways to define the args as just one value.
downvote count: 0
tagged with: tuples
has title: How to pass only one argument to odeint?
has comment: http://stackoverflow.com/comment/91847041
score: 3
answer count: 1
has answer: http://stackoverflow.com/a/52451853
favorite count: 0
tagged with: odeint
tagged with: python

http://stackoverflow.com/q/52580521
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92096336
upvote count: 1
has body: I have tried constructing a neural network for the XOR-function. The network has 1 hidden layer with 2 nodes in addition to a bias node. The Sigmoid function is used as activation function. I have tested the network for multiple learning rates. The result is always the same: the network give the value 0.5 for all inputs. There are some other threads where people report the same problem, but as far as I can see, other mistakes were done in those cases. The following code shows my network and the results. import numpy as np import matplotlib.pyplot as plt class NN: """ XOR function test. 1 hidden layer with 2 hidden nodes in addition to bias node.""" def __init__(self, nodeNumbers, learningRate, targetMatrix, inputMatrix, errorTolerance, \ maxIterations): self.nodeNumbers, self.learningRate, self.targetMatrix, \ self.inputMatrix, self.errorTolerance, self.maxIterations = \ nodeNumbers, learningRate, targetMatrix, inputMatrix, errorTolerance, \ maxIterations self.numberOfInputs = np.shape(self.inputMatrix)[1] self.weightMatrices = [] for nodeNumber in range(len(nodeNumbers[1:])): self.weightMatrices.append(np.random.random_sample((nodeNumbers[nodeNumber+1], \ nodeNumbers[nodeNumber]+1)).T - .5) def activationFunction(self, x): return 1./(1+np.exp(-x)) def derivative(self, weightedInputs): return self.activationFunction(weightedInputs)*(1 - self.activationFunction(weightedInputs)) def run(self): self.iterationNumber = 0 numberOfAdjustmentsDuringIteration = 1 while (self.iterationNumber &lt; self.maxIterations and numberOfAdjustmentsDuringIteration != 0): self.iterationNumber += 1 numberOfAdjustmentsDuringIteration = 0 for inputNumber in range(self.numberOfInputs): self.inputs = self.inputMatrix[:,inputNumber] self.targets = self.targetMatrix[inputNumber] self.forward() self.calculateError() if abs(self.error2) &gt; self.errorTolerance: numberOfAdjustmentsDuringIteration +=1 self.backward() print('Iterations: ', self.iterationNumber, '|Error|: ', self.error2) def forward…
type: Question
score: 1
downvote count: 0
tagged with: neural-network
has title: Neural network XOR always gives 0.5
favorite count: 0
tagged with: xor
has comment: http://stackoverflow.com/comment/92096195
type: UnansweredQuestion

http://stackoverflow.com/comment/91983499
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52521728
has text: Until you have a known problem with your program, you do not yet have a valid Stack Overflow question.

http://stackoverflow.com/comment/91993017
comment on: http://stackoverflow.com/q/52525734
score: 1
has text: To obtain a plot y vs. x you would use `plt.plot(x,y)`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52464123
has comment: http://stackoverflow.com/comment/91870270
has body: You can use any one of these optimizers that Tensorflow has implemented, refer here. Also, any of your optimizer (like a Genetic Algorithm) can also be modelled using Tensorflow.
score: 0
has comment: http://stackoverflow.com/comment/91870397
answers question: http://stackoverflow.com/q/52464094
type: Answer
has comment: http://stackoverflow.com/comment/91870288

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/52464539
tags question: http://stackoverflow.com/q/52460511
tags question: http://stackoverflow.com/q/52583098
tags question: http://stackoverflow.com/q/52434724
tags question: http://stackoverflow.com/q/52488977
tags question: http://stackoverflow.com/q/52471361
tags question: http://stackoverflow.com/q/52518294
tags question: http://stackoverflow.com/q/52510586
tags question: http://stackoverflow.com/q/52552211
tags question: http://stackoverflow.com/q/52440041
tags question: http://stackoverflow.com/q/52537445
tags question: http://stackoverflow.com/q/52584097
tags question: http://stackoverflow.com/q/52552784
tags question: http://stackoverflow.com/q/52439290
tags question: http://stackoverflow.com/q/52517905
tags question: http://stackoverflow.com/q/52489365
tags question: http://stackoverflow.com/q/52530756
tags question: http://stackoverflow.com/q/52514453
tags question: http://stackoverflow.com/q/52462931
tags question: http://stackoverflow.com/q/52488885
tags question: http://stackoverflow.com/q/52494567
tags question: http://stackoverflow.com/q/52548890
tags question: http://stackoverflow.com/q/52485045
tags question: http://stackoverflow.com/q/52534075
tags question: http://stackoverflow.com/q/52568312
tags question: http://stackoverflow.com/q/52454246
tags question: http://stackoverflow.com/q/52445743
tags question: http://stackoverflow.com/q/52485382
tags question: http://stackoverflow.com/q/52588466
tags question: http://stackoverflow.com/q/52489578
tags question: http://stackoverflow.com/q/52533697
tags question: http://stackoverflow.com/q/52459844
tags question: http://stackoverflow.com/q/52527932
tags question: http://stackoverflow.com/q/52452174
type: Tag
tags question: http://stackoverflow.com/q/52580747
tags question: http://stackoverflow.com/q/52435842
tags question: http://stackoverflow.com/q/52508541
tags question: http://stackoverflow.com/q/52461137
tags question: http://stackoverflow.com/q/52519633
tags question: http://stackoverflow.com/q/52507413
tags question: http://stackoverflow.com/q/52499763
tags question: http://stackoverflow.com/q/52499969
tags question: http://stackoverflow.com/q/52578054
tags question: http://stackoverflow.com/q/52529767
tags question: http://stackoverflow.com/q/52572874
tags question: http://stackoverflow.com/q/52521109
tags question: http://stackoverflow.com/q/52439904
tags question: http://stackoverflow.com/q/52510834
tags question: http://stackoverflow.com/q/52575705
tags question: http://stackoverflow.com/q/52465664
tags question: http://stackoverflow.com/q/52438357
tags question: http://stackoverflow.com/q/52538618
tags question: http://stackoverflow.com/q/52497775
tags question: http://stackoverflow.com/q/52449800
tags question: http://stackoverflow.com/q/52441203
tags question: http://stackoverflow.com/q/52467146
tags question: http://stackoverflow.com/q/52545816
tags question: http://stackoverflow.com/q/52511804
tags question: http://stackoverflow.com/q/52507723
tags question: http://stackoverflow.com/q/52472430
tags question: http://stackoverflow.com/q/52504203
tags question: http://stackoverflow.com/q/52465655
tags question: http://stackoverflow.com/q/52587848
tags question: http://stackoverflow.com/q/52463761

http://stackoverflow.com/comment/91951083
has text: "in a json file" it is not a json file, because that isn't a valid JSON-formatted string, which is why the parser is failing.
comment on: http://stackoverflow.com/q/52505247
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/52489032
has comment: http://stackoverflow.com/comment/91919231
score: 0
has comment: http://stackoverflow.com/comment/91920226
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91919255
has comment: http://stackoverflow.com/comment/91920230
type: UnansweredQuestion
has title: Python 2.7 cannot import sklearn
has comment: http://stackoverflow.com/comment/91919415
tagged with: python
has body: I installed sklearn, version: 0.19.2, but cannot import it. Please see the errors below: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-61-b7c74cbf5af0&gt; in &lt;module&gt;() ----&gt; 1 import sklearn c:\python27\lib\site-packages\sklearn\__init__.py in &lt;module&gt;() 131 # process, as it may not be compiled yet 132 else: --&gt; 133 from . import __check_build 134 from .base import clone 135 __check_build # avoid flakes unused variable error ImportError: cannot import name __check_build
has comment: http://stackoverflow.com/comment/91919419
answer count: 0
type: Question
linked to: http://stackoverflow.com/q/15274696

http://stackoverflow.com/q/52436923
has body: Trying to build a simple Weasy Print Application with Django Made a little function at views.py: def generate_pdf(request): # Model data students = Student.objects.all().order_by('last_name') context = { 'invoice_id': 18001, 'street_name': 'Rue 76', 'postal_code': '3100', 'city': 'Washington', 'customer_name': 'John Cooper', 'customer_mail': 'customer@customer.at', 'amount': 1339.99, 'today': 'Today', } # Rendered html_string = render_to_string('pdf/invoice.html', context) html = HTML(string=html_string) result = html.write_pdf() # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_people.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'r') response.write(output.read()) return response After running it I get a UnicodeDecodeError for the line "response.write(output.read())" This is my first time having such a problem, how can I fix that? Thanks!
type: Question
has answer: http://stackoverflow.com/a/53112771
has title: Unicode Decode for Weasy Print
possible better answer: http://stackoverflow.com/a/52436946
downvote count: 0
answer count: 3
tagged with: weasyprint
accepted answer: http://stackoverflow.com/a/53112771
favorite count: 0
has answer: http://stackoverflow.com/a/52591691
upvote count: 2
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52436946

http://stackoverflow.com/a/52530454
has body: I suggest to use dateutil. For instance from dateutil import parser d1 = parser.parse(date_list[0]) d2 = parser.parse(date_list[1]) at this point d1 and d2 are standard datetime objects and you can use the standard methods/operators to operate on them
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52530413
answers question: http://stackoverflow.com/q/52530413
upvote count: 1

http://stackoverflow.com/comment/91860494
comment on: http://stackoverflow.com/q/52458461
score: 0
has text: I think for the moment you may revert to version 2.2.3. I'm not sure what the solution to this problem will be in the end, it's still being discussed, but there should probably be a bugfix release soon.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52462532
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52462497
has body: Your condition to stop the iteration is wrong. You need to set a self.counter to zero in the __init__ method, then in the __next__ method increment this counter and in the condition compare it with max. The second case you got right by coincidence because the fifth element is five.
has comment: http://stackoverflow.com/comment/91868016
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52462497

http://stackoverflow.com/comment/92057904
type: QuestionComment
comment on: http://stackoverflow.com/q/52543550
type: Comment
has text: sorry, I added the code and error. @micha137
score: 0

http://stackoverflow.com/q/52502405
type: UnansweredQuestion
has title: Pass js variable to Jinja template in Ckan
tagged with: python
tagged with: ckan
has comment: http://stackoverflow.com/comment/91946333
has body: I want to pass javascript variable value to jinja2 template to query db according to some user requests.I can store user requests in js variable but I cannot pass variable value to Jinja.Do you have any idea or example?I use ckan project so I have to use Jinja template.I made some research maybe I have to use ajax request but how can I learn which function will be running in backend side as far as I know ckan use pyloans framework in backend side.How to render template in pyloans framework.Do you have any example?
tagged with: jinja2
type: Question
has answer: http://stackoverflow.com/a/52506570
score: 0
has comment: http://stackoverflow.com/comment/91945654
answer count: 1

http://stackoverflow.com/comment/92083425
comment on: http://stackoverflow.com/a/52549253
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot, I’m studying python through my senior code and there are a bunch classes inside class which make me confused a little bit, but I got my answer now.

http://stackoverflow.com/a/52583306
answers question: http://stackoverflow.com/q/52574679
type: Answer
has body: def fitness(self, cromosoma): record = self.numeroN * (self.numeroN - 1) for row in range(len(board)): decodedGenes.append(self.decodeGene(board[row])) for y in range(len(decodedGenes)): x = decodedGenes[y] record = record - self.collisions(decodedGenes, x, y) return record def collisions(self, coords, X, Y): board = [] r = 0 for i in range(len(coords)): board.append([0] * self.numeroN) for y in range(len(coords)): board[y][coords[y]] = 1 for y in range(len(board)): for x in range(len(board)): # if has Queen and is not the same if board[y][x] == 1 and y != Y: # check x if x == X: r = r + 1 # check Diagonals if self.crash_diagonal(x, y, X, Y): r = r + 1 return r def crash_diagonal(self, x1, y1, x2, y2): dx = abs(x1 - x2) dy = abs(y1 - y2) return dx == dy
score: 0

http://stackoverflow.com/comment/91996131
has text: Your link is bad.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52527949

http://stackoverflow.com/q/52456267
has comment: http://stackoverflow.com/comment/113472808
has body: I have a df like this: import numpy as np import pandas as pd import matplotlib.pylab as plt np.random.seed(100) data = np.random.rand(200,3) df = pd.DataFrame(data) df.columns = ['a', 'b', 'y'] df['y_roll'] = df['y'].rolling(10).mean() df['y_roll_predicted'] = df['y_roll'].apply(lambda x: x + np.random.rand()/20) In above code, I created a random pandas df. Then used rolling(10).mean() to perform a moving average ondf['y'] and saved it as df['y_roll']. plot of df['y'] is as follows: Because my model was not able to predict sharp edges of df['y'], I decided to do a rolling.mean() operation on it and try to predict the rolled data, df['y_roll']. Now my model is able to predict df['y_roll'] and its name is: df['y_roll_predicted']. How can I do a reverse of rolling operation on this predicted column, so that I can compare it with df['y'] values? plot of df['y_roll_predicted'] vs df['y_roll'] is as follows:
has title: How to do a reverse moving average ( in pandas, rolling().mean ) operation on predicted values?
has answer: http://stackoverflow.com/a/64158928
has comment: http://stackoverflow.com/comment/91855471
answer count: 1
favorite count: 0
tagged with: moving-average
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/113474593
upvote count: 3
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/64155524
downvote count: 1
type: Question
score: 2

http://stackoverflow.com/q/52510752
favorite count: 0
possible better answer: http://stackoverflow.com/a/52510935
has comment: http://stackoverflow.com/comment/91961531
has body: I'm currently working on some Python code where I'm trying to retrieve a subset of a DataFrame where the column value equals a certain value. I'm doing it like so: for i in brands.index: current_brand = brands.get_value(i, 'Car Brand') my_dataframe_subset = my_dataframe[my_dataframe['Brand'] == current_brand] This of course works in making the subset, but I'm doing this continuously in a loop, thousands of times. What I've found is that this is a huge bottleneck in my execution speed, but unfortunately the 'current_brand' changes every iteration of the loop so I don't see another way. Is there a faster alternative to getting this subset that wouldn't cause such a huge delay? Thanks EDIT: This is a more realistic example of what my code is doing. Obviously the data is gibberish, but I hope you get the idea: ------------------------ |Person | Car Brand | |------------------------ |'dave' | 'Toyota' | |'mike' | 'Ford' | |'sally'| 'Ford' | |'doug' | 'BMW' | ------------------------ my_list = [] for i in brands.index: current_person = brands.get_value(i, 'Person') current_brand = brands.get_value(i, 'Car Brand') my_dataframe_subset = my_dataframe[my_dataframe['Brand'] == current_brand] for i_b in my_dataframe_subset.index: #do stuff with current_person and current_brand car_colour = my_dataframe_subset(i_b, 'Colour') car_speed = my_dataframe_subset(i_b, 'Speeds') my_dict = {'person': current_person, 'brand': current_brand, 'colour': car_colour, 'speed': car_speed} my_list.append(my_dict)
has title: Is there a faster alternative to getting a subset of a DataFrame?
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52510798
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91962135
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/91961856
has answer: http://stackoverflow.com/a/52510935
has answer: http://stackoverflow.com/a/52510778
has comment: http://stackoverflow.com/comment/91962352
accepted answer: http://stackoverflow.com/a/52510778
has comment: http://stackoverflow.com/comment/91962657
has comment: http://stackoverflow.com/comment/91961664
answer count: 3
tagged with: pandas
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/52537518
has body: I had to do this for one of my projects. The way I did this was to create two models. One to define the student, and the other to define a file for import. Then, I had to create a post save hook if I used the option to bulk import a CSV file. models.py import os import csv from django.db import models from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings class Student(models.Model): fname = models.CharField(max_length=32, blank=False, null=False) lname = models.CharField(max_length=32, blank=False, null=False) ... # additional model attributes class StudentImportFile(models.Model): # upload to MEDIA_ROOT/temp student_import = models.FileField(upload_to="temp", blank=False, null=False) def save(self, *args, **kwargs): if self.pk: old_import = StudentImportFile.objects.get(pk=self.pk) if old_import.student_import: old_import.student_import.delete(save=False) return super(StudentImportFile, self).save(*args, **kwargs) # post save signal @receiver(post_save, sender=StudentImportFile, dispatch_uid="add_records_to_student_from_import_file") def add_records_to_student_from_import_file(sender, instance, **kwargs): to_import = os.path.join(settings.MEDIA_ROOT, instance.student_import.name) with open(to_import) as f: reader = csv.DictReader(f) for row in reader: fname = row['First Name'] lname = row['Last Name'] ... # additional fields to read s = Student(fname=fname, lname=lname, ... # additional attributes ) s.save()
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52535552
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92019024
has text: Sure. Anaconda created a Python scripts folder, and log.setting files (.conda, etc) in my \user\ folder (which I think it uses as its default/root folder). But I use Google sync in a different folder and want all of those there (...\user\Document\Gsync\)
score: 0
comment on: http://stackoverflow.com/q/52525129
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52501886
has comment: http://stackoverflow.com/comment/91944514
has comment: http://stackoverflow.com/comment/91944691
answers question: http://stackoverflow.com/q/52501665
has body: You are using a tuple, which means it has index-bassed assignment of values. To refer to a length in a tuple(length,width) you simply access the index [0].
has comment: http://stackoverflow.com/comment/91944414
score: 0
has comment: http://stackoverflow.com/comment/91944339
type: Answer

http://stackoverflow.com/comment/92065585
type: QuestionComment
has text: Please properly indent your code to make it more readable
comment on: http://stackoverflow.com/q/52563593
score: 0
type: Comment

http://stackoverflow.com/q/52564146
has answer: http://stackoverflow.com/a/52564215
type: UnansweredQuestion
has body: I am trying to display a bar graph for a file of student scores from chapter 5 EX15 python book by Zelle. I am not able to get the bar graph to display however. Program to plot a bar chart of student exam scores. Author: Matthew Jenkins from graphics import* def main(): print("This program reads the student scores from a file that you can insert!") fName = input("Enter the file name: ") inFile = open(fName, 'r') numStudents = int(inFile.readline()) scores = inFile.readlines() inFile.close() winH = 50 + numStudents * 30 win = GraphWin('Student Exam Scores', 500, winH) win.setCoords(0, 0, 100, winH) win.setBackground("gray") scoreHeader = Text(Point(50, winH * .9), 'Exam Scores') scoreHeader.setFill("Blue") scoreHeader.draw(win) x = 10 i = 1 for i in range(10): numtxt = Text(Point(x, 1),'%d'%x ) numtxt.setFill('blue') numtxt.draw(win) x = x + 10 y = 1 for line in scores: name, num = line.split() y+=1 bar = Rectangle(Point(40, (y*10)), Point(num, (y*10) + 10)).draw(win) print(name, num) main()
tagged with: python
has title: unsupported operand type(s) for -: 'str' and 'int' error for chapter 5 EX15
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92066644
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52465449
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have that weird string (single line) where first field is a key, second is a value. It looks like this: key1\val1\key2\val2\key3\val3\...\keyn\valn What would be the best way to convert such notation to python dictionary?
downvote count: 0
has answer: http://stackoverflow.com/a/52465489
type: Question
has comment: http://stackoverflow.com/comment/91872666
has title: Convert string with alternating key value pairs to a dictionary
possible better answer: http://stackoverflow.com/a/52465514
has answer: http://stackoverflow.com/a/52465674
answer count: 6
has answer: http://stackoverflow.com/a/52465514
upvote count: 2
has comment: http://stackoverflow.com/comment/91872615
favorite count: 0
has answer: http://stackoverflow.com/a/52465572
accepted answer: http://stackoverflow.com/a/52465572
has answer: http://stackoverflow.com/a/52465671
has answer: http://stackoverflow.com/a/52465503

http://stackoverflow.com/comment/91929198
score: 0
comment on: http://stackoverflow.com/q/52493921
type: Comment
type: QuestionComment
has text: These are litteraly shots in the dark to me since I can't reproduce. Try doing `df.index.values.astype('int32')` ?

http://stackoverflow.com/a/52570858
downvote count: 1
answers question: http://stackoverflow.com/q/52569427
score: -1
has comment: http://stackoverflow.com/comment/92079809
upvote count: 0
type: Answer
has body: This can be simply implemented with python set() as folows.. &gt;&gt;&gt; string1 = "abcde" &gt;&gt;&gt; string2 = "cdefg" &gt;&gt;&gt; string3 = string1 + string2 &gt;&gt;&gt; print (''.join(sorted(set(string3)))) abcdefg Explanation: set() removes the duplicate elements, sorted() sorts, and the join() combines it all back.

http://stackoverflow.com/comment/91962475
score: 0
comment on: http://stackoverflow.com/q/52511042
type: Comment
has text: the installation that indicates is only an unpacked, it is not an installation properly compiled for ARM.
type: QuestionComment

pyqt
type: Tag
tags question: http://stackoverflow.com/q/52546461
tags question: http://stackoverflow.com/q/52457559
tags question: http://stackoverflow.com/q/52463896
tags question: http://stackoverflow.com/q/52552680
tags question: http://stackoverflow.com/q/52522218
tags question: http://stackoverflow.com/q/52471705
tags question: http://stackoverflow.com/q/52483704
tags question: http://stackoverflow.com/q/52526040
tags question: http://stackoverflow.com/q/52470040
tags question: http://stackoverflow.com/q/52473040
tags question: http://stackoverflow.com/q/52545316
tags question: http://stackoverflow.com/q/52527995
tags question: http://stackoverflow.com/q/52480526
tags question: http://stackoverflow.com/q/52461309
tags question: http://stackoverflow.com/q/52451700
tags question: http://stackoverflow.com/q/52584644
tags question: http://stackoverflow.com/q/52560496
tags question: http://stackoverflow.com/q/52559854
tags question: http://stackoverflow.com/q/52507438
tags question: http://stackoverflow.com/q/52511042
tags question: http://stackoverflow.com/q/52514618
tags question: http://stackoverflow.com/q/52517773
tags question: http://stackoverflow.com/q/52530402
tags question: http://stackoverflow.com/q/52486823
tags question: http://stackoverflow.com/q/52472975
tags question: http://stackoverflow.com/q/52528627
tags question: http://stackoverflow.com/q/52581727
tags question: http://stackoverflow.com/q/52561983
tags question: http://stackoverflow.com/q/52447494
tags question: http://stackoverflow.com/q/52585297
tags question: http://stackoverflow.com/q/52536505
tags question: http://stackoverflow.com/q/52550903
tags question: http://stackoverflow.com/q/52464699
tags question: http://stackoverflow.com/q/52463969
tags question: http://stackoverflow.com/q/52450219
tag name: pyqt
tags question: http://stackoverflow.com/q/52517516
tags question: http://stackoverflow.com/q/52523007
tags question: http://stackoverflow.com/q/52493439
tags question: http://stackoverflow.com/q/52496532

http://stackoverflow.com/comment/92011275
score: 0
type: Comment
has text: If you make `_students` an implementation ("protected") attribute - which is what the single leading underscode means, and which is the right thing to do here (the client code has no business knowing how students are "stored" in the Course objects - this might as well use a database of any kind, or a dict, or a set, or whatever...), then you don't want to allow client code to overwrite `_students`.
comment on: http://stackoverflow.com/a/52533938
type: AnswerComment

http://stackoverflow.com/a/52545737
accepted answer of: http://stackoverflow.com/q/52543384
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52543384
upvote count: 1
has body: Your global variable path and your function argument path are entirely separate variables. There is no risk of Python confusing the two. There is only the risk of you or another programmer confusing them.
type: AcceptedAnswer
downvote count: 0

python
tags question: http://stackoverflow.com/q/52489949
tags question: http://stackoverflow.com/q/52553208
tags question: http://stackoverflow.com/q/52463972
tags question: http://stackoverflow.com/q/52507723
tags question: http://stackoverflow.com/q/52440485
tags question: http://stackoverflow.com/q/52556616
tags question: http://stackoverflow.com/q/52455161
tags question: http://stackoverflow.com/q/52554013
tags question: http://stackoverflow.com/q/52437481
tags question: http://stackoverflow.com/q/52490405
tags question: http://stackoverflow.com/q/52572613
tags question: http://stackoverflow.com/q/52487313
tags question: http://stackoverflow.com/q/52484154
tags question: http://stackoverflow.com/q/52500012
tags question: http://stackoverflow.com/q/52583321
tags question: http://stackoverflow.com/q/52449997
tags question: http://stackoverflow.com/q/52559614
tags question: http://stackoverflow.com/q/52468601
tags question: http://stackoverflow.com/q/52482926
tags question: http://stackoverflow.com/q/52442896
tags question: http://stackoverflow.com/q/52494242
tags question: http://stackoverflow.com/q/52554906
tags question: http://stackoverflow.com/q/52438941
tags question: http://stackoverflow.com/q/52468889
tags question: http://stackoverflow.com/q/52494395
tags question: http://stackoverflow.com/q/52556939
tags question: http://stackoverflow.com/q/52454955
tags question: http://stackoverflow.com/q/52526167
tags question: http://stackoverflow.com/q/52458370
tags question: http://stackoverflow.com/q/52481028
tags question: http://stackoverflow.com/q/52500506
tags question: http://stackoverflow.com/q/52481773
tags question: http://stackoverflow.com/q/52548433
tags question: http://stackoverflow.com/q/52484136
tags question: http://stackoverflow.com/q/52551247
tags question: http://stackoverflow.com/q/52584730
tags question: http://stackoverflow.com/q/52491589
tags question: http://stackoverflow.com/q/52542559
tags question: http://stackoverflow.com/q/52588453
tags question: http://stackoverflow.com/q/52552401
tags question: http://stackoverflow.com/q/52516918
tags question: http://stackoverflow.com/q/52518364
tags question: http://stackoverflow.com/q/52579378
tags question: http://stackoverflow.com/q/52554674
tags question: http://stackoverflow.com/q/52527458
tags question: http://stackoverflow.com/q/52521545
tags question: http://stackoverflow.com/q/52579792
tags question: http://stackoverflow.com/q/52523339
tags question: http://stackoverflow.com/q/52433517
tags question: http://stackoverflow.com/q/52550304
tags question: http://stackoverflow.com/q/52528493
tags question: http://stackoverflow.com/q/52578329
tags question: http://stackoverflow.com/q/52569047
tags question: http://stackoverflow.com/q/52462209
tags question: http://stackoverflow.com/q/52468477
tags question: http://stackoverflow.com/q/52521963
tags question: http://stackoverflow.com/q/52440622
tags question: http://stackoverflow.com/q/52517236
tags question: http://stackoverflow.com/q/52460163
tags question: http://stackoverflow.com/q/52535073
tags question: http://stackoverflow.com/q/52507778
tags question: http://stackoverflow.com/q/52525290
tags question: http://stackoverflow.com/q/52521488
tags question: http://stackoverflow.com/q/52454896
tags question: http://stackoverflow.com/q/52483948
tags question: http://stackoverflow.com/q/52532802
tags question: http://stackoverflow.com/q/52495211
tags question: http://stackoverflow.com/q/52502408
tags question: http://stackoverflow.com/q/52431170
tags question: http://stackoverflow.com/q/52469687
tags question: http://stackoverflow.com/q/52529903
tags question: http://stackoverflow.com/q/52443519
tags question: http://stackoverflow.com/q/52507154
tags question: http://stackoverflow.com/q/52450529
tags question: http://stackoverflow.com/q/52560700
tags question: http://stackoverflow.com/q/52468956
tags question: http://stackoverflow.com/q/52574366
tags question: http://stackoverflow.com/q/52458898
tags question: http://stackoverflow.com/q/52458265
tags question: http://stackoverflow.com/q/52533473

http://stackoverflow.com/a/52441208
answers question: http://stackoverflow.com/q/52439564
type: Answer
has comment: http://stackoverflow.com/comment/92007429
has body: Something like this works if n is a small number. import numpy as np from scipy.optimize import minimize K = 5 n = 10 X = np.random.random_sample((K, n, n)) Y = np.random.random_sample((K, n, n)) def opt(A): A = np.reshape(A, (n, n)) # maybe need to transpose X.dot(a) ? # if axis is a 2-tuple, it specifies the axes that hold 2-D matrices, # and the matrix norms of these matrices are computed. return np.sum(np.linalg.norm(Y - X.dot(A), ord='fro', axis=(1, 2)) ** 2.0) A_init = np.random.random_sample((n, n)) print(minimize(opt, A_init )) Careful: The optimization algorithms used by minimize as default are local.
score: 0

http://stackoverflow.com/a/52523487
answers question: http://stackoverflow.com/q/52523418
upvote count: 1
type: Answer
downvote count: 0
has body: Using comprehension with sorted x[0] and reverse print(*sorted([[k, v] for k, v in d.items()], key=lambda x: sum(x[1]), reverse = True)) ['jbgood', [4.0, 4.0, 1.5, 1.5]] ['clovato', [2.0, 1.0, 1.0, 1.5, 2.0]] ['fnegro', [1.0, 3.0, 0.5]]
score: 1

http://stackoverflow.com/q/52446171
accepted answer: http://stackoverflow.com/a/52446203
has body: I'm trying to grasp the syntax of converting for loops to list comprehensions. I understand the very basics, which would be: [expression **for** item **in** list **if** conditional] However, I have a for loop which stores a value in an intermediate variable. I'm newer to Python, so it may be sloppy coding on my part: for n in wf: if n == 'Table of Contents': continue name = wf[n].iloc[1,2] store_list.append(name) I'm not sure how I would store the name variable in a list comprehension. Do I need to store it? Is there a better way to code this? store_list1=[] store_list1 = [name = wf[n].iloc[1,2], store_list1.append(name) for n in wf if not == 'Table of Contents'] The code above returns a syntax error at the equal sign...Could someone explain to me if it is possible to code this particular for loop as a list comprehension? Thanks in advance,
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/52446313
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52446203
possible better answer: http://stackoverflow.com/a/52446313
tagged with: python
has comment: http://stackoverflow.com/comment/91835319
has title: Generally Converting For Loops to List Comprehensions
type: AnsweredQuestion
upvote count: 2
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91835217
has comment: http://stackoverflow.com/comment/91835279

http://stackoverflow.com/a/52575345
downvote count: 1
has body: I think you are using the wrong version of Python. The 'f-strings' syntax is a new feature of Python3.6. If your version is before 3.6, it will raise error. I try your code in Python3.6, and I got no errors. If you are using earlier version of python, don't use the 'f-strings' syntax: def subtract(a, b): print("SUBTRACTING {a} - {b}") return a - b
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52575199
upvote count: 1

http://stackoverflow.com/comment/92032853
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52544838
score: 0
has text: `collections.Counter((obj.Gender,obj.Diseases) for obj in MyModel.objects.all())` I think would work

http://stackoverflow.com/q/52542628
answer count: 1
favorite count: 0
has body: I am trying to order a user input, set of cards (Not deck) from lowest to highest A-K. I am not very experienced with python, and don't know much of the terminology and functions. I am trying to keep the code simple and basic. Here is what I have: A = 1 J= 11 Q = 12 K = 13 alist = sorted(input("Type your card set: ")) #it prints 1,11,12,and 13 instead of A,K,Q,J print(alist) How do I change 1,11,12,13 back to A,K,Q,J before printing?
accepted answer: http://stackoverflow.com/a/52542795
has comment: http://stackoverflow.com/comment/92025209
score: -3
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Card set sorting - Python
has answer: http://stackoverflow.com/a/52542795
has comment: http://stackoverflow.com/comment/92025372
has comment: http://stackoverflow.com/comment/92025325
type: Question
has comment: http://stackoverflow.com/comment/92025137
downvote count: 3

http://stackoverflow.com/a/52586128
answers question: http://stackoverflow.com/q/52585694
type: Answer
has comment: http://stackoverflow.com/comment/92285289
downvote count: 0
score: 1
has body: I guess we cant handle direct authentication using scrapy I guess.But with given credentials we can access it. Check here for more information on handling login staff.
upvote count: 1

http://stackoverflow.com/q/52558614
tagged with: series
score: 0
has title: Pandas map on series
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52558822
tagged with: python
has comment: http://stackoverflow.com/comment/92055870
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92056218
has body: I have a DataFrame with lots of categories, but I'm only trying to use two. I managed to get the result I wanted but it wasn't accepted in my project ('there's better ways of doing it'). Working with 2 columns - Gender (M/F) and Showed (1/0) I'm trying to get out 4 variables: male1, male0, female1, female0 to create bar chart with them. I was told to use pd.series.map function but I've looked everywhere and can't find a good example on it - also not really sure how to get 4 variables out of it. Thanks for any help.
has comment: http://stackoverflow.com/comment/92055830
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52558822
tagged with: dataframe
type: Question
possible better answer: http://stackoverflow.com/a/52559048
has answer: http://stackoverflow.com/a/52559048
has answer: http://stackoverflow.com/a/52558690

http://stackoverflow.com/q/52543817
tagged with: machine-learning
tagged with: python
score: 1
has body: I am trying create a Cudgru based model that predicts sequence of 7 features that are interrelated. Here's my keras model summary: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= cu_dnngru_1 (CuDNNGRU) (None, 49, 100) 32700 _________________________________________________________________ dropout_1 (Dropout) (None, 49, 100) 0 _________________________________________________________________ cu_dnngru_2 (CuDNNGRU) (None, 49, 100) 60600 _________________________________________________________________ dropout_2 (Dropout) (None, 49, 100) 0 _________________________________________________________________ cu_dnngru_3 (CuDNNGRU) (None, 49, 100) 60600 _________________________________________________________________ dropout_3 (Dropout) (None, 49, 100) 0 _________________________________________________________________ cu_dnngru_4 (CuDNNGRU) (None, 49, 100) 60600 _________________________________________________________________ dropout_4 (Dropout) (None, 49, 100) 0 _________________________________________________________________ cu_dnngru_5 (CuDNNGRU) (None, 49, 100) 60600 _________________________________________________________________ dropout_5 (Dropout) (None, 49, 100) 0 _________________________________________________________________ cu_dnngru_6 (CuDNNGRU) (None, 49, 100) 60600 _________________________________________________________________ dropout_6 (Dropout) (None, 49, 100) 0 _________________________________________________________________ cu_dnngru_7 (CuDNNGRU) (None, 49, 100) 60600 _________________________________________________________________ dropout_7 (Dropout) (None, 49, 100) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 4900) 0 _________________________________________________________________ dense_1 (Dense) (None, 7) 34307 =================================================================…
tagged with: tensorflow
type: Question
upvote count: 2
answer count: 1
tagged with: keras
has title: Keras training crashes mid epoch after multiple correct executions
has comment: http://stackoverflow.com/comment/92065707
has answer: http://stackoverflow.com/a/52571237
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92028852
type: UnansweredQuestion

http://stackoverflow.com/a/55631753
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/115612529
type: Answer
has comment: http://stackoverflow.com/comment/117487676
has comment: http://stackoverflow.com/comment/115612389
has comment: http://stackoverflow.com/comment/117487818
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52479046
has body: Some additional information on top of Felipe Mello's informative answer (disclaimer: author of DTAIDistance here). For the distance results: DTAIDistance only uses Euclidean distance (or L2 norm), this is hardcoded. This choice was made to speed up the execution of the C-code (no function calls). The 'fast' refers to using the C-based implementation instead of a pure Python version and both methods thus give the exact same results. FastDTW is a different algorithm than DTW. It is a linear approximation. The 'fast' refers to a lower complexity. cDTW. I'm not very familiar with this toolbox but it seems to implement L1 norm. For the speed results: In general, pure C-based algorithms are ~100 times faster than pure Python ones (in DTAIDistance this is the difference between distance() and distance_fast()). For the C-based methods the differences are mainly due to flexibility of the methods. Passing a custom norm, for example, will slow down the method (more function calls). Also, different methods have different options which cause more or less switch statements in the algorithm. For example, DTAIDistance, offers quite a number of options to tune the method because it prefers early stopping the computation over further optimizations (also observed by Felipe Mello). Furthermore, different methods store different amounts of data. The DTAIDistance distance method does not store the entire matrix to also offer linear space complexity (the full matrix is obtained using the warping_paths method that has quadratic space complexity). In general for DTW it is recommended to use a window to reduce also the time complexity a bit. For DTAIDistance, all the design choices were made with timeseries clustering applications in mind (the distance_matrix_fast method). This is another reason not to allow custom norms. The DTW code needs to be pure C to support parallelization on the level of C-code and have minimal overhead (it uses OpenMP) to compute all pairwise distances between serie…
answers question: http://stackoverflow.com/q/52479046

numpy
tags question: http://stackoverflow.com/q/52537021
tags question: http://stackoverflow.com/q/52581855
tags question: http://stackoverflow.com/q/52452026
tags question: http://stackoverflow.com/q/52443107
tags question: http://stackoverflow.com/q/52556903
tags question: http://stackoverflow.com/q/52576615
tags question: http://stackoverflow.com/q/52530444
tags question: http://stackoverflow.com/q/52533669
tags question: http://stackoverflow.com/q/52582899
tags question: http://stackoverflow.com/q/52481376
tags question: http://stackoverflow.com/q/52452515
tags question: http://stackoverflow.com/q/52463972
tags question: http://stackoverflow.com/q/52491501
tags question: http://stackoverflow.com/q/52478005
tags question: http://stackoverflow.com/q/52534892
tags question: http://stackoverflow.com/q/52471145
tags question: http://stackoverflow.com/q/52444921
tags question: http://stackoverflow.com/q/52478703
tags question: http://stackoverflow.com/q/52442499
tags question: http://stackoverflow.com/q/52554388
tags question: http://stackoverflow.com/q/52537888
tags question: http://stackoverflow.com/q/52446427
tags question: http://stackoverflow.com/q/52508642
tags question: http://stackoverflow.com/q/52505225
tags question: http://stackoverflow.com/q/52462435
tags question: http://stackoverflow.com/q/52516043
tags question: http://stackoverflow.com/q/52472531
tags question: http://stackoverflow.com/q/52499416
tags question: http://stackoverflow.com/q/52530651
tags question: http://stackoverflow.com/q/52460809
tags question: http://stackoverflow.com/q/52498172
tags question: http://stackoverflow.com/q/52491286
tags question: http://stackoverflow.com/q/52436394
tags question: http://stackoverflow.com/q/52489883
tags question: http://stackoverflow.com/q/52466532
tags question: http://stackoverflow.com/q/52486435
tags question: http://stackoverflow.com/q/52508359
tags question: http://stackoverflow.com/q/52539461
tags question: http://stackoverflow.com/q/52487891
tags question: http://stackoverflow.com/q/52565436
tags question: http://stackoverflow.com/q/52447815
tags question: http://stackoverflow.com/q/52544105
tags question: http://stackoverflow.com/q/52539134
tags question: http://stackoverflow.com/q/52486446
tags question: http://stackoverflow.com/q/52480804
tags question: http://stackoverflow.com/q/52464947
tags question: http://stackoverflow.com/q/52524211
tags question: http://stackoverflow.com/q/52570489
tags question: http://stackoverflow.com/q/52477839
tags question: http://stackoverflow.com/q/52511944
tags question: http://stackoverflow.com/q/52432124
tags question: http://stackoverflow.com/q/52487727
tags question: http://stackoverflow.com/q/52563621
tags question: http://stackoverflow.com/q/52572321
tags question: http://stackoverflow.com/q/52533083
tags question: http://stackoverflow.com/q/52470889
tags question: http://stackoverflow.com/q/52465718
tags question: http://stackoverflow.com/q/52443469
tags question: http://stackoverflow.com/q/52477962
tags question: http://stackoverflow.com/q/52434990
tags question: http://stackoverflow.com/q/52501817
tags question: http://stackoverflow.com/q/52430395
tags question: http://stackoverflow.com/q/52502338
tags question: http://stackoverflow.com/q/52552864
tags question: http://stackoverflow.com/q/52457661
tags question: http://stackoverflow.com/q/52491972
tags question: http://stackoverflow.com/q/52453436
tags question: http://stackoverflow.com/q/52461039
tags question: http://stackoverflow.com/q/52573085
tags question: http://stackoverflow.com/q/52570086
tags question: http://stackoverflow.com/q/52476601
tags question: http://stackoverflow.com/q/52467098
tags question: http://stackoverflow.com/q/52475717
tags question: http://stackoverflow.com/q/52566672
tags question: http://stackoverflow.com/q/52517466
tags question: http://stackoverflow.com/q/52571619
tags question: http://stackoverflow.com/q/52489181
tags question: http://stackoverflow.com/q/52578470
tags question: http://stackoverflow.com/q/52566835
tags question: http://stackoverflow.com/q/52441629

http://stackoverflow.com/q/52486591
tagged with: linux
type: UnansweredQuestion
has body: I have the error in the script output Notice: /Stage[main]/Python/Exec[set-python-global]/returns: pyenv: version `2.7.9' not installed Error: /usr/local/pyenv/bin/pyenv global 2.7.9 returned 1 instead of one of [0] However, the command pyenv versions returns correctly: pyenv versions • system (set by /usr/local/pyenv/version) 2.7.9 Some other commands: sudo /usr/local/pyenv/bin/pyenv global 2.7.9 pyenv: version `2.7.9' not installed In the directory /usr/local/pyenv/versions I see the directory 2.7.9 The command sudo /usr/local/pyenv/bin/pyenv local 2.7.9 Also returns pyenv: version `2.7.9' not installed I am on RHEL 7
tagged with: python
type: Question
has title: Why pyenv states that a version is not installed despite it does exist?
has answer: http://stackoverflow.com/a/57887637
score: 0
tagged with: pyenv
answer count: 1

http://stackoverflow.com/a/52567567
has body: I have downloaded your picture and edited it to remove the yellow squares and made my own template both done with paint (please don't judge me). Then I tried your code and it worked well. It is hard to tell why it is not working in your case but if I guess I would have to say that it has something to do with your template. When you say you have a transparent png picture does it mean it is completly transparent (even inside the black borders) or just the surroundings? If the first case is true try to make a template that has the middle filled with white pixels as in the original image. Your code: import cv2 import numpy as np img = cv2.imread('pawn.png') # Standard settings img_rgb = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) img_gray = cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY) # White Pawn Template pawn_white_template = cv2.imread("pawn_white2.png",0) w_pawn_white, h_pawn_white = pawn_white_template.shape[::-1] res_pawn_white = cv2.matchTemplate(img_gray,pawn_white_template,cv2.TM_CCOEFF_NORMED) threshhold = 0.6 loc = np.where(res_pawn_white &gt;= threshhold) for pt in zip(*loc[::-1]): cv2.rectangle(img_rgb,pt,(pt[0]+w_pawn_white, pt[1]+h_pawn_white),(0,255,255),1) cv2.imshow('detected',img_rgb) Result: My original img: My template:
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/92073873
answers question: http://stackoverflow.com/q/52560812
has comment: http://stackoverflow.com/comment/92074008
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92073974

http://stackoverflow.com/comment/91971796
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52516101
score: 0
has text: Does validity mean that it has the correct structure or that it produces the desired results?

http://stackoverflow.com/comment/92082031
comment on: http://stackoverflow.com/q/52572508
score: 0
type: Comment
has text: Perhaps you should setup CPU and Memory profiling for your application
type: QuestionComment

http://stackoverflow.com/comment/91907761
score: 0
type: Comment
type: QuestionComment
has text: You're sure you're not calling `sg.next()` anywhere else in your program? Or even `next(sg.iterator)`?
comment on: http://stackoverflow.com/q/52477809

http://stackoverflow.com/comment/92110633
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52587761
has text: Well there is no activity with the slug `myactivity` and in the year `2018`.

http://stackoverflow.com/q/52503222
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91947056
tagged with: python
tagged with: opencv
answer count: 0
upvote count: 1
type: Question
tagged with: python-multiprocessing
has body: The following is a simplified version of my program: import cv2 import multiprocessing import numpy import copy import time def f(d, img): t0 = d[1] print("before") print(type(t0)) Bg_sub_img = t0.apply(img,learningRate=0.1) print("after") t0 = cv2.bgsegm.createBackgroundSubtractorMOG(history=20) d = multiprocessing.Manager().dict() #d = {} #d[1] = copy.deepcopy(t0) d[1] = t0 img = cv2.imread('test.jpg', 0) print(type(t0)) p = multiprocessing.Process(target=f, args=(d,img)) p.start() time.sleep(10) p.join() which results in the following output: &lt;type 'cv2.bgsegm_BackgroundSubtractorMOG'&gt; before &lt;type 'cv2.bgsegm_BackgroundSubtractorMOG'&gt; Process Process-2: Traceback (most recent call last): File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run self._target(*self._args, **self._kwargs) File "amrutha.py", line 12, in f Bg_sub_img = t0.apply(img,learningRate=0.1) TypeError: Incorrect type of self (must be 'BackgroundSubtractor' or its derivative) If you try to run the program as just a regular funciton, without multiprocessing, it works ok. However, if instead of directly taking the variable t0, I perform a deepcopy of it (even when using it as a regular function and not running in a process), I get the same error. If I try to just pass the variable (not the dictionary) in multiprocessing, its works ok too. Not sure why thats the case. And when using it in a separate process, does it copy the object when passing it via a dicitonary? And which is perhaps the reason why it fails in a multiprocessing function? FYI: Ubuntu 16.04 Python 2.7 OpenCV: 3.4.0
has title: BackgroundSubtractor incorrect type when using via dictionary and multiprocessing
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91983849

http://stackoverflow.com/a/52592271
answers question: http://stackoverflow.com/q/52565964
score: 0
has body: That's probably happening because you initalize the variable on every epoch, so in other words the error means: Do you want to share this variable or you want to redeclare it? Since the desired behavior is unclear (create new variables or reuse the existing ones?) TensorFlow will fail. If you do want to share the variable you can just change the line: conv_w = tf.get_variable('conv/W', initializer=tf.constant_initializer(conv_W[0]),reuse=True) Otherwise set reuse=False, and that will solve your problem. For more information about how to share/unshare variables see the Tensorflow documentation:
type: Answer

http://stackoverflow.com/comment/92097610
has text: I'm not sure what your question is? You haven't called the function.
comment on: http://stackoverflow.com/q/52581163
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/52481658
has title: Python pandas data frame/dictionary to csv
type: Question
score: -2
answer count: 1
favorite count: 0
has body: I need some assistance formatting a python pandas data frame that is written to a csv. The data frame consists of multiple data dictionaries. The dictionary keys are printing fine, but I need the values to be written in separate rows down a column and without the square brackets and quotation marks. I have been scratching my head over this. I have tried pd.wide_to_long and getting creative with pandas melt. However, the outputs are not what I need. Currently dictionary values look like this in a single cell: Key ['a''b''c''d'] I would like a, b, c, d printed down a single column: Key a b c d
tagged with: pandas
has answer: http://stackoverflow.com/a/52481769
tagged with: python
upvote count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: dataframe

http://stackoverflow.com/a/52576360
accepted answer of: http://stackoverflow.com/q/52576338
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52576338
has body: You have a zero-length match there, and you have a capturing group. When the regular expression for re.findall has a capturing group, the resulting list will be what's been captured in those capturing groups (if anything). Four positions are matched by your regex: the start of the string, before the first b, before the second b, and before the third b. Here's a diagram, where | represents the position matched (spaces added for illustration): b b b b | captures the next b, passes b b b b | captures the next b, passes b b b b | captures the next b, passes b b b b | captures the next b, passes b b b b | lookahead fails, match fails If you didn't want a capturing group and only want to match the zero-length positions instead, use (?: instead of ( for a non-capturing group: (?=(?:b)) (though the resulting list will be composed of empty strings and won't be very useful)
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/92088097

http://stackoverflow.com/q/52484604
score: 1
type: Question
tagged with: mypy
has title: How to reduce verobsity when dealing with lists and using mypy?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52489307
accepted answer: http://stackoverflow.com/a/52489307
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I was just writing this sort of thing at work and was wondering if there was any pythonic way to reduce the extraneous stuff related to list, iterator and set handling in Item.display(). Is there some more pythonic way to deal with the filtering and transformation in Item.display()? Is there some way I could use different type to make typing easier? import unittest from dataclasses import dataclass, field from typing import Union, Tuple, List, Iterator @dataclass class Category: id: str name: str = field(compare=False) canonical: Union['Category', None] = field(compare=False) def __hash__(self)-&gt;int: return self.id.__hash__() def unalias(self)-&gt;'Category': #There could be more tests here if self.canonical: return self.canonical else: return self def display_str(self)-&gt;str: if self.id and self.name: return f'{self.id} [{self.name}]' else: return self.id @dataclass class Item: id: str categories: List[Category] def display(self,primary:Category)-&gt; List[str]: """Unalias, dedup and sort for display.""" if not self.categories: return [] def unalias(secs:Iterator[Category])-&gt;Iterator[Category]: return map(lambda c: c.unalias(), secs) def de_prim(secs:Iterator[Category])-&gt;Iterator[Category]: return filter(lambda c: c.id != primary.id, secs) def to_display(secs:List[Category])-&gt;List[str] : return list(map(lambda c: c.display_str(), secs) ) de_primaried = set(de_prim(unalias(iter(self.categories)))) if not de_primaried: return [] return sorted(to_display(de_primaried)) class DoiTest(unittest.TestCase): def test(self): primary = Category('shirt', 'Shirts', None) cats = [Category('snow','Snowflakes', Category('frozen_water','Frozen Water',None) ), Category('t-shirt','Tee Shirts', primary), Category('cheese','Yummy Cheese',None)] item = Item( 'ItemX', cats) self.assertEqual( item.display(primary) , ['cheese [Yummy Cheese]', 'frozen_water [Frozen Water]'])

http://stackoverflow.com/q/52468137
has answer: http://stackoverflow.com/a/55788176
score: 0
answer count: 1
tagged with: unit-testing
has title: Python3.6 and singletons - use case and parallel execution
type: UnansweredQuestion
tagged with: singleton
tagged with: python-3.x
type: Question
tagged with: python
has body: I have several unit-tests (only python3.6 and higher) which are importing a helper class to setup some things (eg. pulling some Docker images) on the system before starting the tests. The class is doing everything while it get instantiate. It needs to stay alive because it holds some information which are evaluated during the runtime and needed for the different tests. The call of the helper class is very expensive and I wanna speedup my tests the helper class only once. My approach here would be to use a singleton but I was told that in most cases a singleton is not needed. Are there other options for me or is a singleton here actually a good solution? The option should allow executing all tests at all and every test on his own. Also I would have some theoretical questions. If I use a singleton here how is python executing this in parallel? Is python waiting for the first instance to be finish or can there be a race condition? And if yes how do I avoid them?

http://stackoverflow.com/comment/92100977
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52582905
type: Comment
has text: This is great! Thank you

http://stackoverflow.com/q/52486076
tagged with: python
has comment: http://stackoverflow.com/comment/91918215
type: UnansweredQuestion
score: -4
type: Question
has body: n = int(input("Enter the number of rows in a matrix: ")) #key matrix for Hill Cipher key = [[0] * n for i in range(n)] #print(key) def key_mat(key): # To fill the elements in the matrix "key" for i in range(n): for j in range(n): key[i][j] = int(input()) #print(np.array(key)) key = np.array(key) print("Key = ",key) return key key_mat(n,key) # "adjoint of a matrix" in numpy is obtained by np.matrix.getH() #getH means get Hermitian transpose. adj_Key = key.getH() print(adj_Key) And I got error at this line adj_Key = key.getH() AttributeError: 'list' object has no attribute 'getH' I want to find adjoint of the matrix "key", and doing so I am getting this error..How to resolve it. Thanks
has title: AttributeError: 'list' object has no attribute 'getH' ...Then how to find adjoint of a matrix in my given code?
has comment: http://stackoverflow.com/comment/91913696
tagged with: numpy
tagged with: geth
downvote count: 4
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52487092
has comment: http://stackoverflow.com/comment/91913567

http://stackoverflow.com/comment/91881012
type: Comment
has text: I want to post my config Edward. but when i answer in comments i do not know how to leave an empty line between lines. ` ' wont do. How do i i insert an empty line between comments so my post would not seen as a long string ?
comment on: http://stackoverflow.com/a/52468934
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92102495
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52583740
type: Comment
has text: I'm checking out "lookup" because i was told "apply" is not vectorized (i.e. slower): https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6

http://stackoverflow.com/a/52525497
type: Answer
answers question: http://stackoverflow.com/q/52520711
score: 2
accepted answer of: http://stackoverflow.com/q/52520711
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has body: Try prettytable. from prettytable import PrettyTable x = PrettyTable() x.field_names = ["Sl.n0", "date1", "date2", "comments","Boolean"] with open('file.csv') as f: line = f.readline() while line: x.add_row(line.rstrip().split(',')) line = f.readline() print x Install with pip : pip install PrettyTable Find examples here
has comment: http://stackoverflow.com/comment/118738120

http://stackoverflow.com/comment/91917498
type: Comment
has text: It would be really great if I was able to learn how to receive unique samples without having the performance issue. Otherwise, even one epoch is completed in unreasonable long time :(
comment on: http://stackoverflow.com/a/52470287
type: AnswerComment
score: 0

http://stackoverflow.com/q/52459511
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Python, how do i get the entry to be attached to the label
has comment: http://stackoverflow.com/comment/91863361
has comment: http://stackoverflow.com/comment/91861992
type: Question
downvote count: 4
has answer: http://stackoverflow.com/a/52460097
has body: from tkinter import* class contactMain: def __init__(self, master): #First Label Heading self.heading = Label(master, text='CONTACT REGISTRY', bg='blue', fg='white', width=30) self.heading.grid(row=0,column=0) #Space between the heading and the first self.spaceHF = Label(master,bg='blue',fg='white', width=30) self.spaceHF.grid(row=1, column=0) #firstName label and entry self.fNameLabel = Label(master,text='First Name' ,bg='white', fg='blue',width=15) self.fNameLabel.grid(row=2,column=0,sticky=W) self.fNameEntry = Entry(master) self.fNameEntry.grid(row=2,column=1) root = Tk() app = contactMain(root) root.mainloop()
answer count: 1
has comment: http://stackoverflow.com/comment/92008210
score: -3
favorite count: 0
tagged with: python-3.x
tagged with: tkinter

http://stackoverflow.com/a/52555352
has body: solved by uninstalling and reinstalling gdal conda uninstall gdal conda install gdal
answers question: http://stackoverflow.com/q/52550415
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/91875645
score: 0
type: AnswerComment
type: Comment
has text: You are recreating the obj_list to its previous form. Please take a look. And this doesn't work as the order of validation is done as `nested_serializer` then `parent_serializer`. So the data mixed with ids and no ids of pages is first passed to `PageSerializer`, which identifies missing ids or any other validation and throws error before reaching your `validate_pages`.
comment on: http://stackoverflow.com/a/52466524

http://stackoverflow.com/a/52441053
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52440939
downvote count: 1
answers question: http://stackoverflow.com/q/52440939
has comment: http://stackoverflow.com/comment/91825857
has body: This is because lists in python are mutable Essentially when you do: lista[0]=lista[1] You are saying let the index 0 point to the same location in memory that the index 1 is pointing to. So, we essentially have the same pointer at index 0 and 1 pointing to the same object. A visual explanation: Picture the list: list_a = [1, 2, 3] If we set list_b equal to list_a (by doing list_b = list_a) then we get can picture the lists as: As you can see from above, the objects (the integers in list_a) are shared with list_b. Thus, if we change a value in list_b like so: list_b[0] = 100 then list_a and list_b will look like [100, 2, 3] Thus, if you apply this concept to your 2D list (table) you can picture we can observe that you are editing the same object in memory. In order to get your expected output you need to copy the list so that it points to its own unique object in memory.
type: AcceptedAnswer
score: 1

http://stackoverflow.com/comment/92087359
type: QuestionComment
score: 0
has text: So you mean can be 1 or 2 or 3, or only can have 1?
comment on: http://stackoverflow.com/q/52576000
type: Comment

http://stackoverflow.com/comment/91839643
type: Comment
has text: Looks like the copied_str is Cyrillic [1058, 1054, 1043]. Is it possible to convert the original document to normal characters? Is that the issue?
comment on: http://stackoverflow.com/q/52447536
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91862583
type: Comment
type: QuestionComment
has text: @hiroprotagonist That takes me further, but in my w20 h15 list, when I get to `l[14][0]`, I get `list index out of range`. If you don't mind helping me some more, could this be moved to chat to discuss further?
comment on: http://stackoverflow.com/q/52460068
score: 0

http://stackoverflow.com/comment/91878465
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52468312
has text: 1. `set_index` id, 2. `pd.concat` 3. `reset_index` 4. drop duplicates `subset = 'id', keep= last`. Thats it. I can give you the code but try for yourself once. :)

http://stackoverflow.com/q/52462148
favorite count: 0
accepted answer: http://stackoverflow.com/a/52462216
tagged with: python
has comment: http://stackoverflow.com/comment/91867516
type: AnsweredQuestion
score: 1
has body: I have the following table (tab delimited) for students. The name, class, grade in August, then grade in September provided. 1 Tom Bever 101 20,6 21,3 2 John Hein 102 23,7 22,4 3 Melissa Andrew 401 24,1 25,3 I converted it into python dictionary using this code: myfile = open ("students.txt", "r") d = { } for line in myfile: x = line.strip().split("\t") key, values = x[1], x[2:] d.setdefault(key, []).extend(values) print(d) Now, I need to use regular expressions to compute The name of the student with the lowest grade The name of the student(s) with an increase order them according to the highest grades they got in September So, how can I iterate through the dictionary using RE to answer these questions?
has comment: http://stackoverflow.com/comment/91867461
has comment: http://stackoverflow.com/comment/91866665
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52462216
has comment: http://stackoverflow.com/comment/91866625
has title: Using Regular Expressions to iterate through a python dictionary created from a tab delimited table
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52563893
score: 0
type: Answer
has body: Hope this helps, tried to comment everything clearly! Like mentioned in the comments, you'll need to use a while loop, the "input" function to get the user input, and lists. import csv with open ('groceries.csv') as csv_file: reader = csv.reader(csv_file) mydict = {rows[0]:rows[1]for rows in reader} print(mydict) enumeratemydict = enumerate(mydict) for item in enumerate(mydict): print(item) # Create an empty list of everything that the user wants that we will add to later purchased_items = [] # Ask user to select an item user_answer = "" while True: user_answer = input("Enter the number corresponding to your item: ") # Get user input if user_answer != '0': # If user entered 0 break # Leave the while loop, thus ending the program item_num = int(user_answer) # Convert to integer selected_item = mydict[item_num] # Figure out what item that integer corresponds to in your dict quantity = input("Enter the quantity: ") # Get user input quantity = int(quantity) # Convert to integer purchased_items.append([selected_item, quantity]) # add a list containing the item and quantity to your list of purchased items. print(purchased_items) # See what the user has bought up to this point
answers question: http://stackoverflow.com/q/52562363

http://stackoverflow.com/comment/91939680
comment on: http://stackoverflow.com/a/52498288
has text: Python v3.6.1 Can you show me how to write it in code?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91995027
score: 1
comment on: http://stackoverflow.com/q/52525876
type: Comment
type: QuestionComment
has text: When you use `minimize`, *always* check the `success` attribute of the object that is returned. In your code, after `minimum = minimize(...)`, add `if not minimum.success: print(minimum.status, minimum.message)`. Then include the output in the question here.

http://stackoverflow.com/a/52455696
has comment: http://stackoverflow.com/comment/91856087
answers question: http://stackoverflow.com/q/52455336
downvote count: 0
has body: After the line input("press Enter to continue ") You can simply enter: (y, x) = s.pop() Which flips the coordinates for the whole code I recently worked on a Maze Solver too... Here's a sample maze and printing function from my code: maze=[[ 0 ,0,1,1,0,'S'], [ 0 ,0,0,0,1, 0 ], ['F',1,0,0,0, 0 ], [ 0 ,0,0,0,1, 0 ], [ 0 ,1,0,0,0, 0 ]] ## 0 represents empty space, 1 represents a wall def printmaze(maze): for i in maze: for j in i: print('X' if j==1 else (' ' if j==0 else j),end='') print() Also in your code: def PrintMaze(maze): # an auxilliary function that prints a maze for row in range(MAZE_SIZE): print(maze[row], end='') print() is the same as: def PrintMaze(maze): for row in maze: print(row) In order to invert the printing you should do: for col in range(MAZE_SIZE): for row in maze: print(row[col],end='') print()
upvote count: 2
has comment: http://stackoverflow.com/comment/91855531
type: Answer
score: 2

http://stackoverflow.com/q/52453908
type: AnsweredQuestion
tagged with: docker-compose
downvote count: 0
score: 1
tagged with: uwsgi
has body: For some reason when I update the "app.py" file on the host computer it will not update in the browser (localhost). The only way it will update is if I shutdown the container, rebuild, and restart. Cant figure out what I am missing here? Here are a few of the relevant parts. You can see the whole code on my github https://github.com/longfellowone/Docker-Flask-NGINX-uWSGI . ├── app │ ├── app.py │ ├── Dockerfile │ ├── requirements.txt │ ├── sock.sock │ └── uwsgi.ini ├── docker-compose.yml ├── nginx │ ├── Dockerfile │ ├── nginx.conf │ └── uwsgi_params └── README.md docker-compose.yml web: build: ./app volumes: - type: bind source: ./app target: /src command: uwsgi --ini ./uwsgi.ini nginx: container_name: nginx image: nginx:latest volumes: - ./nginx/:/etc/nginx/ - type: bind source: ./app/ target: /tmp nginx.conf sendfile off; upstream app { server unix:/tmp/sock.sock; } server { location / { try_files $uri @web; } location @web { include uwsgi_params; uwsgi_pass app; } /app/Dockerfile FROM python:latest COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt WORKDIR /src/ app.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' uwsgi.ini [uwsgi] module = app:app socket = sock.sock chmod-socket = 666
type: Question
tagged with: nginx
has title: Docker-Compose NGINX/uWSGI/Flask bind mount issue
answer count: 1
tagged with: flask
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52462756
accepted answer: http://stackoverflow.com/a/52462756
tagged with: python

http://stackoverflow.com/comment/117702533
comment on: http://stackoverflow.com/a/52466625
score: 1
type: AnswerComment
type: Comment
has text: I get mypy error (Return type "Coroutine[Any, Any, ...]" of "..." incompatible with return type "..." in supertype "..." mypy(error)) when overriding sync methods with their async versions.

http://stackoverflow.com/comment/91843536
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52450183
score: 0
has text: @juanpa.arrivillaga how would i go about returning it and then referencing it in the next block?

http://stackoverflow.com/q/52511065
tagged with: python
has answer: http://stackoverflow.com/a/52511129
has title: Pandas error when filtering rows based on multiple column conditionals, "ValueError: invalid literal for int() with base 10: "
type: AnsweredQuestion
score: 0
type: Question
accepted answer: http://stackoverflow.com/a/52511129
possible better answer: http://stackoverflow.com/a/52511119
answer count: 2
has answer: http://stackoverflow.com/a/52511119
has body: I am getting a 'ValueError: invalid literal for int() with base 10: ' when I try to filter the dataframe using multiple column conditions Here is the code to set up the pandas dataframe. Warning: it'll download 6 mb of data. Can run in Google Colab if too concerned. Code to import stuff and download the data #Import stuff import re import os import zipfile from urllib.request import urlretrieve from os.path import isfile, isdir import requests #Define Download Function def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params = { 'id' : id }, stream = True) token = get_confirm_token(response) if token: params = { 'id' : id, 'confirm' : token } response = session.get(URL, params = params, stream = True) save_response_content(response, destination) def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, "wb") as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: # filter out keep-alive new chunks f.write(chunk) #Download data download_file_from_google_drive('1sZk3WWgdyHLru7q1KSWQwCT4nwwzHlpY', 'TheAnimeList.csv') Code to set up the pandas dataframe download_file_from_google_drive('1sZk3WWgdyHLru7q1KSWQwCT4nwwzHlpY', 'TheAnimeList.csv') animeuser = pd.read_csv('TheAnimeList.csv' ) animeuser = animeuser'anime_id','title_english', 'popularity', 'rank' animeuser.head() anime_id title_english popularity rank 0 11013 Inu X Boku Secret Service 231 1274.0 1 2104 My Bride is a Mermaid 366 727.0 2 5262 Shugo Chara!! Doki 1173 1508.0 3 721 Princess Tutu 916 307.0 4 12365 Bakuman. 426 50.0 I am trying to filter rows based on column conditionals. First I tried animeuser = animeuser[ (animeuser.popularity &gt;= 3000) | (animeuser.rank &gt;= 3000) ] But that gave me this error TypeError…
tagged with: pandas

http://stackoverflow.com/q/52575710
type: Question
has body: I go stuck on a problem and I cannot think of any efficient way to do this. The problem is the following: I got 2 lists, each with n up to 10^3. v = [v_1, v_2, ..., v_n] w = [w_1, w_2, ..., w_n] In the following example n = 3. v = [60, 100 , 120] w = [20, 50, 30] I need to sort both lists based on the decreasing order of the following equation: v_i/w_i So in this case I would get: v_1/w_1 = 3 v_2/w_2 = 2 v_3/w_3 = 4 After that I need to sort both lists (depended to each other) by the decreasing order and I would get the following result. v_new = [120, 60, 100] w_new = [30, 20, 50] I know there is a way with sorted(zip(X,Y), but doing so it would change my list in a tuple and I need it as a list. Any suggestions?
has answer: http://stackoverflow.com/a/52575885
score: 5
upvote count: 5
tagged with: sorting
possible better answer: http://stackoverflow.com/a/52575792
has answer: http://stackoverflow.com/a/52575796
accepted answer: http://stackoverflow.com/a/52575796
has answer: http://stackoverflow.com/a/52575821
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52575792
has comment: http://stackoverflow.com/comment/92087020
has title: Sort 2 list linked to each other

http://stackoverflow.com/a/56645232
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52444016
has body: Here's an answer to your question: import re poem=''' If I can stop one heart from breaking, I shall not live in vain; If I can ease one life the aching, Or cool one pain, Or help one fainting robin Unto his nest again, I shall not live in vain. '''` p1=poem print(re.sub(r"\n","",poem)) poem=re.sub(r"co","Co",poem) poem=re.sub(r"ch","Ch",poem) print(poem) print(re.sub(r"ai|hi{3}","*/*",p1))`

http://stackoverflow.com/q/52470567
has comment: http://stackoverflow.com/comment/91883253
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91883755
has comment: http://stackoverflow.com/comment/91883607
has comment: http://stackoverflow.com/comment/91883662
answer count: 1
has title: Bizarre hang in python when subprocess returns an error
favorite count: 0
has comment: http://stackoverflow.com/comment/91883456
tagged with: subprocess
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91883581
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52471173
has body: I have a python program designed to evolve a 3d model which is CFD analyzed in OpenFOAM. The analysis is conducted in parallel with a program called "mpirun"; my python script runs mpirun via subprocess.Popen. Nothing unusual so far. What is unusual is that when mpirun encounters an error with one of its children and kills its children, then prints an error... then the python parent process freezes. And doesn't freeze at some obvious place, like reading from the pipe... at random locations, it just stops... doing anything. I tried running my program with "python3 -m trace --trace" to see what line things are stopping on, here's the final output: foam.py(1765): print("-B") -B foam.py(1766): if match: foam.py(1776): print("-A") -A foam.py(1777): if re.match(" *Sum of moments *", line_text): --- modulename: re, funcname: match re.py(163): return _compile(pattern, flags).match(string) --- modulename: re, funcname: _compile re.py(280): try: re.py(281): p, loc = _cache[type(pattern), pattern, flags] re.py(282): if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE): re.py(283): return p foam.py(1780): print("A") A foam.py(1781): if force_mode: As you can see, it gets up to "if force_mode:".... and then just stops. Obviously "if bool" should never hang. I've been working on trying to figure this out for several days and I'm no closer to an answer. It doesn't seem to make a difference how I start the process via subprocess.Popen - shell=True, shell=False, running "mpirun" directly, running it through a bash wrapper script... nothing matters (the only thing I've kept consistent is stdout=subprocess.PIPE, since I have to be able to read the output). As soon as one of mpirun's children dies and it reports its error, foam.py just hangs. Any clue what might be going on here? I'm stumped. :(
tagged with: openfoam
has comment: http://stackoverflow.com/comment/91883412
has comment: http://stackoverflow.com/comment/91883367
score: 1
tagged with: openmpi

http://stackoverflow.com/a/52513416
type: AcceptedAnswer
upvote count: 2
has body: This question is related to this one As the answer provided by MattH, you can use functools.partial from functools import partial funccall = partial(func, 1, 2, 3, 4, 5) funccall()
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52512725
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52512725

http://stackoverflow.com/comment/92083408
type: Comment
has text: Oh hey, that looks pretty cool! Copying and pasting in Python is a real gotcha, since you can end up copying tabs instead of spaces, and the language won't run the code if they're combined. I'm not sure what editor you are using, but many have a feature to convert tabs to spaces and spaces to tabs. Only semi-relevant but thought it would be helpful if you didn't already know.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52573451

http://stackoverflow.com/comment/91933401
has text: I have solved it recreating virtual environment.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52495550
score: 0

http://stackoverflow.com/q/52497534
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91935349
tagged with: python
has answer: http://stackoverflow.com/a/52497701
has comment: http://stackoverflow.com/comment/91935322
has title: Find words in strings which contain specific characters only
type: Question
has answer: http://stackoverflow.com/a/52499452
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52497744
tagged with: regex
has body: I am trying to write regex to find words which contain specific characters only. For ex : text= "I want to mes a message saying mess" I want regex to find words which contain characters only "m" "e" "s" i.e mes and mess. I don't want regex to find message as it contains other characters than "m" "e" "s". reg= r"(?:[mes"]){1,} is what am trying.... Also can you please help me in writing a regex which contains words starting with me but does not contain words like men meal text=" Regex should find mess mean and all words starting with me except men and meal" Output should be only : mess mean me Thanks...

http://stackoverflow.com/comment/92073868
has text: @Newcontributor Sorry, but I don't quite understand. The code can run without issues if I just run one programme.
score: 0
comment on: http://stackoverflow.com/q/52509107
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52457648
has body: Is there a way in Python to use assignment operators for multiple targets (operands) like this: a, b, c += d with d being something expensive in terms of memory and computation time? If not, what is the Pythonic way to do it and calculate d only once without saving it in a new variable?
has answer: http://stackoverflow.com/a/52457741
score: 1
has comment: http://stackoverflow.com/comment/91858033
type: Question
has answer: http://stackoverflow.com/a/52457748
downvote count: 0
tagged with: operator-keyword
tagged with: variable-assignment
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/91857583
favorite count: 0
has comment: http://stackoverflow.com/comment/91857952
has answer: http://stackoverflow.com/a/52457667
has comment: http://stackoverflow.com/comment/91858276
type: UnansweredQuestion
upvote count: 1
has title: multiple targets for assignment operators in Python?
has answer: http://stackoverflow.com/a/52457759

http://stackoverflow.com/a/52436732
has comment: http://stackoverflow.com/comment/91816592
score: -1
has body: for images you need to find the &lt;img&gt; tag, &lt;a&gt; is markup for links. &lt;a aria-label="SomeImageName" data-asset-id="10101010101" href="SomeWebsite"&gt; &lt;img alt="SomeImageName" src="https://SomeImageUrl"/&gt; &lt;/a&gt; you found that image because as you can see, the link tag wraps the image tag. and that's not how dictionary syntax works, use : in attrs={} (see https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments) so it's soup.find_all('a', attrs={'css': 'value'}) instead of soup.find_all('a', attrs{"aria-label" "SomeImageName"})
type: Answer
answers question: http://stackoverflow.com/q/52436604
has comment: http://stackoverflow.com/comment/91817531
downvote count: 1
upvote count: 0

http://stackoverflow.com/q/52584158
has body: Here is my code [Link] (https://www.kaggle.com/fabiendaniel/customer-segmentation) Part 3.1 Product Descriptions Doing NLP , came across this code, precisly looking for 'pos' part, what does it do? is_noun = lambda pos: pos[:2] == 'NN'
tagged with: python
upvote count: 0
has title: Meaning of this code : is_noun = lambda pos: pos[:2] == 'NN'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92103236
has comment: http://stackoverflow.com/comment/92103354
score: -2
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92103576
type: Question
downvote count: 2
answer count: 1
tagged with: neural-network
has answer: http://stackoverflow.com/a/52584223
favorite count: 0

http://stackoverflow.com/comment/92007683
comment on: http://stackoverflow.com/a/52467987
score: 0
type: AnswerComment
has text: @Mauritius, Why are you grouping by `'col3'`? This column is *calculated* for the result, not an input. I honestly have no idea where you derive `list1` from. Your question has it as a given input.
type: Comment

http://stackoverflow.com/q/52539828
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/92019444
has comment: http://stackoverflow.com/comment/92019439
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74066104
accepted answer: http://stackoverflow.com/a/52539962
upvote count: 4
has comment: http://stackoverflow.com/comment/92019395
has comment: http://stackoverflow.com/comment/92022487
type: Question
has title: Regex search multiple suffixes
has body: I have a big list of target words I am searching words = ['Word1', 'Word2', 'Word3'] I've been told that a regular expression of this sort: suffix = re.compile('(?:{words}) (\\w+)'.format(words='|'.join(words))) Is pretty efficient, since it fails the regex evaluation immediately when a character that doesn't match the expression is met. However, the other way around is not efficient: prefix = re.compile('(\\w+) (?:{words})'.format(words='|'.join(words))) Is there an elegant way to instruct python's regex to do the search in reverse ? Edit I've been asked to add example usages: # prefix search title = re.compile('(?:Mr.|Mrs.|Ms.|Dr. |Lt.) (\\w+)') # suffix search company = re.compile('(\\w+) (?:Inc.| LLP.|ltd.|GMBH)') # invoking the regex all_people_names = title.findall(document) all_company_names = company.findall(document) Edit 2 A lot of people had been skeptical regarding the significance of the timing differences. I've implemented the 2 methods: endswith() and endswith_rev() that reverses the string and the results as kabanus suggested. These are the results: As you can see, it makes a huge difference, even with a small amount of suffixes.
score: 4
has comment: http://stackoverflow.com/comment/92019478
has answer: http://stackoverflow.com/a/52547618
has comment: http://stackoverflow.com/comment/92019464
answer count: 3
has answer: http://stackoverflow.com/a/52539962
downvote count: 0
possible better answer: http://stackoverflow.com/a/52547618
favorite count: 0
has comment: http://stackoverflow.com/comment/92028336

http://stackoverflow.com/a/57701680
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52582830
accepted answer of: http://stackoverflow.com/q/52582830
has body: You made two mistakes with your code. The first one is the url. You need to use the correct url to request data to investing.com. Your current url is 'https://br.investing.com/commodities/aluminum-historical-data' However, when you see inspection and click 'Network' the Request URLis https://br.investing.com/instruments/HistoricalDataAjax. Your second mistake exists in s.post(blah). As Federico Rubbi referred above, what you coded assigned to headers must be assigned to data instead. Now, your mistakes are all resolved. You need to do only one step more. You have to add a dictionary {'X-Requested-With': 'XMLHttpRequest'} to your_headers. Seeing from your code, I can see that you have already checked Network tab in HTML inspection. So, you are probably able to see why you need {'X-Requested-With': 'XMLHttpRequest'}. So the entire code should be as follows. import requests import bs4 as bs with requests.Session() as s: url = 'https://br.investing.com/instruments/HistoricalDataAjax' # Making up for the first mistake. your_headers = {'User-Agent': 'Mozilla/5.0'} s.get(url, headers= your_headers) c_list = s.cookies.get_dict().items() cookie_list = [key+'='+value for key,value in c_list] cookie = ','.join(cookie_list) your_headers = {**{'X-Requested-With': 'XMLHttpRequest'},**your_headers} your_headers['Cookie'] = cookie data= {} # Your data. Making up for the second mistake. response = s.post(url, data= data, headers = your_headers)
score: 0

http://stackoverflow.com/q/52448144
answer count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: pandas
tagged with: python
tagged with: sklearn-pandas
tagged with: python-3.x
type: UnansweredQuestion
has body: I am working on some data mining self-learning from a free online resource I found. Basically I got a csv file with a bunch of names, movie titles, and what each person rated it. I'm trying to get the K-Nearest Neighbor from it using a cosine metric but I can't get the output to look not awful. Heres what I have so far for the code: from pandas import DataFrame import pandas as pd import numpy as np from sklearn.neighbors import NearestNeighbors as nn df = pd.read_csv("https://docs.google.com/spreadsheets/d/1MSBm3M6YmaLf0aiJCvkvrPsIJB2pPuBwse5ylnzEHRI/pub?gid=639849687&amp;single=true&amp;output=csv",index_col='Unnamed: 0') df = df.fillna(0) nn([df], metric = 'cosine') Pretty simple to do! Except my output looks like this: NearestNeighbors(algorithm='auto', leaf_size=30, metric='cosine', metric_params=None, n_jobs=1, n_neighbors=[ Patrick C Heather Bryan Patrick T Thomas aaron \ Alien NaN NaN 2.0 NaN 5.0 4.0 Avatar 4.0 5.0 5.0 4.0 2.0 NaN Blade Runner 5.0 NaN NaN N... You Got Mail NaN 2.0 2.0 1.0 2.0 NaN 2.0 [25 rows x 25 columns]], p=2, radius=1.0) Its messy and doesn't even show all the data. I tried casting it into an array but I go the error message "'ABCMeta' object does not support indexing" I'm fairly new to Python, I can do a few basic things but I am no expert. I was hoping someone could help nudge me in the direction to help clean this up. Thank you.
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52449147
score: -1
has title: Python 3 Cosine Nearest Neighbor Format
upvote count: 0

http://stackoverflow.com/comment/91998516
has text: @mynameisarjay of course! It's course 1 of a 5 course specialization on Coursera: [https://www.coursera.org/specializations/data-science-python](https://www.coursera.org/specializations/data-science-python). For a beginner such as I was it's very tough and demanding, but equally rewarding. I only did the first 3 courses, but even by the end of that, I was already achieving some supervised machine learning activities.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52525887

http://stackoverflow.com/comment/91999508
has text: So problem is why in your file is not read first column? Very hard to find problem without your real data (or data sample with same structure, values should be dummy data, if real are confidental). So is possible share your file - by gdocs, dropbox, similar?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52529948

http://stackoverflow.com/comment/91956453
score: 0
has text: Why not ask the user to set the environment variables `CC` and `FC` before hand? `setup.py` will then detect the compiler properly. You can test which compiler is used by calling `os.environ["CC"]` within your `setup.py`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52462910

http://stackoverflow.com/comment/91877600
type: Comment
score: 0
type: AnswerComment
has text: Thank you very much for your help!!
comment on: http://stackoverflow.com/a/52451339

http://stackoverflow.com/a/52456426
upvote count: 3
has comment: http://stackoverflow.com/comment/91855791
accepted answer of: http://stackoverflow.com/q/52451797
has comment: http://stackoverflow.com/comment/91856080
has body: If you look at the output of each layer you can easily understand what you are missing. def forward(self, x): print ('input', x.size()) out = self.layer1(x) print ('layer1-output', out.size()) out = self.layer2(out) print ('layer2-output', out.size()) out = out.reshape(out.size(0), -1) print ('reshape-output', out.size()) out = self.fc(out) print ('Model-output', out.size()) return out test_input = torch.rand(4,1,28,28) model(test_input) OUTPUT: ('input', (4, 1, 28, 28)) ('layer1-output', (4, 16, 14, 14)) ('layer2-output', (4, 32, 7, 7)) ('reshape-output', (4, 1568)) ('Model-output', (4, 10)) Conv2d layer doesn't change the height and width of the tensor. only changes the channel of tensor because of stride and padding. MaxPool2d layer halves the height and width of the tensor. inpt = 4,1,28,28 conv1_output = 4,16,28,28 max_output = 4,16,14,14 conv2_output = 4,32,14,14 max2_output = 4,32,7,7 reshapeutput = 4,1585 (32*7*7) fcn_output = 4,10 N --> Input Size, F --> Filter Size, stride-> Stride Size, pdg-> Padding size ConvTranspose2d; OutputSize = N*stride + F - stride - pdg*2 Conv2d; OutputSize = (N - F)/stride + 1 + pdg*2/stride [e.g. 32/3=10 it ignores after the comma]
answers question: http://stackoverflow.com/q/52451797
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91857699
has comment: http://stackoverflow.com/comment/91856276
type: Answer
score: 3

http://stackoverflow.com/q/52485828
downvote count: 0
has comment: http://stackoverflow.com/comment/92278281
favorite count: 0
accepted answer: http://stackoverflow.com/a/59432548
type: Question
has body: Background I want to avoid ever "accidentally" working in a default environment. I want to always have an equivalent to a requirements.txt or package.json file available, both to clearly separate one project from another, and so that I can easily look back to see what is installed (and what version of it). But I work primarily in the data science / analytics world, and primarily with Python. As such, I use Anaconda, pip, and Homebrew (I have a Mac). It would be great to rely upon just one package manager, and many folks espouse one method or another to accomplish this. Truth is, as of now (Sep 2018), it's impossible to work in any breadth of topics and avoid at least some mixture. Setting my sights lower and more realistic, I simply want to make sure that there is no default environment wherever possible, to make it cleaner and easier to work on projects with others. To my knowledge, there is no concept of an environment in Homebrew at all. Conda of course has environments, but it first sets up a default environment before you can create any others. Question Is there any way to install Anaconda without any default environment, so that I will always have to source activate <my_env>? If so, how do I do that? Barring this, what are the best suggestions to accomplish what I want, which is to never accidentally work in an environment where it is unclear what my dependencies are, recognizing that I'm talking primarily but not exclusively about using Python? (Please don't suggest that I should "just be careful" when installing packages. Yes, I understand that. But I am trying to pre-emptively be careful by making the wrong choices as difficult or impossible as I can. If I had no default environment, for instance, then pip would not even work until I sourced an environment since it would not be found in my normal environment.)
linked to: http://stackoverflow.com/q/33541876
has comment: http://stackoverflow.com/comment/92205806
tagged with: python
has comment: http://stackoverflow.com/comment/91913212
score: 10
has answer: http://stackoverflow.com/a/52737094
has comment: http://stackoverflow.com/comment/92280144
has comment: http://stackoverflow.com/comment/92241311
has title: Possible to install Anaconda without **any** default environment?
has comment: http://stackoverflow.com/comment/92278454
tagged with: homebrew
answer count: 3
has comment: http://stackoverflow.com/comment/91913250
tagged with: pip
linked to: http://stackoverflow.com/q/3819449
upvote count: 10
has comment: http://stackoverflow.com/comment/92292376
tagged with: anaconda
has comment: http://stackoverflow.com/comment/92278218
has comment: http://stackoverflow.com/comment/91913288
has comment: http://stackoverflow.com/comment/92205710
has comment: http://stackoverflow.com/comment/92373682
has comment: http://stackoverflow.com/comment/92276725
linked to: http://stackoverflow.com/q/37677476
has comment: http://stackoverflow.com/comment/92280182
linked to: http://stackoverflow.com/q/42859781
has comment: http://stackoverflow.com/comment/92280152
possible better answer: http://stackoverflow.com/a/52724556
has comment: http://stackoverflow.com/comment/92276626
tagged with: package-managers
has answer: http://stackoverflow.com/a/59432548
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52724556

http://stackoverflow.com/comment/92016929
comment on: http://stackoverflow.com/q/52538443
score: 0
has text: Yes, i did , but seems that it wasn't the same problem. I have tried the solution.But still not working
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91956656
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52504692
has text: Hi I added a edit with a bit more detail I hope this helps you.

http://stackoverflow.com/q/52471231
upvote count: 2
has answer: http://stackoverflow.com/a/52471340
tagged with: python
has answer: http://stackoverflow.com/a/52471246
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52471246
has body: Given two lists A = ['a','b','c','d'] B = [(1,11),(2,22),(3,33),(4,44)] I want to zip into the list [('a', 1, 11), ('b', 2, 22), ('c', 3, 33), ('d', 4, 44)]. Doing list(zip(a, b)) gives [('a', (1, 11)), ('b', (2, 22)), ('c', (3, 33)), ('d', (4, 44))]. Unpacking B doesn't work [('a', 1, 2, 3, 4), ('b', 11, 22, 33, 44)].
type: Question
has answer: http://stackoverflow.com/a/52471255
downvote count: 0
has title: Zipping tuples and unpacking into same dimension
answer count: 3
favorite count: 0
possible better answer: http://stackoverflow.com/a/52471340

http://stackoverflow.com/comment/91965719
type: Comment
comment on: http://stackoverflow.com/a/52507848
score: 1
has text: Thanks, that's really helpful. I didn't realise win32api only worked on Windows. So I've instead changed to `import tkinter as tk` `from tkinter import messagebox` `root = tk.Tk() root.withdraw() messagebox.showwarning('End of Data', "You have reached the end of the data.")` Do you know similar tools for testing that message box? I'll keep my original question as it is because I imagine someone else might find it useful. But I don't know if this change makes it worth writing a new question.
type: AnswerComment

http://stackoverflow.com/comment/91870288
comment on: http://stackoverflow.com/a/52464123
score: 0
type: AnswerComment
has text: I do not get what you mean by "use the same optimizer in other"
type: Comment

http://stackoverflow.com/comment/92016427
type: QuestionComment
comment on: http://stackoverflow.com/q/52538429
score: 1
has text: `alaska baobab greg` is alphabetic order. Did you get your example wrong, or did you mean something other than alphabetic?
type: Comment

http://stackoverflow.com/a/59112073
type: Answer
score: 0
has body: It seems that the role you're using doesn't have the relevant policies regarding the SES service. Step 1: Create a custom policy - For example: SES-SendEmail-Policy and provide it with the following JSON: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ses:SendEmail", &lt;--- This is the action that was missing ], "Resource": "*" } ] } Step 2: Attach the SES-SendEmail-Policy to the basic-lambda-role role.
answers question: http://stackoverflow.com/q/52473158

http://stackoverflow.com/q/52559146
has answer: http://stackoverflow.com/a/52612858
type: Question
has answer: http://stackoverflow.com/a/52559234
answer count: 2
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/92057638
score: 0
has comment: http://stackoverflow.com/comment/92057468
has comment: http://stackoverflow.com/comment/92057688
has comment: http://stackoverflow.com/comment/92057859
has body: I am trying to run examples presented on this website My code is this #!/usr/bin/env python3 from bottle import route, run @route('/cars') def getcars(): cars = [ {'name': 'Audi', 'price': 52642}, {'name': 'Mercedes', 'price': 57127}, {'name': 'Skoda', 'price': 9000}, {'name': 'Volvo', 'price': 29000}, {'name': 'Bentley', 'price': 350000}, {'name': 'Citroen', 'price': 21000}, {'name': 'Hummer', 'price': 41400}, {'name': 'Volkswagen', 'price': 21600} ] return dict(data=cars) run(host='localhost', port=8080, debug=True) When I run python run.py, and log on to http://localhost:8080/cars. I get the 404 errors. When I run the following example, I get the same 404 errors #!/usr/bin/env python3 from bottle import route, run @route('/message') def hello(): return "Today is a beautiful day" run(host='localhost', port=8080, debug=True) What am I missing?
has title: Keep getting 404 errors in Bottle
has comment: http://stackoverflow.com/comment/92057822
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92057456
tagged with: python
tagged with: bottle

flask-restful
tags question: http://stackoverflow.com/q/52547705
tags question: http://stackoverflow.com/q/52473147
type: Tag
tags question: http://stackoverflow.com/q/52568304
tag name: flask-restful

python-3.x
tags question: http://stackoverflow.com/q/52569623
tags question: http://stackoverflow.com/q/52469795
tags question: http://stackoverflow.com/q/52584104
tags question: http://stackoverflow.com/q/52489359
tags question: http://stackoverflow.com/q/52554712
tags question: http://stackoverflow.com/q/52588167
tags question: http://stackoverflow.com/q/52533860
tags question: http://stackoverflow.com/q/52505767
tags question: http://stackoverflow.com/q/52480002
tags question: http://stackoverflow.com/q/52547525
tags question: http://stackoverflow.com/q/52513043
tags question: http://stackoverflow.com/q/52562851
tags question: http://stackoverflow.com/q/52431785
tags question: http://stackoverflow.com/q/52466216
tags question: http://stackoverflow.com/q/52544740
tags question: http://stackoverflow.com/q/52443717
tags question: http://stackoverflow.com/q/52484250
tags question: http://stackoverflow.com/q/52430463
tags question: http://stackoverflow.com/q/52477025
tags question: http://stackoverflow.com/q/52451471
tags question: http://stackoverflow.com/q/52500666
tags question: http://stackoverflow.com/q/52434785
tags question: http://stackoverflow.com/q/52459465
tags question: http://stackoverflow.com/q/52462622
tags question: http://stackoverflow.com/q/52506066
tags question: http://stackoverflow.com/q/52491747
tags question: http://stackoverflow.com/q/52529086
tags question: http://stackoverflow.com/q/52579021
tags question: http://stackoverflow.com/q/52529122
tags question: http://stackoverflow.com/q/52541377
tags question: http://stackoverflow.com/q/52587850
tags question: http://stackoverflow.com/q/52448755
tags question: http://stackoverflow.com/q/52442589
tags question: http://stackoverflow.com/q/52445977
tags question: http://stackoverflow.com/q/52582659
tags question: http://stackoverflow.com/q/52463634
tags question: http://stackoverflow.com/q/52574978
tags question: http://stackoverflow.com/q/52455477
tags question: http://stackoverflow.com/q/52563826
tags question: http://stackoverflow.com/q/52498223
tags question: http://stackoverflow.com/q/52583845
tags question: http://stackoverflow.com/q/52488843
tags question: http://stackoverflow.com/q/52459780
tags question: http://stackoverflow.com/q/52486822
tags question: http://stackoverflow.com/q/52496978
tags question: http://stackoverflow.com/q/52507548
tags question: http://stackoverflow.com/q/52435224
tags question: http://stackoverflow.com/q/52541450
tags question: http://stackoverflow.com/q/52568667
tags question: http://stackoverflow.com/q/52489260
tags question: http://stackoverflow.com/q/52533733
tags question: http://stackoverflow.com/q/52507345
tags question: http://stackoverflow.com/q/52562544
tags question: http://stackoverflow.com/q/52548299
tags question: http://stackoverflow.com/q/52574557
tags question: http://stackoverflow.com/q/52533044
tags question: http://stackoverflow.com/q/52453925
tags question: http://stackoverflow.com/q/52516109
tags question: http://stackoverflow.com/q/52431602
tags question: http://stackoverflow.com/q/52459110
tags question: http://stackoverflow.com/q/52568213
tags question: http://stackoverflow.com/q/52523102
tags question: http://stackoverflow.com/q/52468909
tags question: http://stackoverflow.com/q/52564301
tags question: http://stackoverflow.com/q/52571873
tags question: http://stackoverflow.com/q/52496390
tags question: http://stackoverflow.com/q/52467177
tags question: http://stackoverflow.com/q/52434246
tags question: http://stackoverflow.com/q/52527098
tags question: http://stackoverflow.com/q/52567128
tags question: http://stackoverflow.com/q/52471227
tags question: http://stackoverflow.com/q/52462326
tags question: http://stackoverflow.com/q/52452912
tags question: http://stackoverflow.com/q/52497775
tags question: http://stackoverflow.com/q/52545977
tags question: http://stackoverflow.com/q/52583006
tags question: http://stackoverflow.com/q/52486899
tags question: http://stackoverflow.com/q/52442793
tags question: http://stackoverflow.com/q/52431995
tags question: http://stackoverflow.com/q/52565893

http://stackoverflow.com/q/52433006
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/52433515
has body: I have this command in Ubuntu: bgpq3 -4 AS-YAHOO-JP-2 -m 24 -l Google the output is a list of prefixes: ip prefix-list Google permit 14.137.224.0/19 ip prefix-list Google permit 27.111.76.0/22 ip prefix-list Google permit 27.121.128.0/17 ip prefix-list Google permit 27.133.224.0/22 ip prefix-list Google permit 27.133.240.0/22 ip prefix-list Google permit 27.133.240.0/24 ip prefix-list Google permit 27.133.241.0/24 ip prefix-list Google permit 27.133.242.0/24 ip prefix-list Google permit 27.133.243.0/24 how can i put the output to a list and use each line (as example send them to a database) I dont want to save them first to a file.txt i am using this command but is does'nt help because the results are stored in a text file. os.system("bgpq3 -4 AS-YAHOO-JP-2 -m 24 -l Google > list.txt") Please help me figure this out!!!
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52433515
tagged with: command
tagged with: terminal
has title: Python Script send a ubuntu terminal command to a list
tagged with: python

http://stackoverflow.com/q/52462402
answer count: 2
has answer: http://stackoverflow.com/a/52462494
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91867073
has comment: http://stackoverflow.com/comment/91867174
tagged with: python
has comment: http://stackoverflow.com/comment/91867187
has answer: http://stackoverflow.com/a/52462612
type: AnsweredQuestion
has body: I'm pretty new at python, and coding really. I'm trying to create an ATM type program that will let you make deposits and withdraws. I put the error message that I'm receiving. To be honest, I just don't know where to go from here. Also, how can I make sure the withdrawal amount is divisible by 10 with the % call? Any help is appreciated! File "/Users/jess/PycharmProjects/assignment2/assignment 1.py", line 54, in &lt;module&gt; r = input("Are you sure you want to deposit ", deposit, "? [Y/N]") TypeError: [raw_]input expected at most 1 arguments, got 3 code: #display welcome message print("Welcome to a Virtual Credit Union ATM!") counter = 0 while counter &lt; 3: pin = input("Please input your 4-digit PIN: ") if pin == 9876: print("Correct PIN, will continue to menu") break print("Incorrect PIN, please try again") counter += 1 if counter == 3: print("You're locked out, Goodbye") else: print("Onto Menu options") def menu(): ## Your menu design here print "1. View Account Balance" print "2. Withdraw cash" print "3. Make a deposit" print "4. Exit" loop = True while loop: ## While loop which will keep going until loop =False menu() ## Displays menu choice = input("Enter your choice [1-4]: ") if choice == 1: account_balance = (int, 'Your account balance is: $500') print(account_balance) elif choice == 2: print "Withdraw Cash, must be multiple of 10" withdraw = int(input('How much do you want to Withdraw?:')) if withdraw &gt; account_balance: print("Insufficient funds") withdraw = int(input("Enter new amount to Withdraw: ")) elif withdraw &lt;= account_balance: balance = account_balance - withdraw print (' New Balance :', balance) elif choice == 3: print "Make Deposit" deposit = int(input('How much do you want to Deposit?:')) r = input("Are you sure you want to deposit ", deposit, "? [Y/N]") if choice == y: balance = account_balance + deposit print (' New Balance:', balance) elif choice == n: deposit2 = input("Enter the amount you want to deposit") balance = account_balanc…
upvote count: 1
has comment: http://stackoverflow.com/comment/91867131
type: Question
has comment: http://stackoverflow.com/comment/91867105
score: 1
accepted answer: http://stackoverflow.com/a/52462612
has title: error message with atm withdrawal, can't get it to run properly when entering an amount greater than, or less than the account balance
possible better answer: http://stackoverflow.com/a/52462494

http://stackoverflow.com/comment/91946864
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52502551
score: 0
has text: which python version you are using?

http://stackoverflow.com/q/52456643
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/68591986
answer count: 1
has body: I am using python 3.7.0 Eg:- Person 'A' sent mail to me with text :- "Test mail". Person 'B' received the mail and replied with body :- "Thanks for the information. Please attach logs" Person 'A' received the mail with new body message mentioned in step-2. The body message mentioned in step-1 is not appearing in the mail. import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox=outlook.GetDefaultFolder(6) messages=inbox.items msg=messages.GetLast() reply=msg.Reply() reply.Body = "Thanks for the information. Please attach logs" reply.Send
downvote count: 0
type: UnansweredQuestion
score: 2
has title: In python when I use 'Reply' function for outlook mail item the previous conversation is not appending
favorite count: 0
type: Question

http://stackoverflow.com/a/52575754
accepted answer of: http://stackoverflow.com/q/52574728
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92100631
upvote count: 2
type: Answer
score: 2
has body: To keep the desired columns try this cols_to_keep = ['col1', 'col2', 'col3'] df = df[cols_to_keep] df You can also read in only the columns you need like this df = pd.read_csv('test_old.csv', usecols = ['col1', 'col2', 'col3'], dtype={"col1" : str, "col2" : str})
answers question: http://stackoverflow.com/q/52574728

http://stackoverflow.com/comment/92017369
score: 0
comment on: http://stackoverflow.com/q/52536655
type: Comment
type: QuestionComment
has text: Ah, and that’s exactly it; I bet you are passing the encrypted data as a filename to the decrypt function.

http://stackoverflow.com/comment/92041207
comment on: http://stackoverflow.com/a/52551159
score: 0
type: Comment
has text: But the OP said the original question was to count duplicate in a dictionary and count the duplicate values in descending order....
type: AnswerComment

http://stackoverflow.com/a/78902708
score: 0
type: Answer
has body: class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -&gt; Optional[ListNode]: cur = dummy = ListNode() while list1 and list2: if list1.val &lt; list2.val: cur.next = list1 list1, cur = list1.next, list1 else: cur.next = list2 list2, cur = list2.next, list2 if list1 or list2: cur.next = list1 if list1 else list2 return dummy.next
has comment: http://stackoverflow.com/comment/139152824
answers question: http://stackoverflow.com/q/52453738

http://stackoverflow.com/a/52530888
score: 0
has body: Using same collection in two loops and deleting from the collection inside the loop is creating the issue here. I think it is better to create a new list of items that should be removed and delete them after this loop. toDelete = [] for i in ap: for j in ap: if i[1] == j[1] and not ap.index(i) == ap.index(j): if i[0] == "unknown": toDelete.append(i) else: toDelete.append(j) for i in toDelete: try: ap.remove(i) except Exception as e: pass The try-catch is there as each element to be updated appears twice in the toDelete. This can be avoided by taking the second loop as: for j in ap[ap.index(i)+1:]:
answers question: http://stackoverflow.com/q/52530777
type: Answer

http://stackoverflow.com/a/52529387
has comment: http://stackoverflow.com/comment/92000844
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91998432
has body: I already left you a comment but I figured I'd put this in an answer to make it easier to read without the limitations of a comment. There are a couple of problems here. Firstly, it appears you're trying to make a dictionary of lists, but you're using dictionary syntax (curly braces) for your lists instead of list syntax (square brackets) so instead of doing: # this is wrong invdict = {{'fruits':{'apple','manggo'}},{'veggies':{'cabbage','cucumber'}},{'drinks:{'juice','coke'}}} You should do: # this is right invdict = {'fruits': ['apple','mango'], 'veggies': ['cabbage','cucumber'], 'drinks': ['juice','coke']} You can also make this a lot easier to read with some appropriately-placed whitespace: # easier to read invdict = {'fruits': ['apple','mango'], 'veggies': ['cabbage','cucumber'], 'drinks': ['juice','coke']} Now for the next problem. You want your function funcB to know about invdict, which is currently only available in the namespace of your function funcB. It looks like you're trying to return invdict from funcA but you're using return incorrectly. It also looks like you want to print the return values from these functions, but again, your syntax is incorrect (you're printing the function instance rather than calling it and printing its return value.) What you probably want to do is this: def funcA(): # correct syntax for a dictionary of lists, with whitespace for readability invdict = {'fruits': ['apple','mango'], 'veggies': ['cabbage','cucumber'], 'drinks': ['juice','coke']} # correct usage of return statement return invdict def funcB(): invdict = funcA() return invdict # correct way to call functions for their return values print(funcA()) print(funcB()) remember, to call a function, you have to do function_name(). If the function takes parameters, the parameters go inbetween the parentheses. If it doesn't take parameters, you just use "()." If you just type the function name, you're passing the function definition itself, rather than executing that function …
upvote count: 2
has comment: http://stackoverflow.com/comment/91998443
type: Answer
has comment: http://stackoverflow.com/comment/92003673
has comment: http://stackoverflow.com/comment/92003442
has comment: http://stackoverflow.com/comment/92001257
score: 2
has comment: http://stackoverflow.com/comment/92001109
has comment: http://stackoverflow.com/comment/92001533
has comment: http://stackoverflow.com/comment/91998259
accepted answer of: http://stackoverflow.com/q/52529122
has comment: http://stackoverflow.com/comment/92001660
answers question: http://stackoverflow.com/q/52529122
downvote count: 0
has comment: http://stackoverflow.com/comment/92004071
has comment: http://stackoverflow.com/comment/92001984
has comment: http://stackoverflow.com/comment/91998495
has comment: http://stackoverflow.com/comment/92002060
has comment: http://stackoverflow.com/comment/92001411
has comment: http://stackoverflow.com/comment/92001177
has comment: http://stackoverflow.com/comment/92001586

http://stackoverflow.com/q/52481607
has body: I have this problem: cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return f(a, b) return pair Implement car and cdr. I don't get the function. It has an inner function and calls an other function in the return. As far as I understood the inner functions is that these functions should depend on the functions above them. In this case on cons(..). But the function is not using a or b. And why is the function f there? The task is to implement car and cdr, and function f should be given. So could someone explain me this function? And how could I start with the task?
has comment: http://stackoverflow.com/comment/91904817
favorite count: 0
answer count: 5
has title: Don't understand the inner function in python
tagged with: python
has comment: http://stackoverflow.com/comment/91905287
has answer: http://stackoverflow.com/a/63362964
has answer: http://stackoverflow.com/a/52481852
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91904751
has answer: http://stackoverflow.com/a/52481994
tagged with: parameters
has comment: http://stackoverflow.com/comment/91904881
type: Question
has answer: http://stackoverflow.com/a/52481807
upvote count: 15
tagged with: function
downvote count: 0
score: 15
has answer: http://stackoverflow.com/a/71457651

http://stackoverflow.com/q/52513429
downvote count: 0
has body: I have below pandas dataset: set_id A,B A,C,E A Desired result: set_id set_id_1 set_id_2 set_id_3 A,B A B null A,C,E A C E A A null null set_id can have n number of values. Suppose the maximum number of values in set_id is 100, I should have 100 new columns I tried using multilabel binarizer df1 = pd.DataFrame() df1['set_id'] = df['set_id'].str.split(',') from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() df1=df.join(pd.DataFrame(mlb.fit_transform(df['set_id']) ,columns=mlb.classes_,index=df.head(100).index)) It will create more than 100K columns as I have more than 100K unique records
accepted answer: http://stackoverflow.com/a/52513498
tagged with: pandas
type: AnsweredQuestion
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 1
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52513498
has title: Pandas: a column with repeating groups to multiple columns

http://stackoverflow.com/q/52479249
has comment: http://stackoverflow.com/comment/91905422
has comment: http://stackoverflow.com/comment/91905058
has comment: http://stackoverflow.com/comment/91905544
has comment: http://stackoverflow.com/comment/91902216
has comment: http://stackoverflow.com/comment/91904869
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91900443
has body: I have a txt file which contains the datas corresponding to every second in every single day from year 2016-2018(everyday concluding about over 1400 datas), firstly, I selected the datas on a specifical day: 05.01.2016, then I want to draw a graph in python using the day's datas the following code is for selecting values and drawing graph: if '01.05.2016' in row: #select the value in day 05.01.2016 x = [row.split()[6]] y = [row.split()[2]] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x,y) plt.ylim((200,800)) plt.show() if I use the command: x = [row.split()[6]] y = [row.split()[2]] print(x,y) then the x and y come will successfully come out(just some pairs x-y values as example): ['01.05.2016/15:43:00'] ['499'] ['01.05.2016/15:44:00'] ['501'] ['01.05.2016/15:45:00'] ['502'] ['01.05.2016/15:46:00'] ['502'] a part of my original txt.file is like: 01.05.2016 15:43:00 499 U 42491,65486 -0,01 01.05.2016/15:44:00 01.05.2016 15:44:00 501 U 42491,65556 0,01 01.05.2016/15:45:00 01.05.2016 15:45:00 502 U 42491,65625 0,02 01.05.2016/15:46:00 01.05.2016 15:46:00 503 U 42491,65694 0,03 01.05.2016/15:47:00 But if I continue to write the command for drawing graph. the graph only show one pair(the last one pair) x-y value, my graph is like: who can help me maybe?
tagged with: dataframe
has title: Plotting selected values from txt file in python
has comment: http://stackoverflow.com/comment/91900765
has comment: http://stackoverflow.com/comment/91905130
upvote count: 2
has comment: http://stackoverflow.com/comment/91900228
tagged with: pandas
has comment: http://stackoverflow.com/comment/91905485
answer count: 1
has answer: http://stackoverflow.com/a/52480028
accepted answer: http://stackoverflow.com/a/52480028
has comment: http://stackoverflow.com/comment/91904123
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91900389
has comment: http://stackoverflow.com/comment/91905525
type: Question

http://stackoverflow.com/comment/91986798
score: 0
has text: So this is *text*?
comment on: http://stackoverflow.com/q/52523614
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52537561
score: 3
has answer: http://stackoverflow.com/a/52537818
upvote count: 3
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/92014665
type: Question
accepted answer: http://stackoverflow.com/a/52537818
has comment: http://stackoverflow.com/comment/92014999
has title: How is the function launched without a function call?
tagged with: class
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: Can somebody explain to me how the program knows that if I click the right mouse button it must launch the contextMenuEvent? Where is this call made? And if it is the parent class that is doing it, how it knows the name of the function? import sys from PyQt5.QtWidgets import QMainWindow, qApp, QMenu, QApplication class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Context menu') self.show() def contextMenuEvent(self, event): cmenu = QMenu(self) newAct = cmenu.addAction("New") opnAct = cmenu.addAction("Open") quitAct = cmenu.addAction("Quit") action = cmenu.exec_(self.mapToGlobal(event.pos())) if action == quitAct: qApp.quit() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91967425
score: 0
comment on: http://stackoverflow.com/q/52512606
type: QuestionComment
type: Comment
has text: i will check it out

http://stackoverflow.com/a/54197704
has body: You can get the data (x and y values) used to plot the distribution. From that you can interpolate to any values in between. If you want to get a probability you must integrate the pdf data and calculate the value in the range. import numpy as np import seaborn as sns import scipy x=np.array([33,42,31,36,36,33, 37 ,37, 28 ,36 ,32, 40 ,43 ,37, 33 ,40 ,41 ,44, 53 ,38, 32, 48, 51, 37 ,29, 41 ,30 ,29 ,28, 40 ,35 ,33 ,33 ,29, 27 ,33, 35, 34, 28 ,35, 39 ,37 ,31 ,33 ,32 ,39 ,24, 30, 29, 21, 28, 28, 29, 29 ,25, 34, 24, 28 ,25, 25 ,27, 18, 27, 27, 35, 26, 29, 29, 30]) ax = sns.distplot(x) #Value to estimate for value = 20 #Get the data from the KDE line xdata, ydata = ax.get_lines()[0].get_data() #Find the closest point on the curve idx = (np.abs(xdata-value)).argmin() #Interpolate to get a better estimate p = np.interp(value,xdata[idx:idx+2],ydata[idx:idx+2]) print('Point on PDF for X = {} is: {}'.format(value,p)) #Plot the line ax.vlines(value, 0, p ,colors='r') #Find the probability for an interval of one (e.g. between 20 and 21) cdf = scipy.integrate.cumtrapz(ydata, xdata, dx=1, initial=0) pr = cdf[value+1] - cdf[value] print('Probability of X &lt;{},{}&gt; is: {}'.format(value,value+1,pr)) # Fill the area plt.fill_between(xdata,ydata, where = (xdata&gt;=value) &amp; (xdata&lt;=value+1), color='g') Output should be: Point on PDF for X = 20 is: 0.007789463075158201 Probability of X &lt;20,21&gt; is: 0.0015438476906999374 Output distplot
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52470172

http://stackoverflow.com/q/52564048
has answer: http://stackoverflow.com/a/52564098
upvote count: 1
accepted answer: http://stackoverflow.com/a/52564079
type: Question
has title: if date is weekend - auto rerun the function
answer count: 2
downvote count: 0
favorite count: 0
has body: So I can generate random days in a given start-end date relationship, but, if the date happens to be a weekend - currently all I can get working is to print to the user 'it is a weekend'. What I would like to do is, if the random day IS a weekend, rerun the function so the user does not have to manually. Basically - only print out weekdays - currently, if the random day is a weekend, it prints a blank space or None value. Only return/print weekdays is the main goal. Here is the code so far: from datetime import datetime, timedelta from random import randrange def random_date(start, end): delta = end - start random_day = randrange(delta.days) myresult = start + timedelta(days=random_day) return myresult d1 = datetime.strptime('9/1/2018', '%m/%d/%Y') d2 = datetime.strptime('9/30/2018', '%m/%d/%Y') myresult = random_date(d1, d2) if myresult.weekday() not in (5, 6): print myresult.strftime('%m-%d-%Y') else: print "hit a weekend"
has answer: http://stackoverflow.com/a/52564079
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52564098
score: 1

mergesort
tags question: http://stackoverflow.com/q/52435547
tag name: mergesort
type: Tag
tags question: http://stackoverflow.com/q/52570838

http://stackoverflow.com/comment/91812101
has text: You are looping through the output (`joined`) string and printing.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52434130

http://stackoverflow.com/a/52463504
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52463349
has body: How about instantiating an empty dataframe and appending your scraped data rowwise: columns = ("names", "age", "w", "l", "g", "gs", "ip", "hits", "runs", "bb", "so") df = pd.DataFrame(columns=columns) for idx, pitcher_row in enumerate(tree.xpath('//table[contains(@class,"stats_table")]//tr[contains(@class,"full_table")]')): tmp = [] tmp.append(pitcher_row.xpath('.//td[@data-stat="player"]/a')[0].text) tmp.append(pitcher_row.xpath('.//td[@data-stat="age"]/text()')[0]) tmp.append(pitcher_row.xpath('.//td[@data-stat="W"]/text()')[0]) ... df.loc[idx] = tmp Or even simpler if you want to stick with most of your code: columns = ("names", "age", "w", "l", "g", "gs", "ip", "hits", "runs", "bb", "so") df = pd.DataFrame(columns=columns) for idx, pitcher_row in enumerate(tree.xpath('//table[contains(@class,"stats_table")]//tr[contains(@class,"full_table")]')): names = pitcher_row.xpath('.//td[@data-stat="player"]/a')[0].text age = pitcher_row.xpath('.//td[@data-stat="age"]/text()')[0] w = pitcher_row.xpath('.//td[@data-stat="W"]/text()')[0] l = pitcher_row.xpath('.//td[@data-stat="L"]/text()')[0] g = pitcher_row.xpath('.//td[@data-stat="G"]/text()')[0] gs = pitcher_row.xpath('.//td[@data-stat="GS"]/text()')[0] ip = pitcher_row.xpath('.//td[@data-stat="IP"]/text()')[0] hits = pitcher_row.xpath('.//td[@data-stat="H"]/text()')[0] runs = pitcher_row.xpath('.//td[@data-stat="R"]/text()')[0] bb = pitcher_row.xpath('.//td[@data-stat="BB"]/text()')[0] so = pitcher_row.xpath('.//td[@data-stat="SO"]/text()')[0] df.loc[idx] = (names, age, w, l, g, gs, ip, hits, runs, bb, so)
answers question: http://stackoverflow.com/q/52463349
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91882618

http://stackoverflow.com/q/52468175
score: 0
has comment: http://stackoverflow.com/comment/91878503
tagged with: python
has comment: http://stackoverflow.com/comment/91881366
answer count: 0
has comment: http://stackoverflow.com/comment/91880055
type: UnansweredQuestion
has title: Is there a way to replicate scikit.measure.label for edge detection in Numpy?
has comment: http://stackoverflow.com/comment/91878575
has comment: http://stackoverflow.com/comment/91878655
type: Question
has body: I know this is a frivolous question, but is there a way to replicate that functionality without using the scikit library? This question is essentially what I'm trying to do. As far as I've gotten is possibly using the concept of neighbors via a meta array, but I'm still struggling with the idea of how to split that into different arrays for each set of neighbors. Edit: Sorry haven't asked many questions here, realized this is difficult without actual examples. E.g. Given the numpy array: [ 0, 0, 1, 1, 0, 0 ] [ 0, 0, 1, 0, 0, 0 ] [ 0, 0, 1, 1, 0, 0 ] [ 0, 0, 0, 0, 0, 0 ] [ 0, 1, 1, 1, 0, 0 ] [ 0, 1, 1, 0, 0, 0 ] I'm trying to get to an output that's two different arrays with the index location of the touching values (excluding 0's). So desired result is: output1 = [[0,2], [0,3], [1,2], [2,2], [2,3]] output2 = [[4,1], [4,2], [4,3], [5,1], [5,2]] Edit #2: I've made some progress. I am now able to create a list of lists. Here is the code: data = np.asarray(image_x) vals = np.argwhere(data == 0) list = [] listoflists = [] row = -1 for x in range(0, vals.shape[0]): for y in range(0, vals.shape[1]-1): if row == -1: row = vals[x][0] if row == vals[x][0]: list.append(vals[x][1]) else: listoflists.append((vals[x-1][0], list)) row = vals[x][0] list = [] list.append(vals[x][1]) Notes: image_x is a black and white image of shape outlines The loop currently doesn't capture a pixel if it is a single pixel on a single row at the very end. I'm troubleshooting this now, just wanted to post the update in my excitement.
tagged with: python-imaging-library
linked to: http://stackoverflow.com/q/49771746
has comment: http://stackoverflow.com/comment/91880008
tagged with: numpy
has comment: http://stackoverflow.com/comment/91878120
has comment: http://stackoverflow.com/comment/91880472

http://stackoverflow.com/q/52546295
score: 1
has body: I'm trying to use a generic object called 'Memory' to temporary store a value that is writen by a process called 'Writer_process' and readed by 'Reader_process' but reader return only the original value stored in 'Memory'. import multiprocessing import time class Writer_process(multiprocessing.Process): def __init__(self, val, memory): super().__init__() self.val = val self.memory = memory def run(self): cont = 0 while True: cont += self.val self.memory.num = cont time.sleep(1) class Reader_process(multiprocessing.Process): def __init__(self, val, memory): super().__init__() self.val = val self.memory = memory def run(self): while True: print(self.memory.num) time.sleep(self.val) class Memory(): num = 0 if __name__ == '__main__': memory = Memory() writer = Writer_process(1, memory) reader = Reader_process(1, memory) writer.start() reader.start()
tagged with: multiprocessing
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/92032451
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52552285
has title: Python multiprocessing, share data between process using an object

http://stackoverflow.com/q/52543777
score: 1
has comment: http://stackoverflow.com/comment/92030177
type: Question
downvote count: 0
favorite count: 0
tagged with: sentiment-analysis
has title: How can I concatenate the lines of dialogue while doing Natural Language Processing on a book
tagged with: nlp
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
has body: I am working on a sentiment analysis project of a book. I am using nltk.vader.sentimentintensityanalyzer to record the sentiment polarity of paragraphs in the Harry Potter series. To create paragraphs and remove the line breaks I did: text_file = open('HP1 Sorcerer of Stone.txt', 'r') text = str(text_file.readlines()) text.replace('\\n"', "").replace("\'", "").replace(" , ","") This breaks the book down into paragraphs. The problem arises when it comes to dialogue. Dialogue has the same paragraph breaks in between each character's words ' "So?" snapped Mrs. Dursley. ', ' "Well, I just thought... maybe... it was something to do with... you know... her crowd." ', ' Mrs. Dursley sipped her tea through pursed lips. Mr. Dursley wondered whether he dared tell her he\\d heard the name "Potter." He decided he didn\\t dare. Instead he said, as casually as he could, "Their son -- he\\d be about Dudley\\s age now, wouldn\\t he?" ', ' "I suppose so," said Mrs. Dursley stiffly. ', ' "What\\s his name again? Howard, isn\\t it?" ', ' "Harry. Nasty, common name, if you ask me." ', How can I edit my breakdown methods so dialogue stays together as one element? The dialogue as a whole will then be used as a single input into the intensity analyzer.

http://stackoverflow.com/comment/92096051
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52580096
has text: @Bazingaa Thanks. this is not my problem. It was a typo. The error is on scatter.

http://stackoverflow.com/q/52493231
answer count: 0
type: UnansweredQuestion
has title: multiple output and losses for multi-class image segmentation
has comment: http://stackoverflow.com/comment/91927402
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91928102
has comment: http://stackoverflow.com/comment/91928779
has comment: http://stackoverflow.com/comment/91928162
has comment: http://stackoverflow.com/comment/91928487
has comment: http://stackoverflow.com/comment/91928327
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92226251
tagged with: keras
has comment: http://stackoverflow.com/comment/91928603
tagged with: python
has body: I use Keras with Tensorflow for a multi-class image segmentation problem. For each training pair {(x_i,y_i)}^N, my model has different auxiliary losses (out_aux) that are added together with one main (out_main) loss function. Input(256,256,5) | | something happening here / | | | \ | | | | | out_main out_aux(0) out_aux(1) out_aux(2) out_aux(3) At the moment, I'm using the same loss for all outputs ( categorical_crossentropy), so basically, a single (x,y)-pair is evaluated on all losses. I'm having some issues when defining the model. The method to create the auxiliary losses looks as follows: def aux_branch(self, x, nb_labels=5): # x is a list of feature maps. x_aux = [] for nf in range(len(x)): x_in = x[nf] out_aux = _conv(filters=nb_labels, kernel_size=(1, 1), activation='linear')(x_in) out_aux = Reshape((im_rows * im_cols, nb_labels))(out_aux) out_aux = Activation('softmax')(out_aux) out_aux = Reshape((im_rows, im_cols, nb_labels), name='out_aux_{}'.format(nf))(out_aux) x_aux.append(out_aux) return x_aux and the method to create and compile the model is defined as: def create_model(self, x, lossfunc, nb_labels=5): ... ... out_aux = self.aux_branch(x) ... out_main = _conv(filters=nb_labels, kernel_size=(1, 1), activation='linear')(out_main) out_main = Reshape((im_rows * im_cols, nb_labels))(out_main) out_main = Activation('softmax')(out_main) out_main = Reshape((im_rows, im_cols, nb_labels), name='out_main')(out_main) model = Model(inputs=inputs, outputs=[out_main, out_aux[0], out_aux[1], out_aux[2], out_aux[3], out_aux[4]]) model.compile(loss={'out_aux_0': lossfunc, 'out_aux_1': lossfunc, 'out_aux_2': lossfunc, 'out_aux_3': lossfunc, 'out_aux_4': lossfunc, 'out_main': lossfunc}, # loss_weights={'out_aux_0': 1.0, # 'out_aux_1': 1.0, # 'out_aux_2': 1.0, # 'out_aux_3': 1.0, # 'out_aux_4': 1.0, # 'out_main': 1.0}, optimizer=optimizer, metrics={'out_main': 'accuracy', 'out_aux_0': 'accuracy', 'out_aux_1': 'accuracy', 'out_aux_2': 'accuracy', 'out_aux_3': 'accuracy', 'o…

http://stackoverflow.com/comment/92057827
type: Comment
comment on: http://stackoverflow.com/a/52546499
type: AnswerComment
score: 0
has text: is it possible to just take the value from one of the rows? No sort of aggregation/sum/concatenation needed, there won't be much or any difference between the rows other than the `amount` and `desc` columns.

http://stackoverflow.com/a/52458320
has comment: http://stackoverflow.com/comment/91858802
score: 2
answers question: http://stackoverflow.com/q/52458290
downvote count: 0
has comment: http://stackoverflow.com/comment/91858894
has comment: http://stackoverflow.com/comment/91858827
upvote count: 2
has body: One way to do it would be to loop over the ord of the corresponding ascii characters for num in range(ord('='), ord('F')): print(num) Output 61 62 63 64 65 66 67 68 69 This works by essentially looking up which characters correspond to 61 and 70 then using those to loop over &gt;&gt;&gt; chr(61) '=' &gt;&gt;&gt; chr(70) 'F'
has comment: http://stackoverflow.com/comment/91858849
type: Answer

http://stackoverflow.com/q/52500857
has title: Creating nested dictionary from text file
possible better answer: http://stackoverflow.com/a/52502375
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52591455
accepted answer: http://stackoverflow.com/a/52591455
downvote count: 0
has answer: http://stackoverflow.com/a/52502375
has comment: http://stackoverflow.com/comment/91950630
has comment: http://stackoverflow.com/comment/91942362
upvote count: 1
has body: /tmp/bond0: Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011) Bonding Mode: IEEE 802.3ad Dynamic link aggregation Transmit Hash Policy: layer2+3 (2) MII Status: up MII Polling Interval (ms): 100 Up Delay (ms): 0 Down Delay (ms): 0 802.3ad info LACP rate: slow Min links: 0 Aggregator selection policy (ad_select): stable Active Aggregator Info: Aggregator ID: 2 Number of ports: 2 Actor Key: 11 Partner Key: 705 Partner Mac Address: 02:1c:73:9c:3c:fe Slave Interface: p1p1 MII Status: up Speed: 10000 Mbps Duplex: full Link Failure Count: 0 Permanent HW addr: 9c:dc:71:45:eb:80 Aggregator ID: 2 Slave queue ID: 0 Slave Interface: p4p1 MII Status: up Speed: 10000 Mbps Duplex: full Link Failure Count: 0 Permanent HW addr: 9c:dc:71:4d:80:20 Aggregator ID: 2 Slave queue ID: 0 I have the above text outputs and I want to create a nested dictionary that looks like this: in the text above there could be more than two slave interface blocks bond0 : { 'MII Status:' : 'up', 'Aggregator ID:' : '2', 'Slave Interfaces' : { 'p1p1' : { 'MII Status' : 'up', 'Permanent HW addr' : '9c:dc:71:45:eb:80', 'MII Status' : up }, 'p4p1' : { ''MII Status' : 'up', 'Permanent HW addr' : '9c:dc:71:4d:80:20', 'MII Status' : up }, }, I began doing some coding as shown below, but still not getting there : #/usr/bin/python from future import print_function import pprint import os import re import subprocess class BndClass(dict): def __init__(self, Bnd=None): self['Name'] = Bnd self.uPdateInfo() super(BndClass, self).__init__() def uPdateInfo(self): OutBnd = subprocess.Popen(['cat', '/tmp/'\ + self['Name']],shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) for line in OutBnd.stdout: match = re.search(r'^Cur.*?:\s+(.*?)$', line) if match: self['act_int'] = match.group(1) match = re.search(r'^\s*?Aggregator ID:\s+(\d)$', line) if match: self['agid'] = match.group(1) match = re.search(r'^Slave\sInterface:\s(.*?)$', line) if match: self.setdefault('slvs', []).append(match.group(1)) if __name__ == …
has comment: http://stackoverflow.com/comment/91943513
favorite count: 0

http://stackoverflow.com/comment/91981161
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52519565
has text: There's centainly a `datetime` module in Python 3, maybe there's something wrong with your setup (wrong permissions?)
score: 0

http://stackoverflow.com/q/52544527
has answer: http://stackoverflow.com/a/52547061
has title: OverflowError: MongoDB can only handle up to 8-byte ints?
has comment: http://stackoverflow.com/comment/92029006
linked to: http://stackoverflow.com/q/17185220
downvote count: 0
has comment: http://stackoverflow.com/comment/92029037
has comment: http://stackoverflow.com/comment/92029089
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
score: 10
has comment: http://stackoverflow.com/comment/102416778
type: Question
tagged with: mongodb
answer count: 1
accepted answer: http://stackoverflow.com/a/52547061
favorite count: 0
has body: I have spent the last 12 hours scouring the web. I am completely lost, please help. I am trying to pull data from an API endpoint and put it into MongoDB. The data looks like this: {"_links": { "self": { "href": "https://us.api.battle.net/data/sc2/ladder/271302?namespace=prod" } }, "league": { "league_key": { "league_id": 5, "season_id": 37, "queue_id": 201, "team_type": 0 }, "key": { "href": "https://us.api.battle.net/data/sc2/league/37/201/0/5?namespace=prod" } }, "team": [ { "id": 6956151645604413000, "rating": 5321, "wins": 131, "losses": 64, "ties": 0, "points": 1601, "longest_win_streak": 15, "current_win_streak": 4, "current_rank": 1, "highest_rank": 10, "previous_rank": 1, "join_time_stamp": 1534903699, "last_played_time_stamp": 1537822019, "member": [ { "legacy_link": { "id": 9964871, "realm": 1, "name": "mTOR#378", "path": "/profile/9964871/1/mTOR" }, "played_race_count": [ { "race": "Zerg", "count": 195 } ], "character_link": { "id": 9964871, "battle_tag": "Hellghost#11903", "key": { "href": "https://us.api.battle.net/data/sc2/character/Hellghost-11903/9964871?namespace=prod" } } } ] }, { "id": 11611747760398664000, ..... .... Here's the code: for ladder_number in ladder_array: ladder_call_url = ladder_call+slash+str(ladder_number)+eng_locale+access_token url = str(ladder_call_url) response = requests.get(url) print('trying ladder number '+str(ladder_number)) print('calling :'+url) if response.status_code == 200: print('status: '+str(response)) mmr_db.ladders.insert_one(response.json()) I get an error: OverflowError: MongoDB can only handle up to 8-byte ints? Is this because the data I am trying to load is too large? Are the "ID" integers too large? Oh man, any help would be sincerely appreciated. _______ EDIT ____________ Edited to include the Traceback: Traceback (most recent call last): File "C:\scripts\mmr_from_ladders.py", line 96, in &lt;module&gt; mmr_db.ladders.insert_one(response.json(), bypass_document_validation=True) File "C:\Users\me\AppData\…
upvote count: 10
tagged with: python

http://stackoverflow.com/comment/91826266
type: QuestionComment
has text: Don't do that. You can't change your question, especially after you've already received an answer.
comment on: http://stackoverflow.com/q/52440960
score: 0
type: Comment

http://stackoverflow.com/a/52557672
has body: You need to understand how correctly asynchronous programming works in python. When you call apply_async you get Future object. The Queue implementation in python relies on a system pipe to transmit the data from one process to another and some semaphores to protect the read and write on this pipe. from multiprocessing import Pool, Queue, Event import os import time import multiprocessing def worker( Qin, Qout, event): print('worker') time.sleep(1) event.set() def manager(): processes = multiprocessing.cpu_count() m = multiprocessing.Manager() Qin = m.Queue() Qout = m.Queue() event = m.Event() pool = Pool(processes=processes) result = pool.apply_async(worker, (Qin, Qout, event)) result.get() pool.close() event.wait() return Qout if __name__ == '__main__': Qout = manager()
answers question: http://stackoverflow.com/q/52556941
score: 0
type: Answer

http://stackoverflow.com/a/52581151
has comment: http://stackoverflow.com/comment/92097521
score: 0
has body: Your question lacks clarity. You state: Lets assume that the person making the api did have proper error handling in place for to validate the arguments (in this case that integer_argument is an integer). Yeah that would be Django handling things.... Which is why you get the debug page \ Bad Request because it doesn't match. In your API you're defining endpoints which match that format - precisely. If a uri doesn't match then that's expected behavior you shouldn't be doing any wizardry here because that just doesn't make sense. If you want to use type annotations sure - mypy is useful and other devs may find it useful as well. Now for the next bit: Note: in this case I want every request to my_api/ to return a uniform response (error or otherwise). So.... add an endpoint which acts as a catch all to return that uniform response when the other path \ regular expression paths fail to find a match. I think you're overcomplicating this.
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52580825
accepted answer of: http://stackoverflow.com/q/52580825

http://stackoverflow.com/comment/91831748
comment on: http://stackoverflow.com/q/52443907
type: QuestionComment
has text: Can I add something like Markov decision process
score: 0
type: Comment

http://stackoverflow.com/comment/92016645
score: 0
type: Comment
has text: Same result, empty page
type: AnswerComment
comment on: http://stackoverflow.com/a/52534377

http://stackoverflow.com/q/52526545
upvote count: 4
type: AnsweredQuestion
has body: I have the following dataframe: date = ['2015-02-03 23:00:00','2015-02-03 23:30:00','2015-02-04 00:00:00','2015-02-04 00:30:00','2015-02-04 01:00:00','2015-02-04 01:30:00','2015-02-04 02:00:00','2015-02-04 02:30:00','2015-02-04 03:00:00','2015-02-04 03:30:00','2015-02-04 04:00:00','2015-02-04 04:30:00','2015-02-04 05:00:00','2015-02-04 05:30:00','2015-02-04 06:00:00','2015-02-04 06:30:00','2015-02-04 07:00:00','2015-02-04 07:30:00','2015-02-04 08:00:00','2015-02-04 08:30:00','2015-02-04 09:00:00','2015-02-04 09:30:00','2015-02-04 10:00:00','2015-02-04 10:30:00','2015-02-04 11:00:00','2015-02-04 11:30:00','2015-02-04 12:00:00','2015-02-04 12:30:00','2015-02-04 13:00:00','2015-02-04 13:30:00','2015-02-04 14:00:00','2015-02-04 14:30:00','2015-02-04 15:00:00','2015-02-04 15:30:00','2015-02-04 16:00:00','2015-02-04 16:30:00','2015-02-04 17:00:00','2015-02-04 17:30:00','2015-02-04 18:00:00','2015-02-04 18:30:00','2015-02-04 19:00:00','2015-02-04 19:30:00','2015-02-04 20:00:00','2015-02-04 20:30:00','2015-02-04 21:00:00','2015-02-04 21:30:00','2015-02-04 22:00:00','2015-02-04 22:30:00','2015-02-04 23:00:00','2015-02-04 23:30:00'] value = [33.24 , 31.71 , 34.39 , 34.49 , 34.67 , 34.46 , 34.59 , 34.83 , 35.78 , 33.03 , 35.49 , 33.79 , 36.12 , 37.09 , 39.54 , 41.19 , 45.99 , 50.23 , 46.72 , 47.47 , 48.46 , 48.38 , 48.40 , 48.13 , 38.35 , 38.19 , 38.12 , 38.05 , 38.06 , 37.83 , 37.49 , 37.41 , 41.84 , 42.26 , 44.09 , 48.85 , 50.07 , 50.94 , 51.09 , 50.60 , 47.39 , 45.57 , 45.03 , 44.98 , 41.32 , 40.37 , 41.12 , 39.33 , 35.38 , 33.44 ] df = pd.DataFrame({'value':value,'index':date}) df.index = pd.to_datetime(df['index'],format='%Y-%m-%d %H:%M') df.drop(['index'],axis=1,inplace=True) print(df) value index 2015-02-03 23:00:00 33.24 2015-02-03 23:30:00 31.71 2015-02-04 00:00:00 34.39 2015-02-04 00:30:00 34.49 2015-02-04 01:00:00 34.67 2015-02-04 01:30:00 34.46 I want to do the following operation efficiently: for each year, compute the percentage of occurences of values stricly un…
downvote count: 0
has title: how to bin efficiently a column and groupby in pandas?
has answer: http://stackoverflow.com/a/52527659
accepted answer: http://stackoverflow.com/a/52527659
type: Question
tagged with: binning
score: 4
tagged with: pandas-groupby
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52561549
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52562391
type: UnansweredQuestion
tagged with: python
has title: BlueZ AutoReconnect as device to PC
tagged with: pybluez
has comment: http://stackoverflow.com/comment/119623604
type: Question
upvote count: 4
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/119668401
score: 4
tagged with: bluez
tagged with: bluetooth
has body: I'm working on a HID bluetooth device with the code on the device in Python; at the moment it can connect to a PC by running: os.system("hciconfig hcio class 0x002560") os.system("hciconfig hcio name DataPaqWalk") Then we can use pybluez to connect the sockets and wait for a connection: print("Waiting for connections") self.scontrol=BluetoothSocket(L2CAP) self.sinterrupt=BluetoothSocket(L2CAP) self.scontrol.listen(1) # Limit of 1 connection self.sinterrupt.listen(1) self.ccontrol,cinfo = self.scontrol.accept() self.cinterrupt, cinfo = self.sinterrupt.accept() This works and we have a thread polling with hcitool con to detect the Windows PC (adapter) disconnecting where we dump the sockets and listen again. The hci is setup with no security so the PC connecting to it automatically pairs - this all works. However the issue comes when the device is powered off; the PC correctly detects that the device is gone and it remains in the paired state. What I want to do is to get the device to automatically connect to the PC it is paired with. I've obviously got the Mac address of the PC and I am trying to connect using: (P_CTRL is 17 and P_INTR is 19) self.ccontrol,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_CTRL)) self.controlClientMac = cinfo[0] self.controlClientPsm = cinfo[1] print ('control is ' + self.controlClientMac + " " + str(self.controlClientPsm)) self.cinterrupt,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_INTR)) self.interruptClientMac = cinfo[0] self.interruptClientPsm = cinfo[1] print ('interrupt is ' + self.interruptClientMac + " " + str(self.interruptClientPsm)) This basically tries to connect and gives me back: Traceback (most recent call last): File "server/btk_server.py", line 267, in &lt;module&gt; myservice = BTKbService(); File "server/btk_server.py", line 226, in __init__ self.device.listen(); File "server/btk_server.py", line 174, in listen self.ccontrol,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_CTRL)) Fi…
answer count: 1

http://stackoverflow.com/comment/91863232
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52460493
has text: In this case check if the attribute value is `callable()` (or use `inspect` module for further details) and only return function if it is.

http://stackoverflow.com/comment/91832314
type: Comment
has text: Is there another way to add username to the view. I tried changing the URL and also had to change the `def get_api_like_url(self):` in the models which is breaking a lot of code in my other pages. I tried changing my views to `def get(self, request, slug=None, username=None, format=None):` that is giving me `'Post' is not JSON serializable` error
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52444032

http://stackoverflow.com/comment/91910698
has text: Off-by one error -- it should be `101 * 101` (which it is), since you have an edge in column 100 and row 100. Imagine in small scale (`[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]`) that's 4 lines, covering 4 pixels (and nothing to fill).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52484507
score: 1

http://stackoverflow.com/comment/91913709
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180687/discussion-between-debbie-and-roganjosh).
comment on: http://stackoverflow.com/q/52485276
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52477822
upvote count: 4
has comment: http://stackoverflow.com/comment/91896918
has comment: http://stackoverflow.com/comment/91897021
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91896806
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91897102
has comment: http://stackoverflow.com/comment/91896712
has comment: http://stackoverflow.com/comment/91896883
has comment: http://stackoverflow.com/comment/91896798
answer count: 2
has comment: http://stackoverflow.com/comment/112651721
has title: How to convert an integer into string without using in-built function?
has comment: http://stackoverflow.com/comment/91896862
downvote count: 1
has comment: http://stackoverflow.com/comment/91896977
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/63705054
has answer: http://stackoverflow.com/a/52478037
accepted answer: http://stackoverflow.com/a/52478037
has answer: http://stackoverflow.com/a/63705054
has body: I wanna ask how to convert an integer into string without using in-built function. This is the original question: Write a function string(ls) that returns a string representation of the list ls. Note: do not use the built-in str() method for this task. We are attempting to emulate its behavior. s = string(['a','b','c']) # '['a','b','c']' s = string([1,2,3]) # '[1, 2, 3]' s = string([True]) # '[True]' s = string([]) # '[]' Restrictions: Don't just return str(ls)! Don't use the str.join method, don't use slicing. Here is my code: def string(ls): if len(ls)==0: mess="'[]'" return mess elif isinstance(ls[0],str): i=0 mess="'[" while True: if i==len(ls)-1: elem="'"+ls[i]+"'" mess=mess+elem break else: elem="'"+ls[i]+"', " mess=mess+elem i=i+1 mess=mess+"]'" return mess else: i=0 mess="'[" while True: if i==len(ls)-1: elem=str(ls[i])+"]'" mess=mess+elem break else: elem=str(ls[i])+', ' mess=mess+elem i=i+1 return mess
has comment: http://stackoverflow.com/comment/91897059
tagged with: python

http://stackoverflow.com/a/52577075
type: Answer
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/52576914
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52576914
downvote count: 0
has body: Since it detects keypress only, use flags. I think something like this can do it: 1. Make a bool variable to detect a single key press 2. If key is pressed, the bool will be set to true 3. If bool is true and not key.is_pressed: do your thing 4. Set bool to false after operation For example, in code, that will be like this: keypress = False key = 'space' while True: if keypress and not keyboard.is_pressed(key): '''DO YOUR THING''' #beak out of while loop? keypress = False break elif keyboard.is_pressed(key) and not keypress: keypress = True Dont know if this is how you'll do it, but I guess you can get my drift from this. Good luck!

http://stackoverflow.com/a/52508595
downvote count: 0
has body: You can use a dictionary comprehension: demo1={'1':['a','b','c'],'2':['x','y']} demo2={1:['b','c','e'],2:['x','z','w']} coef={'1':5,'2':6} result = {i:sum(c in demo1[i] and c in demo2[int(i)] for c in set(demo1[i]+demo2[int(i)]))/coef[i] for i in demo1} Output: {'1': 0.4, '2': 0.16666666666666666}
answers question: http://stackoverflow.com/q/52508552
type: Answer
has comment: http://stackoverflow.com/comment/91957494
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91957478
accepted answer of: http://stackoverflow.com/q/52508552
type: AcceptedAnswer

http://stackoverflow.com/comment/91840510
has text: Welcome to the site, and thank you for contributing! That said, do note the section *Answer Well-Asked Questions* in [How to Answer](https://stackoverflow.com/help/how-to-answer), documenting that questions which do not meet the topic guidelines at https://stackoverflow.com/help/on-topic (which includes a requirement that questions be about a *specific problem*) are best repaired, migrated (in this case to our sister site [codereview.se]) or closed rather than answered.
score: 2
comment on: http://stackoverflow.com/a/52448546
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91823414
has text: @Deadpool it always gives me this Error: Executing consumer group command failed due to The consumer group command timed out while waiting for group to initialize
comment on: http://stackoverflow.com/q/52435151
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91991497
type: QuestionComment
type: Comment
score: 2
has text: Well the error is clear: it contains comma separators for the thousands, but Python's `int(..)` function can not handle that. So you need to remove these.
comment on: http://stackoverflow.com/q/52525841

http://stackoverflow.com/comment/91981188
has text: I've recheckd code. It's same now. (difference was in `print(wololo)`). Interesting fact: when I run script via pycharm (on Windows) I don't see multiple windows issue, but logs still there. When I build it using cz_Freeze - issue is reproduces on Windows.
comment on: http://stackoverflow.com/q/52519568
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/132492443
type: QuestionComment
comment on: http://stackoverflow.com/q/52580589
has text: Thanks @Arihant your suggestion for printing `keys()` helped in debugging me issue.
score: 0
type: Comment

http://stackoverflow.com/comment/92101026
has text: Thanks for the reply! Is this the practical way to do relative loading data in a pypi package?
comment on: http://stackoverflow.com/a/52582999
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91927137
score: 1
comment on: http://stackoverflow.com/q/52493104
type: Comment
has text: Read about [datetime.datetime.timestamp](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp)
type: QuestionComment

http://stackoverflow.com/a/52437058
accepted answer of: http://stackoverflow.com/q/52437024
answers question: http://stackoverflow.com/q/52437024
score: 3
has body: I think list comprehension is not necessary, better and faster is use vectorized solution by filter by boolean indexing with isin and then convert to lists: mask = extract['NBN Location Id'].isin(closed['SP Order Location ID']) cheat_data = extract.loc[mask, ['latitude', 'longitude']].values.tolist() Sample: closed = pd.DataFrame({'SP Order Location ID':list('ace')}) print (closed) SP Order Location ID 0 a 1 c 2 e extract = pd.DataFrame({'NBN Location Id':list('abcde'), 'latitude':['lat1','lat2','lat3','lat4','lat4'], 'longitude':['long1','long2','long3','long4','long4']}) print (extract) NBN Location Id latitude longitude 0 a lat1 long1 1 b lat2 long2 2 c lat3 long3 3 d lat4 long4 4 e lat4 long4 mask = extract['NBN Location Id'].isin(closed['SP Order Location ID']) cheat_data = extract.loc[mask, ['latitude', 'longitude']].values.tolist() print (cheat_data) [['lat1', 'long1'], ['lat3', 'long3'], ['lat4', 'long4']] Your solution failed, because in in pandas check index values, not values of Series, so need convert to list: cheat_data = [[row['latitude'],row['longitude']] for index, row in extract.iterrows() if row['NBN Location Id'] in closed['SP Order Location ID'].tolist()] print (cheat_data) [['lat1', 'long1'], ['lat3', 'long3'], ['lat4', 'long4']] #changed index values closed = pd.DataFrame({'SP Order Location ID':list('ace')}, index=list('dbw')) print (closed) SP Order Location ID d a b c w e cheat_data = [[row['latitude'],row['longitude']] for index, row in extract.iterrows() if row['NBN Location Id'] in closed['SP Order Location ID']] print (cheat_data) [['lat2', 'long2'], ['lat4', 'long4']]
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/q/52446943
has comment: http://stackoverflow.com/comment/91844375
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73014138
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91839271
has comment: http://stackoverflow.com/comment/91836993
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/91843476
answer count: 1
downvote count: 0
has title: Pandas: plot Series on a new figure by default
has body: Is there a way to force the .plot method of a pandas Series to generate a new figure, instead of trying to plot on the currently open figure? I currently create a new figure using plt.figure() or using plt.subplots and passing the axis, but for quick plots from the interactive console it would be great to simply use the .plot method without extra lines of code. I wonder if there are configs in pandas that can be changed to achieve this.
score: 15
has comment: http://stackoverflow.com/comment/138670806
has comment: http://stackoverflow.com/comment/91836909
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/91944360
type: AnswerComment
comment on: http://stackoverflow.com/a/52484974
type: Comment
score: 0
has text: @gaoquanliang you can't do this. That means "I want to change the graph for each iteration" in that case model can't learn anything. There is no option like that in any framework. AFAIK

http://stackoverflow.com/q/52499337
favorite count: 0
has comment: http://stackoverflow.com/comment/91939355
tagged with: pandas
tagged with: python
has title: Python Pivot for multiple entries
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52499519
accepted answer: http://stackoverflow.com/a/52499519
tagged with: pivot
upvote count: 3
has body: I have a repeating list of Employe Name-Skill-Value pairs sourced from pivoted excel data. I loaded the data into a data frame, Staff, that looks like so: Name Skill Attribute Value Bob S Certification ACA Bob S Certification GSA Bob S Degree Comp Sci Kate Certification BCA I now want to pivot the data back, in python, so that it’s Name Certification Degree Bob S ACA Comp Sci Bob S GSA Lit Kate BCA None When I try pivoting in python with: Staff=Staff.drop_duplicates([‘Name’,’Skill Attribute’]) Staff=Staff.pivot(‘Name’, ‘Skill Attribute’, ‘Value) I lose value data. For example, Bob S has two certifications, but only one shows: Name Certification Degree Bob S ACA Comp Sci Kate BCA None Attempting to use the pivot function without the preceding drop_duplicates line gives a “ValueError: Index contains duplicate entries, cannot reshape” How can I pivot so that all value data is kept, and multiple skills attribute-value entries per employee name are allowed?
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91939443
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/a/78441416
type: Answer
answers question: http://stackoverflow.com/q/52488977
has body: Had the same issue, the solution from https://stackoverflow.com/a/56053013/13634735 worked for me urlpatterns = [ path('question', cebula_views.QuestionView.as_view(), name='userpage-question') ]
score: 0

http://stackoverflow.com/q/52552910
tagged with: keras
has answer: http://stackoverflow.com/a/59637953
favorite count: 0
tagged with: cross-entropy
has answer: http://stackoverflow.com/a/52555557
possible better answer: http://stackoverflow.com/a/59637953
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52555557
type: AnsweredQuestion
score: 1
has body: I want to write a function with two arguments, A and B, tensors of the same shape (for example, 13x13, or some other shape), and that returns a number that represents the summation of all losses when applied binary cross-entropy componentwise. So, for A[i, j] and B[i, j] we find the binary cross-entropy loss, and then sum over all i and j. How to implement that in Keras and Tensorflow?
tagged with: loss-function
tagged with: tensorflow
type: Question
answer count: 2
has title: How do I apply the binary cross-entropy element-wise and then sum all these losses in Keras?
downvote count: 0

http://stackoverflow.com/q/52516109
has comment: http://stackoverflow.com/comment/91973606
tagged with: cron
linked to: http://stackoverflow.com/q/876239
tagged with: python
has comment: http://stackoverflow.com/comment/91980383
tagged with: shell
has title: Cronjob on Ubuntu Mate for Raspberry stops right after execution
has comment: http://stackoverflow.com/comment/91975097
tagged with: python-3.x
score: 0
has answer: http://stackoverflow.com/a/52521008
linked to: http://stackoverflow.com/q/2388087
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17518073
has comment: http://stackoverflow.com/comment/91981129
has comment: http://stackoverflow.com/comment/91978835
has body: I use a RaspberryPi 3 with UbuntuMate 16.04. On it, I want to start a little Python (3.5) program every midnight. For that I call a little shell script, so that I can change into the wanted directory comfortably. crontab: 5 0 * * * /path/to/script/start.sh start.sh (yes, it's executable): #!/bin/bash cd /path/to/wanted/workingDir/ python3.5 ControllerQueue.py #also tried: python3.5 ControllerQueue.py &amp; Now if I execute the programm or script from the terminal, everything runs fine. But if I use the crontab it starts the script and stops right after. I also tried running the programm directly but get the same outcome. The paths are correct as I copied the workingDir path from the crontab-file and started it via the terminal. Is there something I overlook?
accepted answer: http://stackoverflow.com/a/52521008
tagged with: cron-task
answer count: 1
has comment: http://stackoverflow.com/comment/91974222

http://stackoverflow.com/q/52574552
has title: django compare time fields
type: AnsweredQuestion
downvote count: 1
possible better answer: http://stackoverflow.com/a/52574682
type: Question
has answer: http://stackoverflow.com/a/52574682
has answer: http://stackoverflow.com/a/52574639
tagged with: comparison
score: 0
answer count: 2
favorite count: 0
accepted answer: http://stackoverflow.com/a/52574639
has body: I am trying to compare two date fields for the time. Here is what I am doing. My output when I print. I can see it is the same, but comparison result is False! Any pointers to what I am doing wrong? for appt in appointment_detail: print(appt['start_time']) print(slot_time) print(slot_time == appt['start_time']) Result: 2018-09-22 11:00:00+00:00 2018-09-22 11:00:00 False Thanks
tagged with: time
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/a/52559542
downvote count: 0
answers question: http://stackoverflow.com/q/52559448
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52559448
type: AcceptedAnswer
has body: sorted() returns a newly sorted list while leaving self._queue untouched. In order to make your code work the way you expected you should call the method .sort() class SortingQueue: _queue = [] @property def queue(self): self._queue.sort(key=attrgetter("votes"), reverse=True) return self._queue The other way to fix it using sorted() is this: class SortingQueue: _queue = [] @property def queue(self): self._queue = sorted(self._queue, key=attrgetter("votes"), reverse=True) return self._queue edit: In my haste I overlooked the fact this was a @property. I would normally suggest not letting a property alter 'hidden attribute _queue'. In which case I would do something like this: class SortingQueue: _queue = [] @property def queue(self): return sorted(self._queue, key=attrgetter("votes"), reverse=True)

http://stackoverflow.com/comment/91956842
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52507911
type: AnswerComment
has text: It doesn't work if I use the area from my last comment: amax: array([[1, 5]])

http://stackoverflow.com/comment/91957109
has text: Looks like at the end of the day, the documentation provided was incorrect and ObjectIdentifier should have been `ObjectIdentity('1.3.6.1.4.1.2682.1.2.3.4.0')`. Debugging helped though. Thanks.
comment on: http://stackoverflow.com/a/52491604
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52447348
tagged with: user-defined-functions
has answer: http://stackoverflow.com/a/59343218
tagged with: pyspark
has answer: http://stackoverflow.com/a/73733962
has title: Return an array using pandas_udf
tagged with: apache-spark
answer count: 3
downvote count: 0
score: 7
favorite count: 0
has answer: http://stackoverflow.com/a/52455751
type: UnansweredQuestion
has body: I'm trying to make a pandas UDF that takes in two columns with integer values and based on the difference between these values return an array of decimals whose length is equal to the aforementioned difference. Here's my attempt so far, I've been messing around with a lot of different ways trying to get this to work but here's the general idea from pyspark.sql.functions import pandas_udf, PandasUDFType from pyspark.sql.types import * import pandas as pd @pandas_udf(ArrayType(DecimalType()), PandasUDFType.SCALAR) def zero_pad(x, y): buffer = [] for i in range(0, (x - y)): buffer.append(0.0) return buffer Here's how I use it: df = df.withColumn("zero_list", zero_pad(df.x, df.y)) The end result being df with a new column called "zero_list" being an ArrayType(DecimalType()) column that looks like [0.0, 0.0, 0.0, ...] the length of which is (df.x - df.y). The error message is so general it's almost not worth posting, simply "Job aborted due to stage failure" and it only traces back to the part of my code where I do a df.show(): Py4JJavaError Traceback (most recent call last) <command-103561> in <module>() ---> 33 df.orderBy("z").show(n=1000) /databricks/spark/python/pyspark/sql/dataframe.py in show(self, n, truncate, vertical) 350 """ 351 if isinstance(truncate, bool) and truncate: --> 352 print(self._jdf.showString(n, 20, vertical)) 353 else: 354 print(self._jdf.showString(n, int(truncate), vertical)) /databricks/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py in __call__(self, *args) 1255 answer = self.gateway_client.send_command(command) 1256 return_value = get_return_value( -> 1257 answer, self.gateway_client, self.target_id, self.name) 1258 1259 for temp_arg in temp_args: How to create a pandas_udf that would return an array of variable length? I'm doing all of this using Databricks with Spark 2.3.1.
tagged with: python
tagged with: databricks
upvote count: 7
type: Question

http://stackoverflow.com/a/54269048
type: Answer
answers question: http://stackoverflow.com/q/52554073
has body: You can try to get your result using filters (see filters4Doxygen) to act as pre-processor. You must make a custom filter for pyton (use as sample BATdoxFilter.bat(sh)): The filter 'exclude' will be defined in bin/rgx/excpt.RGX, using the regular expression: ## rule 1, /*skip*/.../*endskip*/ is destroid regex1=(?mis)/\\*skip(.)*?endskip\\*/ replacement1= note: I not tested the regex, so maybe some tuning can be required: see https://github.com/msillano/regexfilter/blob/master/README.pdf I hope that can help. Best regards, m.s.
score: 0

http://stackoverflow.com/q/52466724
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91875544
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91875461
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52467091
type: Question
accepted answer: http://stackoverflow.com/a/52467091
has title: Load Test for keras based GPU Machine Learning
score: 0
answer count: 1
has body: I am looking for a simple (self containing) keras based example that causes my GPU to run a decent long time with maximum usage. With this I want to test the thermal behaviour of my machine.
tagged with: keras

http://stackoverflow.com/q/52490621
type: Question
has comment: http://stackoverflow.com/comment/91922244
downvote count: 0
answer count: 1
has body: I have been trying to create a bunch of similar methods using a YAML configuration file. However, I have been unable to find something online or figure it out. example.yml attributes: - a - b - c example class import yaml class Test: def __init__(self): with open('example.yml', 'rb') as f: attrib_list = yaml.load(f) _list = [] for name in attrib_list: _list.append(self.__setattr__('_' + name, None)) # create similar methods in a loop for name, _ in zip(attrib_list, _list): @property def name(self): # I know name is a string so cannot be this way but how if this can be done? return _ @name.setter def __set + _(self, v): # __set + '_' + name as method name pass @name.getter def __get + _(self): # __get + '_' + name as method name pass Is there efficient way to create many similar methods this way by looping through a configuration file? Or is there a better way to handle something of this nature? Thanks.
tagged with: class
accepted answer: http://stackoverflow.com/a/52491895
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91922321
upvote count: 1
has title: Python: Using a YAML to auto create class methods
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: methods
has answer: http://stackoverflow.com/a/52491895

http://stackoverflow.com/q/52461419
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91865103
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/91865009
upvote count: 3
has comment: http://stackoverflow.com/comment/91865701
has comment: http://stackoverflow.com/comment/91866308
has comment: http://stackoverflow.com/comment/91865285
has body: hash(str), how much time does this operation take? O(n), where n is the length of the string? (I know hashes are cached.) To be more specific, does it compute the hash on call to the hash(str), or it compute when you create the string? Since it is immutable, hash should remain the same. Please provide reference for answer.
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91865330
has comment: http://stackoverflow.com/comment/91865326
has comment: http://stackoverflow.com/comment/91866107
has comment: http://stackoverflow.com/comment/91865563
has comment: http://stackoverflow.com/comment/91865150
has comment: http://stackoverflow.com/comment/91865084
has title: Time complexity of hash(str) in python
has comment: http://stackoverflow.com/comment/91865115
tagged with: string
has comment: http://stackoverflow.com/comment/91865018
favorite count: 0
has comment: http://stackoverflow.com/comment/91865205
has comment: http://stackoverflow.com/comment/91865415
tagged with: python-3.x
tagged with: hash
has comment: http://stackoverflow.com/comment/91864973
has comment: http://stackoverflow.com/comment/91864966

http://stackoverflow.com/a/52478850
score: 1
upvote count: 2
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52476244
has body: I'm making some assumption on what you want to accomplish here. Even if this is not exactly what you want, it might still push you the right direction: You got two different sub directories, A and B. These contain scripts of identical names a.py and b.py. Based on some condition, your script should call either A/a.py or A/a.py and then maybe B/b.py or B/b.py. I would set up A and B as actual python modules, that is, create a __init__.py file in both folders. Then have a master-script which somehow determines which module to use.. # root_folder/master.py import sys import A import B master_script_name = sys.argv[0] print("I'm the master script : " + str(master_script_name)) def choose_module_A_or_B(arg): if arg == "A": print(" You chose module A !") return A return B module = choose_module_A_or_B("A") module.b.print_locations() Then, # root_folder/A/__init__.py from A import b and, # root_folder/A/b.py import os import sys # how to obtain paths and script name: folder = os.path.dirname(os.path.realpath(__file__)) script = __file__ parent = os.path.abspath(os.path.join(folder, os.pardir)) def print_locations(): print(" --&gt; script : " + str(script)) print(" --&gt; folder : " + str(folder)) print(" --&gt; parent : " + str(parent)) Similarily .. # root_folder/B/__init__.py from B import b and, # root_folder/B/b.py import os import sys # how to obtain paths and script name: folder = os.path.dirname(os.path.realpath(__file__)) script = __file__ parent = os.path.abspath(os.path.join(folder, os.pardir)) def print_locations(): print(" --&gt; script : " + str(script)) print(" --&gt; folder : " + str(folder)) print(" --&gt; parent : " + str(parent)) OUTPUT: $ python master.py I'm the master script : master.py You chose module A ! --&gt; script : A\b.py --&gt; folder : C:\dev\ScriptTesting\py\script_by_name\A --&gt; parent : C:\dev\ScriptTesting\py\script_by_name

http://stackoverflow.com/comment/112193076
score: 0
type: Comment
has text: I want to make sure I understand correctly: For most ML tasks I will need to split the feature tensors into "InputA_1"..."InputA_256"..."InputB_1"..."InputB_256"..."Label_1"..."Label_1000". So, I need to split my 3 N-dimensional NumPy arrays into thousand individual column arrays. Is that correct?
comment on: http://stackoverflow.com/a/52563718
type: AnswerComment

http://stackoverflow.com/comment/92088499
comment on: http://stackoverflow.com/a/52576253
has text: I also need to use append statement as there are already few rows in the list 1
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52536678
has body: There are Catalan(nmatrices-1) combinations, and we can use simple balanced parentheses algorithm to generate pre-combinations. Here is code to get both parentheses (for comparison) and matrix pre-combinations. But I have not found concise method to set closing parentheses yet (cx argument is my attempt to count multiplications and deduce number of closing parens in given point). Perhaps somebody might see simple formula/law to get the final result. def genparens(s, maxlen, l, r): if l + r == maxlen * 2: print(s) return if l &lt; maxlen: genparens(s + '(', maxlen, l + 1, r) if r &lt; l: genparens(s + ')', maxlen, l, r + 1) alpha = "ABCDEFGHIJK" def genmatparens(s, n, l, r, ci, cx): if l + r == n * 2: s = s + alpha[ci] # + ")" * cx print(s) return if l &lt; n: genmatparens(s + '(', n, l + 1, r, ci, cx + 1) if r &lt; l: s += alpha[ci] #s += ")" * cx s += "x" genmatparens(s, n, l, r + 1, ci + 1, 1) genparens("", 3, 0, 0) print() genmatparens("", 3, 0, 0, 0, 0) ((())) (()()) (())() ()(()) ()()() current should be (((AxBxCxD (((AxB)xC)xD) ((Ax(BxCxD ((Ax(BxC))xD) ((AxBx(CxD ((AxB)x(CxD)) (Ax((BxCxD (Ax((BxC)xD)) (Ax(Bx(CxD (Ax(Bx(CxD)))
score: 3
answers question: http://stackoverflow.com/q/52529409
upvote count: 3
downvote count: 0
type: Answer

http://stackoverflow.com/q/52586258
has answer: http://stackoverflow.com/a/52587880
type: Question
has body: import json dict = {'username': u'Toto', 'staffTitle': u'Mr', 'staffName': u'Toto', 'company': &lt;Company: Test1&gt;, 'qualifications': [{u'dateObtained': u'2017-11-22', u'qualificationId': 1048,} convert_to_string = json.dumps (dict) sa_ = sanitize_data(conver_to_string) back_to_dict = json.loads(sa_) def sanitize_data(dirty_data): clean_data = re.sub('(&lt;0x\w*&gt;)|\s',"", dirty_data) return clean_data So what i'm trying to achieve something.To convert as dict into a string using json.dumps then use my made function to sanitize and remove non_ascii characters and convert it back to a dict and save it. Because ,there is an in memory instance ('company': ) part of the dict. I'm having an error, the dumps does not work. How can i sort out this and being able to convert this dict into string and process the data? Any ideas?
has title: how to convert a dictionnary which contains an in memory model instance into a string using json.dumps
has comment: http://stackoverflow.com/comment/92107740
answer count: 1
has comment: http://stackoverflow.com/comment/92108014
score: 0
has comment: http://stackoverflow.com/comment/92107588
tagged with: python
has comment: http://stackoverflow.com/comment/92107413
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/a/52461822
upvote count: 1
answers question: http://stackoverflow.com/q/52461661
has comment: http://stackoverflow.com/comment/91865822
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91869775
has comment: http://stackoverflow.com/comment/91865869
type: Answer
has body: Have you tried converting to Unicode implicitly? For example: a = u"[狂おしく咲いた凄惨な骸は奏で、愛おしく裂いた少女は聖餐の詞を謳う。 #10] 謳" This makes the string Unicode supported and might fix your issue
has comment: http://stackoverflow.com/comment/91865810

http://stackoverflow.com/q/52579293
has comment: http://stackoverflow.com/comment/92148306
has comment: http://stackoverflow.com/comment/92148722
possible better answer: http://stackoverflow.com/a/67764178
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/52607858
favorite count: 0
has comment: http://stackoverflow.com/comment/92148221
has comment: http://stackoverflow.com/comment/92148803
has comment: http://stackoverflow.com/comment/92148977
has comment: http://stackoverflow.com/comment/92148609
has comment: http://stackoverflow.com/comment/92148689
has comment: http://stackoverflow.com/comment/92149226
tagged with: python
has answer: http://stackoverflow.com/a/52607858
score: 2
linked to: http://stackoverflow.com/q/31948879
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/67764178
tagged with: machine-learning
has body: I have a dataset of 3500 observations x 70 features which is my training set and I also have a dataset of 600 observations x 70 features which is my validation set. The target is to classify observations correctly either as 0 or 1. I use the Xgboost and I aim at the highest possible precision at classification threshold = 0.5. I am conducting a grid search: import numpy as np import pandas as pd import xgboost # Import datasets from edge node data_train = pd.read_csv('data.csv') data_valid = pd.read_csv('data_valid.csv') # Specify 'data_test' as validation set for the Grid Search below from sklearn.model_selection import PredefinedSplit X, y, train_valid_indices = train_valid_merge(data_train, data_valid) train_valid_merge_indices = PredefinedSplit(test_fold=train_valid_indices) # Define my own scoring function to see # if it is called for both the training and the validation sets from sklearn.metrics import make_scorer custom_scorer = make_scorer(score_func=my_precision, greater_is_better=True, needs_proba=False) # Instantiate xgboost from xgboost.sklearn import XGBClassifier classifier = XGBClassifier(random_state=0) # Small parameters' grid ONLY FOR START # I plan to use way bigger parameters' grids parameters = {'n_estimators': [150, 175, 200]} # Execute grid search and retrieve the best classifier from sklearn.model_selection import GridSearchCV classifiers_grid = GridSearchCV(estimator=classifier, param_grid=parameters, scoring=custom_scorer, cv=train_valid_merge_indices, refit=True, n_jobs=-1) classifiers_grid.fit(X, y) ............................................................................ train_valid_merge - Specify my own validation set: I want to do the training of every model with my training set (data_train) and the hyperparameter tuning with a distinct/separate validation set of mine (data_valid). For this reason I define a function called train_valid_merge which concatenates my training and my validation set so that they can be fed to the GridSea…
type: Question
has title: GridSeachCV with separate training & validation sets erroneously takes also into account the training results for finally choosing the best model
has comment: http://stackoverflow.com/comment/92147995
tagged with: cross-validation
tagged with: grid-search
answer count: 2

http://stackoverflow.com/comment/91972420
comment on: http://stackoverflow.com/a/52514562
type: Comment
has text: Your data is many-to-one-to-many: one name can have several ids and several fuzzy matches. And you want to connect the attributes on both *many* sides together. That implies 3 loops and two sets of lists. That may be more than you want, but I can't see how it could logically be reduced.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52624802
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52583912
has body: This is possibly an issue with the Maya API package itself. Recent versions of Maya packages are compiled with Visual Studio 2015, so the DLLs might be incompatible with your Python environment due to compiler differences. I would also make sure your environment is set up correctly. Instead of copying over files, I would recommend to set the corresponding environment variables instead. Autodesk has a short guide on how to do this for every OS. For Maya 2018: http://help.autodesk.com/view/MAYAUL/2018/ENU/?guid=GUID-83799297-C629-48A8-BCE4-061D3F275215

http://stackoverflow.com/a/63940760
has body: On Linux and macOS this can be done using nctoolkit (https://nctoolkit.readthedocs.io/en/latest/). If you want an annual anomaly, you can do the following: import nctoolkit as nc data = nc.open_data("./interim_t2m_19792017.nc") data.annual_anomaly(baseline = [1997, 2017]) and for monthly anomalies: import nctoolkit as nc data = nc.open_data("./interim_t2m_19792017.nc") data.monthly_anomaly(baseline = [1997, 2017]) The package does not have seasonal anomalies, but I will add that in a future release. Under the hood, nctoolkit uses CDO so the system commands will be similar to those mentioned by Adrian Tompkins.
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52462472

http://stackoverflow.com/comment/92091700
has text: `url="https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&allThreadsRelatedToChannelId=UCBqUbOUyAsTB7Xc7xQAHWZA&maxResults=100&pageToken=QURTSl9pMmtEczg4MHVORVFQMXB5RVg2Q1Qxd1BLak9zQ1JjNDBpUWJfZ2NhdWV5R3pId0ZZbkFVcXhGSTdUc3d6bERrRk9nOU1vZnBTZGl5VV9kWm8wdjVfUmZGeWNsWTBnMy16My03ZXZfcWdKcWlRbmRJRG5lQUdLQlBjUXJPYTA%3D&key=AIzaSyCNveCCr3exzqIZDUHhqgFVF3ujuy5plgA"; `
score: 0
comment on: http://stackoverflow.com/a/52578116
type: AnswerComment
type: Comment

recursion
type: Tag
tags question: http://stackoverflow.com/q/52512150
tags question: http://stackoverflow.com/q/52498410
tags question: http://stackoverflow.com/q/52472273
tags question: http://stackoverflow.com/q/52574197
tags question: http://stackoverflow.com/q/52521921
tags question: http://stackoverflow.com/q/52528449
tags question: http://stackoverflow.com/q/52449995
tags question: http://stackoverflow.com/q/52568678
tags question: http://stackoverflow.com/q/52477358
tag name: recursion
tags question: http://stackoverflow.com/q/52547085
tags question: http://stackoverflow.com/q/52566533
tags question: http://stackoverflow.com/q/52563040
tags question: http://stackoverflow.com/q/52482678
tags question: http://stackoverflow.com/q/52435547
tags question: http://stackoverflow.com/q/52572613
tags question: http://stackoverflow.com/q/52527544
tags question: http://stackoverflow.com/q/52432988
tags question: http://stackoverflow.com/q/52431995
tags question: http://stackoverflow.com/q/52452978
tags question: http://stackoverflow.com/q/52497333
tags question: http://stackoverflow.com/q/52461272
tags question: http://stackoverflow.com/q/52557905
tags question: http://stackoverflow.com/q/52533016
tags question: http://stackoverflow.com/q/52578602
tags question: http://stackoverflow.com/q/52491816
tags question: http://stackoverflow.com/q/52579218
tags question: http://stackoverflow.com/q/52576825
tags question: http://stackoverflow.com/q/52438275
tags question: http://stackoverflow.com/q/52554857
tags question: http://stackoverflow.com/q/52523149

http://stackoverflow.com/a/53436229
type: Answer
answers question: http://stackoverflow.com/q/52456874
score: 10
upvote count: 11
has comment: http://stackoverflow.com/comment/121327536
downvote count: 1
has body: You can use or (|) operator for this , Refer this link for it pandas: multiple conditions while indexing data frame - unexpected behavior i.e dropping rows where both conditions are met df = df.loc[~((df['col_1']==1) | (df['col_2']==0))]

http://stackoverflow.com/comment/91973142
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52494011
has text: @Sanju Yeah, you are right. I updated the device firmware and now I can get files. It seems to be working alright. Thank you! However I had to do some digging in the code because I could not readily find any examples on how to form the requests and send them (e.g. that I needed to build a FileRecord instance). If you care to post an answer with a (full) simple example, I'll accept it.
score: 0

http://stackoverflow.com/q/52544043
score: 1
has answer: http://stackoverflow.com/a/52545772
accepted answer: http://stackoverflow.com/a/52545772
type: Question
tagged with: date
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/92030021
answer count: 1
favorite count: 0
tagged with: python
tagged with: dictionary
has body: I have the following pandas data frame: Shortcut_Dimension_4_Code Stage_Code 10225003 2 8225003 1 8225004 3 8225005 4 It is part of a much larger dataset that I need to be able to filter by month and year. I need to pull the fiscal year from the first two digits for values larger than 9999999 in the Shortcut_Dimension_4_Code column, and the first digit for values less than or equal to 9999999. That value needs to be added to "20" to produce a year i.e. "20" + "8" = 2008 | "20" + "10" = 2010. That year "2008, 2010" needs to be combined with the stage code value (1-12) to produce a month/year, i.e. 02/2010. The date 02/2010 then needs to converted from fiscal year date to calendar year date, i.e. Fiscal Year Date : 02/2010 = Calendar Year date: 08/2009. The resulting date needs to be presented in a new column. The resulting df would end up looking like this: Shortcut_Dimension_4_Code Stage_Code Date 10225003 2 08/2009 8225003 1 07/2007 8225004 3 09/2007 8225005 4 10/2007 I am new to pandas and python and could use some help. I am beginning with this: Shortcut_Dimension_4_Code Stage_Code CY_Month Fiscal_Year 0 10225003 2 8.0 10 1 8225003 1 7.0 82 2 8225003 1 7.0 82 3 8225003 1 7.0 82 4 8225003 1 7.0 82 I used .map and .str methods to produce this df, but have not been able to figure out how to get the FY's right, for fy 2008-2009.
type: AnsweredQuestion
has title: Slice, combine, and map fiscal year dates to calendar year dates to new column
downvote count: 0

http://stackoverflow.com/q/52462599
type: Question
tagged with: debugging
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/61840767
has answer: http://stackoverflow.com/a/75154592
linked to: http://stackoverflow.com/q/68709411
has answer: http://stackoverflow.com/a/72676036
has answer: http://stackoverflow.com/a/76587262
has answer: http://stackoverflow.com/a/57881778
has answer: http://stackoverflow.com/a/52825668
has answer: http://stackoverflow.com/a/53916133
has answer: http://stackoverflow.com/a/71570475
upvote count: 68
has title: Visual Studio Code with Python: Timeout waiting for debugger connection
linked to: http://stackoverflow.com/q/42729130
answer count: 18
favorite count: 0
has answer: http://stackoverflow.com/a/76576983
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52738297
linked to: http://stackoverflow.com/q/44435697
tagged with: python
has answer: http://stackoverflow.com/a/78561807
has answer: http://stackoverflow.com/a/71013689
has answer: http://stackoverflow.com/a/77642618
has answer: http://stackoverflow.com/a/52781131
has answer: http://stackoverflow.com/a/67098578
has answer: http://stackoverflow.com/a/58003909
score: 68
has answer: http://stackoverflow.com/a/52933829
downvote count: 0
has answer: http://stackoverflow.com/a/79533790
has body: I'm running the Visual Studio Code tutorial with Python and am unable to connect to the debugger. Usually I use Anaconda with Jupyter, so I'm connecting Visual Studio Code to Python in my activated 3.6 virtual environment. I tried pip installing ptvsd in my virtual environment, but that did not make a difference in what I am seeing. My launch.json (I've since added a comma to remove the red underline; that is not the issue):
has comment: http://stackoverflow.com/comment/92027566
linked to: http://stackoverflow.com/q/73993577

http://stackoverflow.com/comment/91883662
has text: ED: It's possible that the strace-not-finishing-writing might be due to "tee" - will try re-running it without tee.
score: 0
comment on: http://stackoverflow.com/q/52470567
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52695355
score: 1
type: Answer
has body: this issue has been resolved and I'd like to share my findings. Finding 1: Regardless set to verify certificate or not, OpenSSL socket, which called by Python Socket, will always do SSL handshake where PEM certificate is required. This finding answers why my code fails during socket handshake. Finding 2: Python is able to load system trusted CA from windows 10 default location, however, it fails on Android. It might be caused by two potential reasons: 1) Python could not find default CA location on Andorid which is /system/etc/security/cacerts/ 2) Python expects CA to be PEM format, but Android trusted CA has additional lines after ---END CERTIFICAT--- which is a sign of end of CA content. I did not verify which reason actually caused the failure of loading CA certificate. What I did to give Python proper CA data is combined all CA files I extracted from one Android device into a single file, and set to ssl.SSLContext with load_verify_locations method. Finding 3: There're some trusted CAs missing on Android comparing to trusted CAs on Windows, so I have to manually add them into my combined CA file. Finding 4: Python document says "If you want maximum compatibility between clients and servers, it is recommended to use PROTOCOL_SSLv23 as the protocol version" which is not true. It causes invalid certification error when I use this protocol version. ssl.PROTOCOL_TLSv1 protocol version works fine in my case. Finding 5: Python document says to give a certificate as an "ASCII PEM string" which is not right. We have to give a unicode string. Here is the code for reference: #!/usr/bin/python # -*- coding: UTF-8 -*- import sys reload(sys) sys.setdefaultencoding("utf-8") import os from os import path import urllib import urllib2 import ssl import traceback import shutil def loadCA(): concatedCA = u''' -----BEGIN CERTIFICATE----- [binary] -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- [binary] -----END CERTIFICATE----- ''' return concatedCA cadata = loadCA() try: url="…
upvote count: 1
answers question: http://stackoverflow.com/q/52539683
downvote count: 0

http://stackoverflow.com/comment/92099656
comment on: http://stackoverflow.com/q/52579792
score: 0
type: Comment
type: QuestionComment
has text: Do you have a file named `coverage.py` in your current directory?

http://stackoverflow.com/comment/91867576
comment on: http://stackoverflow.com/q/52458158
type: QuestionComment
type: Comment
has text: And if you create a new environment with Python 3.6.6:: Anaconda, Inc. pandas:0.23.4, this bug disappears.
score: 0

http://stackoverflow.com/q/52513772
tagged with: python
has answer: http://stackoverflow.com/a/52513808
tagged with: strip
downvote count: 0
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52515163
tagged with: filter
tagged with: byte
upvote count: 1
has body: I have an input stream from an unit and I want to filter out the bytes '\x00'. Those empty bytes appear only printing the variable. For example, I want to filter out \x00 from the following variable. example = b'\n\x00[\x007\x000\x004\x005\x001\x009\x004\x009\x000\x006\x008\x004\x002\x00]\x00 \x00-\x00 \x00D\x00S\x00I\x00 \x00-\x00 \x00R\x00e\x00s\x00p\x00o\x00n\x00s\x00e\x00' Any help is really appreciated.
favorite count: 0
type: UnansweredQuestion
has title: How can strip out \x00 bytes from a text document

http://stackoverflow.com/comment/91844300
has text: You need to explain **why** some of these should match and not others. Right now any answer provided is just pure guess work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52450401
score: 2

http://stackoverflow.com/q/52441741
has answer: http://stackoverflow.com/a/52442419
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91832861
accepted answer: http://stackoverflow.com/a/52442419
has body: Python and Django newbie here I've been trying to get a delete button onto a standard UpdateView form from Django and then get that to redirect to the DeleteView if that button is pressed instead of the submit button. I have that working but im not sure how to redirect to the corresponding delete page on click. I expect i need to change the reverse_lazy('app:submission_delete') to include the id somehow but im a bit lost here, and my google fu isnt helping much either. views.py class AssessmentUpdate(UpdateView): model = Submission fields = '__all__' success_url = reverse_lazy('app:index') def form_valid(self, request): if 'Delete' in self.request.POST: reverse_lazy('app:Submission_delete') else: self.object = request.save() return HttpResponseRedirect(self.get_success_url()) urls.py app_name = 'app' urlpatterns = [ re_path(r'^$', views.index, name='index'), path('&lt;int:submission_id&gt;/', views.detail, name='detail'), path('&lt;int:pk&gt;/update/', views.AssessmentUpdate.as_view(), name='Submission_update'), path('&lt;int:pk&gt;/delete/', views.AssessmentDelete.as_view(), name='Submission_delete'), ]
type: Question
has comment: http://stackoverflow.com/comment/91832041
tagged with: django
tagged with: python
has title: Problem getting a delete button on an UpdateView to redirect
answer count: 1
score: 0
tagged with: django-forms
has comment: http://stackoverflow.com/comment/91827406

http://stackoverflow.com/comment/92926378
type: Comment
type: QuestionComment
score: 0
has text: Still facing issues so didn't marked as accepted
comment on: http://stackoverflow.com/q/52438822

datetime-format
tags question: http://stackoverflow.com/q/52442589
tag name: datetime-format
type: Tag

http://stackoverflow.com/q/52444456
upvote count: 3
has comment: http://stackoverflow.com/comment/91831915
accepted answer: http://stackoverflow.com/a/52444646
answer count: 1
has title: Jupyter notebook run all code between two cells
has body: Is there a way on Jupyter notebook to run the code between two specific cells? For instance, suppose that I have 100 cells and I want to run only cells from 35 to 60. I don't want to run everything again from 1 to 60 because, for instance, the cells from 1 to 34 might require a long time to execute.
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91832005
downvote count: 0
has answer: http://stackoverflow.com/a/52444646
favorite count: 0
linked to: http://stackoverflow.com/q/33864681
type: Question
has comment: http://stackoverflow.com/comment/91831616
tagged with: python
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/91831704

http://stackoverflow.com/q/52578946
has comment: http://stackoverflow.com/comment/92093056
tagged with: javascript
upvote count: 3
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52579273
accepted answer: http://stackoverflow.com/a/52579273
linked to: http://stackoverflow.com/q/52550953
has body: I created a Python 3 script using the BeautifulSoup library. What it does, is going to the duckduckgo search engine using the following url: https://duckduckgo.com/?q=searchterm and then, it will display to me all the websites in the first page. Here is the code and it is working perfectly: import requests from bs4 import BeautifulSoup r = requests.get('https://duckduckgo.com/html/?q=test') soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('a', attrs={'class':'result__a'}) i = 0 while i &lt; len(results): link = results[i] url = link['href'] print(url) i = i + 1 The thing is, I am not getting the urls in the proper format (example: https://www.google.com). Instead, I am getting all my urls in the format of a search query. Here is what I mean when I search test on duckduckgo: /l/?kh=-1&amp;uddg=https%3A%2F%2Fduckduckgo.com%2Fy.js%3Fu3%3Dhttps%253A%252F%252Fr.search.yahoo.com%252Fcbclk%252FdWU9MEQwQzVENEZDNDU0NDlEMyZ1dD0xNTM4MzE4MTI3MzE5JnVvPTc3NTg0MzM1OTYxMTUyJmx0PTImZXM9ZVBGTU9iWUdQUy42cVdRVQ%252D%252D%252FRV%253D2%252FRE%253D1538346927%252FRO%253D10%252FRU%253Dhttps%25253a%25252f%25252fwww.bing.com%25252faclick%25253fld%25253dd3peyDLOVSWraifG78tpZ1GjVUCUzCMDkx%252DfJrFXeY2IfiXIwUmngX%252DYKvZWQ6q7hPHC_3kc%252DzBWS1SE015Or2c3CncFMVc9OjVV5OyB2kJqXdRsOzRnaCGy8gYCPuival0gLe7WCkfk_%252DAVKTWmYxranfh02ficTC7i6oC38n2q9U9KPe%252526u%25253dhttps%2525253a%2525252f%2525252fwww.dotdrugconsortium.com%2525252f%2525253futm_source%2525253dbing%25252526utm_medium%2525253dcpc%25252526utm_campaign%2525253dadcenter%25252526utm_term%2525253ddottest%252526rlid%25253d590f68ae34ff126ed0e3331eebd0c4fb%252FRK%253D2%252FRS%253DeKe3rY19jdg9vb_ayBSboMzPU1g%252D%26ad_provider%3Dyhs%26vqd%3D3%2D12729109948094676568590283448597440227%2D122882305188756590950269013545136161936 /l/?kh=-1&amp;uddg=https%3A%2F%2Fwww.merriam%2Dwebster.com%2Fdictionary%2Ftest /l/?kh=-1&amp;uddg=https%3A%2F%2Fwww.speedtest.net%2F /l/?kh=-1&amp;uddg=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FTest /l/?kh=-1&…
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/92093115
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/92093235
downvote count: 0
has title: Web scraping duckduckgo, but getting the links in the wrong format
has comment: http://stackoverflow.com/comment/92093282
tagged with: web-scraping
type: Question

http://stackoverflow.com/q/52448755
downvote count: 0
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/37924808
type: UnansweredQuestion
tagged with: python-pptx
tagged with: python
has answer: http://stackoverflow.com/a/52451396
upvote count: 3
tagged with: powerpoint
has body: I am trying to create new.pptx using an old.pptx . old.pptx is having 4 slides in it . I want to create the new.pptx with almost same content with few text modifications in 4 slides . I skipped the modification part from the below code, you can take an example like converting lower cases to upper case..Need to do these things in run time, so that if i just pass the old.pptx it will do the required operation and then write it to new pptx with same no. of slides..I am not sure how to tweak below, may be need to change it completely . Please have a look to below code.. from pptx import Presentation prs1 = Presentation() prs = Presentation('old.pptx') title_slide_layout = prs1.slide_layouts[0] for slide in prs.slides: for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: #print(paragraph.text) prs1.slides.add_slide(paragraph.text) prs1.save('new.pptx')
type: Question
score: 3
has title: create new pptx using existing pptx Python-Pptx
has answer: http://stackoverflow.com/a/52453187
answer count: 2

http://stackoverflow.com/comment/92031339
score: 0
comment on: http://stackoverflow.com/q/52497031
type: Comment
type: QuestionComment
has text: The way you phrase it - no. VS doesn’t speak python. But you can put a long sleep at the beginning of your code (preferably before any other import than time) and thenattach the debugger to the python process. Then when it crashes, you get a thread frame that might give a clue to where they Problem is. In C!

http://stackoverflow.com/comment/91906051
has text: Sorry if I wasn't clear. I have added a more verbose answer below. Let me know if that was what you were looking for
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52476512
type: QuestionComment

http://stackoverflow.com/a/52464431
answers question: http://stackoverflow.com/q/52463621
score: 1
has body: The error is because I was passing x into feed_dict, but I had overwritten x with the reshape. By replacing lines 12 and 13 with nn = tf.reshape(x, (batch_size, x_size * y_size)) y = tf.layers.dense(nn, 1) and adding sess.run(tf.global_variables_initializer()) I was able to get it to work perfectly. Moral of the story, always keep your placeholders separate.
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91878273
downvote count: 0

http://stackoverflow.com/comment/91914038
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52485021
has text: [Edit] your Question and show the `response` as shown in this [SO:Answer](https://stackoverflow.com/a/19343099)
score: 0

http://stackoverflow.com/comment/92178554
comment on: http://stackoverflow.com/q/52581584
score: 0
has text: @hoefling Question updated.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52562244
type: UnansweredQuestion
has body: It appears that the issue with the code is my constraints. I'm looking to model employment at the state level &amp; sector level. So I want to make sure that the total modelled employment for each state equals the total recorded employment for each state. For my constraint, I join the modelled dataframe (1D) to the original table (concatenate) and perform a sum command (groupby the state code). def Constraint_STBalance(x): TableRebuild = ST_2d_total #&lt;-outside table, orginal data. TableRebuild['Table_EMP_MOD'] = x TableRebuild['EMPNEW'] = TableRebuild['Table_EMP_MOD'] + TableRebuild['EMP_ADJ'] sumby2d = TableRebuild.groupby(['FIPSTATE'], as_index=False)['EMP_NEW'].sum() return sumby2d['EMP_NEW'] - ST_total['EMP'] #&lt;-outside table, reference data. scipy.optimize.minimize with the 'SLSQP' method returns the error code 6 which references a problem with the "LSQ matrix", which from I can determine relates to the jacobian and hessian matrices. I think the use of the sumby is changing the dimensions of the jacobian and hessian matrices but I admittedly am new to optimizing. Does anyone know with 'sumby' can be used in this manner or perhaps there's some workaround I'm overlooking?
tagged with: scipy
type: Question
tagged with: constraints
tagged with: minimize
has comment: http://stackoverflow.com/comment/92090547
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92260175
has title: Can constraints utilize the groupby (pivot) function? (scipy.optimize.minimize; SLSQP)
has comment: http://stackoverflow.com/comment/92133889
answer count: 0

http://stackoverflow.com/a/52476358
has body: If you are using happybase, you can use following: row = table.row('row-key', columns=['cf1']) It will give you all the columns and value for column family "cf1" for "row-key". More documentation is available here:
score: 2
accepted answer of: http://stackoverflow.com/q/52456032
downvote count: 0
answers question: http://stackoverflow.com/q/52456032
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/a/52543909
has comment: http://stackoverflow.com/comment/92028420
answers question: http://stackoverflow.com/q/52538268
has body: this is the code: t = time.time() def f1(a,b): lock2.acquire() for i in range(5): print(f'\t {i} \t {a+b} \t THREAD1 \t {time.ctime(time.time())} \n') time.sleep(1) lock2.release() def f2(a,b): lock2.acquire() for i in range(5): print(f'\t {i**2} \t {a+b} \t THREAD2 \t {time.ctime(time.time())} \n') time.sleep(1) lock2.release() class myThread3 (threading.Thread): # create class of threads def __init__(self, ID, NAME, f, x, y): super().__init__(target = f, name = NAME, args = (x,y,)) # kein self in super()!!! # threading.Thread.__init__(self, group=None, target = f, name = NAME, args = (x,y,)) self.threadID = ID lock2 = threading.Lock() # Create new threading.Thread objects t1 = myThread3(101, "Threaddd-1", f1, 5, 5) t2 = myThread3(102, "Threaddd-2", f2, 1, 1) # Start new Threads t1.start() t2.start() t1.join() t2.join() and this is the output: 0 10 THREAD1 Thu Sep 27 21:19:36 2018 1 10 THREAD1 Thu Sep 27 21:19:37 2018 2 10 THREAD1 Thu Sep 27 21:19:38 2018 3 10 THREAD1 Thu Sep 27 21:19:39 2018 4 10 THREAD1 Thu Sep 27 21:19:40 2018 0 2 THREAD2 Thu Sep 27 21:19:41 2018 1 2 THREAD2 Thu Sep 27 21:19:42 2018 4 2 THREAD2 Thu Sep 27 21:19:43 2018 9 2 THREAD2 Thu Sep 27 21:19:44 2018 16 2 THREAD2 Thu Sep 27 21:19:45 2018 so what i dont understand, why are t1 and t2 not running simultaniously??? t1 calls f1 and not f2. t2 calls f2 and not f1. they dont share variables. so the locks should not have any effect, right??? why is t2 blocked till t1 releases the lock?
has comment: http://stackoverflow.com/comment/92029427
score: 0
type: Answer

http://stackoverflow.com/comment/91816973
has text: unfortunately my rep is still too low for me to increase your score, but i will increase the score as soon as i hit 15 rep. also chosen your answer as the best answer. you're welcome. /ogs
comment on: http://stackoverflow.com/a/52436739
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91925609
type: Comment
type: QuestionComment
score: 0
has text: Read about [os.path.join](https://docs.python.org/3/library/os.path.html#os.path.join)
comment on: http://stackoverflow.com/q/52490758

http://stackoverflow.com/a/52566261
upvote count: 2
score: 2
has body: Last character is left from the first line, as a workaround you could overwrite it manually: while counter &gt; 0: sys.stdout.write(str(counter).ljust(7) + "\r") counter -= 100000 time.sleep(1)
downvote count: 0
answers question: http://stackoverflow.com/q/52566169
type: Answer

http://stackoverflow.com/a/52629135
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52521130
type: Answer
answers question: http://stackoverflow.com/q/52521130
has body: I have concluded that retweet_status doesn't work when using Cursor as it works fine with OAuth or Stream.

http://stackoverflow.com/comment/92077238
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52570225
has text: I know :D I didn't get to elif part, where surname would be longer

http://stackoverflow.com/comment/92040940
comment on: http://stackoverflow.com/q/52548275
has text: Can you try directly calling your weather API to see if that works?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91852208
score: 0
comment on: http://stackoverflow.com/q/52453436
type: QuestionComment
type: Comment
has text: `(720, 1280, 3)`

http://stackoverflow.com/q/52580658
tagged with: ubuntu-server
type: Question
upvote count: 2
has body: I just can't figure out how to get pip3 working on Ubuntu Server. I've done: sudo apt-get update sudo apt-get upgrade When running sudo python3 --version the output is 3.6.6. I've tried the following: sudo apt-get install python3-pip and python3-pip3, python-pip3, i've tried installing python3-setuptools and they appear to be installed but easy_install is not recognised as a command. I think i've literally tried all options and the error unable to locate package python3-pip pops every time.
answer count: 1
has comment: http://stackoverflow.com/comment/92096807
favorite count: 0
has comment: http://stackoverflow.com/comment/93959642
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/92097115
has answer: http://stackoverflow.com/a/52580886
accepted answer: http://stackoverflow.com/a/52580886
tagged with: pip
has comment: http://stackoverflow.com/comment/92096950
has comment: http://stackoverflow.com/comment/92096683
has title: Install pip on Ubuntu server 18.04.1 LTS
type: AnsweredQuestion
score: -1

http://stackoverflow.com/a/52511921
score: 1
upvote count: 1
has body: Try not using Excel automation on the server, it is a security risk and not designed for a multi threaded web server environment. Instead, use one of these products: Closed XML (free) spreadsheet gear Aspose Cells Soft Artisans excel writer and I am sure there are many more.
answers question: http://stackoverflow.com/q/52511631
downvote count: 0
type: Answer

http://stackoverflow.com/q/52520825
score: 1
has body: Like many people developing deep learning models, I am hindered by my hardware resources, namely GPU memory. I have an audio classification problem for which I am trying out a number of RNNs. The data is very large and I am only able to use small batch sizes and must limit the lstm size also. I understand that many people use spectrograms or other methods to provide more condensed data to the network but I would specifically like to know how to do this with raw data. This is what I am doing currently on a batch size of around 4: loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=label_op)) optimisation_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss_op) I would ideally like to calculate the gradients for each parameter for a batch on the GPU, then move those to RAM whilst calculating the gradients for the next batch. After some number of batches, I would then like to average the gradients for each parameter and use them to update the network. I got this idea from the inception github page, which describes something similar to parallelise over multiple GPUs: https://github.com/tensorflow/models/tree/master/research/inception
favorite count: 0
tagged with: tensorflow-gradient
type: Question
tagged with: python
tagged with: recurrent-neural-network
upvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52615959
type: UnansweredQuestion
has title: Using tensorflow, how can you average parameter gradient values over a number of batches and update using that average?
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52572194
type: Answer
has comment: http://stackoverflow.com/comment/92082036
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52571647
has body: According to these docs, the function you're calling is defined as: pysnmp.hlapi.bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options) maxRepetitions (int) But for the maxRepetitions parameter, you're passing an ObjectType() instead of an int. I think the ObjectType() should be one of the *varBinds, I think you missed the maxRepetitions parameter. In your code: snmp_iter = bulkCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget((hostip, 161)), ContextData(), 1, I think you're missing the maxRepetitions parameter that should go here... ObjectType(ObjectIdentity('IF-MIB','ifOperStatus')), lexicographicMode=True)
downvote count: 0

http://stackoverflow.com/a/52523962
has comment: http://stackoverflow.com/comment/91988558
has comment: http://stackoverflow.com/comment/91987746
has comment: http://stackoverflow.com/comment/91989513
type: Answer
has body: If you want to replace them with zeros you can use between and do this top = depth_3.max() bottom = depth_1.min() df1[~df1.depth.between(bottom, top)] = 0 df3[~df3.depth.between(bottom, top)] = 0 Edit: as mentioned in your comment if you don't want to overwrite the depth you can use top = depth_3.max() bottom = depth_1.min() df1_cols = df1.columns.difference(["depth"]) df1.loc[~df1.depth.between(bottom, top), df1_cols] = 0
has comment: http://stackoverflow.com/comment/91987961
upvote count: 1
has comment: http://stackoverflow.com/comment/91988773
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/52523805
has comment: http://stackoverflow.com/comment/91988167

http://stackoverflow.com/q/52434544
accepted answer: http://stackoverflow.com/a/52435213
type: AnsweredQuestion
tagged with: tkinter
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91813429
type: Question
has comment: http://stackoverflow.com/comment/91813005
has comment: http://stackoverflow.com/comment/91813089
linked to: http://stackoverflow.com/q/17166074
has answer: http://stackoverflow.com/a/52435213
tagged with: keyboard-events
downvote count: 0
answer count: 1
has title: python 3 calculator with tkinter
favorite count: 0
has comment: http://stackoverflow.com/comment/91812959
tagged with: python-3.x
tagged with: python
has body: I have been programming for a long time. Only recently have I decided to take a stab at python (I should be working with C# as I am in school for it, but I don't care for windows. Long story) Anyway I was on this site and it showed source for a calculator. I took it, and put it in PyCharm and started to study. By the time I was done I had changed the source significantly. I had added keyboard binding and reduced a lot of the redundant code in it. My question is simple, is this code that I wrote efficient from a python standard viewpoint? # -*-coding: utf-8-*- # !/usr/bin/python3.5 from tkinter import Tk, Button, Entry, END import math class Calc: def getandreplace(self): # replace x, + and % to symbols that can be used in calculations # we wont re write this to the text box until we are done with calculations self.txt = self.e.get() # Get value from text box and assign it to the global txt var self.txt = self.txt.replace('÷', '/') self.txt = self.txt.replace('x', '*') self.txt = self.txt.replace('%', '/100') def evaluation(self, specfunc): # Evaluate the items in the text box for calculation specfunc = eq, sqroot or power self.getandreplace() try: self.txt = eval(str(self.txt)) # evaluate the expression using the eval function except SyntaxError: self.displayinvalid() else: if any([specfunc == 'sqroot', specfunc == 'power']): # Square Root and Power are special self.txt = self.evalspecialfunctions(specfunc) self.refreshtext() def displayinvalid(self): self.e.delete(0, END) self.e.insert(0, 'Invalid Input!') def refreshtext(self): # Delete current contents of textbox and replace with our completed evaluatioin self.e.delete(0, END) self.e.insert(0, self.txt) def evalspecialfunctions(self, specfunc): # Calculate square root and power if specfunc is sqroot or power if specfunc == 'sqroot': return math.sqrt(float(self.txt)) elif specfunc == 'power': return math.pow(float(self.txt), 2) def clearall(self): # AC button pressed on form or 'esc" pressed on keyboard self.e.del…
linked to: http://stackoverflow.com/q/419163

http://stackoverflow.com/q/52565505
score: 6
favorite count: 0
type: Question
has body: I am trying to remove an item from a list. Usually pretty obvious but the problem is that those items are objects and I want to remove them by one of their attributes. Is there a more graceful way to do this than what I have below? class Item: def __init__(self, name, color): self.name = name self.type = type if __name__ == "__main__": myList = [] myList.append(Item("item1", "green")) myList.append(Item("item2", "blue")) # Try to remove object with name "item2" index = None for i, val in enumerate(myList): if val.name == "item2" del myList[i]
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/52565906
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52565590
has answer: http://stackoverflow.com/a/52565590
answer count: 2
has comment: http://stackoverflow.com/comment/92068698
accepted answer: http://stackoverflow.com/a/52565906
has title: Simplest way to delete object from list of objects?
has comment: http://stackoverflow.com/comment/92068852
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52491062
upvote count: 3
type: Question
downvote count: 0
has body: I am trying to get pycurl to install on PyCharm for MacOS High Sierra, but I keep getting this error: __main__.ConfigurationError: Curl is configured to use SSL, but we have not been able to determine which SSL backend it is using. Please see PycURL documentation for how to specify the SSL backend manually. I am able to get pycurl to install in terminal with the commands PYCURL_SSL_LIBRARY=openssl LDFLAGS="-L/usr/local/opt/openssl/lib" CPPFLAGS="-I/usr/local/opt/openssl/include" pip install --no-cache-dir pycurl and pip install --no-cache-dir --compile --ignore-installed --install-option="--with-openssl" --user pycurl However, when trying to run in PyCharm, it doesn't recognize that pycurl is installed unless I install it through PyCharm. PyCharm only gives me the option to add options to the pip install command, so the first solution doesn't work. The second solution does not work because PyCharm's venv does not allow the --self option. When I try to run without this option, I get the same error I would get with no options.
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pycurl
score: 3
tagged with: pycharm
answer count: 0
has title: PyCharm won't install pycurl macOS High Sierra

http://stackoverflow.com/a/52508299
has comment: http://stackoverflow.com/comment/92017338
has comment: http://stackoverflow.com/comment/91980294
score: 0
answers question: http://stackoverflow.com/q/52505778
has body: Surely the issue isn't about cookies, but the headers. You're using your custom headers only in the first request. yield scrapy.Request( url=url, headers=headers, # callback=self.parse_page1) #... yield scrapy.Request( #❓ url=url, method='POST', callback=self.parse_page2, meta={'senderid': senderid})` You can define it as a custom_settings to make them work for every request in the spider: class MySpider(scrapy.Spider): custom_settings = { 'DEFAULT_REQUEST_HEADERS': { 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', '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', 'DNT': '1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9', 'If-Modified-Since': 'Tue, 18 Sep 2018 19:11:50 GMT', }, } More info about custom_settings: https://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.custom_settings
type: Answer
has comment: http://stackoverflow.com/comment/91980330
has comment: http://stackoverflow.com/comment/91980355

http://stackoverflow.com/comment/91992735
type: QuestionComment
score: 2
has text: That behavior is most of the point of Python's `super`. (Yes, the name is confusing.)
comment on: http://stackoverflow.com/q/52526451
type: Comment

http://stackoverflow.com/a/52478210
has comment: http://stackoverflow.com/comment/91904364
has comment: http://stackoverflow.com/comment/91900824
downvote count: 0
has comment: http://stackoverflow.com/comment/91900790
has comment: http://stackoverflow.com/comment/91900189
score: 1
has body: Solution of first question: bind focus in and focus out of your widget. Like: txtFixedIncome.bind("<FocusIn>",lambda _:txtFixedIncome.delete('1.0', 'end')) txtFixedIncome.bind("<FocusOut>",lambda _:txtFixedIncome.insert("1.0","your income portion" if str(txtFixedIncome.get("1.0","end")) == "\n" else "")) This will erase all data in entry when focused out and enter information data when focused in. Solution of second question: You can make a function to update your values and format them like: def updat(text): try:txtCalculationResult.insert(tkinter.INSERT,"{:,.0f}".format(float(text))) except:txtCalculationResult.insert(tkinter.INSERT,"CalculationResults") As: >>> "{:,.0f}".format(23442) '23,442' >>> Full code: Here is a full example code that shows the behavior you are expecting: import tkinter mainForm = tkinter.Tk() mainForm.title('Shahr Fixed Income Fund') def updat(text): try:txtCalculationResult.insert(tkinter.INSERT,"{:,.0f}".format(float(text))) except:txtCalculationResult.insert(tkinter.INSERT,"CalculationResults") def btnCalculatePressed(): txtCalculationResult.delete('1.0', 'end') yourIncomePortion = txtFixedIncome.get('1.0', 'end') updat(yourIncomePortion) btnCalculate = tkinter.Button(mainForm , text = "Calculate", command= btnCalculatePressed) txtCalculationResult = tkinter.Text(mainForm) txtCalculationResult.insert(tkinter.INSERT, "CalculationResults") txtFixedIncome = tkinter.Text(mainForm, height = 1, width = 30 ) txtFixedIncome.insert(tkinter.INSERT, "your income portion") txtFixedIncome.bind("<FocusIn>",lambda _:txtFixedIncome.delete('1.0', 'end')) txtFixedIncome.bind("<FocusOut>",lambda _:txtFixedIncome.insert("1.0","your income portion" if str(txtFixedIncome.get("1.0","end")) == "\n" else "")) txtFixedIncome.pack(); txtCalculationResult.pack() btnCalculate.pack() mainForm.mainloop() Format during typing: If you want to format the string during typing as you commented then use the following code: import tkinter mainForm = tkinter.Tk() mainForm.ti…
has comment: http://stackoverflow.com/comment/91897953
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52476783
has comment: http://stackoverflow.com/comment/91900901
answers question: http://stackoverflow.com/q/52476783
has comment: http://stackoverflow.com/comment/91898734
type: Answer

http://stackoverflow.com/q/52518364
type: UnansweredQuestion
tagged with: python
tagged with: aws-iot
has body: I have an IoT Project which is: 2 bulbs, connect to 2 Raspberry Pi (python) web app (Javascript) with 3 buttons: one to turn on/off bulb 1, one to turn on/off bulb 2, one to turn on/off both bulbs. I approached 2 different ways using AWSIoTMQTTClient: Pi: class CallbackContainer(object): def __init__(self, client): self._client = client def messagePrint(self, client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") myAWSIoTMQTTClient = AWSIoTMQTTClient("myClientID") myAWSIoTMQTTClient.configureEndpoint("xxxxx.iot.eu-west-1.amazonaws.com", 8883) myAWSIoTMQTTClient.configureCredentials("./certs/rootCA.pem", "./certs/xxxxxxx-private.pem.key", "./certs/xxxxxxx-certificate.pem.crt") myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myCallbackContainer = CallbackContainer(myAWSIoTMQTTClient) myAWSIoTMQTTClient.connect() myAWSIoTMQTTClient.subscribe("topic_both", 0, myCallbackContainer.messagePrint) myAWSIoTMQTTClient.subscribe("topic_bulb1", 0, myCallbackContainer.messagePrint) while True: time.sleep(1) Javascript: var params = { payload: JSON.stringify(body), topic: myTopic, //"topic_both" or "topic_bulb1" qos: 0 }; var iotPromise = iotData.publish(params).promise(); using AWSIoTShadowClient: Pi: def customShadowCallback_Delta(payload, responseStatus, token): print(responseStatus) payloadDict = json.loads(payload) print("++++++++DELTA++++++++++") print("property: " + str(payloadDict["state"])) print("+++++++++++++++++++++++\n\n") #Need to handle JSON to control bulbs thingName = "control_bulb" myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("myClientID") myAWSIoTMQTTShadowClient.configureEndpoint("xxxxxx.iot.eu-west-1.amazonaws.com", 8883) myAWSIoTMQTTShadowClient.configureCredentials("/certs/rootCA.pem", "/certs/xxxxx-private.pem.key", "/certs/xxxxx-certificate.pem.crt") myAWSIoTMQTTShadowClient.…
type: Question
has answer: http://stackoverflow.com/a/52913854
tagged with: javascript
tagged with: amazon-web-services
tagged with: iot
has title: AWSIoT: AWSIoTShadowClient vs AWSIoTMQTTClient
score: 0
answer count: 1

http://stackoverflow.com/comment/91859950
type: Comment
comment on: http://stackoverflow.com/a/52458857
type: AnswerComment
has text: By after the keyword what do you mean? Does the code work if i put the "while True:" before like you did?
score: 0

http://stackoverflow.com/comment/92093384
has text: If I'm gonna get downvoted without any explanation for correctly answering a question and how to solve it I'll rather just delete my answer alltogether instead of helping.
type: Comment
comment on: http://stackoverflow.com/a/52578829
score: 1
type: AnswerComment

http://stackoverflow.com/q/52477891
has title: Can we test the Naive Bayes algorithm with unlabeled data?
downvote count: 1
score: -1
type: Question
answer count: 2
upvote count: 0
has body: I have trained the model using labeled data for Naive Bayes algorithm. And tested the same model with the other set of labeled data. And I have calculated accuracy, precision and recall scores using the below code. My code : from sklearn.metrics import confusion_matrix from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import precision_score from sklearn.metrics import recall_score from io import open def load_data(filename): reviews = list() labels = list() with open(filename, encoding='utf-8') as file: file.readline() for line in file: line = line.strip().split(' ',1) labels.append(line[0]) reviews.append(line[1]) return reviews, labels X_train, y_train = load_data('./train_data.txt') X_test, y_test = load_data('./test_data.txt') vec = CountVectorizer() X_train_transformed = vec.fit_transform(X_train) X_test_transformed = vec.transform(X_test) clf= MultinomialNB() clf.fit(X_train_transformed, y_train) score = clf.score(X_test_transformed, y_test) print("score of Naive Bayes algo is :" , score) y_pred = clf.predict(X_test_transformed) print(confusion_matrix(y_test,y_pred)) print("Precision Score : ",precision_score(y_test, y_pred,average='micro')) print("Recall Score : ",recall_score(y_test, y_pred,average='micro')) But, now I have another test set which contains unlabeled data. Now, can I test the model with this unlabeled data using the above code ?
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91897552
has answer: http://stackoverflow.com/a/52989226
favorite count: 0
has answer: http://stackoverflow.com/a/52502449
has comment: http://stackoverflow.com/comment/91897724
has comment: http://stackoverflow.com/comment/91898208
linked to: http://stackoverflow.com/q/52423386
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/91898418

http://stackoverflow.com/q/52506767
downvote count: 0
tagged with: postman
favorite count: 0
has answer: http://stackoverflow.com/a/52509354
tagged with: python
has title: Post request does not work in Scrapy. Works in Postman. Where am I wrong?
score: 2
has body: I use scrapy.FormRequest.from_response to Post. I am getting through captcha and all data is in place but Do not get the table I expect. Here is my payload { 'captcha': '680336', 'districtCode': '714', 'sroVal': 'TADIKONDA(714)', 'selectedSroId': 'null', 'sroId': '7', 'path': '/APCARDECClient', 'regyear': '2018', 'docSel': '1', 'doct': '861' } And headers I used for Post request. { 'origin': 'http://registration.ap.gov.in', 'accept-language': 'en-US,en;q=0.9,ru;q=0.8,uk;q=0.7', 'accept-encoding': 'gzip, deflate', 'accept': 'text/html,application/xh tml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'upgrade-insecure-requests': '1', 'referer': 'http://registration.ap.gov.in/APCARDECClient/ecSearchByDocAu to.jsp?distcode=&amp;distname=&amp;srocode=&amp;sroname=', 'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', 'dnt': '1', 'Cookie': 'JSESSIONID=dQJTbqhpYdg1PMjJZkYT9bTyLLnMqV43zxj2sws1gZ2fQ8fJn0CQ!-392092779', 'cache-control': 'no-cache', 'content-type': 'application/x-www-form-urle ncoded' } When I use the same data to mimic Post in Postman it works fine and I recieve the table as expected. Here is payload from Postman: captcha:331683 districtCode:7 docSel:1 doct:861 path:/APCARDECClient regyear:2018 selectedSroId:null sroId:714 sroVal:TADIKONDA(714) and headers from Postman: Origin:http://registration.ap.gov.in Upgrade-Insecure-Requests:1 DNT:1 User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Referer:http://registration.ap.gov.in/APCARDECClient/FetchHelpDetails Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.9,ru;q=0.8,uk;q=0.7 Cookie:JSESSIONID=dQJTbqhpYdg1PMjJZkYT9bTyLLnMqV43zxj2sws1gZ2fQ8fJn0CQ!-392092779 Content-Type:application/x-www-form-urlencoded Please point me where am I wrong? The only possibility I see is t…
upvote count: 2
type: UnansweredQuestion
tagged with: scrapy
has answer: http://stackoverflow.com/a/52518768
type: Question
answer count: 2

http://stackoverflow.com/comment/92208684
type: QuestionComment
comment on: http://stackoverflow.com/q/52584889
score: 0
type: Comment
has text: What do you get from `print repr(event)` when there is no match?

http://stackoverflow.com/comment/91903258
score: 0
type: QuestionComment
type: Comment
has text: I just want to print something in the brower, a simple messge to notify the user that he is about to receive the file
comment on: http://stackoverflow.com/q/52467095

http://stackoverflow.com/a/52434253
answers question: http://stackoverflow.com/q/52431265
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
has body: To be able to access imported functions/modules you need to pass globals to eval. For example: &gt;&gt;&gt; from math import exp # anything in global scope will be accessible &gt;&gt;&gt; lambda_t = 'lambda x: exp(x)' &gt;&gt;&gt; l = eval(lambda_t, globals()) &gt;&gt;&gt; l(2) 7.38905609893065 To make this work as an argument, you would need to either accept a string and process it after, or wrap the creation of the lambda in another function. You can pass this as your type parameter to handle the conversion. import argparse from math import exp def create_lambda_with_globals(s): return eval(s, globals()) parser = argparse.ArgumentParser() help_f= "The Syntax is lambda x: f(x), where f(x) is the function in python language" parser.add_argument("-f",dest="f", type=create_lambda_with_globals, help=help_f, required=True) params = parser.parse_args() # the lambda is now defined in params.f print(params.f(2)) # run the lambda with an input of 2 Running this from the command line: python test.py -f 'lambda x: exp(x)' 7.38905609893
accepted answer of: http://stackoverflow.com/q/52431265

http://stackoverflow.com/q/52566533
has answer: http://stackoverflow.com/a/52566560
accepted answer: http://stackoverflow.com/a/52566560
has comment: http://stackoverflow.com/comment/92070361
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has body: Recently, I am practicing writing code for "recursive functions". this, I am trying to code one function called reverse digits and I notice that there are lots of different ways to do that. My code works in IDLE when I use return. For example: def reverse_digits(num): if num &lt; 10: return num else: return str(num%10) + str(reverse_digits(num//10)) print(reverse_digits(1234)) However, I want to print the result in the recursive function, for example, def reverse_digits(num): if num &lt; 10: return num else: print(str(num%10) + str(reverse_digits(num//10))) reverse_digits(1234) I would get 21 3None 4None Anyone can explain why? Or help me to improve the code?
type: AnsweredQuestion
downvote count: 0
has title: Python recursive function with print reverse digits
type: Question
tagged with: recursion
score: 1

http://stackoverflow.com/comment/92092626
type: Comment
score: 1
has text: It's worth noting that the Python *language* doesn't guarantee that the `__del__` method is called immediately when the name is re-bound. In the CPython implementation that happens to be true, but not in most other implementations (PyPy, Jython). And even in CPython there are lots of ways to prevent `__del__` from being called in a timely manner or even at all.
comment on: http://stackoverflow.com/q/52578619
type: QuestionComment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/52552401
type: Tag
tags question: http://stackoverflow.com/q/52526729
tags question: http://stackoverflow.com/q/52552264
tags question: http://stackoverflow.com/q/52583640
tags question: http://stackoverflow.com/q/52498776
tags question: http://stackoverflow.com/q/52505583
tags question: http://stackoverflow.com/q/52544331
tags question: http://stackoverflow.com/q/52451946
tag name: csv
tags question: http://stackoverflow.com/q/52457602
tags question: http://stackoverflow.com/q/52523976
tags question: http://stackoverflow.com/q/52587256
tags question: http://stackoverflow.com/q/52548737
tags question: http://stackoverflow.com/q/52555225
tags question: http://stackoverflow.com/q/52461374
tags question: http://stackoverflow.com/q/52464269
tags question: http://stackoverflow.com/q/52431921
tags question: http://stackoverflow.com/q/52430649
tags question: http://stackoverflow.com/q/52499562
tags question: http://stackoverflow.com/q/52505802
tags question: http://stackoverflow.com/q/52576617
tags question: http://stackoverflow.com/q/52492404
tags question: http://stackoverflow.com/q/52454900
tags question: http://stackoverflow.com/q/52462279
tags question: http://stackoverflow.com/q/52433957
tags question: http://stackoverflow.com/q/52584320
tags question: http://stackoverflow.com/q/52501688
tags question: http://stackoverflow.com/q/52559812
tags question: http://stackoverflow.com/q/52578897
tags question: http://stackoverflow.com/q/52479288
tags question: http://stackoverflow.com/q/52498943
tags question: http://stackoverflow.com/q/52470985
tags question: http://stackoverflow.com/q/52500368
tags question: http://stackoverflow.com/q/52552258
tags question: http://stackoverflow.com/q/52514068
tags question: http://stackoverflow.com/q/52573331
tags question: http://stackoverflow.com/q/52557037
tags question: http://stackoverflow.com/q/52530791
tags question: http://stackoverflow.com/q/52570941
tags question: http://stackoverflow.com/q/52465880
tags question: http://stackoverflow.com/q/52546298
tags question: http://stackoverflow.com/q/52451264
tags question: http://stackoverflow.com/q/52535552
tags question: http://stackoverflow.com/q/52581125
tags question: http://stackoverflow.com/q/52511354
tags question: http://stackoverflow.com/q/52504185
tags question: http://stackoverflow.com/q/52513472
tags question: http://stackoverflow.com/q/52576147
tags question: http://stackoverflow.com/q/52518048
tags question: http://stackoverflow.com/q/52549102
tags question: http://stackoverflow.com/q/52565665
tags question: http://stackoverflow.com/q/52494242
tags question: http://stackoverflow.com/q/52586286
tags question: http://stackoverflow.com/q/52522143
tags question: http://stackoverflow.com/q/52482867
tags question: http://stackoverflow.com/q/52445977
tags question: http://stackoverflow.com/q/52479311
tags question: http://stackoverflow.com/q/52517311
tags question: http://stackoverflow.com/q/52452524
tags question: http://stackoverflow.com/q/52545977
tags question: http://stackoverflow.com/q/52582187
tags question: http://stackoverflow.com/q/52434296
tags question: http://stackoverflow.com/q/52507049
tags question: http://stackoverflow.com/q/52498403
tags question: http://stackoverflow.com/q/52532317
tags question: http://stackoverflow.com/q/52520711
tags question: http://stackoverflow.com/q/52435611
tags question: http://stackoverflow.com/q/52583792
tags question: http://stackoverflow.com/q/52462568
tags question: http://stackoverflow.com/q/52588463
tags question: http://stackoverflow.com/q/52504876

http://stackoverflow.com/a/66592686
downvote count: 0
answers question: http://stackoverflow.com/q/52510584
score: 10
has body: HTTP methods in the requests library have a json argument that, when given, will perform json.dumps() for you and set the Content-Type header to application/json: data = [{"$key": 8},{"$key": 7}] response = requests.put(url, json=data)
upvote count: 10
type: Answer

http://stackoverflow.com/comment/137404116
has text: What do you mean by "capture"?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52438304

http://stackoverflow.com/comment/92008333
has text: So..... must be a request issue. I'll research what factors have an impact on the https request getting through. Any steer on best practise troubleshooting this issue?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52533863

http://stackoverflow.com/q/52487103
has answer: http://stackoverflow.com/a/52488931
has body: I am working on an application with a few nested loops of non vectorizable code. There's a group of around 50 functions that get called hundreds or thousands of times. These functions receive dictionaries and pass dictionaries back. Each function is very short, each with simple numerical code, so just compiling the functions will not do much good. I think that I need to compile both the loop with the functions. Cython could work but I am worried about the amount of work in maintaining type declarations on so many functions plus not getting big improvements due to all those dictionaries being passed around. I was wondering if this is a good use case for PyPy. There's no numpy or c extensions involved. Just simple functions reading off inputs from a dictionary and updating those dictionaries. I've read the documentation for PyPy where it says that short-running processes will not be improved by PyPy. I am wondering if this short-running functions will prevent the JIT compiler from improving the runtime. What do you think? Any experience with pypy on something similar is welcome. Thanks!
has comment: http://stackoverflow.com/comment/91915581
type: Question
has title: Is this a use case for pypy?
has comment: http://stackoverflow.com/comment/91915925
has comment: http://stackoverflow.com/comment/91915479
answer count: 1
tagged with: pypy
score: 0
has comment: http://stackoverflow.com/comment/91915741
has comment: http://stackoverflow.com/comment/91915539
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91923763
has comment: http://stackoverflow.com/comment/91923718

http://stackoverflow.com/comment/92076698
score: 1
has text: **`pd.DataFrame.apply` is not vectorised**. It is nothing more than a thinly veiled loop and often slower than a list comprehension.
comment on: http://stackoverflow.com/a/52568196
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52530756
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: import-from-csv
has comment: http://stackoverflow.com/comment/92001353
accepted answer: http://stackoverflow.com/a/52531551
type: Question
has comment: http://stackoverflow.com/comment/92000855
tagged with: django-models
has title: How to import a .csv table with a foreign key into a django database
answer count: 3
has body: This is my first Django project and I am having difficulty loading data from a .csv file into a model with a foreign key. Here are my models: class Artist(models.Model): artistID = models.IntegerField(primary_key=True, null=False, unique=True) artistName = models.CharField(max_length=50) artistNotes = models.TextField(blank=True) class Art(models.Model): artID = models.IntegerField(primary_key=True, null=False, unique=True) artistID = models.ForeignKey(Artist, db_column='artistID', on_delete=models.CASCADE, default = 1) title = models.CharField(max_length=100, default = "No Title Given") location = models.CharField(max_length=100) owner = models.CharField(max_length=50, blank=True) origin = models.CharField(max_length=150, blank=True) medium = models.CharField(max_length=50, blank=True) artNotes = models.TextField(blank=True) I wrote a view that would import the data: def importArt(request): myFile = open('misc/Art.csv', 'r') for line in myFile: line = line.split(',') temp = Art.objects.create() temp.artID = line[0] temp.artistID = line[1] temp.title = line[2] temp.location = line[3] temp.owner = line[4] temp.origin = line[5] temp.medium = line[6] temp.artNotes = line[7] temp.save() myFile.close() return render(request, 'dtccArt/importArt.html', {}) This strategy worked fine for the Artist table but this is the error that I am getting: Cannot assign "'2'": "Art.artistID" must be a "Artist" instance. My first line of data looks like this: 1,2,Wisdom &amp; Knowledge,Main Library,College,Visiting Artist at DTCC 19??-19??,Stone Sculpture,, I fixed two errors before getting to this stuck point. I added db_column='artistID' and default = 1 to the Art model's ArtistID field. The default = 1 refers to an unknown artist in case the artist is unknown for a piece of art. Can someone explain what the error message means, some hints on how to fix it, or an easier way to import .csv data into an existing Django model? Thanks in advance! Andrea
downvote count: 0
favorite count: 0
tagged with: foreign-keys
has answer: http://stackoverflow.com/a/52531551
possible better answer: http://stackoverflow.com/a/52530822
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92001278
has answer: http://stackoverflow.com/a/65397124
has answer: http://stackoverflow.com/a/52530822

http://stackoverflow.com/comment/92096889
score: 0
comment on: http://stackoverflow.com/q/52580747
type: Comment
type: QuestionComment
has text: Okay I get it. But I don't want to show users an ordered results so I can avoid bias. Having the results in no order while applying pagination would have been a bigggg plus for me. Anyways, I'll develop my workaround

http://stackoverflow.com/q/52485276
has comment: http://stackoverflow.com/comment/91912838
has comment: http://stackoverflow.com/comment/91912503
has comment: http://stackoverflow.com/comment/91912767
score: 0
has comment: http://stackoverflow.com/comment/91913397
answer count: 1
has answer: http://stackoverflow.com/a/52485522
linked to: http://stackoverflow.com/q/49359627
has comment: http://stackoverflow.com/comment/91913709
tagged with: python
has body: I wrote this piece of code to connect the MySQLServer from Jupyter notebook: import sqlalchemy from sqlalchemy import create_engine engine = sqlalchemy.create_engine(‘mysql+mysqlconnector://root:password@localhost:3306/dbname′) I am getting the following error: File "&lt;ipython-input-12-c958f7670e02&gt;", line 6 engine = sqlalchemy.create_engine(‘mysql+mysqlconnector://root:password@localhost:3306/events′) ^ SyntaxError: invalid character in identifier pip list command also lists PyMySQL (0.9.2).
tagged with: jupyter-notebook
has title: Connecting MySQLServer from Jupyter notebook
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91912093
tagged with: mysql
has comment: http://stackoverflow.com/comment/91913222
type: Question

graphics
tag name: graphics
type: Tag
tags question: http://stackoverflow.com/q/52574623
tags question: http://stackoverflow.com/q/52432549

http://stackoverflow.com/q/52567912
accepted answer: http://stackoverflow.com/a/52568900
has answer: http://stackoverflow.com/a/52569710
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has title: Pandas apply function to every second row of column
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/52568900
has body: I am trying to alter the text on every second row after interpolation the numeric values between rows. stamp value 0 00:00:00 2 1 00:00:00 3 2 01:00:00 5 trying to apply this change to every second stamp row (ie 30 instead of 00 between colons) - str column stamp value 0 00:00:00 2 1 00:30:00 3 2 01:00:00 5 function to change string def time_vals(row): #run only on odd rows (1/2 hr) if int(row.name) % 2 != 0: l, m, r = row.split(':') return l+":30:"+r I have tried the following: hh_weather['time'] =hh_weather[hh_weather.rows[::2]['time']].apply(time_vals(2)) but I get an error: AttributeError: 'DataFrame' object has no attribute 'rows' and when I try: hh_weather['time'] = hh_weather['time'].apply(time_vals) AttributeError: 'str' object has no attribute 'name' Any ideas?
answer count: 2
downvote count: 0
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92073087
possible better answer: http://stackoverflow.com/a/52569710

http://stackoverflow.com/q/52527232
has body: I am trying to structure a Python 3 program as follows: Base Class: Body Sub-Class: Head A super-simple code representation is as follows: class Body: def __init__(self): self.head_obj = Head() # ...Set-up body... def body_actions: print('Body does something') class Head(Body): def __init__(self): super().__init__() # ...Set-up head... def head_actions: print('Head does something') I want to be able to create an instance of Body called 'body_obj' and then access the Head sub-class (and its properties/methods) as follows: body_obj = Body() body_obj.body_actions() body_obj.head_obj.head_actions() However, when I run the code, Python returns a maximum recursion depth RuntimeError. I need to do some setup with __ init __ in both the Body and Head classes, and Pycharm complains when I don't call a super() function within the Head class's __ init __ as this appears to be bad practice. What is the proper way to set up this kind of structure where a Class's sub-objects all need to be initialized when the base class is instantiated? I have looked into nesting the classes, but this also appears to be poor practice.
downvote count: 0
has title: how can does one declare a sub-class object inside of a base class without leading to recursion errors?
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/91994123
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/91994381
has answer: http://stackoverflow.com/a/52527277
answer count: 1
tagged with: oop
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/52527277

http://stackoverflow.com/a/52458806
type: Answer
has body: Take iteration through one dictionary and check for existence of key in the other: dict_one = {'12':'fariborz','13':'peter','14':'jadi'} dict_two = {'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} for k in dict_one: if k in dict_two: print(dict_one[k], dict_two[k]) # fariborz daei # jadi jafar
answers question: http://stackoverflow.com/q/52458754
score: 0

http://stackoverflow.com/comment/91891922
has text: @TheWho It is hard to tell without further knowledge. I would try the usual recommended tricks first, like prefetching. Also, if you have the possibility to load the label first then the corresponding data, you will probably be faster by loading data after doing the `split_and_merge`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52470287
score: 0

http://stackoverflow.com/q/52584209
has title: How object of parent class is created in Python?
has comment: http://stackoverflow.com/comment/92103728
has comment: http://stackoverflow.com/comment/92103645
type: Question
has comment: http://stackoverflow.com/comment/92103727
has comment: http://stackoverflow.com/comment/92103867
score: 0
has comment: http://stackoverflow.com/comment/92103334
has comment: http://stackoverflow.com/comment/92103641
answer count: 1
has answer: http://stackoverflow.com/a/52584237
accepted answer: http://stackoverflow.com/a/52584237
has comment: http://stackoverflow.com/comment/92103535
has comment: http://stackoverflow.com/comment/92103463
duplicate of: http://stackoverflow.com/q/576169
has body: I am not sure how object of a parent class is created in Python. Consider a following scenario. class Animal(): def __init__(self): print("Animal is created") def eat(self): print("I am eating") class Dog(Animal): def __init__(self, breed, name, spots): self.breed = breed self.name = name self.spots = spots def bark(self): print("Woof! My name is {}".format(self.name)) my_dog = Dog(breed="lab", name="Sam", spots=False) This does not print "Animal is created". class Animal(): def __init__(self): print("Animal is created") def eat(self): print("I am eating") class Dog(Animal): def __init__(self, breed, name, spots): Animal.__init__(self) self.breed = breed self.name = name self.spots = spots def bark(self): print("Woof! My name is {}".format(self.name)) my_dog = Dog(breed="lab", name="Sam", spots=False) Whereas this prints "Animal is created" But in both the cases I am able to access eat() method of Animal class from Dogs instance (my_dog). This means Animal is created in both the cases. Then why I don't see Animals constructor getting called in case#1?
linked to: http://stackoverflow.com/q/576169
tagged with: python
type: AnsweredQuestion

sprite
tags question: http://stackoverflow.com/q/52564391
type: Tag
tags question: http://stackoverflow.com/q/52456284
tag name: sprite

http://stackoverflow.com/q/52453530
upvote count: 4
has answer: http://stackoverflow.com/a/52453634
has title: What does tensorflow.keras.utils.normalize actually do?
type: AnsweredQuestion
has body: Documentation only says that it "Normalizes a Numpy array." By normalization I expect that it makes the mean = 0 and standard deviation = 1. But when i run it on an array of [1,2,3], I get the following array: [0.26726124 0.53452248 0.80178373] Which has mean = 0.53, and std = 0.21. It would be good to know what it means by normalize.
downvote count: 0
tagged with: tensorflow
type: Question
score: 4
answer count: 1
tagged with: keras
accepted answer: http://stackoverflow.com/a/52453634
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/91935322
has text: You can experiment with regex interactively here: https://www.regexpal.com/ you might be able to come up with the right solution yourself
score: 1
comment on: http://stackoverflow.com/q/52497534
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52583498
has comment: http://stackoverflow.com/comment/92211388
score: 1
has body: how do I pass a python method and kwargs to a boost C++ function and call the python method with kwargs. python: def py_method(**kwargs): for key in kwargs.keys(): print 'Key: ', key, ', Value: ', kwargs[key] cpp_method(py_method, arg1=1, arg2=2) or kwargs = {'arg1': 1, 'arg2': 2} cpp_method(py_method, **kwargs) C++: please help me to correct the below code. using namespace boost::python; void cpp_method(object py_method, object kwargs) py_method(kwargs) Thanks to Dan Mašek for pointing this link Compiled on MacOS HighSierra and getting segmentation fault: g++ -std=c++11 -I/Library/Frameworks/Python.framework/Versions/2.7/Headers -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"foo.d" -MT"foo.o" -o "foo.o" foo.cpp g++ -L/usr/local/lib -L/Library/Frameworks/Python.framework/Versions/2.7/ -shared -o foo.so ./foo.o -lboost_python27 -lPython $ python Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import foo &gt;&gt;&gt; dir(foo) ['__doc__', '__file__', '__name__', '__package__', 'cpp_method'] &gt;&gt;&gt; def py_method(**kwargs): ... print 'from py_method' ... print kwargs ... &gt;&gt;&gt; kwargs = {'arg1': 1, 'arg2': 2} &gt;&gt;&gt; foo.cpp_method(py_method, kwargs) Segmentation fault: 11 Process: Python [22790] Path: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 2.7.14 (2.7.14) Code Type: X86-64 (Native) Parent Process: bash [368] Responsible: Python [22790] User ID: 501 Date/Time: 2018-10-04 16:54:51.618 -0700 OS Version: Mac OS X 10.13.6 (17G65) Report Version: 12 Anonymous UUID: 3A7BC812-2E65-69A4-936B-21E5CE648BCF Sleep/Wake UUID: E32B82BD-2B4C-4220-A9C2-F71FF57DDA56 Time Awake Since Boot: 580000 seconds Time Since Wake: 2700 seconds System Integrity Protection: disabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EX…
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52799027
tagged with: pybind11
has title: how to pass python method and kwargs to boost python c++ function and call
has comment: http://stackoverflow.com/comment/92207663
has comment: http://stackoverflow.com/comment/92242228
tagged with: boost-python
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92207451
favorite count: 0
has comment: http://stackoverflow.com/comment/92190232
has comment: http://stackoverflow.com/comment/92207337
type: UnansweredQuestion
tagged with: python
tagged with: c++
linked to: http://stackoverflow.com/q/6500755

http://stackoverflow.com/comment/95794051
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52545003
type: Comment
has text: Ali, can you look at `https://stackoverflow.com/questions/54493277/dynamic-filtering-a-pyspark-dataframe` ? I have not posted it, but I am curious as to how can we solve this using dynamic `lead` or some other method. Thanks for your consideration.

http://stackoverflow.com/q/52535552
has comment: http://stackoverflow.com/comment/92010524
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92010510
favorite count: 0
has comment: http://stackoverflow.com/comment/92010565
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/92010399
has comment: http://stackoverflow.com/comment/92010588
has answer: http://stackoverflow.com/a/52537518
has comment: http://stackoverflow.com/comment/92010596
has comment: http://stackoverflow.com/comment/92010558
has comment: http://stackoverflow.com/comment/92010912
tagged with: django
upvote count: 1
type: Question
has title: How to store csv file to database in django?
has body: In my project I want to enter 300 students every year. so it is not possible using add student form.So I want to create functionality for bulk data entry using csv or excel file. I have tried many things related to this but can't get solution. ** models.py ** class AddStudent(models.Model): enrollment_no = models.BigIntegerField(primary_key=True) student_name = models.CharField(max_length=500,null=True) gender = models.CharField(max_length=1,choices=GENDER_CHOICES) course = models.ForeignKey(CourseMaster, on_delete=models.DO_NOTHING, null=True) category= models.ForeignKey(CatMaster, on_delete=models.DO_NOTHING, null=True) admission_year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) college = models.ForeignKey(CollegeMaster, on_delete=models.DO_NOTHING, null=True) branch = models.ForeignKey(BranchMaster,on_delete=models.DO_NOTHING, null=True) current_semester = models.IntegerField(null=True) address = models.CharField(max_length=1000,null=True) city = models.CharField(max_length=100,null=True) district = models.CharField(max_length=100,null=True) state = models.CharField(max_length=100,null=True) student_contact = models.BigIntegerField() parent_contact = models.BigIntegerField() This is my models.py file and I want to store following fields through csv file. some fields are foreign key related to another models. so how to solve this? ** Views.py ** def upload_csv(request): data = {} if "GET" == request.method: return render(request, "add_student/bulk.html", data) # if not GET, then proceed try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("add_student:upload_csv")) #if file is too large, return if csv_file.multiple_chunks(): messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) return HttpResponseRedirect(reverse("add_student:upload_csv")) file_data = csv_file.read().dec…
score: 1
tagged with: database

pip
tags question: http://stackoverflow.com/q/52488937
tags question: http://stackoverflow.com/q/52447224
tags question: http://stackoverflow.com/q/52492082
tags question: http://stackoverflow.com/q/52478788
tags question: http://stackoverflow.com/q/52569794
tags question: http://stackoverflow.com/q/52528475
tags question: http://stackoverflow.com/q/52559906
tags question: http://stackoverflow.com/q/52586723
tags question: http://stackoverflow.com/q/52500777
tags question: http://stackoverflow.com/q/52466227
tags question: http://stackoverflow.com/q/52469743
tags question: http://stackoverflow.com/q/52441790
tags question: http://stackoverflow.com/q/52499752
tags question: http://stackoverflow.com/q/52470651
tags question: http://stackoverflow.com/q/52527774
tags question: http://stackoverflow.com/q/52580658
tag name: pip
tags question: http://stackoverflow.com/q/52495550
tags question: http://stackoverflow.com/q/52507260
tags question: http://stackoverflow.com/q/52476302
tags question: http://stackoverflow.com/q/52433549
tags question: http://stackoverflow.com/q/52466343
tags question: http://stackoverflow.com/q/52459457
tags question: http://stackoverflow.com/q/52518336
tags question: http://stackoverflow.com/q/52578131
tags question: http://stackoverflow.com/q/52489246
tags question: http://stackoverflow.com/q/52524463
tags question: http://stackoverflow.com/q/52485828
tags question: http://stackoverflow.com/q/52574514
tags question: http://stackoverflow.com/q/52484796
tags question: http://stackoverflow.com/q/52474931
tags question: http://stackoverflow.com/q/52478149
tags question: http://stackoverflow.com/q/52566285
tags question: http://stackoverflow.com/q/52456379
tags question: http://stackoverflow.com/q/52517407
tags question: http://stackoverflow.com/q/52460484
type: Tag
tags question: http://stackoverflow.com/q/52460652
tags question: http://stackoverflow.com/q/52582563
tags question: http://stackoverflow.com/q/52510275
tags question: http://stackoverflow.com/q/52458326
tags question: http://stackoverflow.com/q/52546251
tags question: http://stackoverflow.com/q/52536132
tags question: http://stackoverflow.com/q/52505470
tags question: http://stackoverflow.com/q/52450285
tags question: http://stackoverflow.com/q/52530297
tags question: http://stackoverflow.com/q/52535386
tags question: http://stackoverflow.com/q/52431707
tags question: http://stackoverflow.com/q/52535464
tags question: http://stackoverflow.com/q/52550241
tags question: http://stackoverflow.com/q/52445685
tags question: http://stackoverflow.com/q/52454310
tags question: http://stackoverflow.com/q/52560787
tags question: http://stackoverflow.com/q/52486985
tags question: http://stackoverflow.com/q/52434321
tags question: http://stackoverflow.com/q/52513626
tags question: http://stackoverflow.com/q/52560819
tags question: http://stackoverflow.com/q/52551595
tags question: http://stackoverflow.com/q/52527203
tags question: http://stackoverflow.com/q/52505649

http://stackoverflow.com/a/64419491
score: 1
answers question: http://stackoverflow.com/q/52534658
has comment: http://stackoverflow.com/comment/116010855
upvote count: 1
type: Answer
has body: As Nico and jay have stated you need to check the logs to see the details of the error. As you might use different systems, you can specify the path where the log is stored (i.e. "/tmp/geckodriver.log"). from selenium import webdriver firefox_options = webdriver.firefox.webdriver.Options() driver = webdriver.Firefox(log_path="/tmp/geckodriver.log", options=firefox_options) In my particular case, what the log said was: Error: no DISPLAY environment variable specified That was resolved adding in the options the headless mode before starting the driver. With the line: firefox_options.set_headless()
downvote count: 0

http://stackoverflow.com/a/53956051
answers question: http://stackoverflow.com/q/52558382
type: Answer
downvote count: 1
score: -1
has body: Try add codes: import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) and modify your codes {'loss': loss_to_log} to {'loss': loss_to_log.name}
upvote count: 0

http://stackoverflow.com/q/52562969
score: 2
tagged with: uwsgi
type: Question
has answer: http://stackoverflow.com/a/52572020
answer count: 1
downvote count: 0
tagged with: flask
has body: I have very simple application with two resources leveraging the Eve framework, which is in turn based on Flask. TL;DR: The built in WSGI works fine, but uWSGI is not receiving content from the script. Am I configuring the WSGI correctly to communicate with Eve, or do I need to modify the default Flask configuration? Eve I manage everything (at the moment) through a single main.py which looks like this: ## main.py from eve import Eve from settings import these_settings def post_post_callback(): ... def post_get_callback(): ... # def main(): # `-&gt; throws TypeError, main() expects exactly 0 arguments def main(*args, **kwargs): app = Eve(settings=these_settings) app.on_post_POST += post_post_callback app.on_post_GET += post_get_callback return app def serve(): app = main() app.run() The built-in WSGI works just fine without *args, **kwargs on main(). uWSGI The configuration for uWSGI has been taken from here with modification only for a virtual environment, log, and module and callable: [uwsgi] http = 127.0.0.1:5000 module = main callable = main virtualenv = /Users/me/.local/share/virtualenvs/my_app-qtX0KE_c processes = 4 enable-threads = true threads = 2 logto = uwsgi.log I have disabled and enabled threading with no success in either direction. Logs and Responses From the uWSGI logs: *** Starting uWSGI 2.0.17.1 (64bit) on [Fri Sep 28 15:29:28 2018] *** compiled with version: 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.2) on 27 September 2018 19:43:49 os: Darwin-17.7.0 Darwin Kernel Version 17.7.0: Thu Jun 21 22:53:14 PDT 2018; root:xnu-4570.71.2~1/RELEASE_X86_64 nodename: GVOMB0036.local machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 4 current working directory: /Users/me/my_app detected binary path: /usr/local/bin/uwsgi your processes number limit is 1418 your memory page size is 4096 bytes detected max file descriptor number: 256 lock engine: OSX spinlocks thunder lock: disabled (you can enable it with --thunder-lock) uW…
tagged with: eve
accepted answer: http://stackoverflow.com/a/52572020
favorite count: 0
upvote count: 2
has title: Eve (Flask) app responds with no content to uWSGI
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52578602
possible better answer: http://stackoverflow.com/a/63317054
accepted answer: http://stackoverflow.com/a/52582104
score: 6
tagged with: python
has title: How does a Python recursive function works for tri_recursion function?
tagged with: recursion
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52582104
has body: I'm new to Python, I found the below recursive program being tough to follow. While debugging the program I could find that it goes through recursion and the value of k decrements -1 every time we recurse. At one point k is -1 and the compiler moves to the else part and returns 0. Finally, the k value turns out to be 1, how does this happen? def tri_recursion(k): if(k>0): result = k+tri_recursion(k-1) print(result) else: result = 0 return result print("\n\nRecursion Example Results") tri_recursion(6) And the output: Recursion Example Results 1 3 6 10 15 21
type: Question
has comment: http://stackoverflow.com/comment/92092795
has answer: http://stackoverflow.com/a/63317054
upvote count: 6
has comment: http://stackoverflow.com/comment/99922518
has comment: http://stackoverflow.com/comment/92092830
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/91844437
score: 0
has text: @yorodm, thank you very much! It helped, I got another error)
type: Comment
comment on: http://stackoverflow.com/q/52450435
type: QuestionComment

http://stackoverflow.com/q/52452155
upvote count: 3
accepted answer: http://stackoverflow.com/a/52458807
has title: Should OpenCV Python Canny edge detection be giving me very different results depending on image size?
tagged with: canny-operator
tagged with: image-processing
answer count: 1
has comment: http://stackoverflow.com/comment/91848017
has comment: http://stackoverflow.com/comment/91848662
type: AnsweredQuestion
score: 3
has body: I am importing an image from a video frame, using cv2.resize() to enlarge the image by 4X, and then using Canny edge detection to help remove some noise before doing some object tracking. However Canny edge detection kept giving me a black image. After much testing I found that using cv2.resize() to reduce the image size to 1/4th before Canny edge detection gave me the result I was hoping for. Reducing image size to a 1/3rd also gave me a much better result but had fewer edges than the 1/4th reduction, and scaling down the image to 1/16th gave more edges than scaling to 1/4th. Why would this be happening? Actually while writing this question I was resizing the unscaled result and I found that calling namedWindow and cv.WINDOW_NORMAL also improved it. I realize I can simply rescale down, run Canny detection, and then enlarge the result of the Canny edge detection and do my object tracking, but this is baffling me and knowing why this is happening would be of interest to myself and I think to others as well. Nothing I could find in the opencv docs suggested a dependence of the Canny algorithm on image size. See images below, all generated by output = cv2.Canny(input, 30, 50): Unscaled (improved by using cv.WINDOW_NORMAL) https://i.sstatic.net/y4CCA.png 1/4 Reduced Before Canny Detection https://i.sstatic.net/YkX0t.png 1/3 Reduced Before Canny Detection https://i.sstatic.net/tGtn4.png 1/16 Reduced before Canny Detection https://i.sstatic.net/4l7Qi.png
downvote count: 0
has answer: http://stackoverflow.com/a/52458807
favorite count: 0
tagged with: edge-detection
type: Question
tagged with: python
tagged with: opencv

http://stackoverflow.com/q/52472437
tagged with: python
has comment: http://stackoverflow.com/comment/91886704
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52472480
score: 0
accepted answer: http://stackoverflow.com/a/52472480
has body: I have a data frame as follows: orderid ordername 1 a 1 b 1 c 2 d 2 e 3 f I want to create a suborder_id column for each orderid. suborder_id 1 2 3 1 2 1 I used: def get_suborder_id(???) df['suborder_id'] = ???? return df df = df.groupby('orderid').apply(get_suborder_id) However, I am not particularly clear on how it actually works. Please help me understand on this!!!
answer count: 1
has comment: http://stackoverflow.com/comment/91886674
has title: Create a sub-group for each group

http://stackoverflow.com/q/52432681
score: 3
has title: DDPG (Actor-Critic) Runs Away to Min/Max Values
type: Question
has comment: http://stackoverflow.com/comment/91902873
favorite count: 0
upvote count: 3
tagged with: reinforcement-learning
has comment: http://stackoverflow.com/comment/113036614
has comment: http://stackoverflow.com/comment/120247232
has body: I'm hoping for some help with my DDPG algorithm. Everything runs and the Q values from the critic network are created correctly but the result for the action ends up pegged at either the maximum or minimum allowed value. Such behavior seems to imply that something is wrong with my gradient computations but I can't quite figure it out. For testing purposes I'm using a very simple input that the agent should be able to learn and to which I know the correct answer: state | action | reward A | 100 | 100 A | 100 | 100 A | 100 | 100 A | 100 | 100 A | 200 | 200 A | 200 | 0 A | 200 | 0 A | 200 | 0 Since 200 is accepted once it has an expected value of 50 reward while 100 is accepted every time, meaning that it has an expected value of 100 reward. Thus, given that the state is the same, the result should always be 100. I should point out that future rewards are currently being ignored - this is a session-maximizing model only. The code is a bit long so I've edited out that parts that are irrelevant: def build_actor_net(s, scope, trainable,a_dim,act_max,act_min,features): with tf.variable_scope(scope): s = tf.feature_column.input_layer(features=features, feature_columns=s) init_w = tf.random_normal_initializer(0., 0.003) init_b = tf.constant_initializer(0.1) regularizer = tf.contrib.layers.l2_regularizer(scale=0.01) net = tf.layers.batch_normalization(s,fused=True) net = tf.layers.dense(net, 400, activation=tf.nn.relu,kernel_initializer=init_w, bias_initializer=init_b, name='l1',trainable=trainable,kernel_regularizer=regularizer) net = tf.layers.batch_normalization(net,fused=True) net = tf.layers.dense(net, 300, activation=tf.nn.relu,kernel_initializer=init_w, bias_initializer=init_b, name='l2',trainable=trainable,kernel_regularizer=regularizer) with tf.variable_scope('actor_action'): actions = tf.layers.dense(net, a_dim, activation=tf.nn.sigmoid,name='actions', trainable=trainable) scaled_a = tf.add(tf.multiply(actions,tf.subtract(act_max,act_min)), act_min, name='scaled_a')…
tagged with: python
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/114412564
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91871187

http://stackoverflow.com/comment/91814028
comment on: http://stackoverflow.com/a/52435278
type: Comment
has text: @RustyShackleford It does, No?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91877939
comment on: http://stackoverflow.com/q/52468068
score: 1
has text: Please paste your code here as text, not as an image
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52528158
has title: sqlite3: using two columns in a row to make a calculation
score: 0
has body: Image of the database I am working with... I am currently practicing with a database of NBA players. Related fields include name, active, and games. I am trying to create a temporary table containing name and games_per_year (active/games). Firstly, I filtered the original database to players with 11+ active years, which I have successfully completed. Now I am unsure how to create the temporary table consisting of name and games_per_year. Ultimately, I want to order this temp table by games_per_year and return the top 6 player names. Here is my attempt at coding below. As you can see, I am a bit lost... def most_games_per_year_for_veterans(): """Top 6 players that are &gt; 10 years active, that have the highest # games / year""" player_list = cur.execute("SELECT name, active, games FROM players WHERE active &gt; 10").fetchall() conn.execute('''CREATE TABLE IF NOT EXISTS active_vets (name TEXT, games_per_year REAL)''') for player in player_list: # Create a tuple? Just a guess... player = (player[0], player[2]/ player[1]) cur.executemany('INSERT INTO active_vets VALUES (?,?)', player) Critique is welcome, if you have any resources that have helped you in the past, I would love to read them. I have found it difficult to find the answers I need online.
tagged with: sqlite
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91997383
has comment: http://stackoverflow.com/comment/91996024
type: Question

http://stackoverflow.com/q/52471194
upvote count: 1
answer count: 1
favorite count: 0
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/52471311
has body: I need help manipulating values in an XML file with Python. The XML looks like this, but with even more plants: Bloodroot Sanguinaria canadensis 4 Mostly Shady 2.44 031599 Columbine Aquilegia canadensis 3 Mostly Shady 9.37 030699 Marsh Marigold Caltha palustris 4 Mostly Sunny 6.81 051799 I need to be able to change the value based on the value. I have this so far: if tree.find('.//COMMON').text == 'Bloodroot': tree.find('.//PRICE').text = '3.50' This code works, but that's only because it's the first block. If I do this nothing happens: if tree.find('.//COMMON').text == 'Columbine': tree.find('.//PRICE').text = '3.50' Can someone point me the right direction here? How do I change the price values for all the plants based on the 'COMMON' value. I've also tried some different things with looping through the xml file with no luck. Thanks!
has title: Manipulating XML with Python
has answer: http://stackoverflow.com/a/52471311

http://stackoverflow.com/a/52441054
type: Answer
accepted answer of: http://stackoverflow.com/q/52440848
answers question: http://stackoverflow.com/q/52440848
score: 0
has comment: http://stackoverflow.com/comment/91826332
has body: Pandas has .iloc for accessing rows by row number. You can get the current row number using enumerate: for e, (index, row) in enumerate(f.iterrows()): prev = f.iloc[e - 1] current = row Warning: During the first iteration (i.e. when e == 0), f.iloc[e - 1] will get you the last row of of the data frame.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91825456

http://stackoverflow.com/comment/92035055
type: AnswerComment
has text: This is not my query. I can provide excel file path in python. But I don't know how to pass this excel input file path to vbscript. This excel input file will actually be used by vbscript and I am just providing it's path in python code.
comment on: http://stackoverflow.com/a/52547854
type: Comment
score: 0

http://stackoverflow.com/q/52546519
has comment: http://stackoverflow.com/comment/92034608
tagged with: python
has body: I have more than 6000 XML want to parse and save as csv (or anything else for storage). I need to perform JOIN for each XML to join them to big dataframe. The problem is the process takes so long and uses too many memory. I am wondering would sql can solve the problem? faster and less memory consumption? def get_data(lst): results = pd.DataFrame() errors = [] for data in lst: try: df = parseXML_Annual(data) try: results = results.join(df, how = "outer") except: results = df except: errors.append(data) return results, errors results, errors = get_data(lst_result)
type: AnsweredQuestion
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/92053571
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92034992
has answer: http://stackoverflow.com/a/52581308
tagged with: database
has comment: http://stackoverflow.com/comment/92053222
accepted answer: http://stackoverflow.com/a/52581308
tagged with: pandas
tagged with: sql
answer count: 1
has comment: http://stackoverflow.com/comment/92040798
favorite count: 0
has comment: http://stackoverflow.com/comment/92035661
has comment: http://stackoverflow.com/comment/92041349
has title: Is an SQL database more memory/performance efficient than a large Pandas dataframe?
has comment: http://stackoverflow.com/comment/92070606

http://stackoverflow.com/q/52437002
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52446517
has title: Incorrect FFT of Gaussian kernel
score: 2
favorite count: 0
tagged with: fft
has body: I'm trying generate the FFT of a Gaussian kernel to use in later filtering. My understanding is that the FFT of a Gaussian kernel should yield a magnitude that is visually similar to the original intensity image. Here's what I'm getting, Here's a snippet that should reproduce this image. import numpy as np import cv2 from matplotlib import pyplot as plt ksize = 50 ksize = ksize*2+1 sigma = 15 fil = cv2.getGaussianKernel(ksize,0) fil = fil * fil.T fil_fft = cv2.dft(np.float32(fil),flags = cv2.DFT_COMPLEX_OUTPUT) fil_shift = np.fft.fftshift(fil_fft) magnitude_fil = 20*np.log(cv2.magnitude(fil_shift[:,:,0],fil_shift[:,:,1])) plt.subplot(131),plt.imshow(fil) plt.title('Input Image'), plt.xticks([]), plt.yticks([]) plt.subplot(132),plt.imshow(magnitude_fil) plt.title('FFT (Magnitude)'), plt.xticks([]), plt.yticks([]) plt.show() Any ideas as to why I'm getting this t-shaped response would be great.
type: Question
answer count: 2
tagged with: python
tagged with: opencv
upvote count: 3
has answer: http://stackoverflow.com/a/52439154
tagged with: image-processing
downvote count: 1
tagged with: filtering

http://stackoverflow.com/q/52583321
tagged with: python
has body: menu_items = ["French fries", "1/4 pound burger", "1/4 pound chesseburger", "1/2 pound burger", "1/2 pound cheeseburger", "Medium pizza", "Meidum pizza with extra toppings", "Large pizza", "Large pizza with extra toppings", "Garlic bread"] menu_prices = ["$2.00", "$5.00", "$5.55", "$7.00", "$7.50", "$9.00", "$11.00", "$12.00", "$14.50", "$4.50"] menu_codes = ["ff", "bb", "ccb", "vb", "vcb", "mp", "mpx", "lp", "lpx", "gb"] order = input(str("Write the item code of the food you wish to buy: ")) quantity = input(int("How many units of the previous food do want? ")) if order == "ff" or "bb" or "ccb" or "vb" or "vcb" or "mp" or "mpx" or "lp" or "lpx" or "gb": print("The item code was inputted correctly") else: print("The item code was inputted incorrectly") if quantity == (0 &lt; 100): print("Quantity entered is inside acceptable range") else: print("Quantity entered is out of range") This part is the list of the code, it is supposed to be the menu of a restaurant. The user should be able to input only items that are in the list (menu_codes) and any other value entered should be denied. And the quantity should only be between 1-100, and anything different should not be allowed. But for some reason, my "while" loop doesn't work, and it prints always the same thing, here is an example of the output of my code. Write the item code of the food you wish to buy: this is not on the list How many units of the previous food do want? 56 The item code was inputted correctly Quantity entered is out of range
possible better answer: http://stackoverflow.com/a/52583386
type: AnsweredQuestion
has title: How can i check if the user has entered a valid value? And how can i then append this value to a list if it was entered correctly?
accepted answer: http://stackoverflow.com/a/52583447
linked to: http://stackoverflow.com/q/15112125
type: Question
has comment: http://stackoverflow.com/comment/92101715
has comment: http://stackoverflow.com/comment/92101744
has answer: http://stackoverflow.com/a/52583447
has answer: http://stackoverflow.com/a/52583386
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92101682
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/15112125
tagged with: while-loop
tagged with: input

http://stackoverflow.com/q/52467098
tagged with: masked-array
tagged with: masking
favorite count: 0
has answer: http://stackoverflow.com/a/52467153
has comment: http://stackoverflow.com/comment/91876370
has body: I have an ndarray. I need to mask any number less than 50 until the first number encountered is greater than 50. This should be done both at the beginning and at the end of a row. Right, when the first number encountered is >50, the masking should stop. One row looks like: [ 0 1 1 0 57 121 120 157 77 14 0 3 0 0 0 0 67 100 98 97 101 129 139 105 97 105 181 126 10 0 0] I want something like: [-- -- -- -- 57 121 120 157 77 14 0 3 0 0 0 0 67 100 98 97 101 129 139 105 97 97 105 181 126 -- -- --] The masking should stop right before 57 in the second line, and at 126 in the 4th last line. I have tried ma.masked_where, but it masks the 0s in between as well, which I don't want. So, if there a way to do this, or can you help me so that I can specify a range of indices, eg: [0:40] only which should be masked. I do not want to change the dimension of the array after it is masked. Also, the presence of -- wouldn't make a difference to my purpose.
tagged with: python
has comment: http://stackoverflow.com/comment/91876466
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/91876424
has comment: http://stackoverflow.com/comment/91876485
has comment: http://stackoverflow.com/comment/91876654
downvote count: 0
has title: Masking only a certain range of indices in numpy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91876494
has comment: http://stackoverflow.com/comment/91876126
tagged with: arrays
accepted answer: http://stackoverflow.com/a/52467153
upvote count: 2
has comment: http://stackoverflow.com/comment/91876147
has comment: http://stackoverflow.com/comment/91876006
answer count: 1
has comment: http://stackoverflow.com/comment/91876190
has comment: http://stackoverflow.com/comment/91876257

http://stackoverflow.com/q/52561692
has comment: http://stackoverflow.com/comment/92077771
has title: Kivy canvas.clear() not clearing the canvas
score: 0
has comment: http://stackoverflow.com/comment/92062094
favorite count: 0
tagged with: kivy-language
answer count: 0
has comment: http://stackoverflow.com/comment/92064516
type: UnansweredQuestion
has body: I have followed the widget tutorial for Kivy, but I cannot get the canvas to clear after painting (from their 'a simple paint app' tutorial), unless I resize the window after pressing the clear button. Please help. I am using kivy v1.10.1 and python v3.7.0. on windows 10 64-bit OS. Further, a widget in scatter mode leaves a trace when you drag to a new position, this also clears when resizing the window. See code below: from random import random from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.graphics import Color, Ellipse, Line class MyPaintWidget(Widget): def on_touch_down(self, touch): color = (random(), 1, 1) with self.canvas: Color(*color, mode='hsv') d = 30. Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d)) touch.ud['line'] = Line(points=(touch.x, touch.y)) def on_touch_move(self, touch): touch.ud['line'].points += [touch.x, touch.y] class MyPaintApp(App): def build(self): parent = Widget() self.painter = MyPaintWidget() clearbtn = Button(text='Clear') clearbtn.bind(on_release=self.clear_canvas) parent.add_widget(self.painter) parent.add_widget(clearbtn) return parent def clear_canvas(self, obj): self.painter.canvas.clear() if __name__ == '__main__': MyPaintApp().run()
upvote count: 1
tagged with: python
tagged with: kivy
downvote count: 1
has comment: http://stackoverflow.com/comment/92064600
type: Question
has comment: http://stackoverflow.com/comment/92512206

http://stackoverflow.com/a/52572261
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52572169
downvote count: 0
answers question: http://stackoverflow.com/q/52572169
score: 4
type: AcceptedAnswer
type: Answer
has body: how about when we don't know the number of lists in advance? You can use itertools.product in this case, assuming you have a container lists holding your arbitrary number of lists. Demo: &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; &gt;&gt;&gt; lists = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] &gt;&gt;&gt; for value in product(*lists): ... print(value) ... (1, 1, 1) (1, 1, 2) (1, 1, 3) (1, 2, 1) (1, 2, 2) (1, 2, 3) (1, 3, 1) (1, 3, 2) (1, 3, 3) (2, 1, 1) (2, 1, 2) (2, 1, 3) (2, 2, 1) (2, 2, 2) (2, 2, 3) (2, 3, 1) (2, 3, 2) (2, 3, 3) (3, 1, 1) (3, 1, 2) (3, 1, 3) (3, 2, 1) (3, 2, 2) (3, 2, 3) (3, 3, 1) (3, 3, 2) (3, 3, 3)

http://stackoverflow.com/comment/92053580
type: Comment
has text: @chepner, That was patently clear in my previous comment. It may be useful for OP to delve further, e.g. the [CPython implementation](https://stackoverflow.com/a/30100743/9209546).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52557195

http://stackoverflow.com/comment/91971576
type: Comment
has text: sorry i wasnt clear.. i need to do it using python. thanks for the answers anyways, i figured something out
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52493713

http://stackoverflow.com/a/52694791
score: 0
type: AcceptedAnswer
type: Answer
has body: So to iterate over all the batches, for a dataset size of 100k and a batch size of 32 (3125 iterations), I just had to do: def body(sess, batch, arr): val = sess.run(batch) def getActivations(sess,layer,stimuli,labels): units = sess.run(layer,feed_dict={"Placeholder:0": np.reshape(stimuli,[32,64,64,3]), keep_prob:1.0}) return units try: res = getActivations(sess,"model_X/logits:0",val) arr = np.append(arr, np.reshape(res,[32,1024]), axis=0) except tf.errors.OutOfRangeError: print("End of dataset") return arr, pred with tf.Session() as sess: load_graph(sess) initialize_iterator(sess, iterator, X_train) next_x = iterator.get_next() arr = np.empty((0,2048), int) for i in range(0,3125): arr = body(sess, next_x, arr)
accepted answer of: http://stackoverflow.com/q/52583219
answers question: http://stackoverflow.com/q/52583219

http://stackoverflow.com/comment/108293928
type: QuestionComment
score: 0
has text: Putting a version check is fine. My question asks 'what is recommended'. Is my current solution fine? does it go against community/industry norms of packaging? I'm not specifically trying to fix my code. I'm trying to get a sense of what should go into setup.py and what should be avoided. The setuptools documentation doesn't really go into _this_ kind of thing (presumably because it's not really come up before).
comment on: http://stackoverflow.com/q/52540693
type: Comment

http://stackoverflow.com/q/52451260
tagged with: server
tagged with: ubuntu-14.04
linked to: http://stackoverflow.com/q/7221577
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52536230
linked to: http://stackoverflow.com/q/48996494
tagged with: client
type: UnansweredQuestion
tagged with: python
has body: All, I come from the microcontroller world (pure "C"), and this my first real project using python and embedded linux (Nanopi Neo). Apologies if the question is poorly worded. I am using a Nanopi Neo board with an Ubuntu distro (16.04.5 LTS). I currently use two interfaces: an wired ethernet connection (eth0) and a wifi wireless connection (wlan0). Both interfaces work, I can see both IP addresses because there is an OLED screen on the board. I would like to associate a TCP server with the wired interface (eth0), and an HTTP client with the wifi interface (wlan0). A field technician will connect to the server on the Nanopi in order to setup the credentials for the wifi. Once the credentials have been received, the field technician will disconnect the wired connection, and the HTTP client on the Nanopi will connect to the wifi and it will send information to a remote server. My questions are the following: How do I associate the HTTP client with wlan0 and the TCP server with eth0? Is it possible? How do I write code so that the two tasks (the server and the client) run at the same time (I guess in two separate threads)? I don't need the answer (even though that would be nice), but useful links. My searches for "interface ", "client/server", "concurrent" brought up all the wrong information/examples ... Thank you for your time and assistance. Grazie e ciao, Vincenzo ======= EDIT 1 ======= I have not had a chance to try it, but the following StackOverflow post: How to bind socket to an interface in python (socket.SO_BINDTODEVICE missing) seems to have relevant/useful information
has title: Ubuntu + Python: HTTP Client on wlan0 and TCP server on eth0
type: Question
tagged with: embedded-linux

http://stackoverflow.com/a/52481915
accepted answer of: http://stackoverflow.com/q/52481711
answers question: http://stackoverflow.com/q/52481711
has comment: http://stackoverflow.com/comment/91905400
has comment: http://stackoverflow.com/comment/91905551
upvote count: 4
has comment: http://stackoverflow.com/comment/131880927
type: AcceptedAnswer
downvote count: 0
score: 4
has body: You can use the following syntax to denote that you want the formatting in two decimal points. - You can read more here. {your_calculation:.2%} The .2 in this case denotes that you want the formatting in two decimal points. If you want to increase or decrease the decimal points you can adjust accordingly.
type: Answer

ubuntu
tags question: http://stackoverflow.com/q/52536132
tags question: http://stackoverflow.com/q/52535386
tags question: http://stackoverflow.com/q/52500412
tags question: http://stackoverflow.com/q/52540682
tags question: http://stackoverflow.com/q/52431734
tags question: http://stackoverflow.com/q/52499573
tags question: http://stackoverflow.com/q/52586324
tags question: http://stackoverflow.com/q/52510375
tags question: http://stackoverflow.com/q/52532872
tags question: http://stackoverflow.com/q/52527203
tags question: http://stackoverflow.com/q/52466638
tags question: http://stackoverflow.com/q/52472063
tag name: ubuntu
tags question: http://stackoverflow.com/q/52511704
tags question: http://stackoverflow.com/q/52446369
tags question: http://stackoverflow.com/q/52498339
type: Tag
tags question: http://stackoverflow.com/q/52506837
tags question: http://stackoverflow.com/q/52495742
tags question: http://stackoverflow.com/q/52572007

http://stackoverflow.com/q/52465642
has comment: http://stackoverflow.com/comment/91873664
has title: how to download video by select by tag with BeautifulSup
score: 0
has comment: http://stackoverflow.com/comment/91873027
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91873549
has comment: http://stackoverflow.com/comment/91874052
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91873600
has body: I try to download video from a site with a python script. The objective is to retrieve the video contained in the div tag '_2nCkU'. The answer of python is "none". Could you help me to see the problem please ? #!/usr/bin/python3 # -*-coding:Utf-8 -* import requests from bs4 import BeautifulSoup username = raw_input('Username : ') url = 'https://www.website.com/add/' + str(username) mozhdr = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'} requete = requests.get(url, headers=mozhdr) page = requete.content soup = BeautifulSoup(page, 'lxml') div = soup.find('div', {'id': '_2nCkU'}) print(div)
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91873926

http://stackoverflow.com/comment/91860034
score: 2
comment on: http://stackoverflow.com/q/52458921
type: Comment
type: QuestionComment
has text: Try using `arr.ravel()` (with parentheses, so the method is actually called) instead of `arr.ravel`?

http://stackoverflow.com/q/52549301
tagged with: keras
has comment: http://stackoverflow.com/comment/92044180
has body: I'm now working on a 3D multi-class semantic segmentation task with Keras. I know there is a way like weighted cross entropy that can increase the weight of each class. But I'm wondering is there a possible way to add different weights on different slices in one input volume? For example, let X denote the number of slices, and W is the weight. I'm now trying to set a dynamic weighted cross entropy as W=sqrt(X). But I don't how exactly to realize it in Keras. Could anyone help me?
has comment: http://stackoverflow.com/comment/92084127
has comment: http://stackoverflow.com/comment/92071078
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92081388
upvote count: 1
tagged with: python
has title: How to place different weights on different slices in one volume in 3D semantic segmantation of keras?
answer count: 0
score: 1
tagged with: tensorflow
type: Question
downvote count: 0

http://stackoverflow.com/q/52526353
answer count: 4
possible better answer: http://stackoverflow.com/a/53256058
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/53256058
has answer: http://stackoverflow.com/a/73967795
linked to: http://stackoverflow.com/q/52526506
has comment: http://stackoverflow.com/comment/130613945
score: 19
type: Question
has answer: http://stackoverflow.com/a/52572709
has comment: http://stackoverflow.com/comment/91992676
has body: Not sure if that's achievable. I want to fire an HTTP POST request from a script, but not wait for a response. Instead I want to return immediately. I tries something along these lines: #!/usr/bin/env python3 import asyncio import aiohttp async def fire(): await client.post('http://httpresponder.com/xyz') async def main(): asyncio.ensure_future(fire()) if __name__ == '__main__': loop = asyncio.get_event_loop() client = aiohttp.ClientSession(loop=loop) loop.run_until_complete(main()) The script returns immediately without errors, but the HTTP request never arrives at the destination. Can I fire the POST request, but not wait for response from the server, just terminate the moment the request is sent?
downvote count: 0
tagged with: asynchronous
accepted answer: http://stackoverflow.com/a/52572709
favorite count: 0
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/70486320
has title: Asynchronous Python - fire and forget HTTP request
tagged with: python

http://stackoverflow.com/comment/91899918
has text: Actually, I can reproduce this with `np`, will update the question for better readability.
comment on: http://stackoverflow.com/q/52479465
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52435160
tagged with: contains
tagged with: pandas
answer count: 1
has body: I have a data frame with String values in one of its columns. I want to iterate each row in the specified column to see if the value contains the word i'm looking for. If it does i want it to return int value 1 and if it doesn't then 0. df['2'] = df['Col2'].str.lower().str.contains('word') I can only get it to return True or False Col1 Col2 1 hello how are you 0 2 that is a big word 1 3 this word is bad 1 4 tonight tonight 0
tagged with: python
has comment: http://stackoverflow.com/comment/91813800
has answer: http://stackoverflow.com/a/52435525
accepted answer: http://stackoverflow.com/a/52435525
type: AnsweredQuestion
has title: Pandas contains condition returns True but want to return as 1 or 0 - creation of a series/dataframe column
type: Question
tagged with: if-statement
tagged with: dataframe
score: 0

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

http://stackoverflow.com/comment/92022296
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52541032
type: Comment
has text: id_i = int(all2[0]) , rate_i = request.form.get("rate", type=int) , i replaced both but it didnt work , same error - ERROR: syntax error at or near "user" --- what i should convert time_i to ?

linear-regression
tags question: http://stackoverflow.com/q/52582766
tags question: http://stackoverflow.com/q/52493079
tag name: linear-regression
tags question: http://stackoverflow.com/q/52541717
tags question: http://stackoverflow.com/q/52562664
type: Tag
tags question: http://stackoverflow.com/q/52517002
tags question: http://stackoverflow.com/q/52580995
tags question: http://stackoverflow.com/q/52536055
tags question: http://stackoverflow.com/q/52448156
tags question: http://stackoverflow.com/q/52555841
tags question: http://stackoverflow.com/q/52479544

http://stackoverflow.com/comment/91877284
type: Comment
comment on: http://stackoverflow.com/a/52466633
type: AnswerComment
score: 0
has text: @ΝικόλαοςΒέργος, see code sample in update. If this results in same then you are doing something else wrong.

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

http://stackoverflow.com/q/52582292
accepted answer: http://stackoverflow.com/a/52582328
duplicate of: http://stackoverflow.com/q/423379
tagged with: python
has answer: http://stackoverflow.com/a/52582328
type: AnsweredQuestion
tagged with: tkinter
type: Question
linked to: http://stackoverflow.com/q/9264763
has body: I am trying to create a stopwatch in tkinter and I need a counter variable in order to be able to do so. However, the issue is that the variable is acting as a local one even though I declared it as global. Here is my script: import tkinter as tk root = tk.Tk() global counter counter = 0 def go(): label.config(text=str(counter)) counter+=1 root.after(1000,go2) def go2(): label.config(text=str(counter)) counter+=1 root.after(1000,go) def stop(): label.config(text=str(0)) gobutt = tk.Button(text = "Go", command = lambda: go()) stopbutt = tk.Button(text = "Stop", command = lambda: go2()) gobutt.pack() stopbutt.pack() label = tk.Label(text = "0") label.pack() root.mainloop() Here is my error message: Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__ return self.func(*args) File "/Users/MinecraftMaster/Desktop/Python/Tests/TkinterTest/Tkinter Test.py", line 29, in &lt;lambda&gt; gobutt = tk.Button(text = "Go", command = lambda: go()) File "/Users/MinecraftMaster/Desktop/Python/Tests/TkinterTest/Tkinter Test.py", line 18, in go label.config(text=str(counter)) UnboundLocalError: local variable 'counter' referenced before assignment
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has title: Global Variable Acting as a Local Variable in Python Tkinter
favorite count: 0

http://stackoverflow.com/q/52505021
has comment: http://stackoverflow.com/comment/91950510
tagged with: operator-precedence
has comment: http://stackoverflow.com/comment/91950496
favorite count: 0
has title: Python operator precedence with augmented assignment
downvote count: 2
has comment: http://stackoverflow.com/comment/91950498
tagged with: augmented-assignment
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52505407
score: 7
has comment: http://stackoverflow.com/comment/91950505
has comment: http://stackoverflow.com/comment/91950542
answer count: 2
has body: It seems this question only answered for Java but I would like to know how it works in Python. So are these the same? a += b / 2 and a += (b / 2)
upvote count: 9
has answer: http://stackoverflow.com/a/52505407
has answer: http://stackoverflow.com/a/52505064
accepted answer: http://stackoverflow.com/a/52505064
tagged with: python

http://stackoverflow.com/comment/91826543
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52441642
has text: You can keep using your `for i in Primes:` loop. But instead of doing `i = 2`, use `break` to exit the inner loop, after you finish incrementing `Num` and printing stuff.

http://stackoverflow.com/q/52557685
has comment: http://stackoverflow.com/comment/92142068
has comment: http://stackoverflow.com/comment/92054843
type: Question
tagged with: python
has title: Store variables in a list in Python
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52557759
has answer: http://stackoverflow.com/a/52557759
has answer: http://stackoverflow.com/a/52558711
has body: I had this Python 2.7 code which queries the movement limits from a device: pan_low_limit = int(self.send_query("PN", 2)) pan_high_limit = int(self.send_query("PX", 2)) tilt_low_limit = int(self.send_query("TN", 2)) tilt_high_limit = int(self.send_query("TX", 2)) I thought I could write this nicer as: limits = [(pan_low_limit, "PN"), (pan_high_limit, "PX"), (tilt_low_limit, "TN"), (tilt_high_limit, "TX")] for v, c in limits: v = int(self.send_query(c, 2)) print("Result from {}: {}".format(c, v)) print(limits) print("tilt_low_limit: {}".format(tilt_low_limit)) Print statements are to find what's going on. When I run this, I get the following output (these four variables had been initialized with value 1 before this piece of code): Result from PN: -27067 Result from PX: 27067 Result from TN: -27999 Result from TX: 9333 [(1, 'PN'), (1, 'PX'), (1, 'TN'), (1,'TX')] tilt_low_limit: 1 PN: 1 I don't really get what's going on. It seems like the value of v in "v = int(self.send_query(c, 2))" is what I'd expect, but at the next line, these variables have the old values again?
has comment: http://stackoverflow.com/comment/92054158
linked to: http://stackoverflow.com/q/28228461
tagged with: python-2.7
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52558711

http://stackoverflow.com/q/52437701
tagged with: opencv
has comment: http://stackoverflow.com/comment/91927875
has title: OpenCV findcontour rectangle creation error
answer count: 0
has comment: http://stackoverflow.com/comment/91851358
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/91821049
type: Question
has comment: http://stackoverflow.com/comment/91868660
has body: x,y,w,h = cv2.boundingRect(ctr) leng = int(h*.9) pt1 = int(y + h // 2 - leng // 2) pt2 = int(x + w // 2 - leng // 2) roi = im_th[pt1-int(leng*0.6) : pt1+ int(leng*1.2) , pt2: pt2+leng] cv2.imwrite("C:\\Users\\kumar\\Desktop\\final year\\test_image\\"+str(idx)+".jpg",roi) cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,0),3) roi = roi/255 # Resize the image roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA) roi=roi*255 cv2.imwrite("C:\\Users\\kumar\\Desktop\\final year\\test_image\\after_resize_"+str(idx)+".jpg",roi) cv2.waitKey(0) while using this block of code to get cropped alphabets out of the image letters such as m and u are creating an error.
score: 0
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/91861203
comment on: http://stackoverflow.com/q/52459478
score: 0
type: QuestionComment
type: Comment
has text: This is the program that will run infinite times..whatever output is printed on python shell should be copied to a file. i want a code for that.

http://stackoverflow.com/q/52463599
upvote count: 1
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52463708
tagged with: dataframe
type: Question
tagged with: 3d
answer count: 1
downvote count: 0
has body: So I have the following 3D Pandas Dataframe, new: unique cat numerical c f b d a e 0 2 5 1 3 0 4 1 8 11 7 9 6 10 2 14 17 13 15 12 16 I want to find which 'shallower' column contains the 'deeper' column 'd', which would be 'cat'. I'm really new to Pandas but after staring at new.columns for a while: MultiIndex(levels=[['cat', 'numerical', 'unique'], ['a', 'b', 'c', 'd', 'e', 'f']], labels=[[2, 2, 0, 0, 1, 1], [2, 5, 1, 3, 0, 4]]) I finally figured this really seemingly long-winded, extremely nested, convoluted way of doing it, which does get me 'cat': print( new.columns.levels[0][\ new.columns.labels[0][\ pd.Index(new.columns.labels[1]).get_loc(\ pd.Index(new.columns.levels[1]).get_loc('d'))]] ) I'm basically getting the position of 'd' in the second array under levels (let's call it pos1), then finding the position (pos2) of that value (pos1) in the second array under labels, and then finding the value (val1) in the first array under 'labels' using that position (pos2), and finally finding what the column name is in the first array under 'levels' using the position val1. So my question is, is there a better, 'proper' way of doing all this? Thanks. P.S. on a separate note, all this is actually just so that I can search column 'd' without knowing which 'shallower' column it belongs to: row = (new.loc[new['cat']['d'] == 9]) such that I get: unique cat numerical c f b d a e 1 8 11 7 9 6 10 So if there was a way to do that, this whole question would be avoided.(I'm new to stack overflow too do I have to put this in a new question or smt)
has title: How to find the column that contains a particular sub-column/nested column in 3D-Pandas Dataframe
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52463708
favorite count: 0

http://stackoverflow.com/a/52559199
has body: You could use numpy, R, or MATLAB, or anything else that works with large matrices for this: Say you have a NxM matrix A, where N is len(string) and M is the number of strings. And say you have a string S you're trying to match. You could: Subtract the array version of S from A Take the the absolute value of all the elements of the result of (1) Sum the result of (2) along the axis of N Argsort the result of (3) to find the indexes of the strings that have the lowest distance to S.
score: 0
answers question: http://stackoverflow.com/q/52558975
type: Answer

http://stackoverflow.com/comment/91939650
comment on: http://stackoverflow.com/q/52499074
type: QuestionComment
has text: Which PHP version are you using? Please show your `json_encode()` code section.
score: 0
type: Comment

http://stackoverflow.com/q/52471426
has title: I'm having a hard time to bulk rename files using os.rename
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91884892
has comment: http://stackoverflow.com/comment/91884858
type: Question
has comment: http://stackoverflow.com/comment/91884876
has comment: http://stackoverflow.com/comment/91884793
score: 0
upvote count: 1
downvote count: 1
tagged with: python
has body: My code: import os videos = {} subtitles = {} files = [f for f in os.listdir('.') if os.path.isfile(f)] for file in files: if (file[-3:] == "ass" or file[-3:] == "srt"): episode = file.split('#')[1].split(' ')[0] subtitles[episode] = file if (file[-3:] == "mp4"): episode = str(int(file.split('ep')[1].split('.')[0])) videos[episode] = file i = 1 for sub in subtitles: try: extension = str(subtitles.get(str(i)))[-3:] video = str(videos.get(str(i))).split('.')[0]+"."+extension subtitle = str(subtitles.get(str(i))) print (subtitle + video) os.rename(subtitle, video) # &lt;---- i+= 1 except Exception as e: print ("Error: " + sub + " exception: " + str(e)) If I comment the line "os.rename(subtitle, video)", leaving only the print command, it prints all the file names normally, but if I don't comment it, all the file names become "None", giving me this error for every single file: NoneNone.one Error: 99 exception: [WinError 2] The system cannot find the file specified: 'None' -&gt; 'None.one'
has comment: http://stackoverflow.com/comment/91921017
favorite count: 0

http://stackoverflow.com/q/52502437
tagged with: indices
tagged with: indexing
has comment: http://stackoverflow.com/comment/91945540
has body: I have a numpy array of indeterminate size and I need to compare some indices being used to extract data. For example if start_index &gt; end_index I want an error to be thrown. However, sometimes the indices might be negative, most notably we might have end_index = -1 to represent the final element in the array. If I just straight up compared the indices and end_index was negative an error could be thrown incorrectly. My current solution is to check if start_index % array_length &gt; end_index % array_length. This does work, but I'm now having to think about everything using modular arithmetic. Does anyone know of a more efficient solution, perhaps a tool from numpy itself?
type: Question
tagged with: numpy
has title: Comparing Negative Indices in Numpy with Postive Indices
tagged with: modular-arithmetic
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91951709
answer count: 0
has comment: http://stackoverflow.com/comment/91946440
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91946020
has comment: http://stackoverflow.com/comment/91945807

http://stackoverflow.com/comment/91901090
type: Comment
score: 2
has text: Please edit your question to include an [mvce](https://stackoverflow.com/help/mcve).
type: QuestionComment
comment on: http://stackoverflow.com/q/52480036

http://stackoverflow.com/comment/93345194
comment on: http://stackoverflow.com/q/52555405
type: Comment
type: QuestionComment
score: 1
has text: Have you tried this one https://camelot-py.readthedocs.io/en/master/user/advanced.html looks like it will fit to your case @MehulVerma

http://stackoverflow.com/comment/91868123
has text: I constructed a coo_matrix from a dataframe object. \n
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52462960

http://stackoverflow.com/a/52583828
answers question: http://stackoverflow.com/q/52583674
upvote count: 1
has body: This is because \b matches the gap between K and -, a word and a non-word character. If you want to avoid matching - if it's preceded by a word you can use negative lookbehind instead: re.findall(r'[$€£]?(?:(?&lt;!\w)-)?\d+[\d,.]*\b', test) With your sample input, this returns: ['9', '111', '3,33'] Demo: https://regex101.com/r/A66C5W/1
score: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92124655

http://stackoverflow.com/q/52574748
answer count: 1
score: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52574766
type: Question
has body: I'm making a sample tornado application. For the first method, I'd like it to return the string "OK", instead of rendering a template. How would I do the following: class IndexHandler(tornado.web.RequestHandler): """Regular HTTP handler to serve the ping page""" def get(self): self.render('Hi') # expects template instead of string -- how to do string?
has title: Sample tornado web request
tagged with: tornado

http://stackoverflow.com/comment/91929321
score: 0
type: AnswerComment
type: Comment
has text: @deceze: really? is there any *language* feature that allows you to do this? Obviously there can be various work-arounds, but this is 3 times longer and harder to read than what the OP wants to avoid.
comment on: http://stackoverflow.com/a/52494329

http://stackoverflow.com/comment/92066283
type: AnswerComment
has text: @PaulDickinson It should work now. Mostly it's an exercise in clever reshaping/broadcasting.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52562874

http://stackoverflow.com/comment/91994336
has text: Questions are encouraged to provide an [MCVE](/help/mcve).
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52526017

http://stackoverflow.com/a/52455113
has body: You can use itemgetter: &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; values = ["shanya", 1.2, 1, False, "test", 2, 3.3, True, "3", "4.0"] &gt;&gt;&gt; itemgetter(0, -3)(values) ('shanya', True)
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52455077

http://stackoverflow.com/q/52478874
has answer: http://stackoverflow.com/a/52479257
accepted answer: http://stackoverflow.com/a/52479257
has comment: http://stackoverflow.com/comment/91899550
type: AnsweredQuestion
score: 1
tagged with: compression
has comment: http://stackoverflow.com/comment/91899198
has body: How can you decompress a string of text in Python 3, that has been compressed with gzip and converted to base 64? For example, the text: EgAAAB+LCAAAAAAABAALycgsVgCi4vzcVAWFktSKEgC9n1/fEgAAAA== Should convert to: This is some text The following C# code successfully does this: var gzBuffer = Convert.FromBase64String(compressedText); using (var ms = new MemoryStream()) { int msgLength = BitConverter.ToInt32(gzBuffer, 0); ms.Write(gzBuffer, 4, gzBuffer.Length - 4); var buffer = new byte[msgLength]; ms.Position = 0; using (var zip = new GZipStream(ms, CompressionMode.Decompress)) { zip.Read(buffer, 0, buffer.Length); } return Encoding.UTF8.GetString(buffer); }
type: Question
tagged with: gzip
upvote count: 2
tagged with: gzipstream
answer count: 1
downvote count: 1
has title: How to decompress text in Python that has been compressed with gzip?
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/92046067
score: 1
comment on: http://stackoverflow.com/q/52553011
type: Comment
type: QuestionComment
has text: It would be a good idea to define a class for the boost pads, because they need their own timers, rects and colors (or images). Do you already know how you can define a class and create objects?

http://stackoverflow.com/comment/91837282
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52447199
has text: If there are columns `e` and `f` then what's wrong with trying `columns=['a','b','c','d','e','f']`? The above answer by the way loops through the columns so you don't have to specify them manually. Give it a try and post a reproducible code if necessary
type: QuestionComment

http://stackoverflow.com/q/52519565
has answer: http://stackoverflow.com/a/52528150
has comment: http://stackoverflow.com/comment/91981161
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/91981191
favorite count: 0
tagged with: python-3.x
tagged with: bitbake
possible better answer: http://stackoverflow.com/a/52528150
accepted answer: http://stackoverflow.com/a/52538995
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: No Module named 'datetime' in python3 when creating a recipe for Yocto but datetime exists in python2.7
score: 1
has answer: http://stackoverflow.com/a/52538995
tagged with: yocto
has comment: http://stackoverflow.com/comment/91981406
type: Question
tagged with: embedded-linux
has body: host machine Debian 9.4 Server Yocto branch krogoth, BitBake Build Tool Core version 1.30.0 workflow tool devtool Requirements They should be available as python3.5 packages on the hardware I want to create recipes for: pynmea2 v1.7.1 influxdb-python v5.2.0 I use the following steps in my $BUILD_DIR: devtool add pynmea2 https://github.com/Knio/pynmea2/archive/v1.7.1.tar.gz devtool add influxdb-python https://github.com/influxdata/influxdb-python/archive/v5.2.0.tar.gz I get the recipes from the tools. I change the RDEPENDS_${PN} += "python-re" to RDEPENDS_${PN} += "${PYTHON_PN}-re" for all runtime dependencies and shift this information to their respective .inc files. The files are mentioned below in the Github Gist GitHub Gists Gists for pynmea2 and influxdb-python Image creation for local tests, I add these recipes from the workspace folder (created automatically by devtool) to the local.conf under `IMAGE_INSTALL_append = " influxdb-python pynmea2" and burn the image for the hardware. Board On the board, I run the python3 shell to see if I can import these packages. Here is the output from the shell: pynmea2: Python 3.5.1 (default, Sep 25 2018, 19:27:54) [GCC 5.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pynmea2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.5/site-packages/pynmea2/__init__.py", line 13, in &lt;module&gt; from .types import * File "/usr/lib/python3.5/site-packages/pynmea2/types/__init__.py", line 3, in &lt;module&gt; from .talker import * File "/usr/lib/python3.5/site-packages/pynmea2/types/talker.py", line 3, in &lt;module&gt; from ..nmea_utils import * File "/usr/lib/python3.5/site-packages/pynmea2/nmea_utils.py", line 2, in &lt;module&gt; import datetime ImportError: No module named 'datetime' influxdb-python: Python 3.5.1 (default, Sep 25 2018, 19:27:54) [GCC 5.3.0] on linux Type "help", "copyright", "credits" or "license" for…

http://stackoverflow.com/comment/119966359
score: 4
comment on: http://stackoverflow.com/a/62458882
type: AnswerComment
type: Comment
has text: Netron also supports horizontal layouts (see menu)

http://stackoverflow.com/a/52533406
has comment: http://stackoverflow.com/comment/92014211
has comment: http://stackoverflow.com/comment/92013117
score: 2
has body: You need to keep a list of tables rather than appending all of the information into a single list. Then you can use zip() to take a single header and table at a time to write it to your output CSV file. This is a better approach than trying to use range(). import time from os import getcwd from selenium.webdriver.firefox.options import Options from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup import pandas import time, re import csv import uuid class metEiren(): def __init__(self): print("hurray33") global downloadDir downloadDir = "" fp = webdriver.FirefoxProfile() fp.set_preference("browser.download.folderList", 2) fp.set_preference("browser.download.manager.showWhenStarting", False) fp.set_preference("browser.download.dir", downloadDir) fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv") options = Options() options.add_argument("--headless") global driver driver = webdriver.Firefox(firefox_profile=fp,firefox_options=options) driver.get("https://www.met.ie/climate/available-data/monthly-data") verificationErrors = [] accept_next_alert = True def scrape(self): driver.get("https://www.met.ie/climate/available-data/monthly-data") driver.execute_script("window.scrollTo(0, 1000)") wait = WebDriverWait(driver, 10) link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Sherkin Island"))) link.click() time.sleep(2) uFileName = str(uuid.uuid4()) filname = downloadDir + uFileName + ".csv" soup = BeautifulSoup(driver.page_source, 'html.parser') headerList = [] for h in soup.find_all('h3'): print(h.text) headerList.append(h.text.strip('\t')) tables = [] …
downvote count: 0
has comment: http://stackoverflow.com/comment/92013693
has comment: http://stackoverflow.com/comment/92013654
answers question: http://stackoverflow.com/q/52526729
accepted answer of: http://stackoverflow.com/q/52526729
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92013967
type: Answer

http://stackoverflow.com/q/52555918
tagged with: pytest
downvote count: 0
has comment: http://stackoverflow.com/comment/92052880
tagged with: pytest-django
has comment: http://stackoverflow.com/comment/92052610
type: Question
has comment: http://stackoverflow.com/comment/92052177
upvote count: 3
has answer: http://stackoverflow.com/a/52561386
accepted answer: http://stackoverflow.com/a/52561386
answer count: 1
has title: Flow control and Failed: Database access not allowed, use the "django_db".... Error
has comment: http://stackoverflow.com/comment/92052277
favorite count: 0
has body: I am running into some odd behavior with one of my celery tasks. def run_single_test(test_name_or_decorator): # get dict of test names, test paths test_dict = get_single_test_names() # check to see if test is in the dict if test_name_or_decorator not in test_dict: return 'The requested test could not be found.' for test_name, test_path in test_dict.items(): # if test name is valid run associated test if test_name == test_name_or_decorator: pytest.main(['-p', 'no:django','--json-report', test_path]) report = return_test_result_json('.report.json') report_id = str(uuid.uuid4()) test_run_data = TestResults.objects.create(name=report_id, data=report) return 'this is your test report: {}'.format(get_report(test_run_data.id)) This task will execute the pytest.main() command and run a test however when it goes to insert the .report.json into the Db with .create() I get the following error: Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. Now if I take all the functionality within the for test_name.... block simplify things and move it into its own function everything works: def run_single_test_path(): test_path = 'test_folder/test_file.py::TestClass::specific_test_name' pytest.main(['-p', 'no:django','--json-report', test_path]) report = return_test_result_json('.report.json') report_id = str(uuid.uuid4()) test_run_data = TestResults.objects.create(name=report_id, data=report) return 'this is your test report: {}'.format(get_report(test_run_data.id)) I get the expected return: "this is your test report: {'created': datetime.datetime(2018, 9, 27, 15, 51, 59, 297991, tzinfo=&lt;UTC&gt;), 'summary': {'total': 1, 'passed': 1}, 'exitcode': 0}" This behavior is not happening with my other tasks that use variations of the same pytest.main() and .create(). One other observation is if I run this task first and the Database access error is thrown all the other tasks will fail with the same error. My working theor…
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92052056
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/52463297
has comment: http://stackoverflow.com/comment/91868744
type: Answer
has comment: http://stackoverflow.com/comment/91868716
has body: import pandas as pd import numpy as np fruits = ["APPLE","BANANA","GRAPES","ORANGE"] prices = [80,45,60,50] fru_prices = list(zip(fruits,prices)) pd.DataFrame(data = fru_prices ,columns = ['fruits','prices']) --------------------------------------------------------------------- output : fruits prices 0 APPLE 80 1 BANANA 45 2 GRAPES 60 3 ORANGE 50 &gt; Python zip function takes iterable elements as input, and returns &gt; iterator. Now data will appear in column wise.
has comment: http://stackoverflow.com/comment/91868662
has comment: http://stackoverflow.com/comment/91868657
answers question: http://stackoverflow.com/q/52463202
has comment: http://stackoverflow.com/comment/91868626
score: 0

http://stackoverflow.com/comment/92105554
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52585220
type: Comment
has text: Is that not this part? # An optimal ordering: [2, 4, 16, 4, 20] # Num happy drivers: 3; If I missed something please let me know and I will update it

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

http://stackoverflow.com/comment/91974199
has text: Can you provide some context as to why you need that?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52517352

http://stackoverflow.com/q/52504622
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91991063
has comment: http://stackoverflow.com/comment/91991255
has comment: http://stackoverflow.com/comment/91949757
has comment: http://stackoverflow.com/comment/91980219
tagged with: numpy
has comment: http://stackoverflow.com/comment/91954520
has title: apply function to 2d slices of a multidimensional NumPy array
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/91949774
has comment: http://stackoverflow.com/comment/91990615
favorite count: 0
has body: I have 6D numpy array and I have a custom function that could be applied to a 2D array, the output is a 2D array of the same shape. I would like to iterate over all 2D arrays that are stored in the indexes 3 and 4, apply the custom function and return the 6D array with the shape of the original 6D array and with the data processed as described above with the custom function. I am currently using nested loops, but the process is awfully slow. Below is what I am currently doing (the size of the dimension 2 and 5 is 1, so no need to iterate over them). orig_array = np.reshape(np.zeros(2**4), (2, 2, 1, 2, 2, 1)) def custom_fun(array_2d): return array_2d + 1 out_array = np.copy(orig_array) for ind1 in range(orig_array.shape[0]): for ind2 in range(orig_array.shape[1]): out_array[ind1, ind2, 0, :, :, 0] = custom_fun(out_array[ind1, ind2, 0, :, :, 0]) I was wondering if there is a way to vectorize this procedure with the aim of speeding up the computation. I searched the NumPy documentation and found the function: np.apply_over_axes, however it does not seem to do what I would like.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91990788
has comment: http://stackoverflow.com/comment/91993519
answer count: 0
score: 1

http://stackoverflow.com/q/52575232
accepted answer: http://stackoverflow.com/a/52575320
has body: I have a list of people and I want to make all combinations of their teams (of 3) with each other. list_of_ppl = ['A','B','C','D','E','F'] What i need is: &gt;&gt;&gt; [['A','B','C'],['D','E','F']] &gt;&gt;&gt; [['A','B','D'],['C','E','F']] &gt;&gt;&gt; [['A','B','E'],['C','D','F']] &gt;&gt;&gt; [['A','B','F'],['C','D','E']] &gt;&gt;&gt; [['A','C','E'],['B','D','F']] &gt;&gt;&gt; and so on... Edit: The len(list_of_ppl) can be greater than 6 and can be a number that is not divisible by 3. I only want teams of 3 For eg: list_of_ppl = ['A','B','C','D','E','F','G'] &gt;&gt;&gt; [['A','B','C'],['D','E','F'],['G']] &gt;&gt;&gt; [['A','B','D'],['C','E','G'],['F']] &gt;&gt;&gt; [['A','B','D'],['C','F','G'],['E']] &gt;&gt;&gt; [['A','B','F'],['C','E','G'],['D']] &gt;&gt;&gt; [['A','E','G'],['B','D','F'],['C']] &gt;&gt;&gt; and so on...
has answer: http://stackoverflow.com/a/52575277
possible better answer: http://stackoverflow.com/a/52575281
score: 4
has answer: http://stackoverflow.com/a/52575281
has answer: http://stackoverflow.com/a/52575320
answer count: 3
upvote count: 4
favorite count: 0
has title: Get combinations of list without replacement in Python
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question

http://stackoverflow.com/comment/105502907
has text: In order for this to work, I had to use brackets instead of parentheses: data = pd.concat([data,pd.get_dummies(data.seniority)],1)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52431171

http://stackoverflow.com/a/53067691
has body: Problem is solved. this code is running on Python shell. I can connect my plc and can access data blocks and internal memories. The code is also running on spyder IDE just copy paste snap7.dll to the script folder of Anaconda (Since I have installed spyder through anaconda). Anways I can run my code on Spyder and Python shell both.
answers question: http://stackoverflow.com/q/52488082
score: 0
type: Answer

http://stackoverflow.com/q/52579189
has answer: http://stackoverflow.com/a/52579238
type: Question
tagged with: function
has comment: http://stackoverflow.com/comment/92093779
linked to: http://stackoverflow.com/q/592746
linked to: http://stackoverflow.com/q/544919
has comment: http://stackoverflow.com/comment/92093484
downvote count: 4
linked to: http://stackoverflow.com/q/18425225
upvote count: 0
duplicate of: http://stackoverflow.com/q/544919
answer count: 1
tagged with: string
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: How can I print the name of variables in Python?
has comment: http://stackoverflow.com/comment/92093505
score: -4
has body: I am trying to define the function which returns the name of variables. &gt;&gt;&gt; def function(x): ... return(str(x)) ... &gt;&gt;&gt; a = 1 &gt;&gt;&gt; function(a) '1' I want to define the following function. How can I define it? &gt;&gt;&gt; a = 1 &gt;&gt;&gt; function(a) a = 1

http://stackoverflow.com/comment/92076782
comment on: http://stackoverflow.com/a/52545974
has text: Right, my bad, you need to do .astype(int) or astype (float) in the first step.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52526909
score: 1
type: AcceptedAnswer
downvote count: 0
has body: You can use set.difference with range to find missing dates and then append a dataframe: # convert to datetime if not already converted df['asofdate'] = pd.to_datetime(df['asofdate']) # calculate missing years years = df['asofdate'].dt.year missing = set(range(years.min(), years.max())) - set(years) # append dataframe, sort and front-fill df = df.append(pd.DataFrame({'asofdate': pd.to_datetime(list(missing), format='%Y')}))\ .sort_values('asofdate')\ .ffill() print(df) asofdate port_id 1 2010-01-01 76.0 2 2010-04-01 43.0 3 2011-02-01 76.0 1 2012-01-01 76.0 4 2013-01-02 93.0 2 2014-01-01 93.0 3 2015-01-01 93.0 0 2016-01-01 93.0 5 2017-02-01 43.0
type: Answer
accepted answer of: http://stackoverflow.com/q/52526818
answers question: http://stackoverflow.com/q/52526818
has comment: http://stackoverflow.com/comment/91994891
upvote count: 1

http://stackoverflow.com/comment/92093630
comment on: http://stackoverflow.com/a/52579152
score: 0
type: AnswerComment
type: Comment
has text: yes it did. But now i changed the question...I just could have left it at it is and mark yours as correct though....

http://stackoverflow.com/q/52512761
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/52514843
has title: How to get user info with bot token
answer count: 1
downvote count: 0
tagged with: slack-api
favorite count: 0
has body: I am using python slack client to connect and send messages with a bot application. slc = SlackClient("BOT_USER_TOKEN") out = slc.api_call(method='users.profile.get', user='XXX') I am getting not_allowed_token_type error in output json. I am able to call: slc.api_call(method='chat.PostMessage',channel) Is there a way to get user email, name from slack API. previously I got the username from event messages. but now I am getting only user id so I am looking for a solution to fetch user info using that id.
accepted answer: http://stackoverflow.com/a/52514843
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91881564
comment on: http://stackoverflow.com/a/52468570
has text: That's for the *otherwise, do nothing* condition that you had in your post. You can take a look at the default argument in the documentation I linked
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92050360
score: 0
type: QuestionComment
has text: And this link does **Answer** your Question! Also without [mcve] this Question will put on **hold**.
type: Comment
comment on: http://stackoverflow.com/q/52555139

http://stackoverflow.com/comment/105406789
type: Comment
has text: I updated everything to its newest version, geckodriver is in the correct location on my computer (running ubuntu 19.04) and I am still getting the same error message as in the original question. Not sure what do to now
score: 7
type: AnswerComment
comment on: http://stackoverflow.com/a/52535654

http://stackoverflow.com/comment/91971912
score: 0
has text: Tensorflow is having support to display graphs `tf.Graph` . YOu can crosscheck the architecture using that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52516101

http://stackoverflow.com/comment/91897920
comment on: http://stackoverflow.com/q/52472531
score: 0
type: QuestionComment
type: Comment
has text: You could do this entirely with `np.exp`, using its `out` and `where` parameters.

http://stackoverflow.com/q/52559161
tagged with: python
accepted answer: http://stackoverflow.com/a/52559316
has comment: http://stackoverflow.com/comment/92057687
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92058535
has body: i am trying to scrape the contents of a website's meta description. example: &lt;meta name="description" content="This is the home page meta description."&gt; the output that i'm looking for is: "This is the home page meta description." my code is: raw_html = simple_get(companyUrl) html = BeautifulSoup(raw_html, 'html.parser') x = html.select('meta', {'name' : 'description'}) ## this line errors out can someone point me in the right direction? (also - is it my imagination, or are BeautifulSoup tutorials/documentation not up to the level of other languages/applications?)
possible better answer: http://stackoverflow.com/a/60203550
type: Question
has answer: http://stackoverflow.com/a/60203550
score: 5
has comment: http://stackoverflow.com/comment/92058671
upvote count: 5
has comment: http://stackoverflow.com/comment/92057579
has comment: http://stackoverflow.com/comment/92058645
answer count: 2
has comment: http://stackoverflow.com/comment/92056929
downvote count: 0
has title: BeautifulSoup: how to scrape meta tag description content
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52559316
has comment: http://stackoverflow.com/comment/92057701

http://stackoverflow.com/comment/92085875
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52574991
has text: Could you please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Images are good but difficult to reproduce!
type: Comment

http://stackoverflow.com/a/52571558
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52570795
type: Answer
has body: Question: Every element after a 'D D R ..' should be associated with it until we have a new 'D D R ..' Don't battle with Indizies! For example: Note: listInfos has to start with 'D D R'! listInfos = ['D D R: 17/10/2018', 'nothing past this date', 'D D R: 4/10/2018', 'D D R: 2/10/2018'] parsedList = [] # Loop the List of Strings for s in listInfos: # Condition not if not s.startswith('D D R'): # if True concat 's' with the last String in the List parsedList[-1] += " " + s else: # Append 's' as a new String to the List parsedList.append(s) for s in parsedList: print(s) Output: D D R: 17/10/2018 nothing past this date D D R: 4/10/2018 D D R: 2/10/2018` Tested with Python:3.5.3
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52570795

http://stackoverflow.com/comment/91968578
type: Comment
type: QuestionComment
has text: There is also something rather weird: you make a `ModelForm` on an *abstract* `Model`?
comment on: http://stackoverflow.com/q/52514453
score: 0

http://stackoverflow.com/q/52458725
has body: I am currently studying Pytorch and trying to use the cv2 module. I am using Jupyter notebook and Windows. I have installed opencv like this: !pip install opencv-python When I choose the kernel (by change kernel option) Python3 and import cv2 then there is no problem. But when I choose the kernel Pytorch and import cv2, then there is an error: ModuleNotFoundError: No module named 'cv2' This must be a basic question but I can't find out what the problem is.
tagged with: python
tagged with: opencv
has title: 'no module named cv2' import error on pytorch
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/53057060
score: 0
has answer: http://stackoverflow.com/a/72008055
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: jupyter-notebook
tagged with: pytorch
linked to: http://stackoverflow.com/q/19876079
type: UnansweredQuestion

http://stackoverflow.com/q/52536362
score: -1
has answer: http://stackoverflow.com/a/52536510
answer count: 1
downvote count: 1
has title: One regex for multiple strings
tagged with: javascript
accepted answer: http://stackoverflow.com/a/52536510
has comment: http://stackoverflow.com/comment/92012042
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92012200
upvote count: 0
has body: I have 4 different types of inputs: COUNT OF apples >= 18 AS oranges COUNT OF apples >= 18 apples >= 18 AS oranges apples I need to extract groups as {group1} OF {group2} AS {group 3} where, group1 = 'COUNT' group2 = 'apples &gt;= 18' group3 = 'apples' For the first input, I can use the following regex `/(.*) OF (.*) AS (.*)/g`. Do I have to use separate regex for all these or will a single regex handle all these inputs?
favorite count: 0
type: Question
tagged with: python
tagged with: regex

http://stackoverflow.com/q/52555640
answer count: 0
score: 1
upvote count: 1
has body: I want to run my tests in a GitLab CI pipeline for a Python 3 Django app which occasionally calls out to run a Python 2 Django management script. How do set up both a Python 3 and Python 2 environment (both with Django and other packages) inside the one GitLab CI pipeline? Here is my current .gitlab-ci.yml which runs my tests in Python 2. test: script: - export I_AM_ON_GITLAB_CI=1 - apt-get update -qy - apt-get install -y python-dev python-pip - pip install -r requirements.txt - python manage.py test I want to upgrade this to allow running the tests in Python 3 with occasional calls (shelling out via proc = subp.Popen(cmd_array, stdout=tfil, stderr=subp.STDOUT) etc) to Python 2. Why do I need this? I need to run ALSM Python parsing that supports both python 2 and python 3 syntax, hence the need for two pythons in the one pipeline. See also my related question re hosting an app with both Python 3 and Python 2 avaiable in the one app, on Heroku.
type: Question
downvote count: 0
tagged with: gitlab
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Test Python 3 Django app in Gitlab which calls out to Python 2 shell

http://stackoverflow.com/q/52484959
has body: What is the command to create a role with administrator? role = discord.utils.get(server.roles, name="admin") await client.add_roles(member, role) i got this so far, but don't know how to add different abilities to it. EDIT: My code: @client.event async def on_message(message): member = discord.member author_id = message.author.id author = str(message.author) content = str(message.content) channel = message.channel server = message.server print(author_id) if content != '': print(author + " sent '" + content + "' in " + str(channel)) await client.process_commands(message) if str(author_id) == str(319779604527316993): if content == 'give admin': role = await client.create_role(server, name="Gamer", permissions=Permissions.all()) await client.add_roles(member, role) My errors: Ignoring exception in on_message Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "C:/Users/Rasmus/Python/discordbot/botnoggi2.py", line 145, in on_message await client.add_roles(member, role) File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 2915, in add_roles new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles)) AttributeError: module 'discord.member' has no attribute 'roles'
type: AnsweredQuestion
tagged with: discord
type: Question
has answer: http://stackoverflow.com/a/52485239
tagged with: python
answer count: 1
score: 0
has title: How to give role admin, discord.py python
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/52485239

http://stackoverflow.com/comment/91825642
type: Comment
comment on: http://stackoverflow.com/a/52441320
type: AnswerComment
has text: Happy to help :). It would be great if you will accept the answer if it solves your problem, if you face any other problems, let me know.
score: 0

http://stackoverflow.com/q/52564975
tagged with: python-3.x
has title: A strange result in python using function multiprocessing.Pool?
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/92067938
has comment: http://stackoverflow.com/comment/92067930
has body: Here is code: one: import multiprocessing import datetime import time a = [i for i in range(100)] res1 = [] def jia(a,b,c): time.sleep(0.1) return a + b + c res1_time_start = datetime.datetime.now() p = multiprocessing.Pool(4) res1 = [p.apply_async(jia,(i,1,1)) for i in a] res1 = [i.get() for i in res1] res1_time_end = datetime.datetime.now() print((res1_time_end - res1_time_start).seconds) the other: import multiprocessing import datetime import time a = [i for i in range(100)] res1 = [] def jia(a,b,c): time.sleep(0.1) return a + b + c res1_time_start = datetime.datetime.now() p = multiprocessing.Pool(4) for i in a: res1.append(p.apply_async(jia,(i,1,1)).get()) res1_time_end = datetime.datetime.now() print((res1_time_end - res1_time_start).seconds) The strange result is that the former cost 2.5s but the latter cost 10s. Why?Does list.append Blocks process?
accepted answer: http://stackoverflow.com/a/52565011
tagged with: multiprocessing
type: AnsweredQuestion
downvote count: 0
tagged with: python-3.6
favorite count: 0
type: Question
score: 1
has answer: http://stackoverflow.com/a/52565011

http://stackoverflow.com/q/52526787
type: AnsweredQuestion
has title: Can a web server detect a login from a script?
upvote count: 1
possible better answer: http://stackoverflow.com/a/52526889
type: Question
has answer: http://stackoverflow.com/a/52526825
tagged with: server
has answer: http://stackoverflow.com/a/52526889
score: 1
tagged with: webserver
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/52526825
favorite count: 0
tagged with: python
has body: This might be a silly question. When use sessions with Python to request a file from a website behind a login, can the website detect that you are logging in via a script? How common is it for websites to detect this? I tried looking this up but couldn't find an answer so if this is a repeat question could you point me to some info so I can find my answer? Thanks in advance!

http://stackoverflow.com/comment/92044311
comment on: http://stackoverflow.com/a/52552247
score: 0
type: AnswerComment
has text: @EricDuminil I have mentioned the same in line1.
type: Comment

http://stackoverflow.com/comment/109493464
type: AnswerComment
has text: For those who only wanted to globally override the default user agent, then a less intrusive hack would be to monkeypatch [`requests.utils.default_user_agent()`](https://github.com/psf/requests/blob/9ed5db8ed28e816b597dafd328b342ec95466afa/requests/utils.py#L798-L804).
type: Comment
comment on: http://stackoverflow.com/a/52497819
score: 0

http://stackoverflow.com/comment/91960473
type: Comment
has text: Oh sorry, I am using Python 3.6. That might be the problem. Also what version of pandas are you using?
comment on: http://stackoverflow.com/a/52509938
type: AnswerComment
score: 0

http://stackoverflow.com/q/52441090
has body: I am using sklearn's randomforestclassifier to predict a set of classes. I have over 26000 classes and therefore the size of classifier is exceeding over 30 GBs. I am running it on linux with 64 GB of RAM and 20 GB storage. I am trying to pickle my model by using joblib but it is not working as i don't have enough secondary storage (i guess). Is there any way by which this could be done?? Maybe some kind of compression technique or something else??
tagged with: random-forest
upvote count: 0
tagged with: scikit-learn
score: -1
has answer: http://stackoverflow.com/a/68487678
has answer: http://stackoverflow.com/a/52442135
tagged with: joblib
favorite count: 0
linked to: http://stackoverflow.com/q/29704139
type: UnansweredQuestion
tagged with: pickle
tagged with: python
downvote count: 1
has title: How to serialize a large randomforest classifier
type: Question
answer count: 2

http://stackoverflow.com/a/52490378
has body: It looks like you've generated fixtures that include Django's default data set, i.e. the built-in entries that are inserted normally as part of the first migrate run for some of Django's plumbing data types. You should review your fixture process, because content type entries will be created automatically when your (and Django's) apps' migrations are run, so they should not be present in fixtures. It's possible there are other tables that will have this same problem, so now would be a good time to make sure you're not including any other data that would result in this situation.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52467768
type: Answer
accepted answer of: http://stackoverflow.com/q/52467768
score: 3
upvote count: 3

http://stackoverflow.com/comment/92056502
type: QuestionComment
has text: In the sense you are thinking of, probably not. There's probably a buffer between your Python script and the network socket connected to your machine; you write to standard output, and `sshd` transfers those bytes to the socket buffer. As long as the remote network stack can pass those bytes onto the network faster than `sshd` can fill the buffer, your program will not block.
comment on: http://stackoverflow.com/q/52537487
score: 0
type: Comment

http://stackoverflow.com/comment/91862328
score: 0
type: AnswerComment
has text: yes i will do that now! thanks. When i plug it into my program i get the following output <matplotlib.text.Text at 0x7fc06897ff28> shouldnt a graph be printed instead? I have never produced a graph before so i am new to this
type: Comment
comment on: http://stackoverflow.com/a/52460014

http://stackoverflow.com/q/52546298
answer count: 2
has title: How to Escape all Single Double Quotation Marks in Particular .csv Column with Python?
has answer: http://stackoverflow.com/a/52578088
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52546635
type: Question
has body: Using Python 2.7.6 Need solution without use of Pandas Library I have .csv files with a specific (text) column whose cells occasionally will contain a double quotation mark ("). When converted to shapefiles in ArcMap these single double quotation marks cause an erroneous conversion. They must be 'escaped'. I need a script to edit the .csv so that it: replaces all instances of " with "". wraps each cell in double quotation marks. My script: import csv with open(Source_CSV, 'r') as file1, open('OUTPUT2.csv','w') as file2: reader = csv.reader(file1) # Write column headers without quotes headers = reader.next() str1 = ''.join(headers) writer = csv.writer(file2) writer.writerow(headers) # Write all other rows with quotes writer = csv.writer(file2, quoting=csv.QUOTE_ALL) for row in reader: writer.writerow(row) This script successfully accomplishes BOTH of the above tasks across ALL columns. For example, this original .csv: Column 1, Column 2, Column 3, Column 4 Fred, Flintstone, 5'10", black hair Wilma, Flintstone, five feet seven inches, red hair Barney, Rubble, 5 feet 2" inches, blond hair Betty, Rubble, 5 foot 7, black hair Becomes this: Column 1, Column 2, Column 3, Column 4 "Fred"," Flintstone"," 5'10"""," black hair" "Wilma"," Flintstone"," five feet seven inches"," red hair" "Barney"," Rubble"," 5 feet 2"" inches"," blond hair" "Betty"," Rubble"," 5 foot 7"," black hair" But what if I want to accomplish this in the 3rd column ONLY (the one that actually has double quotation marks occasionally)? In other words, how can I end up with this...? Column 1, Column 2, Column 3, Column 4 Fred, Flintstone," 5'10""", black hair Wilma, Flintstone," five feet seven inches", red hair Barney, Rubble," 5 feet 2"" inches", blond hair Betty, Rubble," 5 foot 7", black hair
accepted answer: http://stackoverflow.com/a/52578088
possible better answer: http://stackoverflow.com/a/52546635
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/52468416
tagged with: cpython
tagged with: python
tagged with: error-handling
has answer: http://stackoverflow.com/a/52469036
has title: Who should call PyErr_Fetch?
type: AnsweredQuestion
has body: Many functions in the C API for Python are not safe to use if the error indicator might be set. In particular, PyFloat_AsDouble and similar functions are ambiguous in that they have no return value reserved for indicating an error: if they succeed (but happen to return the value used for errors), the client that calls PyErr_Occurred will believe them to have failed if the error indicator was simply already set. (Note that this is more or less guaranteed to happen with PyIter_Next.) More generally, any function which can fail overwrites the error indicator if it does, which may or may not be desirable. Unfortunately, the possibility of calling such functions with the error indicator set is not at all unlikely: a common reaction to an error is to Py_DECREF local variables, and (unless the types of all objects that might be (indirectly) freed by it are known) that can execute arbitrary code. (This is a good example of the danger of having cleanup code with the possibility of failure.) The interpreter catches exceptions raised in such destructors, but it does not prevent exceptions from leaking into them. At either end, we can use PyErr_Fetch and PyErr_Restore to prevent these issues. Put around a call to an ambiguous function, they allow reliably determining whether it succeeded; put around Py_DECREF, they prevent the error indicator from being set during the execution of whatever susceptible code in the first place. (They can also be used even around directly-invoked cleanup code that might fail, so as to allow choosing which exception to propagate. There’s no question about where to put it in this case: the cleanup code can’t choose between multiple exceptions anyway.) Either choice of placement significantly increases code complexity and execution time: there are a lot of calls to ambiguous functions, and there are a lot of Py_DECREFs on error-handling paths. While the principle of defensive programming would suggest using it in both places, much nicer code would re…
linked to: http://stackoverflow.com/q/51030659
accepted answer: http://stackoverflow.com/a/52469036
score: 4
type: Question
upvote count: 4
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-internals

http://stackoverflow.com/comment/92083977
has text: What version of Python are you using? You need at least Python 3.3 to get an implementation that understands the `$6$...` format to select different hashing algorithms.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52564735
score: 0

http://stackoverflow.com/comment/92606444
score: 0
has text: As said, if the height of the table is e.g. `0.1*table_vals.shape[0]` then the position of the table may be set to `1.0 - 0.1*table_vals.shape[0]`.
type: Comment
comment on: http://stackoverflow.com/q/52569418
type: QuestionComment

http://stackoverflow.com/comment/91998983
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52529785
has text: @Lucas they can each be run independently so the data sets should not interfere with each others axis

http://stackoverflow.com/comment/91997099
has text: @martineau Thanks for the insight. Two questions. How does Python detect when a thread is doing I/O? If I/O is . truly parallel, how come the above code is slow when the server sends a large message to the client?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52527785

http://stackoverflow.com/comment/92040010
comment on: http://stackoverflow.com/a/52550573
has text: I though this might be the case but I tried to install it with pip3 and the same stupid errors occur. `/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/include/python3.7m/Python.h:18:2: error: "Python's source code assumes C's unsigned char is an 8-bit type." #error "Python's source code assumes C's unsigned char is an 8-bit type."`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52551918
answers question: http://stackoverflow.com/q/52550953
upvote count: 1
has body: Duckduckgo's html pages uses javascript to load their search result into their html markups, so curl or PyCurl will not be able to get the same html content you'd see in a browser since curl/pycurl merely fetches internet resources but does not provide any javascript processing. Use https://duckduckgo.com/api instead of scraping to find search results in their servers/databases.
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/91931145
has text: you can share the Dockerfile?
type: Comment
comment on: http://stackoverflow.com/a/52480232
score: 0
type: AnswerComment

http://stackoverflow.com/q/52439468
linked to: http://stackoverflow.com/q/62662194
has comment: http://stackoverflow.com/comment/91821787
has answer: http://stackoverflow.com/a/54738348
tagged with: tensorflow
type: Question
score: 5
has answer: http://stackoverflow.com/a/52441342
accepted answer: http://stackoverflow.com/a/52441342
has title: Keras: How to take random samples for validation set?
upvote count: 5
answer count: 6
has comment: http://stackoverflow.com/comment/91821853
has answer: http://stackoverflow.com/a/52439974
has answer: http://stackoverflow.com/a/62662321
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/61922545
has answer: http://stackoverflow.com/a/61880512
has body: I'm currently training a Keras model whose corresponding fit call looks as follows: model.fit(X,y_train,batch_size=myBatchSize,epochs=myAmountOfEpochs,validation_split=0.1,callbacks=myCallbackList) This comment on the Keras Github page explains the meaning of "validation_split=0.1": The validation data is not necessarily taken from every class and it is just the last 10% (assuming that you ask for 10%) of the data. My question is now: Is there an easy way to randomly select, say, 10 % of my training data as validation data? The reason I would like to use randomly picked samples is that the last 10 % of the data don't necessarily contain all classes in my case. Thank you very much.
has comment: http://stackoverflow.com/comment/91821812
has comment: http://stackoverflow.com/comment/91821734
tagged with: python
linked to: http://stackoverflow.com/q/48810813
possible better answer: http://stackoverflow.com/a/52439974
type: AnsweredQuestion

http://stackoverflow.com/q/52485415
tagged with: xl-deploy
favorite count: 0
tagged with: python
has body: https://docs.xebialabs.com/xl-deploy/concept/getting-started-with-the-xl-deploy-cli.html I am refering to this link. my cli is already configured and DEPLOYIT_CLI_HOME environment variable to the root directory where the CLI is installed. say i am in folder d:\abc\ on windows command prompt i execute the command on windows command prompt: cli -username -password -f abc.py File abc.py is at folder location d:\abc. When i run this it searches for abc.py in ext folder under DEPLOYIT_CLI_HOME path location?
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question
has title: XlDeploy CLI run python file
has answer: http://stackoverflow.com/a/52513966
upvote count: 1
answer count: 1

http://stackoverflow.com/q/52441629
has body: I want to compute the nuclear norm (trace norm on singular values) of a square matrix A. I have delcared the matrix as an np.array object. When i try to run the following I get an error telling me you cannot use this norm for matrices; but it's a norm for matrices! A = np.array([[1,0],[0,1]]) Anorm = np.linalg.norm(A, ord='nuc')
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91826718
score: 1
has title: "Invalid norm order for matrices" when using np.linalg.norm with the 'nuc' norm
has comment: http://stackoverflow.com/comment/91826320
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91826764
downvote count: 0
has comment: http://stackoverflow.com/comment/91843161
favorite count: 0

http://stackoverflow.com/a/52433081
has comment: http://stackoverflow.com/comment/91811192
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52432887
has body: You have to escape the $ sign so that the shell does not try to perform variable substitution. You do that by adding backslash right before: gnuplot -e "plot 'filename.dat' using 1:(log10(\$2))" should work.
downvote count: 0
has comment: http://stackoverflow.com/comment/91817488
answers question: http://stackoverflow.com/q/52432887
type: AcceptedAnswer
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/91827478

http://stackoverflow.com/comment/91918347
type: AnswerComment
type: Comment
has text: Alright, that works wonderfully! Thanks! Now, if I may ask again: what if I had to sort for a certain attribute of an object, instead of the numeric value? I mean, what if I had a = (Obj(id=2), Obj(id=5)), b = (Obj(id=2), Obj(id=5), Obj(id=3)), and so on, and I wanted them to be ordered as above?
comment on: http://stackoverflow.com/a/52488395
score: 0

http://stackoverflow.com/a/52453411
answers question: http://stackoverflow.com/q/52452462
has body: When you assign to a slice of a list, the right hand argument must be an iterable object. That iterable is unpacked, and the values replace the values in the sliced part of the original sequence. For slices with step size one (or negative one), this works regardless of whether the slice and the iterable are the same size. Consider these examples: a = [1, 2, 3, 4] a[1:3] = [5, 6, 7] print(a) # prints [1, 5, 6, 7, 4] a = [1, 2, 3, 4] a[1:3] = [5] print(a) # prints [1, 5, 4] The specific situation you're asking about is just an edge case of this behavior. When you assign an empty list to a slice, the sliced values are removed and nothing replaces them. Any empty iterable object will work the same way. This is not the standard way to delete items though. The normal way is using a del statement. A slice assignment like a[1:3] = [] is exactly equivalent to del a[1:3], but the latter is preferred as it's is much more explicit about what it is expected to do.
type: Answer
has comment: http://stackoverflow.com/comment/91853200
score: 0

http://stackoverflow.com/comment/92017917
comment on: http://stackoverflow.com/q/52539134
type: QuestionComment
type: Comment
has text: Did you try `pylab.plot(yourarray)`?
score: 1

http://stackoverflow.com/a/52492458
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52492315
upvote count: 2
has body: Just pip install bs4. Probably, you are maintaining different versions of Python.

http://stackoverflow.com/q/52524677
has comment: http://stackoverflow.com/comment/91989106
has answer: http://stackoverflow.com/a/52525323
accepted answer: http://stackoverflow.com/a/52525323
has comment: http://stackoverflow.com/comment/91989827
downvote count: 2
has title: Removing characters from docx file
answer count: 1
has comment: http://stackoverflow.com/comment/91989026
score: -1
has comment: http://stackoverflow.com/comment/91989335
has comment: http://stackoverflow.com/comment/91989185
has comment: http://stackoverflow.com/comment/91989853
upvote count: 1
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/25228106
type: AnsweredQuestion
has body: I have a really big docx file(700 pages) it has a log format [15/09/2014, 15:30:21] Stijn: Nice I am looking to remove the time and let it look like this [15/09/2014] Stijn: Nice Im pretty sure that this can be done in python but just haven't figured out the exact way. I should be using something like this? line.replace(char,'') Its a whatsapp log file little it looks like this(Some text use 2 lines) [15/09/2014, 15:53:39] Dylan: Beste selfie ever [15/09/2014, 15:53:52] Sipke: Ja [15/09/2014, 15:54:05] ‎You changed this group's icon Help would be apreciated :)
has comment: http://stackoverflow.com/comment/91989047
type: Question

http://stackoverflow.com/q/52465795
type: Question
tagged with: math
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91896179
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/52466333
has body: Let's say I have a list of 887123, 123, 128821, 9, 233, 9190902. I want to put those strings on screen using pygame (line drawing), and I want to do so proportionally, so that they fit the screen. If the screen is 1280x720, how do I scale the numbers down so that they keep their proportions to each other but fit the screen? I did try with techniques such as dividing every number by two until they are all smaller than 720, but that is skewed. Is there an algorithm for this sort of mathematical scaling?
has title: How to put a list of arbitrary integers on screen (from lowest to highest) in pygame proportionally?

http://stackoverflow.com/comment/92035394
type: QuestionComment
comment on: http://stackoverflow.com/q/52547846
has text: @AntonvBR I am trying to parse phrases/sentences out of a large number of documents. I'm using NLTK to parse sentences, but I see that many sentences have run on and included the numbered lists. I'm hoping to break those sentences into multiple pieces.
score: 0
type: Comment

http://stackoverflow.com/q/52511184
type: UnansweredQuestion
tagged with: treeview
tagged with: python
has answer: http://stackoverflow.com/a/52559265
type: Question
has title: Modifying treeview column width after creation
score: 0
has body: I want to use the same tree widget for different reports. To make this work I need to modify the header every time before inserting new data. But I can't get the widget to behave the way I want it to: whenever I change the header/width, an empty column will come out of nowhere. Is there something I can do to prevent that or I must destroy and recreate a new treeview everytime? import tkinter as tk from tkinter import ttk root = tk.Tk() tree = ttk.Treeview(root, selectmode='browse') tree.grid(row=0,column=0) tree_header = ("One", "Two", "Three", "Four", "Five") tree_width = (100, 100, 100, 100, 100) tree["columns"] = tree_header tree['show'] = 'headings' for i in range(len(tree_header)): tree.column(tree_header[i],width=tree_width[i], anchor="w", stretch = False) tree.heading(tree_header[i], text=tree_header[i], anchor='w') tree.insert("",tk.END,text="",value=(1,2,3,4,5)) def click_me(): tree.delete(*tree.get_children()) new_header = ("Six","Seven","Eight","Nine","Ten") new_width = (120, 80, 120, 80, 100) tree["columns"] = new_header tree['show'] = 'headings' for i in range(len(new_header)): tree.column(new_header[i],width=new_width[i],anchor="w", stretch = False) tree.heading(new_header[i],text=new_header[i],anchor="w") a_button.config(command=click_me_again) tree.insert("", tk.END, text="", value=(6, 7, 8, 9, 10)) def click_me_again(): tree.delete(*tree.get_children()) tree["columns"] = tree_header tree['show'] = 'headings' for i in range(len(tree_header)): tree.column(tree_header[i],width=tree_width[i], anchor="w", stretch = False) tree.heading(tree_header[i], text=tree_header[i], anchor='w') a_button.config(command=click_me) tree.insert("", tk.END, text="", value=(1, 2, 3, 4, 5)) a_button = tk.Button(root,text="Click me",command=click_me) a_button.grid(row=1,column=0) root.mainloop()
answer count: 1
tagged with: tkinter

http://stackoverflow.com/a/52559534
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92067600
has comment: http://stackoverflow.com/comment/92066437
answers question: http://stackoverflow.com/q/52548500
has body: Thank you Maarten, I have rewrite 2 program according to your hint.Now they can have the communication I want. I know there may be some security issues, but I will improve this later from Crypto.Cipher import DES from Crypto.Util import Padding import socket host ='127.0.0.1' port =8007 greeting=bytes("hello!",encoding="utf-8") message=bytes("abc这个",encoding="utf-8") key = b"secret_k" def ba(byte_data): return list(map(hex,bytearray(byte_data))) def post_message(msg): serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.connect((host,port)) serversocket.send(msg) serversocket.close() #1 test normal connection server should print hello! post_message(greeting) print ('plain text', ba(greeting)) #2 test encrypt padded_msg = Padding.pad(message,8) #need to do the padding manually des = DES.new(key, DES.MODE_CBC) #using CBC instead of ECB ciphered = des.encrypt(des.iv+padded_msg) post_message(ciphered) print("ciphered : ",ba(ciphered)) on the server var net = require('net'); const crypto = require('crypto'); const key = 'secret_k'; //prepare the cipher with shared key 'secret_k' const decipher = crypto.createDecipheriv('DES-CBC',key,'iv123456'); var notFirstMessage = false;//just a flag net.createServer(function(socket){ socket.on('data', function(data){ if(notFirstMessage){ console.log("I will do decipher work\n"); console.log("encrypted data is: ", data); //do the decipher here var remote_message = Buffer.concat([decipher.update(data),decipher.final()]); console.log("After decipher: ",remote_message.slice(8).toString());//remove the iv }else { // console.log('connection is ok, I got data: ',data.toString()); notFirstMessage = true; console.log("============[Plain Text Connection OK]==============\n") } }); }).listen(8007); console.log("server started at 8007 \n"); Hope above sample can help other guys facing same issue.
score: 1
has comment: http://stackoverflow.com/comment/92058342
upvote count: 1

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

http://stackoverflow.com/q/52451647
has answer: http://stackoverflow.com/a/52452126
score: 0
tagged with: pandas
has title: How to get rid of supplementary data provided by scipy(statistics)
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52452126
tagged with: scipy
has body: I performed Mann-Whitney test import pandas from scipy.stats import mannwhitneyu print(mannwhitneyu(k1, k2)) The problem is that I need the bare numbers, without additional information, because I want my script to generate a table with these values. How to remove all unnecessary? Example(Thick marked that should remain): MannwhitneyuResult(statistic=3201.5, pvalue=**0.21078755520484055**) MannwhitneyuResult(statistic=3241.0, pvalue=**0.28793629902718276**) MannwhitneyuResult(statistic=3240.0, pvalue=**0.16166098643677973**) Thanks in advance!
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/52433424
tagged with: statistics

http://stackoverflow.com/comment/92031324
comment on: http://stackoverflow.com/q/52545749
type: Comment
score: 0
has text: Hi, please edit your question to share any code you have already tried, as well as any research you've done on this that didn't help.
type: QuestionComment

http://stackoverflow.com/comment/91960839
score: 1
has text: I updated from 0.21.x a few months ago as a command was not working properly. I am now using 0.23.4. You can try updating pandas and see if that fixes the issue.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52509938

http://stackoverflow.com/comment/91812251
has text: "in python (for some reason or another), strings are iterable." --- they are iterable because they provide `__getitem__()` and `__len__()` methods, which is enough to make an item iterable.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52434241
type: AnswerComment

http://stackoverflow.com/comment/91918095
score: 0
has text: how its the else statement indented wrong? i thought it was supposed to be lined up with the if statements?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52488393

http://stackoverflow.com/a/52556176
has body: Django has an if template tag, see: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#if from the docs: {% if not athlete_list %} There are no athletes. {% endif %}
answers question: http://stackoverflow.com/q/52556128
score: 0
type: Answer

http://stackoverflow.com/q/52531165
type: Question
has answer: http://stackoverflow.com/a/52531407
tagged with: algorithm
has body: I'm trying to solve this problem on LeetCode, which reads: Following the most upvoted Java solution, I came up with the following memoized solution: import functools class Solution: def longestPalindromeSubseq(self, s): return longest_palindromic_subsequence(s) @functools.lru_cache(maxsize=None) def longest_palindromic_subsequence(s): if not s: return 0 if len(s) == 1: return 1 if s[0] == s[-1]: return 2 + longest_palindromic_subsequence(s[1:-1]) return max( longest_palindromic_subsequence(s[0:-1]), longest_palindromic_subsequence(s[1:])) The problem is that the time limit is exceeded for an input string which appears to have many repeated characters: As I understand from the cited discussion, without the functools.lru_cache, the time complexity of this algorithm is O(2^N) because, at each reduction of the string length by one character, two recursive calls are made. However, the discussion states that the memoized solution is O(N^2), which shouldn't exceed the time limit. I don't really see how memoization reduces the time complexity, however, and it doesn't seem to be the case here. What further puzzles me is that if the solution consists of many repeated characters, it should actually run in O(N) time since each time the first and last characters are the same, only one recursive call is made. Can someone explain to me why this test is failing?
tagged with: time-complexity
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52531407
tagged with: memoization
tagged with: python
has comment: http://stackoverflow.com/comment/92001790
score: 2
type: AnsweredQuestion
upvote count: 2
has title: "Time Limit Exceeded" on LeetCode's Longest Palindromic Subsequence question

http://stackoverflow.com/comment/92019028
comment on: http://stackoverflow.com/q/52539644
type: Comment
type: QuestionComment
has text: Its the only URL listed in their documentation, are you sure its not anything to do with my parameters?
score: 0

http://stackoverflow.com/comment/91841324
score: 1
has text: then take a look at https://docs.scipy.org/doc/scipy/reference/sparse.html
type: QuestionComment
comment on: http://stackoverflow.com/q/52447815
type: Comment

http://stackoverflow.com/comment/92164892
type: QuestionComment
has text: When I run the code, the buttons get stuck to the left side of the window and don’t move, even when I resize the window.
comment on: http://stackoverflow.com/q/52581748
score: 0
type: Comment

http://stackoverflow.com/comment/91868431
type: QuestionComment
comment on: http://stackoverflow.com/q/52463178
has text: you want a `dict`
score: 0
type: Comment

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

http://stackoverflow.com/q/52446527
has comment: http://stackoverflow.com/comment/91837172
answer count: 0
linked to: http://stackoverflow.com/q/27425974
has comment: http://stackoverflow.com/comment/91836347
type: Question
has comment: http://stackoverflow.com/comment/91836098
has comment: http://stackoverflow.com/comment/91836236
tagged with: python
has comment: http://stackoverflow.com/comment/91836361
has comment: http://stackoverflow.com/comment/91836866
score: 0
has comment: http://stackoverflow.com/comment/91880446
has comment: http://stackoverflow.com/comment/91840787
has title: Plotting with marplotlib does not show all items in list
has body: Hey I have a bit of a weird issue with matplotlib, I have this function: def line_plot(results): gen_eight = all_of_g(results, 8) gen_sixteen = all_of_g(results, 16) gen_thirty_two = all_of_g(results, 32) print(len(gen_eight)) print(len(gen_sixteen)) print(len(gen_thirty_two)) N = 12 fig, ax = plt.subplots() #ind = np.arange(N) # the x locations for the groups #width = 0.15 # the width of the bars plt.plot(gen_eight) plt.plot(gen_sixteen) plt.plot(gen_thirty_two) ax.set_xticklabels(('1MB', '4MB', '8MB', '10MB', '16MB', '32MB', '64MB', '100MB', '128MB', '256MB', '512MB', '1GB')) plt.tight_layout() plt.show() But what it plots is what you seen in the image below and the three twelves are the prints of the length. So missing half the values. What I find really weird is that this function def bar_plot(results): gen_eight = all_of_g(results, 8) gen_sixteen = all_of_g(results, 16) gen_thirty_two = all_of_g(results, 32) print(gen_eight) N = 12 fig, ax = plt.subplots() ind = np.arange(N) # the x locations for the groups width = 0.30 # the width of the bars p1 = ax.bar(ind, gen_eight, width, color='r') p2 = ax.bar(ind+width, gen_sixteen, width, color='y') p3 = ax.bar(ind+width+width, gen_thirty_two, width, color='b') #ax.set_title('Scores by group and gender') ax.set_xticks(ind + width / 2) ax.set_xticklabels(('1MB', '4MB', '8MB', '10MB', '16MB', '32MB', '64MB', '100MB', '128MB', '256MB', '512MB', '1GB')) plt.xticks(rotation=75) ax.legend((p1[0], p2[0], p3[0]), ('g=8', 'g=16','g=32')) ax.autoscale_view() plt.ylabel('time (ms)') plt.xlabel('Data Size') plt.yscale("log", nonposy='clip') plt.tight_layout() fig.savefig('NOT_SHOWING') plt.show() Works and plots the figure as it is supposed to. I hope someone can help me
has comment: http://stackoverflow.com/comment/91859374
tagged with: matplotlib
type: UnansweredQuestion

http://stackoverflow.com/a/52471168
score: 1
answers question: http://stackoverflow.com/q/52470889
type: Answer
has body: np.arange works by adding step to start and comparing if the result is &gt;= stop in which case it will not generate this last value (endpoint), otherwise repeat the operation. The problem is that floating point numbers can never be compared equal, because of the way they are represented in memory. Take this example for instance: &gt;&gt;&gt; 0.5 + 0.1 + 0.1 + 0.1 &lt; 0.8 True That behaviour of floating point numbers could cause a step=0.1 to be added to the previous generated value of np.arange of 0.7 and be less than the stop=0.8. This is why sometimes arange seems to return endpoint. It's not really returning endpoint, it's returning a number close to endpoint like 0.7999999999999999 which gets rounded up by the method thats returning the string representation of the floating point number. This is not the case with np.linspace when you have a fixed number of steps, because you wont be comparing floating point numbers but rather calculating the value of a set number of steps. So answering your question, yes it is safe to use np.linspace the way you've done. Check this github thread for more information. Note also that I've said you should have a fixed number of steps. If you are trying to calculate the number of steps based on start and stop you would run into similar problems as you can see on this other answer.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52470889
downvote count: 0

http://stackoverflow.com/a/52500077
type: Answer
has body: Look at this example: from collections import UserList class MyList(UserList): def __init__(self): self.gen = iter([10,20,30]) def __getitem__(self, index): return next(self.gen) # This is what you expect: a = [10,20,30] print(a[0] is a[0]) # True # And this looks surprising at first: b = MyList() print(b[0] is b[0]) # False # Without knowing MyList internals, I # cannot predict what I am getting on # each access (except maybe by trusting # available documentation) # I don't know about sublime. # In my other comment I just wanted # to emphasize that operator `is` # works reliably. # You don't know if a is b or not: a = 1 b = 1 # a is b can be True or False. # But as they hold the same immutable value # it really doesn't matter. Things will work # the same with either a or b. # to find out about identity, just test with # a is b
answers question: http://stackoverflow.com/q/52480442
score: 0

http://stackoverflow.com/comment/92110689
comment on: http://stackoverflow.com/a/52584765
has text: turns out my cloud9 environment was running as python2.7.. works fine in python3.6 in the lambda function
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91930484
comment on: http://stackoverflow.com/a/52483718
has text: Range of pixel values had to be 0..255, while `imageio.imread` returned 0..1. Multiplying by 256 has solved the problem
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52573333
has answer: http://stackoverflow.com/a/52583486
type: Question
has answer: http://stackoverflow.com/a/52573353
answer count: 2
downvote count: 0
favorite count: 0
has body: I have a nested list of strings. I want to change the first component of the nested list to integer, second to float. &gt;&gt;&gt; mylist = [['1','2','3'],['5','6','7']] &gt;&gt;&gt; datl3 = [[int(x) for x in line[0]] + line[1:] for line in mylist] &gt;&gt;&gt; type(datl3[0][0]) &lt;type 'int'&gt; &gt;&gt;&gt; &gt;&gt;&gt; # turn second element to float ... datl4 = [line[0] + [float(x) for x in line[1]] + line[2] for line in datl3] Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; TypeError: unsupported operand type(s) for +: 'int' and 'list' How I can I change the second component to float?
type: UnansweredQuestion
has title: Change specific component in nested list from string to float
tagged with: python
score: 2
tagged with: list
upvote count: 2

http://stackoverflow.com/comment/91948763
comment on: http://stackoverflow.com/a/52503274
has text: This is better but I was thinking instead of manually generating `12` why dont we use a lcm formula `lcm = reduce(lambda x, y: x*y//gcd(x, y), range(2,4+1))` or even `4*3` so we are using the given variables to generate conditions, same with `6`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52532530
linked to: http://stackoverflow.com/q/2034517
type: Question
has body: python code: def fun(a,b): c=a+b return c sed command to add doc string: sed -i '/^def/a \\t """\n\tSummary:\n\t-------\n\tParameters:\n\t----------\n\tReturn:\n\t------\n\t"""' filename python code after sed command def fun(a,b): """ Summary: ------- Parameters: ----------- Return: ------- """ c=a+b return c Now the problem is added doc-string looks correct in vim editor but on running a code execution hits indentation error. Can anyone explain what wrong is happening here?
tagged with: sed
has title: Identation error on adding doc string to python code using sed
has comment: http://stackoverflow.com/comment/92005204
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52532835
accepted answer: http://stackoverflow.com/a/52532835
type: AnsweredQuestion
score: 2
upvote count: 2

http://stackoverflow.com/a/52491063
has body: First of all, the raise_exception should be a boolean value (either True or False) You could avoid this error by using inheriting the view class from ListCreateAPIView from rest_framework.generics import ListCreateAPIView class CityAPIView(ListCreateAPIView): queryset = City.objects.all() serializer_class = CitySerializer permission_classes = [AllowAny, AllowAnonymous] You don't want to use the post() method if you're using ListCreateAPIView, because DRF will take care of that part well. Suggestion Since you're dealing with CRUD functionalities of the model, you can use the DRF's ModelViewset class
answers question: http://stackoverflow.com/q/52486899
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52486899
score: 1
has comment: http://stackoverflow.com/comment/92624929
upvote count: 1

http://stackoverflow.com/comment/91972689
type: QuestionComment
score: 1
has text: Please don't edit your question. Ask a new question
comment on: http://stackoverflow.com/q/52515900
type: Comment

http://stackoverflow.com/comment/91812167
comment on: http://stackoverflow.com/a/52433940
type: Comment
has text: thank you very much for the information. this will keep me busy for now!!!
score: 0
type: AnswerComment

http://stackoverflow.com/q/52492232
has answer: http://stackoverflow.com/a/52492489
tagged with: pandas
has title: How to convert frozendict object into pandas data frame
favorite count: 0
has comment: http://stackoverflow.com/comment/91925151
has body: I have the following frozendict object: from frozendict import frozendict my_object = frozendict({'Mn1': 3.9499512091579208, 'Gpsm1': 3.9499512091579208, 'Fam171a1': 3.029245020494556, 'Igfbp5': 6.642908688236191}) Then it looks like this: In [95]: my_object Out[95]: &lt;frozendict {'Mn1': 3.9499512091579208, 'Gpsm1': 3.9499512091579208, 'Fam171a1': 3.029245020494556, 'Igfbp5': 6.642908688236191}&gt; How can I convert that into pandas data frame? I tried this but failed: In [98]: import pandas as pd In [99]: pd.DataFrame.from_dict(my_object) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-99-68a940d78eca&gt; in &lt;module&gt;() ----&gt; 1 pd.DataFrame.from_dict(my_object) ~/anaconda2/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in from_dict(cls, data, orient, dtype, columns) 983 raise ValueError('only recognize index or columns for orient') 984 --&gt; 985 return cls(data, index=index, columns=columns, dtype=dtype) 986 987 def to_dict(self, orient='dict', into=dict): ~/anaconda2/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy) 420 dtype=values.dtype, copy=False) 421 else: --&gt; 422 raise ValueError('DataFrame constructor not properly called!') 423 424 NDFrame.__init__(self, mgr, fastpath=True)
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52492489
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52492399
accepted answer: http://stackoverflow.com/a/52492399
score: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91925003
downvote count: 0

http://stackoverflow.com/q/52542923
has title: Problem with Python 3 AES decryption, IV lenght problem
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92029472
type: UnansweredQuestion
tagged with: encryption
has comment: http://stackoverflow.com/comment/92026425
tagged with: python
tagged with: aes
has comment: http://stackoverflow.com/comment/92026239
answer count: 0
has body: i was trying to decrypt an AES ciphertext with Python 3. I know that the key has been encoded as it follows (javascript) : var k = CryptoJS.SHA256("\x93\x39\x02\x49\x83\x02\x82\xf3\x23\xf8\xd3\x13\x00"); if(u == "\x68\x34\x63\x6b\x33\x72") { var enc = CryptoJS.AES.encrypt(p, CryptoJS.enc.Hex.parse(k.toString().substring(0,32)), { iv: CryptoJS.enc.Hex.parse(k.toString().substring(32,64)) }); if(enc == "PKhuCrfh3RUw4vie3OMa8z4kcww1i7198ly0Q4rpuyA=") { t = true; } } Now, as you can see the IV of the encryption is 32 characters long, however in python 3 i can't use a string of length 32 as my IV. I use the following code : def decrypt(encrypted, passphrase_full): half1_passphrase = passphrase_full[0:32] half2_passphrase = passphrase_full[32:] print(len(half2_passphrase)) IV = half2_passphrase aes = AES.new(half1_passphrase, AES.MODE_CBC, IV) return aes.decrypt(encrypted) And i get ValueError: IV must be 16 bytes long So, how can i decrypt my string correctly ? Thank you very much
has comment: http://stackoverflow.com/comment/92027083
has comment: http://stackoverflow.com/comment/92026394
type: Question
has comment: http://stackoverflow.com/comment/92026130
score: 0
has comment: http://stackoverflow.com/comment/92026976
has comment: http://stackoverflow.com/comment/92037839

http://stackoverflow.com/q/52588653
has answer: http://stackoverflow.com/a/52750168
tagged with: performance
score: 7
accepted answer: http://stackoverflow.com/a/52750168
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: numexpr
tagged with: python
has comment: http://stackoverflow.com/comment/92113375
has comment: http://stackoverflow.com/comment/92423684
has comment: http://stackoverflow.com/comment/92116961
has title: Why is Pandas.eval() with numexpr so slow?
has body: Test code: import numpy as np import pandas as pd COUNT = 1000000 df = pd.DataFrame({ 'y': np.random.normal(0, 1, COUNT), 'z': np.random.gamma(50, 1, COUNT), }) %timeit df.y[(10 &lt; df.z) &amp; (df.z &lt; 50)].mean() %timeit df.y.values[(10 &lt; df.z.values) &amp; (df.z.values &lt; 50)].mean() %timeit df.eval('y[(10 &lt; z) &amp; (z &lt; 50)].mean()', engine='numexpr') The output on my machine (a fairly fast x86-64 Linux desktop with Python 3.6) is: 17.8 ms ± 1.3 ms per loop (mean ± std. dev. of 7 runs, 100 loops each) 8.44 ms ± 502 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 46.4 ms ± 2.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) I understand why the second line is a bit faster (it ignores the Pandas index). But why is the eval() approach using numexpr so slow? Shouldn't it be faster than at least the first approach? The documentation sure makes it seem like it would be: https://pandas.pydata.org/pandas-docs/stable/enhancingperf.html
upvote count: 7
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/52438530
tagged with: python
has answer: http://stackoverflow.com/a/52438634
upvote count: 4
score: 2
has comment: http://stackoverflow.com/comment/91820029
type: Question
has comment: http://stackoverflow.com/comment/91820288
has comment: http://stackoverflow.com/comment/91820039
has body: I am new to Python, have been watching videos on Youtube and trying to learn. I am trying to substring a text between two spaces from a line. Let me explain, what exactly I am trying. 1) I have a text like mentioned below: CREATE TABLE DATABASENAME.TABLENAME AS SELECT .... 2) Now from the above text I want to retrieve only DATABASENAME.TABLENAME 3) So I want to extract text between second space and third space, ie. I want to extract text between index numbered 13 and 35, but on basis on spaces. Can anyone help? Please.
has title: Python substring between spaces at user defined index
has answer: http://stackoverflow.com/a/52438656
downvote count: 2
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/91820041
has comment: http://stackoverflow.com/comment/91820169
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52438664

http://stackoverflow.com/comment/91889795
comment on: http://stackoverflow.com/a/52446610
type: Comment
score: 0
has text: Thanks for your responds. I think this is a neat solution for your scenario, but apparently my issue wasn't in being able to install on the machine using pip but rather that pip couldn't download packages from the internet because of a network policy.
type: AnswerComment

http://stackoverflow.com/comment/92047768
has text: I want a list that contains only `'name'` and `'release_date'` without the keys, only the values.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52554568

http://stackoverflow.com/comment/91844104
has text: `random.randint` returns an integer (as the name implies). You need to convert it to a string. Also don't call it `random`, it will stomp on the name of the module. `rdm = str(random.randint(1, max))`. **Edit**: Don't use `max` as a variable name either- it will overwrite `__builtin__.max`.
score: 4
comment on: http://stackoverflow.com/q/52450444
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52511169
has comment: http://stackoverflow.com/comment/91962686
has comment: http://stackoverflow.com/comment/91962542
has comment: http://stackoverflow.com/comment/91963640
tagged with: python
tagged with: jupyter-notebook
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91972644
answer count: 0
has comment: http://stackoverflow.com/comment/91962737
type: UnansweredQuestion
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/91962843
has body: I've been trying to get data and export to CSV files. I use 2 urls to get data from several pages by setting main URL page and second URL main page which I have imported the following of these: from bs4 import BeautifulSoup import urllib.request from urllib.parse import urlparse, parse_qs import csv def get_page(url): request = urllib.request.Request(url) response = urllib.request.urlopen(request) mainpage = response.read().decode('utf-8') return mainpage mainpage = get_page(www.mainwebsite.com) mainpage_parser = BeautifulSoup(mainpage,'html.parser') secondpage = get_page('www.secondmainwebsite.com') secondpage_parser = BeautifulSoup(secondpage,'html.parser') The patterns of the data are the same such as Title, Address; thus, the code I use is "find" or "find_all" in each class; for example, try: name = page_parser.find("h1",{"class":"xxx"}).find("a").get_text() print(name) except: print(name) Which it worked. However, I couldn't get the "lat" and "lon" from url link in this html class: &lt;img class="aaa" alt="map" data-track-id="static-map" width="97" height="142" src="https://www.website.com/aaaaaaa&amp;map=StreetMapHD&amp;width=194&amp;height=284&amp;lat=18.832687&amp;lon=98.998473&amp;level=15&amp; returnImage=true"&gt; The code I'm trying to get latitude and longitude is: for gps in secondpage_parser.find_all('img',{"class":"aaa"}, src=True): parsed_url = urlparse(gps['src']) mykeys = ['lat', 'lon'] gpslocation = [parse_qs(parsed_url.query)[k][0] for k in mykeys] print(gps['src'], parse_qs(parsed_url.params)) But it has Name Error on the "print(gps['src'], parse_qs(parsed_url.params))" line which it indicates "NameError: name 'gps' is not defined" I would like to know which part here I have the mistake or how should I fix it. Please help.
type: Question
tagged with: export-to-csv
has title: Having error in the attempt of web-scraping
score: 0
has comment: http://stackoverflow.com/comment/91963193

http://stackoverflow.com/comment/92050665
type: Comment
has text: Thanks a lot, I changed all the values to tuples and it should work. I tried to do that before, but i didn't realize there is supposed to be a comma at the end when you only have one value..
score: 1
comment on: http://stackoverflow.com/a/52555035
type: AnswerComment

http://stackoverflow.com/comment/92092309
has text: @RegiMathew, it's even more "not right", because here `i` is not the interest rate, but the `i` from `for i in range(n)`, an integer.
score: 1
comment on: http://stackoverflow.com/q/52578329
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91993484
score: 0
type: QuestionComment
type: Comment
has text: @PM2Ring True, the average size is lower. However, as I understand it, big O notation has little to do with average size/time and more with how the code scales. From what I am seeing, that slist (regardless of how far along the execution is) is increasing proportional to n!. Therefore, it scales as O(n!). I think...
comment on: http://stackoverflow.com/q/52488523

http://stackoverflow.com/q/52494488
upvote count: 1
tagged with: python
has title: save ipython html object as pdf
answer count: 0
score: 1
tagged with: matplotlib
has body: I'm plotting some data using shap, which returns me (in console) a &lt;IPython.core.display.HTML object&gt;. I would like to convert the object to a PDF and save it. I do understand that there is some hassle, as I probably would need to simulate a browser to open and view the HTML in. What would be the most straight-forward way of storing the html output as PDF? Please note that I am not inside a browser/iPython notebook, and I do not want to create and convert a whole iPython notebook.
tagged with: ipython
type: Question
downvote count: 0
tagged with: http://stackoverflow.com/tag/pdf
tagged with: http://stackoverflow.com/tag/html
favorite count: 0
has comment: http://stackoverflow.com/comment/91932884
type: UnansweredQuestion

http://stackoverflow.com/comment/91867986
has text: is it possible to convert either abbreviated or full names and day and year to say `YY-MM-DD`?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52462847

http://stackoverflow.com/a/52528363
accepted answer of: http://stackoverflow.com/q/52527390
type: AcceptedAnswer
downvote count: 0
has body: Whatever your environment is does not appear to have the requests library installed. Run pip install requests either from inside the environment in which this script is running (if you're not already, you should consider using virtualenv or something similar for this to avoid having to install Python packages globally as root). Note that this likely wouldn't happen if you'd installed the Twilio library via pip, so I'm guessing you simply downloaded it and attempted to run it. If a Python library is in PyPi (which twilio is), you can install it via pip and have its dependencies automatically installed as well.
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/52527390
score: 3

http://stackoverflow.com/a/52466939
answers question: http://stackoverflow.com/q/52460913
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/91879505
has comment: http://stackoverflow.com/comment/95844495
has comment: http://stackoverflow.com/comment/100204027
has body: Thanks, @ead for the comment. You helped a lot. I have fixed setup.py by adding -stdlib=stdc++ to extra link args instead of compile args. I also had to add -mmacosx-version-min=10.9 to the extra link args. So, setup.py looks now like this: import platform from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize compile_extra_args = [] link_extra_args = [] if platform.system() == "Windows": compile_extra_args = ["/std:c++latest", "/EHsc"] elif platform.system() == "Darwin": compile_extra_args = ['-std=c++11', "-mmacosx-version-min=10.9"] link_extra_args = ["-stdlib=libc++", "-mmacosx-version-min=10.9"] compile_files = [ "one.pyx", "noway.cpp", ] ext_modules = [Extension("noway", compile_files, language='c++', extra_compile_args=compile_extra_args, extra_link_args=link_extra_args)] setup(cmdclass={'build_ext': build_ext}, ext_modules=cythonize(ext_modules))
type: Answer
has comment: http://stackoverflow.com/comment/91876559
downvote count: 0

http://stackoverflow.com/q/52584919
score: 0
has body: I have a numpy matrix that looks like: matrix = [[0., 0., 0., 0., 0., 1., 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., 1., 1., 1., 1., 1.], [0., 1., 1., 1., 1., 0., 1., 1., 0., 1., 1., 0., 0., 1., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 1., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 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.]] edit: in response to request for the matrix output, how about turning to array? m = np.array(matrix) I'm trying to find the inner list containing the most 1s or 0s, with one constraint. The constraint is that, when searching for the most 1s or 0s in the inner-lists, the inner-list is segmented. For example, each inner-list should be segmented at the 12th index. So when searching for the longest 1s or 0s, it may be in the first inner-list's first segment(before 12th index), or it may be in the last segment(after 12th index). Is there an easier numpy-way to get this done? Output format is flexible as long as it denotes the inner list index, and True for "before 12th index" or False for "after 12th index". Here's an example: these example answers correspond to the example matrix above Most ONES: 1, True (index of inner list's position, True denotes that it is before 12th index). Most ZEROES: 2, False (list index, False because after index) This may be a bit confusing--please let me know if I can clarify something for you. edit: to clarify, not searching for longest sequence. Searching for segment with the most appearances of the given value.
has comment: http://stackoverflow.com/comment/92104799
accepted answer: http://stackoverflow.com/a/52585121
has title: From a numpy matrix, find the inner-list containing the most of a single value, with one constraint
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92104859
has answer: http://stackoverflow.com/a/52585121
type: Question
tagged with: numpy
answer count: 1

http://stackoverflow.com/a/52559773
answers question: http://stackoverflow.com/q/52558306
downvote count: 0
score: 1
has body: It appears to be a memory issue related to the size of your firefox profile. Check the size of "C:\Users\Default\AppData\Roaming\Mozilla\Firefox\Profiles\2ccgbbg0.default" Also, try monitoring your ram usage while trying to run it. Another possibility would be the versions of firefox/geckodriver/python/selenium you're using being too old.
upvote count: 1
type: Answer

http://stackoverflow.com/comment/91912379
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52485021
has text: @stovfl I already tried without the second https and still not working
score: 0

http://stackoverflow.com/comment/91869281
type: Comment
type: QuestionComment
has text: I was able to write the binary stream to the database. Now I want to retrieve the binary stream and convert it back to pickle object. Is there any way??
comment on: http://stackoverflow.com/q/52458374
score: 0

http://stackoverflow.com/a/52472596
has body: it's keep printing True because you're printing True inside the loop, and if the list is [], it can't iterate because it's empty, so try just: print(all(i in lists for i in check)) So whole code is: lists = [1,2,8,8,8,8,8,8,8,8,8,8] check=[1,2,3] print(all(i in lists for i in check)) Update: print(all(i in lists for i in check) and [lists.index(i) for i in check]==range([lists.index(i) for i in check][0],[lists.index(i) for i in check][-1]+1))
has comment: http://stackoverflow.com/comment/91887096
answers question: http://stackoverflow.com/q/52472561
has comment: http://stackoverflow.com/comment/91887111
has comment: http://stackoverflow.com/comment/91887016
has comment: http://stackoverflow.com/comment/91887057
has comment: http://stackoverflow.com/comment/91887136
has comment: http://stackoverflow.com/comment/91887069
has comment: http://stackoverflow.com/comment/91887130
has comment: http://stackoverflow.com/comment/91886991
has comment: http://stackoverflow.com/comment/91887427
has comment: http://stackoverflow.com/comment/91887152
has comment: http://stackoverflow.com/comment/91887287
has comment: http://stackoverflow.com/comment/91887052
has comment: http://stackoverflow.com/comment/91887076
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91887125

http://stackoverflow.com/comment/91946628
comment on: http://stackoverflow.com/q/52501454
has text: Thanks for quickly clearing my doubt!! Question of a newbie to python..
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92061765
has text: Thanks MattR, but I want the Category column to consists of alphabets, not numbers
type: Comment
comment on: http://stackoverflow.com/a/52561611
type: AnswerComment
score: 0

http://stackoverflow.com/q/52528090
has comment: http://stackoverflow.com/comment/91996040
downvote count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/15479928
answer count: 1
has title: Printing order of elements in a dictionary
has comment: http://stackoverflow.com/comment/91995892
has comment: http://stackoverflow.com/comment/91995849
accepted answer: http://stackoverflow.com/a/52528196
has comment: http://stackoverflow.com/comment/91995901
has comment: http://stackoverflow.com/comment/91995793
type: AnsweredQuestion
tagged with: iteration
tagged with: printing
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52528196
tagged with: python-2.x
tagged with: dictionary
favorite count: 0
score: -1
has body: The Dictionary parm should contain all the keys ['f', 'r', 'b', 'l', 't','u'] and only then the below should happen. The below mentioned iteration prints in an unexpected order, please correct what's wrong. parm = {'r':'r', 'l':'l', 't':'t', 'u':'u', 'f':'f', 'b':'b'} if all(key in parm for key in ['f', 'r', 'b', 'l', 't','u']): parm = [_ for _ in parm.values() for i in range(0,9)] print (parm) Returns: ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 't', 't', 't', 't', 't', 't', 't', 't', 't'] Expected: ['f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 't', 't', 't', 't', 't', 't', 't', 't', 't', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u',]

http://stackoverflow.com/comment/91812300
comment on: http://stackoverflow.com/a/52434034
type: Comment
has text: The `0` says replace the 0th indexed element in format, i.e. `x`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92011381
has text: Byte objects are indeed immutable, but you can make a *new* byte array, for example with `a[:2] + 'F' + a[3:]`.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52535980
type: Comment

http://stackoverflow.com/comment/91811495
type: QuestionComment
comment on: http://stackoverflow.com/q/52433611
type: Comment
score: 0
has text: Thank you, I edited the name of the module and I made a simpler code that you can use to replicate the issue. Thank you very much.

http://stackoverflow.com/comment/91845856
type: Comment
type: QuestionComment
has text: Have you tried printing out the message object to see what is actually being passed? Try doing so both on the Python side and on the JS side.
comment on: http://stackoverflow.com/q/52451179
score: 0

http://stackoverflow.com/q/52536997
tagged with: list
has comment: http://stackoverflow.com/comment/92013324
has comment: http://stackoverflow.com/comment/92013712
accepted answer: http://stackoverflow.com/a/52537068
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52537417
upvote count: 9
tagged with: if-statement
tagged with: list-comprehension
score: 9
has answer: http://stackoverflow.com/a/52537121
has answer: http://stackoverflow.com/a/52537760
has comment: http://stackoverflow.com/comment/92013655
has body: I'm trying to get my head around nested list comprehension and have read the excellent explanation here. The problem I'm having translating is that I've an if clause in my inner loop and I can't see how to apply this to the func() step as I'm loosing the counter I get from enumerate() when I go from nested loops to list comprehension. nested_list = [[{'a': 1, 'b': 2}, {'c': 3, 'd': 4}], [{'a': 5, 'b': 6}, {'c': 7, 'd': 8}]] new_list = [] for c, x in enumerate(nested_list): for d, y in enumerate(x): if d == 1: new_list.append(y) print(new_list) [{'c': 3, 'd': 4}, {'c': 7, 'd': 8}] Nested list comprehension might look something like new_list = [if ??? y for x in nested_list for y in x] ...but I can't see/think how to get the clause as I have no counter under the nested list comprehension. Is there a way of achieving this or should I stick to the nested loops approach?
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52537121
has comment: http://stackoverflow.com/comment/92013459
has answer: http://stackoverflow.com/a/52537068
has comment: http://stackoverflow.com/comment/92013487
has title: Nested list comprehension with if statement
has comment: http://stackoverflow.com/comment/92013513
linked to: http://stackoverflow.com/q/18072759
tagged with: python
has comment: http://stackoverflow.com/comment/92013310
answer count: 4

http://stackoverflow.com/comment/92066956
has text: Yes 15 min interval is just a simplification in this example
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52564186
score: 0

http://stackoverflow.com/comment/92049444
has text: I really can't follow what this code is doing. Why do you have `df = pd.read_csv("2018-19.csv")` inside a `for` loop?
score: 0
comment on: http://stackoverflow.com/q/52555225
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92045216
type: Comment
has text: Yes I know what `__slots__` does. With type annotations, I mostly meant just specifying a docstring which is recognized by PyCharm. But what you are saying is basically that I should just add sth like this in the class? `ref_seq_idx = None # type: int` *Edit* I just tried, but then it complains that this conflicts with class variable in `__slots__`. *Edit* Ok, doing the same thing in `__init__` works.
comment on: http://stackoverflow.com/a/52553217
score: 0
type: AnswerComment

http://stackoverflow.com/q/52587552
downvote count: 0
favorite count: 0
has title: Scrapy Contracts - Unhandled error in Deferred
answer count: 1
has answer: http://stackoverflow.com/a/52588173
tagged with: web-scraping
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I am writing a spider using Scrapy, and I am currently adding contracts to the spider. The spider is still running fine, but I am getting weird results when running checks, after adding @returns in the contracts. @returns response 1 I am suddenly getting "Unhandled error is Deferred" when running scrapy check: $ scrapy check regjeringen_no ---------------------------------------------------------------------- Ran 0 contracts in 0.000s OK Unhandled error in Deferred: The spider code: # -*- coding: utf-8 -* import scrapy class RegjeringenNoSpider(scrapy.Spider): '''A spider to crawl the Norwegian Government's pages containing news, speeches and opinions''' name = "regjeringen_no" start_urls = [ 'https://www.regjeringen.no/no/aktuelt/taler_artikler/', 'https://www.regjeringen.no/no/aktuelt/nyheter/', ] def parse(self, response): '''Parses the response downloaded for each of the requests made. Some contracts are mingled with this docstring. @url https://www.regjeringen.no/no/aktuelt/taler_artikler/ @url https://www.regjeringen.no/no/aktuelt/nyheter/ @returns response 1 ''' self.logger.info('Parse function called on %s', response.url) for href in response.css('li.listItem h2.title a::attr(href)'): yield response.follow(href, callback=self.parse_article) for href in response.css('li.next a::attr(href)'): yield response.follow(href, callback=self.parse) def parse_article(self, response): '''Parse response for pages with a single article''' self.logger.info('Parse article function called on %s', response.url) yield { 'article_title': self._extract_with_css("header.article-header h1::text", response), 'article_date': self._extract_with_css("div.article-info span.date::text", response), 'article_type': self._extract_with_css("div.article-info span.type::text", response), 'article_lead': self._extract_with_css("div.article-ingress p::text", response), 'article_text': self._extract_with_css("div.article-body::text", response), } def _extract_with_css(self, query, response): ret…
score: 1
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/52588173

http://stackoverflow.com/a/52502784
score: 3
downvote count: 1
upvote count: 4
has body: Besides the fact that you need to be careful with "\" and instead of : locationDir="D:\something_else.py" prepend your string with r: locationDir=r"D:\something_else.py" you can simply set the PYTHONPATH environment variable to point to the directory in which sit the other modules. See here for additional informations : https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH
has comment: http://stackoverflow.com/comment/91969539
has comment: http://stackoverflow.com/comment/91947894
has comment: http://stackoverflow.com/comment/91946973
type: Answer
answers question: http://stackoverflow.com/q/52502689
has comment: http://stackoverflow.com/comment/91949397

http://stackoverflow.com/q/52536810
has body: I able to split a list into array of chunks from a list as demonstrated in the bellow python code: def split_list(the_list, chunk_size): result_list = [] while the_list: result_list.append(the_list[:chunk_size]) the_list = the_list[chunk_size:] return result_list a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print split_list(a_list, 3) which yield the bellow result of array of chunks: # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] I am also aware of making a random sample through numpy.random.choice (even with replacement) as demonstrated bellow: import numpy as np a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] np.random.choice(a_list, size=20, replace=True) which yields the bellow result: #array([ 6, 9, 4, 9, 1, 1, 6, 10, 8, 5, 10, 6, 2, 6, 7, 1, 3, 2, 7, 6]) What I want I want to sample chunk in the array (while the elements of each chunk is left as it is) with replacement. I am looking forward to get a code that will produce something like this: # [[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [10], [1, 2, 3], [1, 2, 3], [10], [1, 2, 3], [7, 8, 9], [1, 2, 3], [1, 2, 3], [10], [4, 5, 6], [4, 5, 6], [10], [10], [7, 8, 9],, [1, 2, 3], [7, 8, 9]] I picked the above sample of chunk myself, I need help to get a working python code to do that for me.
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52537205
downvote count: 1
type: Question
tagged with: arrays
score: 0
has answer: http://stackoverflow.com/a/52537205
answer count: 1
has title: How to make a random sample of chunk in an array/list (with replacement) instead of sampling the individual elements in the list list with python

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/52481557
tags question: http://stackoverflow.com/q/52495198
tags question: http://stackoverflow.com/q/52523802
tags question: http://stackoverflow.com/q/52524725
tags question: http://stackoverflow.com/q/52513327
tags question: http://stackoverflow.com/q/52484647
tags question: http://stackoverflow.com/q/52536958
tags question: http://stackoverflow.com/q/52543574
tags question: http://stackoverflow.com/q/52584420
tags question: http://stackoverflow.com/q/52544527
tags question: http://stackoverflow.com/q/52497320
tags question: http://stackoverflow.com/q/52488717
tags question: http://stackoverflow.com/q/52588109
tags question: http://stackoverflow.com/q/52542392
tags question: http://stackoverflow.com/q/52439531
tags question: http://stackoverflow.com/q/52504972
tags question: http://stackoverflow.com/q/52509254
tags question: http://stackoverflow.com/q/52434310
tags question: http://stackoverflow.com/q/52572742
tags question: http://stackoverflow.com/q/52513904
tags question: http://stackoverflow.com/q/52545943
tags question: http://stackoverflow.com/q/52544060
tags question: http://stackoverflow.com/q/52458406
tags question: http://stackoverflow.com/q/52522681
tags question: http://stackoverflow.com/q/52494242
tags question: http://stackoverflow.com/q/52584104
type: Tag
tags question: http://stackoverflow.com/q/52450967
tags question: http://stackoverflow.com/q/52433490
tags question: http://stackoverflow.com/q/52482867
tags question: http://stackoverflow.com/q/52442721
tags question: http://stackoverflow.com/q/52439437
tags question: http://stackoverflow.com/q/52582187
tags question: http://stackoverflow.com/q/52447958
tags question: http://stackoverflow.com/q/52587808
tags question: http://stackoverflow.com/q/52536673
tags question: http://stackoverflow.com/q/52564564
tags question: http://stackoverflow.com/q/52532637
tags question: http://stackoverflow.com/q/52517294
tag name: json
tags question: http://stackoverflow.com/q/52456207
tags question: http://stackoverflow.com/q/52450444
tags question: http://stackoverflow.com/q/52442154
tags question: http://stackoverflow.com/q/52491124
tags question: http://stackoverflow.com/q/52522818
tags question: http://stackoverflow.com/q/52517662
tags question: http://stackoverflow.com/q/52443658
tags question: http://stackoverflow.com/q/52467864
tags question: http://stackoverflow.com/q/52488617
tags question: http://stackoverflow.com/q/52510584
tags question: http://stackoverflow.com/q/52441692
tags question: http://stackoverflow.com/q/52548218
tags question: http://stackoverflow.com/q/52533049
tags question: http://stackoverflow.com/q/52449639
tags question: http://stackoverflow.com/q/52477982
tags question: http://stackoverflow.com/q/52587991
tags question: http://stackoverflow.com/q/52575212
tags question: http://stackoverflow.com/q/52559412
tags question: http://stackoverflow.com/q/52467151
tags question: http://stackoverflow.com/q/52574413
tags question: http://stackoverflow.com/q/52526546
tags question: http://stackoverflow.com/q/52502605
tags question: http://stackoverflow.com/q/52496959
tags question: http://stackoverflow.com/q/52505985
tags question: http://stackoverflow.com/q/52472635
tags question: http://stackoverflow.com/q/52523603
tags question: http://stackoverflow.com/q/52505247
tags question: http://stackoverflow.com/q/52445863
tags question: http://stackoverflow.com/q/52480066
tags question: http://stackoverflow.com/q/52453164

http://stackoverflow.com/a/52483513
score: 13
has comment: http://stackoverflow.com/comment/91908731
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52483449
has comment: http://stackoverflow.com/comment/91908772
has comment: http://stackoverflow.com/comment/91909097
upvote count: 13
answers question: http://stackoverflow.com/q/52483449
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91908658
has comment: http://stackoverflow.com/comment/91908461
has body: Setting SESSION_COOKIE_SECURE does not encrypt the cookie value, no. When set, this causes Flask to create cookies with the "Secure" flag set. This means that a browser can only return the cookie to the server over an encrypted connection, nothing more. The setting doesn't change anything about the cookie value itself. Flask produces cookies that are cryptographically signed, by default. That means that the cookie contents can be decoded but not altered, because a third party without access to the server secret can't create a valid signature for the cookie. You generally don't need to encrypt your session cookie if you a) use HTTPS (which encrypts the data from outsiders) and b) protect your web app from XSS attacks. Without an XSS attack vector, attackers can't get access to your cookie contents at all anyway. You certainly don't need to do so here, as SESSION_COOKIE_HTTPONLY means that the browser will never expose the cookie to JavaScript, and only someone with full access to the browser can see the cookie value. Flask doesn't have a 'encrypt cookie' setting, because it is not deemed necessary when you can secure the cookie in other ways. You should not store information in a session cookie so sensitive that it should be protected from the end-user with access to the browser storage; keep such data on the server and only store a unique identifier in the session to retrieve that secret data later on. If for some reason you can't keep such secrets out of the session cookie and are unwilling to accept that the end-user can read this data, then you'll have to encrypt the cookie yourself or use an alternative session provider for Flask, such as EncryptedSession. As for the attribute error: only a few configuration settings are accessible as attributes on the Flask object. To print arbitrary configuration settings, use the app.config object: print(MyApp.config['SESSION_COOKIE_SECURE'])
type: Answer

http://stackoverflow.com/q/52458869
tagged with: algorithm
has title: Maze Solving Using Stack in Python - is my Algorithm correct?
tagged with: stack
score: 1
has answer: http://stackoverflow.com/a/52459102
type: Question
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I've written some Python code to help me understand how to solve a maze using a stack and no recursion. what I've come up with SEEMS to work (as in the target position in the 2d array representing the maze is reached is several versions of the maze). The representation if 1 for a wall, 0 for a space, 2 for the goal and 3 for "visited". However, I'm suspicious and would like someone to confirm whether the logic is correct or if not what I need to do to fix it. My main concern is that coordinates are being put back on the stack even when they have been visited. Please understand the chicken and egg nature of my situation - I don't fully understand how the algorithm works, so I've written some code to help me understand but I'm not sure if the code is correct, which partly depends on understanding the algorithm... As always, any help much appreciated. Code below: class Stack: def __init__(self): self.list = [] def push(self, item): self.list.append(item) def pop(self): return self.list.pop() def top(self): return self.list[0] def isEmpty(self): return not self.list def empty(self): self.list = [] maze = [[0, 0, 1, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 2, 0]] MAZE_SIZE = len(maze) def print_maze(maze): for row in maze: print((row)) def is_valid_pos(tup): (col, row) = tup if col &lt; 0 or row &lt; 0 or col &gt;= MAZE_SIZE or row &gt;= MAZE_SIZE : return False return maze[row][col] == 0 or maze[row][col] == 2 def solve(maze, start): s = Stack() (col,row) = start print('pushing ({},{})'.format(col,row)) s.push((col,row)) while not s.isEmpty(): print('Stack contents: {}'.format(s.list)) input('Press Enter to continue: ') print('Popping stack') (col, row) = s.pop() print('Current position: ({}, {})'.format(col,row)) if maze[row][col] == 2: print('Goal reached at ({}, {})'.format(col,row)) return if maze[row][col] == 0: print('Marking ({}, {})'.format(col,row)) maze[row][col] = 3 print_maze(maze) print('Pushing coordinates of valid positions in 4 directions onto stack.') if …

http://stackoverflow.com/comment/92041496
has text: ImportError: No module named pandas
comment on: http://stackoverflow.com/a/52549470
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91992690
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52526435
has text: Is every entry on one line, and is every field guaranteed to be separated by a space?
score: 0

http://stackoverflow.com/comment/92107824
has text: Thank you. It helps a lot. Just one doubt I haven't came accros `RepeatedStratisfiedKFold`. Can you explain it a bit in the answer on what it does. I always used `cv=10` in `GridSearchCV`? why should I use `cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=2)` rather than cv=10? any advantages?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52577675
type: AnswerComment

http://stackoverflow.com/comment/132217616
has text: Also, which browser are you using
score: 0
comment on: http://stackoverflow.com/q/52580561
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52460040
has answer: http://stackoverflow.com/a/52460796
accepted answer: http://stackoverflow.com/a/52460796
answer count: 1
tagged with: user-interface
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91862265
tagged with: python-3.x
tagged with: paint
upvote count: 2
has comment: http://stackoverflow.com/comment/91863700
tagged with: pyqt5
downvote count: 1
type: Question
type: AnsweredQuestion
has body: I'm trying to implement the equivalent of Paint, and for this I need to make a filling. Can anyone tell how to use PyQt5 to find out the color of a pixel, and use the width search to find similar pixels. And then change all these pixels to a new color. Just in tkinter for this were getpixel and putpixel. I'm wondering if PyQt5 does this. If there is, then I ask to show some example of the implementation of this. P.s. You can without looking for pixels, just show how to take and replace pixels. P.s.s. I apologize for my English, if something is wrong с:
score: 1
has comment: http://stackoverflow.com/comment/91862147
has title: Implementing flood fill in PyQt5

http://stackoverflow.com/comment/92011342
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52535828
has text: And an added motivation to not use `datetime`: because the module expects `time` to be a point in time, the format is limited to a 24h clock. Any duration beyond 24h can't be parsed! I don't think you'll run into that here when taking timings for individual road / cross-country / track races or training runs (humans generally can't run for 24h straight) but it could be a problem if you were to track total time running, for example.
score: 0

http://stackoverflow.com/q/52433611
has answer: http://stackoverflow.com/a/52434067
has comment: http://stackoverflow.com/comment/91811058
has comment: http://stackoverflow.com/comment/91811160
type: Question
has comment: http://stackoverflow.com/comment/91811232
has answer: http://stackoverflow.com/a/52434012
has body: I'm building a calculator and I'm in the part of pressing a button and display the value in the screen. For that purpose, I created two different .py files (I want to use modules). Following up your request I will update the post with the simplest code possible to reproduce the issue. This is the calculator layout: from tkinter import * from screenvalue import value root=Tk() frame=Frame(root) #frame for the buttons and other options frame.config(background="#40798C") frame.pack() #------------------------ SCREEN ---------------------- screen=Text(frame, width=150, height=5) screen.grid(row=1, column=1, padx=5, pady=5, columnspan=15) screen.config(background="#E2E2E2", fg="black") #--------button--------------------------------- button4=Button(frame, text="4", width=10, padx=0, pady=0, command=value) button4.grid(row=4,column=11) root.mainloop() and this is the module I'm using from tkinter import * character=StringVar() def value(): return character.set("4") I changed the name of the module from typing.py to screenvalue.py. Do you know what's happening? They both are in the same folder Thank you very much in advance and my apologies if my English is not clear.
has comment: http://stackoverflow.com/comment/91811014
has comment: http://stackoverflow.com/comment/91811084
score: 0
answer count: 2
has title: Error message when importing function - modules
type: UnansweredQuestion
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/91811495
tagged with: attributes
tagged with: tkinter

http://stackoverflow.com/comment/91978948
has text: Right, so you want to *zip* the nested lists. Note that dictionaries are not really ordered; do you need to sort by keys here?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52518946

http://stackoverflow.com/a/52565713
has comment: http://stackoverflow.com/comment/92069066
type: Answer
accepted answer of: http://stackoverflow.com/q/52565673
has comment: http://stackoverflow.com/comment/92069347
score: 2
answers question: http://stackoverflow.com/q/52565673
upvote count: 2
has comment: http://stackoverflow.com/comment/92069148
has body: Use pandas string slicing str on column as (Since Datatype is object as per OP): df['ColB (New datetime)'] = df['ColA (Localized datetime)'].str[:-6] Or: df['ColB (New datetime)'] = df['ColA (Localized datetime)'].str.slice(start=0,stop=19) print(df) ColA (Localized datetime) ColB (New datetime) 0 2016-09-19 00:29:13-05:00 2016-09-19 00:29:13 1 2016-09-19 04:16:04-02:00 2016-09-19 04:16:04 2 2016-09-19 06:57:54+01:00 2016-09-19 06:57:54 EDIT : Since the previous SO solution output is Timestamp with inconsistent format across the column, Though the data type is object but each value is Timestamp: df['ColB (New datetime)'] = df['ColA (Localized datetime)'].apply(lambda x: x.replace(tzinfo=None))
has comment: http://stackoverflow.com/comment/92069079
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92069362

http://stackoverflow.com/comment/92119051
type: Comment
type: AnswerComment
has text: If the size is fixed and the columns shrink, obviously there has to be some remaining whitespace. What is really strange is that the new Tree width becomes larger than the original total width, wthout need, in the first headers change.
comment on: http://stackoverflow.com/a/52559265
score: 0

http://stackoverflow.com/comment/91934788
comment on: http://stackoverflow.com/q/52497159
score: 2
has text: chaining operator comparisons... try without `==True` or like this `if '(extraarg' in kwargs) == True`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52507943
has body: Wondering if anyone can shed some light on what this error may be coming from. I have just moved to Postgresql from sqllite and at the same time changed my ID fields to UUID. For most of the models it works however I have isolated a few which are causing the migration to fail. The error is: AttributeError: 'int' object has no attribute 'replace' django.core.exceptions.ValidationError: ["'1' is not a valid UUID."] As I said this is a new db and am not aware of any code that would create rows upon migration so not sure where the 1 would be coming from. This question appears quite similar however the asker is explicitly setting the integer and trying to pass it as a UUID Model import uuid class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Trace Running migrations: Applying survey.0001_initial...Traceback (most recent call last): File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2363, in to_python return uuid.UUID(value) File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/uuid.py", line 137, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'int' object has no attribute 'replace' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jd/.virtual…
linked to: http://stackoverflow.com/q/49444648
type: Question
downvote count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/91957452
tagged with: migration
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/108811369
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91972255
tagged with: uuid
has comment: http://stackoverflow.com/comment/91956818
has title: UUID field in fresh Postgresql DB failing ValidationError: ["'1' is not a valid UUID."]

http://stackoverflow.com/q/52483034
has comment: http://stackoverflow.com/comment/91945594
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91908664
has title: Selenium WebDriver : could not be scrolled into view
has comment: http://stackoverflow.com/comment/91910173
downvote count: 0
has comment: http://stackoverflow.com/comment/91908415
has comment: http://stackoverflow.com/comment/91946718
has comment: http://stackoverflow.com/comment/91945722
has comment: http://stackoverflow.com/comment/91909098
tagged with: python
has comment: http://stackoverflow.com/comment/91909069
has comment: http://stackoverflow.com/comment/91945616
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91908276
tagged with: selenium
tagged with: web-scraping
upvote count: 1
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/91908428
has body: I'm trying to do a bot to navigate a website with Python and Selenium Webdriver but I found a trouble when trying to access and change the result_delimiter of some data returned by the site. They have "comma" as default delimiter and I need they to be separate by "New Line" Here is the HTML: Comma New Line Space Vertical Bar And the error it is returning: Traceback (most recent call last): File "C:\Users\...xxx\AsinGrabberTest.py", line 28, in <module> select.click() File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute return self._parent.execute(command, params) File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: Element could not be scrolled into view I know I could download my data with commas and then make the change within the program, BUT I'm unavailable to access to the text Area when the results are showed and copy them. Following, the HTML related to this text area: I would thank any solution, to could select the "new_line" option or to could copy the information provided in the text area. Below, the code used: import selenium from selenium import webdriver from selenium.webdriver.support.ui import Select from pruebaAmazon import copy_link from selenium.webdriver.support.ui import Select browser = webdriver.Firefox() browser.get('http://arkgroup.org/asin-grabber/about/') currentURL = ('https://www.amazon.com/gp/goldbox/ref=gbps_ftr_s-4_bd57_wht_21023130?ref=nav_cs_gb&gb_f_deals1…

http://stackoverflow.com/q/52441524
has body: Script 1: import time print('Wait') time.sleep (10) print('Start') Script 2: from picamera import PiCamera import time camera = PiCamera() camera.start_preview() while(1): time.sleep(100) camera.capture('/home/pi/image.jpg') camera.stop_preview How can I say to Script 1 start after sleep the second Script at Autostart? Because I have use the second script with crontab and I can't execute it when it has started. So I want to try to start from .config/autostart/ with a .desktop script.
tagged with: python
has comment: http://stackoverflow.com/comment/91826806
has comment: http://stackoverflow.com/comment/91829644
score: 1
has title: How can i start a bash and after then my script
upvote count: 1
has comment: http://stackoverflow.com/comment/91829881
type: Question
has comment: http://stackoverflow.com/comment/91826415
tagged with: bash
has comment: http://stackoverflow.com/comment/91825845
answer count: 1
tagged with: scripting
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52478389
type: UnansweredQuestion

http://stackoverflow.com/comment/91884871
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52460123
has text: "automatically" like using some API instead of having a human running some Kafka command line to create a new consumer group.

http://stackoverflow.com/comment/92757525
has text: Thanks a lot for staying with me on this issue. Unfortunately, converting the input sequences to double arrays only results in (roughly) the same output. :-(
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/52517579
type: Comment

http://stackoverflow.com/q/52505620
tagged with: excel
has comment: http://stackoverflow.com/comment/91952074
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91952175
score: -1
has comment: http://stackoverflow.com/comment/91951879
has body: I would like to use python 3.4 to compare columns. I have two columns a and b If A=B print A in column C. If B &gt; A, print all numbers between A and B including A and B in column C. The subsequent compared rows would print in column C after the results of the previous test. Any help is appreciated. My question wording must be off as I'm sure this has been done before, but I just can't find it here or elsewhere.
answer count: 1
has title: How do I expand a range between two excel cells in python 3 and add results to a new column?
has answer: http://stackoverflow.com/a/52506394
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52462179
has body: You could represent your vertices as a list composed of the vertex numbers, and a list of edges, as tuples corresponding to the destination vertices and the weight of the edge: Your graph could look something like this: [1, [(2, 14), (3, 10)]] [2, [(1, 14), (4, 2)]] [3, [(1, 10)]] [4, [(2, 2)]] where: edge ----- [3, [(1, 10)]] ^ ^ ^ weight | destination vertice Vertice number
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52461929

http://stackoverflow.com/q/52460146
upvote count: 1
downvote count: 1
favorite count: 0
has title: flask project- css not pulling in colors
has comment: http://stackoverflow.com/comment/91865065
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/22259847
tagged with: python
has comment: http://stackoverflow.com/comment/91865104
has comment: http://stackoverflow.com/comment/91868118
has answer: http://stackoverflow.com/a/52470601
type: Question
answer count: 1
has body: I'm new to web development in python. I'm working on converting a project from php over to flask. I followed the instructions in this post (Application not picking up .css file (flask/python)), and now my text is centered, so I know that I'm linked to my stylesheet. But I'm not getting any colors on my pages. Not sure what I did wrong. Here is my css file: body { background-color: #003300; text-align: center; } .greenones{ color: #003300; text-align: center; } .redones{ color: #dd164e; text-align: center; } .yellowones{ color: #CA9800; text-align: center; } .orangeones{ color: #ff6600; text-align: center; } .centerMe{ text-align: center; } .dropdown-toggle{ color: #CA9800; } .yellowleft{ color: #CA9800; text-align: left; } .leagueguide{ color: #CA9800; text-align: left; list-style-type: upper-roman; } .leagueguide-indent{ color: #CA9800; text-align: left; list-style-type: upper-alpha; } .leagueguide-decimal{ color: #CA9800; text-align: left; list-style-type: decimal; } div.well { font-weight: bold; } a { font-weight: bold; } img.align-left { float: left; margin-right: 10 px; text-align: left; } label.yellow, div.yellow{ color: #CA9800; } label.logs{ color: #CA9800; text-align: right; padding: 10px 10px 10px 10px; } table.statsTable{ text-align: center; color: #003300; padding: 3px; } td.cen { text-align: center; } #login-dp{ min-width: 250px; padding: 14px 14px 0; overflow:hidden; background-color:rgba(255,255,255,.8); } #login-dp .help-block{ font-size:12px } #login-dp .bottom{ background-color:rgba(255,255,255,.8); border-top:1px solid #ddd; clear:both; padding:14px; } #login-dp .social-buttons{ margin:12px 0 } #login-dp .social-buttons a{ width: 49%; } #login-dp .form-group { margin-bottom: 10px; } .btn-fb{ color: #fff; background-color:#3b5998; } .btn-fb:hover{ color: #fff; background-color:#496ebc } .btn-tw{ color: #fff; background-color:#55acee; } .btn-tw:hover{ color: #fff; background-color:#59b5fa; } @media(max-width:768px){ #login-dp{ background-color: inhe…
tagged with: flask
score: 0

http://stackoverflow.com/a/52588746
accepted answer of: http://stackoverflow.com/q/52588168
downvote count: 0
answers question: http://stackoverflow.com/q/52588168
upvote count: 2
type: Answer
score: 2
has body: something like this might work: mat = [[True, False, False, True], [False, False, True, False], [True, True, False, True]] max_i = len(mat) max_j = len(mat[0]) def surrounding(i, j): ret = [] for ii in range(max(0, i-1), min(i+2, max_i)): for jj in range(max(0, j-1), min(j+2, max_j)): if (ii, jj) == (i, j): continue ret.append(int(mat[ii][jj])) return ret note the min and max functions inside the ranges that take care of the borders of your matrix. and as python bools are subclasses of int anyway, True and False can just be cast to int.
type: AcceptedAnswer

http://stackoverflow.com/q/52501232
accepted answer: http://stackoverflow.com/a/54448045
has body: Versions Python 3.7.0 pyOpenSSL 18.0.0 requests 2.19.1 requests-futures 0.9.7 urllib3 1.23 <a href="https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHL/MapServer/identify?imageDisplay=1000,1000&amp;geometryType=esriGeometryEnvelope&amp;geometry=-8987371.414955758,4875311.000052227,-8986571.414955758,4876111.000052227&amp;tolerance=0&amp;mapExtent=-8987371.414955758,4875311.000052227,-8986571.414955758,4876111.000052227&amp;f=JSON&amp;layers=visible:16,20,21,28&amp;returnGeometry=true" rel="nofollow noreferrer">https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHL/MapServer/identify I am unable to receive a full response from an ArcGIS rest API when using Python. I am able to navigate to the URL via Chrome and am also able to make the GET request in Postman without issue. The link above is an example of a successful GET request with the JSON response I am expecting. I have tried writing the request using requests, urllib, and socket. Obviously, both requests and socket both fail at recv_into. When running the below code, I receive exactly two chunks before I get the WSAECONNRESET error. If I make a request with geometry set to false, the response is much smaller and returns without issue. I am at a loss for why the connection is only closing in Python and could really use some help fixing it or an alternative to make the query. Thanks! Code def FEMA_identify(self, latitude, longitude, layers, is_envelope=False, envelope_range=None, return_geometry=False): envelope = self.getEnvelope(envelope_range, latitude, longitude) if\ is_envelope else self.getPoint(latitude, longitude) extent = envelope if is_envelope else\ self.getEnvelope(100, latitude, longitude) geometry_type =\ "esriGeometryEnvelope" if is_envelope else "esriGeometryPoint" payload = { "imageDisplay": "1000,1000", "geometrytype": geometry_type, "geometry": f"{envelope.x_min},{envelope.y_min},{envelope.x_max},{envelope.y_max}", "tolerance": f"{0}", "mapExtent": f"{extent.x_min},{extent.y_min},{e…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has title: OpenSSL.SSL.SysCallError: (10054, 'WSAECONNRESET') during GET request to ArcGIS API
upvote count: 3
has answer: http://stackoverflow.com/a/54448045
tagged with: python-requests
type: AnsweredQuestion
score: 3
type: Question

http://stackoverflow.com/comment/92100994
has text: Why are you using `POST` if you're not actually submitting any post data? Also, why are you using a session if you're only performing one action?
score: 0
comment on: http://stackoverflow.com/q/52582830
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52492315
score: 0
answer count: 3
has title: ImportError: No module named bs4 - despite bs4 and BeautifulSoup being installed
tagged with: macos
favorite count: 0
type: UnansweredQuestion
has body: I downloaded Python 3.7 and am running a script with "from bs4 import BeautifulSoup" and am receiving the following error on execution; "File "myscript.py", line 3, in from bs4 import BeautifulSoup ImportError: No module named bs4" When I type "pip3 install bs4" or "pip3 install BeautifulSoup4" in the terminal I get the following; "Requirement already satisfied: bs4 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (0.0.1) Requirement already satisfied: beautifulsoup4 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from bs4) (4.6.3)" Executing "import bs4" and "from bs4 import BeautifulSoup" in IDLE don't error out. Any idea about what's going on?
tagged with: python
has answer: http://stackoverflow.com/a/74641567
upvote count: 1
has answer: http://stackoverflow.com/a/56063007
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52492458

http://stackoverflow.com/a/52441938
has body: You can also use Series.nlargest, so sorting arguments won't matter: data2['name'].value_counts().nlargest(3).index
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52441836
upvote count: 1
has comment: http://stackoverflow.com/comment/91826556

http://stackoverflow.com/a/52532870
type: Answer
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/52532846
has body: You need to give path to folder as well. for filename in f: h1 = Image.open(os.path.join(f, filename)).histogram()

http://stackoverflow.com/comment/91875797
type: Comment
has text: please check the column names and give proper column names in place of column df["' "] (df.columns will give proper name of column) @EricMyhre
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52466810

http://stackoverflow.com/q/52518294
has comment: http://stackoverflow.com/comment/91976135
type: Question
has comment: http://stackoverflow.com/comment/91976435
score: -2
tagged with: django-models
has body: keywords=Donut working with keyword__name__in=Donut but i need to get result keyword__name__in=Don views.py items=ItemVariation.objects.filter(item__restaurant__id = i['restaurant']['id'],keyword__name__in=keyword,keyword__mood__moods=mood).select_related() # items=ItemVariation.objects.filter(item__restaurant__id = i['restaurant']['id'],keyword__name__contains=keyword,keyword__mood__moods=mood).select_related() # it is returning null # items=ItemVariation.objects.filter(item__restaurant__id = i['restaurant']['id'],keyword__name__icontains=keyword,keyword__mood__moods=mood).select_related() models.py class Keyword(models.Model): name=models.CharField(max_length=500,unique=True) image = models.ImageField(upload_to='keywords/', blank=True, null=True) mood=models.ManyToManyField(Mood,blank=True) def __str__(self): return str(self.name) class ItemVariation(models.Model): restaurant=models.ForeignKey(Restaurant,on_delete=models.CASCADE) item=models.ForeignKey(Item,on_delete=models.CASCADE) price=models.IntegerField(blank=True,null=True,default=0) item_code=models.CharField(max_length=500) keyword= models.ManyToManyField(Keyword) image=models.ImageField(upload_to='dishes/', blank=True, null=True) i have this query i need to use keyword__name__in= %keyword% as a like i'm using PostgreSQL database parameter that i'm passing for this /?keywords=Donut&amp;mood=Dating result when i'm using keyword__name__in "items": [ { "id": 7, "item": { "name": "Donut", "short_description": "Donuts" }, "price": 0, "item_code": "test", "image": "/media/dishes/download_3_kcE78IS.jpeg", "restaurant": 1, "keyword": [ 3 ] } ], result when i'm using icontains "items": [],
upvote count: 0
has comment: http://stackoverflow.com/comment/91980325
has comment: http://stackoverflow.com/comment/91976724
answer count: 1
has comment: http://stackoverflow.com/comment/91976255
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91976466
has answer: http://stackoverflow.com/a/52518369
has comment: http://stackoverflow.com/comment/91976487
has comment: http://stackoverflow.com/comment/92011500
downvote count: 2
has title: ORM 'like' query in django python

http://stackoverflow.com/comment/91994739
score: 0
type: Comment
has text: I can help you with the download issue, but please open a new question since it is distinct from this one and too big to put in a comment.
type: AnswerComment
comment on: http://stackoverflow.com/a/52522463

http://stackoverflow.com/a/52566767
has comment: http://stackoverflow.com/comment/92071348
has body: def post(self,request): user_serializer=UserSerializer(request.user, data=request.data, partial=True) if user_serializer.is_valid(): user_serializer.save() return Response(user_serializer.data, status=status.HTTP_200_OK) else: return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
has comment: http://stackoverflow.com/comment/92071005
has comment: http://stackoverflow.com/comment/92071180
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52566728
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/92071040
answers question: http://stackoverflow.com/q/52566728
has comment: http://stackoverflow.com/comment/92070858
has comment: http://stackoverflow.com/comment/92070925

http://stackoverflow.com/a/52465229
type: Answer
accepted answer of: http://stackoverflow.com/q/52465066
upvote count: 43
has comment: http://stackoverflow.com/comment/131701931
answers question: http://stackoverflow.com/q/52465066
downvote count: 0
has comment: http://stackoverflow.com/comment/132323535
type: AcceptedAnswer
has body: The more complete answer to what argpartition does is in the documentation of partition, and that one says: Creates a copy of the array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined. So, for the input array 3, 4, 2, 1, the sorted array would be 1, 2, 3, 4. The result of np.partition([3, 4, 2, 1], 3) will have the correct value (i.e. same as sorted array) in the 3rd (i.e. last) element. The correct value for the 3rd element is 4. Let me show this for all values of k to make it clear: np.partition([3, 4, 2, 1], 0) - [1, 4, 2, 3] np.partition([3, 4, 2, 1], 1) - [1, 2, 4, 3] np.partition([3, 4, 2, 1], 2) - [1, 2, 3, 4] np.partition([3, 4, 2, 1], 3) - [2, 1, 3, 4] In other words: the k-th element of the result is the same as the k-th element of the sorted array. All elements before k are smaller than or equal to that element. All elements after it are greater than or equal to it. The same happens with argpartition, except argpartition returns indices which can then be used for form the same result.
score: 43
has comment: http://stackoverflow.com/comment/134716544

http://stackoverflow.com/comment/91971632
type: Comment
type: QuestionComment
has text: Its because range will start from 0 and end at 9
score: 1
comment on: http://stackoverflow.com/q/52515900

dataframe
tags question: http://stackoverflow.com/q/52435166
tags question: http://stackoverflow.com/q/52492620
tags question: http://stackoverflow.com/q/52486670
tags question: http://stackoverflow.com/q/52488252
tags question: http://stackoverflow.com/q/52489397
tags question: http://stackoverflow.com/q/52442589
tags question: http://stackoverflow.com/q/52507108
tags question: http://stackoverflow.com/q/52574923
tags question: http://stackoverflow.com/q/52579551
tags question: http://stackoverflow.com/q/52435537
tags question: http://stackoverflow.com/q/52544301
tags question: http://stackoverflow.com/q/52510403
tags question: http://stackoverflow.com/q/52579942
tags question: http://stackoverflow.com/q/52446136
tags question: http://stackoverflow.com/q/52470997
tags question: http://stackoverflow.com/q/52463349
tags question: http://stackoverflow.com/q/52559300
tags question: http://stackoverflow.com/q/52439437
tags question: http://stackoverflow.com/q/52564723
tags question: http://stackoverflow.com/q/52487691
tags question: http://stackoverflow.com/q/52505165
tags question: http://stackoverflow.com/q/52566588
tags question: http://stackoverflow.com/q/52470712
tags question: http://stackoverflow.com/q/52487785
tags question: http://stackoverflow.com/q/52500722
tags question: http://stackoverflow.com/q/52466374
tags question: http://stackoverflow.com/q/52436394
tags question: http://stackoverflow.com/q/52443444
tags question: http://stackoverflow.com/q/52449789
tags question: http://stackoverflow.com/q/52538454
tags question: http://stackoverflow.com/q/52491327
tags question: http://stackoverflow.com/q/52436238
tags question: http://stackoverflow.com/q/52505268
tags question: http://stackoverflow.com/q/52528568
tags question: http://stackoverflow.com/q/52584849
tags question: http://stackoverflow.com/q/52468543
tags question: http://stackoverflow.com/q/52434359
tags question: http://stackoverflow.com/q/52498848
tags question: http://stackoverflow.com/q/52484129
tags question: http://stackoverflow.com/q/52568152
tags question: http://stackoverflow.com/q/52564456
tags question: http://stackoverflow.com/q/52509972
tags question: http://stackoverflow.com/q/52560895
tags question: http://stackoverflow.com/q/52436345
tags question: http://stackoverflow.com/q/52464947
tags question: http://stackoverflow.com/q/52469357
tags question: http://stackoverflow.com/q/52575354
tags question: http://stackoverflow.com/q/52516924
tags question: http://stackoverflow.com/q/52493365
tags question: http://stackoverflow.com/q/52526818
tags question: http://stackoverflow.com/q/52585836
tags question: http://stackoverflow.com/q/52469045
tags question: http://stackoverflow.com/q/52509633
tags question: http://stackoverflow.com/q/52479184
tags question: http://stackoverflow.com/q/52450505
tags question: http://stackoverflow.com/q/52529663
tags question: http://stackoverflow.com/q/52577080
tags question: http://stackoverflow.com/q/52547142
tags question: http://stackoverflow.com/q/52496060
tags question: http://stackoverflow.com/q/52552185
tags question: http://stackoverflow.com/q/52503363
tags question: http://stackoverflow.com/q/52492961
tags question: http://stackoverflow.com/q/52567912
tags question: http://stackoverflow.com/q/52494999
tags question: http://stackoverflow.com/q/52524014
tags question: http://stackoverflow.com/q/52493921
tags question: http://stackoverflow.com/q/52484290
tags question: http://stackoverflow.com/q/52454730
tags question: http://stackoverflow.com/q/52532519
tags question: http://stackoverflow.com/q/52510752
tags question: http://stackoverflow.com/q/52485217
tags question: http://stackoverflow.com/q/52564080
tags question: http://stackoverflow.com/q/52437024
tags question: http://stackoverflow.com/q/52465355
tags question: http://stackoverflow.com/q/52523455
tags question: http://stackoverflow.com/q/52491530
tags question: http://stackoverflow.com/q/52484271
tags question: http://stackoverflow.com/q/52504640
tags question: http://stackoverflow.com/q/52461523
tags question: http://stackoverflow.com/q/52569340

http://stackoverflow.com/q/52584420
has title: Read in a JSON file
has comment: http://stackoverflow.com/comment/92103925
has comment: http://stackoverflow.com/comment/92103779
has comment: http://stackoverflow.com/comment/92103829
has comment: http://stackoverflow.com/comment/92103783
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52584502
accepted answer: http://stackoverflow.com/a/52584502
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/92103929
has comment: http://stackoverflow.com/comment/92103872
has comment: http://stackoverflow.com/comment/92103859
has comment: http://stackoverflow.com/comment/92103857
type: Question
has comment: http://stackoverflow.com/comment/92103806
has comment: http://stackoverflow.com/comment/92103743
score: -1
has body: I am trying to read in a JSON file into python, but a test script I am running after my code is giving me an error. Here is my code to read in the JSON file when my function is called. The data file is saved on the same server and there aren't any known issues with that file. def read_json(data_file): ''' A function which reads in a JSON file. Parameters ------- data_file: a string, the name of the file to be read in. Returns -------- data: a Python list containing the read in data from the json file. ''' with open(data_file) as fin: data = json.load(fin) return data Here is the test script that calls the function. data_file = './data/dow_jones.json' data = read_json(data_file) Here is the error I am receiving from the previous call. JSONDecodeError: Expecting value: line 1 column 1 (char 0)
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/92103797
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92103864
has comment: http://stackoverflow.com/comment/92103805

http://stackoverflow.com/a/52439457
upvote count: 2
has comment: http://stackoverflow.com/comment/91828944
has body: Normally the child threads die when the main thread exits. The code you've given as example exits directly after starting two child threads. To solve this, you should 'join' the threads back to the main thread. This will make it so the main thread waits for the child threads to die. thread1.join() thread2.join() at the end of your file should solve this problem. https://docs.python.org/3.5/library/threading.html#threading.Thread.join Also, why do you want to run this application as daemon?
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91822030
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52439021
downvote count: 0
has comment: http://stackoverflow.com/comment/91823045
accepted answer of: http://stackoverflow.com/q/52439021

http://stackoverflow.com/comment/91850334
type: QuestionComment
score: 1
has text: You made a new list instead of mutating the object. Please explain in excruciating detail why you expected to get the same id.
type: Comment
comment on: http://stackoverflow.com/q/52453670

http://stackoverflow.com/a/74376227
has comment: http://stackoverflow.com/comment/133590327
has comment: http://stackoverflow.com/comment/133594282
has comment: http://stackoverflow.com/comment/131407258
has comment: http://stackoverflow.com/comment/133910360
has comment: http://stackoverflow.com/comment/133590317
type: Answer
has comment: http://stackoverflow.com/comment/131411066
score: 32
has comment: http://stackoverflow.com/comment/140205599
downvote count: 1
answers question: http://stackoverflow.com/q/52468956
has comment: http://stackoverflow.com/comment/140153950
upvote count: 33
has body: This might be a late answer. But, especially with __torch_function__ developed, it is possible to get better visualization. You can try my project here, torchview For your example of resnet50, you check the colab notebook, here where I demonstrate visualization of resnet18 model. The image of resnet18 is produced by the following code import torchvision from torchview import draw_graph model_graph = draw_graph(resnet18(), input_size=(1,3,224,224), expand_nested=True) model_graph.visual_graph It also accepts a wide range of output/input types (e.g. list, dictionary)

http://stackoverflow.com/q/52495246
favorite count: 0
has answer: http://stackoverflow.com/a/52498284
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91934043
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91931126
has comment: http://stackoverflow.com/comment/91931043
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/91931138
has body: There is unique ID that changes for the text field, but the text field is the same! The id every time looks like this: id-e9eeb082b846435682bfe4ce10359f17- css //*[@id="id-e9eeb082b846435682bfe4ce10359f17"] - xpath html body div.main.main_bottom-740 div.container div.row div.col-md-24.col-xs-24 div.article-area.article-area_without-top-radius form.step2 div.row div.col-md-12.col-xs-12 input#id-e9eeb082b846435682bfe4ce10359f17.input.input__field.input_full-width.input_with-label-above.input_email-validation - path to CSS I want to know how to choose it by another way - xpath, or id does not work
has title: Alternative selection for element with unique ID - python selenium?
upvote count: 1
answer count: 1

http://stackoverflow.com/q/52455742
favorite count: 0
has comment: http://stackoverflow.com/comment/91853955
has answer: http://stackoverflow.com/a/52455768
has title: for loop doesen't iterate over string in a function but does without function - python 3
tagged with: python
accepted answer: http://stackoverflow.com/a/52455779
type: AnsweredQuestion
tagged with: loops
upvote count: 1
type: Question
has body: my code: def word_distribution(stringeling): for char in "?!.,": Satz = stringeling.replace(char,"") return Satz print(word_distribution("Hallo du Peter? Du! und punkt. und komma,")) output: Hallo du Peter Du! und punkt. und komma The code does only remove the first "?" Why when i use the for loop without the function it prints me all the word without punctuation. Thanks for help ;)
has comment: http://stackoverflow.com/comment/91854214
has answer: http://stackoverflow.com/a/52455779
has comment: http://stackoverflow.com/comment/91853893
has answer: http://stackoverflow.com/a/52455948
answer count: 3
tagged with: for-loop
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/52455768
tagged with: string

http://stackoverflow.com/a/61521566
downvote count: 1
score: 5
has body: Strictly speaking, CPython supports multi-io-bound-thread + single-cpu-bound-thread. I/O bound method: file.open, file.write, file.read, socket.send, socket.recv, etc. When Python calls these I/O functions, it will release GIL and acquire GIL after I/O function returns implicitly. CPU bound method: arithmetic calculation, etc. C extension method: method must call PyEval_SaveThread and PyEval_RestoreThread explicitly to tell the Python interpreter what you are doing.
answers question: http://stackoverflow.com/q/52507601
type: Answer
upvote count: 6

http://stackoverflow.com/a/52433871
upvote count: 1
downvote count: 0
has body: numpy.histogram is also a useful option for discretizing stuff
answers question: http://stackoverflow.com/q/52433738
type: Answer
score: 1

pandas
tags question: http://stackoverflow.com/q/52473547
tags question: http://stackoverflow.com/q/52523230
tags question: http://stackoverflow.com/q/52432844
tags question: http://stackoverflow.com/q/52456078
tags question: http://stackoverflow.com/q/52463343
tags question: http://stackoverflow.com/q/52461668
tags question: http://stackoverflow.com/q/52548467
tags question: http://stackoverflow.com/q/52535214
tags question: http://stackoverflow.com/q/52564511
tags question: http://stackoverflow.com/q/52497554
tags question: http://stackoverflow.com/q/52457779
tags question: http://stackoverflow.com/q/52553666
tags question: http://stackoverflow.com/q/52471331
tags question: http://stackoverflow.com/q/52516504
tags question: http://stackoverflow.com/q/52548121
tags question: http://stackoverflow.com/q/52481942
tags question: http://stackoverflow.com/q/52533864
tags question: http://stackoverflow.com/q/52586240
tags question: http://stackoverflow.com/q/52547805
tags question: http://stackoverflow.com/q/52454127
tags question: http://stackoverflow.com/q/52493360
tags question: http://stackoverflow.com/q/52579274
tags question: http://stackoverflow.com/q/52573743
tags question: http://stackoverflow.com/q/52447748
tags question: http://stackoverflow.com/q/52523946
tags question: http://stackoverflow.com/q/52529948
tags question: http://stackoverflow.com/q/52437670
tags question: http://stackoverflow.com/q/52494087
tags question: http://stackoverflow.com/q/52519887
tags question: http://stackoverflow.com/q/52550227
tags question: http://stackoverflow.com/q/52485146
tags question: http://stackoverflow.com/q/52487801
tags question: http://stackoverflow.com/q/52507154
tags question: http://stackoverflow.com/q/52581439
tags question: http://stackoverflow.com/q/52471078
tags question: http://stackoverflow.com/q/52474886
tags question: http://stackoverflow.com/q/52584417
tags question: http://stackoverflow.com/q/52463149
tags question: http://stackoverflow.com/q/52475010
tags question: http://stackoverflow.com/q/52485569
tags question: http://stackoverflow.com/q/52450323
tags question: http://stackoverflow.com/q/52465771
tags question: http://stackoverflow.com/q/52506364
tags question: http://stackoverflow.com/q/52522952
tags question: http://stackoverflow.com/q/52447970
tags question: http://stackoverflow.com/q/52517399
tags question: http://stackoverflow.com/q/52500666
tags question: http://stackoverflow.com/q/52569194
tags question: http://stackoverflow.com/q/52564186
tags question: http://stackoverflow.com/q/52480841
tags question: http://stackoverflow.com/q/52433721
tags question: http://stackoverflow.com/q/52438300
tags question: http://stackoverflow.com/q/52442499
tags question: http://stackoverflow.com/q/52583061
tags question: http://stackoverflow.com/q/52521944
tags question: http://stackoverflow.com/q/52538878
tags question: http://stackoverflow.com/q/52492232
tags question: http://stackoverflow.com/q/52489565
tags question: http://stackoverflow.com/q/52446571
tags question: http://stackoverflow.com/q/52492949
tags question: http://stackoverflow.com/q/52569810
tags question: http://stackoverflow.com/q/52491442
tags question: http://stackoverflow.com/q/52492928
tags question: http://stackoverflow.com/q/52452996
tags question: http://stackoverflow.com/q/52517311
tags question: http://stackoverflow.com/q/52450278
tags question: http://stackoverflow.com/q/52572518
tags question: http://stackoverflow.com/q/52509491
tags question: http://stackoverflow.com/q/52588298
tags question: http://stackoverflow.com/q/52487862
tags question: http://stackoverflow.com/q/52485496
tags question: http://stackoverflow.com/q/52538849
tags question: http://stackoverflow.com/q/52431602
tags question: http://stackoverflow.com/q/52460620
tags question: http://stackoverflow.com/q/52456900
tags question: http://stackoverflow.com/q/52503700
tags question: http://stackoverflow.com/q/52472270
tags question: http://stackoverflow.com/q/52564644
tags question: http://stackoverflow.com/q/52502179
tags question: http://stackoverflow.com/q/52572316

http://stackoverflow.com/comment/92073497
comment on: http://stackoverflow.com/a/52566514
type: AnswerComment
score: 0
type: Comment
has text: I updated my answer. `date_format` can parse a date and the convert it to your format.

http://stackoverflow.com/q/52462326
answer count: 2
has title: VS code python debugger error with print statements
tagged with: python-3.x
has body: So when ever im trying to debug any Python script on VS code an that script has a print or input statement, it crashes an throws me an "AttributeError" that says 'NoneType' object has no attribute 'write', any ideas why this happens? i cant find any information on Google about it here is a screenshot in the error:Link to the screenshot and also here is my configuration file: { // Use IntelliSense para saber los atributos posibles. // Mantenga el puntero para ver las descripciones de los existentes atributos // Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File (Integrated Terminal)", "type": "python", "request": "launch", "stopOnEntry": true, "program": "${file}", "console": "integratedTerminal" }, { "name": "Python: Attach", "type": "python", "request": "attach", "port": 5678, "host": "localhost" }, { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true }, { "name": "Python: Flask", "type": "python", "request": "launch", "module": "flask", "env": { "FLASK_APP": "app.py" }, "args": [ "run", "--no-debugger", "--no-reload" ], "jinja": true }, { "name": "Python: Current File (External Terminal)", "type": "python", "request": "launch", "program": "${file}", "console": "externalTerminal" } ] }
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52785455
tagged with: vscode-debugger
has answer: http://stackoverflow.com/a/52462487
type: Question
tagged with: visual-studio-code
score: 0

http://stackoverflow.com/a/52498974
has comment: http://stackoverflow.com/comment/91938753
has comment: http://stackoverflow.com/comment/91938907
has comment: http://stackoverflow.com/comment/91939226
score: 0
has body: Try this, df = df.drop(['Class'],axis=1) df = df.drop(['Time'],axis=1) # optional
has comment: http://stackoverflow.com/comment/91938620
has comment: http://stackoverflow.com/comment/91939122
type: Answer
has comment: http://stackoverflow.com/comment/91939197
answers question: http://stackoverflow.com/q/52498934
has comment: http://stackoverflow.com/comment/91938594

http://stackoverflow.com/comment/92049504
comment on: http://stackoverflow.com/q/52555458
type: Comment
type: QuestionComment
score: 2
has text: Why are you running a `__init__.py` file inside an installed package as a script?

http://stackoverflow.com/a/52552759
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92057595
type: Answer
has body: I can propose an answer, where you determine probability density function (PDF) and cumulative distribution function (CDF) using NumPy. import numpy as np # ----------------- data = [88,93,184,91,107,170,88,107,167,90]; # ----------------- # get PDF: ydata,xdata = np.histogram(data,bins=np.size(data),normed=True); # ---------------- # get CDF: cdf = np.cumsum(ydata*np.diff(xdata)); # ----------------- print 'Sum:',np.sum(ydata*np.diff(xdata)) I am using Numpy method histogram, which will give me the PDF and then I will calculate CDF from PDF.
accepted answer of: http://stackoverflow.com/q/52524625
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92055086
answers question: http://stackoverflow.com/q/52524625
has comment: http://stackoverflow.com/comment/92169899
upvote count: 1
has comment: http://stackoverflow.com/comment/92179776

http://stackoverflow.com/comment/92066704
score: 0
type: QuestionComment
type: Comment
has text: Is the data all from the same plant species?
comment on: http://stackoverflow.com/q/52563371

http://stackoverflow.com/comment/91979564
type: Comment
type: QuestionComment
has text: To load text `fromfile` requires a delimiter - read the whole docs.
comment on: http://stackoverflow.com/q/52515599
score: 1

http://stackoverflow.com/q/52473602
has body: This code generates individual boxplots for samples subdivided into three groups of data. So, dataset 1 has samples A, B and C and so on. When I plot the x-axis I only want the sample names ('Sample A, 'Sample B' etc) and NOT the major labels (i.e. 'dataset1', 'dataset2' etc) - I don't know how to suppress the major labels. import matplotlib.pyplot as plt import numpy as np import random #build dataset as dictionary data = {} data['dataset1'] = {} data['dataset2'] = {} data['dataset3'] = {} #simulate data n = 100 for k,v in data.iteritems(): upper = random.randint(0, 1000) v['sample A'] = np.random.uniform(0, upper, size=n) v['sample B'] = np.random.uniform(0, upper, size=n) v['sample C'] = np.random.uniform(0, upper, size=n) fig, axes = plt.subplots(ncols=3, sharey=True) fig.subplots_adjust(wspace=0) #build subplots for ax, name in zip(axes, ['dataset1', 'dataset2', 'dataset3']): ax.boxplot([data[name][item] for item in ['sample A', 'sample B', 'sample C']]) ax.set(xticklabels=['sample A', 'sample B', 'sample C'], xlabel=name) ax.margins(0.05) # Optional #plot labels for ax in fig.axes: plt.sca(ax) plt.xticks(ha = 'right', rotation=45) plt.show() In case your wondering this is causing a major presentation problem for my actual dataset.
has answer: http://stackoverflow.com/a/52478903
tagged with: python
has answer: http://stackoverflow.com/a/52473743
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52473743
type: Question
accepted answer: http://stackoverflow.com/a/52478903
tagged with: matplotlib
has title: How can I suppress the major label xticks in matplotlib axes?
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52473827

http://stackoverflow.com/q/52485242
has title: How to use embedding layer and other feature columns together in a network using tensorflow keras
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52494446
tagged with: tensorflow
type: Question
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/91926972
has body: Let’s consider a example data set contains 6 columns and 10 rows. In these 3 columns are numeric and remaining 3 columns are categorical variable. categorical columns are converted into multi hot encoded array of size 10x3. I have target columns which i want predict is also categorical variable which can take 3 possible values again. This column is one hot encoded. Now I want to use this multi-hot-encoded array as input to embedding layer. Embedding layer should output 2 units. Then I want to use 3 numeric columns from the dataset and 2 output units from the embedding layer total 5 unit as input to the hidden layer. This is the place I got stuck up. I don’t know how to bridge embedding layer and my other feature columns using tensorflow keras, also I don’t know how to pass input for embedding layer and other 2 units. I have googled it. I tried the following code but still I get error. I guess there is no Merge layer in tf.keras package. Any help on this would be greatly appreciated. import tensorflow as tf from tensorflow import keras import numpy as np num_data = np.random.random(size=(10,3)) multi_hot_encode_data = np.random.randint(0,2, 30).reshape(10,3) target = np.eye(3)[np.random.randint(0,3, 10)] model = keras.Sequential() model.add(keras.layers.Embedding(input_dim=multi_hot_encode_data.shape[1], output_dim=2)) model.add(keras.layers.Dense(3, activation=tf.nn.relu, input_shape=(num_data.shape[1],))) model.add(keras.layers.Dense(3, activation=tf.nn.softmax) model.compile(optimizer=tf.train.RMSPropOptimizer(0.01), loss=keras.losses.categorical_crossentropy, metrics=[keras.metrics.categorical_accuracy]) #model.fit([multi_hot_encode_data, num_data], target) # I get error here My network structure will be multi-hot-encode-input num_data_input | | | | | | embedding_layer | | | | | \ / \ / dense_hidden_layer | | output_layer
answer count: 1
accepted answer: http://stackoverflow.com/a/52494446
has comment: http://stackoverflow.com/comment/91912757
downvote count: 0
has comment: http://stackoverflow.com/comment/91920120
tagged with: keras
favorite count: 0

arrays
tags question: http://stackoverflow.com/q/52560845
tags question: http://stackoverflow.com/q/52532580
tags question: http://stackoverflow.com/q/52527175
tags question: http://stackoverflow.com/q/52508982
tags question: http://stackoverflow.com/q/52581426
tags question: http://stackoverflow.com/q/52434942
tags question: http://stackoverflow.com/q/52526546
tags question: http://stackoverflow.com/q/52500199
tags question: http://stackoverflow.com/q/52551952
tags question: http://stackoverflow.com/q/52554857
type: Tag
tags question: http://stackoverflow.com/q/52494061
tags question: http://stackoverflow.com/q/52500885
tags question: http://stackoverflow.com/q/52446424
tags question: http://stackoverflow.com/q/52586790
tags question: http://stackoverflow.com/q/52518584
tags question: http://stackoverflow.com/q/52537299
tags question: http://stackoverflow.com/q/52494910
tags question: http://stackoverflow.com/q/52494407
tags question: http://stackoverflow.com/q/52579601
tags question: http://stackoverflow.com/q/52447778
tags question: http://stackoverflow.com/q/52511123
tags question: http://stackoverflow.com/q/52442229
tags question: http://stackoverflow.com/q/52539338
tags question: http://stackoverflow.com/q/52550460
tags question: http://stackoverflow.com/q/52545527
tags question: http://stackoverflow.com/q/52453779
tags question: http://stackoverflow.com/q/52588378
tags question: http://stackoverflow.com/q/52465377
tags question: http://stackoverflow.com/q/52579341
tags question: http://stackoverflow.com/q/52534972
tags question: http://stackoverflow.com/q/52557357
tags question: http://stackoverflow.com/q/52536810
tags question: http://stackoverflow.com/q/52485840
tags question: http://stackoverflow.com/q/52551259
tags question: http://stackoverflow.com/q/52460068
tags question: http://stackoverflow.com/q/52462004
tags question: http://stackoverflow.com/q/52573393
tags question: http://stackoverflow.com/q/52556903
tags question: http://stackoverflow.com/q/52475717
tags question: http://stackoverflow.com/q/52530444
tags question: http://stackoverflow.com/q/52571619
tags question: http://stackoverflow.com/q/52432675
tags question: http://stackoverflow.com/q/52582159
tags question: http://stackoverflow.com/q/52551247
tags question: http://stackoverflow.com/q/52579378
tag name: arrays
tags question: http://stackoverflow.com/q/52519451
tags question: http://stackoverflow.com/q/52554388
tags question: http://stackoverflow.com/q/52574040
tags question: http://stackoverflow.com/q/52432166
tags question: http://stackoverflow.com/q/52488269
tags question: http://stackoverflow.com/q/52509500
tags question: http://stackoverflow.com/q/52443658
tags question: http://stackoverflow.com/q/52523034
tags question: http://stackoverflow.com/q/52546411
tags question: http://stackoverflow.com/q/52491286
tags question: http://stackoverflow.com/q/52586395
tags question: http://stackoverflow.com/q/52434485
tags question: http://stackoverflow.com/q/52539461
tags question: http://stackoverflow.com/q/52565436
tags question: http://stackoverflow.com/q/52466901
tags question: http://stackoverflow.com/q/52515244
tags question: http://stackoverflow.com/q/52539134
tags question: http://stackoverflow.com/q/52503054
tags question: http://stackoverflow.com/q/52465718
tags question: http://stackoverflow.com/q/52443469
tags question: http://stackoverflow.com/q/52477962
tags question: http://stackoverflow.com/q/52581665
tags question: http://stackoverflow.com/q/52487716
tags question: http://stackoverflow.com/q/52467098
tags question: http://stackoverflow.com/q/52467994
tags question: http://stackoverflow.com/q/52535980
tags question: http://stackoverflow.com/q/52458921
tags question: http://stackoverflow.com/q/52588034
tags question: http://stackoverflow.com/q/52444657
tags question: http://stackoverflow.com/q/52503035
tags question: http://stackoverflow.com/q/52505018
tags question: http://stackoverflow.com/q/52571930
tags question: http://stackoverflow.com/q/52538032

http://stackoverflow.com/comment/92115915
comment on: http://stackoverflow.com/a/52588536
score: 0
type: AnswerComment
has text: @NiladryKar: well there are still elements in templates, views, etc. that don't. The traceback, etc. might contain the exact location.
type: Comment

http://stackoverflow.com/comment/91809035
score: 0
comment on: http://stackoverflow.com/q/52432133
has text: @Aran-Fey my bad, doing it now.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52448847
tagged with: processing-efficiency
tagged with: python
has comment: http://stackoverflow.com/comment/91841283
has comment: http://stackoverflow.com/comment/91840669
tagged with: bigdata
has comment: http://stackoverflow.com/comment/91840838
has comment: http://stackoverflow.com/comment/91840811
has comment: http://stackoverflow.com/comment/91840739
has answer: http://stackoverflow.com/a/52449281
downvote count: 1
type: Question
tagged with: performance
tagged with: if-statement
score: -1
has body: So I am dealing with a large data file which has 1.3 million rows. What I'm trying to do is simple, I want to change values in some columns given some conditions. for i in range(0,len(data2)): #where len(data2) is about 1.3 million if data2.loc[i,'PPA']==0: data1.loc[i,'LDU']=0 #(data1 and data2 have same amount of rows) and I will also need to format for some other columns. for example, I want to format gender as either 0 or 1. data as follows: data['Gender'] Out[156]: 0 F 1 M 2 F 3 F .. 1290573 M 1290574 F Name: Gender, Length: 1290575, dtype: object #Format to 0 and 1 for i in range(0,len(data)): if data.loc[i,'Gender']=='F': data.loc[i,'Gender']=0; else: data.loc[i,'Gender']=1 Btw regarding the processing time, I noticed something unusual... I saved the first 5000 rows to a new csv file, when I test my code on the sample data, it performed well and fast, like in 10 seconds. But when I try to run it on my real data, and let it do for i in range(0,10000) #instead of the full length of data it takes about 9 minutes. last time I formatted another column like this(assigning 0 and 1) on my full data takes more than 10 hours in python. So I'm just wondering if there anything wrong on my codes? is any other more efficient way to let it read and rewrite faster? ... Any help would be appreciated! :) I'm kinda new to python and it's my first question post, thank you everyone for your comment :)
has comment: http://stackoverflow.com/comment/91842962
has title: Is there more efficient way than this if statement for large data in python
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91841848
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91840679

http://stackoverflow.com/q/52548821
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52549071
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How to get the population and geographic location of a city using Python?
tagged with: web-scraping
downvote count: 1
type: Question
score: -1
has body: The only way I could think of is to search it in google and scrape the result using the BeautifulSoup module. So I did it: Image 1 (Sorry, my reputation isn't enough to post image directly) Then I checked the source of the search result: Image 2 So I wrote the code: from bs4 import BeautifulSoup import requests url = 'https://www.google.com.hk/search?q=new+york+city+population&amp;oq=New+York+&amp;aqs=chrome.1.69i57j0l5.4853j0j7&amp;sourceid=chrome&amp;ie=UTF-8' html = requests.get(url).text soup = BeautifulSoup(html, 'lxml') print(soup.find('div', class_ = "kpd-ans kno-fb-ctx KBXm4e")) The result is returned as None. What can I do about that?

http://stackoverflow.com/q/52466532
tagged with: numpy
tagged with: dataframe
has answer: http://stackoverflow.com/a/52468942
has answer: http://stackoverflow.com/a/52469024
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/52467126
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have following dataframe in pandas prod S X a 10 123 b 20 150 b 30 140 a 40 100 Formula for product a and b is as follows a = IF(S&gt;X, (0.6/100(S-X)),0) b = IF(S&gt;X, (0.2/100(S-X)),0) How can I calculate new column based on formula for product a and b in existing dataframe
has title: combination of np.where and if in pandas
has answer: http://stackoverflow.com/a/52467213
answer count: 4
score: 2
upvote count: 2
type: Question

http://stackoverflow.com/a/52578144
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
has body: In your terminal enter: python -m pip install tweepy.
score: 2
answers question: http://stackoverflow.com/q/52578131
accepted answer of: http://stackoverflow.com/q/52578131

http://stackoverflow.com/q/52574316
has title: What is the meaning of tuple under function definition
type: UnansweredQuestion
has body: recently, I read codes from https://github.com/danfeiX/scene-graph-TF-release/ In lib/fast-rcnn/models.py, there are lots of tuple-under-function style code. for example, _vgg_fc() def _vgg_fc(self): (self.feed('conv_out', 'rois') .roi_pool(7, 7, 1.0/16, name='pool5') .fc(4096, name='fc6') .dropout(self.keep_prob, name='drop6') .fc(4096, name='fc7') .dropout(self.keep_prob, name='vgg_out')) I wonder what is the different from the code below? def _vgg_fc(self): self.feed('conv_out', 'rois') .roi_pool(7, 7, 1.0/16, name='pool5') .fc(4096, name='fc6') .dropout(self.keep_prob, name='drop6') .fc(4096, name='fc7') .dropout(self.keep_prob, name='vgg_out')
tagged with: python
has comment: http://stackoverflow.com/comment/92084664
answer count: 0
linked to: http://stackoverflow.com/q/53162
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92085244
tagged with: vgg-net
score: 0
tagged with: deep-learning
duplicate of: http://stackoverflow.com/q/53162

http://stackoverflow.com/comment/91899568
comment on: http://stackoverflow.com/q/52479310
has text: How working `df.columns = ["id","information"]` ?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52509083
tagged with: if-statement
has answer: http://stackoverflow.com/a/52509111
duplicate of: http://stackoverflow.com/q/15112125
has title: Why do I keep getting "Shutting down..." as an output no matter what?
score: -1
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91958316
favorite count: 0
accepted answer: http://stackoverflow.com/a/52509111
tagged with: while-loop
tagged with: python
has comment: http://stackoverflow.com/comment/91958416
type: AnsweredQuestion
downvote count: 1
linked to: http://stackoverflow.com/q/15112125
type: Question
has body: I'm trying to create a text based mini game. For the code of my loading screen, no matter what I input, I get "Shutting Down..." What am I doing wrong? import random import sys def characterCreation(): gender = raw_input("Please enter your gender: ") name = raw_input("Please enter your name: ") age = raw_input("Please enter your age: ") def loadingScreen(): option = raw_input("Welcome to Riften! Type either 'Play Game' or 'Quit' to procede!: ") option = str(option) if option == "Quit" or "quit" : sys.exit('Shutting down...') elif option == "Play Game" or "Play game" or "play Game" or "play game": characterCreation() else: while option != "Quit" or "quit" or "Play Game" or "Play game" or "play Game" or "play game": print("Please choose a valid option.: ") option = raw_input("Type either 'Play Game' or 'Quit' to procede!: ") loadingScreen() I wanna have it where if the user inputs "quit" in any capitalization, the program exits. If the user inputs "play game" the game continues to the character creation screen, and if the user inputs any thing else, to ask for the input of either "play game" or "quit" until given Thank you

http://stackoverflow.com/comment/91858554
type: QuestionComment
comment on: http://stackoverflow.com/q/52458085
has text: Use the `~` operator before the mask
score: 0
type: Comment

http://stackoverflow.com/comment/91953202
type: AnswerComment
has text: run_spider("quotes5") works! thank you sir! I have a new error.."ModuleNotFoundError: No module named 'WS_Vardata.spiders'". The location of my scrapy program is this "C:\Users\raresb\Desktop\TEST\WS_Vardata\spiders\quotes_spider". "quotes_spider" is the scrapy program.
type: Comment
comment on: http://stackoverflow.com/a/52506344
score: 0

http://stackoverflow.com/a/52560047
has comment: http://stackoverflow.com/comment/92077695
downvote count: 0
has comment: http://stackoverflow.com/comment/92058689
has comment: http://stackoverflow.com/comment/92059084
upvote count: 3
has body: If all your values are positive or 0 Could use transform with sum and check if 0: m = (df.groupby('itemname').transform('sum') == 0)['value'] df.loc[m, 'value'] = 100
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/92058763
has comment: http://stackoverflow.com/comment/92059126
answers question: http://stackoverflow.com/q/52559963
has comment: http://stackoverflow.com/comment/92058779

http://stackoverflow.com/comment/91991851
score: 0
type: Comment
type: QuestionComment
has text: RafaelC i updated the data to remove the commas, but now I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 83: invalid start byte
comment on: http://stackoverflow.com/q/52525841

http://stackoverflow.com/comment/91954491
has text: Thanks for the advice! I tried using the distinct values from each feature and use those in an $in, in order to extract a subset to a dataframe I could then use pandas intersect to find the matching rows - what I didn't consider was that the distinct set of values from one feature was effectively enough to query for every document in the remote collection. So in the end i just used an $and for each of the 3 features and just hammered the mongodb server with a single query per row. It did work, I just didn't like doing it, as it just didn't feel like a good way to do it. But thanks again!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52462006
type: AnswerComment

http://stackoverflow.com/comment/92073199
type: QuestionComment
has text: I know, I can add that later. But I've had fun watching people try to play it over and over, back when I had the text print in the command line. This is more of an exercise to learn tkinter.
comment on: http://stackoverflow.com/q/52568016
score: 0
type: Comment

http://stackoverflow.com/comment/91821460
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52438791
type: Comment
has text: Thank you. I have actually much problems with scipy.minimize when functions gets long and complicated. Can you recommend alternatives?

http://stackoverflow.com/q/52547535
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Get list of data in different sections on scrapy
score: 1
tagged with: web-scraping
upvote count: 1
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/52550087
has body: I need data scrape in different sections of a site. In first section, I get data from a customer and the id of your orders. With this id, I access a second section and get the items details from the orders. So, I need to concatenate the result of a dict "customer" with a list of "orders" with a list of "itens". Basically, my algorithm is: def parse1(self, response): customer['data'] = response.xpath("path to customer data").extract() customer_orders = response.xpath("path to customer orders") for index, customer_order in enumarate(customer_orders): id = customer_order.xpath('path to order id').extract_first() customer['orders'].append({'id' : id}) yield scrapy.FormRequest(url="www.url.com/orders"+id, callback=self.parse2, method='GET', meta= {'customer': customer}) def parse2(self, response): customer = response.meta['customer'] customer['orders']['items'] = [] for index, order_item in response.xpath("path to order items"): customer['orders']['items'].append({"items_details": order_item.xpath("path to items details").extract_first()}) yield customer But I can't code this logic with Scrapy asynchronous architecture. The closer of this what I got it was print many times the same costumer dict in result. Anybody can help a to do this?
downvote count: 0
answer count: 1
tagged with: asynchronous

http://stackoverflow.com/a/56851110
answers question: http://stackoverflow.com/q/52553593
has body: &lt;!-- Success, please check --&gt; import tensorflow as tf import matplotlib.pyplot as plt mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() plt.imshow(x_train[0], cmap=plt.cm.binary) x_train = tf.keras.utils.normalize(x_train, axis=1) x_test = tf.keras.utils.normalize(x_test, axis=1) plt.imshow(x_train[0], cmap=plt.cm.binary) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten(input_shape=x_train[0].shape)) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax)) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=3) val_loss, val_acc = model.evaluate(x_test, y_test) print(val_loss) print(val_acc) model.save('epic_num_reader.model')
score: 0
type: Answer

http://stackoverflow.com/a/52484194
answers question: http://stackoverflow.com/q/52484136
has comment: http://stackoverflow.com/comment/91910177
score: 1
upvote count: 1
downvote count: 0
has body: The problem here is that you're using for i in arr to iterate over a string. When iterating over a string like this, i is the characters in the string, not a numeric value. That's why you can't access arr[i].
type: Answer

http://stackoverflow.com/q/52449810
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52449902
favorite count: 0
has title: Jupyter notebook and matplotlib (runtime warning): continue to display plots after closing
tagged with: python
tagged with: jupyter-notebook
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/52449902
has body: I would like to use matplotlib.pyplot to display many images in my jupyter notebook. However, when I try to display more than 20, a runtime warning appears, since images are kept in memory if not closed: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_open_warning). I am using %matplotlib inline If I close the plot plt.close(), the plots are not displayed. How can I can close the plot and still look at the plot in jupyter, I need to look at many images simultanously: I am using a loop where crop and value are two images. plt.figure() f, axarr = plt.subplots(1,2) plt.title('Image: ' + str(key)) plt.gray() axarr[0].imshow(crop) axarr[1].imshow(value) plt.close()
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91842820

http://stackoverflow.com/comment/91853123
score: 0
type: AnswerComment
type: Comment
has text: @Aran-Fey: I had no idea that existed. As a nice bonus, `.copy()` behaves identically for `ndarray`s and `list`s, unlike `[:]` which has different semantics.
comment on: http://stackoverflow.com/a/52455329

http://stackoverflow.com/comment/93266481
comment on: http://stackoverflow.com/q/52433549
score: 0
has text: @LjubisaLivac I've answered at the linked dup.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52559308
has body: import random def pair(): base = random.choice('AGCT') if base == 'A': base = base + 'G' elif base == 'G': base = 'A' + base elif base == 'C': base = base + 'T' else: base = 'C' + base return base def sequence(): pair() n = random.randint(1, 3) print(base * n) def main(): pair() sequence() pair() sequence() pair() sequence() main() I have to create three sequences in the main function, concatenate them to form a larger sequence, and print the result. But I keep getting an error, why? Traceback (most recent call last): File "/Users/nicole/Desktop/CS/dna.py", line 33, in &lt;module&gt; main() File "/Users/nicole/Desktop/CS/dna.py", line 27, in main sequence() File "/Users/nicole/Desktop/CS/dna.py", line 23, in sequence print(base * n) NameError: name 'base' is not defined
answer count: 1
has comment: http://stackoverflow.com/comment/92057216
favorite count: 0
has title: DNA Sequence Python not printing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92057283
has answer: http://stackoverflow.com/a/52562197
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/92057612
has comment: http://stackoverflow.com/comment/92057899
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/92062322
upvote count: 0
has comment: http://stackoverflow.com/comment/92059481
tagged with: dna-sequence

http://stackoverflow.com/comment/91839389
has text: `[84, 79, 72]` and `[1058, 1054, 1053]`
comment on: http://stackoverflow.com/q/52447536
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52477852
answers question: http://stackoverflow.com/q/52476935
upvote count: 1
has body: I guess you are using beatifulsoup4 library for parsing HTML. If yes, you can get phone number from html like this: text = soup.find_all('li')[3].contents[1] phone_number = re.sub(": ", "", text) print(phone_number)
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52476935
type: Answer

http://stackoverflow.com/comment/92096839
type: Comment
has text: @gboffi no worries :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52573006

http://stackoverflow.com/q/52514397
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52524310
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52524310
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91980916
type: Question
has title: Set up a proxy with python requests
has body: I'm trying to write a webserver (proxy?) so that I can make requests to, say, http://localhost:8080/foo/bar which would transparently return the response from https://www.gyford.com/foo/bar. The python script below works for a web page itself, but some kinds of files aren't returned (e.g. https://www.gyford.com/static/hines/js/site-340675b4c7.min.js ). If I manually request that file, while this server's running, like: import requests r = requests.get('http://localhost:8080/static/hines/js/site-340675b4c7.min.js') then I get: 'Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect header check',) So I guess I need to handle gzipped files differently but I can't work out how. from http.server import HTTPServer, BaseHTTPRequestHandler import requests HOST_NAME = 'localhost' PORT_NUMBER = 8080 TARGET_DOMAIN = 'www.gyford.com' class MyHandler(BaseHTTPRequestHandler): def do_GET(self): host_domain = '{}:{}'.format(HOST_NAME, PORT_NUMBER) host = self.headers.get('Host').replace(host_domain, TARGET_DOMAIN) url = ''.join(['https://', host, self.path]) r = requests.get(url) self.send_response(r.status_code) for k,v in r.headers.items(): self.send_header(k, v) self.end_headers() self.wfile.write( bytes(r.text, 'UTF-8') ) if __name__ == '__main__': server_class = HTTPServer httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler) try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() EDIT: Here's the output of print(r.headers): {'Connection': 'keep-alive', 'Server': 'gunicorn/19.7.1', 'Date': 'Wed, 26 Sep 2018 13:43:43 GMT', 'Content-Type': 'application/javascript; charset="utf-8"', 'Cache-Control': 'max-age=60, public', 'Access-Control-Allow-Origin': '*', 'Vary': 'Accept-Encoding', 'Last-Modified': 'Thu, 20 Sep 2018 16:11:29 GMT', 'Etag': '"5ba3c6b1-6be"', 'Content-Length': '771', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur'}
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91984071
favorite count: 0

http://stackoverflow.com/comment/91947692
comment on: http://stackoverflow.com/q/52503112
type: Comment
has text: Scrapy crawls static pages, dynamic web pages that have a lot of ajax queries running at the load time do not work very well.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91883531
score: 1
has text: Yes there is a way to do this but as a new comer to SO you should check the policy for asking questions as it will help you get answers. It would be a lot easier if you ask with some code that you've already tried as this will allow mw to give you a specific answer. Could you include some code?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52470735

http://stackoverflow.com/comment/91859016
has text: Any other ideas? I've tried this with mingw, mingw64, and cygwin. All are having the same problem.
comment on: http://stackoverflow.com/q/52430325
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52569710
has comment: http://stackoverflow.com/comment/92078021
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/92076864
downvote count: 0
answers question: http://stackoverflow.com/q/52567912
score: 1
has body: #convert string value to timedelta (better to work with time) df['stamp']=pd.to_timedelta(df['stamp']) #slicing only odd row's from `stamp` column and adding 30 minutes to all the odd row's odd_df=pd.to_timedelta(df.loc[1::2,'stamp'])+pd.to_timedelta('30 min') #updating new series (out_df) with the existing df, based on index. df['stamp'].update(odd_df) #print(df) stamp value 0 00:00:00 2 1 00:30:00 3 2 01:00:00 5
has comment: http://stackoverflow.com/comment/92077901

http://stackoverflow.com/q/52523614
has comment: http://stackoverflow.com/comment/91986791
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/52523742
accepted answer: http://stackoverflow.com/a/52523742
downvote count: 2
has title: Efficient way to parse different lines of a text file
tagged with: loops
type: Question
score: -2
has comment: http://stackoverflow.com/comment/91986786
has body: I have a text file containing the data like this: 1 --- 1 --- 100 2 --- 1 --- 200 3 --- 1 --- 100 1 --- 2 --- 300 2 --- 2 --- 100 3 --- 2 --- 400 I want to extract the data of third column corresponding to different values of second column, for example add three numbers in third column corresponding to number 1 in second column and so on. I can loop though the text line by line, and find the third column in each line and add them. But that is not what I want. How should I do it efficiently in Python?
answer count: 1
has comment: http://stackoverflow.com/comment/91986798
has comment: http://stackoverflow.com/comment/91986731

http://stackoverflow.com/a/52561611
score: 1
has comment: http://stackoverflow.com/comment/92061765
has body: You can use CatCodes straight from pandas. First make a column a category Call cat.codes Assign it to your new Column df['Category2'] = df['CategoryNumber'].astype('category').cat.codes CategoryNumber Category2 0 1 0 1 2 1 2 3 2 3 1 0 4 3 2 If you need to make it A,B,C, etc. look at map df['Letters'] = df['Category2'].map(dict(zip(df['Category2'].tolist(),string.ascii_uppercase))) CategoryNumber Category2 Letters 0 1 0 D 1 2 1 B 2 3 2 E 3 1 0 D 4 3 2 E
downvote count: 0
has comment: http://stackoverflow.com/comment/92062185
type: Answer
answers question: http://stackoverflow.com/q/52561537
upvote count: 1

http://stackoverflow.com/q/52484459
has comment: http://stackoverflow.com/comment/91910613
favorite count: 0
tagged with: tuples
has title: String splits to characters while adding it to tuple
has answer: http://stackoverflow.com/a/52484496
tagged with: python
has answer: http://stackoverflow.com/a/52484680
has comment: http://stackoverflow.com/comment/91910561
upvote count: 3
possible better answer: http://stackoverflow.com/a/52484526
has answer: http://stackoverflow.com/a/52484526
accepted answer: http://stackoverflow.com/a/52484496
type: AnsweredQuestion
score: 3
tagged with: list
has body: I am trying to append a tuple with string to a list, after appending tuple to the list, the tuple splits strings to its characters. My Code: def create_list(): raw_data = ['hello world', 'hello world 1'] new_data = [] for data in raw_data: new_data.append(tuple(data)) print(new_data) Output [("'", 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', "'"), ("'", 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', '1', "'")] Expected Output [('hello world'), ('hello world 1')]
has comment: http://stackoverflow.com/comment/91910483
type: Question
has comment: http://stackoverflow.com/comment/91910554
answer count: 3
has comment: http://stackoverflow.com/comment/91912730
tagged with: python-3.5
downvote count: 0

http://stackoverflow.com/q/52571708
has comment: http://stackoverflow.com/comment/92079999
has title: django url testing case
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92080153
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92080034
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92080108
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52571968
answer count: 2
has answer: http://stackoverflow.com/a/62257746
has body: I am new to Django, I am following one tutorial for learning, everything went fine after writing the testing cases it's showing some error, I am following as per tutorial don't know why it's not working. Run python manage.py test Output: Creating test database for alias 'default'... System check identified no issues (0 silenced). E. ====================================================================== ERROR: test_home_url_resolves_home_view (boards.tests.HomeTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\sradha\Development\myproject\myproject\boards\tests.py", line 13, in test_home_url_resolves_home_view view = resolve('/') File "C:\Users\sradha\Development\myproject\venv\lib\site-packages\django\urls\base.py", line 24, in resolve return get_resolver(urlconf).resolve(path) File "C:\Users\sradha\Development\myproject\venv\lib\site-packages\django\urls\resolvers.py", line 520, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[&lt;URLResolver &lt;URLPattern list&gt; (admin:admin) 'admin/'&gt;], [&lt;URLPattern 'homepage/' [name='home']&gt;]], 'path': ''} ---------------------------------------------------------------------- Ran 2 tests in 0.036s FAILED (errors=1) Destroying test database for alias 'default'... tests.py file from django.urls import reverse from django.urls import resolve from django.test import TestCase from .views import home class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('home') response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) urls.py from django.contrib import admin from django.urls import path from boards import views urlpatterns = [ path('admin/', admin.site.urls), path('homepage/', views.home, name='home'), ] python version 3.6.2 django version 2.1.…
has comment: http://stackoverflow.com/comment/92080012
has comment: http://stackoverflow.com/comment/92080384
favorite count: 0
has comment: http://stackoverflow.com/comment/92080360

http://stackoverflow.com/comment/91891568
type: Comment
comment on: http://stackoverflow.com/q/52474747
has text: seems like the keras config file has been altered. you may want to check where the config file is. normally its ~/.keras in linux based systems(~=home folder). sorry not sure about Windows
score: 0
type: QuestionComment

http://stackoverflow.com/q/52559374
has comment: http://stackoverflow.com/comment/92057432
has body: Is there static analysis tool which checks Python 3 code for functional programming best practices, pure functions, etc.? EDIT: Moved to softwarerecs.stackexchange.com
has comment: http://stackoverflow.com/comment/92059809
has title: Static analysis for Python functional programming best practices?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52560162
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/92058926
upvote count: 2
has comment: http://stackoverflow.com/comment/92057407
type: Question

http://stackoverflow.com/a/52754513
has comment: http://stackoverflow.com/comment/92528662
type: Answer
has body: The problem was that SECRET_KEY was not static on Heroku. The SECRET_KEY changing was breaking sessions. The fix is to add a static SECRET_KEY to Heroku config: heroku config:set SECRET_KEY=`openssl rand -base64 32`
answers question: http://stackoverflow.com/q/52535488
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52535488
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92046553
has text: A general advice: https://softwareengineering.stackexchange.com/questions/254475/how-do-i-move-away-from-the-for-loop-school-of-thought
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52553842

http://stackoverflow.com/q/52552185
tagged with: dictionary
has title: Get dictionary values as List
has comment: http://stackoverflow.com/comment/92043461
tagged with: list
has body: I know this is asked earlier, but I tried but could not help. I have below dictionary, want to convert to List, What is the best way to convert to List dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']} dList = list(dct.values()) Result: 'activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)' I need splitted List: ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)'] Later, I want to compare list of items in "dList" with another List.
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52552247
possible better answer: http://stackoverflow.com/a/52552451
tagged with: dataframe
has answer: http://stackoverflow.com/a/52552451
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/92043434
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92043271
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52552247
type: Question
tagged with: python

http://stackoverflow.com/q/52472452
has comment: http://stackoverflow.com/comment/91886721
upvote count: 2
has title: How to fix negative number on python on user guessing a number
type: UnansweredQuestion
score: 1
downvote count: 1
type: Question
has body: Is there a way to fix the obtaining negative numbers in the code below? import random number = random.randrange(1, 100) guess = int(input("I’m thinking of a number between 1 and 100 " + "Can you guess it? ")) number1 = number - guess number2 = (number) - guess if guess&gt;number: print ("You were " + str(number1)+ " away! ") else: if guess&lt;number: print ("You were " + str(number2)+ " away! ") else: if guess == number: print ("You got it right ")
answer count: 2
has answer: http://stackoverflow.com/a/52472509
has answer: http://stackoverflow.com/a/52472521
favorite count: 0
tagged with: python

http://stackoverflow.com/a/52504053
has body: I think you want this: #!/usr/local/bin/python3 from PIL import Image,ImageDraw, ImageColor, ImageChops # Load images im1 = Image.open('im1.jpg') im2 = Image.open('im2.jpg') # Flood fill white edges of image 2 with black seed = (0, 0) black = ImageColor.getrgb("black") ImageDraw.floodfill(im2, seed, black, thresh=127) # Now select lighter pixel of image1 and image2 at each pixel location and save it result = ImageChops.lighter(im1, im2) result.save('result.png') If you prefer OpenCV, it might look like this: #!/usr/local/bin/python3 import cv2 # Load images im1 = cv2.imread('im1.jpg', cv2.IMREAD_GRAYSCALE) im2 = cv2.imread('im2.jpg', cv2.IMREAD_GRAYSCALE) # Threshold, because JPEG is dodgy! ret, im1 = cv2.threshold(im1, 127, 255, cv2.THRESH_BINARY) ret, im2 = cv2.threshold(im2, 127, 255, cv2.THRESH_BINARY) # Flood fill white edges of image 2 with black h, w = im2.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) cv2.floodFill(im2, mask, (0,0), 0) # Now select lighter of image1 and image2 and save it result = np.maximum(im1, im2) cv2.imwrite('result.png', result)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52501817
has comment: http://stackoverflow.com/comment/91949380
answers question: http://stackoverflow.com/q/52501817
has comment: http://stackoverflow.com/comment/91949782
has comment: http://stackoverflow.com/comment/91949793
type: Answer
has comment: http://stackoverflow.com/comment/91948795
has comment: http://stackoverflow.com/comment/91949826
has comment: http://stackoverflow.com/comment/91949748
score: 4
has comment: http://stackoverflow.com/comment/91949822
has comment: http://stackoverflow.com/comment/91957203
has comment: http://stackoverflow.com/comment/91957445
has comment: http://stackoverflow.com/comment/91948692
upvote count: 4
has comment: http://stackoverflow.com/comment/91957040

design-patterns
tags question: http://stackoverflow.com/q/52588608
tags question: http://stackoverflow.com/q/52483656
tag name: design-patterns
type: Tag
tags question: http://stackoverflow.com/q/52574433

http://stackoverflow.com/a/52484775
answers question: http://stackoverflow.com/q/52484567
has comment: http://stackoverflow.com/comment/91911161
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/91911060
type: AcceptedAnswer
downvote count: 0
has body: Where should I use my logging_setup() utility, if anywhere? In library code, you should not configure logging anywhere. It is up to the users of your library (application distributors) to configure logging handlers. As a library author, you don't know anything about the runtime context, you don't even know if there is a writable filesystem available at all in order to create logfiles. But to use logging, you don't need to care about the configuration - just import logging and create loggers, at the module level, and you can log events from library code. It is not for the library code to decide where those log events go - or if they go anywhere at all. If you're providing an app and you want logging output, then configure logging as the first thing your application does when starting up - usually in Python this means a call to logging.config.dictConfig or similar is made shortly after entering the main() function (please make sure the logging configuration does not happen at import time).
type: Answer
accepted answer of: http://stackoverflow.com/q/52484567

http://stackoverflow.com/comment/92030858
score: 0
comment on: http://stackoverflow.com/a/52545447
type: AnswerComment
has text: A lambda could check the incoming file's name, and write it down to a well-known bucket. This may and likely will have a data race problem if several files are uploaded in parallel and complete nearly simultaneously.
type: Comment

http://stackoverflow.com/a/52547812
accepted answer of: http://stackoverflow.com/q/52547747
has body: Modified your code little bit and I think if you use dictionary than it will be easy to use and understand. import random # count2 = 0 # count3 = 0 # count4 = 0 # count5 = 0 # count6 = 0 # count7 = 0 # count8 = 0 # count9 = 0 # count10 = 0 # count11 = 0 # count12 = 0 count = {i: 0 for i in range(2,13)} rolls = int(input("How many times would you like to roll? ")) for i in range(rolls): die1 = random.randint(1, 6) print("Roll number 1 = " + str(die1)) die2 = random.randint(1, 6) print("Roll number 2 = " + str(die2)) total = die1 + die2 print(total) # if total == 2: # count2 += 1 # elif total == 3: # count3 += 1 # elif total == 4: # count4 += 1 # elif total == 5: # count5 += 1 # elif total == 6: # count6 += 1 # elif total == 7: # count7 += 1 # elif total == 8: # count8 += 1 # elif total == 9: # count9 += 1 # elif total == 10: # count10 += 1 # elif total == 11: # count11 += 1 # elif total == 12: # count12 += 1 count[total] += 1 # print("You rolled " + str(count2) + " 2's") # print("You Rolled " + str(count3) + " 3's") # print("You Rolled " + str(count4) + " 4's") # print("You Rolled " + str(count5) + " 5's") # print("You Rolled " + str(count6) + " 6's") # print("You Rolled " + str(count7) + " 7's") # print("You Rolled " + str(count8) + " 8's") # print("You Rolled " + str(count9) + " 9's") # print("You Rolled " + str(count10) + " 10's") # print("You Rolled " + str(count11) + " 11's") # print("You Rolled " + str(count12) + " 12's") for i in range(2,13): print("You rolled " + str(count[i]) + " "+i+"'s")
answers question: http://stackoverflow.com/q/52547747
score: 1
has comment: http://stackoverflow.com/comment/92035584
has comment: http://stackoverflow.com/comment/92035238
has comment: http://stackoverflow.com/comment/92035325
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92035458
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92035523

http://stackoverflow.com/comment/92107245
type: QuestionComment
comment on: http://stackoverflow.com/q/52586108
score: 1
type: Comment
has text: You are removing elements from `total_partitions` (which changes its length) while iterating it based on its initial length.

http://stackoverflow.com/comment/91950587
comment on: http://stackoverflow.com/a/52504692
score: 0
has text: Edited script to include all fields you are searching for
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52446473
type: Answer
upvote count: 1
has body: Here you can find examples on how to do this: https://github.com/bmihelac/docker-images-with-private-python-packages-example You basically have two alternatives: ssh keys or deploy/access tokens.
accepted answer of: http://stackoverflow.com/q/52446369
score: 1
answers question: http://stackoverflow.com/q/52446369
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91932941
score: 1
type: AnswerComment
has text: Btw, in `numpy`, I would have done it as `(np.arange(95) % 5 < 3) * 10`.
type: Comment
comment on: http://stackoverflow.com/a/52493584

http://stackoverflow.com/comment/91865224
type: Comment
has text: Instead of trying "save an object for each day", you would do better to set your code to handle "in" and "out" times and configure off that.
type: QuestionComment
comment on: http://stackoverflow.com/q/52460511
score: 0

http://stackoverflow.com/comment/92109714
has text: Yep, right you are. Removed the extra \r\n 's for the formatting . As well, it seems like the network I was at was causing some issues. The same code works now.
type: Comment
comment on: http://stackoverflow.com/a/52585082
score: 0
type: AnswerComment

http://stackoverflow.com/q/52446347
has answer: http://stackoverflow.com/a/52446461
has comment: http://stackoverflow.com/comment/91835552
tagged with: python
has answer: http://stackoverflow.com/a/52446616
score: 2
has comment: http://stackoverflow.com/comment/91835553
has comment: http://stackoverflow.com/comment/91835513
type: UnansweredQuestion
has title: Python for loop and function
has body: Am new to python and I have been trying to solve this problem but it does not seem to work as intended. your help is highly appreciated: Given two numbers X and Y, write a function that: returns even numbers between X and Y, if X is greater than Y else returns odd numbers between x and y . def number(x,y): if x &gt; y: for i in range(x,y): if i%2 == 0: list = [] return list.append[i] else: for i in range(x,y): if i%2 == 1: list = [] return list.append[i] print(number(10,2))
answer count: 6
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52447332
has answer: http://stackoverflow.com/a/52446510
downvote count: 0
has answer: http://stackoverflow.com/a/52452025
has answer: http://stackoverflow.com/a/52447021
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/91811102
comment on: http://stackoverflow.com/q/52433501
has text: Suggest: adding that error (editing) to your question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52522643
upvote count: 2
answers question: http://stackoverflow.com/q/52522584
has body: This strikes me as a dangerous design pattern, creating a function with intentional side effects on global scope. I would be careful doing things like this. That being said it doesn't look like you've called your function which may be why you aren't seeing what you expect.
type: Answer
has comment: http://stackoverflow.com/comment/91985363
score: 2
downvote count: 0

http://stackoverflow.com/q/52444921
has answer: http://stackoverflow.com/a/62553779
has answer: http://stackoverflow.com/a/56766359
has answer: http://stackoverflow.com/a/52445033
linked to: http://stackoverflow.com/q/2848099
type: Question
tagged with: numpy
has title: Save Numpy Array using Pickle
has answer: http://stackoverflow.com/a/68007406
has comment: http://stackoverflow.com/comment/111197500
has body: I've got a Numpy array that I would like to save (130,000 x 3) that I would like to save using Pickle, with the following code. However, I keep getting the error "EOFError: Ran out of input" or "UnsupportedOperation: read" at the pkl.load line. This is my first time using Pickle, any ideas? Thanks, Anant import pickle as pkl import numpy as np arrayInput = np.zeros((1000,2)) #Trial input save = True load = True filename = path + 'CNN_Input' fileObject = open(fileName, 'wb') if save: pkl.dump(arrayInput, fileObject) fileObject.close() if load: fileObject2 = open(fileName, 'wb') modelInput = pkl.load(fileObject2) fileObject2.close() if arrayInput == modelInput: Print(True)
has answer: http://stackoverflow.com/a/52447914
linked to: http://stackoverflow.com/q/28439701
upvote count: 51
downvote count: 0
has answer: http://stackoverflow.com/a/55750128
has comment: http://stackoverflow.com/comment/111199661
favorite count: 0
has answer: http://stackoverflow.com/a/69634731
answer count: 9
has comment: http://stackoverflow.com/comment/91833279
score: 51
linked to: http://stackoverflow.com/q/9619199
type: UnansweredQuestion
tagged with: pickle
tagged with: python
has answer: http://stackoverflow.com/a/71198095
has answer: http://stackoverflow.com/a/62883390

http://stackoverflow.com/comment/91891340
score: 0
type: Comment
type: QuestionComment
has text: There should be a `1` behind `calculator` I assume? Order in dictionaries is tricky, it only works for insertion (as of python 3.7) but you cannot order alphabetically (you might need an `OrderedDict` then).
comment on: http://stackoverflow.com/q/52474374

http://stackoverflow.com/comment/92102318
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52583395
has text: Have you tried simply passing in the file's S3 URL as `input_file_path`?

http://stackoverflow.com/comment/92057692
has text: I want the system to first compute the number of values greater than 0.5 and less than 0.5, and if, for example, values greater than 0.5 were more in the list, at the output of one of these numbers
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52559403

http://stackoverflow.com/q/52471626
score: 1
type: Question
has body: sum_num = 0 for human in humans: sum_num += human.limbs return sum_num Assume object human has a attribute limbs as in: human.limbs = rand.int(0, 4) What would be a good way to shorten this as we would with list comprehension? sum_num = sum_num + human.limbs for human in humans Obviously, the above raises an error. Is there no way to shorten some for loop like above?
tagged with: list-comprehension
tagged with: python-2.7
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91885190
has answer: http://stackoverflow.com/a/52471876
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91885277
has comment: http://stackoverflow.com/comment/91885255
type: UnansweredQuestion
tagged with: python
has title: Shortening For Loops
tagged with: list
downvote count: 0

http://stackoverflow.com/comment/91865695
has text: @CharlesDuffy duly noted
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52461787

http://stackoverflow.com/q/52533308
has body: The problem: I want to iterate over folder in search of certain file type, then execute it with a program and the name.ext as argument, and then run python script that changes the output name of the first program. I know there is probably a better way to do the above, but the way I thought of was this: [BAT] for /R "C:\..\folder" %%a IN (*.extension) do ( SET name=%%a "C:\...\first_program.exe" "%%a" "C:\...\script.py" "%name%" ) [PY] import io import sys def rename(i): name = i with open('my_file.txt', 'r') as file: data = file.readlines() data[40] ='"C:\\\\Users\\\\UserName\\\\Desktop\\\\folder\\\\folder\\\\' + name + '"\n' with open('my_file.txt', 'w') as file: file.writelines( data ) if __name__ == "__main__": rename(sys.argv[1]) Expected result: I wish the python file changed the name, but after putting it once into the console it seems to stay with the script. The BAT does not change it and it bothers me. PS. If there is a better way, I'll be glad to get to know it.
linked to: http://stackoverflow.com/q/89228
has comment: http://stackoverflow.com/comment/92006455
answer count: 1
linked to: http://stackoverflow.com/q/14574170
has comment: http://stackoverflow.com/comment/92006554
has comment: http://stackoverflow.com/comment/92009791
has comment: http://stackoverflow.com/comment/92006347
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92009880
tagged with: python
has comment: http://stackoverflow.com/comment/92009891
has comment: http://stackoverflow.com/comment/92010256
has comment: http://stackoverflow.com/comment/92010721
type: Question
has comment: http://stackoverflow.com/comment/92006210
has comment: http://stackoverflow.com/comment/92010438
has title: Running .py file with and argument in .bat
has answer: http://stackoverflow.com/a/52537304
score: 0
tagged with: batch-file
has comment: http://stackoverflow.com/comment/92006167
has comment: http://stackoverflow.com/comment/92006736
has comment: http://stackoverflow.com/comment/92006338

constraints
type: Tag
tags question: http://stackoverflow.com/q/52562244
tags question: http://stackoverflow.com/q/52508293
tag name: constraints

http://stackoverflow.com/q/52560904
type: Question
tagged with: web-crawler
downvote count: 0
has title: Pass a list of URLs to Scrapy function
favorite count: 0
has body: I have a API Python that gets two arguments (URL and a user-defined word) and provides in the JSON file how many times the specified word appears in the URL. In the meanwhile, I would like to spend more than one URL at a time, a list. I would also like to make the request with AsyncIO. Any suggestion ? Follow the code: from flask import Flask from flask_restful import Resource, Api, reqparse, abort import requests app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('url') parser.add_argument('word') parser.add_argument('ignorecase') # Função que faz um GET para a URL e retorna quantas vezes a palavra word aparece no conteudo def count_words_in(url, word, ignore_case): try: r = requests.get(url) data = str(r.text) if (str(ignore_case).lower() == 'true'): return data.lower().count(word.lower()) else: return data.count(word) except Exception as e: raise e # Função que inclui 'http://' na url e retorna a URL valida def validate_url(url): if not(url.startswith('http')): url = 'http://' + url return url class UrlCrawlerAPI(Resource): def get(self): try: args = parser.parse_args() valid_url = validate_url(args['url']) return { valid_url : { args['word'] : count_words_in(valid_url, args['word'], args['ignorecase']) }} except AttributeError: return { 'message' : 'Please provide URL and WORD arguments' } except Exception as e: return { 'message' : 'Unhandled Exception: ' + str(e) } api.add_resource(UrlCrawlerAPI, "/") if __name__ == '__main__': app.run(debug=True)
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
tagged with: scrapy

http://stackoverflow.com/a/52439425
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52438344
accepted answer of: http://stackoverflow.com/q/52438344
has body: TL;DR Use tf.accumulate_n. More on that The answer is actually more complicated in tensorflow than one would anticipate. You can chain the additions: res = a + b + c but then you create as many nodes as there are additions. What's more, you force the order of the additions: a and b are summed first (so TF has to wait for their values to be ready) then c is added. The solution seems to be res = tf.add_n([a, b, c]) which creates a single node. Alas, tf.add_n is not efficient. It waits for all inputs to be ready before summing them, so it is actually less efficient than chaining additions, which can start as soon as a and b are ready. Second, all inputs must be in memory at the same time, which wastes memory — again, when chaining additions, a and b can be discarded before summing c. The better way to sum multiple inputs is to use tf.accumulate_n, which alleviates the problems of tf.add_n, because it sums inputs as they come. IMHO the only reason for still having tf.add_n around is for compatibility with TF &lt; 1.7, for which tf.accumulate_n does not pass gradients through — a major con if you intend to support older version of TF.

http://stackoverflow.com/a/52434304
upvote count: 1
score: 1
type: AcceptedAnswer
has body: That isn't a concatenation: you're not appending this to anything else. It's only a value substitution. Thus, you should (1) use the variable name, rather than a string; (2) leave out the concatenation attempt. "device-id": d1, This should substitute the desired value of varibale d1.
downvote count: 0
answers question: http://stackoverflow.com/q/52434276
accepted answer of: http://stackoverflow.com/q/52434276
type: Answer

http://stackoverflow.com/a/52577707
has comment: http://stackoverflow.com/comment/92093529
has body: Lets go through the source code and the formulas. Sklearn states the following formula: eta = 1/(alpha* (t+t_0)). On the website of Leon Bottou we find the expression eta = eta_0 / (1 + lambda eta_0 t). Lets rewrite the latter formula a bit: eta = eta_0 / (1 + lambda eta_0 t) = 1 / ( 1/eta_0 + lambda t ) = 1 / ( lambda * ( 1/eta_0 * 1/lambda + t)). If now lambda = alpha and the t_0 from sklearn is the same as 1/(eta_0*alpha), the formulas are the same. Lets now look into the source code: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/sgd_fast.pyx#L657 In line 657 we see that optimal_init = 1.0 / (initial_eta0 * alpha). The optimal_init variable is only a different name for t_0 from our formulas as we see in line 679: eta = 1.0 / (alpha * (optimal_init + t - 1)). Hence, the formulas are the same.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92094479
answers question: http://stackoverflow.com/q/52577305
has comment: http://stackoverflow.com/comment/92094288
accepted answer of: http://stackoverflow.com/q/52577305
has comment: http://stackoverflow.com/comment/92093688
score: 4
upvote count: 4

http://stackoverflow.com/comment/91884449
comment on: http://stackoverflow.com/a/52471004
score: 0
type: Comment
type: AnswerComment
has text: If you sample from the original list three separate times, though, you'll sometimes get the same value in multiple outputs (as you do for 18, for example). The OP's example doesn't have any, so it's not clear that it's allowed.

http://stackoverflow.com/q/52494495
has title: how to write a single row cell by cell and fill it in csv file
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/52494663
has answer: http://stackoverflow.com/a/52497429
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91929575
score: -1
type: Question
answer count: 2
upvote count: 0
has body: I have a CSV file that only has column headers: cat mycsv.csv col_1@@@col_2@@@col_3@@@col_3 I have to fill a single row with None values in each cell of the CSV file. Can someone suggest me the best-optimized way to do that in Python and Pandas? After I fill the row the csv file should look like: cat mycsv.csv col_1 , col_2 , col_3 , col_3 0@@@None@@@None@@@None How to insert index and separator is @@@ instead of , ? I am getting an error as: tmp.to_csv(csvFile,sep='@@@',index=True) , line 1381, in to_csv formatter.save() 3.6.1/linux_x86_64/lib/python3.6/site-packages/pandas/formats/format.py", line 1473, in save self.writer = csv.writer(f, **writer_kwargs) TypeError: "delimiter" must be a 1-character string Exception ignored in: &lt;module 'threading' from Traceback (most recent call last): File python-3.6.1/linux_x86_64/lib/python3.6/threading.py", line 1015, in _delete del _active[get_ident()] KeyError: 140459817715712

http://stackoverflow.com/a/52546187
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52545943
type: Answer
answers question: http://stackoverflow.com/q/52545943
downvote count: 0
has body: You can try using ast.literal_val which will return a python dict. For example, in your code: import ast import json data = input['data'] begin_index = data.find('plan:') + 6 end_index = data.rfind('}') + 1 plan = ast.literal_eval(data[begin_index:end_index]) json_plan = json.dumps(plan) ast.literal_eval simply parses the string as a literal (it does not execute any code, and thus safe to use, unlike eval). This string is a valid python dict object. the "u" prefix marks a unicode type in python pre python3.

http://stackoverflow.com/comment/100625415
type: Comment
has text: I've exactly the same problem, 10 hours, would be nice to know how this ended
comment on: http://stackoverflow.com/q/52549271
score: 0
type: QuestionComment

http://stackoverflow.com/a/52474388
has comment: http://stackoverflow.com/comment/91890472
has body: Another solution using pandas: import pandas as pd import matplotlib.pyplot as plt test = "quatre jutges dun jutjat mengen fetge dun penjat" # convert input to list of chars so it is easy to get into pandas char_list = list(test) # create a dataframe where each char is one row df = pd.DataFrame({'chars': char_list}) # drop all the space characters df = df[df.chars != ' '] # add a column for aggregation later df['num'] = 1 # group rows by character type, count the occurences in each group # and sort by occurance df = df.groupby('chars').sum().sort_values('num', ascending=False) / len(df) plt.bar(df.index, df.num, width=0.5, color='g') plt.show() Result: Edit: I timed my and ikkuh's solutions Using counter: 10000 loops, best of 3: 21.3 µs per loop Using pandas groupby: 10 loops, best of 3: 22.1 ms per loop For this small dataset, Counter is definately a LOT faster. Maybe i'll time this for a bigger set when i have time.
upvote count: 2
has comment: http://stackoverflow.com/comment/91892953
score: 2
has comment: http://stackoverflow.com/comment/91892113
has comment: http://stackoverflow.com/comment/91893130
downvote count: 0
has comment: http://stackoverflow.com/comment/91893188
has comment: http://stackoverflow.com/comment/91890628
has comment: http://stackoverflow.com/comment/91890372
answers question: http://stackoverflow.com/q/52474028
type: Answer
has comment: http://stackoverflow.com/comment/91891053

http://stackoverflow.com/a/52459966
has comment: http://stackoverflow.com/comment/91888436
has comment: http://stackoverflow.com/comment/91871190
has comment: http://stackoverflow.com/comment/91862218
score: 0
has body: Update - Added file.close() as without that it doesn't work in python 3 def print_and_write(content): print(content) file = open("for_posterity.txt", "a") file.write(content) file.close() def main(): while True: print_and_write(fun1()) print_and_write(fun2()) def fun1(): return("inside fun 1") def fun2(): return("inside fun 2") if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/91862231
has comment: http://stackoverflow.com/comment/91868697
type: Answer
has comment: http://stackoverflow.com/comment/91868023
answers question: http://stackoverflow.com/q/52459478

http://stackoverflow.com/q/52560312
tagged with: flask
has comment: http://stackoverflow.com/comment/92059349
has body: I'm developing a Flask app to host a REST API service. In order to distribute the code for testing on differing systems, I can't hard-code the port that the application runs on. When running Flask 0.12.2 I am able to use the command app.run(port=0) to get a usable port assigned by the OS. This works. When I try the same command with Flask 1.0.2, I receive the message OSError: [Errno 98] Address already in use. Does anyone know why there is this discrepancy, and whether there's a workaround using Flask 1.0.2? I'm aware that it's possible to get a socket assigned by the OS using Python's socket module, but the ensuing race condition isn't acceptable for the testing environment.
tagged with: python
has comment: http://stackoverflow.com/comment/92059337
answer count: 0
has comment: http://stackoverflow.com/comment/92059576
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5085656
type: Question
has comment: http://stackoverflow.com/comment/92059494
has comment: http://stackoverflow.com/comment/92059671
has comment: http://stackoverflow.com/comment/92059222
has title: How to run a Flask (1.0.2) app on an OS-assigned port
has comment: http://stackoverflow.com/comment/92059381
score: 0
has comment: http://stackoverflow.com/comment/92059167

http://stackoverflow.com/comment/91977356
has text: @sobek It's important because my input signal `x` is separated into several signals `x = x1 + x2 + x3`. Then I'm applying modifications (filtering, etc.) on `x1`, this gives `x1_modified`. Then I'm resumming `x_modified = x1_modified + x2 + x3`. If there is some delay in `x1`'s modification, it will be weird when resumming with `x2` and `x3` which are not delayed. That's why I was looking for delay compensation, and that's why I was using `filtfilt` instead of `lfilter`.
comment on: http://stackoverflow.com/q/52502874
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52554295
has answer: http://stackoverflow.com/a/52554559
tagged with: pandas
has comment: http://stackoverflow.com/comment/92049005
favorite count: 0
has body: I have a data frame with 2 column Date and time with type in string. Date Time 20/11/2017 22:49:05 20/11/2017 22:51:07 20/11/2017 22:53:07 20/11/2017 22:58:07 I want to convert these two column into one column which is in seconds compare to 1970/01/01. Anyone knows how to do that without install any packages but time numpy pandas packages? Because I can not install package on my server which I don't have permission to do that, and the above three packages are pre-installed. Thanks in advance.
has comment: http://stackoverflow.com/comment/92047283
tagged with: time
tagged with: datetime
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/92047295
downvote count: 0
possible better answer: http://stackoverflow.com/a/52554676
has answer: http://stackoverflow.com/a/52554676
type: Question
accepted answer: http://stackoverflow.com/a/52554559
upvote count: 2
answer count: 2
has title: Convert time to seconds format in python

http://stackoverflow.com/comment/91805729
has text: try swapping axes first? `np.swapaxis()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52431034

http://stackoverflow.com/a/52457013
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52456063
has comment: http://stackoverflow.com/comment/91856807
answers question: http://stackoverflow.com/q/52456063
score: 0
has body: If you want have 50 csv files: for i in range(0,len(df['A']),100): df_100=df[i:i+100] df_100.to_csv("file"+str(i)+".csv", index=False) If you want to do some process to those sliced dataframes, you can store them in as dictionary: dict_of_df = {} for i in range(0,len(df['A']),100): dict_of_df["slice{}".format(i)]=df[i:i+100] So you will access to sliced dataframe by dict_of_df[key], where key = "slice0", "slice100", "slice200", ... When you have done with those sliced dataframes and want to combine them, df_final = pd.DataFrame() for key, values in dict_of_df.items(): df_final = df_final.append(dict_of_df[key]) Check if df_final isn't sorted well, then: df_final = df_final.sort_index() And export back to csv: df_final.to_csv("filename.csv")
type: Answer

http://stackoverflow.com/q/52516949
has comment: http://stackoverflow.com/comment/91973475
tagged with: python
has comment: http://stackoverflow.com/comment/91973516
upvote count: 3
type: Question
has title: Angle between two non intersecting lines
score: 3
has answer: http://stackoverflow.com/a/52517518
has comment: http://stackoverflow.com/comment/91973794
linked to: http://stackoverflow.com/q/46357099
answer count: 2
downvote count: 0
has body: Consider there are two lines, l1, l2 and they might be intersecting or non-intersecting. Is there any elegent way to find a angle between them? Thank you import numpy as np from shapely import LineString l1 = [(0,0), (1,1)] l2 = [(0.5, 1), (0.5, 2)] ls1 = LineString(l1) ls2 = LineString(l2) angle = compute_angle(ls1, ls2) # This is I want to avoid because I have very big dataset and performance will degrade def compute_anlge(l1, l2): #Extend line1 and line2 in both direction util they intersect # Find intersection point # Create new lines with the intersection point # find angle and return
linked to: http://stackoverflow.com/q/2150050
favorite count: 0
has answer: http://stackoverflow.com/a/52517343
type: UnansweredQuestion
tagged with: shapely

http://stackoverflow.com/a/52565139
has comment: http://stackoverflow.com/comment/92068551
answers question: http://stackoverflow.com/q/52564644
downvote count: 0
has comment: http://stackoverflow.com/comment/92074762
type: Answer
score: 2
has body: CSV is not an appropriate format for saving dictionaries (and honestly, putting dictionaries into DataFrames isn't a great data structure). You should try writing the DataFrame to json instead: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html
upvote count: 2
has comment: http://stackoverflow.com/comment/92074861
has comment: http://stackoverflow.com/comment/92068213

http://stackoverflow.com/comment/91934112
score: 0
type: AnswerComment
has text: Thank you, that was quite helpful. I will need to practice quite a bit more to understand numpy indexing.
type: Comment
comment on: http://stackoverflow.com/a/52489537

http://stackoverflow.com/comment/92014618
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52537311
has text: @Alex: do you know how to write a regular decorator wrapper? That's usually just another function. Write a function that does what you want based on an extra parameter.
score: 0

http://stackoverflow.com/comment/91922142
comment on: http://stackoverflow.com/q/52432675
has text: Something like lower(table.filename).in_(files)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91813005
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52434544
has text: As a side note, Windows is not a necessity for C#. There is a cross platform open source version of c#. You can check it out here: https://www.mono-project.com/.
score: 0

http://stackoverflow.com/q/52541912
has comment: http://stackoverflow.com/comment/92024157
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52558184
has body: I have a custom docx file dictionary where the words to be defined are on uppercase and bold. That is the only distinction from other words. The definitions are often large and with lines between, therefor it creates a new paragraph. As Sample: A ASDFG this means blah. Blah comes from the aakak It is still the same definition for ASDFG MUG meaning of mug ABBA musical group I want to separate the paragraphs correctly to sort by the word to define (Upper case word) alphabetically. This is what I have for p in document.paragraphs: if p.text.split(' ', 1)[0].isupper(): #save as paragraph paragraph1 = text else: #concatenate to previews paragraph paragraph1 = text[-1] + text Desired Output A ABBA definition ASDFG definition M MUG definition Thank you!
type: Question
has comment: http://stackoverflow.com/comment/92024106
has comment: http://stackoverflow.com/comment/92024179
has title: Python Sorting a docx file
tagged with: text-mining
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92054775

http://stackoverflow.com/q/52569318
has body: I have same question here, I have only two data sets, one for test and train. I am using test data as the validation_data for the keras model.fit function like this. model.fit(X_train,y_train, batch_size=64, epochs=epochs, callbacks=[es,reduceLROnPlateau,modelCheckpoint], validation_data=(X_test,y_test), verbose=2) I am using Early stop, ReduceLROnPlateau and ModelCheckpoint. All on the val_loss. My objective is to get the training to stop where the test accuracy or auc score is highest. Since the validation data is not contributing to the training, is this alright to do it this way? Futher details, my test_data contains completely different/unseen objects than train data, so even when I make validation data from splitting the train data it is not a great indicator for the generalization performance of my network on test data. So the results I am getting are they scientifically fair or its cheating? What's the best practice in this? Train on 39840 samples, validate on 7440 samples Epoch 1/30 - 257s - loss: 0.6046 - acc: 0.7782 - val_loss: 0.6797 - val_acc: 0.8055 Epoch 00001: val_loss improved from inf to 0.67972, saving model to keras_densenet_simple_wt_28Sept.h5 Epoch 2/30 - 253s - loss: 0.5055 - acc: 0.8236 - val_loss: 0.5370 - val_acc: 0.8085 Epoch 00002: val_loss improved from 0.67972 to 0.53701, saving model to keras_densenet_simple_wt_28Sept.h5 Epoch 3/30 - 253s - loss: 0.4506 - acc: 0.8518 - val_loss: 0.6623 - val_acc: 0.7937 Epoch 00003: val_loss did not improve from 0.53701 Epoch 4/30 - 253s - loss: 0.4110 - acc: 0.8711 - val_loss: 0.6583 - val_acc: 0.7995 Epoch 00004: val_loss did not improve from 0.53701 Epoch 5/30 - 253s - loss: 0.3726 - acc: 0.8908 - val_loss: 0.5282 - val_acc: 0.8237 Epoch 00005: val_loss improved from 0.53701 to 0.52820, saving model to keras_densenet_simple_wt_28Sept.h5 Epoch 6/30 - 253s - loss: 0.3427 - acc: 0.9035 - val_loss: 0.4683 - val_acc: 0.8422 Epoch 00006: val_loss improved from 0.52820 to 0.46830, saving model to keras_den…
type: Question
has title: keras: Can the test data be used for early_stoppage and model checkpoint
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/92076356
has comment: http://stackoverflow.com/comment/92076034
answer count: 0
type: UnansweredQuestion
tagged with: keras
has comment: http://stackoverflow.com/comment/92076007

http://stackoverflow.com/q/52565399
answer count: 1
has body: I am trying to remove some fields from existing model of Django on Heroku, So I run make migrations, then migrate commands, it seemed like succesfully did the migrations. After that I found out one field was missing, so I created next migration file myself, put dependency to previous auto generated migration file. When I run it, I have an error like this: ~ $ python manage.py migrate Operations to perform: Apply all migrations: API, admin, auth, authtoken, contenttypes, sessions Running migrations: Applying API.0007_timezoneremoval...Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "…
tagged with: django-rest-framework
has title: 'NoneType' object has no attribute 'is_relation' error on Django Migrations
tagged with: postgresql
has comment: http://stackoverflow.com/comment/92068542
tagged with: django
has comment: http://stackoverflow.com/comment/92068575
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56506178
type: Question
tagged with: heroku
has comment: http://stackoverflow.com/comment/92068671
score: 0

http://stackoverflow.com/a/52505816
has comment: http://stackoverflow.com/comment/91953353
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/52505732
score: 6
has body: You're looking for np.linalg.matrix_power. If you're using numpy, don't use a for loop, use a vectorized operation. arr = np.arange(16).reshape((4,4)) np.linalg.matrix_power(arr, 3) array([[ 1680, 1940, 2200, 2460], [ 4880, 5620, 6360, 7100], [ 8080, 9300, 10520, 11740], [11280, 12980, 14680, 16380]]) Which is the same as the explicit multiplication: arr @ arr @ arr &gt;&gt;&gt; np.array_equal(arr @ arr @ arr, np.linalg.matrix_power(arr, 3)) True Since you asked If you really want a naive solution using loops, we can put together the pieces quite easily. First we need a way to actually multiple the matrices. There are options that beat n^3 complexity, this answer is not going to do that. Here is a basic matrix multiplication function: def matmultiply(a, b): res = np.zeros(a.shape) size = a.shape[0] for i in range(size): for j in range(size): for k in range(size): res[i][j] += a[i][k] * b[k][j] return res Now you need an exponential function. This function takes a matrix and a power, and raises a matrix to that power. def loopy_matrix_power(a, n): res = np.identity(a.shape[0]) while n &gt; 0: if n % 2 == 0: a = matmultiply(a, a) n /= 2 else: res = matmultiply(res, a) n -= 1 return res In action: loopy_matrix_power(arr, 3) array([[ 1680., 1940., 2200., 2460.], [ 4880., 5620., 6360., 7100.], [ 8080., 9300., 10520., 11740.], [11280., 12980., 14680., 16380.]])
has comment: http://stackoverflow.com/comment/91952487
downvote count: 0
has comment: http://stackoverflow.com/comment/91952342

http://stackoverflow.com/a/52489159
has comment: http://stackoverflow.com/comment/98853363
has comment: http://stackoverflow.com/comment/91956166
score: 11
has comment: http://stackoverflow.com/comment/98867247
downvote count: 0
type: Answer
has body: Looking at the documentation for this API it seems the only responses are in JSON format, so receiving HTML is strange. To increase the likelihood of receiving a JSON response, you can set the 'Accept' header to 'application/json'. I tried querying this API many times with parameters and did not encounter a JSONDecodeError. This error is likely the result of another error on the server side. To handle it, except a json.decoder.JSONDecodeError in addition to the ConnectionError error you currently except and handle this error in the same way as the ConnectionError. Here is an example with all that in mind: import requests, json, time, random def get_submission_records(client, since, try_number=1): url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&amp;filter[]=date,cs,'+since headers = {'Accept': 'application/json'} try: response = requests.get(url, headers=headers).json() except (requests.exceptions.ConnectionError, json.decoder.JSONDecodeError): time.sleep(2**try_number + random.random()*0.01) #exponential backoff return get_submission_records(client, since, try_number=try_number+1) else: return response['submission']['records'] I've also wrapped this logic in a recursive function, rather than using while loop because I think it is semantically clearer. This function also waits before trying again using exponential backoff (waiting twice as long after each failure). Edit: For Python 2.7, the error from trying to parse bad json is a ValueError, not a JSONDecodeError import requests, time, random def get_submission_records(client, since, try_number=1): url = 'http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&amp;filter[]=date,cs,'+since headers = {'Accept': 'application/json'} try: response = requests.get(url, headers=headers).json() except (requests.exceptions.ConnectionError, ValueError): time.sleep(2**try_number + random.random()*0.01) #exponential backoff return get_submission_records(client, since…
upvote count: 11
has comment: http://stackoverflow.com/comment/92027645
has comment: http://stackoverflow.com/comment/92029452
answers question: http://stackoverflow.com/q/52488117
has comment: http://stackoverflow.com/comment/139736927
has comment: http://stackoverflow.com/comment/92027779
has comment: http://stackoverflow.com/comment/139737346

http://stackoverflow.com/a/52472933
has body: you need, pd.merge with outer join, pd.merge(df1,df2,on=['Index','block_id'],how='outer') #[out] #Index block_id Ut_rec_0 Ut_rec_1 #0 0 7 3.0 #1 1 10 NaN #2 2 2 5.0 #3 3 0 5.0 #4 4 10 NaN #5 5 3 9.0 #6 6 6 NaN #7 7 9 4.0
score: 0
answers question: http://stackoverflow.com/q/52471770
type: Answer

http://stackoverflow.com/a/52556541
upvote count: 1
has comment: http://stackoverflow.com/comment/92126220
answers question: http://stackoverflow.com/q/52552978
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92126313
score: 1
has comment: http://stackoverflow.com/comment/92126121
has body: I think the following code will answer your questions: (A) how can you print the batch loss AFTER performing the train step? (B) how can you calculate the loss over the entire training set, even though the dataset iterator gives only a batch each time? import tensorflow as tf import numpy as np dataset_size = 200 batch_size= 5 dimension = 4 # create some training dataset dataset = tf.data.Dataset.\ from_tensor_slices(np.random.normal(2.0,size=(dataset_size,dimension)). astype(np.float32)) dataset = dataset.batch(batch_size) # take batches iterator = dataset.make_initializable_iterator() x = tf.cast(iterator.get_next(),tf.float32) w = tf.Variable(np.random.normal(size=(1,dimension)).astype(np.float32)) loss_func = lambda x,w: tf.reduce_mean(tf.square(x-w)) # notice that the loss function is a mean! loss = loss_func(x,w) # this is the loss that will be minimized train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # we are going to use control_dependencies so that we know that we have a loss calculation AFTER the train step with tf.control_dependencies([train_op]): loss_after_train_op = loss_func(x,w) # this is an identical loss, but will only be calculated AFTER train_op has # been performed with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # train one epoch sess.run(iterator.initializer) for i in range(dataset_size//batch_size): # the training step will update the weights based on ONE batch of examples each step loss1,_,loss2 = sess.run([loss,train_op,loss_after_train_op]) print('train step {:d}. batch loss before step: {:f}. batch loss after step: {:f}'.format(i,loss1,loss2)) # evaluate loss on entire training set. Notice that this calculation assumes the the loss is of the form # tf.reduce_mean(...) sess.run(iterator.initializer) epoch_loss = 0 for i in range(dataset_size // batch_size): batch_loss = sess.run(loss) epoch_loss += batch_loss*batch_size epoch_loss = epoch_loss/dataset_size print('loss over entire training dataset: {:f…
has comment: http://stackoverflow.com/comment/92111829
has comment: http://stackoverflow.com/comment/92110045
has comment: http://stackoverflow.com/comment/92126386

http://stackoverflow.com/q/52462165
has comment: http://stackoverflow.com/comment/91917953
downvote count: 1
has comment: http://stackoverflow.com/comment/91917683
has comment: http://stackoverflow.com/comment/91912022
favorite count: 0
tagged with: python-3.x
has title: Matplotlib Interactive subplots with integers and dates on X axes
tagged with: python
has comment: http://stackoverflow.com/comment/91955286
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91876689
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/91877273
has comment: http://stackoverflow.com/comment/91866683
tagged with: subplot
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91906083
has comment: http://stackoverflow.com/comment/91918313
has comment: http://stackoverflow.com/comment/91876194
has body: I am trying to create two interactive plots where the first plot is simply a plot of x and y and the second plot is a subplot which plots dates (fulldate) on its x axis, which correspond to the integer values of x (x axis values) from the first plot. This code almost does what I want. The only problem is that the dates are not linked to the integers, so when I use the zoom function on the graph, it zooms into the first plot and the subplot is linked and zooms also, but the dates stay stationary and therefore are completely inaccurate. note that this is just a simplified version of my program. i will be rearranging the dates on the bottom display to got on the bottom. The integers and the dates must be linked because in my actual program i will be using integers to keep count of the days in the time series. import matplotlib.pyplot as plt import seaborn as sns x=[1,5,7,4,6] y=[1,3,8,4,6] fulldate=['01/01/2018','02/01/2018','03/01/2018','04/01/2018','05/01/2018'] with sns.axes_style("darkgrid"): ax1=plt.subplot2grid((6,1),(0,0),rowspan=3,colspan=1) ax2=plt.subplot2grid((6,1),(4,0),rowspan=1,colspan=1,sharex=ax1) ax2v = ax2.twiny() ax1.plot(x,y) ax2v.fill_between(fulldate,'Dates') for label in ax2v.xaxis.get_ticklabels(): label.set_rotation(60)
has comment: http://stackoverflow.com/comment/91918222
score: 0
has comment: http://stackoverflow.com/comment/91876511
upvote count: 1
has comment: http://stackoverflow.com/comment/91872320

http://stackoverflow.com/a/52431848
type: Answer
answers question: http://stackoverflow.com/q/52431165
score: 0
has body: Combined some solution above d = defaultdict(int) for num in set(arr): d[getErrorType(num)] += arr.count(num)

http://stackoverflow.com/a/52461491
upvote count: 1
answers question: http://stackoverflow.com/q/52459748
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52459748
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91883668
has body: The best way to accomplish this is to create a new class in addition to dog and cat to handle images you have no interest in. So now, your labels would be ["dogs", "cats", "other"]. In your current architecture, your model is forced to predict a random image as either a dog or cat as those are the only two options it has. Adding a new class to deal with other images is generally the easiest way to make your classifier more robust to incorrect predictions.
type: Answer
has comment: http://stackoverflow.com/comment/91882773
score: 1

http://stackoverflow.com/q/52482926
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52483099
downvote count: 1
has comment: http://stackoverflow.com/comment/91907567
type: Question
has body: I am attempting to run a data check comparing columns within a dataframe and returning the % difference; however, I cannot get the conditional aspect of the below code to run without getting the following ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Item Number') def checks(df): if Multi['Masterpack qty'] == Multi['SUBPACK_QTY']: Multi['Length Difference'] = abs((Multi['Length']-Multi['SUBPACK_LENGTH'])/((Multi['Length']+Multi['SUBPACK_LENGTH'])/2)) Multi['Height Difference'] = abs((Multi['Height']-Multi['SUBPACK_HEIGHT'])/((Multi['Height']+Multi['SUBPACK_HEIGHT'])/2)) Multi['Width Difference'] = abs((Multi['Width']-Multi['SUBPACK_WIDTH'])/((Multi['Width']+Multi['SUBPACK_WIDTH'])/2)) Multi['Weight Difference'] = abs((Multi['Weight']-Multi['SUBPACK_WEIGHT'])/((Multi['Weight']+Multi['SUBPACK_WEIGHT'])/2)) elif Multi['Masterpack qty'] == Multi['PACK_QTY']: Multi['Length Difference'] = abs((Multi['Length']-Multi['PACK_LENGTH'])/((Multi['Length']+Multi['PACK_LENGTH'])/2)) Multi['Height Difference'] = abs((Multi['Height']-Multi['PACK_HEIGHT'])/((Multi['Height']+Multi['PACK_HEIGHT'])/2)) Multi['Width Difference'] = abs((Multi['Width']-Multi['PACK_WIDTH'])/((Multi['Width']+Multi['PACK_WIDTH'])/2)) Multi['Weight Difference'] = abs((Multi['Weight']-Multi['PACK_WEIGHT'])/((Multi['Weight']+Multi['PACK_WEIGHT'])/2)) else: Multi['Length Difference'] = 'No Match' Multi['Height Difference'] = 'No Match' Multi['Width Difference'] = 'No Match' Multi['Weight Difference'] = 'No Match' Multi.apply(checks)
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91907336
has title: Python Data Comparisons
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52483099

http://stackoverflow.com/q/52488885
tagged with: python
has answer: http://stackoverflow.com/a/52489000
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: django
type: Question
tagged with: django-models
has title: E1101:Instance of 'Meta' has no 'title' member
upvote count: 1
has body: im working on a project with Django 2.1 (Python 3.7), so i used an inner class of another one, and i tried to use the "title" variable of the parent class ,but unfortunately i had an error (Instance of 'Meta' has no 'title' member),here is the code, can you guys please help me ? enter image description here
answer count: 1
accepted answer: http://stackoverflow.com/a/52489000
favorite count: 0

http://stackoverflow.com/comment/92002437
type: QuestionComment
comment on: http://stackoverflow.com/q/52521068
has text: Is the python version on windows and linux same?
score: 0
type: Comment

http://stackoverflow.com/q/52527774
tagged with: azure-devops
has title: Azure DevOps Pip Install
has body: I am getting the following error when trying to deploy my build release for a python/flask web app:- I created a python command task with the following - pip install --upgrade However, error persists.
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/91997515
has comment: http://stackoverflow.com/comment/91997985
type: Question
score: 0
has answer: http://stackoverflow.com/a/52529913
tagged with: azure
tagged with: release
answer count: 1

pytorch
tags question: http://stackoverflow.com/q/52524117
tags question: http://stackoverflow.com/q/52474439
tags question: http://stackoverflow.com/q/52469566
tags question: http://stackoverflow.com/q/52458725
tags question: http://stackoverflow.com/q/52455285
tags question: http://stackoverflow.com/q/52570007
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/52548174
tags question: http://stackoverflow.com/q/52503695
tags question: http://stackoverflow.com/q/52547157
tags question: http://stackoverflow.com/q/52455658
tags question: http://stackoverflow.com/q/52451797
tags question: http://stackoverflow.com/q/52465723
tags question: http://stackoverflow.com/q/52439364
tags question: http://stackoverflow.com/q/52554314
tags question: http://stackoverflow.com/q/52498690
tags question: http://stackoverflow.com/q/52560040
tags question: http://stackoverflow.com/q/52489460
tags question: http://stackoverflow.com/q/52489037
tags question: http://stackoverflow.com/q/52513802
tags question: http://stackoverflow.com/q/52468956
tags question: http://stackoverflow.com/q/52478445
tags question: http://stackoverflow.com/q/52458508
tags question: http://stackoverflow.com/q/52566050

http://stackoverflow.com/comment/92103783
has text: Sorry about that, didn't realize I left that out. I have added the example above.
comment on: http://stackoverflow.com/q/52584420
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/91958316
comment on: http://stackoverflow.com/q/52509083
has text: Short answer: The use of `or` is wrong.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/92036968
has text: @cosmic_inquiry, an example has been provided. Does this make sense?
comment on: http://stackoverflow.com/q/52547638
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91932054
has text: Hi @Poolka thank you very much - all works fine, could you tell me where you found information about the command pipe.stdin.write(str(a).encode('UTF-8')) ? I read https://docs.python.org/3/library/subprocess.html but found no information about the command there. Actually it seems to me that I do not learn from standard library the write way since I often do not get the needfull information from it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52479283
type: Comment

http://stackoverflow.com/q/52572693
answer count: 4
tagged with: audio
type: AnsweredQuestion
tagged with: audio-processing
has comment: http://stackoverflow.com/comment/134952800
has comment: http://stackoverflow.com/comment/92090594
has comment: http://stackoverflow.com/comment/92092675
has body: I have a load of 3 hour MP3 files, and every ~15 minutes a distinct 1 second sound effect is played, which signals the beginning of a new chapter. Is it possible to identify each time this sound effect is played, so I can note the time offsets? The sound effect is similar every time, but because it's been encoded in a lossy file format, there will be a small amount of variation. The time offsets will be stored in the ID3 Chapter Frame MetaData. Example Source, where the sound effect plays twice. ffmpeg -ss 0.9 -i source.mp3 -t 0.95 sample1.mp3 -acodec copy -y Sample 1 (Spectrogram) ffmpeg -ss 4.5 -i source.mp3 -t 0.95 sample2.mp3 -acodec copy -y Sample 2 (Spectrogram) I'm very new to audio processing, but my initial thought was to extract a sample of the 1 second sound effect, then use librosa in python to extract a floating point time series for both files, round the floating point numbers, and try to get a match. import numpy import librosa print("Load files") source_series, source_rate = librosa.load('source.mp3') # 3 hour file sample_series, sample_rate = librosa.load('sample.mp3') # 1 second file print("Round series") source_series = numpy.around(source_series, decimals=5); sample_series = numpy.around(sample_series, decimals=5); print("Process series") source_start = 0 sample_matching = 0 sample_length = len(sample_series) for source_id, source_sample in enumerate(source_series): if source_sample == sample_series[sample_matching]: sample_matching += 1 if sample_matching &gt;= sample_length: print(float(source_start) / source_rate) sample_matching = 0 elif sample_matching == 1: source_start = source_id; else: sample_matching = 0 This does not work with the MP3 files above, but did with an MP4 version - where it was able to find the sample I extracted, but it was only that one sample (not all 12). I should also note this script takes just over 1 minute to process the 3 hour file (which includes 237,426,624 samples). So I can imagine that some kind of averaging o…
upvote count: 8
has answer: http://stackoverflow.com/a/54032274
type: Question
accepted answer: http://stackoverflow.com/a/54032274
has answer: http://stackoverflow.com/a/52682780
has comment: http://stackoverflow.com/comment/92084575
has comment: http://stackoverflow.com/comment/137691891
has title: Find sound effect inside an audio file
possible better answer: http://stackoverflow.com/a/52683259
has answer: http://stackoverflow.com/a/52802473
linked to: http://stackoverflow.com/q/62524604
downvote count: 0
tagged with: librosa
score: 8
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52683259
has comment: http://stackoverflow.com/comment/92523584

http://stackoverflow.com/q/52460484
has body: What is the problem? I tried "python -m pip install -U pip" and "python -m pip install --upgrade pip" both with the same error (and "pip install -U --force-reinstall pip"). what should I do? C:\Users\Peyman\PycharmProjects\untitled3&gt;python -m pip install -U pip Collecting pip Using cached https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 9.0.3 Uninstalling pip-9.0.3: Successfully uninstalled pip-9.0.3 Rolling back uninstall of pip Exception: Traceback (most recent call last): File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\wheel.py", line 462, in move_wheel_files generated.extend(maker.make(spec)) File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\_vendor\distlib\scripts.py", line 372, in make self._make_script(entry, filenames, options=options) File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\_vendor\distlib\scripts.py", line 276, in _make_script self._write_script(scriptnames, shebang, script, filenames, ext) File "C:\Users\Peyman\AppData\Roaming\Python\Python35\site-packages\pip\_vendor\distlib\scripts.py", line 212, in _write_scr…
has answer: http://stackoverflow.com/a/52460551
score: 17
upvote count: 17
type: Question
tagged with: python-3.5
possible better answer: http://stackoverflow.com/a/54518924
has answer: http://stackoverflow.com/a/54518924
has answer: http://stackoverflow.com/a/59993004
accepted answer: http://stackoverflow.com/a/52460551
downvote count: 0
has answer: http://stackoverflow.com/a/71119306
favorite count: 0
tagged with: pip
tagged with: python
has title: Python 3.5 pip 9 AttributeError: 'NoneType' object has no attribute 'bytes'
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/52441974
has title: How do you succinctly add two series together, but only adding the positive values?
favorite count: 0
tagged with: python
has body: I have two series; energy_dict['QLD'] = Timestamp 2017-04-27 00:00:00 523.720765 2017-04-27 01:00:00 512.180608 2017-04-27 02:00:00 519.076642 2017-04-27 03:00:00 516.329201 2017-04-27 04:00:00 525.150158 ... ... Freq: H, Name: QLD Total Energy (MWh), Length: 8760, dtype: float64 and Incoming_Flow = Timestamp 2017-04-27 00:00:00 -8.961111 2017-04-27 01:00:00 9.503472 2017-04-27 02:00:00 -10.776389 2017-04-27 03:00:00 1.451389 2017-04-27 04:00:00 -10.388195 ... ... Freq: H, Name: METEREDMWFLOW N-Q-MNSP1, Length: 8760, dtype: float64 I would like to add them together, but only when the second one is larger than zero. What is the best way to do this? I am aware that I could do something like this; Incoming_Flow[Incoming_Flow &lt; 0 ] = 0 but I would like to be able to do it all in one line
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: addition
has answer: http://stackoverflow.com/a/52445253
type: Question
has answer: http://stackoverflow.com/a/52442039
score: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52443640

http://stackoverflow.com/q/52431295
has answer: http://stackoverflow.com/a/52431664
score: 1
has comment: http://stackoverflow.com/comment/91806480
has comment: http://stackoverflow.com/comment/91806298
upvote count: 1
has answer: http://stackoverflow.com/a/52433498
has comment: http://stackoverflow.com/comment/91808456
has title: How to make variable(s) global over different modules in Python?
type: Question
accepted answer: http://stackoverflow.com/a/52431664
possible better answer: http://stackoverflow.com/a/52432125
has answer: http://stackoverflow.com/a/52432125
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91806265
favorite count: 0
tagged with: python
has body: I have a small project where I need to initially introduce and use some quite large number of variables. Obviously, I can make some configure file, where I set up all the values of the variables. I have made just some Python file, where I give values: value_a = 'something' value_b = 'something' value_c = 5.0 and call the file conf.py. When I do from conf import *, I have all the variables with values initialized. Nevertheless, I have different modules in project with different subroutines (methods in it) and I want to have all those values from conf.py known in every method and in every module. Obviously, I can do from conf import * in every module and/or import conf in every subroutine, but is it the best way how to implement the initialization of variables?
has comment: http://stackoverflow.com/comment/91810060
has comment: http://stackoverflow.com/comment/91806277
type: AnsweredQuestion

http://stackoverflow.com/a/52582767
has comment: http://stackoverflow.com/comment/92100635
has comment: http://stackoverflow.com/comment/92100918
answers question: http://stackoverflow.com/q/52582695
type: Answer
has comment: http://stackoverflow.com/comment/92100716
has comment: http://stackoverflow.com/comment/92100600
downvote count: 0
has comment: http://stackoverflow.com/comment/92100559
has comment: http://stackoverflow.com/comment/92100693
has comment: http://stackoverflow.com/comment/92100751
has comment: http://stackoverflow.com/comment/92100947
score: 1
has comment: http://stackoverflow.com/comment/92100609
has body: Your code has other issues beyond this but as your question at hand, it is here: elif right == len(choice): answer[int(location)] = guess print(answer[0:len(choice)]) print("Congratulations! You have won!") guessed = True else: right += 1 answer[location] = guess print(answer[0:len(choice)]) Your two statements answer[int(location)] = guess and answer[location] = guess if you print location it is a list, for a 4 letter word example vash, location is a list of range [0,3] you are attempting to pass the entire list as an index which will not work regardless if you convert it to int or not. Please try this modification, this is not a full solution, I do not want to take away from your journey on this project but this will get your moving: import random lines = ['hey', 'this', 'that'] choice = random.choice(lines) #print("it says", choice) guessed = False print("Your word is", len(choice), "letters long!") answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"] wrong = 0 right = 0 print(choice) while not guessed: guess = input("Guess a letter!") #location = choice.find(guess) if wrong == 6: print("Sorry, you have killed yourself.") guessed = True elif guess not in choice: wrong += 1 print("Sorry, that was not part of the word!") print("You have", (6 - wrong), "guesses left") elif right == len(choice): print(answer) print("Congratulations! You have won!") guessed = True else: right += 1 answer[choice.index(guess)] = guess print(answer[0:len(choice)])
upvote count: 1

http://stackoverflow.com/a/52549714
answers question: http://stackoverflow.com/q/52549254
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/92038398
has body: You have to place your counters on the right places. Suppose bestcounter1 is used to count values of 1 during every run (12 rolls) while bestcounter2 is used to count runs when you got 2 or more values of 1. Then your main for loop should look like this: for i in range(get_sample): # reset before every run bestcounter1 = 0 for i in range(12): if random.randint(1, 6) == 1: # count values of 1 bestcounter1 += 1 # check if we got 2 or more values of 1 if bestcounter1 &gt;= 2: # count proper cases bestcounter2 += 1 break oneatleasttwice = bestcounter2 / get_sample I got result 61.9% with one million runs.
downvote count: 0

http://stackoverflow.com/a/54209347
upvote count: 1
answers question: http://stackoverflow.com/q/52564716
has body: You can use inspect module to get the sol variable from main function without change anything of main.py. Of course, you need to call main function. Main.py: from test import test def main(): sol = 'hello' if test() == sol: print('Yes') else: print('No') main() test.py: import inspect def test(): frame = inspect.currentframe() sol_from_main = 'default' try: sol_from_main = frame.f_back.f_locals['sol'] # line A except: print('No sol found') print(sol_from_main) # this print 'hello' return sol_from_main Output: hello Yes Explanation: From the python doc, we can see next: frame f_back | next outer frame object (this frame’s caller) f_locals | local namespace seen by this frame So line A get the caller of current function, that is main function, and use f_locals to get all local variables of main function, so it can get the sol value from main. FYI in case you still need it.
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/52556847
has answer: http://stackoverflow.com/a/52632807
has body: I'm trying to use batch requests on a retrained Inception model using retrain.py from tensorflow(actually available on hub repository). Unfortunately I didn't find any documentation available. Basically I'm using inception_client.py to perform requests to tensorflow_model_server on a docker container and it works very well when there is one image(even if with the parameter --enable_batching). I've tried to use a stacked list of 10 images using tf.stack() to test batching but it raises the following exception: AbortionError(code=StatusCode.INVALID_ARGUMENT, details="Input to reshape is a tensor with 20480 values, but the requested shape has 2048 [[Node: pool_3/_reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _output_shapes=[[1,2048]], _device="/job:localhost/replica:0/task:0/device:CPU:0"](pool_3, pool_3/_reshape/shape)]]") I'm guessing that my model didn't support batching requests. So, how do I should retrain Inception models to support batching requests?
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: tensorflow-serving
tagged with: tensorflow
has title: Using batch requests on retrained inception
type: Question

http://stackoverflow.com/comment/91836277
type: QuestionComment
has text: Do any of your print statements go off when you click? Or does nothing happen?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52446599

http://stackoverflow.com/comment/92062038
has text: Probably looking for `value_counts`. Try `df.col.value_counts().loc[1]`
score: 3
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52561762

http://stackoverflow.com/q/52505470
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: package
tagged with: python
has comment: http://stackoverflow.com/comment/91954202
has body: I create a python package. The configuration should be placed in /etc/myapp if installed globally or in ~/.myapp if installed for user only (pip install myapp --user). I can do the first point with this in the setup.py file: data_files = [("/etc/myapp", ['application.properties']) But how can I place this file in ~/.myapp if installed for user only?
answer count: 0
upvote count: 3
tagged with: pip
type: Question
score: 3
linked to: http://stackoverflow.com/q/47460804
has title: setup.py install etc files in user directory

http://stackoverflow.com/a/52912861
has body: The indentation was bad and the conditions weren't handled properly. import re import sys current_name = None zero_count, one_count = 0,0 i = 0 for line in sys.stdin: # parse the input name, binary, count = line.split('\t') #print(name) #print(current_name) if(i == 0): current_name = name i = i + 1 if(name == current_name): if int(binary) == 0: zero_count += int(count) elif int(binary) == 1: one_count += int(count) else: print(f'{current_name}\t{0} \t{zero_count}') print(f'{current_name}\t{1} \t{one_count}') current_name = name #print(current_name) zero_count, one_count = 0,0 if int(binary) == 0: zero_count += int(count) elif int(binary) == 1: one_count += int(count) print(f'{current_name}\t{0} \t{zero_count}') print(f'{current_name}\t{1} \t{one_count}') 'i' handles the case where you do not have a 'current_name' for the first line of input (It will run only once). In the else block, you had re-initialize 'zero_count' and 'one_count', and also do the calculation for the new 'current_name'. Output for my code : Adam 0 2 Adam 1 1 Mike 0 1 Mike 1 2
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/52434983
upvote count: 1

django-rest-framework
tags question: http://stackoverflow.com/q/52437156
tags question: http://stackoverflow.com/q/52447984
tags question: http://stackoverflow.com/q/52520800
tags question: http://stackoverflow.com/q/52454977
tags question: http://stackoverflow.com/q/52474287
tags question: http://stackoverflow.com/q/52566790
tags question: http://stackoverflow.com/q/52534075
tags question: http://stackoverflow.com/q/52491330
tags question: http://stackoverflow.com/q/52523297
tags question: http://stackoverflow.com/q/52585200
tags question: http://stackoverflow.com/q/52488977
tags question: http://stackoverflow.com/q/52583585
tags question: http://stackoverflow.com/q/52512099
tags question: http://stackoverflow.com/q/52587144
tags question: http://stackoverflow.com/q/52495474
tags question: http://stackoverflow.com/q/52580825
tags question: http://stackoverflow.com/q/52470386
type: Tag
tags question: http://stackoverflow.com/q/52585206
tags question: http://stackoverflow.com/q/52529397
tags question: http://stackoverflow.com/q/52507413
tags question: http://stackoverflow.com/q/52475303
tags question: http://stackoverflow.com/q/52469751
tags question: http://stackoverflow.com/q/52565399
tags question: http://stackoverflow.com/q/52465664
tags question: http://stackoverflow.com/q/52477714
tags question: http://stackoverflow.com/q/52460372
tags question: http://stackoverflow.com/q/52570246
tags question: http://stackoverflow.com/q/52523244
tags question: http://stackoverflow.com/q/52435842
tags question: http://stackoverflow.com/q/52467146
tags question: http://stackoverflow.com/q/52485203
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/52434564
tags question: http://stackoverflow.com/q/52566728
tags question: http://stackoverflow.com/q/52569690
tags question: http://stackoverflow.com/q/52553680
tags question: http://stackoverflow.com/q/52438357
tags question: http://stackoverflow.com/q/52497775
tags question: http://stackoverflow.com/q/52486899
tags question: http://stackoverflow.com/q/52509276
tags question: http://stackoverflow.com/q/52483397
tags question: http://stackoverflow.com/q/52444818
tags question: http://stackoverflow.com/q/52507709
tags question: http://stackoverflow.com/q/52505814
tags question: http://stackoverflow.com/q/52552838
tags question: http://stackoverflow.com/q/52438130
tags question: http://stackoverflow.com/q/52431668
tags question: http://stackoverflow.com/q/52469050
tags question: http://stackoverflow.com/q/52480307
tags question: http://stackoverflow.com/q/52574898
tags question: http://stackoverflow.com/q/52439290
tags question: http://stackoverflow.com/q/52514453

http://stackoverflow.com/q/52474282
type: Question
score: 5
has answer: http://stackoverflow.com/a/79087639
has body: This question is different than Is there a way to use asyncio.Queue in multiple threads? I have 2 asyncio event loops running in two different threads. Thread1 produces data to Thread2 through a asyncio.Queue(). One of the threads throws an exception: got Future &lt;Future pending&gt; attached to a different loop Now this is true because I have a single queue that I use in different loops. How can I share a queue between two loops, in two different threads? Example code: q = asyncio.Queue() async def producer(q): await asyncio.sleep(3) q.put(1) def prod_work(q): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(producer(q)) async def consumer(q): await asyncio.sleep(3) res = await q.get() def cons_work(q): loop2 = asyncio.new_event_loop() asyncio.set_event_loop(loop2) loop2.run_until_complete(consumer(q)) def worker(q): # main thread - uses this threads loop prod = threading.Thread(target=prod_work, args=(q,)) # separate thread - uses NEW loop cons = threading.Thread(target=cons_work, args=(q,)) prod.start() cons.start() worker(q) full stack trace: Exception in thread Thread-2: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "asyncio_examples.py", line 24, in cons_work loop2.run_until_complete(consumer(q)) File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete return future.result() File "asyncio_examples.py", line 18, in consumer res = await q.get() File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/queues.py", line 159, in get await getter RuntimeError: Task &lt;Task pending coro=&lt;consu…
linked to: http://stackoverflow.com/q/32889527
upvote count: 5
has comment: http://stackoverflow.com/comment/91890714
tagged with: python-asyncio
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91891204
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
linked to: http://stackoverflow.com/q/50520430
has title: How can I share asyncio.Queue between multiple threads?
has comment: http://stackoverflow.com/comment/91890483

http://stackoverflow.com/comment/92085011
comment on: http://stackoverflow.com/a/52574510
score: 0
type: AnswerComment
type: Comment
has text: gives error that maximum recursion depth exceeded in comparison, also yield from does not work in python <3.3

http://stackoverflow.com/comment/91879387
type: AnswerComment
has text: I think the `op` module provides slightly more standard « operators as functions » if you’re interested.
type: Comment
comment on: http://stackoverflow.com/a/52464592
score: 0

http://stackoverflow.com/comment/91984690
type: AnswerComment
score: 0
has text: What I'm saying is, have you tried feeding in a list of all of your stationary columns into `index=[YOUR_STATIONARY_COLUMNS]`
type: Comment
comment on: http://stackoverflow.com/a/52505692

http://stackoverflow.com/a/52435325
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52434942
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/120629844
answers question: http://stackoverflow.com/q/52434942
type: Answer
has body: As @erip has pointed out in the comments, you can iterate through the list, add items to a set, and if the item is already in a set, it is a duplicate that has the lowest index, so you can simply return the item; or return -1 if you get to the end of the loop without finding a duplicate: def firstDuplicate(a): seen = set() for i in a: if i in seen: return i seen.add(i) return -1
score: 5
upvote count: 5

http://stackoverflow.com/a/52506544
has comment: http://stackoverflow.com/comment/92130600
has comment: http://stackoverflow.com/comment/92154393
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52431372
has body: I think this answer might be close to what you are looking for! You create batches by sliding over windows, and then shuffle the input in your case. The shuffle function of the dataset api has a reshuffle_after_each_iteration parameter, which you might probably want to set to False if you want to experiment with setting a random seed and looking at the order of shuffled outputs.
has comment: http://stackoverflow.com/comment/92130696
type: Answer
accepted answer of: http://stackoverflow.com/q/52431372
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/92102357

http://stackoverflow.com/comment/92043552
type: AnswerComment
comment on: http://stackoverflow.com/a/52519810
score: 0
type: Comment
has text: I have checked and just the get_ip function takes also 1 minute, so maybe your proposed method is better but still not noticeable cause the main problem is the get_ip.

http://stackoverflow.com/comment/91991628
type: QuestionComment
comment on: http://stackoverflow.com/q/52525693
has text: You can specify your delimiter if it is something else apart from a comma. E.g., for tab separated files, you can add `sep='\t'`
score: 0
type: Comment

http://stackoverflow.com/comment/108735301
type: AnswerComment
has text: @BjornW I'm not really sure what you mean with "compact hex representation". If you don't want a slug field, you should probably use something else than a slug field.
comment on: http://stackoverflow.com/a/52507825
type: Comment
score: 0

http://stackoverflow.com/q/52474403
downvote count: 0
has body: I am working on a banking related use case where I need to forecast savings account balances of customers. I have both time dependent data of last 12 months as well as static data. Time dependent data like savings account balances, term deposit balances, mutual fund balances, credit txns done, debit txns done, etc. on a monthly basis. Static data includes age, gender, region, occupation, marital status, etc. I am trying to forecast next 3 months savings account balances using LSTM but getting poor rmse. Please find below the LSTM architecture I am currently using along with the python code:Network Architecture # Model Development main_input = Input(shape=(X_train_dynamic.shape[1], X_train_dynamic.shape[2])) encoded1 = LSTM(10,return_sequences=True,activation='tanh')(main_input) encoded = LSTM(10,activation='tanh')(encoded1) auxiliary_input = Input(shape=(X_train_static.shape[1],)) output_auxiliary = Dense(10, activation='tanh')(auxiliary_input) x = concatenate([encoded, output_auxiliary]) decoded = RepeatVector(y_train.shape[1])(x) #decoded = RepeatVector(y_train.shape[1])(encoded) main_output = LSTM(1, return_sequences=True,activation='tanh')(decoded) # return_sequences=True gives Many to Many relationship model = Model(inputs=[main_input,auxiliary_input], outputs=[main_output]) #model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output]) model.compile(optimizer='adam', loss='mean_squared_error') history = model.fit([X_train_dynamic, X_train_static], [y_train], validation_data=([X_test_dynamic, X_test_static], y_test), epochs=50, batch_size=128) I am not getting good results for this architecture and open to try out new things if there are reasonable chances of success following that. I am unable to share the exact dataset but happy to provide anything else that might help.
accepted answer: http://stackoverflow.com/a/57581931
type: Question
has answer: http://stackoverflow.com/a/57581931
tagged with: lstm
upvote count: 2
answer count: 1
favorite count: 0
has title: Keras Time Series: Suggestion for including static and dynamic variables in LSTM
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52525536
tagged with: python
answer count: 0
upvote count: 3
type: UnansweredQuestion
has body: Good day, I have applied lightGBM algorithm to real estate price data set (85524 observations and 167 features). I want to receive the interaction between year and real estate area size to price. The dependent variable is transformed with log1p to get normal distribution. I have used Python, pdpbox module to generate an interaction plot. As I understand the coloring is the average price between the variables, however, I would like to receive the interval of the interaction i.e. min and max. Is it possible to do so? LGBMR.fit(df_train.drop(["Price"], axis = 1, inplace = False), df_train["Price"]) feats = ['Year', 'Real estate area'] p = pdp.pdp_interact(LGBMR, df, model_features = columns, features = feats) pdp.pdp_interact_plot(p, feats, plot_type = 'grid') I am adding the pdp interaction plot. For example, in 2008 year, the real estate object of size 0.52 was purchased for an average price of 5.697 (prediction), but I would like to know the min and max predicted price of this interaction.
type: Question
score: 3
downvote count: 0
favorite count: 0
tagged with: lightgbm
has title: Partial dependence plots with min/max (interval) and not only average in Python
tagged with: partial

http://stackoverflow.com/comment/92045747
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52553538
has text: Ok I will try it out and let you know.
type: AnswerComment

http://stackoverflow.com/comment/91986467
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52523211
type: QuestionComment
has text: Thank you, the question has been updated.

http://stackoverflow.com/comment/109683903
type: AnswerComment
score: 1
type: Comment
has text: What is I am using windows authentication instead of a username and password?
comment on: http://stackoverflow.com/a/52451469

http://stackoverflow.com/comment/91980785
has text: Thank you very much for your time and effort! I'm going to use this for this script and remember it for future projects!
comment on: http://stackoverflow.com/a/52520051
type: AnswerComment
type: Comment
score: 1

mask
tags question: http://stackoverflow.com/q/52471456
tags question: http://stackoverflow.com/q/52501817
type: Tag
tag name: mask
tags question: http://stackoverflow.com/q/52461803
tags question: http://stackoverflow.com/q/52520480

http://stackoverflow.com/comment/92047198
type: AnswerComment
comment on: http://stackoverflow.com/a/52553784
type: Comment
has text: Almost it, `uniq` give a output without duplicate but i want to remove the duplicate (both strings) to keep only string without duplicate domain name in their strings as `Insertion domainname4.com 206.188.200.6 - Insertion domainname5.com 206.188.200.7` in fact i would like to change my `change` first list into `Insertion domainname4.com 206.188.200.6 - Insertion domainname5.com 206.188.200.7`
score: 0

http://stackoverflow.com/comment/91978382
type: AnswerComment
score: 0
type: Comment
has text: html: `all your text ` and python, 2 lines: `@app.route('/books/ -<heading>' )` and `def bookPage(title, heading):`
comment on: http://stackoverflow.com/a/52505660

http://stackoverflow.com/comment/92024652
has text: *If I have python script which activates the virtualenv like this:*: that just selects the Python binary, the venv is not 'activated'. Activating a venv is mostly just an update to your PATH variable by the `bin/activate` shell script, but that's not a requirement to use the Python binary.
type: Comment
comment on: http://stackoverflow.com/q/52449602
type: QuestionComment
score: 0

http://stackoverflow.com/q/52480002
score: -1
has answer: http://stackoverflow.com/a/52483543
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91907915
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91901159
upvote count: 0
has title: Python Index error in a while loop for a simple weather information operation
type: Question
has comment: http://stackoverflow.com/comment/91904465
has comment: http://stackoverflow.com/comment/91903907
has comment: http://stackoverflow.com/comment/91901216
tagged with: index-error
has comment: http://stackoverflow.com/comment/91901402
has body: Can anyone spot anything obvious with the below index error i'm getting? I've created a simple operation which takes data from a .txt file and prints the information in a specific format. It's not complex but i'm getting an index error and i'm not sure why as the index exists; city_info = open("mean_temp.txt", "a+") city_info.write("Rio de Janeiro,Brazil,30.0,18.0\n") city_info.seek(0,0) headings = city_info.readline().split(",") print("heading index 0:", headings[0],"\n","heading index 1:", headings[1],"\n","heading index 2:", headings[2],"\n","heading index 3:", headings[3]) while city_info: city_temp = city_info.readline().split(",") print(headings[0], "of", city_temp[0], "is", city_temp[2], "Celcius") city_info.close() My index values are as below; heading index 0: city heading index 1: country heading index 2: month ave: highest high heading index 3: month ave: lowest low This is my current output (which looks correct (ignore the numbers) but i just need to get rid of the index error. city of Beijing is 30.9 Celcius city of Cairo is 34.7 Celcius city of London is 23.5 Celcius city of Nairobi is 26.3 Celcius city of New York City is 28.9 Celcius city of Sydney is 26.5 Celcius city of Tokyo is 30.8 Celcius city of Rio de Janeiro is 30.0 Celcius This is my error: IndexError Traceback (most recent call last) &lt;ipython-input-5-fb9cc0942cef&gt; in &lt;module&gt;() 20 while city_info: 21 city_temp = city_info.readline().split(",") ---&gt; 22 print(headings[0], "of", city_temp[0], "is", city_temp[2], "Celcius") 23 24 IndexError: list index out of range If i run the URL for the location the .txt file is stored in i get and i can't find any blank lines: &lt;p&gt; city,country,month ave: highest high,month ave: lowest low &lt;p&gt;Beijing,China,30.9,-8.4 &lt;p&gt;Cairo,Egypt,34.7,1.2 &lt;p&gt;London,UK,23.5,2.1 &lt;p&gt;Nairobi,Kenya,26.3,10.5 &lt;p&gt;New York City,USA,28.9,-2.8 &lt;p&gt;Sydney,Australia,26.5,8.7 &lt;p&gt;Tokyo,Japan,30.8,0.9 &lt;p&gt; &lt;p&gt;

http://stackoverflow.com/q/52555726
tagged with: python
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/52731448
has title: VSCode shows different Pylint errors in editor mouseover versus problems pane
type: Question
score: 3
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/52731448
downvote count: 0
answer count: 1
favorite count: 0
has body: As a newish user of VSCode (ver. 1.27.2) I am trying to run Pylint (v. 2.1.1 on Python 3.6) with many of the extra checkers enabled like the design checker but even though the errors show up on the mouseovers in the editor window, they are not listed in the problems pane. In the image below you can see at least 3 in the mouseover yet only 2 in the problems pane. (There is actually a total of 5 in the editor while still only 2 in the problems pane.) I have "python.linting.pylintUseMinimalCheckers": false, in my user settings and also I am sending the extra checkers in my user settings "python.linting.pylintArgs": ["--load-plugins", "pylint.extensions.mccabe"], but there seems to be some setting that I am missing that I assume would correctly display the same errors seen in the mouseovers in the editor. Can anyone help? The ones missing seem to be the 'R' type pylint errors - the refactor types.
tagged with: pylint

http://stackoverflow.com/comment/91893329
type: Comment
has text: Can you check if I did this wrong pelase: `c = '{MyText}' c = '{}_{}'.format(b, a) print(c)` the Program don't evan start when I do this
comment on: http://stackoverflow.com/a/52475588
type: AnswerComment
score: 0

python-collections
type: Tag
tag name: python-collections
tags question: http://stackoverflow.com/q/52459624

scikit-learn
tags question: http://stackoverflow.com/q/52436903
tags question: http://stackoverflow.com/q/52437481
tags question: http://stackoverflow.com/q/52554712
tags question: http://stackoverflow.com/q/52489521
tags question: http://stackoverflow.com/q/52440529
tags question: http://stackoverflow.com/q/52555841
tags question: http://stackoverflow.com/q/52477891
tags question: http://stackoverflow.com/q/52585975
tags question: http://stackoverflow.com/q/52587574
tags question: http://stackoverflow.com/q/52448144
tags question: http://stackoverflow.com/q/52579293
tags question: http://stackoverflow.com/q/52458426
tags question: http://stackoverflow.com/q/52461893
tags question: http://stackoverflow.com/q/52457705
tags question: http://stackoverflow.com/q/52447815
tags question: http://stackoverflow.com/q/52433738
tags question: http://stackoverflow.com/q/52486446
tags question: http://stackoverflow.com/q/52471649
tags question: http://stackoverflow.com/q/52434327
tags question: http://stackoverflow.com/q/52479544
tags question: http://stackoverflow.com/q/52472611
tags question: http://stackoverflow.com/q/52577305
tags question: http://stackoverflow.com/q/52504263
tags question: http://stackoverflow.com/q/52499788
tags question: http://stackoverflow.com/q/52461039
tags question: http://stackoverflow.com/q/52567225
tags question: http://stackoverflow.com/q/52496230
tags question: http://stackoverflow.com/q/52587973
tags question: http://stackoverflow.com/q/52513495
tags question: http://stackoverflow.com/q/52574040
tags question: http://stackoverflow.com/q/52430798
tags question: http://stackoverflow.com/q/52431823
tags question: http://stackoverflow.com/q/52499536
tags question: http://stackoverflow.com/q/52561024
tags question: http://stackoverflow.com/q/52567035
tags question: http://stackoverflow.com/q/52540204
tags question: http://stackoverflow.com/q/52500971
tags question: http://stackoverflow.com/q/52457024
tags question: http://stackoverflow.com/q/52505606
tags question: http://stackoverflow.com/q/52567129
tags question: http://stackoverflow.com/q/52541717
tags question: http://stackoverflow.com/q/52507815
tags question: http://stackoverflow.com/q/52517002
tag name: scikit-learn
tags question: http://stackoverflow.com/q/52521475
tags question: http://stackoverflow.com/q/52548689
tags question: http://stackoverflow.com/q/52586577
tags question: http://stackoverflow.com/q/52573507
type: Tag
tags question: http://stackoverflow.com/q/52560683
tags question: http://stackoverflow.com/q/52484410
tags question: http://stackoverflow.com/q/52573224
tags question: http://stackoverflow.com/q/52547379
tags question: http://stackoverflow.com/q/52442229
tags question: http://stackoverflow.com/q/52446826
tags question: http://stackoverflow.com/q/52464543
tags question: http://stackoverflow.com/q/52546600
tags question: http://stackoverflow.com/q/52580023
tags question: http://stackoverflow.com/q/52448156
tags question: http://stackoverflow.com/q/52498544
tags question: http://stackoverflow.com/q/52587280
tags question: http://stackoverflow.com/q/52545600
tags question: http://stackoverflow.com/q/52489775
tags question: http://stackoverflow.com/q/52535359
tags question: http://stackoverflow.com/q/52582796
tags question: http://stackoverflow.com/q/52434568
tags question: http://stackoverflow.com/q/52483935
tags question: http://stackoverflow.com/q/52498640
tags question: http://stackoverflow.com/q/52546651
tags question: http://stackoverflow.com/q/52489032
tags question: http://stackoverflow.com/q/52586531
tags question: http://stackoverflow.com/q/52551444
tags question: http://stackoverflow.com/q/52554853
tags question: http://stackoverflow.com/q/52514977
tags question: http://stackoverflow.com/q/52441090
tags question: http://stackoverflow.com/q/52449331
tags question: http://stackoverflow.com/q/52558526

http://stackoverflow.com/q/52557099
has title: Numpy commands not working as they did 3 weeks ago
score: 0
has comment: http://stackoverflow.com/comment/92052906
tagged with: spyder
has comment: http://stackoverflow.com/comment/92053129
type: UnansweredQuestion
tagged with: python
tagged with: anaconda
has comment: http://stackoverflow.com/comment/92057235
answer count: 0
has comment: http://stackoverflow.com/comment/92054557
has comment: http://stackoverflow.com/comment/92053723
type: Question
tagged with: numpy
has body: I need some help/advice. First off, I am using Python 2.7.14 and I use it through the Spyder 3.2.6 interface. I have never utilized python 3. I have a 64 bit Windows 10 OS and have extremely limited ability to update things due to workplace network restrictions. So nothing should have been updated automatically except windows-based things. I use a script to generate plots from data on my computer. It was working perfectly 3 weeks ago when I used it last. Here is a portion of it: import numpy as np def map_track(): A1=loadtxt("C:\data\island.shape", usecols=(0,1)) Resulting in the error: Traceback (most recent call last): File "&lt;ipython-input-2-af497edda909&gt;", line 1, in &lt;module&gt; A1=loadtxt("C:\data\island.shape", usecols=(0,1)) NameError: name 'loadtxt' is not defined I have found that using np.loadtxt will eliminate the error, but I have a lot of different python code that utilize numpy commands and it would be tedious to have to manually add 'np.' at the beginning of each instance. I use many more commands from numpy including percentile and isnan, which both generated the same error that is "fixed" by adding np. before them. I am not overly experienced in checking, installing, uninstalling, etc. packages and I am at a loss as to what I am supposed to look for in attempting to fix this. Thanks for any help you can provide!
has comment: http://stackoverflow.com/comment/92052881

http://stackoverflow.com/a/52467980
downvote count: 0
type: Answer
has body: It's because np.zeros by default assigns it's values to float. To change that replace line: mat=np.zeros((n,n)) with: mat=np.zeros((n,n), dtype=int) It will give you output you want. Also good practice is to use help() on used methods, to know what can be done with them, like in this example.
score: 5
answers question: http://stackoverflow.com/q/52467934
upvote count: 5

http://stackoverflow.com/comment/91922951
comment on: http://stackoverflow.com/a/52481403
type: AnswerComment
has text: I edited my answer to show a complete top-to-bottom solution, so you can see exactly how the sprite loop relates to the main loop, and also demonstrated how to use `win.getMouse()`. (I also had a mistake where I used `this` in place of `self`, which I fixed.)
score: 0
type: Comment

http://stackoverflow.com/q/52475833
has comment: http://stackoverflow.com/comment/91897523
has comment: http://stackoverflow.com/comment/91896125
score: 0
has comment: http://stackoverflow.com/comment/91896427
has title: Will install_requires in setuptools work without explicit yocto-recipe for certain packages
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91897488
tagged with: python
has comment: http://stackoverflow.com/comment/91901784
answer count: 0
tagged with: python-packaging
tagged with: yocto
type: Question
has body: I have a python3 application and want to create a yocto-recipe for the same. The application depends mainly on: pyserial influxdb-python pynmea2 pynmea2 and influxdb-python are not available in the meta-python layer. I have a setup.py which has the flag install_requires install_requires = ['pynmea2', 'pyserial', 'influxdb-python'] I have found a repository which provides a basic example for creating python based yocto-recipes but it does not mention any dependencies. Will there be any problem by mentioning install_requires and not having those dependencies as recipes? P.S. My Repo

http://stackoverflow.com/comment/91990898
score: 0
type: Comment
type: QuestionComment
has text: `pd.DataFrame({'vector1': vector_data[0], 'vector2': vector_data[1]})`
comment on: http://stackoverflow.com/q/52525361

teradata
type: Tag
tag name: teradata
tags question: http://stackoverflow.com/q/52486414

http://stackoverflow.com/q/52586790
upvote count: 2
has answer: http://stackoverflow.com/a/52587308
has title: create shortcut with Run As Administrator
type: AnsweredQuestion
tagged with: powershell
type: Question
answer count: 2
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/52587308
possible better answer: http://stackoverflow.com/a/52588516
favorite count: 0
has answer: http://stackoverflow.com/a/52588516
tagged with: byte
tagged with: shortcut
has body: im trying to create a shortcut that needs administrator privileges ... i found this code on the internet but its coded in powershell ... i test it its working !! but i need it in python how i can do the same with python powershell code : Read the .lnk file in as an array of bytes. Locate byte 21 (0x15) and change bit 6 (0x20) to 1. This is the RunAsAdministrator flag. Then you write you byte array back into the .lnk file. $WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk") $Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe" $Shortcut.Save() $bytes = [System.IO.File]::ReadAllBytes("$Home\Desktop\ColorPix.lnk") $bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON [System.IO.File]::WriteAllBytes("$Home\Desktop\ColorPix.lnk", $bytes) this is my python code : filename = r'C:\Users\root\Desktop\qassam.lnk' with open(filename, "rb") as f2: while True: current_byte = f2.read(1) if (not current_byte): break val = ord(current_byte) q = hex(val) print q i dont know what is the next step can u help me ?
tagged with: python
score: 2

http://stackoverflow.com/q/52455356
has comment: http://stackoverflow.com/comment/91853178
favorite count: 0
upvote count: 5
tagged with: python
has title: How can I make ring from Gaussian distribution
has answer: http://stackoverflow.com/a/52455979
accepted answer: http://stackoverflow.com/a/52455979
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/62231391
tagged with: normal-distribution
has body: I saw the formula for making a ring from Gaussian on https://arxiv.org/pdf/1606.05908.pdf but it did not work, and I found another formula which makes sphere(ring) from normal distribution it is maked by using GCN. I used this algorithm to make a ring from a normal distribution but it also did not work. please help me
possible better answer: http://stackoverflow.com/a/62231391
score: 4
tagged with: normalization
answer count: 3
has answer: http://stackoverflow.com/a/78956314
downvote count: 1

http://stackoverflow.com/a/52447253
answers question: http://stackoverflow.com/q/52436762
type: Answer
upvote count: 4
downvote count: 0
type: AcceptedAnswer
score: 4
has body: You get to choose how you tag your texts. The Doc2Vec model only learns doc-vectors for the exact tags you provide. In the original Paragraph Vectors paper upon which Doc2Vec is based (and many published examples since), every document gets its own unique ID tag, so there's a unique doc-vector per document. You get the doc-vector for a document by querying the model for that document's unique tag. Using categorical labels, like 'positive' and 'negative' that may repeat across many examples, is possible and sometimes effective – but different from the original conception. If all your N texts only have among them 2 unique tags (repeating across texts), then at the end of training only 2 doc-vectors will be learned. (It's also possible to give texts multiple tags – so they could have both a unique ID and some other label(s). For example: tags=['id001', 'positive']. However, that's best considered an advanced/experimental technique that I would only recommend after you've had simpler approaches work well, and understand from those simpler approaches how various qualities of your setup – like parameters, corpus size &amp; quality, etc – affect results. In particular, trying to train more uniquely-tagged doc-vectors from the same amount of data can in practice mean each doc-vector is a bit 'weaker' in its usefulness. In essence, the same source info and "signal" in the data is spread out over more learned vectors. So you'd only want to do fancy things like have multiple tags per doc if you have a lot of data – and possibly even do more training passes.) Other notes about your setup: The update=True function of build_vocab() is only officially supported for Word2Vec, is an advanced feature that requires a lot of experimentation to use right, and even there should only be used the 2nd or subsequent times you build_vocab() on a model, not the 1st. Toy-sized datasets generally won't give useful or intuitive results in Word2Vec/Doc2Vec – at best they can be used to understand …
accepted answer of: http://stackoverflow.com/q/52436762

http://stackoverflow.com/comment/92057820
type: Comment
type: QuestionComment
has text: This is the sort of detail that should be put in the question via an [edit].
score: 0
comment on: http://stackoverflow.com/q/52558018

http://stackoverflow.com/comment/91904639
type: Comment
comment on: http://stackoverflow.com/a/52481623
has text: Instead of just stating, maybe it would be better to write how to get the initial number using argmin
score: 0
type: AnswerComment

http://stackoverflow.com/q/52487390
tagged with: python-decorators
favorite count: 0
has comment: http://stackoverflow.com/comment/91920176
tagged with: python
has body: Let's say I have my unittest set up like this: import unittest class BaseTest(object): def setup(self): self.foo = None def test_something(self): self.assertTrue(self.foo.something()) def test_another(self): self.assertTrue(self.foo.another()) def test_a_third_thing(self): self.assertTrue(self.foo.a_third_thing()) class TestA(BaseTest, unittest.TestCase): def setup(self): self.foo = FooA() class TestB(BaseTest, unittest.TestCase): def setup(self): self.foo = FooB() class TestC(BaseTest, unittest.TestCase): def setup(self): self.foo = FooC() Now let's say FooC doesn't have a_third_thing implemented yet, and I want to skip test_a_third_thing for ONLY the TestC class. Is there some way I can use the @unittest.skipif decorator to do this? Or some other handy way to skip this test for only this class? Python 2.7, in case it matters
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: python-unittest
possible better answer: http://stackoverflow.com/a/52487893
has comment: http://stackoverflow.com/comment/91916652
accepted answer: http://stackoverflow.com/a/52543385
type: Question
upvote count: 2
answer count: 2
linked to: http://stackoverflow.com/q/1323455
has answer: http://stackoverflow.com/a/52543385
has comment: http://stackoverflow.com/comment/92026634
has title: Python unittest skip test for only one subclass
has comment: http://stackoverflow.com/comment/92026292
has answer: http://stackoverflow.com/a/52487893

http://stackoverflow.com/comment/91952095
has text: Please read through https://packaging.python.org/ and associated articles linked therein.
score: 0
comment on: http://stackoverflow.com/q/52505649
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52499285
has comment: http://stackoverflow.com/comment/91979072
type: Answer
has comment: http://stackoverflow.com/comment/91961058
has body: Twisted 15 and Twisted 17.9 have different behavior with respect to automatically including $PWD in sys.path. Twisted 15 does and Twisted 17.9 does not. Add the path containing your project to PYTHONPATH (perhaps by creating a virtualenv and using pip to do an editable install of your project into it) and Twisted 17.9 will find the code and therefore also your plugin.
accepted answer of: http://stackoverflow.com/q/52498339
score: 0
answers question: http://stackoverflow.com/q/52498339
type: AcceptedAnswer

http://stackoverflow.com/q/52472757
downvote count: 0
has answer: http://stackoverflow.com/a/57650324
possible better answer: http://stackoverflow.com/a/64541025
favorite count: 0
score: 8
upvote count: 8
tagged with: seaborn
tagged with: data-visualization
tagged with: boxplot
has body: I'm trying to create a 4x4 FacetGrid in seaborn for 4 boxplots, each of which is split into 3 boxplots based on the iris species in the iris dataset. Currently, my code looks like this: sns.set(style="whitegrid") iris_vis = sns.load_dataset("iris") fig, axes = plt.subplots(2, 2) ax = sns.boxplot(x="Species", y="SepalLengthCm", data=iris, orient='v', ax=axes[0]) ax = sns.boxplot(x="Species", y="SepalWidthCm", data=iris, orient='v', ax=axes[1]) ax = sns.boxplot(x="Species", y="PetalLengthCm", data=iris, orient='v', ax=axes[2]) ax = sns.boxplot(x="Species", y="PetalWidthCm", data=iris, orient='v', ax=axes[3]) However, I'm getting this error from my interpreter: AttributeError: 'numpy.ndarray' object has no attribute 'boxplot' I'm confused on where the attribute error is exactly in here. What do I need to change?
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64541025
type: Question
has answer: http://stackoverflow.com/a/52482277
has answer: http://stackoverflow.com/a/52473553
tagged with: data-science
accepted answer: http://stackoverflow.com/a/52473553
has title: Creating a boxplot FacetGrid in Seaborn for python

http://stackoverflow.com/comment/92043644
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52552178
has text: The code works fine? What is the problem you're facing?
score: 0

class
tags question: http://stackoverflow.com/q/52490621
tags question: http://stackoverflow.com/q/52480773
tags question: http://stackoverflow.com/q/52577249
tags question: http://stackoverflow.com/q/52501512
tags question: http://stackoverflow.com/q/52527912
tags question: http://stackoverflow.com/q/52574772
tags question: http://stackoverflow.com/q/52579725
tags question: http://stackoverflow.com/q/52510681
tags question: http://stackoverflow.com/q/52472635
tags question: http://stackoverflow.com/q/52518578
tags question: http://stackoverflow.com/q/52478741
tags question: http://stackoverflow.com/q/52520274
tags question: http://stackoverflow.com/q/52528985
tags question: http://stackoverflow.com/q/52430537
tags question: http://stackoverflow.com/q/52466815
type: Tag
tags question: http://stackoverflow.com/q/52513124
tags question: http://stackoverflow.com/q/52522346
tags question: http://stackoverflow.com/q/52505696
tags question: http://stackoverflow.com/q/52581710
tags question: http://stackoverflow.com/q/52537561
tags question: http://stackoverflow.com/q/52565507
tag name: class
tags question: http://stackoverflow.com/q/52572956
tags question: http://stackoverflow.com/q/52523102
tags question: http://stackoverflow.com/q/52465658
tags question: http://stackoverflow.com/q/52432210
tags question: http://stackoverflow.com/q/52571832
tags question: http://stackoverflow.com/q/52465131
tags question: http://stackoverflow.com/q/52551309
tags question: http://stackoverflow.com/q/52499774
tags question: http://stackoverflow.com/q/52556414
tags question: http://stackoverflow.com/q/52463142
tags question: http://stackoverflow.com/q/52564911
tags question: http://stackoverflow.com/q/52500506

sql
tags question: http://stackoverflow.com/q/52431208
tags question: http://stackoverflow.com/q/52481282
tags question: http://stackoverflow.com/q/52574987
tags question: http://stackoverflow.com/q/52546519
tags question: http://stackoverflow.com/q/52482349
tags question: http://stackoverflow.com/q/52448660
tags question: http://stackoverflow.com/q/52563047
tags question: http://stackoverflow.com/q/52481093
tags question: http://stackoverflow.com/q/52459844
tags question: http://stackoverflow.com/q/52480036
tag name: sql
tags question: http://stackoverflow.com/q/52571398
type: Tag
tags question: http://stackoverflow.com/q/52445132
tags question: http://stackoverflow.com/q/52504626
tags question: http://stackoverflow.com/q/52458641
tags question: http://stackoverflow.com/q/52494572
tags question: http://stackoverflow.com/q/52432675
tags question: http://stackoverflow.com/q/52484978
tags question: http://stackoverflow.com/q/52528615
tags question: http://stackoverflow.com/q/52505165
tags question: http://stackoverflow.com/q/52449246
tags question: http://stackoverflow.com/q/52443444
tags question: http://stackoverflow.com/q/52561004
tags question: http://stackoverflow.com/q/52430137

http://stackoverflow.com/comment/91903322
type: Comment
comment on: http://stackoverflow.com/a/52478814
score: 0
type: AnswerComment
has text: Hey good news I just realized from `DISLIKE` to `LIKE` is Asynchronous However from `LIKE` to `DISLIKE` Its a Page refresh. Trying to resolve that. Do you think you know why that could be happening. If we figure that. This question is answered

http://stackoverflow.com/a/52446827
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52446748
answers question: http://stackoverflow.com/q/52446748
has comment: http://stackoverflow.com/comment/91843488
type: Answer
has comment: http://stackoverflow.com/comment/91843533
has body: You should using to_dict df.groupby(by =['a', 'b']).v.apply(list).unstack().to_dict('index') Out[1042]: {1: {0: [2], 1: [4, 3]}, 2: {0: [7], 1: [6]}, 3: {0: [5, 9], 1: [3, 2]}, 4: {0: [5], 1: [4]}, 5: {0: [3], 1: [2]}}
has comment: http://stackoverflow.com/comment/91836954
has comment: http://stackoverflow.com/comment/91837032
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/92024253
type: Comment
comment on: http://stackoverflow.com/q/52541850
has text: Not always, there are plenty of examples where a tabbed loop is superior to list comprehension. IMHO
score: 0
type: QuestionComment

http://stackoverflow.com/q/52551595
score: 0
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/92042264
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/23013220
has title: Can't get virtualenv working due to SSL error
tagged with: ssl
has comment: http://stackoverflow.com/comment/92043361
linked to: http://stackoverflow.com/q/49324802
has answer: http://stackoverflow.com/a/52554368
answer count: 1
has comment: http://stackoverflow.com/comment/92045719
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/92045893
has body: I'm trying to use virtualenv on my Mac (El Capitan) but something must have changed recently, as it's no longer working, and complains about SSL problems. It's the first time I've had to use this project in about 9 months, and in that time, I've not changed anything on my system regarding Python. In an effort to get it working, over the past day or so I've uninstalled virtualenv, manually deleted some files (I found these instructions in a GitHub issue, but I can't find them again to provide a link, but if I remember correctly, it was just deleting broken symlinks and directories relating to virtualenv,) and then uninstalled Python via Brew, leaving me with a system that had no Python, pip, or virtualenv libraries or executables on it. Then I ran brew install python2 to get Python installed. Then I ran pip install virtualenv which gave me the same SSL error as before. I manually downloaded virtualenv from the URL pip was trying to download it from, and then pip installed it locally using the downloaded file. This worked. However, when I then run virtualenv venv, I still get the same SSL error. I've seen issues offering all kinds of advice, from downloading DigiCertHighAssuranceEVRootCA.pem and using it via the --cert option, creating a pip.ini file with trusted-host=files.pythonhosted.org in it, using the --trusted-host option, using a different network that isn't my company's corporate network, but none of it so far has worked for me. I am consistently getting the following SSL error whenever I try to pip install anything, or, in this specific example, create a new virtualenv: New python executable in /Users/apl/Projects/fdm/FDM-fordele/venv/bin/python2.7 Also creating executable in /Users/apl/Projects/fdm/FDM-fordele/venv/bin/python Installing setuptools, pip, wheel... Complete output from command /Users/apl/Projects/...e/venv/bin/python2.7 - setuptools pip wheel: Looking in links: /usr/local/lib/python2.7/site-packages, /usr/local/lib/python2.7/site-packages/virt…
tagged with: python
accepted answer: http://stackoverflow.com/a/52554368
has comment: http://stackoverflow.com/comment/92042995

http://stackoverflow.com/q/52539276
score: 0
upvote count: 1
downvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92018188
answer count: 0
has comment: http://stackoverflow.com/comment/92020179
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/40444787
has title: keeps adding spaces when saving to a file even with .strip, .replace and everything possible to get rid of them
tagged with: python
has comment: http://stackoverflow.com/comment/92018896
has body: Doesn't matter if the spaces are in the file i just cant have them show. bigscore = str(bigscore) leaderboard = [] highscore = open("highscore.txt", mode = "r+") for each in highscore: leaderboard.append(each.strip()) leaderboard.append(winner) leaderboard.append(bigscore) scores = [] for each in range(1, 12): if each % 2 != 0: x = int(leaderboard[each]) scores.append(x) scores.sort() newleaderboard = [] loser = str(scores[0]).strip() losernum = leaderboard.index(loser) leaderboard.pop(losernum) leaderboard.pop(losernum - 1) scores.pop(0) for each in scores: each = str(each).strip() sort = leaderboard.index(each) newleaderboard.insert(0, leaderboard[sort].strip()) newleaderboard.insert(0, leaderboard[sort - 1].strip()) open("highscore.txt", mode = "w") for each in (newleaderboard): highscore.write(each.replace(" ", "")) highscore.write("\n") print("Here is the new leaderBoard") for each in newleaderboard: each.rstrip() each.strip() each.lstrip() each.replace("\x00","") each.replace(" ","") print(each.strip()) my code sorts the name and score of players in an external file. It keeps the name together with the person that gets it and saves to an external file. However, it adds spaces when i write to the file. But i do not want to change the way i did it (eg. using a dictionary instead) It is meant to be my work but i need help on the spaces and the spaces only. I cant fix it and my teacher cant. Disclaimer-this is for the new NEA, help from forums online are now allowed, and all credit will be given when i submit it, this was a last resort.

http://stackoverflow.com/comment/91844355
comment on: http://stackoverflow.com/q/52433414
score: 0
type: QuestionComment
has text: Yeah I just checked and it is Django version 2.1.1 and the API is the root directory folder contains the LoginAPI which contains the other two directories.
type: Comment

http://stackoverflow.com/q/52488701
has title: How to make a Bokeh scatter plot interactive (with slider)
tagged with: bokeh
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52489545
tagged with: slider
answer count: 1
favorite count: 0
has body: I'm trying to make a scatter plot in Bokeh based on the simple example code posted here. The following code produces a working demo for a line plot: from bokeh.layouts import column from bokeh.models import CustomJS, ColumnDataSource, Slider from bokeh.plotting import Figure, show # fetch and clear the document from bokeh.io import curdoc curdoc().clear() x = [x*0.005 for x in range(0, 100)] y = x source = ColumnDataSource(data=dict(x=x, y=y)) plot = Figure(plot_width=400, plot_height=400) plot.line(x='x', y='y', source=source) def callback(source=source, window=None): data = source.data f = cb_obj.value x, y = data['x'], data['y'] for i in range(len(x)): y[i] = window.Math.pow(x[i], f) source.trigger('change') slider = Slider(start=0.1, end=4, value=1, step=.1, title="Start week", callback=CustomJS.from_py_func(callback)) layout = column(slider, plot) show(layout) It looks like this: In this demo, when you adjust the slider and press the 'reset' icon, the plot re-draws itself based on the updated formula for y=f(x). However, I want to make a scatter plot that changes, not a line plot. Problem: When I simply change plot.line in above code to plot.circle, the plot renders okay but it is static - it does not change when you shift the slider and press 'reset'. No error messages that I can see.
has answer: http://stackoverflow.com/a/52489545
upvote count: 2
tagged with: python
tagged with: plot
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/52524761
has comment: http://stackoverflow.com/comment/91989743
accepted answer: http://stackoverflow.com/a/52525177
has comment: http://stackoverflow.com/comment/91989897
has comment: http://stackoverflow.com/comment/91989918
tagged with: python
tagged with: indexing
type: AnsweredQuestion
score: 3
has body: I have a 2D numpy array A with dimensions NxM I have two arrays start and end with dimensions Nx1 For each row k given by A[k,:] I want to set the columns from start[k] to end[k] to 0: A[:,start:end]=0 However, I get the error TypeError: only integer scalar arrays can be converted to a scalar index If I just index A[:,start]=0 it works. But this is not what I want to achieve. The length of start[k]:end[k] differs for each k
has answer: http://stackoverflow.com/a/52525177
has comment: http://stackoverflow.com/comment/91989892
upvote count: 3
has answer: http://stackoverflow.com/a/52524935
has comment: http://stackoverflow.com/comment/91989847
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91989690
downvote count: 0
has title: Index numpy array with two arrays given start and end for each column
answer count: 2
possible better answer: http://stackoverflow.com/a/52524935
has comment: http://stackoverflow.com/comment/91989274
favorite count: 0

http://stackoverflow.com/comment/91806665
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52430649
type: QuestionComment
has text: I have a clue, can you check once if this solves 'reader = csv.reader(uploaded_file.seek(0))' solves the issue?

http://stackoverflow.com/a/52536755
answers question: http://stackoverflow.com/q/52476244
has body: I've read your other, similar question and come up with a solution without any pre-imports. This is (imho) highly un-pythonic, and may by all means be considered a dirty "hack". I highly recommend you to consider my other answer and just properly deal with the imports. Your problem occurs because you're trashing the namespace, and all it holds dear. When you pollute the namespace with functions/methods with the same signature, there is absolutely no way for the Python-interpreter to distinguish them: it resolves to the one that was first imported. However, as stated, there is a workaround: There is (currently) no way to unload a python module, but you may reload it, using the imp module. Essentially, it lets you clean up (redefine) the namespace. A complete, working example can be found at my repl.it # root_folder/main.py import sys import imp from importlib import import_module def import_script(mod_dir, script): sys.path.append(mod_dir) mod = imp.reload(import_module(script, 'Script')) sys.path.remove(mod_dir) return mod # input: mod_dir = "A" script = "b" # import module/script.py active_mod = import_script(mod_dir, script) # use module/script.py mod_name = active_mod.get_mod_name() print(mod_name) # Prints "A : b.y" # New input: different module/script.py mod_dir = "C" script = "b" # import module/script.py active_mod = import_script(mod_dir, script) # use module/script.py mod_name = active_mod.get_mod_name() print(mod_name) # Prints "C : b.y" when the modules look like below, # root_folder/A/b.py def get_mod_name(): return "A : b.py" Do note that every import is doubled, since everytime you import a module (with possibly a duplicate name), it must also be reloaded to clean up the namespace. It is not enough to just del the module.
type: Answer
score: 0

http://stackoverflow.com/a/52585606
score: 5
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/92106291
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52585200
type: Answer
answers question: http://stackoverflow.com/q/52585200
has body: The cors-header missing in you docker. So add django-cors-headers in your requirement.txt of your project. add the django-cors-headers dependencies to your Dockerfile after (RUN apt-get update .....). now build and run. Using either docker-compose build docker-compose up or docker-compose up --build

http://stackoverflow.com/q/52493617
has title: Does Session.partial_run execute all fetches, not only those requested?
tagged with: python
score: 2
answer count: 0
downvote count: 0
tagged with: tensorflow
type: Question
upvote count: 2
favorite count: 0
has body: Take this example: import tensorflow as tf ph = tf.placeholder(tf.float32, shape=()) foo = tf.Print(ph, [ph], 'foo') bar = tf.Print(ph, [ph], 'bar') sess = tf.Session() h = sess.partial_run_setup([foo, bar], [ph]) # query "foo" sess.partial_run(h, foo, feed_dict={ph: 0}) # prints: # bar[0] # foo[0] Even though I am requesting only foo, it seems that both foo and bar operations are run. Am I right, then, in assuming that partial_run always compute all fetches (and all other operations in the graph needed for their computation) specified in partial_run_setup, and not only those requested in partial_run, as for plain run?
type: UnansweredQuestion

http://stackoverflow.com/a/52567579
has body: Try using raw_input instead of input. It sounds like in the online interpreter you might be running the code in Python 3, in which input behaves like Python 2's raw_input, and using Python 2 locally. In python 2, input results in your code looking for a definition for your input, rather than taking it as a string.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52567471
has comment: http://stackoverflow.com/comment/92113584
upvote count: 11
answers question: http://stackoverflow.com/q/52567471
type: Answer
score: 11
type: AcceptedAnswer

http://stackoverflow.com/comment/91863853
type: AnswerComment
comment on: http://stackoverflow.com/a/52451339
type: Comment
score: 0
has text: @miki Sorry! I posted this answer without testing my codes. Actually, you can access the output of the layers in the sequential sub-model. If you run `print(model.layers[-1])` or do `model.summary()` you would realize that the whole sequential model is encoded as the one layer of `model`. And whatever I tried, I could not construct a model where its output is the output of middle layers in sequential model. Though, If you had added the layers initially using functional API then it was possible. So my answer is wrong and I am currently investigating to find a solution. Accept my apologies!

http://stackoverflow.com/q/52532041
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52533764
has answer: http://stackoverflow.com/a/52532547
tagged with: package
has body: Directory Structure test.py Info __init.py msg1.py msg2.py msg3.py test.py import Info Info.msg1() Info.msg2() Info.msg3() init.py from msg1 import msg1 from msg2 import msg2 from msg3 import msg3 msg1.py def msg1(): print "This is msg1" msg2.py and msg3.py is also same as msg1.py me running this on windows pc with python 3.7.0 getting the below error Please help me out Thank you!
tagged with: python
possible better answer: http://stackoverflow.com/a/52532547
score: 2
type: AnsweredQuestion
has title: ModuleNotFoundError : No module named msg1 (in ubuntu with python 2.7.6 is not showing any error)
upvote count: 2
accepted answer: http://stackoverflow.com/a/52533764
type: Question
answer count: 2

http://stackoverflow.com/comment/92021365
has text: Thanks Wiktor for the solution. But I don't want to read line by line as this regex needs to work on logs. I want to apply regex in re.findall function
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52540621
type: Comment

http://stackoverflow.com/q/52523793
has body: Given the dataframe: coords x y likelihood 0 197.486369 4.545954 3.890000e-07 1 319.946460 191.035224 2.360000e-07 2 319.880388 191.012984 2.740000e-07 3 320.286005 190.843329 2.170000e-07 4 320.210989 190.863304 2.490000e-07 5 320.212529 190.867178 2.310000e-07 ... ... ... ... 10461 349.995217 303.397438 9.999956e-01 10462 349.109666 305.710711 9.665585e-01 10463 352.142571 310.081763 9.994751e-01 10464 351.916488 317.078128 1.792100e-02 10465 353.809847 320.086683 9.277161e-01 10466 349.233529 321.859424 9.466683e-03 How can I x; y values with NaN if respective index in a boolean array is True.
accepted answer: http://stackoverflow.com/a/52523874
tagged with: numpy
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/52523874
has title: Replace pandas dataframe x; y values with NaN if respective index in boolean array is True
upvote count: 1
tagged with: python
answer count: 1
tagged with: dataframe

http://stackoverflow.com/comment/91827364
comment on: http://stackoverflow.com/q/52442340
score: 0
type: Comment
type: QuestionComment
has text: By the way `len(x)` please.

http://stackoverflow.com/comment/91873569
comment on: http://stackoverflow.com/q/52465721
has text: `l = lowestData` makes `l` a number, but you had it as a list before. Use more descriptive names and you won't accidentally overwrite old variables like that.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92036547
has text: Go for the whole shabang print the expected output statement as well xD, you have evertyhing you need
comment on: http://stackoverflow.com/a/52548672
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91862471
type: AnswerComment
has text: Thanks for the suggestions @Thiago. This approach, although common, is very slow and inefficient because it hammers the database and makes many round trips over the network. Hence the approach I'm using.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52460199

http://stackoverflow.com/a/52568900
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Use timedelta instead of str The strength of Pandas lies in vectorised functionality. Here you can use timedelta to represent times numerically. If data is as in your example, i.e. seconds are always zero, you can floor by hour and add 30 minutes. Then assign this series conditionally to df['stamp']. # convert to timedelta df['stamp'] = pd.to_timedelta(df['stamp']) # create series by flooring by hour, then adding 30 minutes s = df['stamp'].dt.floor('h') + pd.Timedelta(minutes=30) # assign new series conditional on index df['stamp'] = np.where(df.index % 2, s, df['stamp']) print(df) stamp value 0 00:00:00 2 1 00:30:00 3 2 01:00:00 5
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52567912
answers question: http://stackoverflow.com/q/52567912
score: 3

http://stackoverflow.com/comment/92107532
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52583994
has text: this does not work @PL200

http://stackoverflow.com/q/52488523
has comment: http://stackoverflow.com/comment/91918452
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91956739
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92066617
has comment: http://stackoverflow.com/comment/91918969
has comment: http://stackoverflow.com/comment/91918466
has comment: http://stackoverflow.com/comment/91918763
has comment: http://stackoverflow.com/comment/91993484
has comment: http://stackoverflow.com/comment/92064713
has comment: http://stackoverflow.com/comment/91993567
answer count: 0
has comment: http://stackoverflow.com/comment/91976770
linked to: http://stackoverflow.com/q/12836385
type: Question
has comment: http://stackoverflow.com/comment/91918311
has comment: http://stackoverflow.com/comment/92341141
tagged with: python
has comment: http://stackoverflow.com/comment/91956783
tagged with: big-o
has comment: http://stackoverflow.com/comment/91956626
has body: My code takes in a string and returns a list of strings that are permutations of the input string. (No repeats) def perm(slist, c): rTup = [] for s in slist: #O(n!) for i in range(len(s) + 1): #O(n) rstr = s[:i] + c + s[i:] #O(n) rTup.append(rstr) return rTup def permWrap(s): #wrapper slist = [s] rlist = [""] for i in reversed(range(-1,len(s)-1)): #O(n) rlist = perm(rlist , s[i+1]) return list(set(rlist)) #O(n!) permWrap("abbc") I put little comments for what I believe the time complexity is at each step. However, I could be wrong. I am thinking that the time complexity is O(n! * n^3). Is that correct? In addition, how would you make this function more efficient?
score: 0
has comment: http://stackoverflow.com/comment/91956632
has comment: http://stackoverflow.com/comment/91937363
linked to: http://stackoverflow.com/q/31655120
has comment: http://stackoverflow.com/comment/92013720
has comment: http://stackoverflow.com/comment/91975643
has title: What is the time complexity of my code? (Return all permutations of a string)

http://stackoverflow.com/a/52559061
score: 0
has comment: http://stackoverflow.com/comment/92088845
has comment: http://stackoverflow.com/comment/92057464
has body: import statistics def calculate_z_scores(raw_data): z_scores = [] for elem in raw_data: z_score = (elem - (sum(raw_data) / len(raw_data))) / statistics.pstdev(raw_data) z_scores.append(z_score) return z_scores or use a list comprehension: import statistics def calculate_z_scores(raw_data): average = sum(raw_data)/len(raw_data) std = statistics.pstdev(raw_data) return [(elem - average)/std for elem in raw_data] or better still, use numpy: import numpy as np def calculate_z_scores(raw_data): data = np.array(raw_data) return list((data - np.mean(data))/np.std(data)) # Although I have a feeling you're better off leaving it as a numpy array
has comment: http://stackoverflow.com/comment/92061008
type: Answer
answers question: http://stackoverflow.com/q/52558986

http://stackoverflow.com/q/52462392
has comment: http://stackoverflow.com/comment/91867621
tagged with: python
has title: Printing the positions MATRIX of the values in a matrix
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52462963
has comment: http://stackoverflow.com/comment/91867851
type: Question
has comment: http://stackoverflow.com/comment/91867186
score: 1
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/52462963
upvote count: 1
has answer: http://stackoverflow.com/a/52463033
accepted answer: http://stackoverflow.com/a/52463033
favorite count: 0
tagged with: position
has body: I have a matrix with some values. I want to get the m,n positions of each value into a separate matrix. import numpy as np a = np.zeros((3,3)) #Creating "a" matrix with all zeros vals = [22,34,43,56,37,45] # the values that i want to add to the matrix "a" pos = [(0,1),(0,2),(1,0),(1,2),(2,0),(2,1)] # Corresponding positions of the above given values rows, cols = zip(*pos) # This code is to assign the given values in the correct position a[rows, cols] = vals print (a) output = [[(0,0) (0,1) (0,2)] [(1,0) (1,1) (1,2)] [(2,0) (2,1) (2,2)]] please help me out. I want to get the position matrix(m,n) of whatever a matrix (m,n)
tagged with: matrix

http://stackoverflow.com/a/52489831
type: Answer
has body: The way you set up your apps will be dictated by your preferences (coding style), the size of the app, and the purpose of the app. However, here are a couple considerations: Will total lines of Python code be greater than 1000 lines? A file with over a 1000 lines will be unwieldy to navigate. I know code folding, snippets, and etc help but still. If you have more than one GtkWindow, put each window's .ui and .py separately. This helps when tracking down bugs or adding features. You mentioned sqlite, and sql queries within a file are easier to master 5 years down the road if the files are somewhat purpose specific. If you put dialogs in the same ui file as the parent window, it makes it easier to use set_transient_for and similar programming. Having more than one GtkWindow in a .ui file will make drag and drop widget reordering a pain. Are parts of the app code reusable? If you find that you are duplicating features in several different files that have different purposes, make a class or function to simplify that one feature (only applicable to multi-file setup). And finally, when your folder with .ui and .py files starts becoming large (? 25 - 50 files ?) you might want a subfolder that has a group of files with similar functionality. This is not written in stone. Nemo doesn't use this a lot, others do. I actively develop my own business management software using Python + Gtk found here. I found the principles described above to work well for me. I think the reason the documentation for Gtk typically shows single file setups is because they are merely proof of concept and not best app management tutorials. App management (for me, anyway) was trial and error, and from studying other open source apps out there. Disclaimer: These suggestions are my opinion only. They are not endorsed by Python, Gtk, or Glade. You will need to evaluate these suggestions based on your use case.
has comment: http://stackoverflow.com/comment/91926353
upvote count: 3
answers question: http://stackoverflow.com/q/52485109
accepted answer of: http://stackoverflow.com/q/52485109
type: AcceptedAnswer
downvote count: 0
score: 3

http://stackoverflow.com/q/52457485
tagged with: django
tagged with: python
tagged with: css
has title: face problem to import css, js files link in django
has body: I am a newbie in Django 2.11.1 and using macbook as my platform. I have a problem to link my css, images and js to django templage,I tryies several methods whether to change the code in setting.py, or run 'python manage.py collectstatic --noinput',the result is I can the path of the css and js files are right, I can trace them in the "http://127.0.0.1:8000/become-a-host/index", but they doesn't have an impact on the visual effect of the websites, apparently they don't work, I don't know why. Here is my project structure sentiment_analysis |-zeta | |-.vscode | |-users | |-manage.py | |-venv | |-static | |-zeta | | |-_pycache_ | | |-__init__.py | | |-setting.py | | |-wsgi.py | | |-urls.py | |-advertising | | |-_pycache_ | | |-migrations | | |-__init__.py | | |-admin.py | | |-models.py | | |-tests.py | | |-urls.py | | |-views.py | | |-tests.py | | |-app.py | |-templates | | |-advertising | | | |-index.html | | |-users setting.py STATIC_URL = '/static/' STATICFILES_DIRS = ( '/Users/zachary/lecture/9900/zeta/static/', ) TEMPLATE_DIRS = ( '/advertising/templates', ) STATIC_ROOT = '/Users/zachary/lecture/9900/zeta/static_root/' url.py urlpatterns += staticfiles_urlpatterns() base.html &lt;meta charset="utf-8"&gt; {% load staticfiles %} &lt;link rel="stylesheet" href="{% static 'css/icomoon.css'%}" type='test/css'/&gt; &lt;link rel="stylesheet" href="{% static 'css/style.css'%}" type='test/css'/&gt; &lt;script src="{% static 'js/jquery.min.js' %}"&gt;&lt;/script&gt; &lt;script src="{% static 'js/jquery-migrate-3.0.1.min.js' %}"&gt;&lt;/script&gt; &lt;script src="{% static 'js/popper.min.js' %}"&gt;&lt;/script&gt;
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91870296
type: Question
has comment: http://stackoverflow.com/comment/91865249
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91861142
has answer: http://stackoverflow.com/a/52464281
favorite count: 0
has comment: http://stackoverflow.com/comment/91857409
type: UnansweredQuestion

http://stackoverflow.com/q/52584256
has body: I have trained an LSTM model for Time Series Forecasting. I have used an early stopping method with a patience of 150 epochs. I have used a dropout of 0.2, and this is the plot of train and validation loss: The early stopping method stop the training after 650 epochs, and save the best weight around epoch 460 where the validation loss was the best. My question is : Is it normal that the train loss is always above the validation loss? I know that if it was the opposite(validation loss above the train) it would have been a sign of overfitting. But what about this case? EDIT: My dataset is a Time Series with hourly temporal frequence. It is composed of 35000 instance. I have split the data into 80 % train and 20% validation but in temporal order. So for example the training will contain the data until the beginning of 2017 and the validation the data from 2017 until the end. I have created this plot by averaging the data over 15 days and this is the result: So maybe the reason is as you said that the validation data have an easier pattern. How can i solve this problem?
tagged with: keras
has comment: http://stackoverflow.com/comment/92107128
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52593325
type: AnsweredQuestion
has title: Interpretation of train-validation loss of a Neural Network
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92244639
accepted answer: http://stackoverflow.com/a/52593325
tagged with: loss
tagged with: neural-network
has comment: http://stackoverflow.com/comment/92103429
possible better answer: http://stackoverflow.com/a/52584959
tagged with: lstm
has comment: http://stackoverflow.com/comment/92244547
score: 0
has answer: http://stackoverflow.com/a/52584959
answer count: 2

http://stackoverflow.com/q/52475852
has comment: http://stackoverflow.com/comment/91893736
downvote count: 6
has comment: http://stackoverflow.com/comment/91893158
upvote count: 1
has comment: http://stackoverflow.com/comment/91893523
accepted answer: http://stackoverflow.com/a/52476887
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91893599
score: -5
has comment: http://stackoverflow.com/comment/91893513
type: Question
has title: obtaining substring from square bracket in a sentence
has comment: http://stackoverflow.com/comment/91893333
favorite count: 0
has answer: http://stackoverflow.com/a/52476673
has comment: http://stackoverflow.com/comment/91894284
possible better answer: http://stackoverflow.com/a/52476593
has comment: http://stackoverflow.com/comment/91893961
has answer: http://stackoverflow.com/a/52476887
answer count: 3
has body: I would like to ask as a python beginner, I would like to obtain strings from inside a square bracket and best if without trying to import any modules from python. If not it's okay. For example, def find_tags #do some codes x = find_tags('Hi[Pear]') print(x) it will return 1-Pear if there are more than one brackets for example, x = find_tags('[apple]and[orange]and[apple]again!') print(x) it will return 1-apple,2-orange,3-apple I would greatly appreciate if someone could help me out thanks!
has answer: http://stackoverflow.com/a/52476593
tagged with: python

http://stackoverflow.com/a/52571571
score: 0
type: Answer
has body: Assuming you want to print the suit and the card when you call the Draw_Card function (i.e. 7D), then you can move the print(card) to the bottom of the Draw_Card function. Also in order to change the Card variable outside the function, you'd need to place global Card at the top of the function. import random Card = "Nothing" def Draw_Card(): global Card Rank = random.randint(1, 13) Card = str(Rank) if Rank == 11: Card = "J" elif Rank == 12: Card = "Q" elif Rank == 13: Card = "K" Suit = random.randint(1, 4) if Suit == 1: Card = Card + "D" elif Suit == 2: Card = Card + "C" elif Suit == 3: Card = Card + "H" elif Suit == 4: Card = Card + "S" print(Card) print("And the game begins!") Card = "Nothing" Draw_Card() print(Card)
answers question: http://stackoverflow.com/q/52571361

http://stackoverflow.com/q/52447748
downvote count: 0
accepted answer: http://stackoverflow.com/a/52459486
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91838769
has title: Rolling mean (that extends its window) on grouped multi-index
tagged with: python
has body: I have a multi-index based on dates and times (grouped by times). Data looks like this: r2 var_v2x _s date time 2017-10-02 08:05:00 0.00000031 0.00008784 0.00353914 2017-10-03 08:05:00 0.00000008 0.00009055 0.00085233 2017-10-04 08:05:00 0.00000000 0.00018774 0.00000000 2017-10-05 08:05:00 0.00000031 0.00007609 0.00409934 and for another time period: r2 var_v2x _s date time 2017-10-02 08:30:00 0.00000000 0.00008784 0.00000000 2017-10-03 08:30:00 0.00000008 0.00009055 0.00085375 2017-10-04 08:30:00 0.00000008 0.00018774 0.00041180 2017-10-05 08:30:00 0.00000000 0.00007609 0.00000000 2017-10-10 08:30:00 0.00000008 0.00006900 0.00112288 Now I want to apply a rolling mean to column _s with a self-extendable rolling window. This means for the first observation within a group the rolling window is 1 (so just the value, 2nd observation includes 1st and 2nd value of column _s and so on. In the end, I want to have the ungrouped dataframe like: r2 var_v2x _s s_rolling date time 2017-10-02 08:05:00 0.00000031 0.00008784 0.00353914 0.00353914 2017-10-02 08:10:00 0.00000024 0.00008784 0.00249531 rolling(2) 2017-10-02 08:15:00 0.00000024 0.00008784 0.00249531 rolling(3) 2017-10-02 08:20:00 0.00000024 0.00008784 0.00249531 rolling(4) So far I have this: `file_name = r'E:\Model\ModelSpecific\Index_shat.txt' df = pd.read_csv(file_name, parse_dates=[0], index_col=None, sep=',') list_date = sorted(set(df['Date'])) list_time = sorted(set(df['Time'])) iterables = [list_date, list_time] indexed = pd.MultiIndex.from_product(iterables, names=['date', 'time']) df = df.set_index(indexed) df = df.dropna() df['_s'] = df['r2']/df['var_v2x'] for date, new_df in enumerate(df.groupby(level=1)): new_df = pd.DataFrame(new_df) new_df['rolling_s'] = new_df.expanding().mean() print(new_df) But returns: ValueError: Wrong number of items passed 3, placement implies 1. I also tried enumerate(df.groupby(level=1)): But returns: AttributeError: 'tuple' object has no attribute 'rolling'
answer count: 1
has comment: http://stackoverflow.com/comment/91839382
upvote count: 1
tagged with: multi-index
has comment: http://stackoverflow.com/comment/91839546
has answer: http://stackoverflow.com/a/52459486
tagged with: mean
tagged with: dataframe
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/comment/92064708
comment on: http://stackoverflow.com/q/52562991
score: 0
type: Comment
type: QuestionComment
has text: Gotcha. Still learning. Appreciate the feedback.

http://stackoverflow.com/q/52538374
score: 2
tagged with: mysql
has answer: http://stackoverflow.com/a/52540437
type: Question
answer count: 2
downvote count: 0
tagged with: pymysql
has title: How to select without column names in python with pymysql?
has body: I want to select a row in mysql, I do like this: import pymysql conn = pymysql.connect( host='10.0.0.11', port=3306, user='root', password='159753arazr', db='bili_1810', charset='utf8', cursorclass=pymysql.cursors.DictCursor) cursor = conn.cursor() table_name = ['24569', '25510'] for x in table_name: sql = "SELECT `播放`, `关注`, `弹幕`, `硬币` FROM `"+x+"` LIMIT %s, 1" cursor.execute(sql, (9)) conn.commit() result = cursor.fetchall() print(result) conn.close() The result is: [{'播放': '25824', '关注': '3071', '弹幕': '141', '硬币': '107'}] [{'播放': '0', '关注': '1244460', '弹幕': '0', '硬币': '0'}] But I want it to be like this: [{'25824', '3071', '141', '107'}] [{'0', '1244460', '0', '0'}] Just without the column names, how can I do it?
has comment: http://stackoverflow.com/comment/92016354
has comment: http://stackoverflow.com/comment/92016199
has comment: http://stackoverflow.com/comment/92024717
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70981728
tagged with: python

http://stackoverflow.com/comment/91891315
type: Comment
has text: This would work well for a write method, but it doesn't really answer my question about a read method. I would like to be able to to call my read function as `pd.read_custom`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52465897

series
tags question: http://stackoverflow.com/q/52461878
tag name: series
tags question: http://stackoverflow.com/q/52484271
type: Tag
tags question: http://stackoverflow.com/q/52537299
tags question: http://stackoverflow.com/q/52558614
tags question: http://stackoverflow.com/q/52530316
tags question: http://stackoverflow.com/q/52544400
tags question: http://stackoverflow.com/q/52541146
tags question: http://stackoverflow.com/q/52527417
tags question: http://stackoverflow.com/q/52541217
tags question: http://stackoverflow.com/q/52503141
tags question: http://stackoverflow.com/q/52498172
tags question: http://stackoverflow.com/q/52507052
tags question: http://stackoverflow.com/q/52498916
tags question: http://stackoverflow.com/q/52554917

http://stackoverflow.com/comment/92077697
score: 4
has text: The OP didn't say what optimisation was used, but it seems to me a smart optimiser could remove the loop entirely -- since c%2 is 0, b never changes and since b%2 is 1 the effect of the loop is to subtract the loop count from a.
type: Comment
comment on: http://stackoverflow.com/a/52570221
type: AnswerComment

http://stackoverflow.com/a/52466970
has body: I find a solution to get data from List_List_tuple item, the below code works well for me. for index, comparelist in enumerate(comparelists): if len(comparelist) == 0: # examble [...[].....] pass elif len(comparelist) == 1: # examble ('nana', 2.3, 3.3, 'gift') worksheet.write(row, 0, randomlistone[index]) # 3 --&gt; row number, column number, value worksheet.write(row, 1, randomlisttwo[index]) worksheet.write(row, 2, comparelist[0][0]) # write nana worksheet.write(row, 3, comparelist[0][1]) # write 2.3 worksheet.write(row, 6, 'visible')) if comparelist[0][2] is not None: # check if 3.3 exist worksheet.write(row, 4, comparelist[0][2]) # write 3.3 worksheet.write(row, 5, comparelist[0][3]) # write gift row += 1 else: worksheet.write(row, 0, randomlistone[index]) # 3 --&gt; row number, column number, value worksheet.write(row, 1, randomlisttwo[index]) worksheet.write(row, 6, 'visible')) worksheet.write(row, 7, 'grouped' + str(index)) for i in comparelist: if i[2] is not None: worksheet.write(row, 5, i[3]) pass row += 1 for y in comparelist: # examble ('nana', 2.3, 3.3, 'gift'),('nano', 5.3, 4.3, None),.....('nani', 2.1, 0.9, 'cart') worksheet.write(row, 0, randomlistone[index]) # 3 --&gt; row number, column number, value worksheet.write(row, 1, randomlisttwo[index]) worksheet.write(row, 2, y[0]) worksheet.write(row, 3, y[1]) worksheet.write(row, 6, 'hidden')) worksheet.write(row, 7, 'simple') if y[2] is not None: worksheet.write(row, 4, y[2]) worksheet.write(row, 5, y[3]) row += 1
answers question: http://stackoverflow.com/q/52431924
type: Answer
score: 0

http://stackoverflow.com/q/52523636
tagged with: python
has answer: http://stackoverflow.com/a/52524006
has body: Hi i am Using Feedparser to fetch rss news and display the news headlines import feedparser import kivy kivy.require('1.0.6') # replace with your current kivy version ! from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): d=feedparser.parse('https://en.wikinews.org/w/index.php?title=Special:NewsFeed&amp;feed=rss&amp;categories=Published&amp;notcategories=No%20publish%7CArchived%7cAutoArchived%7cdisputed&amp;namespace=0&amp;count=15&amp;ordermethod=categoryadd&amp;stablepages=only') print (len(d['entries'])) for post in d['entries']: news=post.title print(news) return Label(text=news) if __name__ == '__main__': MyApp().run() i.enews=post.title using a kivy label. Originally the output is as follows: Study suggests Mars hosted life-sustaining habitat for millions of years NASA's TESS spacecraft reports its first exoplanet Russians protest against pension reform US rapper Mac Miller dies at home in Los Angeles Creativity celebrated at Fan Expo Canada 2018 in Toronto Brisbane, Australia Magistrates Court charges two cotton farmers with $20m fraud Fossil genome shows hybrid of two extinct species of human Singer Aretha Franklin, 'queen of soul', dies aged 76 New South Wales, Australia government says entire state in winter 2018 drought Real Madrid agrees with Chelsea FC to sign goalkeeper Thibaut Courtois But,Whenever i run the program the Kivy app only shows the Last headline in the loop i.e:Real Madrid agrees with Chelsea FC to sign goalkeeper Thibaut Courtois Any ideas about what im missing on? any help would be grateful.
type: AnsweredQuestion
has title: Kivy label only shows last element of a text loop
upvote count: 1
type: Question
tagged with: feedparser
accepted answer: http://stackoverflow.com/a/52524006
downvote count: 0
answer count: 1
tagged with: kivy
score: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52509491
has answer: http://stackoverflow.com/a/52512073
score: 5
answer count: 3
tagged with: pandas
downvote count: 0
has title: Duplicating rows sequentially based on sum of multiple columns
favorite count: 0
has body: Let's say I have the the following dataframe (although the one I'm actually working with is over 100 rows): &gt;&gt; df a b c d e title0 1 0 0 string title1 0 1 1 string For each row, I want to: In col= ['b','c','d'], find rows where there is more than one column with value = 1. This is my condition. Duplicate rows that meet the above condition should be duplicated so that the first copy only =1 for the first column that =1 in the original, and so on for n times there is a column with value = 1. Delete the original row Output should be: &gt;&gt; df a b c d e title0 1 0 0 string title1 0 1 0 string title1 0 0 1 string
tagged with: python
accepted answer: http://stackoverflow.com/a/52512073
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52510543
type: Question
upvote count: 5
tagged with: duplicates
possible better answer: http://stackoverflow.com/a/52511284
has answer: http://stackoverflow.com/a/52511284

http://stackoverflow.com/q/52555139
has comment: http://stackoverflow.com/comment/92050155
linked to: http://stackoverflow.com/q/17591426
favorite count: 0
linked to: http://stackoverflow.com/q/34837707
tagged with: extract
upvote count: 5
has answer: http://stackoverflow.com/a/52563153
type: UnansweredQuestion
has body: Problem Statement: I have a PDF whose structure is like tables but the lines are not visible. Please find below the example: The above image is how my table looks in one of the PDF pages. My Research How to extract table as text from the PDF using Python? -- Gone through this question and seen all the answers. Not helpful Tabula: Tried tabula API but it is only extracting headers and not the text, probably because there are no lines. I can convert the whole pdf to text and then try to extract it with regex or data manipulations somehow. But that can be very tedious and time taking. Also, as the PDF changes the whole coding has to be done again. Ask Is their any API or Python package which can help me do this (Windows and Python 3.x)?
linked to: http://stackoverflow.com/q/47533875
tagged with: python
has comment: http://stackoverflow.com/comment/92050105
has comment: http://stackoverflow.com/comment/92051730
has comment: http://stackoverflow.com/comment/102364907
has comment: http://stackoverflow.com/comment/92051472
type: Question
has comment: http://stackoverflow.com/comment/104697021
has answer: http://stackoverflow.com/a/68270329
has comment: http://stackoverflow.com/comment/102383224
duplicate of: http://stackoverflow.com/q/17591426
linked to: http://stackoverflow.com/q/53209335
score: 4
has answer: http://stackoverflow.com/a/65072792
has title: Extract table with invisible lines from PDF
answer count: 3
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/92050360
downvote count: 1
has comment: http://stackoverflow.com/comment/92050945

http://stackoverflow.com/a/52502602
upvote count: 1
score: 1
downvote count: 0
has body: if you want to check if all letters occur only once use all return all(k == 1 for k in unique_chars.values()) that will avoid to return too soon a result when you haven't scanned the rest of the letters. Also consider counting your letters with collections.Counter which is a specialized dictionary made for counting hashable elements: unique_chars = collections.Counter(input_string) so combining in one line: return all(k == 1 for k in collections.Counter(input_string).values()) That said, we're missing the point. If we need to check if a word has non-duplicate letters this can be done without counting using a set: return len(input_string) == len(set(input_string))
type: Answer
answers question: http://stackoverflow.com/q/52502508

http://stackoverflow.com/q/52517813
answer count: 0
has title: Brython erreur open with brython_stdlib.js
upvote count: 1
type: Question
score: 1
has body: I get erreur open in the console when I add this line in index.html. If I delete it, I don't get the erreur open I don't know where is the problem.
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: brython

http://stackoverflow.com/q/52477655
upvote count: 4
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/126654885
has comment: http://stackoverflow.com/comment/92538532
favorite count: 0
has comment: http://stackoverflow.com/comment/92526209
tagged with: python-3.x
type: Question
tagged with: pubnub
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/91912051
has title: pubnub asyncio not publishing data
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I am using PubNub Asyncio library to publish the data, below is my code. import asyncio import os from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_asyncio import PubNubAsyncio def publish_callback(result, status): print(status) class PubNubIntegrator: def __init__(self): print("In initialize") pn_configuration = PNConfiguration() pn_configuration.publish_key = os.environ['PUB_KEY'] pn_configuration.subscribe_key = os.environ['SUB_KEY'] pn_configuration.ssl = True self.pubnub = PubNubAsyncio(pn_configuration) async def publish_data(self, message, channel_name): print('message on channel {0}'.format(channel_name)) try: asyncio.ensure_future(self.pubnub.publish().channel(channel_name).message(message).future()).add_done_callback(publish_callback) except PubNubException as e: print("Error while publishing data", message) And I am calling it from another function, async def stream(self): result = { "mesage": "data"} pn_integrator = PubNubIntegrator() await pn_integrator.publish_data(result, 'demo_channel') But it doesn't work and not publishing the data to channel.

http://stackoverflow.com/comment/91870786
comment on: http://stackoverflow.com/a/52460039
type: Comment
has text: Performance is not an issue. And Thanks, all the suggestions mentioned here works. But I have a small problem.I am working this in an excel i used `writer = pd.ExcelWriter("Rule.xlsx",engine="openpyxl") excel=openpyxl.load_workbook("Rule.xlsx") writer.book=excel writer.save() writer.close()` but its not overwriting in my excel sheet. Can you tell me why?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52454372
tagged with: python
answer count: 0
tagged with: incompatibletypeerror
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91851852
type: Question
has comment: http://stackoverflow.com/comment/91851660
score: 0
has title: Incompatible shapes: [14250,10] vs. [15000,10]
tagged with: jupyter-notebook
has body: I am new to tensorflow and am following udacity program. I have been asked to build the image classifier on notMNIST dataset. I am attaching the code and the error, please help me out with whatever you can. Thanks. features_count = 784 labels_count = 10 features = tf.placeholder(tf.float32) labels = tf.placeholder(tf.float32) weights = tf.Variable(tf.truncated_normal((features_count, labels_count))) biases = tf.Variable(tf.zeros(labels_count)) train_feed_dict = {features: train_features,labels: train_labels} valid_feed_dict = {features: valid_features, labels: valid_labels} test_feed_dict = {features: test_features, labels: test_labels} # Linear function Wx+b logits = tf.add(tf.matmul(features,weights), biases) prediction = tf.nn.softmax(logits) #Cross entropy cross_entropy = -tf.reduce_sum(labels * tf.log(prediction), reduction_indices = 1) # Training loss loss = tf.reduce_mean(cross_entropy) # Initialize all the variables init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) sess.run(loss, feed_dict = train_feed_dict) sess.run(loss, feed_dict = valid_feed_dict) sess.run(loss, feed_dict = test_feed_dict) biases_data = sess.run(biases) This is the error I am getting: InvalidArgumentError: Incompatible shapes: [14250,10] vs. [15000,10] [[Node: mul_7 = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"] . (_arg_Placeholder_16_0_1, Log_7)]] During handling of the above exception, another exception occurred: InvalidArgumentError Traceback (most recent call last) &lt;ipython-input-46-83a463c8a201&gt; in &lt;module&gt;() 53 with tf.Session() as sess: 54 sess.run(init) ---&gt; 55 sess.run(loss, feed_dict = train_feed_dict) 56 sess.run(loss, feed_dict = valid_feed_dict) 57 sess.run(loss, feed_dict = test_feed_dict)
type: UnansweredQuestion

http://stackoverflow.com/comment/91900263
score: 0
type: Comment
type: QuestionComment
has text: The work-around is to either use `float`, or use `math.sqrt()`. `numpy.sqrt()` only can work with native C types, and integers are limited to `unsigned long long` (8 bytes).
comment on: http://stackoverflow.com/q/52479465

http://stackoverflow.com/comment/92099575
type: Comment
comment on: http://stackoverflow.com/a/52582189
type: AnswerComment
has text: Because I am wondering the, which one of those numbers is my final answer then?! when I get the `return` out of loop.
score: 0

http://stackoverflow.com/q/52440940
has answer: http://stackoverflow.com/a/52442586
tagged with: tensorflow
type: Question
tagged with: keras
has body: Using TensorFlow/Keras, I want to classify pictures into two classes, selfie and non-selfie. I have gathered samples into two filesystem folders, one for each category. I implemented the training below by following the official tutorial for MNIST fashion (which is also a pictures classification problem), after using loading pictures from the filesystem as seen at https://stackoverflow.com/a/52417770/226958. Unfortunately, I get an error: 1.10.1 Tensor("IteratorGetNext:0", shape=(?, 100, 100, 1), dtype=float32) Tensor("IteratorGetNext:1", shape=(?,), dtype=int32) Traceback (most recent call last): File "run.py", line 50, in &lt;module&gt; model.fit(images, labels, epochs=1, steps_per_epoch=60000) File "/home/nico/.local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 1278, in fit validation_split=validation_split) File "/home/nico/.local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 878, in _standardize_user_data exception_prefix='input') File "/home/nico/.local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training_utils.py", line 182, in standardize_input_data 'with shape ' + str(data_shape)) ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (None, 100, 100, 1) Here is the source code: import tensorflow as tf print(tf.__version__) out_shape = tf.convert_to_tensor([100, 100]) batch_size = 2 image_paths, labels = ["selfies-data/1", "selfies-data/2"], [1, 2] epoch_size = len(image_paths) image_paths = tf.convert_to_tensor(image_paths, dtype=tf.string) labels = tf.convert_to_tensor(labels) # The images loading part is from https://stackoverflow.com/a/52417770/226958 dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels)) dataset = dataset.repeat().shuffle(epoch_size) def map_fn(path, label): # path/label represent values for a single example image = tf.image.decode_jpeg(tf.read_file(path)) # some mapping to constant size - be…
score: 0
answer count: 1
has title: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (None, 100, 100, 1)
tagged with: classification
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/52442586
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44416764

http://stackoverflow.com/a/52482918
downvote count: 0
has comment: http://stackoverflow.com/comment/91907905
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52482762
score: 2
has comment: http://stackoverflow.com/comment/91907505
has body: I would iterate through the letters keeping track of the vowels and consonants, and then use join at the end. def encrypt_sentence(sentence): vowel_set = set("aeiouAEIOU") final_list=[] word=sentence.split() for i in range(0,len(word)): if((i%2)==0): final_list.append(word[i][::-1]) else: # do rearrangement vowels = list() consonants = list() for letter in word[i]: if letter in vowel_set: vowels.append(letter) else: consonants.append(letter) new_string = "".join(consonants) + "".join(vowels) final_list.append(new_string) return final_list
accepted answer of: http://stackoverflow.com/q/52482762
type: AcceptedAnswer

http://stackoverflow.com/a/52531908
type: Answer
answers question: http://stackoverflow.com/q/52526435
has body: simple pythonic way, hope it may help you city = input("Enter City name") with open('your text file') as file: print(file.readline().split()[:3]) for line in file.readlines(): if line.split()[2] == city: print(line.split()[:3])
score: 0

http://stackoverflow.com/q/52567746
tagged with: download
type: UnansweredQuestion
tagged with: python
tagged with: curl
has body: My Institute doesn't allow file downloads more than 300MB so I came up with this trick of downloading the files in parts! Now I wanted to ease the task and make a script in python! I'm using os.system() to execute commands! My plan is to use this curl --range 300000000*X-(300000000*(X+1)-1) [url] -o filename.partX # X is the part number But I have no idea how to terminate the loop! How would i know that the all available parts of file are downloaded! Can anyone help me out with this?
has title: Python Script to download large files in parts using curl
type: Question
has answer: http://stackoverflow.com/a/52568270
tagged with: filesplitting
score: 0
answer count: 1
tagged with: terminal

http://stackoverflow.com/q/52439490
accepted answer: http://stackoverflow.com/a/52439686
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91821756
has comment: http://stackoverflow.com/comment/91821732
has answer: http://stackoverflow.com/a/52439686
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/91821931
has body: I'm running loop that writes around 10000 lines to a file. I've been searching but can't find whether it's more efficient to concatenate a string in a write statement, or use multiple write statements. ie: f = open(fileName,"w+") for item in list: f.write(str1 + str2 + str3 + item + "\n\n") or f = open(fileName,"w+") for item in list: f.write(str1) f.write(str2) f.write(str3) f.write(item) f.write("\n\n") Is the first or second option more efficient? I imagine this has been asked before and I'm asking the question in a strange way, so if someone can point me in the right direction that'd be fantastic!
has title: Is it more efficient to write to a file in one statement than multiple statements?
score: 0
answer count: 1

http://stackoverflow.com/comment/91937765
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52498310
type: Comment
has text: Well, actually, it is "'{}'".format(u'ES SIOUF_1') so it is correct. How could work for you and not for me?

http://stackoverflow.com/q/52536093
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92030228
tagged with: flask
accepted answer: http://stackoverflow.com/a/52540701
has comment: http://stackoverflow.com/comment/92027173
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/52542353
score: 0
answer count: 2
tagged with: pymongo
has answer: http://stackoverflow.com/a/52542353
has body: I am currently working on a flask project that uses several blueprints and mongo for data storage. I have created multiple PyMongo instances in order to reach different databases: In app.py which is the core file of the project I have defined the instances: # The PyMongo instance 'mongo_app' takes its uri from the project's config. mongo_app.init_app(app) # The second PyMongo instance is initialized with the needed uri. mongo_project.init_app(app, uri="mongodb://mongodb:27017/rick_and_morty") In a blueprint of the project I need the name of the database with which the PyMongo object 'mongo_project' has been initialized, namely 'rick_and_morty'. My question is, how can I suck this information out of the PyMongo object? Something like the following I am trying to achieve: database_name = mongo_project.db_name #rick_and_morty
has title: Get the database name from a PyMongo object
tagged with: mongodb
has answer: http://stackoverflow.com/a/52540701

http://stackoverflow.com/comment/91959941
has text: Likely related to [raw_input() won't show prompt until after input](https://stackoverflow.com/q/11621082/364696), but the answer there is poor; not willing to mark as duplicate.
comment on: http://stackoverflow.com/q/52509889
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91895604
comment on: http://stackoverflow.com/a/52476745
score: 0
type: AnswerComment
has text: Cool thanks, I have already changed the recursion into iterative functions. So, I'm the right way. I use mainly texts without punctaution marks, noting else from plain letters.
type: Comment

http://stackoverflow.com/comment/92027266
score: 0
type: QuestionComment
has text: Is it always between `If...then` or is that just an example?
type: Comment
comment on: http://stackoverflow.com/q/52538047

http://stackoverflow.com/q/52579725
score: -1
has title: python Dictionary function call in class
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/52579798
tagged with: class
answer count: 3
has answer: http://stackoverflow.com/a/52579800
tagged with: python-2.x
favorite count: 0
has body: I tried to implement my own stack in Python. When I choose any of 'pos', an error shows up class Stack: '''This is Stack Class''' def __init__(self): self.stack=[] def push(self): '''Enter item to push into stack''' self.stack.append(raw_input("Enter item to stack: ")) def pop(self): '''Pops item from stack''' if len(self.stack)==0: print 'Cannot pop from empty stack' else: i = self.stack.pop(index=-1) print ('Item popped: [%s]'%i) def show(self): '''Display Stack Content''' print self.stack choiceDict={'p':push, 'o':pop, 's':show, 'q':quit} def menu(): '''This is a menu list for stack''' s=Stack() while True: while True: print '''Enter Choice p) push o) pop s) show q) quit''' c=raw_input('Enter choice &gt; ').lstrip()[0].lower() if c not in 'posq': print '**Invalid Choice' else: break if(c=='q'): break s.choiceDict[c]() if __name__=='__main__': menu() Error: s.choiceDict[c]() TypeError: push() takes exactly 1 argument (0 given) ps: If there are any other bugs in code. I'll be happy to know them :) And by the way I just want the way to solve this issue
has answer: http://stackoverflow.com/a/52579791
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
downvote count: 1
tagged with: oop

while-loop
tags question: http://stackoverflow.com/q/52570850
tags question: http://stackoverflow.com/q/52532176
tags question: http://stackoverflow.com/q/52461010
tags question: http://stackoverflow.com/q/52546482
type: Tag
tags question: http://stackoverflow.com/q/52441642
tags question: http://stackoverflow.com/q/52442723
tags question: http://stackoverflow.com/q/52504708
tags question: http://stackoverflow.com/q/52547525
tags question: http://stackoverflow.com/q/52568667
tags question: http://stackoverflow.com/q/52489103
tags question: http://stackoverflow.com/q/52467253
tags question: http://stackoverflow.com/q/52517487
tags question: http://stackoverflow.com/q/52528954
tags question: http://stackoverflow.com/q/52583321
tags question: http://stackoverflow.com/q/52489201
tags question: http://stackoverflow.com/q/52527528
tags question: http://stackoverflow.com/q/52487064
tags question: http://stackoverflow.com/q/52509083
tags question: http://stackoverflow.com/q/52523259
tags question: http://stackoverflow.com/q/52485805
tags question: http://stackoverflow.com/q/52547143
tags question: http://stackoverflow.com/q/52490607
tags question: http://stackoverflow.com/q/52574277
tags question: http://stackoverflow.com/q/52564152
tags question: http://stackoverflow.com/q/52561688
tag name: while-loop
tags question: http://stackoverflow.com/q/52576185

http://stackoverflow.com/q/52520670
has body: I'm trying to change the callable for an instance method on my MagicMock to a PropertyMock as that is how it is accessed (Django model column). But test fails with _mock_self = &lt;PropertyMock name='get().my_prop' id='4524632776'&gt; Given the following code # view def get(self request): # stuff... obj = MyModel.objects.get(id=2) # more stuff... print(obj.my_prop) some_val = MyOtherModel(my_prop=obj.my_prop) # tests def test_my_test(mocker): other_obj = mocker.patch("app.views.MyOtherModel") obj_get = mocker.patch("app.views.MyModel.objects.get") obj_prop = mocker.PropertyMock(return_value=1) # This should translate to an instance of MyModel i.e. MyModel().my_prop obj_get.return_value.my_prop = obj_prop # run view obj_prop.assert_called_once() # Says never invoked # Failed as my_prop was a PropertyMock instead of actual value other_obj.assert_called_once_with(my_prop=obj_prop) The print statement shows &lt;PropertyMock name='get().my_prop' id='4524632776'&gt; So it appears it is the same instance it just is not actually being invoked I also had attempted directly patching the property off the model but that does not appear to work as the Mocks are not the same. def test_my_test(mocker): other_obj = mocker.patch("app.views.MyOtherModel") obj_prop = mocker.patch("app.views.MyModel.my_prop", new_callable=mocker.PropertyMock) obj_get = mocker.patch("app.views.MyModel.objects.get") obj_get.return_value.my_prop = obj_prop # run view obj_prop.assert_called_once() # Failed as my_prop was a PropertyMock instead of actual value other_obj.assert_called_once_with(my_prop=obj_prop) Which fails with... _mock_self = &lt;PropertyMock name='my_prop' id='4543022192'&gt; but prints &lt;MagicMock name='get().my_prop' id='4543752232'&gt; EDIT Added in other patches that more accurately depicted the implementation
has answer: http://stackoverflow.com/a/52521729
answer count: 1
downvote count: 0
favorite count: 0
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52521729
score: 1
has title: Change MagicMock return_value instance method callable to PropertyMock
type: Question
tagged with: mocking

http://stackoverflow.com/q/52552994
tagged with: list
duplicate of: http://stackoverflow.com/q/1720421
score: 1
has answer: http://stackoverflow.com/a/52553055
has comment: http://stackoverflow.com/comment/92045654
type: Question
has body: I have a maybe stupid problem, but can't figure out how to solve it. So basically what I'm trying to do is to: Create a list Add items to the list (stored in a second list) Transform the list into a tuple So I thought I would do something like this: anotherList = [2,5,8] myTuple = tuple([1,2,3].extend(anotherList)) This does not work as it throws the error: TypeError: 'NoneType' object is not iterable This makes sense, as the result of the extend operation is not a list. The problem is that I wasn't able to make it in a one line code, but only in a 4 lines code, like that: anotherList = [2, 5, 8] myList = [1, 2, 3] myList.extend(anotherList) myTuple = tuple(myList) Is there a way to simplify this code? It looks unnecessarily long!
downvote count: 0
has title: Create list, append data and transform to tuple: shortest code
has answer: http://stackoverflow.com/a/52553053
tagged with: tuples
tagged with: python-2.7
answer count: 3
accepted answer: http://stackoverflow.com/a/52553055
possible better answer: http://stackoverflow.com/a/52553047
has comment: http://stackoverflow.com/comment/92044780
has comment: http://stackoverflow.com/comment/92044971
has answer: http://stackoverflow.com/a/52553047
favorite count: 0
has comment: http://stackoverflow.com/comment/92044815
linked to: http://stackoverflow.com/q/1720421
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/93959642
score: 1
has text: In case it helps: in my case this was solved by adding "universe" to apt sources (see [this answer](https://askubuntu.com/a/1061488/865083))
comment on: http://stackoverflow.com/q/52580658
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92049847
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52555439
has text: @deceze: I've seen the pattern in standard python libraries, so it should be pythonic enough. If there's more code, the OP could make a function out of it (which should be done anyway, regardless of which approach he chooses)

http://stackoverflow.com/q/52451146
upvote count: 1
has title: Adding a MultiIndex Summary Column at the Beginning of a DataFrame
type: Question
type: AnsweredQuestion
tagged with: multi-index
has answer: http://stackoverflow.com/a/52451373
tagged with: summary
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: pandas
has body: If I have a Dataframe and I'd like to insert a summary column at the beginning I can run df.insert(0, 'Average', df.mean(axis='columns')) Say I have a MultiIndexed dataframe of the form df = pd.DataFrame() for l1 in ('a', 'b'): for l2 in ('one', 'two'): df[l1, l2] = np.random.random(size=5) df.columns = pd.MultiIndex.from_tuples(df.columns, names=['L1', 'L2']) L1 a b L2 one two one two 0 0.585409 0.563870 0.535770 0.868020 1 0.404546 0.102884 0.254945 0.362751 2 0.475362 0.601632 0.476761 0.665126 3 0.926288 0.615655 0.257977 0.668778 4 0.509069 0.706685 0.355842 0.891862 How do I add the mean of all the one columns and all the two columns to the first two columns of this DataFrame and call it 'Average'? EDIT: Expected output would be df.mean(level=1, axis=1) but inserted into the first two columns of the frame with the L1 label 'Average'. I was hoping the following would work: df.insert(0, 'Average', df.mean(level=1, axis=1))
tagged with: python
accepted answer: http://stackoverflow.com/a/52451373
has comment: http://stackoverflow.com/comment/91846123

http://stackoverflow.com/a/52588171
upvote count: 1
type: Answer
score: 1
has body: Most likely what you want isn't m.toarray but m.tocsr(). a csr matrix can do simple linear algebra (like .dot() and matrix powers) natively, for instance this works: m.tocsr() random_walk_2 = m.dot(m) random_walk_n = m ** n # see https://stackoverflow.com/questions/28702416/matrix-power-for-sparse-matrix-in-python Covariance should be implementable as well, but I'm not sure what the specific implementation would be without seeing what your current process is. EDIT: To turn the output back into a simpler format to read out to csv, you can follow up by returning to coo with .tocoo() m.tocoo() out = np.c_[m.data, m.row, m.col].T np.savetxt("foo.csv", out, delimiter=",") # see https://stackoverflow.com/questions/6081008/dump-a-numpy-array-into-a-csv-file
accepted answer of: http://stackoverflow.com/q/52586643
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52586643

http://stackoverflow.com/a/52432125
answers question: http://stackoverflow.com/q/52431295
has comment: http://stackoverflow.com/comment/91827557
score: 1
has comment: http://stackoverflow.com/comment/91810243
has body: In my opinion a solution that I would implement for that issue is to create a conf.py, as you said, and then define in it global variables as dictionary structures in order to be properly organized and easy-to-use on the modules that will be imported. For example: globals = {'value_a': 'something a', 'value_b': 'something b', 'value_c': '5.0', 'allowed_platforms': { 'windows': 'value 1', 'os x': 'value 2', 'linux': 'value 3' }, 'hosts': ['host a', 'host b', 'host c'], ... } You need to avoid the from some_module import * statement because you could put a lot of imports into the namespace and because it's not explicit about what is importing. So doing at the top of each module from your_package.conf import globals you could use it without the need of importing explicitly every single variable that you want to use or without importing the entire module. I prefer that solution, and also could be better if you use json files to store the info of that global variables and then read and serialize them in the conf.py module before being imported in your required modules.
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/52441702
has body: I have two dataframes df1: index Value 0 A 1 B 2 Nan 3 D 4 Nan And df2: index Value 2 C 4 E In my jupyter notebook I use Pandas update function to fill in the missing values of df1 from df2. Using the following function: def my_function(df, df_2): df1.update(df2) return Because .update() modifies dataframes in place and has no return value, my functions also doen't return anything. The behaviour I don't understand occurs when I run the following code in jupyter notebook: blaat = df1 my_function(blaat, df2) Now not only the 'blaat' dataframe has been modified by the function but also df1. I don't understand why that is.
type: UnansweredQuestion
has title: Strange behaviour with pandas.DataFrame.update
has comment: http://stackoverflow.com/comment/91826484
tagged with: python
has answer: http://stackoverflow.com/a/72216357
type: Question
has comment: http://stackoverflow.com/comment/91826518
has comment: http://stackoverflow.com/comment/91826300
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/91924671
type: QuestionComment
comment on: http://stackoverflow.com/q/52489246
score: 0
type: Comment
has text: Beware that a simple `pip2 freeze` will also list packages you won't be able to uninstall, so `pip uninstall`ing with break on first error.

http://stackoverflow.com/q/52539614
type: AnsweredQuestion
score: -1
type: Question
has comment: http://stackoverflow.com/comment/92019243
has answer: http://stackoverflow.com/a/52540328
answer count: 2
has body: I have a python program which I want to execute exactly 30 seconds before every 5th Minute and need to run for 30 seconds only.
upvote count: 0
tagged with: scheduled-tasks
favorite count: 0
accepted answer: http://stackoverflow.com/a/52541331
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52540328
tagged with: python
has title: How to Run Python Code 30 Sec before Every 5th Minute
downvote count: 1
has answer: http://stackoverflow.com/a/52541331

http://stackoverflow.com/q/52554674
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/54296100
has title: How does TnT (Goloboff et al., 2008) assign internal node labels?
answer count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/54296100
has body: I have used TnT v1.1 (Goloboff et al., 2008) to assign synapomorphies from a presence-absence matrix (PAM) to a phylogeny. TnT does not allow for internal node IDs or branch lengths and I need to use the branch lengths with the TnT data for statistical analyses. I have a huge dataset (>1000 taxa) so assigning branch lengths by hand would be tedious. TnT begins internal node naming based on the first species in the data file (eg if a datafile with 100 species is presented and Aspergillus flavus is the first species, then the node preceding A. flavus is annotated N101). TnT provides internal nodes in its ASCII tree but not in its output newick tree. Does anyone know how I can either (a) get TnT to print out the internal nodes in a newick tree or how I can replicate TnTs naming procedure, preferably using python (ete2/ete3)? TIA
tagged with: phylogeny
downvote count: 0

http://stackoverflow.com/a/52489929
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52489565
has body: a = pd.DataFrame(index=[78],columns=["detail"]) a.loc[78,"detail"] = [{'y1': 549, 'score': 1, 'x2': 630, 'frame': 1054, 'y2': 564, 'x1': 602, 'visibility': 0.0, 'class': 5}] a.loc[188,"detail"] = [{'y1': 649, 'score': 1, 'x2': 630, 'frame': 1054, 'y2': 564, 'x1': 602, 'visibility': 0.0, 'class': 5}] For each dict, you should use pd.DataFrame.from_dict. Actually, I don't exactly that you want to print it out? or convert it into multiple dataframes. Here is some simple solutions. # print it a.applymap(lambda x:print(pd.DataFrame.from_dict({0:x[0]}))) # convert it for i in a.index: tmp = pd.DataFrame.from_dict({0:a.loc[i,"detail"][0]}).T tmp.x2 = tmp.x2+tmp.x1 tmp.y2 = tmp.y2 + tmp.y1 # this function you could storge in any dict/list. Or you could storge into a list. And using pd.concat to concate them together.
answers question: http://stackoverflow.com/q/52489565
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/92041659
comment on: http://stackoverflow.com/a/52519810
type: Comment
has text: Thank you for your answer. I have measured the time both in my laptop and in a server for a dataframe of 100 IP addresses. In my laptop, your proposed method is 1 sec (1 min vs 1min1sec) slower than the iterrows, and in the server, it is 0.4s slower (49.7s vs 49.3s)
type: AnswerComment
score: 0

http://stackoverflow.com/q/52487412
tagged with: python
has answer: http://stackoverflow.com/a/52487593
score: 0
accepted answer: http://stackoverflow.com/a/52487593
answer count: 1
has title: Pandas: rolling windows with a sum product
tagged with: pandas
type: AnsweredQuestion
type: Question
has body: There are a number of answers that each provide me with a portion of my desired result, but I am challenged putting them all together. My core Pandas data frame looks like this, where I am trying to estimate volume_step_1: date volume_step_0 volume_step_1 2018-01-01 100 a 2018-01-02 101 b 2018-01-03 105 c 2018-01-04 123 d 2018-01-05 121 e I then have a reference table with the conversion rates, for e.g. step conversion 0 0.60 1 0.81 2 0.18 3 0.99 4 0.75 I have another table containing point estimates of a Poisson distribution: days_to_complete step_no pc_cases 0 0 0.50 1 0 0.40 2 0 0.07 Using these data, I now want to estimate volume_step_1 = (volume_step_0(today) * days_to_complete(step0, day0) * conversion(step0)) + (volume_step_0(yesterday) * days_to_complete(step0,day1) * conversion(step0)) and so forth. How do I write some Python code to do so?

http://stackoverflow.com/comment/92093943
type: QuestionComment
has text: try following the docs first https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html
score: 0
comment on: http://stackoverflow.com/q/52577218
type: Comment

http://stackoverflow.com/q/52508217
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52508719
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52508719
has body: I need to generate multiple (say, 100 000) random sets of holdings for users who can hold multiple holdings. For any given user, these holdings have to sum to 1. In theory, generating these random holdings can be done fairly easily in numpy: num_users = 100000 num_holdings = 8 random_holdings = np.random.rand(num_users, num_holdings) random_holdings /= np.sum(random_holdings, axis=1, keepdims=True) This gives us random_holdings array([[0.044, 0.169, 0.204, ..., 0.051, 0.116, 0.176], [0.132, 0.078, 0.23 , ..., 0.102, 0.028, 0.204], [0.036, 0.182, 0.165, ..., 0.138, 0.065, 0.04 ], ..., [0.195, 0.028, 0.136, ..., 0.147, 0.113, 0.22 ], [0.19 , 0.237, 0.061, ..., 0.23 , 0.109, 0.046], [0.181, 0.111, 0.1 , ..., 0.166, 0.126, 0.199]]) The problem with this is that it leads to many similar holdings sets and relatively few concentrated holdings sets. For example: len(np.where(random_holdings &gt; 0.5)[0]) gives a result of 24, ie there are only 24 holdings out of the entire 100 000 which are greater than 0.5. Could anybody kindly recommend a better randomization method or just a more sensible overall approach, so that I have fewer similar sets of holdings and more concentrated sets of holdings? Thanks!
score: 0
has comment: http://stackoverflow.com/comment/91957540
answer count: 1
has title: Generating random sets of holdings using numpy
has comment: http://stackoverflow.com/comment/91957437
tagged with: python
has comment: http://stackoverflow.com/comment/91956878
has comment: http://stackoverflow.com/comment/91957028
has comment: http://stackoverflow.com/comment/91957409

http://stackoverflow.com/comment/92088781
score: 0
comment on: http://stackoverflow.com/q/52575784
type: Comment
type: QuestionComment
has text: Your code runs well for me using Python 3.7. I validated the result by searching string "Page 10" in the result

http://stackoverflow.com/comment/91940489
has text: It says 3 minutes until I can. I will mark it then.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52499892
type: AnswerComment

http://stackoverflow.com/comment/92095784
comment on: http://stackoverflow.com/q/52580318
score: 0
has text: Could you elaborate, what's the question here? (What does not work, what did you expect instead ect)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52569766
type: Answer
accepted answer of: http://stackoverflow.com/q/52569051
upvote count: 3
answers question: http://stackoverflow.com/q/52569051
score: 3
type: AcceptedAnswer
downvote count: 0
has body: Aiohttp is running on the port 8001 in the container toolservice, but your proxying to the port 80. proxy_pass http://toolservice; Try proxying to 8001: proxy_pass http://toolservice:8001; Maybe you will need to fix publishing of the port for toolservice container - I'm not 100% sure: ports: - "8001:8001"

http://stackoverflow.com/comment/92113241
has text: [Edit] your Question to show an example of the meaning of: **"...using the parameters in excel sheet whether pyasn can start creating the object..."**. Explain **" the parameters in excel sheet "**, do you mean the Type of values e.g. 'string', 'number' etc.?
comment on: http://stackoverflow.com/q/52552393
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52488977
has answer: http://stackoverflow.com/a/60452590
has answer: http://stackoverflow.com/a/52490842
score: 10
tagged with: django-models
upvote count: 10
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/78441416
tagged with: django-rest-framework
favorite count: 0
has title: In setting viewset, I got an error AttributeError: 'function' object has no attribute 'get_extra_actions'
has answer: http://stackoverflow.com/a/64948754
linked to: http://stackoverflow.com/q/56052906
answer count: 4
has body: I'm learning DRF and feel confused a little now. I set up QuestionView and QuestionSerializer like this. views.py class QuestionView(viewsets.ModelViewSet) : queryset = models.Question.objects.all() serializer_class = QuestionSerializer def list(self, request, *args, **kwargs): serializer = QuestionSerializer(models.Question.objects.all()) return Response(serializer.data) serializer.py class QuestionSerializer(serializers.ModelSerializer): class Meta: model= Question fields= ("question_text", "owner", "pub_date") urls.py router = routers.DefaultRouter() router.register('profile', cebula_views.SettingView) router.register('question', cebula_views.QuestionView.as_view({ 'get':'list', }), 'userpage-question') urlpatterns = [ ... url(r'^', include(router.urls)), ... ] File "C:\Users\1Sun\Cebula3\businessproject\urls.py", line 34, in url(r'^', include(router.urls)), File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 101, in urls self._urls = self.get_urls() File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 363, in get_urls urls = super(DefaultRouter, self).get_urls() File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 261, in get_urls routes = self.get_routes(viewset) File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 176, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' In my opinion, It is that I should write get_extra_actions method in QuestionView class, If so, how I write that? like this? def get_extra_actions() : return ??? If not, what is the problem? [Edit] when I erase .as_view() at the url part and write like router.register('question', cebula_views.QuestionView, 'userpage-question') the error is Unhandled exception in thread started by .wrapper at 0x…
tagged with: serialization
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/92030421
type: AnswerComment
comment on: http://stackoverflow.com/a/52526584
type: Comment
has text: I am implementing a different logic through your guidance above. Its working now I just forgot to add the fill & expand logic in the canvas.pack function. Thank you so much for your help.
score: 0

indexing
tags question: http://stackoverflow.com/q/52560212
tags question: http://stackoverflow.com/q/52447772
tags question: http://stackoverflow.com/q/52580270
tags question: http://stackoverflow.com/q/52583619
tags question: http://stackoverflow.com/q/52491156
tags question: http://stackoverflow.com/q/52531974
tags question: http://stackoverflow.com/q/52559709
tags question: http://stackoverflow.com/q/52480834
type: Tag
tags question: http://stackoverflow.com/q/52502437
tags question: http://stackoverflow.com/q/52534972
tags question: http://stackoverflow.com/q/52557357
tags question: http://stackoverflow.com/q/52566442
tags question: http://stackoverflow.com/q/52485840
tags question: http://stackoverflow.com/q/52486467
tags question: http://stackoverflow.com/q/52506861
tag name: indexing
tags question: http://stackoverflow.com/q/52507154
tags question: http://stackoverflow.com/q/52537888
tags question: http://stackoverflow.com/q/52491286
tags question: http://stackoverflow.com/q/52436238
tags question: http://stackoverflow.com/q/52507303
tags question: http://stackoverflow.com/q/52541217
tags question: http://stackoverflow.com/q/52568437
tags question: http://stackoverflow.com/q/52435070
tags question: http://stackoverflow.com/q/52524761
tags question: http://stackoverflow.com/q/52547143
tags question: http://stackoverflow.com/q/52504709
tags question: http://stackoverflow.com/q/52563916
tags question: http://stackoverflow.com/q/52488536
tags question: http://stackoverflow.com/q/52574122

http://stackoverflow.com/a/52508114
has comment: http://stackoverflow.com/comment/91956924
score: 1
has comment: http://stackoverflow.com/comment/91994593
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52508081
type: Answer
has comment: http://stackoverflow.com/comment/91956629
answers question: http://stackoverflow.com/q/52508081
has body: Your issue is that if there isn't a character that splits at the end of the string, what you already have inside word isn't added to words. Append the word at the end if word isn't empty. Edit: kindall pointed out that it wouldn't work on strings with just one word so I moved the condition outside the if len(words) != 0 def split(string): words = [] char_to_split = [' ', '\n', '\t'] word = "" for ch in string: if ch in char_to_split: if word != "": words.append(word) word = "" else: word += ch if word: words.append(word) # add this if len(words) != 0: return words else: return None print(split('duff_beer 4.00')) &gt;&gt;&gt; ['duff_beer', '4.00'] Edit thanks to @k
upvote count: 1

http://stackoverflow.com/a/52551897
has comment: http://stackoverflow.com/comment/92070935
accepted answer of: http://stackoverflow.com/q/52551787
score: 3
answers question: http://stackoverflow.com/q/52551787
type: AcceptedAnswer
downvote count: 0
has body: returns 3 if x&gt;y returns 1 if x==0 and returns 0 if x&lt;y You can basically write that as you described: lambda x,y: 3 if x&gt;y else 1 if x==0 else 0
has comment: http://stackoverflow.com/comment/92070278
type: Answer
upvote count: 3

database
tags question: http://stackoverflow.com/q/52438106
tags question: http://stackoverflow.com/q/52546519
tags question: http://stackoverflow.com/q/52507721
type: Tag
tags question: http://stackoverflow.com/q/52564267
tags question: http://stackoverflow.com/q/52475303
tags question: http://stackoverflow.com/q/52453037
tags question: http://stackoverflow.com/q/52457172
tags question: http://stackoverflow.com/q/52468036
tag name: database
tags question: http://stackoverflow.com/q/52535552
tags question: http://stackoverflow.com/q/52574959
tags question: http://stackoverflow.com/q/52461091
tags question: http://stackoverflow.com/q/52550922
tags question: http://stackoverflow.com/q/52543420
tags question: http://stackoverflow.com/q/52432061
tags question: http://stackoverflow.com/q/52479133
tags question: http://stackoverflow.com/q/52432166

http://stackoverflow.com/q/52584104
has answer: http://stackoverflow.com/a/76535419
accepted answer: http://stackoverflow.com/a/52584765
has body: Relatively new to Python here, coming from a node.js background, having quite a few issues parsing the output I get from get_query_results() Documentation Link I have been at this for some hours, i have tried iterating through the ['ResultSetMetadata']['ColumnInfo'] to grab the column names, but i don't know how to tie the ['ResultSet']['Data'] to these items so the code knows which name to apply to each dataValue. I know i need to select the row headers then add the associated objects to those rows, but the logic on how to do such a thing in python escapes me. I can see that the first column name always lines up with the first ['Data']['VarCharValue'] so I can get all the values in order, but if I loop through ['ResultSet']['Rows'] how do I isolate the first iteration as the column names to then populate with each other row? Or is there a better way to do this? Here is my json.dumps(ATHENAoutput) { "ResultSet": { "Rows": [{ "Data": [{ "VarCharValue": "postcode" }, { "VarCharValue": "CountOf" }] }, { "Data": [{ "VarCharValue": "1231" }, { "VarCharValue": "2" }] }, { "Data": [{ "VarCharValue": "1166" }, { "VarCharValue": "2" }] }, { "Data": [{ "VarCharValue": "3651" }, { "VarCharValue": "3" }] }, { "Data": [{ "VarCharValue": "2171" }, { "VarCharValue": "2" }] }, { "Data": [{ "VarCharValue": "4697" }, { "VarCharValue": "2" }] }, { "Data": [{ "VarCharValue": "4450" }, { "VarCharValue": "2" }] }, { "Data": [{ "VarCharValue": "4469" }, { "VarCharValue": "1" }] }], "ResultSetMetadata": { "ColumnInfo": [{ "Scale": 0, "Name": "postcode", "Nullable": "UNKNOWN", "TableName": "", "Precision": 2147483647, "Label": "postcode", "CaseSensitive": true, "SchemaName": "", "Type": "varchar", "CatalogName": "hive" }, { "Scale": 0, "Name": "CountOf", "Nullable": "UNKNOWN", "TableName": "", "Precision": 19, "Label": "CountOf", "CaseSensitive": false, "SchemaName": "", "Type": "bigint", "CatalogName": "hive" }] } }, "ResponseMetadata": { "RetryAttempts": 0, "HTTPStatusCode": 200, "Request…
has title: Parsing AWS ATHENA outputs
has comment: http://stackoverflow.com/comment/92106236
answer count: 2
tagged with: amazon-athena
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52584765
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92104796
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
possible better answer: http://stackoverflow.com/a/76535419
type: Question

http://stackoverflow.com/comment/91896332
comment on: http://stackoverflow.com/q/52477335
type: Comment
type: QuestionComment
score: 1
has text: Looks to me like the package is broken. There's a cyclic import between `jsonrpc` and `ethereum`. Maybe try upgrading the `ethereum` module.

http://stackoverflow.com/comment/92026495
has text: Hey, this is the output from your example: Hello from Thread-3 Hello from Thread-3 Hello from Thread-3 Hello from Thread-3 Hello from Thread-4 Hello from Thread-4 Hello from Thread-4 Hello from Thread-4 It is not what i want to achieve. In your example t1 runs through the for-loop till the break command, and only after that t2 starts running through the loop. But i wanted that thread2 starts to tun through the for loop after thread1 finishes its third iteration (after i = 2), and then both threads run simultaniously
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52538734
type: Comment

http://stackoverflow.com/a/52516984
has body: One correct way to solve this is to set the environment variable PYTHONPATH to the path which contains src. Then import src.class1 will always work, regardless of which directory you start in.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52516849
upvote count: 3
score: 3

pipeline
type: Tag
tags question: http://stackoverflow.com/q/52434568
tag name: pipeline
tags question: http://stackoverflow.com/q/52568025

http://stackoverflow.com/comment/91947266
has text: Set your pythonpath enviornment variable as pyspark isn't probably at your pythonpath variable. Go to location where pyspark folder is located and add that folder to your class path.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52502816
type: Comment

http://stackoverflow.com/comment/92175870
type: Comment
comment on: http://stackoverflow.com/a/52558507
score: 0
type: AnswerComment
has text: `find duplicates`would be perfect but I'm unable to locate such function.

http://stackoverflow.com/q/52445743
has comment: http://stackoverflow.com/comment/91834573
type: Question
tagged with: django-models
tagged with: django-forms
has comment: http://stackoverflow.com/comment/91834535
score: 0
has comment: http://stackoverflow.com/comment/91835519
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I am creating modelforms. I have managed to pull the fields i want to use from my tables (using postgresql): Table: class Response(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, on_delete=models.CASCADE) Response = models.TextField() Client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE) Planit_location = models.ForeignKey(Planit_location, on_delete=models.CASCADE) def __str__(self): return self.Response Form: class ResponseForm(forms.ModelForm): class Meta: model = Response fields = ('Response', 'Topic', 'Client') widgets = { 'Response': Textarea(attrs={'rows':3, 'cols':200}), } I want to now add in the Planit_locaiton field, but when i do i get the cursor error as stated in the title. Not sure why. Here is the Location table: class Planit_location(models.Model): Planit_location = models.CharField(max_length=255) def __str__(self): return self.Planit_location HTML: {% csrf_token %} Add Data {{ qform.as_table }} {{ rform.as_table }} Submit views.py: def adddata(request): if request.user.is_authenticated: username = request.user.username if request.method == 'POST': qform = QuestionForm(request.POST) rform = ResponseForm(request.POST) if qform.is_valid() and rform.is_valid(): qf = qform.save() rf = rform.save(commit=False) rf.Question = qf rf.save() return render(request, 'app/adddatatest.html', { "qform": QuestionForm(), "rform": ResponseForm(), "username": username, }) else: qform = QuestionForm() rform = ResponseForm() return render(request, 'app/adddatatest.html', { "qform": QuestionForm(), "rform": ResponseForm(), "username": username, }) EDIT Traceback: db_1 | 2018-09-21 15:35:12.284 UTC [58] ERROR: relation "app_planit_location" does not exist at character 153 db_1 | 2018-09-21 15:35:12.284 UTC [58] STATEMENT: DECLARE "_django_curs_140423080417024_3" NO SCROLL CURSOR WITH HOLD FOR SELECT "app_planit_location"."id", "app_planit_location"."Planit_location" FROM "app_planit_location" db…
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91834632
has title: Getting "cursor "_django_curs_140244427998976_3" does not exist" error
tagged with: django

http://stackoverflow.com/comment/92020166
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52539461
score: 0
has text: I'm assuming you're using structured arrays here, is that correct?

http://stackoverflow.com/q/52566050
linked to: http://stackoverflow.com/q/30901019
favorite count: 0
has comment: http://stackoverflow.com/comment/92069737
tagged with: python
has comment: http://stackoverflow.com/comment/92069585
has comment: http://stackoverflow.com/comment/92069777
type: AnsweredQuestion
score: 3
tagged with: pytorch
has answer: http://stackoverflow.com/a/52625776
has comment: http://stackoverflow.com/comment/92075183
accepted answer: http://stackoverflow.com/a/52625776
has comment: http://stackoverflow.com/comment/92069610
tagged with: torchvision
linked to: http://stackoverflow.com/q/52455886
type: Question
has comment: http://stackoverflow.com/comment/92069718
has title: Given 4 points, how to crop a quadrilateral from an image in pytorch/torchvision?
tagged with: image
upvote count: 3
has body: Problem is pretty straightforward - I want to crop a quadrilateral from an image in pytorch/torchvision. Given, I have four coordinates of the corners of this quadrilateral. Please note that these four points confine a quadrilateral within themselves which may or may not be a rectangle. So please refrain from suggesting answers involving slicing of the image. Please comment if I have missed any relevant detail.
has comment: http://stackoverflow.com/comment/92069668
has comment: http://stackoverflow.com/comment/92069879
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/91948878
has text: I figured out the problem, it was one of the outputs to the transaction objects - the public key. Its output was a point on a curve instead of a tuple, like i have in my personal computer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52496959
score: 0

http://stackoverflow.com/comment/91916511
type: Comment
has text: Make sure you have `gunicorn` in your `requirements.txt`: gunicorn==19.9.0
comment on: http://stackoverflow.com/a/52486067
type: AnswerComment
score: 0

http://stackoverflow.com/q/52558986
has body: def calculate_z_scores(raw_data): z_scores = [] for i in raw_data: z_score = raw_data.element - (sum(raw_data) / len(raw_data)) / raw_data.stdev append.z_scores(z_score) return z_scores This is the current code I have and I'm trying to use a loop to iterate through the raw_data list. I'm trying to calculate the Z-score for the current list element using the following formula: ("current element" -"average of " raw_data)/("standard deviation of " raw_data) And the append the calculated Z-score to the z_scores list. But when I run it it says: List has no attribute to element. I've never really worked with element so any help is appreciated.
favorite count: 0
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92056591
tagged with: python
has comment: http://stackoverflow.com/comment/92061040
has comment: http://stackoverflow.com/comment/92056643
type: Question
answer count: 2
score: -2
has title: List Elements in Python
has answer: http://stackoverflow.com/a/52559061
downvote count: 2
has comment: http://stackoverflow.com/comment/92056638
has answer: http://stackoverflow.com/a/52559010

http://stackoverflow.com/a/52578829
has comment: http://stackoverflow.com/comment/92093887
has comment: http://stackoverflow.com/comment/92093384
type: Answer
has comment: http://stackoverflow.com/comment/92092964
has comment: http://stackoverflow.com/comment/92092863
score: 1
has comment: http://stackoverflow.com/comment/92094299
has body: %2C is the URL Encoded hexadecimal value of ,. When you throw in %2C manually, the request package will try to make the actual value %2C safely URL-encoded, which will result into %252C (more specifically it will try to convert % into %25). You're trying to url encode values, but so is the request package, which means that it's double encoded. If you just write the , manually in the function it should work. steam_url = "https://store.steampowered.com/search?" search = get(steam_url, params = {'tags' : ','.join(list(map(str,[7743, 3871])))}) However, just as Hassan Voyeau says, you don't need to make the function so complicated, you can just write the values normally by {'tags': '7743,3871'}, as long as you don't try to URL-encode any values manually.
has comment: http://stackoverflow.com/comment/92098758
answers question: http://stackoverflow.com/q/52578774
has comment: http://stackoverflow.com/comment/92095797
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52578774
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/91937363
type: Comment
type: QuestionComment
has text: I understand the question now. Please check out https://stackoverflow.com/questions/12836385/how-can-i-interleave-or-create-unique-permutations-of-two-strings-without-recur/12837695#12837695
comment on: http://stackoverflow.com/q/52488523
score: 0

http://stackoverflow.com/q/52462622
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91920819
has comment: http://stackoverflow.com/comment/91945354
type: Question
has title: Error pops after running my first kivy code to display a blank screen
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/91875007
has body: I'm using pycharm and of course I'm new to kivy. I did the installation and everything as prescribed by a blog. And also kivy is there in my IDE packages list. Still I get following errors from kivy.app import App from kivy.uix.gridlayout import GridLayout class Container(GridLayout): pass class MainApp(App): def build(self): self.title = 'Awesome app!!!' return Container() if __name__ == "__main__": app = MainApp() app.run() Result /usr/bin/python3.7 /root/PycharmProjects/suraj/first_class.py [INFO ] [Logger ] Record log in /root/.kivy/logs/kivy_18-09-23_2.txt [INFO ] [Kivy ] v1.10.1 [INFO ] [Python ] v3.7.0 (default, Jun 27 2018, 14:40:03) [GCC 8.1.0] Traceback (most recent call last): File "/root/PycharmProjects/suraj/first_class.py", line 1, in &lt;module&gt; from kivy.app import App File "/usr/lib/python3/dist-packages/kivy/app.py", line 319, in &lt;module&gt; from kivy.base import runTouchApp, stopTouchApp File "/usr/lib/python3/dist-packages/kivy/base.py", line 26, in &lt;module&gt; from kivy.clock import Clock File "/usr/lib/python3/dist-packages/kivy/clock.py", line 362, in &lt;module&gt; from kivy._clock import CyClockBase, ClockEvent, FreeClockEvent, \ ModuleNotFoundError: No module named 'kivy._clock' Process finished with exit code 1
tagged with: kivy
tagged with: python-3.x
answer count: 0

openmdao
tags question: http://stackoverflow.com/q/52437416
tag name: openmdao
type: Tag

http://stackoverflow.com/a/77665188
upvote count: 3
answers question: http://stackoverflow.com/q/52468956
downvote count: 0
type: Answer
score: 3
has body: I'll add another plug: TorchExplorer (live demo here). It's sort of a combination of Netron and wandb.watch. It can: Interactively traverse model architectures, showing input/output tensor sizes and module parameters Visualize module input/output tensors, parameters, and associated gradients as histograms over the course of training (modeled off of wandb.watch) Directly integrate with weights and biases or serve standalone with a simple torchexplorer.watch call

http://stackoverflow.com/comment/91852683
has text: Index `1` will give you the second item. If you want the first item you need to use `0`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52455077
score: 0

http://stackoverflow.com/comment/92124588
comment on: http://stackoverflow.com/q/52580632
score: 0
type: Comment
type: QuestionComment
has text: I did what you told me and still no correct output. Something is wrong with my formula I'm not sure what it is. @figbeam

http://stackoverflow.com/comment/91957975
score: 1
has text: For example: *We'd like the Unassisted(U) list to be up to 20% of the Total units if possible, but we definitely need a minimum of 80% of the Total units to be Assisted(A) units.* => `A = math.ceil(0.8 * Total) ; U = Total - A`
comment on: http://stackoverflow.com/q/52508293
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52540204
type: Question
score: -2
tagged with: scikit-learn
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/52540926
accepted answer: http://stackoverflow.com/a/52540926
favorite count: 0
has body: I created a small MLPRegressor code for the Iris dataset that I had downloaded as a csv. Although I can use the load_iris() module for my code, my uni wants me to do it the old fashioned way. from sklearn.neural_network import MLPRegressor import pandas as pd data = pd.read_csv("iris.csv", header=None) # data = load_iris() attributes = data.iloc[:,:-1].values.tolist() outputs = data.iloc[:,-1].values.tolist() clf = MLPRegressor( # solver="sgd", # activation="logistic", # learning_rate_init=0.01, # max_iter=10000, # verbose=True, hidden_layer_sizes=[4] ) clf.fit(attributes, outputs) print(clf.predict([[5.4,3.9,1.3,0.4],[6.5,3.2,5.1,2.0]])) I get an error like this when I try to run: Traceback (most recent call last): File "prog4_scikit_learn.py", line 28, in &lt;module&gt; clf.fit(attributes, outputs) File "/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 620, in fit return self._fit(X, y, incremental=False) File "/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 378, in _fit intercept_grads, layer_units, incremental) File "/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 516, in _fit_stochastic coef_grads, intercept_grads) File "/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 230, in _backprop loss = LOSS_FUNCTIONS[loss_func_name](y, activations[-1]) File "/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/_base.py", line 194, in squared_loss return ((y_true - y_pred) ** 2).mean() / 2 TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('&lt;U32') dtype('&lt;U32') dtype('&lt;U32') Although I created a code using MLPClassifier for the same dataset and it works like a charm from sklearn.neural_network import MLPRegressor import pandas as pd data = pd.read_csv("iris.csv", header=None) attributes = data.iloc[:,:-1].values.tolist() outputs = data.ilo…
tagged with: python
has title: Scikit-Learn (TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32'))
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/52490138
has body: Sharing database across bounded contexts is not advisable as each microservice should have the capability to make changes on how it persist data. Allowing multiple microservices to manage databases would lead you to a death star pitfall pattern However, you might want to send a copy/updates of user data on the authentication context towards your payroll service. In this way, you can have independent data persistence strategies. One way to do this is to implement event emission strategy on your authentication context, this event emission strategy would be in-charge of broadcasting data changes made on the authentication context that subscribers residing from another bounded context can listen so that they can store a copy of your user data on their own persistence layers.
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52475303
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52475303
type: Answer

http://stackoverflow.com/comment/91812288
type: QuestionComment
has text: Possible duplicate of [Tensorflow SyntaxError with python 3.5.2](https://stackoverflow.com/questions/43875138/tensorflow-syntaxerror-with-python-3-5-2)
comment on: http://stackoverflow.com/q/52434321
score: 1
type: Comment

http://stackoverflow.com/a/68987209
score: 10
downvote count: 2
has comment: http://stackoverflow.com/comment/136322804
has body: Update (6/22): As it's now mid-2022, I thought I'd refresh my answer with a brand new approach I've been toying around with. I am pleased to announce a fast, modern library I have quite recently released, called dotwiz. The dotwiz library can be installed with pip: pip install dotwiz This is a tiny helper library that I've created, which makes dict objects safe to access by dot notation - such as a.b.c instead of a['b']['c']. From personal tests and benchmarks, it's actually a lot faster than something like make_dataclass - more info on this below. Additionally, one can also subclass from DotWiz or DotWizPlus, and this enables type hinting and auto-completion hints from an IDE such as PyCharm. Here is a simple example of that below: from dataclasses import asdict, make_dataclass from dotwiz import DotWiz class MyTypedWiz(DotWiz): # add attribute names and annotations for better type hinting! i: int s: str dw = MyTypedWiz(i=42, s='text') print(dw) # ✫(i=42, s='text') print(dw.to_dict()) # {'i': 42, 's': 'text'} If you still prefer to use dataclasses to model your data, I've included my original answer below that is mostly unchanged from years past. Benchmarks The follow results were timed on a Mac Pro with the M1 chip, Python 3.10.4, and with n=5000 iterations. Creating or instantiating the object: $ python -m timeit -n 5000 -s "from dotwiz import DotWiz" -c "DotWiz(i=42, s='text')" 5000 loops, best of 5: 425 nsec per loop $ python -m timeit -n 5000 -s "from dataclasses import make_dataclass" -c "X = make_dataclass('X', [('i', int), ('s', str)]); X(i=42, s='text')" 5000 loops, best of 5: 97.8 usec per loop These times are probably inflated, but in this particular case it looks like DotWiz is about 250x faster than make_dataclass. In practice, I would say it's about 100 times faster on average. Accessing a key by dot notation: $ python -m timeit -n 5000 -s "from dotwiz import DotWiz" -s "dw = DotWiz(i=42, s='text')" -c "dw.s.lower()" 5000 loops, best of 5: 39.7 nsec p…
type: Answer
upvote count: 12
answers question: http://stackoverflow.com/q/52534427
has comment: http://stackoverflow.com/comment/128980756

http://stackoverflow.com/comment/92008661
comment on: http://stackoverflow.com/q/52534393
type: Comment
type: QuestionComment
has text: @Iguananaut edited, thanks for the information !
score: 0

http://stackoverflow.com/a/52438589
has comment: http://stackoverflow.com/comment/92047480
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52435075
has body: Question: subprocess is not working You are using 2&gt;&amp;1, this is as Shell command and will not work until you use shell=True. You are right to, redirect stderr to stdout, as java -version will write to stderr. Do this for example: (Note the diffs, no list and stdout=, to yours!) check_process = subprocess.Popen("java -version 2&gt;&amp;1", shell=True, stdout=subprocess.PIPE) As this will get the expected output for me, you get (None, '') using: check_process = subprocess.Popen(["java", "-version", "2&gt;&amp;1"], stderr=subprocess.PIPE) The first tuple is the output of stdout which is not used in Popen. The second tuple is the output of stderr which is empty string. For testing purpose try inside QGIS: result = subprocess.check_output(["echo", "Hello World!"]) print(result)
answers question: http://stackoverflow.com/q/52435075
has comment: http://stackoverflow.com/comment/92033041
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52554388
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/52559604
tagged with: numpy
answer count: 2
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/52555827
accepted answer: http://stackoverflow.com/a/52559604
favorite count: 0
possible better answer: http://stackoverflow.com/a/52555827
tagged with: python
has body: I want to fill a masked array whose dtype is object (because I need to store masked ragged arrays) with a non scalar fill_value. Here's an example of a 2D array whose elements are 1D numpy arrays. Of course, I would like the fill_value to be an empty array. import numpy as np arr = np.array([ [np.arange(10), np.arange(5), np.arange(3)], [np.arange(1), np.arange(2), np.array([])], ]) marr = np.ma.array(arr) marr.mask = [[True, False, False], [True, False, True]] marr.fill_value = np.array([]) marr.filled() Unfortunately, it yields an error on the last line: ValueError: could not broadcast input array from shape (0) into shape (2,3) I could manually extract the mask, and apply it on an element-by-element algorithm; but it does not seem to be the right direction to me. Thank you !
score: 2
type: AnsweredQuestion
has title: numpy masked ragged array

http://stackoverflow.com/a/52547382
answers question: http://stackoverflow.com/q/52547323
score: 1
has body: First of all, order of operations. The line height = y_left + y_right / 2 should probably be height = (y_left + y_right) / 2 if you're trying to find the average of y_left and y_right. Division comes before addition, after all. After this, you're calculating the area, but you're not doing anything with it. You need to declare a variable before the loop starts, outside of the loop, and use it to store the area at every iteration. Basically, that means right before the for loop, add the line area_sum = 0 and then add a line at the very end of the for loop, right after the one where you calculate area: area_sum += area # add the area for this rectangle to the sum of areas of all rectangles After which, you can print area_sum and it should be what you want. Before, you were getting the out-of-scope error because the variable you declared was locked within the "scope" where it was created - within the for loop. By declaring this variable outside the for_loop, instead of inside of it, you should be able to print it outside the for loop as well.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92034394
upvote count: 1

http://stackoverflow.com/a/52491357
has comment: http://stackoverflow.com/comment/91923511
type: Answer
upvote count: 27
downvote count: 0
has comment: http://stackoverflow.com/comment/91923443
accepted answer of: http://stackoverflow.com/q/52491330
has comment: http://stackoverflow.com/comment/91924392
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52491330
score: 27
has comment: http://stackoverflow.com/comment/91923341
has body: Since you'd defined the __str__() method in your Company model, you can use the StringRelatedField() as class UserSerializer(serializers.ModelSerializer): company_name = serializers.StringRelatedField() class Meta: model = User fields = '__all__' UPDATE override the to_representation method class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def to_representation(self, instance): rep = super(UserSerializer, self).to_representation(instance) rep['company_name'] = instance.company_name.name return rep

http://stackoverflow.com/a/52527122
has body: You could try: for test, grade in zip(testSet, calculatedMarks): print("{} {}".format(test, grade)) Your example would print the entire lists in a single print call. This will iterate over the lists (creating pairs from each list using zip) and print each pair on it's own line. As in Dawg's answer, you can use a list comprehension and the str.join function instead of a for loop with a body to get this in a single line/print statement.
answers question: http://stackoverflow.com/q/52527098
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/67199782
downvote count: 0
answers question: http://stackoverflow.com/q/52553658
score: 6
has body: I explored the source code for openpyxl.worksheet.worksheet.Worksheet.__init__.py You can see it has the title attribute. For example to get the name of active worksheet you have to do this: >>> sheet = workbook.active >>> sheet.title "sheet 1" Where "sheet 1" is the name of the active sheet.
type: Answer
upvote count: 6

http://stackoverflow.com/a/52558690
answers question: http://stackoverflow.com/q/52558614
has comment: http://stackoverflow.com/comment/92056006
score: 0
type: Answer
has body: You can do this in 4 simple lines. male0 = ((df['Gender'] == 'M') &amp; (df['Showed'] == 0)).sum() female0 = ((df['Gender'] == 'F') &amp; (df['Showed'] == 0)).sum() male1 = ((df['Gender'] == 'M') &amp; (df['Showed'] == 1)).sum() female1 = ((df['Gender'] == 'F') &amp; (df['Showed'] == 1)).sum() Using apply, since you need two series and not one, you need to use apply. male0 = df'Gender', 'Showed'.apply(lambda row: row['Gender'] == 'M' and row['Showed'] == 0, axis=1).sum() female0 = df'Gender', 'Showed'.apply(lambda row: row['Gender'] == 'F' and row['Showed'] == 0, axis=1).sum() male1 = df'Gender', 'Showed'.apply(lambda row: row['Gender'] == 'M' and row['Showed'] == 1, axis=1).sum() female1 = df'Gender', 'Showed'.apply(lambda row: row['Gender'] == 'F' and row['Showed'] == 1, axis=1).sum() Using groupby counts = df.groupby(['Gender', 'Showed']).size().reset_index(name='Count')

http://stackoverflow.com/a/52570336
accepted answer of: http://stackoverflow.com/q/52570086
has comment: http://stackoverflow.com/comment/92079237
has comment: http://stackoverflow.com/comment/92077789
answers question: http://stackoverflow.com/q/52570086
has comment: http://stackoverflow.com/comment/92077722
has comment: http://stackoverflow.com/comment/92078050
score: 12
has comment: http://stackoverflow.com/comment/92077892
has body: You can use seaborn functions to plot graphs. Do dir(sns) to see all the plots. Here is your output in sns.scatterplot. You can check the api docs here or example code with plots here import seaborn as sns import pandas as pd df = pd.DataFrame([[ 1.82716998, -1.75449225], [ 0.09258069, 0.16245259], [ 1.09240926, 0.08617436]], columns=["x", "y"]) df["val"] = pd.Series([1, -1, 1]).apply(lambda x: "red" if x==1 else "blue") sns.scatterplot(df["x"], df["y"], c=df["val"]).plot() Gives Is this the exact input output you wanted? You can do it with pyplot, just importing seaborn changes pyplot color and plot scheme import seaborn as sns import matplotlib.pyplot as plt fig, ax = plt.subplots() df = pd.DataFrame([[ 1.82716998, -1.75449225], [ 0.09258069, 0.16245259], [ 1.09240926, 0.08617436]], columns=["x", "y"]) df["val"] = pd.Series([1, -1, 1]).apply(lambda x: "red" if x==1 else "blue") ax.scatter(x=df["x"], y=df["y"], c=df["val"]) plt.plot() Here is a stackoverflow post of doing the same with sns.lmplot
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92077757
type: Answer
upvote count: 12
downvote count: 0

http://stackoverflow.com/q/52539542
has comment: http://stackoverflow.com/comment/92019516
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52539943
has comment: http://stackoverflow.com/comment/92020143
type: Question
has comment: http://stackoverflow.com/comment/92019482
accepted answer: http://stackoverflow.com/a/52539943
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92020177
has body: def convBin(): cont = [] rest = [] dev = [] decimal = [] print("Ingrese el valor a convertir: ") valor = ast.literal_eval(input()) if isinstance(valor, int): while valor &gt; 0: z = valor // 2 resto = valor%2 valor = valor // 2 cont.append(z) rest.append(resto) cont.reverse() rest.reverse() dev.append(cont[0]) x = 0 while x &lt;= (len(rest) - 1): dev.append(rest[x]) x += 1 print(" ") print("Lista de devoluciones: ") print(dev) print("") elif isinstance(valor, float): a = valor // 1 b = valor % 1 while a &gt; 0: z = a // 2 resto = a%2 a = a // 2 cont.append(z) rest.append(resto) cont.reverse() rest.pop() dev.append(cont[1]) for i in rest: dev.append(rest[i]) print("Inserte el número de error minimo") num = input() while num &gt; 0: dec = b * 1 dec2 = dec//1 dec %= 1 decimal.append(dec2) print("Parte entera: ") print(dev) print("Parte decimal:") print(num) else: print("Ha aparecido un error") Its shows me an error that i can´t append a float into a list. After asking you a number, it controls which type of number is it. When it is an int, it doesn´t have any problem. But when it´s a float, it says that it can´t add a float into a list where it´s saved the numbers of the operations made before. Can someone explain it to me why I can´t append floats into a list or how can I solve the problem? Traceback (most recent call last): File "Converter.py", line 169, in convBin(); File "Converter.py", line 53, in convBin dev.append(rest[i]) TypeError: list indices must be integers or slices, not float Thanks.
has comment: http://stackoverflow.com/comment/92019425
upvote count: 2
has title: TypeError: list indices must be integers or slices, not float
tagged with: python
tagged with: append

http://stackoverflow.com/comment/91955688
has text: Wow, did not even see that. Thank you very much. I also saw in the source code that labels need to be flattened from (samples, 1) to (samples,). After doing that, its working! You are a life saver my friend.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52507306
type: QuestionComment

http://stackoverflow.com/comment/91884538
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52471206
has text: What happens when you try to use that code? Does it throw an ElementNotFound exception?

http://stackoverflow.com/q/52526653
has comment: http://stackoverflow.com/comment/91993083
has comment: http://stackoverflow.com/comment/91993228
has answer: http://stackoverflow.com/a/52526873
possible better answer: http://stackoverflow.com/a/52526752
type: AnsweredQuestion
upvote count: 2
has body: I am working on practice homework for my computer science class and I cannot seem to figure out how to solve for the question I have been given. Write a function that takes two numbers, one number to be divided by the second number. The function should return the number of times the second number goes into the first and the remainder. For example, if the function is sent 9 and 5, it should return 1 and 4. Any ideas? Codes I have Tried: def division_function(a, b): first = a//b second = a%b return(first, second) I have also tried the general division functions within Python, but that also does not seem to be working. The website we use is a bit tricky, as we are not using Python itself. Also, I understand the "general" Python code of division, I am just trying to find other eyes, perhaps to see where I am messing up.I have only been in this class for a few days and we have not yet gone over the material, but have already been given assignments. Also, if this helps, I often get this error code: Traceback (most recent call last): File "/home/runner/unit_tests.py", line 12, in test_testdivRem self.assertEquals(divWithRem(9,5),(1,4)) NameError: name 'divWithRem' is not defined
has comment: http://stackoverflow.com/comment/91993442
has comment: http://stackoverflow.com/comment/91993176
accepted answer: http://stackoverflow.com/a/52526743
type: Question
has comment: http://stackoverflow.com/comment/91993100
has comment: http://stackoverflow.com/comment/91993165
downvote count: 5
has comment: http://stackoverflow.com/comment/91993093
answer count: 3
has title: Python Division Function
has comment: http://stackoverflow.com/comment/91993089
favorite count: 0
has comment: http://stackoverflow.com/comment/91993325
has answer: http://stackoverflow.com/a/52526743
has comment: http://stackoverflow.com/comment/91993096
has answer: http://stackoverflow.com/a/52526752
score: -3
tagged with: python

http://stackoverflow.com/a/71998386
has body: If it shows an import error, it most likely means you didn't set the environment variable for FLASK_APP properly. If you're on windows, use $env:FLASK_APP="nameofyourapp.py" On Mac and Linux bash: set FLASK_APP=nameofyourapp.py If it still shows the error, make sure you're in the powershell terminal not the Python one.
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/52581576
type: Answer

http://stackoverflow.com/comment/91842155
score: 0
type: QuestionComment
has text: With the greatest respect, you seem to be considering them as competing tools. They're not. Pandas _should_ be faster for proper data crunching if it is called for, but that doesn't mean you wouldn't also want to put at least some logic in jinja in order to get something rendered as you wanted. The pure-python method doesn't seem to have been mentioned in your question.
type: Comment
comment on: http://stackoverflow.com/q/52449492

http://stackoverflow.com/comment/91855173
type: Comment
comment on: http://stackoverflow.com/a/52453764
type: AnswerComment
has text: Thanks for your help and pointing out the issues in my code! I get the point about advancing the current pointer with cur = cur.next. However, I have two follow-up questions: 1) What does the cur.next = l1 or l2 do? and 2) What does the cur = newList do/ how is newList.next able to return the correct result?
score: 0

http://stackoverflow.com/comment/91867938
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52435726
score: 0
has text: Thank you everyone! I resolved this problem by execute below command `$ cp /usr/local/etc/odbc.ini /etc/odbc.ini` `$ cp /usr/local/etc/odbcinst.ini /etc/odbcinst.ini`

http://stackoverflow.com/comment/91821840
type: QuestionComment
comment on: http://stackoverflow.com/q/52438941
score: 0
has text: You said you're limited to two keywords but you show three in your code (which will not work).
type: Comment

http://stackoverflow.com/q/52436394
type: Question
tagged with: numpy
tagged with: dataframe
has body: I have a pandas series and I am taking its value count using value_counts.I need to get it into a list. I tried to_list() but got error. df['AAA'].value_counts(sort=True).to_list() If I run, df['AAA'].value_counts(sort=True) , I will get something like 3 301 2 185 7 75 4 25 5 16 Name: AAA, dtype: int64 How to convert this into : [301,185,75,25,16]
has title: How to convert a pandas value_counts into a python list
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52436410
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52436410
upvote count: 1

http://stackoverflow.com/comment/130648677
score: 1
has text: this internalConsole setting mght or does have an issue re input https://stackoverflow.com/questions/73993577/in-vs-code-when-running-a-python-program-via-the-debugger-with-internalconsole
type: AnswerComment
comment on: http://stackoverflow.com/a/52781131
type: Comment

http://stackoverflow.com/comment/109309862
score: 0
type: Comment
type: QuestionComment
has text: This is really minor, but it's a REST framework for Django, it is not "Django's REST framework". The Django project doesn't own or control the REST framework.
comment on: http://stackoverflow.com/q/52439290

http://stackoverflow.com/q/52490109
upvote count: 7
has body: How can I make it that when the user enters input its on the same line as the print statement like for example for the code snippet below. The output becomes: Enter grade for course 1: A Enter credits for course 1: 4 For now this is what I get: Enter grade for course 1: A Enter credits for course 1: 4 Here is the code snippet for i in range(1,coursenumber+1): print("Enter grade for course ", i,":", end =""), grade=str(input()) print("Enter credits for course", i,":", end =" ") credit=int(input()) totalgpa+=translate(credit,grade) totalcredit+=credit
has answer: http://stackoverflow.com/a/52490212
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52490251
possible better answer: http://stackoverflow.com/a/52490212
type: Question
has answer: http://stackoverflow.com/a/69001565
score: 5
has comment: http://stackoverflow.com/comment/91921263
has answer: http://stackoverflow.com/a/52490202
has comment: http://stackoverflow.com/comment/91921004
has title: Python: How do I put print statement and input on same line?
accepted answer: http://stackoverflow.com/a/52490202
has comment: http://stackoverflow.com/comment/91921197
has comment: http://stackoverflow.com/comment/91921216
tagged with: python
answer count: 4
favorite count: 0
tagged with: python-3.x
downvote count: 2
has comment: http://stackoverflow.com/comment/91921284

http://stackoverflow.com/comment/92006231
type: Comment
has text: ok, ill do that
type: QuestionComment
comment on: http://stackoverflow.com/q/52530922
score: 0

http://stackoverflow.com/a/52580726
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Don't take the variables when creating that function. def pay(): You are defining them in your function: def pay(): hrs = int(input("Hours worked")) rate = float(input("Pay grade")) finalPay = (hrs * rate) if hrs &gt; 40: finalPay = (((finalPay - 40) * 1.5) + finalPay) return finalPay And use the function like: print(pay())
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52580685
accepted answer of: http://stackoverflow.com/q/52580685

http://stackoverflow.com/a/52520021
score: 0
answers question: http://stackoverflow.com/q/52519848
type: Answer
has body: Try this: for i in y: lst.append((v for k,v in i.items()))

http://stackoverflow.com/q/52452237
tagged with: pygame
has comment: http://stackoverflow.com/comment/91848195
favorite count: 0
linked to: http://stackoverflow.com/q/46714719
type: UnansweredQuestion
has body: The code works if you write pygame.K_UP, or whatever key you want, being K_UP a constant of pygame. However, I need to write a function which takes the key as an input. For example: def player(keys) """ keys is a list """ keystate = pygame.key.get_pressed() if keystate[pygame.keys[0]]: etc It gives me the following error: "AttributeError: module 'pygame' has no attribute 'keys' " The objective of this is to create multiple instances of players with diferent controls, so controls are stored in a list: keys = [["LEFT", "UP", "RIGHT"], ["a", "w", "d"], ["4", "8", "6"]] keys = [["pygame.K_" + e for e in elem] for elem in keys] # join pygame.K_ to each element players = list() for i in range(num_players): players.append(Player(keys[i])) SOLUTION: Finally, the comment of jasonharper has led me to the solution. Looking for getattr(pygame, key) I found this page with the same question: Pygame, get key object from character keys = [["LEFT", "UP", "RIGHT"], ["a", "w", "d"], ["4", "8", "6"]] keys = [[getattr(pygame, "K_" + e) for e in elem] for elem in keys] This solved it for me. Many thanks to all.
tagged with: python
has comment: http://stackoverflow.com/comment/91847847
has answer: http://stackoverflow.com/a/52452387
has comment: http://stackoverflow.com/comment/91847886
type: Question
has comment: http://stackoverflow.com/comment/91863251
has title: When writing pygame.keys[0] it does not take the value of keys[0]
has comment: http://stackoverflow.com/comment/91847872
score: 0
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/91856423
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52457055
has text: Can you show the things you've tried that don't work?

http://stackoverflow.com/a/52544258
type: Answer
answers question: http://stackoverflow.com/q/52543442
score: 0
has comment: http://stackoverflow.com/comment/92075266
has body: Try this or similar within a function, you may be able to avoid the output str all together. If you wish to handle lowercase's as well check the chr() integer value and if above 96, subtract 32: def convert(inputString): outputString = "" for letter in inputString: if ord(letter) &gt;= 65 and ord(letter) &lt; 86: outputString += letter + chr((ord(letter) + 1)) elif ord(letter) &gt;= 97 and ord(letter) &lt; 122: outputString += chr(ord(letter) - 32) + chr(ord(letter) - 31) elif letter == 'z' or letter == 'Z': outputString += "ZA" else: outputString += letter return outputString wordToConvert = "ABC abc" print(convert( wordToConvert)) wordToConvert = "Hello there" print(convert( wordToConvert)) Output: ABBCCD ABBCCD HIEFLMLMOP TUHIEFRSEF https://docs.python.org/2/library/functions.html#chr https://www.quora.com/What-is-difference-in-the-ASCII-values-of-uppercase-and-lowercase-letters

http://stackoverflow.com/comment/91813916
type: QuestionComment
comment on: http://stackoverflow.com/q/52435166
score: 1
has text: thanks @student - you are more than a student, a teacher.
type: Comment

dictionary
tags question: http://stackoverflow.com/q/52489565
tags question: http://stackoverflow.com/q/52563826
tags question: http://stackoverflow.com/q/52493104
tags question: http://stackoverflow.com/q/52524092
tags question: http://stackoverflow.com/q/52564644
tags question: http://stackoverflow.com/q/52538578
tags question: http://stackoverflow.com/q/52556009
tags question: http://stackoverflow.com/q/52472095
tags question: http://stackoverflow.com/q/52536562
tags question: http://stackoverflow.com/q/52582859
tags question: http://stackoverflow.com/q/52442073
tags question: http://stackoverflow.com/q/52504153
tags question: http://stackoverflow.com/q/52562941
tags question: http://stackoverflow.com/q/52456187
tags question: http://stackoverflow.com/q/52498733
tags question: http://stackoverflow.com/q/52468430
tags question: http://stackoverflow.com/q/52452233
tags question: http://stackoverflow.com/q/52565668
tags question: http://stackoverflow.com/q/52484043
tags question: http://stackoverflow.com/q/52482027
tags question: http://stackoverflow.com/q/52443694
tags question: http://stackoverflow.com/q/52555385
tags question: http://stackoverflow.com/q/52458754
tags question: http://stackoverflow.com/q/52439646
tags question: http://stackoverflow.com/q/52491417
tags question: http://stackoverflow.com/q/52513662
tags question: http://stackoverflow.com/q/52579114
tags question: http://stackoverflow.com/q/52518946
tags question: http://stackoverflow.com/q/52554702
tags question: http://stackoverflow.com/q/52501647
tags question: http://stackoverflow.com/q/52466372
tags question: http://stackoverflow.com/q/52515687
tags question: http://stackoverflow.com/q/52517294
tags question: http://stackoverflow.com/q/52547805
tags question: http://stackoverflow.com/q/52440485
tags question: http://stackoverflow.com/q/52512819
tags question: http://stackoverflow.com/q/52460156
tags question: http://stackoverflow.com/q/52484244
tags question: http://stackoverflow.com/q/52492913
tags question: http://stackoverflow.com/q/52529122
tags question: http://stackoverflow.com/q/52434588
tags question: http://stackoverflow.com/q/52452524
tags question: http://stackoverflow.com/q/52511590
tags question: http://stackoverflow.com/q/52577249
tags question: http://stackoverflow.com/q/52432988
tags question: http://stackoverflow.com/q/52440403
tags question: http://stackoverflow.com/q/52462238
tags question: http://stackoverflow.com/q/52522118
tags question: http://stackoverflow.com/q/52499724
tags question: http://stackoverflow.com/q/52527702
tags question: http://stackoverflow.com/q/52578002
tags question: http://stackoverflow.com/q/52502508
tags question: http://stackoverflow.com/q/52553867
tags question: http://stackoverflow.com/q/52508696
tags question: http://stackoverflow.com/q/52539181
tags question: http://stackoverflow.com/q/52523259
tag name: dictionary
tags question: http://stackoverflow.com/q/52584914
tags question: http://stackoverflow.com/q/52581665
tags question: http://stackoverflow.com/q/52552185
tags question: http://stackoverflow.com/q/52431821
tags question: http://stackoverflow.com/q/52570466
tags question: http://stackoverflow.com/q/52467994
tags question: http://stackoverflow.com/q/52452007
tags question: http://stackoverflow.com/q/52531984
tags question: http://stackoverflow.com/q/52513200
tags question: http://stackoverflow.com/q/52432919
tags question: http://stackoverflow.com/q/52579725
tags question: http://stackoverflow.com/q/52538972
tags question: http://stackoverflow.com/q/52526546
tags question: http://stackoverflow.com/q/52468270
tags question: http://stackoverflow.com/q/52502605
tags question: http://stackoverflow.com/q/52432695
tags question: http://stackoverflow.com/q/52494015
tags question: http://stackoverflow.com/q/52572006
tags question: http://stackoverflow.com/q/52542867
tags question: http://stackoverflow.com/q/52430910
tags question: http://stackoverflow.com/q/52490250
tags question: http://stackoverflow.com/q/52435678
tags question: http://stackoverflow.com/q/52562882

http://stackoverflow.com/comment/92078865
type: Comment
type: QuestionComment
has text: I see, thanks for explaining that
comment on: http://stackoverflow.com/q/52570192
score: 0

http://stackoverflow.com/comment/91814527
has text: I'm in favor of the refactoring, but don't use list comprehensions for side-effects (like `print`ing). That just means making temporary `list`s full of `None` for no reason, when a plain loop `for ind, val in enumerate(gifts):` `if ind >= key: print(val)` would do the job just fine. Beyond the temporary, any use of functional programming tools (e.g. listcomps) for side-effects is a maintenance nightmare; functional styles are intended to minimize side-effects and action at a distance.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52435479

http://stackoverflow.com/comment/92032726
has text: It means that the items don't have sub-items.
comment on: http://stackoverflow.com/q/52546461
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52579167
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52580042
upvote count: 0
has comment: http://stackoverflow.com/comment/92093616
type: Question
score: -2
has comment: http://stackoverflow.com/comment/92093837
has body: Given a string, we must split it into two contiguous substrings, then determine the minimum number of characters to change to make the two substrings into anagrams of one another. def anagram(s): flag = 0 if len(s)%2 != 0: return -1 else: temp1,temp2 = s[:len(s)//2],s[len(s)//2:] temp1 = ''.join(sorted(temp1)) temp2 = ''.join(sorted(temp2)) for i in temp1: flag1 = temp2.count(i) if flag1&gt;1: flag1 = 1 else: flag1 = flag1 flag += flag1 return flag I'm sort of all over the place and highly complicating this without getting it right. Is there any way to simplify the logic?
has comment: http://stackoverflow.com/comment/92093397
has title: Minimum number of manipulations for anagrams
downvote count: 2
tagged with: anagram

http://stackoverflow.com/q/52517882
score: 2
upvote count: 2
tagged with: selenium
tagged with: web-scraping
tagged with: scrapy
type: Question
has title: i want to click a link of website using scrapy python
accepted answer: http://stackoverflow.com/a/52519345
has comment: http://stackoverflow.com/comment/91975742
has body: import scrapy from selenium import webdriver class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://ozhat-turkiye.com/en/brands/a', ] I want to click a link def __init__(self): self.drivers = webdriver.Firefox('C:/Program Files (x86)\Mozilla Firefox') I want to click a link def parse(self, response): for title in response.css('div.tabledivinlineblock a.tablelink50::attr(href)').extract(): yield {'title': title, 'response': response.url } # i want to click this a tag next = self.driver.find_element_by_xpath('//*[@id="maincontent_DataPager"]/a[last()]') # follow pagination links # for href in response.css('span#maincontent_DataPager a:last-child'): # # yield response.follow(href, self.parse) next_page = response.css('span#maincontent_DataPager a:last-child::attr(href)').extract_first().strip() if next_page is not None: yield response.follow(next_page, callback=self.parse)
has answer: http://stackoverflow.com/a/52519345
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion

ascii
tags question: http://stackoverflow.com/q/52509190
tags question: http://stackoverflow.com/q/52538443
type: Tag
tag name: ascii

http://stackoverflow.com/a/52587747
has comment: http://stackoverflow.com/comment/103646872
has body: The solution is to assign the ContentStream that is being iterated and changed to the page afterwards before passing it to the PdfFileWriter: page[NameObject('/Contents')] = content writer.addPage(page) I found the solution reading this and this.
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/127993222
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52499339
has comment: http://stackoverflow.com/comment/103648829
accepted answer of: http://stackoverflow.com/q/52499339

http://stackoverflow.com/q/52521782
has answer: http://stackoverflow.com/a/52522274
type: Question
score: -2
has comment: http://stackoverflow.com/comment/91983077
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91983791
accepted answer: http://stackoverflow.com/a/52522274
favorite count: 0
tagged with: python-3.x
has body: I have two series, and every cell of both series contains a list of elements of random length. My goal is to perform a cross-join between these two series, but only join rows if at least one element of a series' cell's list matches an element of a cell's list in the other series. For example: series_a 0 [1geor, georg, eorge, orges, rgesq, gesqu, esq... 1 [1mark, marks, arksq, rksqu, ksqua, squar, qua... 2 [1prim, primr, rimro, imros, mrose, roses, ose... 3 [1shan, shank, hanka, ankar, nkars, karst, wew... 4 [1stka, stkat, tkath, katha, athar, thari, har... series_b 0 [115br, 15bro, 5broa, broad, roadw, oadwa, adway] 1 [11par, 1park, parkp, arkpl, rkpla, kplac, place] 2 [125we, 25wes, 5west, west2, est25, st25t, t25th] 3 [135ma, 35mad, 5madi, madis, adiso, dison] 4 [135we, 35wes, 5west, west4, est41] I want to check, for every row in series_a, if at least one element in a row = an element in a row of series_b, and if yes, join those rows together in a new dataframe. So, looking at series_a's first row, checking if '1geor' exists in the 1st, 2nd, 3rd. etc. list of series_b; if TRUE, perform the join, and if FALSE, do not perform the join. To clarify, the returned dataframe should have two columns, where the first column contains cells from series_a and the second column contains cells from series_b. For all rows in this dataframe, the list in the 1st column should have at least one element that can be found in the list of the 2nd column. For example: returned_df 0 [115br, 15bro, 5broa] | [15bro, abcde, 12345, hello, world, test1] 1 [11par, 1park, parkp, arkpl, rkpla] | [parkp, broad] 2 [125we, 25wes, 5west, west2, est25, st25t, t25th] | [t25th, sadlf, 234lgk] ... If an element in a row in series_a occurs in more than one row in series_b, all combinations of matching rows should appear in the final dataframe. What is the most efficient Python code for this exercise? The code: any(elem in b for elem in a) easily answers this for two specific lists, but I want to iterate…
tagged with: element
has title: Pandas - iterate through dataframe and join if any element of a list matches any element of another list
tagged with: python
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91983176
downvote count: 2
has comment: http://stackoverflow.com/comment/91983346

http://stackoverflow.com/comment/91985989
comment on: http://stackoverflow.com/a/52522429
type: AnswerComment
has text: @ShenuAmaya Read the SO question about @classmethods. The `cls` is autoprovided when you call the method, same as for instancemethods that get a `self` as first parameter autoprovided. `cls` would be "the class itself". `last+1` because the `range(1,100)` produces 1..99 - not to 100. `randint(1,100)` would produce from 1 to 100. See [range-doku](https://docs.python.org/3/library/functions.html#func-range)
type: Comment
score: 1

http://stackoverflow.com/comment/91869999
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52463990
has text: @vonniklasson I've added output to my topic

http://stackoverflow.com/q/52543824
type: Question
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/92028134
has comment: http://stackoverflow.com/comment/92027544
has title: Plotting multiple columns of different sizes with Pandas
type: UnansweredQuestion
has body: I'm fairly new to Pandas, but typically what I do with data (when all columns are of equal sizes), I build np.zeros(count) matrices, then use a for loop to populate the data from a text file (np.genfromtxt()) to do my graphing and analysis in matplotlib. However, I am now trying to implement similar analysis with columns of different sizes on the same plot from a CSV file. For instance: data.csv: A B C D E F 1 2 3 4 5 6 2 3 4 5 6 7 3 4 5 6 4 5 df = pandas.read_csv('data.csv') ax = df.plot(x = 'A', y = 'B') df.plot(x = 'C', y = 'D', ax = ax) df.plot(x = 'E', y = 'F', ax = ax) This code plots the first two on the same graph, but the rest of the information is lost (and there are a lot more columns of mismatched sizes, but the x/y columns I am plotting are the all the same size). Is there an easier way to do all of this? Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/52545149
has comment: http://stackoverflow.com/comment/92028578

cluster-analysis
tags question: http://stackoverflow.com/q/52560683
tags question: http://stackoverflow.com/q/52514645
tags question: http://stackoverflow.com/q/52522050
tags question: http://stackoverflow.com/q/52517438
tags question: http://stackoverflow.com/q/52539910
tags question: http://stackoverflow.com/q/52587973
tag name: cluster-analysis
type: Tag
tags question: http://stackoverflow.com/q/52556885
tags question: http://stackoverflow.com/q/52512987

http://stackoverflow.com/comment/92077714
type: QuestionComment
has text: @Kasrâmvd you mean like this?
comment on: http://stackoverflow.com/q/52570452
type: Comment
score: 0

http://stackoverflow.com/q/52518957
type: UnansweredQuestion
tagged with: pdfminer
type: Question
has comment: http://stackoverflow.com/comment/91989372
has title: Python pdfminer not showing utf-8 characters properly
has body: I'm extracting text in french from PDF using pdfminer and python. The problem is that I don't see the accents like éàã... etc. For example: on se place (ce qu'il faut faire) sur le terrain social, la famille qu6becoise demeure au fond ce qu'elle n'a jamais cess6 d'Etre, malgr6 certains bouleversements apparents. Les donn~es sociales et familiales qu6becoises ne sont pas les donnes francaises. The command I'm using is: pdf2txt.py -c utf-8 sample.pdf I've installed CJK Languages, but still doesn't work. I'm running python 2.7.10. Any suggestion on how to properly display the characters ?
score: 0
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/91990699
answer count: 0

tuples
tags question: http://stackoverflow.com/q/52454582
tags question: http://stackoverflow.com/q/52500778
tags question: http://stackoverflow.com/q/52505386
tags question: http://stackoverflow.com/q/52484459
tags question: http://stackoverflow.com/q/52442388
tags question: http://stackoverflow.com/q/52548555
tags question: http://stackoverflow.com/q/52578360
tags question: http://stackoverflow.com/q/52520402
tags question: http://stackoverflow.com/q/52562340
tags question: http://stackoverflow.com/q/52507548
tags question: http://stackoverflow.com/q/52451794
tags question: http://stackoverflow.com/q/52431924
tags question: http://stackoverflow.com/q/52564275
tag name: tuples
tags question: http://stackoverflow.com/q/52504709
tags question: http://stackoverflow.com/q/52573594
tags question: http://stackoverflow.com/q/52498276
tags question: http://stackoverflow.com/q/52434752
tags question: http://stackoverflow.com/q/52530777
tags question: http://stackoverflow.com/q/52494391
tags question: http://stackoverflow.com/q/52563793
tags question: http://stackoverflow.com/q/52587956
tags question: http://stackoverflow.com/q/52552994
tags question: http://stackoverflow.com/q/52587693
tags question: http://stackoverflow.com/q/52488375
tags question: http://stackoverflow.com/q/52567038
tags question: http://stackoverflow.com/q/52499562
tags question: http://stackoverflow.com/q/52450348
type: Tag

http://stackoverflow.com/a/52682780
has comment: http://stackoverflow.com/comment/92525958
upvote count: 2
has body: This is an Audio Event Detection problem. If the sound is always the same and there are no other sounds at the same time, it can probably be solved with a Template Matching approach. At least if there is no other sounds with other meanings that sound similar. The simplest kind of template matching is to compute the cross-correlation between your input signal and the template. Cut out an example of the sound to detect (using Audacity). Take as much as possible, but avoid the start and end. Store this as .wav file Load the .wav template using librosa.load() Chop up the input file into a series of overlapping frames. Length should be same as your template. Can be done with librosa.util.frame Iterate over the frames, and compute cross-correlation between frame and template using numpy.correlate. High values of cross-correlation indicate a good match. A threshold can be applied in order to decide what is an event or not. And the frame number can be used to calculate the time of the event. You should probably prepare some shorter test files which have both some examples of the sound to detect as well as other typical sounds. If the volume of the recordings is inconsistent you'll want to normalize that before running detection. If cross-correlation in the time-domain does not work, you can compute the melspectrogram or MFCC features and cross-correlate that. If this does not yield OK results either, a machine learning model can be trained using supervised learning, but this requires labeling a bunch of data as event/not-event.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52572693
downvote count: 0

http://stackoverflow.com/q/52527482
downvote count: 1
type: Question
tagged with: discord.py
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52527696
tagged with: discord
has comment: http://stackoverflow.com/comment/91994602
has answer: http://stackoverflow.com/a/52531478
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Positional error when trying to specify member
upvote count: 1
has body: Hi I'm trying to get a member name rather than the author name I've tried a few methods like for member is message.server.members: which returned multiple results with every member in the server and tried member: discord.Member as a signature which produced an error: Heres what I'm working with: async def on_message_delete(self, message): server = message.server author = message.author role = get(server.roles, name="Powerbot") channel = get(message.server.channels, name="mod-log") time = datetime.utcnow() cleanmsg = message.content for i in message.mentions: cleanmsg = cleanmsg.replace(i.mention, str(i)) fmt = '%H:%M:%S' name = author name = " ~ ".join((name.name, name.nick)) if name.nick else name.name if role not in author.roles: infomessage = "A message by {}, was deleted in {} by {}".format(message.author.mention, message.channel.mention, member,mention) delmessage = discord.Embed(description=infomessage, colour=discord.Color.purple(), timestamp=time) delmessage.add_field(name="Message:", value=cleanmsg) delmessage.set_footer(text="User ID: {}".format(message.author.id)) delmessage.set_author(name=name + " message deleted.", icon_url=message.author.avatar_url) delmessage.set_thumbnail(url="http://i.imgur.com/fJpAFgN.png") try: await self.bot.send_message(channel, embed=delmessage) except: pass The line specifically where member.mention is. infomessage = "A message by {}, was deleted in {} by {}".format(message.author.mention, message.channel.mention, member.mention) Example output: A message by author was deleted in channel by member. If anyone could help that would be appreciated.
has comment: http://stackoverflow.com/comment/91994526

http://stackoverflow.com/comment/92094202
score: 0
has text: What Python version does your virtual env uses?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52579498

http://stackoverflow.com/comment/92017617
type: QuestionComment
comment on: http://stackoverflow.com/q/52535359
has text: what should happen to negative values?
score: 0
type: Comment

http://stackoverflow.com/a/52469337
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52468911
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52468911
has body: Both methods are fine. I'd recommend to use the method which causes less work, i.e. if the external thread acquires the lock ten times per Trio task's once, then use a thread lock, and vice versa. A threading.Lock always blocks the thread trying to acquire it, so taking it from Trio either requires a separate thread (which your first method already does anyway), or the lock's holder needs to signal the Trio task that it has released the lock (which your second method does anyway), so there is no clear advantage for implementing a lower-level solution.
type: AcceptedAnswer

http://stackoverflow.com/comment/91887282
type: QuestionComment
comment on: http://stackoverflow.com/q/52472795
score: 0
type: Comment
has text: what do you mean by decode?

http://stackoverflow.com/q/52469566
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pytorch
score: 1
linked to: http://stackoverflow.com/q/42480111
upvote count: 1
type: Question
has title: How to get weights shape for each layer?
has answer: http://stackoverflow.com/a/52469645
has body: There is a good question how to get model summary in pytorch Model summary in pytorch but it doesn't output shape of weights. Is it possible also to output shape of weights for each layer?

http://stackoverflow.com/q/52434785
has title: Remove whole nested dict by finding if a value is in a list
has body: I am trying to make a choropleth map of values within zip codes in the US. I have a json file with the points for the ZCTA5CE area that corresponds to each zip code. I am using the Folium package. Right now the mapping works, but is painfully slow -- 10s of minutes based on other items running on my machine, and making interacting with the map by sliding and zooming nearly impossible -- because of the size of the json file (482.2M) and thus the resulting dict. The data I want to plot does not have information for all zip codes, so I would like to remove the information in the zip code dict associated with those zip codes that are not in my data. My question is: how can I iterate over a dict of zip code info and remove the dicts that are not in a list of zips I specify. To be clearer about the structure of the dict I'm working with: zip_code_geo_dict.keys() gives: dict_keys(['type', 'features']) where zip_code_geo_dict['type'] is a string, and zip_code_geo_dict['features'] is a list. Now, zip_code_geo_dict['features'][0] is: {'type': 'Feature','geometry': {'type': 'MultiPolygon', 'coordinates': [[[[-88.252618, 32.92675], [-88.249724, 32.93242], **bajillions of lines of coordinates here** [-88.34043199999999, 32.991199]]]]}, 'properties': {'ZCTA5CE10': '35442', 'AFFGEOID10': '8600000US35442', 'GEOID10': '35442', 'ALAND10': 610213891, 'AWATER10': 10838694}} My source data can change, so the actual list of zip codes I want to map is dynamic. That said, I can always create a list: zips_of_interest = ['15210', '15222'] How can I iterate through the zip_code_geo_dict to remove the coordinate information based on zip_code_geo_dict['features']['properties']['ZCTA5CE10'] NOT IN zips_of_interest? It is necessary to keep the over-arching dict structure, such that the filtered version zip_code_geo_dict['features'] is in the same "spot" as the original (it needs to be a dict as the second key in the larger zip_code_geo_dict object). I think it's relevant to note that I would like…
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52434996
has comment: http://stackoverflow.com/comment/91908189
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52434898
score: 0
has answer: http://stackoverflow.com/a/52434898
tagged with: folium
has answer: http://stackoverflow.com/a/52434996
tagged with: geo
tagged with: python-3.x

http://stackoverflow.com/q/52583619
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/28009873
type: UnansweredQuestion
has body: As I know of in Pandas, boolean selection with loc is much faster than the one with just using boolean selection Here is my experiment: First experiment with single column %%timeit df[df['종가']&gt;9700]['시가총액'] &gt;&gt; 727 µs ± 2.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit df.loc[df['종가']&gt;9700, "시가총액"] &gt;&gt; 362 µs ± 456 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) Using loc is much faster as I expected Second experiment with multiple columns %%timeit df[df['종가']&gt;9700]'시가총액', '유통시가총액' &gt;&gt; 1.15 ms ± 22.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit df.loc[df['종가']&gt;9700, ['시가총액', '유통시가총액']] &gt;&gt; 1.47 ms ± 50 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In this time, using loc is slower... I want to know why this performance difference happend
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/52587849
upvote count: 2
type: Question
has title: Pandas boolean selection with `loc` is not always faster?
tagged with: indexing
tagged with: performance
tagged with: dataframe
tagged with: pandas
linked to: http://stackoverflow.com/q/45196149
has comment: http://stackoverflow.com/comment/92102323
answer count: 1

http://stackoverflow.com/comment/92150426
type: Comment
comment on: http://stackoverflow.com/a/52607858
has text: Apologies for my insistence but I always want to know the opinion of senior data scientists about how some libraries or algorithms work etc. Surprisingly enough I may come up with some cases which even senior data scientists have not exactly encountered (separate validation set, `GridSearchCV`, `PredefinedSplit`, training & validation results). In any case, thank you very much for your time :)
score: 0
type: AnswerComment

http://stackoverflow.com/a/52604844
has body: Is your minimum unit of mesurement 6 months ? I hope not, but if yes, then I would sugges that you dont try to predict the next 1 month. Seasonality within a year aside, you would need daily volume measurements.. I would be very worried to build anything on monthly or even weekly numbers. In terms of modelling techniques, please stick to simple regression methods like kungphu suggests.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52487832

http://stackoverflow.com/comment/92000844
has text: Your program seems to work fine (I am using python 2, however, so when I input data I have to put it in double quotes. It is very dangerous to use "input()" in python2, we are supposed to use "raw_input()" instead) The reason your program doesn't print anything is because when you call createPRICE() it clears the screen. I also noticed that you call createINV() twice, but you only save the dictionary the second time you call it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52529387
type: AnswerComment

http://stackoverflow.com/comment/91897333
type: Comment
comment on: http://stackoverflow.com/a/52468744
type: AnswerComment
has text: I know, but i don't know the range. I want data based on the explicit index!
score: 0

http://stackoverflow.com/a/52471003
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91884182
answers question: http://stackoverflow.com/q/52470949
has body: It looks like you are missing a '+' in your first print statement. Should be print("You spent more than 20 dollars per day on food in" +str(over20food) + "days of the week")
has comment: http://stackoverflow.com/comment/91918843
type: Answer
accepted answer of: http://stackoverflow.com/q/52470949
upvote count: 1
score: 1

http://stackoverflow.com/comment/91931438
score: 1
type: AnswerComment
type: Comment
has text: Please take a look at the second half of the question. This use case is specifically mentioned by OP.
comment on: http://stackoverflow.com/a/52493987

http://stackoverflow.com/q/52471206
has answer: http://stackoverflow.com/a/52471442
tagged with: webdriver
type: Question
tagged with: css-selectors
has answer: http://stackoverflow.com/a/52471423
has answer: http://stackoverflow.com/a/52473408
has comment: http://stackoverflow.com/comment/91884538
upvote count: 1
has body: This is the button I'm trying to click: Vote Now This is the xpath (pulled from Firefox): [@id='root']/html/body/div/div/div[3]/div/div/footer/div/button" I've tried a wide variety of ways to click on the button, all to no avail. self.driver.find_element_by_xpath("//*[@id='root']/html/body/div/div/div[3]/div/div/footer/div/button").click() self.driver.findElement(By.id("Vote Now")).click() self.driver.find_element_by_name("Vote").send_keys(Keys.ENTER) self.driver.find_element_by_id('stkv-c-button stkv-us-button-color--background stkv-u-background-color-transition-150 stkv-us-button-color--border stkv-us-button-color stkv-us-button-color--fill stkv-c-button stkv-c-button--raised stkv-c-button--big').click() Any suggestions would be greatly appreciated! I'm not having any luck with it.
tagged with: python
answer count: 4
favorite count: 0
tagged with: xpath
has title: Python - clicking on button with Selenium
downvote count: 0
type: UnansweredQuestion
tagged with: selenium
score: 1
has answer: http://stackoverflow.com/a/52472512

http://stackoverflow.com/q/52498495
tagged with: opencv
has comment: http://stackoverflow.com/comment/91938713
has comment: http://stackoverflow.com/comment/91937812
has body: My example is the following image, a section from a disparity map: I am wanting to fill the gray area completely gray, and the the black area completely black. I know that I can get the edge with canny edge detection, yet I do not know how to fill those regions with two different colours. I am wanting a method that is direct, such as a boundary with edges, as I have tried using kmeans segmentation however with K=3 the unwanted part still shows (and it also ruins the rest of the image). Additional examples: I am wanting to set the section outside the red line to black, and the section inside the line to gray (removing the blue region). In a larger example, which is my goal, I am wanting to set the region outlined in red to complete black, removing the dark gray regions which aren't defining much disparity. This would then apply to the other sections as well, removing overlapping "sections".
has comment: http://stackoverflow.com/comment/91946564
score: 0
has comment: http://stackoverflow.com/comment/91937718
tagged with: python
has title: Filling in edge defined areas with OpenCV
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/52490323
type: Answer
has body: result = [f(x) for x in l if p(x)] You can write if statements inside the list comprehension
score: 0
answers question: http://stackoverflow.com/q/52490293

http://stackoverflow.com/q/52498777
has answer: http://stackoverflow.com/a/52501371
possible better answer: http://stackoverflow.com/a/52626636
has body: OpenCV has a limited amount of color maps. MatplotLib has many more color maps, but it is not straightforward to apply these colormaps to given OpenCV images. How to apply MatplotLib color maps from the page below to OpenCV images when using the Python API? This is similar to applying a custom colormap to a given image. https://matplotlib.org/examples/color/colormaps_reference.html
tagged with: opencv
type: AnsweredQuestion
has title: Apply MatplotLib or custom colormap to OpenCV image
tagged with: matplotlib
score: 12
type: Question
upvote count: 12
has answer: http://stackoverflow.com/a/52626636
downvote count: 0
accepted answer: http://stackoverflow.com/a/52498778
favorite count: 0
tagged with: visualization
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/52498778

http://stackoverflow.com/a/52575027
downvote count: 0
answers question: http://stackoverflow.com/q/52574877
score: 1
upvote count: 1
has body: The regex will find anything between the outside commas and then I strip it from curly braces if they exist: import re s = '{q0,q1,q2,q3},{a,b},q0,{q1,q3}' result = [i[1:-1] if i.startswith('{') else i for i in re.findall(r'[^,{]*(?:\{[^{}]*\})*[^,}]*', s) if i] print(result) # ['q0,q1,q2,q3', 'a,b', 'q0', 'q1,q3'] It will also work for other characters than ASCII letters: import re s = '{q0,q1,q2,q3.?!},{a,b},q0,@,{q1,q3}' result = [i[1:-1] if i.startswith('{') else i for i in re.findall(r'[^,{]*(?:\{[^{}]*\})*[^,}]*', s) if i] print(result) # ['q0,q1,q2,q3.?!', 'a,b', 'q0', '@', 'q1,q3']
type: Answer
has comment: http://stackoverflow.com/comment/92085708

http://stackoverflow.com/q/52443426
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: I want to implement a software for counting cards in blackjack, using some image recognition to automate the process. But i don't know where to start. I think the problem could be divided into these steps: 1- Take an image from the browser in-game (it's basically an Adobe Flash Game) 2- Process the image, with some image recognition, that recognize all the cards. 3- Updating the counter using the strategy Hi-Lo 4- Showing the result on screen How can i do this using python? What are the libraries that could help me? This is a totally new field for me. I'll try to implement the question based on your suggestions. EDIT 1: Selenium Webdriver works fine, so far i've used this peace of code to get the screenshot of the main page, but i can't get into the game, because i don't have the money to play lol: from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.888casino.it/giochi-da-casino/') browser.save_screenshot('screenie.png') browser.quit() But basically i need to substitute the browser.get() with something that hooks the browser, rather then something that opens a new page. Then i need to implement a for loop that takes screenshots every second while i'm playing the game, and after that i can start processing those images. EDIT 2: I will try TensorFlow API for the image processing, but i didn't find any training model for recognizing cards. So i have to create a brand new model, i found this tutorial that helps me training my own object recognition model. Please, if you know an existing training model, link that. EDIT 3: Using Tensorflow i was able to create my own model for object recognition, now i need to use that model in a python script. For now i've used this sample script, that opens an image and draw rectangles around the cards. import os import cv2 import numpy as np import tensorflow as tf import sys # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils …
has comment: http://stackoverflow.com/comment/91832434
score: 1
tagged with: image-processing
has title: Image Recognition on Browser using Python
has comment: http://stackoverflow.com/comment/91833029
type: Question
has comment: http://stackoverflow.com/comment/91831687
linked to: http://stackoverflow.com/q/3422262
has answer: http://stackoverflow.com/a/52458408
answer count: 1
has comment: http://stackoverflow.com/comment/91831634
favorite count: 0
tagged with: blackjack

http://stackoverflow.com/comment/91876413
type: Comment
type: QuestionComment
has text: Use numpy.array_equal(image1, image2)
score: 0
comment on: http://stackoverflow.com/q/52466265

http://stackoverflow.com/comment/91877820
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52468003
has text: Read my comment again carefully.
type: Comment

http://stackoverflow.com/comment/92013256
type: Comment
has text: One last question. I update my post, should I also include the field user? _user = item['user'] item.pop('user') # this is imp collection.update({'_id': _id, 'user': _user }, {$set: item})
comment on: http://stackoverflow.com/a/52536111
score: 0
type: AnswerComment

http://stackoverflow.com/q/52478806
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91903359
has title: Pandas: Split columns having multiple values
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91900367
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91902934
linked to: http://stackoverflow.com/q/12680754
has body: An example of my df: Index time type pwa0 pwa1 pwa2 63 16:05:03 nonJ [20:733:845] [] [2750] I would like to split the columns having no, one or multiple values (pwa0, pwa1 and pwa2) like this: Index time type pwa0 pwa1 pwa2 63 16:05:03 nonJ 20 2750 63 16:05:03 nonJ 733 63 16:05:03 nonJ 845 In contrast to the possible shown duplicate, the to be splitted columns are not correlated. The split order per column should just be order based: first the first value, then the second etc. If no values are present in a column, the cell should remain empty. Any suggestions will be highly appreciated!
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91900088
score: 1
has comment: http://stackoverflow.com/comment/91898670

http://stackoverflow.com/a/52483099
has body: There are multiple issues with your code. The main problems are: You assume if and abs work in a vectorised fashion. This isn't true. Each if statement in regular Python works on a single Boolean value, not element-wise when comparing two series. Because of (1), you continually overwrite an entire series in each of the if / elif / else clauses. Your function returns nothing. Therefore, using Multi.apply(checks) will return None. Instead, you can use np.select to specify conditions and values in a vectorised fashion. Here's an example for Length Difference: conds = [df['Masterpack qty'] == df['SUBPACK_QTY'], df['Masterpack qty'] == df['PACK_QTY']] choices = [((df['Length'] - df['SUBPACK_LENGTH']) / ((df['Length'] + df['SUBPACK_LENGTH'])/2)).abs(), ((df['Length'] - df['PACK_LENGTH']) / ((df['Length'] + df['PACK_LENGTH'])/2)).abs()] df['Length Difference'] = np.select(conds, choices, 'No Match')
accepted answer of: http://stackoverflow.com/q/52482926
answers question: http://stackoverflow.com/q/52482926
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91900493
has text: @user10309160 just an array like `[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]` to number a group. I add an example `df` before `groupby` and `sum`.
type: Comment
comment on: http://stackoverflow.com/a/52476076
score: 0
type: AnswerComment

http://stackoverflow.com/q/52571612
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52571643
type: Question
answer count: 2
has title: How to convert a list of strings representing tuples to tuples of integers?
possible better answer: http://stackoverflow.com/a/52571696
downvote count: 0
has answer: http://stackoverflow.com/a/52571696
has body: I want to convert list_int=['(2,3)','(3,4)'] to integer coordinate points: [(2, 3), (4, 8)] I tried this code list_int=['(2,3)','(3,4)'] for x in list_int: con= int(x0 for x in list_int) print con and I am getting this error TypeError: int() argument must be a string or a number, not 'generator' I am new to Python.
tagged with: python-2.7
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/52571643
tagged with: python
score: 2

http://stackoverflow.com/comment/91990016
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52524736
has text: try `SELECT * FROM schema.table_name WHERE column = '%s';`

http://stackoverflow.com/q/52581855
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92099063
tagged with: python
has body: I have a Numpy array of spikes or peaks like this: peaks = [0, 0, 3, 0, 6, 0, 0, 9, 0, 0, 0, 0, 15, 0] and I want to hold the peaks, to obtain the following steps: steps = [0, 0, 3, 3, 6, 6, 6, 9, 9, 9, 9, 9, 15, 15] I am concerned about speed (this is for image analysis on large arrays (1000**3)), so I can't use for-loops or list comprehensions. It really must be vectorized. In a for-loop this is obviously trivial, but vectorization is vexing me! (Almost-pun intended) Also, because it will be applied to 2D and 3D arrays/images, a solution that only applies to a 1D list is not sufficient. It will operate on only 1 axis, but it must be able to work across additional axes. By this I mean: peaks = [[0, 0, 3, 0, 0, 6, 0, 0] [0, 4, 0, 0, 8, 0, 0, 0] [3, 0, 0, 0, 6, 0, 9, 0]] should become: steps = [[0, 0, 3, 3, 3, 6, 6, 6] [0, 4, 4, 4, 8, 8, 8, 8] [3, 3, 3, 3, 6, 6, 9, 9]] I feel like there must be some numpy function that does this but cannot seem to find it. I'm wishing for a function called hold_peaks or something like that. I have been stuck thinking about cumsum which does create steps, and works on the first step, but makes the subsequent steps too high. I have also thought about add.at but can't find a way to create the indices. Notes In my planned use case, I expect the peak heights to always be increasing, so a solution that does this is ok for me: peaks = [0, 4, 0, 0, 2, 0, 7, 0] steps = [0, 4, 4, 4, 4, 4, 7, 7] but I imagine it might be nice to optionally do this: peaks = [0, 4, 0, 0, 2, 0, 7, 0] steps = [0, 4, 4, 4, 2, 2, 7, 7] as in hold the most recent peak, even if lower than the preceding one.
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/92098893
score: 1
linked to: http://stackoverflow.com/q/28563711
has comment: http://stackoverflow.com/comment/92098899
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92099083
has title: Obtain an array of steps from discrete spikes or peaks using numpy vectorization
duplicate of: http://stackoverflow.com/q/28563711
has comment: http://stackoverflow.com/comment/92099032
upvote count: 1
has comment: http://stackoverflow.com/comment/92099111
has comment: http://stackoverflow.com/comment/92099390
favorite count: 0
has comment: http://stackoverflow.com/comment/92099045

http://stackoverflow.com/comment/92056959
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52559016
has text: Please copy and paste code as text instead of screenshots.
type: QuestionComment

http://stackoverflow.com/comment/91837269
type: QuestionComment
has text: Take a look at the `SdServer.APP_ID_HANDLERS` class attribute. Eg, put `print(SdServer.APP_ID_HANDLERS)` before & after the section where `class SdApp` is defined.
comment on: http://stackoverflow.com/q/52447095
score: 0
type: Comment

http://stackoverflow.com/q/52438822
tagged with: apache-kafka
has comment: http://stackoverflow.com/comment/92929526
has answer: http://stackoverflow.com/a/64570610
tagged with: docker-compose
has answer: http://stackoverflow.com/a/52440056
has comment: http://stackoverflow.com/comment/92926378
type: Question
has comment: http://stackoverflow.com/comment/91852854
downvote count: 0
tagged with: kafka-consumer-api
linked to: http://stackoverflow.com/q/51630260
tagged with: docker
upvote count: 39
has comment: http://stackoverflow.com/comment/91865307
favorite count: 0
has answer: http://stackoverflow.com/a/70758515
score: 39
has answer: http://stackoverflow.com/a/52450933
has comment: http://stackoverflow.com/comment/91838960
type: UnansweredQuestion
has body: I am using dockerized Kafka and written one Kafka consumer program. It works perfectly when I run Kafka in docker and application at my local machine. But when I configured the local application in docker I am facing issues. The issue may be due to a topic not created until time application started. docker-compose.yml version: '3' services: zookeeper: image: wurstmeister/zookeeper ports: - "2181:2181" kafka: image: wurstmeister/kafka ports: - "9092:9092" environment: KAFKA_ADVERTISED_HOST_NAME: localhost KAFKA_CREATE_TOPICS: "test:1:1" KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 volumes: - /var/run/docker.sock:/var/run/docker.sock parse-engine: build: . depends_on: - "kafka" command: python parse-engine.py ports: - "5000:5000" parse-engine.py from kafka import KafkaConsumer import json try: print('Welcome to parse engine') consumer = KafkaConsumer('test', bootstrap_servers='localhost:9092') for message in consumer: print(message) except Exception as e: print(e) # Logs the error appropriately. pass Error log kafka_1 | [2018-09-21 06:27:17,400] INFO [SocketServer brokerId=1001] Started processors for 1 acceptors (kafka.network.SocketServer) kafka_1 | [2018-09-21 06:27:17,404] INFO Kafka version : 2.0.0 (org.apache.kafka.common.utils.AppInfoParser) kafka_1 | [2018-09-21 06:27:17,404] INFO Kafka commitId : 3402a8361b734732 (org.apache.kafka.common.utils.AppInfoParser) kafka_1 | [2018-09-21 06:27:17,431] INFO [KafkaServer id=1001] started (kafka.server.KafkaServer) **parse-engine_1 | Welcome to parse engine parse-engine_1 | NoBrokersAvailable parseengine_parse-engine_1 exited with code 0** kafka_1 | creating topics: test:1:1 As I already added depends_on property in docker-compose but before starting topic application connecting so error occurred. I read that I can possible to add the script in the docker-compose file but I am looking for some easy way. Thanks for help
has title: Docker Kafka w/ Python consumer
tagged with: python
answer count: 4

http://stackoverflow.com/a/52560162
has comment: http://stackoverflow.com/comment/92059872
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52559374
downvote count: 0
has body: Sonarqube has a Python plugin.

http://stackoverflow.com/q/52525896
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52538492
favorite count: 0
has comment: http://stackoverflow.com/comment/92015530
has title: python multiprocessing paramiko ssh connections
has comment: http://stackoverflow.com/comment/91991778
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92015163
has body: I am writing a script to connect to a bunch of cisco routers and run commands on them, hosts and commands are put into a text file and then read from the script. Below is the code i got, when i don't use the pool.map everything works good, but when trying to use the pool.map to spawn more process, i keep getting errors. #!/usr/bin/python #Import modules from multiprocessing.pool import ThreadPool import sys, os import paramiko import time import getpass import socket def unpack_call(callable_arguments): callable, arguments = callable_arguments return callable(*arguments) def conn(host, commands): # Create instance of SSH client object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Pass host to connect to device via SSH remote_conn_pre.connect(host, username=username, password=password, look_for_keys=False, allow_agent=False, timeout=5) print "Working on %s" % host remote_conn = remote_conn_pre.invoke_shell() output = remote_conn.recv(1000) disable_paging(remote_conn) remote_conn.send("enable") remote_conn.send("\n") remote_conn.send(password) remote_conn.send("\n") output = command(commands, remote_conn,host) remote_conn.close() print "Completed %s" % host except (paramiko.SSHException, socket.error) as se: print "Error connecting to %s and reason is %s" % (host, se) time.sleep(1) def disable_paging(remote_conn): ''' Disable Paging on Cisco ''' remote_conn.send("term len 0\n") time.sleep(1) # Clear the buffer on the screen output = remote_conn.recv(1000) return output def command(commands,remote_conn,host): # Open commands.txt file for reading c = open(commands, "r") fil = open("session_%s.txt" % host, "w") for l in c: remote_conn.send(l) time.sleep(1) output = remote_conn.recv(50000) fil.write(output) fil.close() if __name__ == "__main__": # Get login credentials before starting script username = raw_input("Username: ") password = getpass.getpass("Password: ") h…
tagged with: paramiko

http://stackoverflow.com/comment/91839213
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52448067
has text: `.js` files are not parsed by the jinja template engine so it wont replace `{{url for...` you need to pass the url in from one of your html templates or hardcode the path

http://stackoverflow.com/q/52575447
downvote count: 0
has title: Django F expression and ArrayField position
favorite count: 0
has answer: http://stackoverflow.com/a/52577502
accepted answer: http://stackoverflow.com/a/52577502
has comment: http://stackoverflow.com/comment/92090134
tagged with: django
tagged with: python
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92089703
linked to: http://stackoverflow.com/q/39402920
type: Question
has body: I have a problem with Django and would like to ask for some advice: One of my models contains specific indicators with variable values. This is why I am using an Arrayfield for those. For example one Indicator has 3 values, another only 2 and some only have 1 value. Now I want to compare values from within the Arrayfield with each other. So I know there are those fancy F Expressions and I tried to use them, but here I am stuck, because it seems like F doesn't allow an positional-lookup from inside ArrayField. Does anyone know if i can use F for positional lookup of arrayfield? Or do I have to make a direct SQL-Call from Django or change my db somehow to make one value per field? Here is the Model: class Indicators(models.Model): datetime = models.DateTimeField(default=datetime.now) name = models.TextField(default="none") values = ArrayField(models.FloatField(default=0)) This is what I want to achieve: indicator_compareable = Indicators.objects.filter(name='compareable', values__0=F('values__1')).values_list('values') And it raises an Exception.. operator does not exist: double precision = double precision[] LINE 1: ...areable' AND "indicators"."values"[1] = ("... As Mikhail suggested (in first comment to my post), here is the translated SQL from my Django filter: SELECT "indicators"."values"[1] FROM "indicators" WHERE ("indicators"."name" = 'compareable' AND "indicators"."values"[1] = ("indicators"."values")) From the Exception it seems like I am not allowed to give ArrayField position to F Expression (or that Django ignores the position..). And the translated sql-query shows, that it seems like F doesn't handle ArrayField-position... In postgres a correct query for my needs would be: SELECT values FROM indicators WHERE name='compareable' and values[1]=values[2]; During my search I found those links here, but they didn't help..: Django F field iteration https://code.djangoproject.com/ticket/24709
has comment: http://stackoverflow.com/comment/92089845
score: 4
has comment: http://stackoverflow.com/comment/92086554
has comment: http://stackoverflow.com/comment/92088945
answer count: 1

http://stackoverflow.com/a/52564856
answers question: http://stackoverflow.com/q/52564227
has body: You could try something like this: from bs4 import BeautifulSoup html = """ Technical Characteristics END ITEM IDENTIFICATION (AGAV) END ITEM 6675014301965 BODY STYLE (AAQL) TUBE TYPE CONTINUOUS CURRENT RATING IN AMPS (AEBJ) 1.600 III END ITEM IDENTIFICATION (AGAV) END ITEM 6675014301965 """ soup = BeautifulSoup(html, 'html.parser') dts = soup.find_all("dt") outs = {i.string: i.find_next("dd").string for i in dts} print(outs) #> {'END ITEM IDENTIFICATION': '(AGAV) END ITEM 6675014301965', 'BODY STYLE': '(AAQL) TUBE TYPE', 'CONTINUOUS CURRENT RATING IN AMPS': '(AEBJ) 1.600', 'III END ITEM IDENTIFICATION': '(AGAV) END ITEM 6675014301965'} Created on 2018-09-28 by the reprexpy package import reprexpy print(reprexpy.SessionInfo()) #> Session info -------------------------------------------------------------------- #> Platform: Darwin-17.7.0-x86_64-i386-64bit (64-bit) #> Python: 3.6 #> Date: 2018-09-28 #> Packages ------------------------------------------------------------------------ #> beautifulsoup4==4.6.3 #> reprexpy==0.1.1
accepted answer of: http://stackoverflow.com/q/52564227
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91990636
comment on: http://stackoverflow.com/q/52524725
type: Comment
type: QuestionComment
has text: Is there anything in the JSON file before what you showed in the screenshot? Can you post the JSON as plain text instead of an image?
score: 0

http://stackoverflow.com/a/65764112
downvote count: 0
type: Answer
has body: From requests 2.4.2 (https://pypi.python.org/pypi/requests), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version: requests.post('https://sampleurl.com', auth=(username, password), json={'value': '100','utcRectime': '09/23/2018 11:59:00 PM','comment': "test",'correctionValue': '0.0','unit': 'C'}) Details: import requests import json username = "enter_username" password = "enter_password" url = "https://sampleurl.com" data = open('test.json', 'rb') r = requests.post(url, auth=(username, password), data=data) print(r.status_code) print(r.text)
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52469747

http://stackoverflow.com/q/52451049
tagged with: time-series
has comment: http://stackoverflow.com/comment/91845469
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91895097
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91845572
tagged with: pandas
tagged with: python
has body: I'm working on the forecast of some time series and I need to compare different methods using python. Practically I need to generate some predictions using the Triple Exponential Smoothing, and I'm using this library and the relative functions like this. My time series has this format, as pd.Series object: Date Close 2016-04-11 01:17:04 -10.523793 2016-04-11 07:25:13 -5.352295 2016-04-11 22:40:11 92.556003 2016-04-13 05:06:31 -1.769866 2016-04-13 05:17:50 -2.330789 2016-04-14 08:43:09 17.636638 2016-04-17 21:15:12 -0.454655 2016-04-19 06:10:04 -0.026375 2016-04-19 06:10:04 -0.175647 ... I wrote these lines in python: from statsmodels.tsa.holtwinters import ExponentialSmoothing from matplotlib import pyplot as plt import numpy as np import pandas as pd train_size = int(len(myTimeSeries) * 0.66) train, test = myTimeSeries[1:train_size], myTimeSeries[train_size:] model = ExponentialSmoothing(train) model_fit = model.fit() dict=model.params params=np.array(list(dict.items())) dates=test.index.astype(str) pred = model.predict(params,start=dates[2], end=dates[-1]) plt.plot(train, label='Train') plt.plot(test, label='Test') plt.plot(pred, label='Holt-Winters') plt.legend(loc='best') I had a problem with the function model.predict so I added the param values as required, getting them from the class model, after its fit. I'm not sure if I did well but I've not found so much around. Moreover I got a problem in setting the start date (and maybe also the end). It returns this: KeyError: 'Thestartargument could not be matched to a location related to the index of the data.' As I found here, I also moved the start date of the prediction to the third value, that is the index [2] of the test dataset. I got the same if I set [0],[1], etc... What's wrong with that? As you can see, myTimeSeries has not a fixed frequency set, but the collection of the value is random. I've found different tutorials, like this, this other one, or this about theory, but they are not in the same condition…
has title: Predict with Triple Exponential Smoothing using ExponentialSmoothing of statsmodels in python
has comment: http://stackoverflow.com/comment/91894833
type: UnansweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91893293
tagged with: statsmodels
linked to: http://stackoverflow.com/q/36717603
has answer: http://stackoverflow.com/a/52489070

http://stackoverflow.com/comment/92168638
type: Comment
comment on: http://stackoverflow.com/a/52579287
has text: @user7586189 Despite that, in some python docs you may find that they are talking about "threads", don't believe it. If they will be threads, then you will see it so in the `pstree` output, but in the foreseeable future you won't see that in any python software.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52459025
has comment: http://stackoverflow.com/comment/91863780
has comment: http://stackoverflow.com/comment/91945621
has comment: http://stackoverflow.com/comment/91864440
tagged with: image-processing
type: Question
has comment: http://stackoverflow.com/comment/91927277
has comment: http://stackoverflow.com/comment/91883751
has comment: http://stackoverflow.com/comment/91944982
has answer: http://stackoverflow.com/a/52504940
has comment: http://stackoverflow.com/comment/91900254
tagged with: image
upvote count: 2
score: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/91867200
has answer: http://stackoverflow.com/a/52470926
has title: Why 16bit to 8bit conversion produces striped image?
has comment: http://stackoverflow.com/comment/91860382
favorite count: 0
has body: I am testing a segmentation algorithm on several VHSR satellite images, which originally comes in 16bit format, but when I convert them to 8bit images, the produced images are showing striped appearance. I've been trying different python libraries (skimage, cv2, scipy) getting similar results. 1) The original 16-bit image it is a 4 band image (NIR,B,G,R), so you need to choose the right bands to create a true color image, RGB image (4,3,2 bands). thanks in advance. It can be downloaded from this link: 16bit image 2) I use this code to convert each pixel value, from a 16-bit integer now fitting within 8-bit range: from scipy.misc import bytescale SS = io.imread('Imag16bit.tif') SS = bytescale(SS) SS = np.asarray(SS) plt.imshow(SS) This is my result of above code:
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91913538
type: Comment
has text: I mean speed. The answer will be closer to the value of pi depending on the number of points you sample. Just take 10**6 points for comparing speed.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52485654

discord.py
tags question: http://stackoverflow.com/q/52518636
tags question: http://stackoverflow.com/q/52464966
tags question: http://stackoverflow.com/q/52527482
tags question: http://stackoverflow.com/q/52484959
tags question: http://stackoverflow.com/q/52583479
tags question: http://stackoverflow.com/q/52461270
tags question: http://stackoverflow.com/q/52580564
tags question: http://stackoverflow.com/q/52503228
tags question: http://stackoverflow.com/q/52461661
tags question: http://stackoverflow.com/q/52464933
tags question: http://stackoverflow.com/q/52524187
tags question: http://stackoverflow.com/q/52508556
tags question: http://stackoverflow.com/q/52462215
tags question: http://stackoverflow.com/q/52561613
tags question: http://stackoverflow.com/q/52505861
tags question: http://stackoverflow.com/q/52461664
tags question: http://stackoverflow.com/q/52545638
tags question: http://stackoverflow.com/q/52516651
tags question: http://stackoverflow.com/q/52461963
tags question: http://stackoverflow.com/q/52469235
tags question: http://stackoverflow.com/q/52544226
tags question: http://stackoverflow.com/q/52435340
type: Tag
tags question: http://stackoverflow.com/q/52571844
tags question: http://stackoverflow.com/q/52577090
tags question: http://stackoverflow.com/q/52459935
tag name: discord.py
tags question: http://stackoverflow.com/q/52563116
tags question: http://stackoverflow.com/q/52457916

http://stackoverflow.com/q/52458921
upvote count: 1
type: Question
tagged with: numpy
has body: I want to convert some images to numpy arrays, and pretty-print them. I have stored all the images in an array of numpy arrays. path = "greyset/" vector_classwise = [[0 for i in range(200)] for j in range(10)] for image_path in os.listdir(path): inpath = os.path.join(path, image_path) img = Image.open(inpath) arr = np.array(img) shape = arr.shape flat_arr = arr.ravel vector = np.matrix(flat_arr) #image_path is of the form classname_image_number class_num = int(image_path[0:3]) entry = int(image_path[4:7]) vector_classwise[class_num][entry] = vector print (vector_classwise[3][5]) However, when I try printing the last line, I get &lt;built-in method ravel of numpy.ndarray object at 0x7ff472a84490&gt; instead of the array. I tried writing this: print (vector_classwise[3][5]()) to call the method as one of the answers suggested, but I got this error: TypeError: 'matrix' object is not callable How can I print out the vectors in the array vector_classwise?
tagged with: arrays
tagged with: pretty-print
has title: built-in method ravel of numpy.ndarray object... insead of the array
has comment: http://stackoverflow.com/comment/91860096
tagged with: matrix
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/91860034

http://stackoverflow.com/comment/91988369
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52524187
has text: Thank you! It helps me a lot :D
type: Comment

http://stackoverflow.com/comment/113241358
comment on: http://stackoverflow.com/a/52445033
has text: Tried using save/load for numpy.ndarrays and they always came back empty. Urgh.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52524851
score: 0
has title: Broadcast a 1D array using a 2D array
answer count: 1
has comment: http://stackoverflow.com/comment/91989390
tagged with: python
has comment: http://stackoverflow.com/comment/91990531
has answer: http://stackoverflow.com/a/52528883
type: AnsweredQuestion
tagged with: numpy-slicing
tagged with: list
has comment: http://stackoverflow.com/comment/91989653
accepted answer: http://stackoverflow.com/a/52528883
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91989759
has body: I have a 1D array array_data with ~10**8 elements. I have a second array array_index which specifies the bounding indices used to slice array_data with. Below is Minimal, Complete, and Verifiable example of array_data and array_index: import numpy as np #Create data array_data = np.arange(100) #Randomly create indices array_index = np.sort(np.random.randint(100, size=(10,2))) #For each randomly created index, slice the array array_sliced = [array_data[index[0]:index[1]]) for index in array_index] #Now data is sliced, perform operation on the sliced data. For example: val = [] for slice in array_sliced: val.append(np.nanmean(slice)) Question: What is the best way to slice array_data with array_index along axis=1 so I can perform another task on the sliced arrays (e.g. min, max, mean)? My solution at the moment uses list comprehension and conversion back to a numpy array. This method seems clunky and slow: &gt;&gt;&gt; np.array([np.nanmean(array_data[index[0]:index[1]]) for index in array_index], dtype=np.float64) EDIT: Added Minimal, Complete, and Verifiable example (works in python 2.7).
tagged with: list-comprehension

http://stackoverflow.com/comment/92007821
type: AnswerComment
comment on: http://stackoverflow.com/a/52534171
score: 0
has text: DavidG, many thanks for that! Now the code works just fine :-). I originally added the "object" due to an error I was receiving to generate the random numbers inside the loop. I deleted it for the other arrays, and now it works.Thank you again!
type: Comment

http://stackoverflow.com/comment/91836981
comment on: http://stackoverflow.com/q/52447095
type: Comment
type: QuestionComment
score: 1
has text: yes it is a decorator

http://stackoverflow.com/a/52442463
answers question: http://stackoverflow.com/q/52442388
type: Answer
has comment: http://stackoverflow.com/comment/91827817
has body: They are not exactly 1D or 2D. The first is just a tuple of integers, and the second a tuple of tuples. So, you just iterate over them in parallel (using zip) and create a new tuple element for each pair of elements result = tuple( (*pos, h) for pos, h in zip(pos2D, heights))
score: 0

http://stackoverflow.com/comment/92054339
type: QuestionComment
comment on: http://stackoverflow.com/q/52557734
score: 2
has text: I think you need to initialize a spark context before using this function. In the error 'NoneType' object has no attribute '_jvm' ==> sc is NoneType ==> SparkContext does not exist. The first case works because it still uses the native round function, if you want to use the pyspark function you would have to call pyspark.sql.functions.round(3.14159265359,2)
type: Comment

http://stackoverflow.com/comment/91840811
has text: @vash_the_stampede no, I think 10 hour run time for this kind of problem is effectively "not working"
comment on: http://stackoverflow.com/q/52448847
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52450621
has comment: http://stackoverflow.com/comment/91844452
has body: I was just wondering if anyone knew how to list out the usernames that a twitter user is following, and their followers in two separate .csv cells. This is what I have tried so far. import tweepy import csv consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = "" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) csvFile = open('ID.csv', 'w') csvWriter = csv.writer(csvFile) users = ['AindriasMoynih1', 'Fiona_Kildare', 'daracalleary', 'CowenBarry', 'BillyKelleherTD', 'BrendanSmithTD'] for user_name in users: user = api.get_user(screen_name = user_name, count=200) csvWriter.writerow([user.screen_name, user.id, user.followers_count, user.followers_id, user.friends_id user.description.encode('utf-8')]) print (user.id) csvFile.close()
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91844548
favorite count: 0
has answer: http://stackoverflow.com/a/52452208
has comment: http://stackoverflow.com/comment/91844712
tagged with: python
tagged with: tweepy
type: AnsweredQuestion
upvote count: 9
tagged with: twitter
has title: Get list of followers and following for group of users tweepy
type: Question
score: 9
has comment: http://stackoverflow.com/comment/91844427
accepted answer: http://stackoverflow.com/a/52452208
tagged with: api

datetime
tags question: http://stackoverflow.com/q/52521477
tags question: http://stackoverflow.com/q/52542408
tags question: http://stackoverflow.com/q/52450746
tags question: http://stackoverflow.com/q/52470845
tags question: http://stackoverflow.com/q/52473972
tags question: http://stackoverflow.com/q/52503141
tags question: http://stackoverflow.com/q/52519910
tags question: http://stackoverflow.com/q/52432844
tags question: http://stackoverflow.com/q/52552264
tags question: http://stackoverflow.com/q/52573184
tags question: http://stackoverflow.com/q/52530413
tags question: http://stackoverflow.com/q/52521588
tags question: http://stackoverflow.com/q/52462801
tags question: http://stackoverflow.com/q/52466006
tags question: http://stackoverflow.com/q/52504828
tags question: http://stackoverflow.com/q/52498916
tags question: http://stackoverflow.com/q/52550129
tags question: http://stackoverflow.com/q/52430395
tags question: http://stackoverflow.com/q/52576602
tags question: http://stackoverflow.com/q/52554295
tags question: http://stackoverflow.com/q/52448991
tags question: http://stackoverflow.com/q/52451105
tags question: http://stackoverflow.com/q/52580706
tags question: http://stackoverflow.com/q/52466824
tags question: http://stackoverflow.com/q/52559300
tag name: datetime
tags question: http://stackoverflow.com/q/52519046
tags question: http://stackoverflow.com/q/52526437
tags question: http://stackoverflow.com/q/52536311
tags question: http://stackoverflow.com/q/52506557
tags question: http://stackoverflow.com/q/52501102
type: Tag
tags question: http://stackoverflow.com/q/52492404
tags question: http://stackoverflow.com/q/52575694
tags question: http://stackoverflow.com/q/52504329
tags question: http://stackoverflow.com/q/52527406
tags question: http://stackoverflow.com/q/52584417
tags question: http://stackoverflow.com/q/52433721
tags question: http://stackoverflow.com/q/52576622
tags question: http://stackoverflow.com/q/52493104
tags question: http://stackoverflow.com/q/52468909
tags question: http://stackoverflow.com/q/52535828

http://stackoverflow.com/comment/91874128
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52466216
has text: And what's this got to do with `map`?
score: 0

http://stackoverflow.com/comment/91973996
type: Comment
has text: Solved my question, thanks
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52516651

http://stackoverflow.com/comment/91879416
type: Comment
has text: When I run it as: r1 = Rectangle() I get the error: TypeError: __init__() missing 2 required positional arguments: 'topLeft' and 'bottomRight'
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52468746

http://stackoverflow.com/q/52559673
has comment: http://stackoverflow.com/comment/92063175
favorite count: 0
has answer: http://stackoverflow.com/a/52559776
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92063120
has comment: http://stackoverflow.com/comment/92063384
has answer: http://stackoverflow.com/a/52559801
score: 1
has comment: http://stackoverflow.com/comment/92058022
downvote count: 1
type: Question
has title: Python 3 rock Paper Scissors loops
answer count: 2
has body: When I run the program : R,S or P? Rock you threw : R your enemy threw : R &gt;&gt;&gt; The last line of code does not show up if user_choice == computer_choice : print ("tie!") Do you know what should I do? Thank you! import random def main(): user_choice = input("R,S or P?\n") user_choice = user_choice.lower() if user_choice == "rock" or user_choice == "r" : print("you got R") elif user_choice == "p" or user_choice == "paper" : print("you got P") elif user_choice == "s" or user_choice == "scissors" : print("you got S") else : print ("wrong answer!") computer_choice = random.randint(1,3) if computer_choice == 1 : print("your enemy chose R") elif computer_choice == 2 : print("your enemy chose P") else : print("your enemy chose S") if user_choice == computer_choice : print ("tie!") main ()
has comment: http://stackoverflow.com/comment/92058086

http://stackoverflow.com/comment/109517283
score: 0
comment on: http://stackoverflow.com/q/52451154
type: Comment
type: QuestionComment
has text: I still face the same issue. `flask run` just ignores options like `DEBUG` & `ENV`.

http://stackoverflow.com/a/52586758
has comment: http://stackoverflow.com/comment/92108849
answers question: http://stackoverflow.com/q/52565482
type: Answer
has body: Looks like column "visitdate" type is String, can be converted to Timestamp with "unix_timestamp", and then to String in required format with "date_format". After this, grouping can be performed, on Scala: val visitMonthDf = df.withColumn("visitMonth", date_format(unix_timestamp($"visitdate", "dd/MM/yyyy").cast(TimestampType), "1/M/yyyy")) visitMonthDf.groupBy("visitMonth").agg(sum($"totalamount"))
has comment: http://stackoverflow.com/comment/92109103
score: 0

http://stackoverflow.com/q/52464309
answer count: 6
score: -1
possible better answer: http://stackoverflow.com/a/52464377
has answer: http://stackoverflow.com/a/52464399
has answer: http://stackoverflow.com/a/52464379
has comment: http://stackoverflow.com/comment/91870605
has comment: http://stackoverflow.com/comment/91870550
favorite count: 0
has answer: http://stackoverflow.com/a/52464430
has body: I am new to Python so I seem to fail to get the following program run import random num1=0 num2=0 num1=int(random.randint(1,20)) num2=int(random.randint(1,20)) result=0 opr = ("*", "-", "+", "/") print(random.choice(opr)) print(num1,num2) if opr=="*": result = num1 * num2 if opr=="+": result = num1 + num2 if opr=="-": result = num1 - num2 if opr=="/": result = num1 / num2 print(result)
has answer: http://stackoverflow.com/a/52464444
tagged with: python
type: AnsweredQuestion
downvote count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/52464430
has comment: http://stackoverflow.com/comment/91870539
has answer: http://stackoverflow.com/a/52464342
has title: Strings with maths operator do not work here
type: Question
has answer: http://stackoverflow.com/a/52464377
tagged with: math

http://stackoverflow.com/q/52449602
score: 20
has title: How to set environment variables in virtualenv
has comment: http://stackoverflow.com/comment/91897797
downvote count: 0
tagged with: virtualenv
has answer: http://stackoverflow.com/a/66076954
favorite count: 0
has comment: http://stackoverflow.com/comment/116823588
answer count: 5
linked to: http://stackoverflow.com/q/37211115
tagged with: python
has comment: http://stackoverflow.com/comment/92024652
accepted answer: http://stackoverflow.com/a/52555465
has body: If I have python script which activates the virtualenv like this: #!/path/to/venv/bin/python How can I set variables for this script without modifying this script? I want this environment variable to be active for all scripts which use this virtualenv. This means modifying this script is not a solution, since there are twenty scripts, and I don't want to modify twenty scripts. Writing a shell wrapper-script around the python scripts would work, but I would like to avoid this. In the past I thought a custom sitecustomize.py can be used for start-up code. But Ubuntu (AFAIK the only distribution which does this) comes with its own sitecustomize.py file, with the effect that my sitecustomize.py does not get called. See https://bugs.launchpad.net/ubuntu/+source/python2.5/+bug/197219 Here are some ways how I want to use the virtualenv: Script which gets executed via unix cron. virtualenv in a systemd service. See: How to enable a virtualenv in a systemd service unit? via mod_wsgi (Apache): https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html#daemon-mode-single-application (I have thought about this again. I guess it setting the variables is not the job of python or virtualenv. I need a unified way to set environment variables. And in my case I would like to do this without using a shell wrapper).
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91897052
has answer: http://stackoverflow.com/a/52526811
has comment: http://stackoverflow.com/comment/91896211
possible better answer: http://stackoverflow.com/a/52479168
has answer: http://stackoverflow.com/a/52479168
type: Question
upvote count: 20
has comment: http://stackoverflow.com/comment/91896484
linked to: http://stackoverflow.com/q/9554087
has comment: http://stackoverflow.com/comment/91896919
has answer: http://stackoverflow.com/a/65823152
has answer: http://stackoverflow.com/a/52555465

http://stackoverflow.com/comment/91910904
type: Comment
type: QuestionComment
has text: Okay- thank you. This was, as I was hoping it would be, a learning experience.
comment on: http://stackoverflow.com/q/52484567
score: 0

http://stackoverflow.com/q/52491659
tagged with: named-entity-recognition
type: Question
tagged with: stanford-nlp
has comment: http://stackoverflow.com/comment/94023435
downvote count: 0
has body: I have searched and tried to work on this issue for quite some time (around 4 days) before coming here. I'm trying to train a swedish NER-tagged corpus. I got the test data and train data from here. Here is the error I get, when I try to train the model \project\stanford_ner>java -mx1000m -cp stanford-ner.jar;lib/* edu.stanford.nlp.ie.crf.CRFClassifier -prop train/train_properties.txt Invoked on Tue Sep 25 10:44:13 IST 2018 with arguments: -prop train/train_properties.txt usePrevSequences=true useClassFeature=true useTypeSeqs2=true useSequences=true wordShape=chris2useLC useTypeySequences=true useDisjunctive=true noMidNGrams=true serializeTo=dummy_ner_model_swede.ser.gz maxNGramLeng=6 useNGrams=true usePrev=true useNext=true maxLeft=1 trainFile=train/dummy_swede_corpus.tsv map=word=0,answer=1 useWord=true useTypeSeqs=true Error on line 85124: bn Exception in thread "main" java.lang.UnsupportedOperationException: Argument array lengths differ: [class edu.stanford.nlp.ling.CoreAnnotations$TextAnnotation, class edu.stanford.nlp.ling.CoreAnnotations$AnswerAnnotation] vs. [bn] at edu.stanford.nlp.ling.CoreLabel.initFromStrings(CoreLabel.java:263) at edu.stanford.nlp.ling.CoreLabel.(CoreLabel.java:150) The error I'm trying to point out is : Error on line 85124: bn Exception in thread "main" java.lang.UnsupportedOperationException: Argument array lengths differ: [class edu.stanford.nlp.ling.CoreAnnotations$TextAnnotation, class edu.stanford.nlp.ling.CoreAnnotations$AnswerAnnotation] vs. [bn] I do not undersdtand what is "bn" here. I did go through the implementation of the code from github, but to no avail. If I use all train data until before that line of error, I am able to train the data and get the model. And on the line of error, I don't see anything special. It's just another word with NER tag as mentioned in the feature list of properties file.
favorite count: 0
has title: Stanford NLP (NER modelling) - java.lang.UnsupportedOperationException: Argument array lengths differ
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/93877483

http://stackoverflow.com/a/52453274
answers question: http://stackoverflow.com/q/52453164
has comment: http://stackoverflow.com/comment/91865910
accepted answer of: http://stackoverflow.com/q/52453164
type: Answer
has comment: http://stackoverflow.com/comment/91867177
has body: # newurl_resp should also give back same key:value pairs as oldurl was giving #load JSON Data into Dictionary import json f = open("response_oldurl.json") oldurl_resp= json.load(f) f.close() #type(oldurl_resp) --&gt; &lt;class dict&gt; oldurl_resp = { "firstName":"alex", "age":31, "dob":"10-12-1988" } newurl_resp = { "firstName":"**alx**", "**ag**":31, "dob":"10-12-1988"} approach 1 report errors on the fly def validate_resp(old_resp,new_resp): for old_k,old_v in oldurl_resp.items(): try: if old_k in new_resp: new_val = new_resp[old_k] else: raise KeyError('newurl_response doesn\'t have key: '+old_k) try: if old_v != new_val: raise ValueError('new value = '+str(new_val)+' doesn\'t match with orignal value = '+str(old_v)+' of key: '+str(old_k)) #raise ValueError('new value = {} doesn\'t match with orignal value = {} of key: {}'.format(new_val,old_v,old_k)) except ValueError as v_err: print(v_err.args) except KeyError as k_err: print(k_err.args) validate_resp(oldurl_resp,newurl_resp) #("new value = **alx** doesn't match with orignal value = alex of key: firstName",) #("newurl_response doesn't have key: age",) approach 2 saves them for later use items_with_value_err = [] missing_keys = [] def validate_resp(old_resp,new_resp): for old_k,old_v in oldurl_resp.items(): if old_k in new_resp: if new_resp[old_k] != old_v: # key is same but new_resp contains different value items_with_value_err.append((old_k,old_v,new_resp[old_k])) else: missing_keys.append(old_k) if len(items_with_value_err) == 0 and len(missing_keys) == 0: return True else: return False print(validate_resp(oldurl_resp, newurl_resp)) #prints False
downvote count: 0
has comment: http://stackoverflow.com/comment/91867979
has comment: http://stackoverflow.com/comment/91857939
score: 1
has comment: http://stackoverflow.com/comment/91865856
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52488478
upvote count: 2
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52488497
tagged with: pytest
has body: I am trying to run two tests in pytest with two different instances of an attr class (returned from a function-scoped fixture), as input arguments. The first msg object also shows up in the second test. My example: import attr import pytest import uuid @attr.s class Receiver: internal_dict = attr.ib(default=dict()) def send_message(self, msg): self.internal_dict[msg] = msg @pytest.fixture def msg(): yield uuid.uuid1() @pytest.fixture def receiver(): yield Receiver() def test_send_msg_1(msg, receiver): receiver.send_message(msg) assert len(receiver.internal_dict) == 1 def test_send_msg_2(msg, receiver): receiver.send_message(msg) print("internal_dict:{}".format(receiver.internal_dict)) assert len(receiver.internal_dict) == 1 # FAILS How is mutable state leaking between the two tests?
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-attrs
has answer: http://stackoverflow.com/a/52488497
tagged with: python
has title: pytest leaks attrs objects between tests

http://stackoverflow.com/q/52579007
tagged with: networkx
has body: I want to perform tree crossover between two graphs using the following steps: Select one node in each graph, the selected node must have the same type i.e. the node are objects of the same class. Exchange the two subgraphs that are rooted by the selected two nodes. each subgraph must be inserted in the same place of the other subgraph. I have used ego_graph to extract subgraph from each of the two graph, but I do not have idea how to swap the two extracted subgraphs between the two graphs.
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52604609
type: Question
tagged with: graph
downvote count: 0
answer count: 1
tagged with: crossover
has answer: http://stackoverflow.com/a/52604609
has title: how to perform tree crossover between two graphs using networkx?
upvote count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52578749
upvote count: 1
accepted answer: http://stackoverflow.com/a/52578847
type: AnsweredQuestion
score: 1
tagged with: dataframe
linked to: http://stackoverflow.com/q/26763344
type: Question
has body: DATA:: Unnamed: 0 gvkey date CUSIP conm tic cik PERMNO COMNAM 0 0 1001 1983 00016510 A &amp; M FOOD SERVICES INC AMFD. 723576.0 10015 NaN 1 1 1001 1983 00016510 A &amp; M FOOD SERVICES INC AMFD. 723576.0 10015 A &amp; M FOOD SERVICES INC 2 5 1001 1984 00016510 A &amp; M FOOD SERVICES INC AMFD. 723576.0 10015 A &amp; M FOOD SERVICES INC 3 17 1001 1985 00016510 A &amp; M FOOD SERVICES INC AMFD. 723576.0 10015 A &amp; M FOOD SERVICES INC 4 29 1003 1983 00035410 A.A. IMPORTING CO INC ANTQ 730052.0 10031 NaN Goal:: Take specific observation's PERMNO for the year(data) Conditions:: the observation has gvkey data the next year's observation for that gvkey has 'COMNAM' variable's data for example; year = 1983, gvkey = 1001, next_year = 1984 What I've tried:: df = DATA df[(df['date'] == year) &amp; (df['date'] == gvkey) &amp; (df[df['date'] == next_year]['COMNAM'].isna() != 1])] however, it returns, NO OBSERVATIONS.. I think this is because the code contains two mutually exclusive conditions:: df['date'] == year and df['date'] == next_year Can anyone give me advice? Thanks!
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52578847
tagged with: pandas
tagged with: python
favorite count: 0
has title: How to filter observation based on the next period observation in DataFrame

http://stackoverflow.com/a/52506935
upvote count: 6
has comment: http://stackoverflow.com/comment/91954308
score: 6
has comment: http://stackoverflow.com/comment/91954494
has body: It's because replace keeps applying the dictionary df.B.replace({'u': 'v', 'v': 'w', 'w': 'x', 'x': 'y', 'y': 'Hello'}) 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello Name: B, dtype: object With the given dct 'u' -> 'y' then 'y' -> 'u'.
has comment: http://stackoverflow.com/comment/91954324
has comment: http://stackoverflow.com/comment/91954410
has comment: http://stackoverflow.com/comment/91954299
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91954545
accepted answer of: http://stackoverflow.com/q/52506862
has comment: http://stackoverflow.com/comment/91954505
has comment: http://stackoverflow.com/comment/91954361
answers question: http://stackoverflow.com/q/52506862
type: Answer

http://stackoverflow.com/comment/91862520
type: Comment
type: QuestionComment
has text: Thank you everyone, I understand now. I was wrongly under the impression that .remove() returns a list.
comment on: http://stackoverflow.com/q/52460041
score: 0

http://stackoverflow.com/q/52485119
duplicate of: http://stackoverflow.com/q/22392497
has comment: http://stackoverflow.com/comment/91912074
tagged with: python
linked to: http://stackoverflow.com/q/22392497
accepted answer: http://stackoverflow.com/a/52485182
has comment: http://stackoverflow.com/comment/91911712
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/91912132
has comment: http://stackoverflow.com/comment/108539827
has comment: http://stackoverflow.com/comment/91911822
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91911903
has title: Python - How to create an empty numpy array and append to it, like lists
score: -1
has body: This is something I didn't find so easily on the internet. It's easy to create np.arrays, but how do you create an empty one so you can append on the go?
has comment: http://stackoverflow.com/comment/91911771
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/91911793
has comment: http://stackoverflow.com/comment/91911896
has comment: http://stackoverflow.com/comment/91912131
possible better answer: http://stackoverflow.com/a/52485176
has comment: http://stackoverflow.com/comment/91911909
favorite count: 0
has answer: http://stackoverflow.com/a/52485176
has comment: http://stackoverflow.com/comment/91912236
has comment: http://stackoverflow.com/comment/91911964
has answer: http://stackoverflow.com/a/52485182

http://stackoverflow.com/a/52514056
downvote count: 0
has comment: http://stackoverflow.com/comment/91967828
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91967907
upvote count: 1
has body: To avoid any confusion, lets first extract the lambda function and see what it does. The lambda function is defined as lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2 A lambda statement avoids the definition of creating a named function, however any lambda function can still be defined as a normal function. This specific lambda function uses a ternary operator. This can be expanded to a regular if-else statement. This would lead to an equivalent regular function like this def func(x, a1, a2): if x != a1 and x != a2: return x elif x == a2: return a1 else: return a2
answers question: http://stackoverflow.com/q/52513846

http://stackoverflow.com/comment/92075546
type: QuestionComment
has text: Are you sure your folder path is correct? If you use an absolute path, maybe your file(or dir) path should prefix with driver letter.(e.g. D:/A_dest)
comment on: http://stackoverflow.com/q/52569196
score: 0
type: Comment

http://stackoverflow.com/q/52556941
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/92052677
has title: How to manage a pool of processes?
type: UnansweredQuestion
tagged with: pool
has body: I'm trying to set up a multiprocessing pool on Windows 10. Basically some cpus (12 in my case) should read from a Qinand write results to Qout. When writing 'end' in Qin the process should stop. For some reason the process hangs. I developed a simple version: from multiprocessing import Pool, Queue, Event import os,time def worker( Qin, Qout, event): time.sleep(5) while True: item = Qin.get() if item == 'end': event.set() else: Qout.put(item) time.sleep(1) def manager(): Qin,Qout,event= Queue(), Queue(), Event() processes = os.cpu_count() pool = Pool(processes=processes) for _ in range(processes): pool.apply_async(worker,args= (Qin,Qout,event,)) for i in range(100): print(i) Qin.put(i) Qin.put('end') pool.close() event.wait() pool.terminate() return Qout Qout = manager()
score: 2
downvote count: 0
tagged with: events
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52562934
tagged with: windows
tagged with: python
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/52557672

http://stackoverflow.com/a/52588438
has body: Well, this might be solution you are looking for: weighted.loc[weighted['probability']==weighted['probability'].max()].T # 1 2 3 #chrom ch1 chr1 chr1 #start 300 300 600 #end 500 500 800 #probability 0.3 0.3 0.3
answers question: http://stackoverflow.com/q/52588298
type: AcceptedAnswer
downvote count: 0
score: 7
type: Answer
upvote count: 7
accepted answer of: http://stackoverflow.com/q/52588298

http://stackoverflow.com/a/52500037
answers question: http://stackoverflow.com/q/52499910
has comment: http://stackoverflow.com/comment/91949020
score: 0
has body: This is a little better, you don't need to use range() and will not print a lot of do anything it will print do nothing if the value wasn't in A try this: A = [10, 20,.... 500] B = [1, 4,.... 2500] def func(): x = int(input("enter a value from the array A: ")) #user input for i,v in enumerate(A): if v == x: print(B[i]) break else: print("do nothing") func() read here to learn about for else.
type: Answer

http://stackoverflow.com/comment/91864000
comment on: http://stackoverflow.com/q/52460980
type: Comment
type: QuestionComment
score: 1
has text: See also [Why is Python running my module when I import it, and how do I stop it?](//stackoverflow.com/q/6523791)

http://stackoverflow.com/q/52457582
has comment: http://stackoverflow.com/comment/91920940
linked to: http://stackoverflow.com/q/7023052
tagged with: jupyter-notebook
favorite count: 0
has comment: http://stackoverflow.com/comment/92135890
has comment: http://stackoverflow.com/comment/91859578
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91952405
duplicate of: http://stackoverflow.com/q/7023052
has comment: http://stackoverflow.com/comment/91955641
tagged with: python
has comment: http://stackoverflow.com/comment/131386113
downvote count: 1
answer count: 0
has comment: http://stackoverflow.com/comment/91996716
score: 1
has body: I'm trying to access a simple "Hello World" application inside a Jupyter notebook and I'm facing some problems. When I try to access my application by browser I'm getting: This site can’t be reached. If I try the same application from outside notebook everything works. Is there any configuration that I need to make inside Jupyter? from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World" if __name__ == "__main__": app.debug = True app.run(host='0.0.0.0',port=5005) * Running on http://0.0.0.0:5005/ (Press CTRL+C to quit) Getting error log: File "zmq/backend/cython/checkrc.pxd", line 25, in zmq.backend.cython.checkrc._check_rc raise ZMQError(errno) ZMQError: Address already in use
duplicate of: http://stackoverflow.com/q/38982807
type: Question
has title: Flask application inside Jupyter Notebook
has comment: http://stackoverflow.com/comment/97572198
linked to: http://stackoverflow.com/q/41831929
tagged with: flask
has comment: http://stackoverflow.com/comment/92139053
has comment: http://stackoverflow.com/comment/91996255
has comment: http://stackoverflow.com/comment/91864459
has comment: http://stackoverflow.com/comment/91857392

http://stackoverflow.com/q/52465094
downvote count: 2
tagged with: python
tagged with: modulus
has comment: http://stackoverflow.com/comment/91872137
has body: import random value = 1000 a = [] i = 0 b = [None] * 16 print('value = ',1000) for x in range(value): a.append(x) random.Random(4).shuffle(a) print(a) for x in range(16): b[x] = a[x] print(b) This code generate 16 random numbers selected up to the range 1000.But how to generate numbers that has different modulus values from 1 to 26 like this in python ? Consider the numerical example the values obtained randomly are: 184,15,106,8,93,150,210,144,271,365,65,60,385,164,349,405 when we perform a mod 26 operation with all these numbers we get 0,15,2,8,15,20,2,14,11,1,13,8,21,8,11,15 respectively here the numbers 15,8,11,2 are repeating. so i want to eliminate this repeatation. for that i want to generate random numbers that have distinct values while performing a mod 26 operation.
has answer: http://stackoverflow.com/a/52465186
type: Question
answer count: 2
upvote count: 0
score: -2
has title: How to generate random numbers of unique modulus values in python
favorite count: 0
tagged with: random
has answer: http://stackoverflow.com/a/52465180
has comment: http://stackoverflow.com/comment/91871941
type: UnansweredQuestion

http://stackoverflow.com/comment/91880262
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52469105
has text: there is no programming to do this instead of doing it manually?

http://stackoverflow.com/q/52468958
has comment: http://stackoverflow.com/comment/91881078
score: 0
has body: server.py while True: if buffer_len &gt;= 100: connection.sendall("something") else: buffer_read = connection.recv(10) buffer_len = buffer_len + len(buffer_read) In the client, I have sent a request (length = 100) and received a response once. But when I sent the second request, the "buffer_read = connection.recv(10)" line not giving any output. Seems like it is waiting for something to be written in buffer(infinite loop). So, my question: why is conn.rev(10) waiting even though the client has written its request to the buffer? Is it to do with asynchrony? should the client send its request before the server starts waiting? Any ideas on how to solve this? Edit: Here is the client code for tcp in Q self.sock.sendall(tcp.payload) buffer_len = 0 while response_len &gt; buffer_len: data = self.sock.recv(self.buff_size) buffer_len += len(data)
has comment: http://stackoverflow.com/comment/91880781
type: Question
tagged with: server
tagged with: recv
has title: connection.recv not able to read the buffer
type: UnansweredQuestion
tagged with: sockets
tagged with: python
tagged with: client
answer count: 0
has comment: http://stackoverflow.com/comment/91881144

http://stackoverflow.com/comment/91923437
has text: You could go into the directory then loop through it's contents and running `rmtree` on all directories.
type: Comment
comment on: http://stackoverflow.com/a/52491393
score: 1
type: AnswerComment

http://stackoverflow.com/a/52487904
downvote count: 0
has body: The pytest-mock version should look something like this: def test_no_dirs(mocker): mock = mocker.patch('os.listdir', return_value=[]) result = get_list() assert result == [] # because that's the `return_value` mocked mock.assert_called_once_with('/etc/app_data/') Note that users who do from os import listdir will need to mock in a different namespace!
answers question: http://stackoverflow.com/q/52487769
has comment: http://stackoverflow.com/comment/91917191
type: Answer
accepted answer of: http://stackoverflow.com/q/52487769
upvote count: 3
has comment: http://stackoverflow.com/comment/91917219
score: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/92061478
comment on: http://stackoverflow.com/a/52548690
score: 0
type: AnswerComment
has text: >"If it happens that your python script generates specific bytes" - Unfortunately that's not the case. As I stated in my question, the data comes from outside (e.g. passed by user to our host python program). I know about init containers and use them, but reading/writing arbitrary data from/to volume is still hard.
type: Comment

http://stackoverflow.com/comment/92094795
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52579847
has text: Have a look at the uuid library.

http://stackoverflow.com/comment/91995655
type: AnswerComment
score: 0
type: Comment
has text: Note that for simple assignment (rather than mutation), you can do slice assignment more simply/efficiently, e.g. for setting the initial `100`s, `l[:2] = [100]*2`. Bulk mutation (e.g. `l[:3] += 100`) would only work with third party types like `numpy` arrays.
comment on: http://stackoverflow.com/a/52527235

http://stackoverflow.com/comment/91935427
score: 0
has text: A comment is not an answer; it's a comment.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52495120

http://stackoverflow.com/a/52530542
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52530541
score: 3
answers question: http://stackoverflow.com/q/52530541
has body: The default behavior of the print command of Python is to add a space between its arguments. In Python 2.x.x: You could use the string concatenation operator + to do this before you print it like: name = "Andrew" print name + "," Output: Andrew, However, if you are dealing with Python 3.x.x you could use the argument sep to change the separator from space to empty character like: print(name, ",", sep="")
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92001623
type: Answer

index-error
tags question: http://stackoverflow.com/q/52577737
tag name: index-error
type: Tag
tags question: http://stackoverflow.com/q/52551259
tags question: http://stackoverflow.com/q/52480002

http://stackoverflow.com/q/52567704
has comment: http://stackoverflow.com/comment/92081147
tagged with: amazon-web-services
score: 0
answer count: 1
has title: All data not getting stored in DynamoDB
tagged with: amazon-dynamodb
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52587627
accepted answer: http://stackoverflow.com/a/52587627
has body: I'm trying to save some data from a JSON to DynamoDB but only 283 out of 592 items are getting stored. here is my code: r = requests.get(url) j = r.json() for features in j["accountsWithGeo"]["features"]: i = features["properties"]["id"] n = features["properties"]["name"] table.put_item(Item={'id':i,'name':n})
type: Question

http://stackoverflow.com/a/52491644
type: Answer
answers question: http://stackoverflow.com/q/52491589
accepted answer of: http://stackoverflow.com/q/52491589
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91923837
has body: &gt;&gt;&gt; input = ['jeff','69','420','80085\n'] &gt;&gt;&gt; output = [x.replace('\n','') for x in input] &gt;&gt;&gt; output ['jeff', '69', '420', '80085']
has comment: http://stackoverflow.com/comment/91923761

http://stackoverflow.com/a/52488497
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91918873
has body: This code shares the same dict() instance as mutable default: @attr.s class Receiver: internal_dict = attr.ib(default=dict()) Consider instead using a factory: @attr.s class Receiver: internal_dict = attr.ib(factory=dict)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52488478
type: Answer
accepted answer of: http://stackoverflow.com/q/52488478
has comment: http://stackoverflow.com/comment/91919168
has comment: http://stackoverflow.com/comment/91919128

http://stackoverflow.com/a/52468146
has body: You can use this: n = int(input()) mat=[[int(input()) for x in range(n)] for i in range(n)] You can convert above list into numpy as np_mat = numpy.asarray(mat) If you want to input each row at a time,with each element separated by a space, you can do like this. mat=[list(map(int, input().split())) for i in range(n)]
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52467934
upvote count: 2

http://stackoverflow.com/q/52566672
type: AnsweredQuestion
tagged with: opencv3.0
tagged with: pixel
tagged with: image-processing
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52594153
has answer: http://stackoverflow.com/a/52594153
has comment: http://stackoverflow.com/comment/92078633
has comment: http://stackoverflow.com/comment/92084165
score: 0
has answer: http://stackoverflow.com/a/52601970
answer count: 2
has title: Calculate minimum distance of point in image mask to a set of points
tagged with: python
has body: I have an image mask (differenceM) like this: For every single white pixel (pixel value != 0), I want to calculate the minimum distance from that pixel to a set of points. The set of points are points on the external contour which will be stored as a numpy array of [x_val y_val]. I was thinking of doing this: ... def calcMinDist(dilPoints): ... #returns 2d array (same shape as image) def allMinDistDil(dilMask): dilPoints = getPoints(dilMask) ... return arrayOfMinValues #more code here blkImg = np.zeros(maskImage.shape,dtype=np.uint8) blkImg.fill(0) img_out = np.where(differenceM,allMinDistDil(dilatedMask),blkImg) .... But the problem with this is, in order to calculate minimum distance from a pixel point to a set of points (obtained from getPoints function), I'll need to pass in the pixel point (index?) as well. But (if my understanding is correct,) with this where function, it only checks for true and false values in the first parameter...So the way I wrote the np.where() function won't work. I've considered using nested for loops for this problem but I'm trying to avoid using for loops because I have a lot of images to process. May I ask for suggestions to solve this? Any help would be greatly appreciated!
accepted answer: http://stackoverflow.com/a/52601970

http://stackoverflow.com/comment/91824364
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52440611
type: Comment
has text: No worries. BTW, it's probably a good idea to expand your tests to see what happens when the data _does_ have duplicate items.

http://stackoverflow.com/comment/92093244
comment on: http://stackoverflow.com/q/52579010
type: Comment
score: 0
has text: not sure if I got your question clearly enough, but won't just knowing the index in `replaceable_list` suffice? So, instead of for loop, try using `for idx, val in enumerate(replaceable_list)` and then use corresponding idx value for replacement from `mostCommon_list`
type: QuestionComment

http://stackoverflow.com/comment/91865956
type: AnswerComment
comment on: http://stackoverflow.com/a/52461906
type: Comment
has text: I do not want it to assume that, essentially those are dashes in between I guess python thinks it is a negative number ??
score: 0

http://stackoverflow.com/a/52532283
has comment: http://stackoverflow.com/comment/92046328
score: 0
has body: There exists a lot of problems relative to Shell sort complexity and it is suspected that with some appropriate choice of parameters and for some inputs, its complexity could be O(n.logn).
answers question: http://stackoverflow.com/q/52531864
type: Answer
has comment: http://stackoverflow.com/comment/92021481

http://stackoverflow.com/q/52529735
answer count: 0
score: 1
upvote count: 1
type: Question
downvote count: 0
tagged with: pandas
has title: Unable to see all the user input values
favorite count: 0
has comment: http://stackoverflow.com/comment/92104063
tagged with: python-3.x
has body: I am automating my stuff, for which I got stuck at a point. Anyways explaining it, I am using user inputs for which some formula is working in the corresponding cell for outputs.However when am looking at the final output it is reflecting only the last input values for the loop. I wanted to have the final output with all the values submitted. df1 = pd.read_excel('abc.xlsx',worksheet='sheet1') loops = int(input("Total Outage in Month: ")) inputs = [] for x in range(loops): user_input1 = [input('Enter the Impacted_Device : ') ] user_input2 = [input('Number_of_Impacted_Connection :') ] user_input3 = [input('Outage_Minutes :')] inputs.append(user_input1) inputs.append(user_input2) inputs.append(user_input3) break Impacted_Device = input(str("Enter the Impacted_Device : ")) Number_of_Impacted_Connection = int(input("Number_of_Impacted_Connection : ")) Outage_Minutes = int(input("Outage_Minutes : ")) Connection_Outage = int(Number_of_Impacted_Connection * Outage_Minutes) df1['Impacted Connections'] = np.where((df1['Router'].str.contains(Impacted_Device)== True),Number_of_Impacted_Connection,'None') df1['Outage Minutes'] = np.where((df1['Router'].str.contains(Impacted_Device)== True),Outage_Minutes,'None') df1['Connection Outage'] = np.where((df1['Router'].str.contains(Impacted_Device)== True),Connection_Outage,'None') df1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92000095

http://stackoverflow.com/q/52562494
has title: Interpolate in 1D a 3D masked array in python
tagged with: interpolation
answer count: 0
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: python
tagged with: masked-array
has comment: http://stackoverflow.com/comment/92138591
has comment: http://stackoverflow.com/comment/92089836
has comment: http://stackoverflow.com/comment/92063748
type: Question
has comment: http://stackoverflow.com/comment/92065204
has body: I need a faster solution to interpolate a 3D array in one dimension to a 2D surface. My data is gridded (k, j, i): the horizontal grid is regular (j, i), but the vertical grid is not (i.e depth points are different at each i, j point). Additionally, my array has a 2D horizontal mask. My current solution is: from scipy.interpolate import interp1d def interpz(depths, var, z_levs): var_z = np.zeros_like(var[0,:,:]) for j in range(var_z.shape[0]): for i in range(var_z.shape[1]): if var_z.mask[j,i]==False: f = interp1d(depths[:,j,i], var[:,j,i]) var_z[j,i] = f(z_levs[j,i]) return var_z It works, but it's too slow (my horizontal grid is about 200x600, and the number of interpolations reduces quite a lot with the mask but it still takes about one hour). I've looked into griddata, but there is one issue, and one problem: the issue, it uses all the values to interpolate the point, when I actually only require 1D interpolation in the z direction (which, whatever), BUT the problem is that apparently, it doesn't like nans (in fact. not actual NaNs, but masked values): z, y, x = depths.flatten(), y.flatten(), x.flatten() data = var.flatten() var_z = griddata((z, y, x), data, (z_levs.flatten(), y[0,:,:].flatten(), ...: x[0].flatten()), method='linear') I get: in griddata(points, values, xi, method, fill_value, rescale) 215 elif method == 'linear': 216 ip = LinearNDInterpolator(points, values, fill_value=fill_value, --&gt; 217 rescale=rescale) 218 return ip(xi) 219 elif method == 'cubic' and ndim == 2: scipy/interpolate/interpnd.pyx in scipy.interpolate.interpnd.LinearNDInterpolator.__init__ (scipy/interpolate/interpnd.c:5530)() scipy/spatial/qhull.pyx in scipy.spatial.qhull.Delaunay.__init__ (scipy/spatial/qhull.c:18174)() scipy/spatial/qhull.pyx in scipy.spatial.qhull._Qhull.__init__ (scipy/spatial/qhull.c:4788)() ValueError: Points cannot contain NaN Suggestions are deeply appreciated
score: 0

http://stackoverflow.com/a/52438383
answers question: http://stackoverflow.com/q/52438130
has comment: http://stackoverflow.com/comment/96903842
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/91824681
score: 13
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52438130
downvote count: 0
has body: My guess is that the server does not allow authorization header. Usual issue with aws beanstalk Try to add this to your container commands: 01_wsgipass: command: 'echo "WSGIPassAuthorization On" &gt;&gt; ../wsgi.conf'

http://stackoverflow.com/a/53879043
has body: Found a handy library to do exactly what I need: https://github.com/Infinidat/munch import yaml from munch import Munch mydict = yaml.safe_load(""" a: 1 b: - q: "foo" r: 99 s: 98 - x: "bar" y: 97 z: 96 c: d: 7 e: 8 f: [9,10,11] """) mymunch = Munch(mydict) (I had to write a simple method to recursively convert all subdicts into munches but now I can navigate my data with e.g. &gt;&gt;&gt; mymunch.b.q "foo"
score: 13
accepted answer of: http://stackoverflow.com/q/52570869
has comment: http://stackoverflow.com/comment/110633118
type: AcceptedAnswer
upvote count: 13
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/131114691
answers question: http://stackoverflow.com/q/52570869

http://stackoverflow.com/comment/92059877
comment on: http://stackoverflow.com/q/52531898
score: 0
has text: This is a known issue for Sikuli. One solution is to use [SeeShell](https://a9t9.com/seeshell/), which does not have this issue.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52503695
has comment: http://stackoverflow.com/comment/91952312
score: 3
has answer: http://stackoverflow.com/a/52505893
has comment: http://stackoverflow.com/comment/91954727
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/52505893
accepted answer: http://stackoverflow.com/a/52506059
has body: I am new at Pytorch sorry for the basic question. The model gives me dimension mismatch error how to solve this ? Maybe more than one problems in it. Any help would be appriciated. Thanks class PR(nn.Module): def __init__(self): super(PR, self).__init__() self.conv1 = nn.Conv2d(3,6,kernel_size=5) self.conv2 = nn.Conv2d(6,1,kernel_size=2) self.dens1 = nn.Linear(300, 256) self.dens2 = nn.Linear(256, 256) self.dens3 = nn.Linear(512, 24) self.drop = nn.Dropout() def forward(self, x): out = self.conv1(x) out = self.conv2(x) out = self.dens1(x) out = self.dens2(x) out = self.dens3(x) return out model = PR() input = torch.rand(28,28,3) output = model(input)
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: pytorch
upvote count: 3
type: Question
has title: RuntimeError: expected stride to be a single integer value
has answer: http://stackoverflow.com/a/52506059

http://stackoverflow.com/q/52453204
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91849492
has title: Python script to find max coverage with min false positives
score: 1
has body: I have two datasets: DF_EVENT (1 if Event happened for customer, 0 otherwise) Customer Event 1 1 2 1 3 0 4 1 DF_HX (list of all products purchased by customer) Customer Product_id 1 x 2 y 3 x 3 z 4 y 4 x I want to identify a list of Product_Id from DF_HX that will provide the smallest number of Customers who would cover at least 95% of customers with Event=1 in DF_EVENT. In the example above, if I chose Product_Id=x, I'd capture 66% of events with a population of 3 customers (customers 1, 3 and 4 purchased product x). If I chose Product_Id x and y, I'd capture 100% of events with a population of 4 customers (customers 1, 2, 3 and 4 purchased product x and y).
downvote count: 0
favorite count: 0
tagged with: optimization
tagged with: python
has comment: http://stackoverflow.com/comment/91849491

http://stackoverflow.com/comment/91827956
type: QuestionComment
has text: thanks. the data type for specialsData is `coll_cusip object tran_type object maturity_max float64` and for myTradeFrame is `coll_cusip object tran_type object ` the error information is updated in the question.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52441715

http://stackoverflow.com/comment/92104599
type: Comment
has text: Nice! this solved my problem. You even tidy up my code. Thank You!
comment on: http://stackoverflow.com/a/52584750
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91829722
has text: You need `for twords in text.split():`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52443482
score: 0

http://stackoverflow.com/comment/91874903
comment on: http://stackoverflow.com/a/52466458
type: AnswerComment
has text: @DominiqueM I've added a PEP link to my answer!
score: 0
type: Comment

http://stackoverflow.com/comment/91917976
type: Comment
comment on: http://stackoverflow.com/a/52488198
has text: I'm getting myself confused here but the misunderstanding is definitely on my side. I can understand that writing (and flushing) to a file is a buffered process, but my understanding of this dialogue is that the directory might not be in place (as per the quote I gave)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91836411
comment on: http://stackoverflow.com/a/52446590
has text: And simpler with `ellipsis` : `myarray[(Ellipsis,)+(0,)*(myarray.ndim-N)]`.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52567639
answer count: 3
tagged with: operating-system
has comment: http://stackoverflow.com/comment/92072378
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52567669
type: Question
tagged with: python-os
has answer: http://stackoverflow.com/a/52568605
has body: I'm trying to generate windows CMD using os. After I change the directory using os.system('cd other_dir'), how can I find the new directory, using os?
has title: find the new path after using os.system('cd')
has answer: http://stackoverflow.com/a/52567671
score: 0

http://stackoverflow.com/comment/92396607
score: 0
type: Comment
has text: Please compare your setup with testapp in django-rules repo https://github.com/dfunckt/django-rules/blob/master/tests/testapp/rules.py I'm inspecting the tests that use predicate and i can see book being passed correctly
comment on: http://stackoverflow.com/a/52686494
type: AnswerComment

http://stackoverflow.com/a/52559381
has body: so you have some bugs in your code: inside the while loop you forgot to do the replace. In case of Invalid answer you are out of the loop the the code would fail. the other answers are not relevant, although using strip is better practice in this case. also, do not worry about the newline ibug mention, input is already tacking care of it :
answers question: http://stackoverflow.com/q/52559127
has comment: http://stackoverflow.com/comment/92058018
type: Answer
has comment: http://stackoverflow.com/comment/92058075
score: 0

http://stackoverflow.com/q/52484629
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91913205
has title: groupby boxplot with date positions on xaxis
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91912123
type: Question
has body: there is something missing in my understanding of groupby.boxplot(). I have a dataFrame DF with dates' andvalues` like below : dates values 0 2016-10-20 18:19:15 20.8 1 2016-10-20 18:20:15 21.1 2 2016-10-20 18:21:15 21.3 3 2016-10-20 18:22:15 21.6 4 2016-10-20 18:23:15 21.8 5 2016-10-20 18:24:15 22.1 ... ... 1176468 2018-09-18 03:17:19 19.7 1176469 2018-09-18 03:18:19 20.0 1176470 2018-09-18 03:19:19 20.2 1176471 2018-09-18 03:20:19 20.4 1176472 2018-09-18 03:21:19 20.6 I grouped DF : groups = DF.groupby(pd.Grouper(freq='6M', key='dates')) And then I want a boxplot : box = groups.boxplot(subplots=False) The boxplots are fine, but I would like to customized the xaxis "dates" position formats like it is possible with pyplot.boxplot assigning position = mdates.date2num() and using set_major_locator(mdates.YearLocator()) for example. Does someone know How to do that with groupby.boxplot()?
has comment: http://stackoverflow.com/comment/91913346
tagged with: pandas
has comment: http://stackoverflow.com/comment/91913539
tagged with: boxplot

http://stackoverflow.com/comment/92081245
type: AnswerComment
comment on: http://stackoverflow.com/a/52565513
type: Comment
has text: @Oroshimaru I checked that the code I posted works. Used the following sample data: `x=y=z=0` `r=5` `resolution=10`.
score: 0

http://stackoverflow.com/a/59032514
answers question: http://stackoverflow.com/q/52561237
has body: upstream api_server2 { server 127.0.0.1:3001; } instead of this add:- upstream api_server2{ server integration-app:3001; // container name } CMD [ "uwsgi", "--socket", "0.0.0.0:3001", \ "--protocol", "http", \ "--wsgi", "wsgi:app" ] instead of http protocol add uwsgi
type: Answer
score: 0

http://stackoverflow.com/a/52605858
answers question: http://stackoverflow.com/q/52526546
type: Answer
has body: New edit : Answer dict={} with open(fileName, 'r') as file_to_read: for line in file_to_read: data = json.loads(line) json_tree = objectpath.Tree(data) json.dumps(data) dict[json_tree.execute('$.id')] = list(json_tree.execute('$.users.name.text')) return dict
accepted answer of: http://stackoverflow.com/q/52526546
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/52506326
type: Answer
answers question: http://stackoverflow.com/q/52505861
has body: class ModLog: def __init__(self, bot): self.bot = bot async def on_ready(self): await self.bot.wait_until_ready() for guild in self.bot.guilds: channel = await self.get_channel(guild) if channel: self.bot.loop.create_task(self.modlog_purge(channel)) async def get_channel(guild): # Whatever your logic for getting the Channel for a given guild is async def modlog_purge(self, channel): while True: now = datetime.utcnow() two_weeks_ago = now - timedelta(days=14) await channel.purge(before=two_weeks_ago) await asyncio.sleep(86400) def setup(bot): q = ModLog(bot) bot.add_cog(q) Here's how I would structure this (I'm not on a computer with discord.py at the moment, so there may be some errors). We have an on_ready event that kicks off background tasks for each server that has a channel we want to maintain (this could instead loop through a list of channels, or something similar). The actual purge is all taken care of by the TextChannel.purge coroutine. We just pass it a datetime object, and it deletes 100 messages from before that date (this is configurable). It then sleeps for a day and repeats.
score: 0

http://stackoverflow.com/a/59012728
downvote count: 0
type: Answer
upvote count: 1
has body: Just answering to update this post, there is now a nn.Flatten() layer in Pytorch as of 1.3: https://pytorch.org/docs/stable/_modules/torch/nn/modules/flatten.html Also, worth mentioning that if you can't use >=1.3 and you "need" that CNN output size (for example if you have multiple heads, most people do programmatically get the output from a dummy input, with something like: def get_flat_fts(self, input_shape, conv_net): f = conv_net(Variable(torch.ones(1,*input_shape))) return int(np.prod(f.size()[1:]))
score: 1
answers question: http://stackoverflow.com/q/52474439

http://stackoverflow.com/comment/91836898
type: Comment
comment on: http://stackoverflow.com/a/52445264
has text: I've updated my answer so that dicts in `list1` would get replaced by any dict in `dict2` that matches both important keys, as opposed to my previous answer, which would only match if the dict in `list1` and the dict in `list2` are of the same index in their respective lists. Please try again.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52537534
upvote count: 1
has comment: http://stackoverflow.com/comment/92014492
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92014515
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92014917
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92015795
has body: From my program I call a command line XSLT processor (such Saxon or xsltproc). Then (for testing purposes) I want to compare the output of the processor with a predefined string. The trouble is that XML can be formatted differently. The following three are different strings: &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;x/&gt; &lt;?xml version="1.0"?&gt; &lt;x/&gt; &lt;?xml version="1.0"?&gt; &lt;x /&gt; How to check output from different XSLT processors to match a given XML string? Maybe there is a way (not necessarily standartized) for different XSLT processors to output exactly the same? I use Python 3.
has answer: http://stackoverflow.com/a/52541107
tagged with: xslt
type: Question
has answer: http://stackoverflow.com/a/52537554
has answer: http://stackoverflow.com/a/52570231
possible better answer: http://stackoverflow.com/a/52541107
accepted answer: http://stackoverflow.com/a/52570231
has comment: http://stackoverflow.com/comment/92019569
has title: How to check equivalence of two XML documents?
has comment: http://stackoverflow.com/comment/92015172
answer count: 3

http://stackoverflow.com/comment/91814843
type: Comment
has text: To simply print a space you would use print(" "). A space despite the fact it's empty is still considered a character. Which is why the quotations are needed.
comment on: http://stackoverflow.com/q/52435711
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92038878
comment on: http://stackoverflow.com/q/52548751
type: Comment
type: QuestionComment
has text: my question like [https://stackoverflow.com/questions/9416062/sql-like-inside-array]
score: 0

http://stackoverflow.com/a/52476344
answers question: http://stackoverflow.com/q/52473040
has comment: http://stackoverflow.com/comment/91914241
has comment: http://stackoverflow.com/comment/91940778
downvote count: 0
has comment: http://stackoverflow.com/comment/91899777
has comment: http://stackoverflow.com/comment/91899893
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91914813
accepted answer of: http://stackoverflow.com/q/52473040
has comment: http://stackoverflow.com/comment/91931728
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91935303
has body: First of all you do not have to use cv2.imshow() inside PyQt since it blocks the python event loop, if you want to show the image of opencv in PyQt you have to convert it to QImage or QPixmap, the next class implements the data acquisition of opencv and it allows to obtain the QImage but it must be executed in a thread. OpencvQt.py import cv2 import numpy as np from PyQt5 import QtCore, QtGui, QtWidgets class Capture(QtCore.QObject): started = QtCore.pyqtSignal() frameReady = QtCore.pyqtSignal(np.ndarray) def __init__(self, parent=None): super(Capture, self).__init__(parent) self._frame = None self.m_timer = QtCore.QBasicTimer() self.m_videoCapture = cv2.VideoCapture() @QtCore.pyqtSlot() def start(self, cam=0): if self.m_videoCapture is not None: self.m_videoCapture.release() self.m_videoCapture = cv2.VideoCapture(cam) if self.m_videoCapture.isOpened(): self.m_timer.start(0, self) self.started.emit() @QtCore.pyqtSlot() def stop(self): self.m_timer.stop() def __del__(self): self.m_videoCapture.release() def frame(self): return self.m_frame def timerEvent(self, event): if event.timerId() != self.m_timer.timerId(): return ret, val = self.m_videoCapture.read() if not ret: self.m_timer.stop() return self.m_frame = val self.frameReady.emit(self.m_frame) frame = QtCore.pyqtProperty(np.ndarray, fget=frame, notify=frameReady, user=True) class Converter(QtCore.QObject): imageReady = QtCore.pyqtSignal(QtGui.QImage) def __init__(self, parent=None): super(Converter, self).__init__(parent) self.m_frame = np.array([]) self.m_timer = QtCore.QBasicTimer() self.m_processAll = True self.m_image = QtGui.QImage() def queue(self, frame): self.m_frame = frame if not self.m_timer.isActive(): self.m_timer.start(0, self) def process(self, frame): w, h, _ = frame.shape rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self.m_image = QtGui.QImage(rgbImage.data, h, w, QtGui.QImage.Format_RGB888) self.imageReady.emit(QtGui.QImage(self.m_image)) def timerEvent(self, event): if event.timerId() != …

http://stackoverflow.com/a/52452054
has comment: http://stackoverflow.com/comment/91847490
has comment: http://stackoverflow.com/comment/91847448
score: 1
has comment: http://stackoverflow.com/comment/91847502
answers question: http://stackoverflow.com/q/52452026
has comment: http://stackoverflow.com/comment/91847463
has comment: http://stackoverflow.com/comment/91847943
downvote count: 0
has body: This is a good place to use zip and evaluate from there a = [1, 2, 3, 4, 5, 6, 7, 8, 9] f = [True, False, False, False, True, True, False, True, False] x = list(zip(a, f)) c = [i[0] if i[1] == True else '' for i in x] :~/python/stack$ python3.7 sum.py [1, '', '', '', 5, 6, '', 8, '']
type: Answer
has comment: http://stackoverflow.com/comment/91847920
upvote count: 1

http://stackoverflow.com/q/52445903
has comment: http://stackoverflow.com/comment/91852039
has comment: http://stackoverflow.com/comment/91837205
upvote count: 1
has comment: http://stackoverflow.com/comment/91835844
has comment: http://stackoverflow.com/comment/91849877
favorite count: 0
has comment: http://stackoverflow.com/comment/91856148
has title: How can I fix my rolling mean program in tensorflow
answer count: 0
type: UnansweredQuestion
has body: I am trying to create a basic tensorflow program to compute and print the rolling mean of random variables to learn variable assignment etc. I am not able to understand a few things why do i need to supply the feed dict session.run(current_sum_assign_op, feed_dict={current_random: num}) why doesn't the values get added inside the loop, every time it only prints the random number generated divided by two. code : import numpy as np import tensorflow as tf current_sum = tf.Variable(0, name='current_sum') current_div = tf.Variable(1, name='div') current_random = tf.placeholder(dtype=tf.int32, shape=[], name='current_random') mean = tf.div(current_sum, current_div) model = tf.global_variables_initializer() with tf.Session() as session: for i in range(100): num = np.random.random() * 100 current_sum_assign_op = tf.assign(current_sum, value=current_sum + current_random) current_div_assign_op = tf.assign(current_div, value=current_div + 1) session.run(model) session.run(current_random, feed_dict={current_random: num}) session.run(current_sum_assign_op, feed_dict={current_random: num}) session.run(current_div_assign_op) session.run(mean) print('num =', num) print('mean = ') session.run(tf.Print(mean, [mean], 'Mean is')) session.run(tf.Print(current_div, [current_div], 'Div is')) session.run(model) Can you help me understand what is going on and how I can fix it?
tagged with: python
has comment: http://stackoverflow.com/comment/91835790
has comment: http://stackoverflow.com/comment/91837119
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91834751
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/52450342
tagged with: pyinstaller
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am not able to convert following python code into windows executable using pyinstaller. Python code is working fine with python 2.7 and python 3.6. I have installed pyinstaller from github/pyinstaller/pyinstaller/archive/develop.tae.gz import cv2 import os import inspect import os.path filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) os.chdir(path) id = open('Emp.txt', 'r').read() writePath = "./Images/" faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") cam = cv2.VideoCapture(0) sampleNum = 0 while(True): # Capture frame by frame ret, frame = cam.read() #frame = np.full((100,80,3), 12, dtype = np.uint8) grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(grayFrame,scaleFactor=1.5, minNeighbors=5) for (x,y,w,h) in faces: sampleNum = sampleNum + 1 cv2.imwrite(writePath + str(id) + "." +str(sampleNum) + ".jpg", grayFrame[y:y+h,x:x+w]) color = (255,0,0) thickness = 2 cv2.rectangle(frame,(x,y),(x+w, y+h),color, thickness) cv2.imshow ("frame",frame) cv2.waitKey(2) if (sampleNum &gt; 5): break cam.release() cv2.destroyAllWindows()
tagged with: opencv3.0
type: Question
has title: converting python program into windows executable using pyinstaller
downvote count: 0
score: 1
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/91984714
type: Comment
score: 2
type: QuestionComment
has text: Well you never call your function...
comment on: http://stackoverflow.com/q/52522584

http://stackoverflow.com/comment/92007936
has text: @Alasdair great now it works fine..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52533812
score: 0

http://stackoverflow.com/a/52584505
type: Answer
answers question: http://stackoverflow.com/q/52583876
score: 0
has body: Using pandas and dictionaries. purch_df = pd.DataFrame(Purchase, columns = ['name','product','count']) d = dict(Product) Create new column 'price' then perform calculations and save to a new column 'total' purch_df['price'] = [d[product] for product in purch_df['product']] purch_df['total'] = purch_df['count'] * purch_df['price'] Create a dictionary to save grouped dataframes to for future lookup d2 = {} for group, frame in purch_df.groupby('name'): d2[group] = list(frame.sort_values('total', ascending = False).iloc[:3,1]) Extract the desired lists from the dictionary d2 Result = [lst for _, lst in d2.items()]

http://stackoverflow.com/a/52487981
upvote count: 1
downvote count: 1
has body: Ok, took me some time but it was fun doing it. The idea here is to first create a continuous path out of the coordinates which define the walls. Next, create an object Path. Now you loop through each point in the DataFrame and then look if the created Path contains that (x,y) point using contains_point. I additionally had to use the condition x==55 and (5&lt;y&lt;=55) in the if statement so as to include the column adjacent to the right most wall. import matplotlib.path as mplPath import numpy as np wallPointsX = [5,5,30,30,55,55,5] wallPointsY = [5,30,30,55,55,5,5] # Create a continuous path across the wall coordinates path = np.array([list(i) for i in zip(wallPointsX, wallPointsY)]) Path = mplPath.Path(path) df = pd.DataFrame(0, index=range(60), columns=range(60)) for x in range(0, 60): for y in range(0, 60): if Path.contains_point((x,y)) or (x==55 and (5&lt;y&lt;=55)): df[x-1][y-1] = 5 #Should only apply inside "walls" plt.plot(wallPointsX, wallPointsY) plt.pcolor(df) Output
has comment: http://stackoverflow.com/comment/91917734
answers question: http://stackoverflow.com/q/52487612
type: Answer
has comment: http://stackoverflow.com/comment/91918342
score: 0

http://stackoverflow.com/comment/91990205
score: 0
type: AnswerComment
type: Comment
has text: You're right. I was typing out my code in this question while looking at my IDE so I didn't catch that error.
comment on: http://stackoverflow.com/a/52524768

http://stackoverflow.com/comment/92028314
has text: oh jeez im stupid, thanks man, it works fine!
comment on: http://stackoverflow.com/q/52544063
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92045202
comment on: http://stackoverflow.com/q/52553102
type: Comment
type: QuestionComment
has text: Please post a **minimal**, **complete**, **verifiable** example - cf https://stackoverflow.com/help/mcve. Your current snippet is neither minimal nor complete.
score: 2

http://stackoverflow.com/a/52553732
has comment: http://stackoverflow.com/comment/92047018
has comment: http://stackoverflow.com/comment/92046991
has comment: http://stackoverflow.com/comment/92046950
has comment: http://stackoverflow.com/comment/92046858
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52553634
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52553634
has body: In that case it is probably better to construct a regex, and use the __iregex lookup [Django-doc]: import re data = ['Donut', 'Pizza'] the_regex = '|'.join(re.escape(datum) for datum in data) items=ItemVariation.objects.filter( item__restaurant__id = i['restaurant']['id'], keyword__name__iregex=the_regex, keyword__mood__moods__in=moods_array ).select_related() An alternative is to create an long OR, and each time use keyword__name__icontains per item in the array. But this will probably be more "ugly".
type: Answer
has comment: http://stackoverflow.com/comment/92046901
score: 2
downvote count: 0

http://stackoverflow.com/a/52573409
answers question: http://stackoverflow.com/q/52573049
upvote count: 1
has body: Your first two benchmarks essentially nibble off a single byte from the left until there is nothing left. For the bytes example, this does N copies, for memoryview there is never a copy, just an adjustment of the length of the view Your last example isn't at all similar, instead of nibbling off a single byte, you nibble off a progressively larger number of bytes (b[1:] b[2:] b[3:]) -- eventually the string is exhausted and you're slicing an empty string (more precisely when i * (i + 1) / 2 &gt; n). For example with the 100,000 byte sequence, you're doing noops after 446 iterations.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92083087
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52573049

http://stackoverflow.com/comment/91943316
has text: Yes. Your are right.
type: Comment
comment on: http://stackoverflow.com/q/52500506
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92110745
type: QuestionComment
has text: sory I put it wrong. rewrite the error message
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52587761

http://stackoverflow.com/comment/91906724
type: QuestionComment
type: Comment
has text: There's nothing in your code that is checking whether a number is prime. It's really not clear what your question is.
score: 2
comment on: http://stackoverflow.com/q/52482060

http://stackoverflow.com/comment/91925039
type: QuestionComment
comment on: http://stackoverflow.com/q/52491747
has text: Thanks, I learnt something today, sorry for the duplicate question.
score: 0
type: Comment

http://stackoverflow.com/comment/92035880
has text: Also see https://stackoverflow.com/a/8140747/4014959
score: 1
comment on: http://stackoverflow.com/q/52548178
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92037042
comment on: http://stackoverflow.com/a/52548677
score: 0
type: AnswerComment
type: Comment
has text: @YolandaHui I'll break it down line by line. Also, I changed the variable names to be more clear. The first line is a simple `for` loop counting from 0-9 and if we add `+1` to it we get 1-10 which is the desired step size (you want to increment first by 1, then 2, then 3, etc.). The second `for` loop will run from 0-9 again and again we need to add `+1` to it since you want to count from 1-10, not 0-9. This second loop here will run once for every step size (since it's inside of the `stepSize` for loop).

http://stackoverflow.com/comment/92114629
has text: @MohanRadhakrishnan thanks! I will check it out
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52587151

http://stackoverflow.com/comment/91926814
comment on: http://stackoverflow.com/q/52492961
type: QuestionComment
has text: What are the conditions based on which you are assigning priority?
score: 0
type: Comment

http://stackoverflow.com/comment/91983652
score: 0
has text: One note that might also help clarify the situation. From [Kv Language Documentation](https://kivy.org/doc/stable/guide/lang.html): `An id is limited in scope to the rule it is declared in`. Explains why the `ids.rbox.ids` chaining must be used.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52521775

http://stackoverflow.com/comment/91902524
type: QuestionComment
has text: No. i just try to with "sudo" command
type: Comment
comment on: http://stackoverflow.com/q/52479486
score: 0

http://stackoverflow.com/q/52449920
favorite count: 0
duplicate of: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/91843194
linked to: http://stackoverflow.com/q/37717584
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91843799
duplicate of: http://stackoverflow.com/q/37717584
has body: let's say I have a variable called "x" and a string that has the value of "x" (string1 = "x"). How do I do stuff with the variable through the string? For example change the variable's value or call a method if it's an object? Thanks in advance
has answer: http://stackoverflow.com/a/52450074
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91843437
has comment: http://stackoverflow.com/comment/91843642
linked to: http://stackoverflow.com/q/1550479
has answer: http://stackoverflow.com/a/52450091
type: Question
has title: Do stuff with variable that has the same name of a string
answer count: 3
has comment: http://stackoverflow.com/comment/91843333
upvote count: 1
has answer: http://stackoverflow.com/a/52450078
has comment: http://stackoverflow.com/comment/91843443

http://stackoverflow.com/comment/91936595
has text: You mean like this? `return tatic_file( filename.encode("utf-8"), root=filepath, download=True )` ? If you mean that then i do have tried it but it return an error.
comment on: http://stackoverflow.com/q/52497777
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52482969
answers question: http://stackoverflow.com/q/52482762
type: Answer
downvote count: 0
score: 1
has body: try using two list comprehensions: word='testing' vov=[x if x in vowel_set else '' for x in word] cons=[x if x not in vowel_set else '' for x in word] ('').join(cons+vov)
upvote count: 1

http://stackoverflow.com/comment/92128583
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52555837
type: AnswerComment
has text: You only need this if the OS is Windows, which is why I asked them what OS they were on

http://stackoverflow.com/q/52547223
tagged with: matplotlib
type: Question
accepted answer: http://stackoverflow.com/a/52547284
downvote count: 0
has body: I'm using pandas DataReader to graph stock charts in matplotlib, but the dates don't show up on the x-axis when I use the following code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import datetime as dt from datetime import datetime import pandas_datareader.data as web start = datetime(2014,1,1) end = datetime(2018,9,27) spy = web.DataReader('SPY','iex',start,end) spy['open'].plot(xlim=['2018-01-01','2018-02-28']) Result: Chart of SPY with no x-axis dates However, when I import the same data from csv using the following command, the dates show up just fine when I plot the data: spy_csv = pd.read_csv('spy.csv',index_col='date',parse_dates=True) I'm assuming the "parse_dates=True" is making the difference, so I'm wondering if there is an equivalent command when importing from DataReader. What would that equivalent look like in my DataReader code?
favorite count: 0
tagged with: pandas
answer count: 1
tagged with: python
tagged with: pandas-datareader
has answer: http://stackoverflow.com/a/52547284
upvote count: 1
has title: x-axis dates not showing up on matplotlib when importing data from pandas DataReader
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/52493601
has title: Python exersice to accept a 4 digit bin numbers and put in a list those divisible by 5.
score: -2
has comment: http://stackoverflow.com/comment/91927987
has answer: http://stackoverflow.com/a/52493824
answer count: 3
has comment: http://stackoverflow.com/comment/91928135
has answer: http://stackoverflow.com/a/52493809
favorite count: 0
accepted answer: http://stackoverflow.com/a/52493959
has comment: http://stackoverflow.com/comment/91927788
tagged with: python
has body: result_list = [] nr = int(input("Please enter a 4 digit number made from 0 and 1 : ")) if len(str(nr)) &gt; 4: nr = int(input("Please enter a 4 digit number made from 0 and 1 : ")) elif str(nr).split(): for x in str(nr): if x == 0 or x == 1: if nr % 5 == 0: result_list.append(nr) else: nr = int(input("Please enter a 4 digit number made from 0 and 1 : ")) else: nr = int(input("Please enter a 4 digit number made from 0 and 1 : ")) else: print(result_list) I have the following exercise : "Write a Python program which accepts a sequence of comma separated 4 digit binary numbers as its input and print the numbers that are divisible by 5 in a comma separated sequence." But i don`t get how to get it done. Any help appreciated.
has comment: http://stackoverflow.com/comment/91927757
has answer: http://stackoverflow.com/a/52493959
downvote count: 3
has comment: http://stackoverflow.com/comment/91927946
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91930844
possible better answer: http://stackoverflow.com/a/52493824

http://stackoverflow.com/q/52558456
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92055858
has comment: http://stackoverflow.com/comment/92055803
has comment: http://stackoverflow.com/comment/92055744
type: Question
score: 0
tagged with: pandas
has title: Changing column in DataFrame
has answer: http://stackoverflow.com/a/52558629
answer count: 1
accepted answer: http://stackoverflow.com/a/52558629
has body: I am looking to change part of the string in a column of a data frame. I, however, can not get it to update in the data frame. This is my code. import pandas as pd #File path csv = '/home/test.csv' #Read csv to pandas df = pd.read_csv(nuclei_annotations_csv, header=None, names=['A', 'B', 'C', 'D', 'E', 'F']) #Select Data to update paths = df['A'] #Loop over data for x in paths: #Select data to updte old = x[:36] #Update value new = '/Datasets/RetinaNetData' #Replace new_path = x.replace(old, new) #Save values to DataFrame paths.update(new_path) #Print updated DataFrame print(df) The inputs and output I would like are: Input: /Annotations/test_folder/10_m03293_ORG.png /Annotations/test_folder/10_m03293_ORG.png /Annotations/test_folder/10_m03293_ORG.png /Annotations/test_folder/10_m03293_ORG.png OutPut: /Datasets/RetinaNetData/10_m03293_ORG.png /Datasets/RetinaNetData/10_m03293_ORG.png /Datasets/RetinaNetData/10_m03293_ORG.png /Datasets/RetinaNetData/10_m03293_ORG.png
tagged with: python
has comment: http://stackoverflow.com/comment/92055717

extract
tags question: http://stackoverflow.com/q/52555139
tags question: http://stackoverflow.com/q/52490060
tag name: extract
type: Tag
tags question: http://stackoverflow.com/q/52545774
tags question: http://stackoverflow.com/q/52430623

http://stackoverflow.com/comment/91971727
comment on: http://stackoverflow.com/a/52515320
score: 1
type: AnswerComment
has text: Will do, but one further question: I just tried it with my data which has value rows (i.e. RX, RY, TX, TZ) that have NaN values. The stacking removes them in the process. Is there a way to keep the NaN rows?
type: Comment

http://stackoverflow.com/a/52463875
has body: "You need to go deeper" (c) =) After 2 convolution/pooling layers you still have 80x80 image, which becomes a whopping 6400 large Dense layer after flattening. If you have only 17 classes, you need to go deeper, add more convolution and pooling, so your image becomes something about 20x20 (2 more extra conv/maxpool), then your network will work better and require less memory for Dense layers.
type: Answer
has comment: http://stackoverflow.com/comment/91870986
has comment: http://stackoverflow.com/comment/91869862
answers question: http://stackoverflow.com/q/52463538
has comment: http://stackoverflow.com/comment/91870876
has comment: http://stackoverflow.com/comment/91870669
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/66679059
type: Answer
score: 1
upvote count: 1
has body: You might be able to iterate over a C++ enum exposed by pybind11 with something like the below. for name, enum_value in Color.__members__.items(): print(name, enum_value) The way I figured out this approach was possible was by running dir(EnumClass) and seeing all the private attributes available, of which __members__ was one.
answers question: http://stackoverflow.com/q/52459530
downvote count: 0

http://stackoverflow.com/q/52471331
answer count: 2
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/91884562
has comment: http://stackoverflow.com/comment/91884910
favorite count: 0
has answer: http://stackoverflow.com/a/52471498
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52471579
downvote count: 0
has comment: http://stackoverflow.com/comment/91884922
score: 1
has title: Pandas Groupby with Agg Min/Max date
has body: I am trying to get the min/max dates from columns that might not have a date. I have tried things like '', "NaN", True, False, 0, etc... I first set the 'p_date' and 's_date' from the actual date based on the action of '+' or '-'. df_td [ 'p_date' ] = np.where ( df_td.action == '+', df_td.date, ??? ) df_td [ 's_date' ] = np.where ( df_td.action == '-', df_td.date, ??? ) So I need the min of the p_date &amp; max of the s_date here. issue p_date s_date 0 issue 2012-11-01 1 issue 2013-12-09 2 issue 2014-12-08 3 issue 2016-01-13 4 issue 2012-11-01 5 issue 2014-03-26 6 issue 2015-05-29 7 issue 2013-12-18 8 issue 2016-01-13 I do a group by g = df_td.groupby ( [ 'name', 'type' ], as_index = False ).agg ( { ... 'p_date': 'min', 's_date': 'max' } ) This gives me the following error. '&lt;=' not supported between instances of 'datetime.date' and 'str' if I make up a date for the blank space it does work but this is not a great option. What can I fill the date with to get it to work? Thanks.
type: Question
has answer: http://stackoverflow.com/a/52471579
possible better answer: http://stackoverflow.com/a/52471498

http://stackoverflow.com/a/52437264
has body: Change plt.imshow(rdmImg) into plt.imshow(rdmImg.astype(np.uint8)) This may related to this issue https://github.com/matplotlib/matplotlib/issues/9391/
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91834005
downvote count: 0
has comment: http://stackoverflow.com/comment/91817558
score: 1
answers question: http://stackoverflow.com/q/52436652

http://stackoverflow.com/q/52462606
type: Question
has title: Why my final image turned into red after putpixel?
tagged with: image
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I am gonna eliminate the ‘noise’ of the images, mainly is salt-n-pepper noise by using sorting and then assigns the mean value to the coordinate. The result should be based on the previous color, but what I got turned into RED.. Is there any parameter wrong with this? Big thanks! from PIL import Image path='MonaLisa.png' img=Image.open(path) members=[(0,0)]*9 size=width,height=img.size; newimg=Image.new("RGB",(width,height),"white") for i in range(1,width-1): for j in range(1,height-1): members[0] = img.getpixel((i-1,j-1)) members[1] = img.getpixel((i-1,j)) members[2] = img.getpixel((i-1,j+1)) members[3] = img.getpixel((i,j-1)) members[4] = img.getpixel((i,j)) members[5] = img.getpixel((i,j+1)) members[6] = img.getpixel((i+1,j-1)) members[7] = img.getpixel((i+enter image description here1,j)) members[8] = img.getpixel((i+1,j+1)) members.sort() newimg.putpixel((i,j),(members[4])) newimg.show()
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/52515563

http://stackoverflow.com/comment/91988823
has text: If you want to have it working with minimal changes use a singleton list `m=[1.1] `
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52524211

http://stackoverflow.com/comment/92014089
has text: @norok2 this is just a minimal example to illustrate the problem. I'm actually generating a rather complicated function which does this many times, and I need the whole thing to be jit-compiled.
comment on: http://stackoverflow.com/q/52536806
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52566002
score: 0
has body: import sys sys.stdout.write("rotation: %d%%\t [note]"% 123) This should work
type: Answer
answers question: http://stackoverflow.com/q/52565921

http://stackoverflow.com/comment/92095302
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52579754
has text: Aww, I fixed my issue. I feel very stupid now. It should have been df.index not df.target.

http://stackoverflow.com/comment/91911997
type: Comment
type: QuestionComment
has text: @gopalakrishna Update the question with text based HTML
comment on: http://stackoverflow.com/q/52482982
score: 0

http://stackoverflow.com/a/52444206
has comment: http://stackoverflow.com/comment/91887638
has comment: http://stackoverflow.com/comment/91889328
type: Answer
has body: First, select the rows where the conditions apply (note the parentheses and &amp; instead of and): df_fd_temp = df_fd_temp[(df_fd_temp['User_ID'] != 'IND') &amp; (df_fd_temp['Incoming_ID'] == 'Airtel') &amp; (df_fd_temp['Incoming_Category'] == 'Foreign') &amp; (df_fd_temp['Outgoing_ID'] == 'Airtel') &amp; (df_fd_temp['Outgoing_Category'] == 'Foreign') &amp; (df_fd_temp['Current_Operation'] == 'NO') &amp; (df_fd_temp['Active'] == 'NO')] Then, do the group-by logic: df_grouped = df_fd_temp.groupby(['Customer_No','Rate','Customer_Type']) You now have a groupby object, which you can further manipulate and filter: df_grouped.filter(lambda x: "Check" in x['Customer_Type']) You might need to tweak the group filtering based on what your actual dataset looks like. Further reading: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.filter.html
answers question: http://stackoverflow.com/q/52443444
score: 0

http://stackoverflow.com/a/52571565
accepted answer of: http://stackoverflow.com/q/52571493
has body: Same as you would for two points on a plane, or for 3 points in a 3D space - but now extended to a 4 dimensional vector space: sqrt((a1-b1)^2+(a2-b2)^2+(a3-b3)^2+(a4-b4)^2) This extends to any number of dimensions
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/92079767
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52571493

filesplitting
type: Tag
tag name: filesplitting
tags question: http://stackoverflow.com/q/52567746

http://stackoverflow.com/q/52548977
has body: I have already installed Quandl library along with sci-kit learn, matplotlib and pandas through pip but while importing the quandl library, it is showing error. I have attached the screenshots here.
tagged with: python
has answer: http://stackoverflow.com/a/52549043
tagged with: quandl
type: AnsweredQuestion
tagged with: python-imaging-library
type: Question
score: 0
has title: Error while importing Quandl to python shell
answer count: 1
accepted answer: http://stackoverflow.com/a/52549043
has comment: http://stackoverflow.com/comment/92037036

django
tags question: http://stackoverflow.com/q/52443946
tags question: http://stackoverflow.com/q/52454246
tags question: http://stackoverflow.com/q/52587144
tags question: http://stackoverflow.com/q/52459560
tags question: http://stackoverflow.com/q/52440507
tags question: http://stackoverflow.com/q/52489595
tags question: http://stackoverflow.com/q/52558760
tags question: http://stackoverflow.com/q/52440041
tags question: http://stackoverflow.com/q/52495474
tags question: http://stackoverflow.com/q/52537445
tags question: http://stackoverflow.com/q/52580825
tags question: http://stackoverflow.com/q/52573981
tags question: http://stackoverflow.com/q/52480551
tags question: http://stackoverflow.com/q/52465106
tags question: http://stackoverflow.com/q/52445743
tags question: http://stackoverflow.com/q/52552848
tags question: http://stackoverflow.com/q/52501435
tags question: http://stackoverflow.com/q/52435147
tags question: http://stackoverflow.com/q/52470310
tags question: http://stackoverflow.com/q/52516937
tags question: http://stackoverflow.com/q/52588466
tags question: http://stackoverflow.com/q/52470386
tags question: http://stackoverflow.com/q/52467768
tags question: http://stackoverflow.com/q/52581376
tags question: http://stackoverflow.com/q/52552784
tags question: http://stackoverflow.com/q/52431921
tags question: http://stackoverflow.com/q/52503027
tags question: http://stackoverflow.com/q/52496972
tags question: http://stackoverflow.com/q/52517905
tags question: http://stackoverflow.com/q/52489365
tags question: http://stackoverflow.com/q/52430649
tags question: http://stackoverflow.com/q/52467251
tags question: http://stackoverflow.com/q/52465439
tags question: http://stackoverflow.com/q/52459844
tags question: http://stackoverflow.com/q/52530756
tags question: http://stackoverflow.com/q/52510695
tags question: http://stackoverflow.com/q/52459471
tags question: http://stackoverflow.com/q/52451179
tags question: http://stackoverflow.com/q/52526202
tags question: http://stackoverflow.com/q/52504067
tags question: http://stackoverflow.com/q/52486424
tags question: http://stackoverflow.com/q/52463847
tags question: http://stackoverflow.com/q/52462931
tags question: http://stackoverflow.com/q/52464095
tags question: http://stackoverflow.com/q/52583395
tags question: http://stackoverflow.com/q/52555798
tags question: http://stackoverflow.com/q/52487480
tags question: http://stackoverflow.com/q/52437156
tags question: http://stackoverflow.com/q/52473275
tags question: http://stackoverflow.com/q/52486117
tags question: http://stackoverflow.com/q/52587761
tags question: http://stackoverflow.com/q/52527932
tags question: http://stackoverflow.com/q/52555458
tags question: http://stackoverflow.com/q/52537249
tags question: http://stackoverflow.com/q/52534235
tags question: http://stackoverflow.com/q/52569202
tags question: http://stackoverflow.com/q/52451519
tags question: http://stackoverflow.com/q/52537082
type: Tag
tags question: http://stackoverflow.com/q/52432517
tags question: http://stackoverflow.com/q/52466343
tags question: http://stackoverflow.com/q/52441766
tags question: http://stackoverflow.com/q/52555640
tags question: http://stackoverflow.com/q/52534916
tags question: http://stackoverflow.com/q/52492723
tags question: http://stackoverflow.com/q/52536513
tags question: http://stackoverflow.com/q/52529397
tags question: http://stackoverflow.com/q/52465740
tags question: http://stackoverflow.com/q/52508541
tags question: http://stackoverflow.com/q/52483763
tags question: http://stackoverflow.com/q/52578687
tags question: http://stackoverflow.com/q/52461137
tags question: http://stackoverflow.com/q/52581428
tags question: http://stackoverflow.com/q/52556450
tags question: http://stackoverflow.com/q/52454977
tags question: http://stackoverflow.com/q/52458708
tags question: http://stackoverflow.com/q/52430656
tags question: http://stackoverflow.com/q/52525482
tags question: http://stackoverflow.com/q/52479478
tags question: http://stackoverflow.com/q/52503295

http://stackoverflow.com/comment/92136742
type: Comment
type: QuestionComment
has text: @VigneshSP here is what it says: 21315#0: *3284 upstream prematurely closed connection while reading response header from upstream, client: 204.107.115.18, server: www.gndhtrn.tk, request: "GET /crm-project-api HTTP/2.0", upstream: "uwsgi://127.0.0.1:3001", host: "www.gndhtrn.tk"
score: 0
comment on: http://stackoverflow.com/q/52561237

statsmodels
tags question: http://stackoverflow.com/q/52449101
tags question: http://stackoverflow.com/q/52494298
tags question: http://stackoverflow.com/q/52483819
tags question: http://stackoverflow.com/q/52562664
tags question: http://stackoverflow.com/q/52525734
tags question: http://stackoverflow.com/q/52517002
type: Tag
tag name: statsmodels
tags question: http://stackoverflow.com/q/52551247
tags question: http://stackoverflow.com/q/52555841
tags question: http://stackoverflow.com/q/52451049

http://stackoverflow.com/comment/91853929
has text: Well, `setattr` doesn't work, `locals()` only works in the global scope, and dicts always work, so... I think we have a clear winner.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52455778

http://stackoverflow.com/a/52517831
accepted answer of: http://stackoverflow.com/q/52517516
has comment: http://stackoverflow.com/comment/92048201
upvote count: 14
has comment: http://stackoverflow.com/comment/91997493
has comment: http://stackoverflow.com/comment/92000936
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92048055
has comment: http://stackoverflow.com/comment/91975156
type: Answer
has comment: http://stackoverflow.com/comment/129602511
has comment: http://stackoverflow.com/comment/92047785
downvote count: 0
has comment: http://stackoverflow.com/comment/92070139
has body: After loading your UI (if you use .ui file) or in init() of your window, respectively. It should be like this: class MyDialog(QtWidgets.QDialog): def __init__(self): super(MyDialog, self).__init__() self.setFixedSize(640, 480) Let me know if this works for you. Edit: this is how the provided code should be reformatted to work. from PyQt5 import QtWidgets # It is considered a good tone to name classes in CamelCase. class MyFirstGUI(QtWidgets.QDialog): def __init__(self): # Initializing QDialog and locking the size at a certain value super(MyFirstGUI, self).__init__() self.setFixedSize(411, 247) # Defining our widgets and main layout self.layout = QtWidgets.QVBoxLayout(self) self.label = QtWidgets.QLabel("Hello, world!", self) self.buttonBox = QtWidgets.QDialogButtonBox(self) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok) # Appending our widgets to the layout self.layout.addWidget(self.label) self.layout.addWidget(self.buttonBox) # Connecting our 'OK' and 'Cancel' buttons to the corresponding return codes self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) gui = MyFirstGUI() gui.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/92048094
answers question: http://stackoverflow.com/q/52517516
score: 14

http://stackoverflow.com/comment/92083525
type: Comment
comment on: http://stackoverflow.com/a/52550312
type: AnswerComment
has text: @Vishal Have you figured out what solution to use? You can upvote all answers you found helpful, and accept the one you ended up using.
score: 0

http://stackoverflow.com/comment/92503673
comment on: http://stackoverflow.com/a/52501786
type: Comment
score: 1
has text: @anarchist912, I have generalised the solution so you only need to amend one input `k`, see [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) and [`zip`](https://docs.python.org/3/library/functions.html#zip) for more details.
type: AnswerComment

http://stackoverflow.com/a/52582075
type: Answer
has body: FAQ Do you want to be able to multi-select rows, and then deselect individual row? – ikolim Sep 30 '18 at 21:04 no just select in one press and deselect in another press on a line ,but also keep the selection changing when selecting different lines. maybe its easier to say that im looking for listview behavior in this recycleview – amihai Sep 30 '18 at 21:07 Solution The following solution is not for multi-select. Set selected if row is not selected, or to deselect when it is already selected. Snippet def apply_selection(self, rv, index, is_selected): ''' Respond to the selection of items in the view. ''' self.selected = not self.selected Example main.py from kivy.app import App from kivy.lang import Builder from kivy.uix.recycleview import RecycleView from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.label import Label from kivy.properties import BooleanProperty from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior Builder.load_string(''' &lt;SelectableLabel&gt;: # Draw a background to indicate selection canvas.before: Color: rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1) Rectangle: pos: self.pos size: self.size &lt;RV&gt;: viewclass: 'SelectableLabel' SelectableRecycleBoxLayout: default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical' ''') class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): ''' Adds selection and focus behaviour to the view. ''' class SelectableLabel(RecycleDataViewBehavior, Label): ''' Add selection support to the Label ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): ''' Catch and handle the view changes ''' self.index = index return super(SelectableLabel, self).refresh_view_attrs( rv, index, data) def on_touch_…
upvote count: 0
has comment: http://stackoverflow.com/comment/92099623
has comment: http://stackoverflow.com/comment/100561286
accepted answer of: http://stackoverflow.com/q/52576304
score: -1
answers question: http://stackoverflow.com/q/52576304
has comment: http://stackoverflow.com/comment/92099338
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/92099293
has comment: http://stackoverflow.com/comment/92099368
has comment: http://stackoverflow.com/comment/100570210

http://stackoverflow.com/a/52479382
score: 7
accepted answer of: http://stackoverflow.com/q/52479163
upvote count: 7
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52479163
has body: If you need to automatically unpack multiple elements into an SQL statement you cannot just pass it as a list - you have to actually account for the positional arguments in your statement (i.e. add as many ? as there are elements to unpack). Something like: id_list = (23, 19, 35, 16, 12, 78) query = "DELETE FROM table WHERE id IN ({})".format(", ".join("?" * len(id_list))) # DELETE FROM table WHERE id IN (?, ?, ?, ?, ?, ?) cursor.execute(query, id_list) Keep in mind that this might not be necesarily more efficient than issuing multiple statements via: cursor.executemany("DELETE FROM table WHERE id = ?", id_list) It all depends on query buffering, your table relations etc.
downvote count: 0

http://stackoverflow.com/q/52545394
favorite count: 0
has body: I'm trying to solve Hackerrank question: Find next lexicographically bigger string permutation for a given string input. Here my solution: def biggerIsGreater(w): if len(w)&lt;=1: return w # pair letters in w string with int representing positional index in alphabet letter_mapping = dict(zip(string.ascii_lowercase, range(1, len(string.ascii_lowercase)+1))) char_ints = [letter_mapping[letter] for letter in w.lower() if letter in letter_mapping] # reverse it reversed_char_ints = char_ints[::-1] # get char set to reorder, including pivot. scanned_char_ints = [] index = 0 zipped = list(zip(reversed_char_ints, reversed_char_ints[1:])) while index &lt; len(zipped): char_tuple = zipped[index] scanned_char_ints.append(char_tuple[0]) if char_tuple[0] &lt;= char_tuple[1]: if index == len(zipped) - 1: return "no answer" else: scanned_char_ints.append(char_tuple[1]) break index += 1 # get smallest among bigger values of pivot char_to_switch = None char_to_switch_index = None for item in scanned_char_ints[:-1]: if item &gt; scanned_char_ints[-1]: if char_to_switch == None or item &lt;= char_to_switch: char_to_switch = item char_to_switch_index = scanned_char_ints.index(item) # switch pivot and smallest of bigger chars in scanned chars pivot_index = len(scanned_char_ints) - 1 scanned_char_ints[pivot_index], scanned_char_ints[char_to_switch_index] = scanned_char_ints[char_to_switch_index], scanned_char_ints[pivot_index] # order from second to end the other chars, so to find closest bigger number of starting number ord_scanned_char_ints = scanned_char_ints[:-1] ord_scanned_char_ints.sort(reverse=True) ord_scanned_char_ints.append(scanned_char_ints[-1]) # reverse scanned chars ord_scanned_char_ints.reverse() # rebuild char int list result_ints = char_ints[:len(char_ints) - len(ord_scanned_char_ints)] result_ints.extend(ord_scanned_char_ints) result_ = "" for char_intx in result_ints: for char, int_charz in letter_mapping.items(): if int_charz == char_intx: result_ += char return res…
tagged with: python
has comment: http://stackoverflow.com/comment/92030966
tagged with: python-3.x
has title: Next lexicographically bigger string permutation and solution efficiency
answer count: 0
type: UnansweredQuestion
type: Question
score: 1
has comment: http://stackoverflow.com/comment/92031050
upvote count: 1
downvote count: 0

network-programming
tags question: http://stackoverflow.com/q/52560124
tags question: http://stackoverflow.com/q/52578522
tags question: http://stackoverflow.com/q/52513050
tags question: http://stackoverflow.com/q/52452447
type: Tag
tags question: http://stackoverflow.com/q/52462057
tag name: network-programming
tags question: http://stackoverflow.com/q/52547186
tags question: http://stackoverflow.com/q/52580625
tags question: http://stackoverflow.com/q/52482231
tags question: http://stackoverflow.com/q/52435788

http://stackoverflow.com/a/52724037
has comment: http://stackoverflow.com/comment/92418812
has comment: http://stackoverflow.com/comment/92378271
type: Answer
has comment: http://stackoverflow.com/comment/92395189
has comment: http://stackoverflow.com/comment/92378354
answers question: http://stackoverflow.com/q/52467095
has comment: http://stackoverflow.com/comment/92459559
upvote count: 1
has comment: http://stackoverflow.com/comment/92394682
has comment: http://stackoverflow.com/comment/92380599
has comment: http://stackoverflow.com/comment/92378396
score: 1
has comment: http://stackoverflow.com/comment/92378328
has comment: http://stackoverflow.com/comment/92482456
has comment: http://stackoverflow.com/comment/92416918
has comment: http://stackoverflow.com/comment/92382563
downvote count: 0
has body: Use yield. @app.route( '/file', methods=['POST'] ) def file(): pdata = '' pdata = pdata + '''&lt;img src="/static/img/arrow.gif" align="left"&gt;''' yield pdata for f in send_from_directory( filepath, filename, as_attachment=True ): yield f FULL EXAMPLE OF IT WORKING: from bottle import app, get, post, template, route, run @get('/file') @post('/file') def file(): pdata = '&lt;h3&gt;Hello&lt;h3&gt;' pdata = pdata + '''&lt;img src="/static/img/arrow.gif" align="left"&gt;''' yield pdata yield '&lt;br&gt;&lt;br&gt;HELLO WORLD' run(host='localhost', port=8080, debug=True)
has comment: http://stackoverflow.com/comment/92378637

http://stackoverflow.com/q/52458475
score: 2
has comment: http://stackoverflow.com/comment/91860406
downvote count: 0
has comment: http://stackoverflow.com/comment/91860805
type: Question
type: AnsweredQuestion
tagged with: format
tagged with: dataframe
tagged with: date
has comment: http://stackoverflow.com/comment/91860458
upvote count: 2
linked to: http://stackoverflow.com/q/17465045
has comment: http://stackoverflow.com/comment/91860193
has title: Date Format changes within DataFrame
answer count: 1
has comment: http://stackoverflow.com/comment/91859255
favorite count: 0
has answer: http://stackoverflow.com/a/52482130
accepted answer: http://stackoverflow.com/a/52482130
has body: After I read a file and parse the dates the date format changes within the dataframe. Find below my code. v2x = r'E:\Model\Data\v2x.csv' outfile = r'E:\Model\ModelSpecific\Input_shat2.txt' df_data = pd.read_csv(file_name,parse_dates=[0], index_col=0) df_v2x = pd.read_csv(v2x, parse_dates=[0], sep=",") print(df_v2x[4800:5000]) The correct format should be '%y-%m-%d' And the print output: 4988 2018-07-08 V2TX 12.6265 --&gt; Wrong Format 4989 2018-08-08 V2TX 12.8654 4990 2018-09-08 V2TX 12.4882 4991 2018-10-08 V2TX 15.1113 4992 2018-08-13 V2TX 15.9406 --&gt; Right Format 4993 2018-08-14 V2TX 15.8610 4994 2018-08-15 V2TX 18.4755 4995 2018-08-16 V2TX 16.2633 Thanks for your help!
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/52559637
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52558105
downvote count: 0
has comment: http://stackoverflow.com/comment/92088931
type: Answer
has body: You can grab all the Style tags and parse them, searching what you look. Also you can download the css file, using the resource URL and parse them. Also you can create a XPATH/CSS rule for searching nodes that contain the parameter that you're looking for.

http://stackoverflow.com/q/52443376
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Django annotate Cannot compute Sum - is an aggregate
answer count: 0
has body: I have Django ORM queryset and I am trying to perform the following in_month = OrderEntry.objects.filter(order__closed_date__year=self.year).filter( order__closed_date__month=month_nr) result = in_month.values('product_code').annotate( quantity=Sum('quantity'), free_count=Sum('free_count'), quantity_bottles=Sum(Case( When(product_variant__megapack_quantity=4, then=(F('quantity') * Value(4))), When(product_variant__megapack_quantity=None, then=F('quantity')), default=Value(0), output_field=IntegerField(), )) ) However, this does not work. The error I am getting : Cannot compute Sum('&lt;Case: CASE WHEN &lt;Q: (AND: ('product_variant__megapack_quantity', 4))&gt; THEN &lt;CombinedExpression: F(quantity) * Value(4)&gt;, WHEN &lt;Q: (AND: ('product_variant__megapack_quantity', None))&gt; THEN F(quantity), ELSE Value(0)&gt;'): '&lt;Case: CASE WHEN &lt;Q: (AND: ('product_variant__megapack_quantity', 4))&gt; THEN &lt;CombinedExpression: F(quantity) * Value(4)&gt;, WHEN &lt;Q: (AND: ('product_variant__megapack_quantity', None))&gt; THEN F(quantity), ELSE Value(0)&gt;' is an aggregate What I would like to achieve is a queryset with 4 fields: * product_code * quantity * free_count * quantity_bottles Where quantity bottles should be calculated as follow ( in pseudo code): sum = 0 for order in orders: if order.product_variant.megapack_quantity == 4: sum += order.quantity * 4 else: sum += order.quantity how can I fix it/achieve it with a single query to the DB with Django ORM?
upvote count: 2
has comment: http://stackoverflow.com/comment/100289733
tagged with: orm
tagged with: django
type: Question
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91829477

http://stackoverflow.com/comment/91838365
type: Comment
has text: i edited my post, the append command is the only time i submit a request to the api,
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52447671

http://stackoverflow.com/comment/91959537
type: QuestionComment
has text: @o11c Oh, I agree that using the sorted letters is much more sensible, and easier to debug. And probably significantly faster than using the primes. But it's not O(n). We don't need to worry about integer overflow because we're using Python. But we can keep the number size down by assigning them in "etaoinshrdlu..." frequency order.
comment on: http://stackoverflow.com/q/52508671
score: 0
type: Comment

http://stackoverflow.com/comment/92100621
has text: you can do with drop , every time get the df using drop drop the one already selected
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52582696

http://stackoverflow.com/comment/91898477
comment on: http://stackoverflow.com/a/52478332
type: Comment
has text: How do I find probabilities (and conditional probabilities) if I have the data(A,B,C) which is continuous? @kutschkem
type: AnswerComment
score: 0

http://stackoverflow.com/a/52558706
downvote count: 0
answers question: http://stackoverflow.com/q/52553065
type: Answer
score: 1
upvote count: 1
has body: Here is a simple solution: from bs4 import BeautifulSoup import requests r = requests.get('https://www.clos19.com/en-gb/login') soup = BeautifulSoup(r.text, 'html.parser') print(soup.find('input', type='hidden')["value"]) By adding ["value"], the printed output is only the csrf token.
accepted answer of: http://stackoverflow.com/q/52553065
type: AcceptedAnswer

http://stackoverflow.com/q/52440518
tagged with: graph-traversal
tagged with: python
upvote count: 6
answer count: 2
tagged with: networkx
has answer: http://stackoverflow.com/a/52445069
has answer: http://stackoverflow.com/a/52452528
possible better answer: http://stackoverflow.com/a/52452528
tagged with: pandas
type: AnsweredQuestion
has body: I want to find 'n' maximum weighted edges in a networkx graph. How can it be achieved. I have constructed a graph as follows : g_test = nx.from_pandas_edgelist(new_df, 'number', 'contactNumber', edge_attr='callDuration') Now, I want to find top 'n' edge weights, i.e. top 'n' callDurations. I also want to analyse this graph to find trends from it. Please help me how can this be achieved.
downvote count: 0
accepted answer: http://stackoverflow.com/a/52445069
score: 6
favorite count: 0
tagged with: python-3.x
has title: Finding maximum weighted edge in a networkx graph in python
type: Question

http://stackoverflow.com/q/52462500
has comment: http://stackoverflow.com/comment/91868318
answer count: 0
type: Question
tagged with: flush
has title: how to flush the buffer to disk period in python
tagged with: python
has comment: http://stackoverflow.com/comment/101549015
score: 0
tagged with: tcp
tagged with: logging
type: UnansweredQuestion
has body: I write a 'log-server',which is used to receive log from client, using TCP. when receive a log, it will write the log to file on disk. for performance, the file use a large buffer, the problem is the buffer will flush to disk ONLY when buffer is full. So is there any api can make flush perform period? I have an idea: call the flush in a separate thread period, BUT I'm not sure if it is correct, while another thread may writing data at the same time.

http://stackoverflow.com/q/52491640
tagged with: docker
answer count: 1
downvote count: 0
has title: How to run an container with specific tag docker-py
favorite count: 0
tagged with: byte
tagged with: python
tagged with: dockerpy
has answer: http://stackoverflow.com/a/52492064
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52492064
has body: Trying to run a docker container from docker-py, but when I run: client.containers.run(image='my/image:tag') I get this error: TypeError: sequence item 0: expected a bytes-like object, str found Encoding to bytes with: client.containers.run(image='my/image:tag'.encode()) Gives the error: TypeError: b'my/image:tag' is not JSON serializable I've tried going through the run function to see if there's a tag keyword, but as far as I can tell there's not.

http://stackoverflow.com/a/52454676
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52454582
score: 17
has comment: http://stackoverflow.com/comment/91851994
has comment: http://stackoverflow.com/comment/91851989
has body: The most performant approach is to use a collections.defaultdict dictionary to store data as an expanding list, then convert back to tuple/list if needed: import collections list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])] c = collections.defaultdict(list) for a,b in list_1: c[a].extend(b) # add to existing list or create a new one list_2 = list(c.items()) result: [('AAW', [147, 124]), ('AAA', [123, 456])] note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary. On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict but then you cannot use defaultdict (or use a recipe)
upvote count: 17

http://stackoverflow.com/a/52479919
score: 1
has body: Use rename by column FUND_TOTAL_ASSETS_CRNCY with DataFrame.lookup: d = d.rename(index=m['FUND_TOTAL_ASSETS_CRNCY'], level=0) print (d) Assets date USD 2012-01-01 14.32 2012-01-02 14.32 2012-01-03 14.32 2012-01-04 14.34 d['FX_price'] = d_fx.lookup(d.index.get_level_values(1), d.index.get_level_values(0)) print (d) Assets FX_price date USD 2012-01-01 14.32 1.0 2012-01-02 14.32 1.0 2012-01-03 14.32 1.0 2012-01-04 14.34 1.0
accepted answer of: http://stackoverflow.com/q/52479129
answers question: http://stackoverflow.com/q/52479129
has comment: http://stackoverflow.com/comment/91917345
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91907834
downvote count: 0

http://stackoverflow.com/comment/113359743
comment on: http://stackoverflow.com/a/52572237
score: 0
type: AnswerComment
has text: @Sheldore how did you get such a nice looking bar plot? Did you have to tinker with the normal matplotlib styles?
type: Comment

http://stackoverflow.com/q/52575864
type: Question
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/52575925
linked to: http://stackoverflow.com/q/3877230
answer count: 1
linked to: http://stackoverflow.com/q/15667189
favorite count: 0
tagged with: python-3.x
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52575925
has body: discription about id(): Help on built-in function id in module builtins: id(obj, /) Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.) but I found a strange thing as below: &gt;&gt;&gt; id([2222]) == id([2222]) True &gt;&gt;&gt; id([2222]) == id([2223]) True &gt;&gt;&gt; id([2222]) == id([2224]) True &gt;&gt;&gt; id([2222]) == id([2225]) True &gt;&gt;&gt; id((12, 12)) == id((12, 12)) True &gt;&gt;&gt; id((12, 12)) == id((12, 13)) False &gt;&gt;&gt; id([12, 12]) == id([12, 13]) True &gt;&gt;&gt; a = [12, 12] &gt;&gt;&gt; b = [12, 13] &gt;&gt;&gt; id(a) == id(b) False who can explain this?
type: AnsweredQuestion
has title: how to understand id() in python?
duplicate of: http://stackoverflow.com/q/20753364
has comment: http://stackoverflow.com/comment/92087178

http://stackoverflow.com/q/52579218
has comment: http://stackoverflow.com/comment/92115066
downvote count: 1
linked to: http://stackoverflow.com/q/46621733
tagged with: python
favorite count: 0
has body: I'm trying to write a function that will take in two arguments (one list and one dictionary) and return the output for instance, like so: &gt;&gt;&gt;interpret(["door_open", "AND", "cat_gone"], {"door_open" : "false", "cat_gone" : "true", "cat_asleep" : "true"}) 'false' or interpret(["cat_asleep", "OR", ["NOT", "cat_gone"]], {"door_open" : "false", "cat_gone" : "true", "cat_asleep" : "true"}) 'true' .............................................................................................................................................................. As I want to use as few logical statements as possible in this particular function, I have created a couple of separate functions that will do this instead: def and_function(expression1, expression2): if expression1=="true" and expression2=="true": return "true" else: return "false" def or_function(expression1, expression2): if expression1== "true" or expression2=="true": return "true" else: return "false" def not_function(expression): if expression == "true": return "false" elif expression == "false": return "true" .............................................................................................................................................................. However, now I have been stuck for sometime, as I don't quite understand how the program is suppose to first go through the list and nested lists. Then go through the dictionary pick out the value related to the key (which is in the list) and then put compare the values in the list to each other together with the logical statement. I get that recursion of some form is probably needed in order to go through the nested lists, but can't really figure out how to put it all together. Any ideas on how to solve this kind of problem?
has title: Propositional logic in order to interpret two arguments
type: AnsweredQuestion
tagged with: recursion
accepted answer: http://stackoverflow.com/a/52584134
type: Question
has comment: http://stackoverflow.com/comment/92103375
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/52584124
has answer: http://stackoverflow.com/a/52584134
has answer: http://stackoverflow.com/a/52584124
score: 0

http://stackoverflow.com/a/52510732
answers question: http://stackoverflow.com/q/52510681
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91961584
has comment: http://stackoverflow.com/comment/91961459
has body: You need just def __init__(self, type = type.ThisValue):
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52510681
type: AcceptedAnswer

http://stackoverflow.com/q/52537766
possible better answer: http://stackoverflow.com/a/52537874
has answer: http://stackoverflow.com/a/52537874
has title: rearranging a text file corpus in Python
favorite count: 0
tagged with: python
has body: I have a text file, df.txt with following lines: This is sentence 1 This is sentence 2 This is sentence 3 This is sentence 4 This is sentence 5 This is sentence 6 I would like to get another text file as This is sentence 1 This is sentence 2 This is sentence 3 This is sentence 4 This is sentence 5 This is sentence 6 I tried: import itertools block = '' with open('df.txt', 'r') as file: for i, value in enumerate(itertools.islice(file, 2)): block += value print(block) which is not close: This is sentence 1 This is sentence 2 I assume a similar post should be here but I could not find. Thank you for help.
has answer: http://stackoverflow.com/a/52537941
tagged with: nlp
score: -1
tagged with: python-3.x
downvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92016304
accepted answer: http://stackoverflow.com/a/52537941
answer count: 2
upvote count: 0

http://stackoverflow.com/a/52451371
has comment: http://stackoverflow.com/comment/91846976
score: 2
has comment: http://stackoverflow.com/comment/91919553
downvote count: 0
answers question: http://stackoverflow.com/q/52451302
has comment: http://stackoverflow.com/comment/91847159
has comment: http://stackoverflow.com/comment/91915257
upvote count: 2
has body: You're calling argparse in your Base.py file. Don't do that. Move these lines to another file, or wrap them in if __name__ == __main__: if __name__ == __main__ parser = argparse.ArgumentParser() parser.add_argument('browser', default='chrome', help='Types of browser:chrome, firefox, ie') parser.add_argument('username', help='This is the username') parser.add_argument('password', help='This is the password') args = parser.parse_args() If you don't put these lines in another file or inside of if __name__ == "__main__", that section of code will be run upon import, not when calling test_page.py from the command line. You also don't want to be using argparse in conjunction with unittest. Test Base.py using unittest, and setup the arguments you might need for the class in setUp. I recommend you pass in username and password into the constructor of your Browser object so you can easily write a test that uses a canned username/pw. You can do that like so: class Browser(object): url = 'https:someurl' start_time = datetime.datetime.today() def __init__(self, driver, username, password): self.driver = driver self.username = username self.password = password if self.driver == 'chrome': ... then you can write a test like this: def setUp(self): browser_obj = Browser('chrome', 'some_username', 'some_password') self.driver = browser_obj.browser self.login = browser_obj.login() def test_links(self): self.driver.find_elements_by_link_text('click this link').click() def tearDown(self): browser_obj.close() and then invoke your unit test with a simple python test_page.py (no arguments necessary). When you run in prod, you can call Base.py with arguments, like Base.py chrome username password. Usually people don't test their argparse logic too thoroughly if at all: as it's not exactly quantum physics to pass in arguments to existing classes/function. Note that your original test is making several browser objects instead of using the same one. You probably don't want this.
type: Answer

http://stackoverflow.com/comment/92023208
has text: nvm, I just read up, the .get() seems to give me what a want, sorry for that. I'll give this a try, been stuck on this for a while...
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52459473
type: AnswerComment

http://stackoverflow.com/comment/91847041
score: 1
has text: that was a lot easier than in my wildest dreams. Thanks Cleb!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52451794

http://stackoverflow.com/a/52552647
accepted answer of: http://stackoverflow.com/q/52552616
has body: you should use 17/3.0 It is a different place of python2 and python3.
answers question: http://stackoverflow.com/q/52552616
score: 2
has comment: http://stackoverflow.com/comment/92044110
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52443279
score: 0
type: Answer
has body: Try this: $.getJSON('data.json', function(data) { destinations = data[]; $("#selectid").clear(); $.each(destinations, function(id, destination) { $("#selectid").append("&lt;option value="+destination[id]+"&gt;"+destination[id]+"&lt;/option&gt;"); }); }); Hope this is your expectation
answers question: http://stackoverflow.com/q/52442721

http://stackoverflow.com/q/52452677
has comment: http://stackoverflow.com/comment/91852767
has body: So i'm supposed to convert Babylonian characters to number values so that: "&lt;" = 10 "T" = 1 "\" = 0 When I put the values in, it should add the sum of those numbers, so babylonian( "TTT") would equal 3 because there are 3 "1" values. So far I have this code below, but I can't seem to get the sum, but rather just get the individual numbers. def babylonian(symbols) : lst = [] for str in symbols: sum = 0 for i in str: if i == "&lt;": sum = sum + 10 elif i == "T": sum = sum + 1 elif i == "\\": sum = sum + 0 lst.append(sum) return lst
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/91852744
has comment: http://stackoverflow.com/comment/91852684
has title: Need help converting this number system
has answer: http://stackoverflow.com/a/52455213
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91852715
answer count: 1

http://stackoverflow.com/q/52485805
tagged with: for-loop
has body: I created my version of the game all beginners at Python play: Battleship. The user must define two coordinates, X and Y. I have made a validation, which rejects any input that is not an integer. If input is integer, the code continues to execute. At the end, however, I need to hardcode the current user input in a string, or else the code will not enter the while loop and re-prompt the user for another set of coordinates when the next turn starts. This in fact works just fine, yet I feel like this is not the cleanest way to handle this. Can anyone suggest a better way to do this? # ships are positioned, user must sink them for turn in range(num_of_turns): print("Turn", turn + 1) while type(guess_col) is not int: try: guess_col = input("Enter coordinate X: ") guess_col = int(guess_col) except ValueError: print("Enter coordinate X again") continue while type(guess_row) is not int: try: guess_row = input("Enter coordinate Y: ") guess_row = int(guess_row) except ValueError: print("Enter coordinate Y again") continue # do stuff (sink ships, miss ships, etc...) guess_col = str(guess_col) guess_row = str(guess_row)
upvote count: 2
tagged with: while-loop
answer count: 1
favorite count: 0
tagged with: user-input
has comment: http://stackoverflow.com/comment/91913343
tagged with: python-3.x
has title: Python: obliviate user input that has become obsolete
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/52486048
accepted answer: http://stackoverflow.com/a/52486048

http://stackoverflow.com/q/52571951
has body: I have data that look like this: data = 'somekey:value4thekey&amp;second-key:valu3-can.be?anything&amp;third_k3y:it%can have spaces;too' In a nice human-readable way it would look like this: somekey : value4thekey second-key : valu3-can.be?anything third_k3y : it%can have spaces;too How should I parse the data so when I do data['somekey'] I would get &gt;&gt;&gt; value4thekey? Note: The &amp; is connecting all of the different items How am I currently tackling with it Currently, I use this ugly solution: all = data.split('&amp;') for i in all: if i.startswith('somekey'): print i This solution is very bad due to multiple obvious limitations. It would be much better if I can somehow parse it into a python tree object.
has answer: http://stackoverflow.com/a/52572031
tagged with: parsing
favorite count: 0
has answer: http://stackoverflow.com/a/52572012
accepted answer: http://stackoverflow.com/a/52572012
possible better answer: http://stackoverflow.com/a/52572014
answer count: 5
has answer: http://stackoverflow.com/a/52572044
tagged with: python
downvote count: 1
tagged with: tree
type: AnsweredQuestion
score: 1
has title: Python 2.7 parsing data
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52572014
has answer: http://stackoverflow.com/a/52572152

http://stackoverflow.com/comment/91994026
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52527078
type: AnswerComment
has text: yeah, thanks, i was trying to use the elif statement but i didn't knew exactly how does it work. So i was changing only one statement to elif instead changing 3 if them.

http://stackoverflow.com/comment/91843183
type: Comment
type: QuestionComment
score: 1
has text: what was failed? error message?
comment on: http://stackoverflow.com/q/52450011

http://stackoverflow.com/q/52568315
upvote count: 5
accepted answer: http://stackoverflow.com/a/52629847
has comment: http://stackoverflow.com/comment/92074103
score: 5
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92075972
linked to: http://stackoverflow.com/q/17942874
tagged with: python
has body: I'm trying to import a C++ class in Python. I know I could use BoostPython, SWIG or Cython, but just for didatical purposes I'm trying to manually export C++ methods and functions with extern "C". In a nutshell, I'm trying to replicate this. My enviroment is Windows 10, with Anaconda 3 and Python 3.6. I've installed mingw64 4.8.3 as C/C++ compiler. This is my foo.cpp: #include &lt;iostream&gt; // A simple class with a constuctor and some methods... class Foo { public: Foo(int); void bar(); int foobar(int); private: int val; }; Foo::Foo(int n) { val = n; } void Foo::bar() { std::cout &lt;&lt; "Value is " &lt;&lt; val &lt;&lt; std::endl; } int Foo::foobar(int n) { return val + n; } // Define C functions for the C++ class - as ctypes can only talk to C... extern "C" { Foo* Foo_new(int n) {return new Foo(n);} void Foo_bar(Foo* foo) {foo-&gt;bar();} int Foo_foobar(Foo* foo, int n) {return foo-&gt;foobar(n);} } I've compiled in this way: g++ -c -fPIC foo.cpp -o foo.o. The output is: foo.cpp:1:0: warning: -fPIC ignored for target (all code is position independent) [enabled by default] #include &lt;iostream&gt; ^ Then, I've compiled in this way: g++ -shared -Wl,-soname,libfoo.dll -o libfoo.dll foo.o getting no errors/warnings. The file libfoo.dll has appared in the folder. When I try in Python: import ctypes lib = ctypes.windll.LoadLibrary('libfoo.dll') I get the error OSError: [WinError 126] the specified module could not be found. My Python working directory is the libfoo.dll folder. I tried to create a simple C-HelloWorld library: I compiled in the same way (a part gcc instead of g++) and I succeded in loading it into Python. Where is the problem? Is it in the compilation instructions? Or in the code?
has comment: http://stackoverflow.com/comment/92074523
has answer: http://stackoverflow.com/a/52629847
tagged with: c++
type: AnsweredQuestion
has title: Loading C++ class in Python
type: Question
tagged with: dll

http://stackoverflow.com/comment/91836668
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52446826
has text: Can you at least buy another 4 gigs of ram?, what you are proposing is not feasible.
score: 0

http://stackoverflow.com/a/52545393
answers question: http://stackoverflow.com/q/52545334
type: Answer
accepted answer of: http://stackoverflow.com/q/52545334
upvote count: 4
type: AcceptedAnswer
has body: Whenever you find yourself writing a for loop to construct or modify a list, ask yourself how you might do it with a list comprehension instead. List comprehensions are Pythonic. &gt;&gt;&gt; [x for i, x in enumerate(lst) if i &lt;= 10 or x % 2 == 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8]
downvote count: 0
score: 4

http://stackoverflow.com/a/52452368
type: Answer
has comment: http://stackoverflow.com/comment/91848130
accepted answer of: http://stackoverflow.com/q/52452286
has comment: http://stackoverflow.com/comment/91848272
has comment: http://stackoverflow.com/comment/91848123
score: 3
has body: I'd use pandas s = pd.Series(list(map(tuple, l))) s[~s.duplicated(keep=False)].tolist() Takes 211 ms ± 16.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) for 100000 entries, so a 10x speedup.
upvote count: 3
answers question: http://stackoverflow.com/q/52452286
has comment: http://stackoverflow.com/comment/91848238
has comment: http://stackoverflow.com/comment/91848155
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91848121
has comment: http://stackoverflow.com/comment/91848134

http://stackoverflow.com/q/52565673
has answer: http://stackoverflow.com/a/52565713
possible better answer: http://stackoverflow.com/a/52565804
answer count: 2
has answer: http://stackoverflow.com/a/52565804
linked to: http://stackoverflow.com/q/52546068
has comment: http://stackoverflow.com/comment/92068990
score: 0
has body: How to get ColB from ColA ColA (Localized datetime) ColB (New datetime) 2016-09-19 00:29:13-05:00 2016-09-19 00:29:13 2016-09-19 04:16:04-02:00 2016-09-19 04:16:04 2016-09-19 06:57:54+01:00 2016-09-19 06:57:54
has comment: http://stackoverflow.com/comment/92069014
tagged with: python
type: AnsweredQuestion
tagged with: timezone
accepted answer: http://stackoverflow.com/a/52565713
has title: Python - How to strip off timezone info from datetime object
tagged with: timestamp
type: Question
has comment: http://stackoverflow.com/comment/92069002
has comment: http://stackoverflow.com/comment/92068991

http://stackoverflow.com/comment/92048808
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52528615
has text: @Jinne if `crud.sqlite` is in directory it doesn't mean that table `info` was created. Run `db.create_all()` and restart app.

http://stackoverflow.com/a/52582372
type: Answer
answers question: http://stackoverflow.com/q/52578146
has body: I was able to bring the picture together properly by removing empty space inserted by the following code: while (recieved &lt; fileSize) { byte[] data = new byte[camClient.ReceiveBufferSize]; recieved += dataStream.Read(data, 0, data.Length); ms.Write(data, 0, data.Length); } replacing it with this: int increment = 0; while (recieved &lt; fileSize) { byte[] data = new byte[camClient.ReceiveBufferSize]; increment = dataStream.Read(data, 0, data.Length); recieved += increment; ms.Write(data.Take(increment).ToArray(), 0, increment); } So instead of taking an array the size of the client's buffer into the memory stream(even if it wasn't full), it's being condensed to only the amount of information received via the read method. This effectively removed all the blank space in the received image.
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52578146

http://stackoverflow.com/a/52487310
has body: We receive a white-space separated string of integers, then split that string on the white-space, convert each of the components to an int, then use those ints to calculate the price. while True: try: response = input("Enter price (dollars, numerator,denominator):") dollars, numerator, denominator = map(int, response.split()) price = dollars + numerator/denominator except ValueError: print("Invalid price!")
answers question: http://stackoverflow.com/q/52487064
score: 0
type: Answer

http://stackoverflow.com/q/52488691
type: Question
has comment: http://stackoverflow.com/comment/91918658
has title: Python argparser default value is getting split by letters
has comment: http://stackoverflow.com/comment/91979256
has body: I have the below code to get an option in python parser.add_argument("--node", dest="node_list", metavar="all|&lt;NODE1&gt;,&lt;NODE2&gt;,...", action='append', help="Name of worker nodes on which daemonset pods have to be deployed seperated by comma(,).") If --node is not given, I want to set default value as all. When I give default="all", and loop through the node_list argument, here is what I get print nodeList for x in nodeList: print x if "all" in x: And the O/P shows all a l l So "all" is split as 'a','l','l'. If I explicitly give --node="all" , during execution , it works fine.
has comment: http://stackoverflow.com/comment/91918617
score: 0
tagged with: argparse
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52551210
has title: OpenCV displays dark thresholded image
has comment: http://stackoverflow.com/comment/92042236
has comment: http://stackoverflow.com/comment/92041644
accepted answer: http://stackoverflow.com/a/52551857
tagged with: python
has comment: http://stackoverflow.com/comment/92041821
has comment: http://stackoverflow.com/comment/92041498
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92041524
has comment: http://stackoverflow.com/comment/92042038
has comment: http://stackoverflow.com/comment/92042208
has comment: http://stackoverflow.com/comment/92042088
has body: OpenCV displays dark thresholded image wheareas the thresholded image looks fine if I colormap the image to gray using matplotlib. I'm having issues in embedding matplotlib's cmap to my tkinter gui interface. Couldn't make the OpenCV to display my thresholded image properly. How I want the image to look like. (Used cmap=gray to display using matplotlib) How it actually looks with OpenCV. (I want the same results as matplotlib) Code: import cv2 as cv import numpy as np img = cv.imread('dataset.tif') cv.imshow('Input Image',img) b,g,r= cv.split(img) cv.imshow('Red Channel',r) cv.imshow('Green Channel',g) cv.imshow('Blue Channel',b) img2= cv.bitwise_not(g) cv.imshow('Processed Image',img2) kernel3 = cv.getStructuringElement(cv.MORPH_ELLIPSE,(13,13)) tophat = cv.morphologyEx(img2, cv.MORPH_TOPHAT, kernel3) cv.imshow('Top hat',tophat) thres= 12 maxValue = 14 th, dat = cv.threshold(tophat, thres, maxValue, cv.THRESH_BINARY) cv.imshow('thresh',dat) cv.waitKey(0) cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/92041754
type: Question
has comment: http://stackoverflow.com/comment/92042058
tagged with: opencv
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52551857
has comment: http://stackoverflow.com/comment/92042421
score: 0
has comment: http://stackoverflow.com/comment/92042376
has comment: http://stackoverflow.com/comment/92042756
answer count: 1
has comment: http://stackoverflow.com/comment/92041848
has comment: http://stackoverflow.com/comment/92041681

http://stackoverflow.com/a/52583382
answers question: http://stackoverflow.com/q/52583213
has body: ''.join([w for i, w in enumerate(word) if i not in indices]) 'white lapo'
score: 0
type: Answer

http://stackoverflow.com/a/52467937
answers question: http://stackoverflow.com/q/52467781
downvote count: 0
has comment: http://stackoverflow.com/comment/91901097
accepted answer of: http://stackoverflow.com/q/52467781
type: Answer
has body: I don't think is possible using pandas plotting directly from a DataFrame, but you can use fill_between from matplotlib. You would need to do this on each column of your dataframe ('bar', 'home', 'work', etc..). You can manually create an axis and tell matplotlib and pandas to plot onto that axis import matplotlib.pyplot as plt fig, ax = plt.subplots(1,1) for location in [' bar', 'grocers', ' home']: # or whatever subset of columns you want ax.fill_between(range(len(u1[location]), u1[location], step='post') u1[' app_3'].plot(ax=ax, color='orange') # etc.. P.S. the fillstyle argument is for when you have a marker for each data point and you want to modify its appearance: https://matplotlib.org/gallery/lines_bars_and_markers/marker_fillstyle_reference.html Edit: Updated example using the data you provided. I modified the data to add a stop at the bar between work and home to give a nicer looking plot. import matplotlib.pyplot as plt import pandas as pd columns = ['date', 'app_1', 'app_2', 'user', 'bar', 'grocers', 'home', 'lunch', 'park', 'relatives', 'work'] data = [['2017-08-29 14:00:00', 0.013953, 0.052472, 'user_1', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], ['2017-08-29 14:15:00', 0.014070, 0.052809, 'user_1', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], ['2017-08-29 14:30:00', 0.014186, 0.053146, 'user_1', 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0], ['2017-08-29 14:45:00', 0.014302, 0.053483, 'user_1', 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0], ['2017-08-29 15:00:00', 0.014419, 0.053820, 'user_1', 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]] df = pd.DataFrame(data, columns=columns) height = df'app_1', 'app_2'.max().max() fig, ax = plt.subplots(1,1) df['app_1'].plot(ax=ax, color='orange') df['app_2'].plot(ax=ax, color='purple') ax.fill_between(range(len(df['home'])), height * df['home'], step='post', color='blue') ax.fill_between(range(len(df['work'])), height * df['work'], step='post', color='red') plt.show() Data looks like this: date app_1 app_2 user bar grocers home lunch park relatives work 0 …
score: 1
has comment: http://stackoverflow.com/comment/91983441
has comment: http://stackoverflow.com/comment/91941885
has comment: http://stackoverflow.com/comment/91980749
has comment: http://stackoverflow.com/comment/91901135
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52541156
linked to: http://stackoverflow.com/q/9884132
type: Question
upvote count: 1
tagged with: python
tagged with: lambda
answer count: 1
accepted answer: http://stackoverflow.com/a/52541282
linked to: http://stackoverflow.com/q/32238196
duplicate of: http://stackoverflow.com/q/50223227
has title: Python: Understanding Lambda Used in Sorted()
duplicate of: http://stackoverflow.com/q/32238196
has comment: http://stackoverflow.com/comment/92022214
downvote count: 0
has body: I was trying to use the orderedDict module to sort my dictionary but came up with this question while looking at some example code like below: # regular unsorted dictionary d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} # dictionary sorted by key OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) # dictionary sorted by value OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) So what confused me in the code is the Lambda function used inside sorted() function. I understand that 't' is the argument and 't[0]' or 't[1]' are the expression but can't figure out how 't' get assigned value inside the sorted(). In the code it seems like 't = d.items()' happens automatically? Please help me to understand the mechanism here and thanks a lot in advance!
has comment: http://stackoverflow.com/comment/92022235
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52541282
favorite count: 0

http://stackoverflow.com/comment/91910811
type: QuestionComment
score: 1
has text: @SpencerWieczorek Other way around. `else` needs to follow an `if` or `elif`
comment on: http://stackoverflow.com/q/52484609
type: Comment

http://stackoverflow.com/q/52467524
has comment: http://stackoverflow.com/comment/91876828
has answer: http://stackoverflow.com/a/52467757
has comment: http://stackoverflow.com/comment/91877042
tagged with: numerical-methods
answer count: 1
has comment: http://stackoverflow.com/comment/91876880
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91936905
accepted answer: http://stackoverflow.com/a/52467757
has body: I am looking for some help with creating a code for the following in python I have made an attempt at an answer but I am not quite sure how to finish it. Here is what I have so far import numpy as np import math from numpy import cos x=10**(-p) funct = (1-math.cos(x))/x So I have defined my function that I am trying to calculate, I believe I did that correctly with funct = (1-math.cos(x))/x I have said what x needs to be with x=10**(-p) But how do I add the code to find the smallest value of p which has no correct significant digit at x = 10**-p when using standard double precision? Do I need to somehow use print(min(funct)) Looking for some help with this execution, thanks! Edit: new code import numpy as np import math for p in range(10): x=10.0**-p; result = (1-np.cos(x))/x print (p) print (result) Test = 2*np.sin(x/2)**2/x print (p) print(Test) gives the results: 0 0.459697694132 0 0.459697694132 1 0.0499583472197 1 0.0499583472197 2 0.00499995833347 2 0.00499995833347 3 0.000499999958326 3 0.000499999958333 4 4.99999996961e-05 4 4.99999999583e-05 5 5.0000004137e-06 5 4.99999999996e-06 6 5.00044450291e-07 6 5e-07 7 4.99600361081e-08 7 5e-08 8 0.0 8 5e-09 9 0.0 9 5e-10
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91876870
upvote count: 2
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91876884
has title: Finding smallest value in python

http://stackoverflow.com/a/52528701
accepted answer of: http://stackoverflow.com/q/52516027
has body: It's quite hard to trace the action of the compiled numpy code. Even if you can find the astype method, you'll probably have to dig several layers down to see you want. The top method probably focuses on interpreting the parameters, while the conversion itself might take place in an entirely different section of code. Note that your array is object dtype, precisely because of that None object. The other elements are integers, In [48]: np.array([1,2,None]) Out[48]: array([1, 2, None], dtype=object) If I tell it to make an int dtype array, it raise an error: In [49]: np.array([1,2,None],int) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-49-c65114b3ba97&gt; in &lt;module&gt;() ----&gt; 1 np.array([1,2,None],int) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' This is the same error that I'd get with int(None). Specifying float dtype, I get the nan as you do. In effect this np.array call is the same as your astype method. (See what I mean about it being hard to pinpoint where the 'conversion' is being done?) In [50]: np.array([1,2,None],float) Out[50]: array([ 1., 2., nan]) Now float(None) raises a similar error, so the numpy handling on None is different from Python's. numpy also converts the string 'nan' to float nan: In [56]: np.array([1,2,'nan'],float) Out[56]: array([ 1., 2., nan]) It's not surprising that None is converted to a float nan. After all, it stands for not a number. But it will be quite hard to find the exact place (or places) in the numpy code where that equivalence is made.
answers question: http://stackoverflow.com/q/52516027
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/92055744
has text: can you show us an example of what the data is and what you want to acheive
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52558456
type: Comment

http://stackoverflow.com/comment/92082612
score: 0
has text: Python 2.7 or 3.7? Could be a duplicate of: https://stackoverflow.com/questions/51799366/how-to-get-credentials-in-google-appengine-python37/51801781#51801781 PIP installing into a lib directory should fix that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52573041

http://stackoverflow.com/a/52578673
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/52574989
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52574989
has body: If you have a dataframe that contains the image filenames along with their labels, you can use the newly introduced flow_from_dataframe() method which has been exactly defined for this purpose. It takes a Pandas dataframe which contains the filenames of the images in one column and their corresponding labels in another column(s). It has not been officially released yet, so you need use the latest development version of Keras on the Keras Github repository. It is expected to be in the next release, though. Update: It has been included in Keras Preprocessing 1.0.4 and Keras 2.2.3. Also, there is a tutorial about this method as well.
type: Answer

http://stackoverflow.com/comment/91966261
score: 1
has text: Show us that you tried something at least. What did you write so far ?
comment on: http://stackoverflow.com/q/52513271
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52567125
has body: In [4]: phrases = ("Hello There\nHow are you") In [5]: type(phrases) Out[5]: builtins.str I tried this in ipython, you see, ("Hello There\nHow are you") is a string rather than a tuple. print(["Hello there\nHow are you"]) does not really print out the string, it just tells you what is in the list.
answers question: http://stackoverflow.com/q/52567038
score: 0
type: Answer

http://stackoverflow.com/a/52569480
answers question: http://stackoverflow.com/q/52569047
downvote count: 0
has body: Yeah. I removed the post_save, made country nullable and saved user and profile separately. Thanks for the help. views.py def register(request): if request.method == 'POST': user_form = UserRegisterForm(request.POST) profile_form = ProfileRegisterForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.is_active = False user.save() profile = profile_form.save(commit=False) profile.user = user profile.save()
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52569047
type: Answer

http://stackoverflow.com/q/52569621
has comment: http://stackoverflow.com/comment/92127776
type: UnansweredQuestion
has title: Numba functions and pickle
type: Question
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/53326360
tagged with: numba
tagged with: python
score: 2
has body: I'm having a problem using joblib to execute a recursive numba function in parallel. When using numba's jit on a recursive function and then trying to use joblib on that function, I get an error (reproduced at the end). Any workarounds you can think of? The only I can think of is to re-write the function without recursion. I would normally report this on github, but I don't know whose problem it is, cloudpickly or numba. What do you think? Thanks! This code reproduces the problem: from joblib import Parallel, delayed from numba import njit, int64 @njit(int64(int64)) def df(n): if n &lt;= 0: return 1 else: return n * df(n - 2) Parallel(n_jobs=2, verbose=1)(delayed(df)(2) for _ in range(2)) Error message (many lines at the beginning ignored) File "/home/.../anaconda3/envs/test_bug/lib/python3.7/pickle.py", line 504, in save f(self, obj) # Call unbound method with explicit self File "/home/.../anaconda3/envs/test_bug/lib/python3.7/pickle.py", line 856, in save_dict self._batch_setitems(obj.items()) File "/home/.../anaconda3/envs/test_bug/lib/python3.7/pickle.py", line 882, in _batch_setitems save(v) File "/home/.../anaconda3/envs/test_bug/lib/python3.7/pickle.py", line 524, in save rv = reduce(self.proto) File "/home/.../anaconda3/envs/test_bug/lib/python3.7/site-packages/numba/dispatcher.py", line 585, in __reduce__ globs = self._compiler.get_globals_for_reduction() File "/home/.../anaconda3/envs/test_bug/lib/python3.7/site-packages/numba/dispatcher.py", line 89, in get_globals_for_redu ction return serialize._get_function_globals_for_reduction(self.py_func) File "/home/.../anaconda3/envs/test_bug/lib/python3.7/site-packages/numba/serialize.py", line 55, in _get_function_globals _for_reduction func_id = bytecode.FunctionIdentity.from_function(func) File "/home/.../anaconda3/envs/test_bug/lib/python3.7/site-packages/numba/bytecode.py", line 291, in from_function func = get_function_object(pyfunc) RecursionError: maximum recursion depth exceeded During handling of the a…

http://stackoverflow.com/a/52570544
answers question: http://stackoverflow.com/q/52569791
type: Answer
upvote count: 1
downvote count: 1
score: 0
has body: It seems that what you post to server is not a valid json object. So you should debug what you got. class UsersResource(Resource): def post(self): # debug print("request.args is {}".format(request.args)) print("request.form is {}".format(request.form)) print("request.data is {}".format(request.data)) req = request.get_json() user = { "email": req.get("email"), "password": req.get("password") } result = mongo.db.users.insert_one(user) return jsonify(result)

http://stackoverflow.com/q/52521722
tagged with: python
has answer: http://stackoverflow.com/a/70639059
upvote count: 3
has comment: http://stackoverflow.com/comment/91985568
tagged with: tensorflow
type: Question
has title: validation_split in ImageData Generator returns 0 images
score: 3
has body: I'm trying to split my data (images) using ImageDataGenerator in Keras by setting validation_split to some fraction. Here is my code: # Generate batches of tensor image data with real-time data augmentation, looped over in batches train_DataGen_Augmnt =ImageDataGenerator( rescale=1./255, featurewise_center=True, validation_split=0.2, rotation_range=30, horizontal_flip=True, ) # validation data not augmented! Validation_DataGen = ImageDataGenerator(rescale=1./255) # Flow training images in batches of 32 using train_datagen generator train_generator = train_DataGen_Augmnt.flow_from_directory( base_dir, subset='training', target_size=(150, 150), batch_size=32, #save_to_dir='images/Agumented' ) # Flow validation images in batches of 32 using test_datagen generator validation_generator = Validation_DataGen.flow_from_directory( base_dir, subset='validation', target_size=(150, 150), batch_size=32, ) The splitting seems to work as the data is split but only shows the splitting for training only. Here is the output when running this: Found 89 images belonging to 3 classes. Found 0 images belonging to 3 classes.
answer count: 2
has comment: http://stackoverflow.com/comment/135887400
downvote count: 0
has answer: http://stackoverflow.com/a/74929535
tagged with: keras
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91998676
type: Comment
has text: No it doesn't matter where you extract the zip, because during installation all the required files will be copied to the python installation directory or virtualenv directory if you use virtualenv. It is just like installing any exe in your system. No need to change the system variables.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52529337

http://stackoverflow.com/comment/91948935
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52496959
has text: I had used a specific version of fastecdsa and made some changes to the file on my personal computer and forgot about it. So the points on the curve were not serializable . . . . that was the problem, i just had to change the public key output.

http://stackoverflow.com/q/52524463
has answer: http://stackoverflow.com/a/52524895
type: UnansweredQuestion
tagged with: pip
tagged with: python
score: 1
tagged with: setuptools
upvote count: 1
linked to: http://stackoverflow.com/q/26061610
type: Question
linked to: http://stackoverflow.com/q/3472430
has body: I'm having serious trouble with using setup.py to pip install my package which also has dependency links. I have read this answer and this one thoroughly and none of the answers including the accepted ones help. Here is the setup.py for the package trying to install. Basically, it reads the requirements.txt to fill install_requires and dependency_links, most of the rest of the code is boilerplate from cookie-cutter. requirements.txt has a private github repo in it which is causing the issues. e.g. git+https://${GITHUB_OAUTH_TOKEN}@github.com/jmerkow/pripy.git#egg=pripy When I run pip install -r requirements.txt everything works great, it installs the private repository. However, if I try to install using pip install . --process-dependency-links, I get this error: Could not find a version that satisfies the requirement pripy (from mypackage==&lt;sha&gt;) (from versions: ) No matching distribution found for pripy (from mypackage==&lt;sha&gt;) If I take off the #egg=xxx from the link in requirements, the private repo package is completely ignored by pip install . but not by pip install -r requirements.txt. I have confirmed that dependency_links contains 'git+https://&lt;actual-token&gt;@github.com/jmerkow/pripy.git#egg=pripy' and that install_requires includes 'pripy' How do you get setup to properly Is this a problem with the sub-package? setup.py in that repo is done pretty much the same, except there are no private links.
has title: pip install package still not following dependency links
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91925130
type: Comment
type: QuestionComment
has text: multiple matches should have the same label applied, I updated the example based on your comment.
comment on: http://stackoverflow.com/q/52491953
score: 0

http://stackoverflow.com/q/52432783
type: Question
has comment: http://stackoverflow.com/comment/91809283
has comment: http://stackoverflow.com/comment/91809757
score: 0
has body: I created a class: class aTest: name = "" twoGroups = -1 continuous = -1 parametric = -1 covariates = -1 paired = -1 def __init__(self, name, twoGroups, continuous, parametric, covariates, paired): self.name = name self.twoGroups = twoGroups self.continuous = continuous self.parametric = parametric self.covariates = covariates self.paired = paired And then created a list of class instances: testList = [] testList.append(aTest("independent samples t-test", 1, 1, 1, 0, 0)) testList.append(aTest("dependent samples t-test", 1, 1, 1, 0, 1)) testList.append(aTest("Mann-Whitney U-test", 1, 1, 0, 0, 0)) testList.append(aTest("Wilcoxson matched pairs test", 1, 1, 0, 0, 1)) testList.append(aTest("one-way independent ANOVA", 0, 1, 1, 0, 0)) testList.append(aTest("Kruskall-Wallis test", 0, 1, 0, 0, 0)) testList.append(aTest("one-way repeated measures ANOVA", 0, 1, 1, 0, 1)) testList.append(aTest("Friedman's ANOVA", 0, 1, 0, 0, 1)) testList.append(aTest("ANCOVA", 0, 1, 1, 1, 0)) Then, finally, I tried to remove all the items in the list where the attribute parametric was equal to 0: print("Now, remove the nonparametric tests...") for test in testList: if test.parametric == 0: testList.remove(test) print("...and print what's left, with confirmation the attribute was 0") for test in testList: print(test.name+", "+str(test.parametric)) I get this result in the console: &gt; Now, remove the nonparametric tests... &gt; ...and print what's left, with confirmation the attribute was 0 &gt; independent samples t-test, 1 &gt; dependent samples t-test, 1 &gt; Wilcoxson matched pairs test, 0 &gt; one-way independent ANOVA, 1 &gt; one-way repeated measures ANOVA, 1 &gt; ANCOVA, 1 What's going on with the Wilcoxson matched pairs test named object?
tagged with: python
has title: How does the list .remove() function work?
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91809949
linked to: http://stackoverflow.com/q/51132277
duplicate of: http://stackoverflow.com/q/6260089
has comment: http://stackoverflow.com/comment/91809412
has comment: http://stackoverflow.com/comment/91809504
linked to: http://stackoverflow.com/q/6260089
has comment: http://stackoverflow.com/comment/91809388

http://stackoverflow.com/q/52498339
type: Question
has title: Twisted plugin has different result in Ubuntu 12.04 and 18.04
score: 0
tagged with: twisted
has body: I am designing a simple LoRaWAN UDP server based upon Twisted's plugin method. It gives me different results in two PCs. Aliyun ECS, Ubuntu 12.04(32bit), Python 2.7.3, Twisted 15.0.0 Physical PC, Ubuntu 18.04(64bit), Python 2.7.15, Twisted 17.9.0 I have following plug in trees in my project. $ tree lorawan_server/ lorawan_server/ ├── LoRaWANPktFwd.py ├── run.sh ├── shutdown_twistd.sh ├── start_plugin_twistd.sh └── twisted └── plugins └── LoRaWANPktFwd_plugin.py LoRaWANPktFwd.py: #!/usr/bin/env python #coding: utf-8 from __future__ import print_function import getopt import os import sys import string import struct import binascii import time import uuid from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor, protocol, defer from twisted.python import log from twisted.enterprise import adbapi class LoRaWANPktFwd(DatagramProtocol): def datagramReceived(self, data, addr): # A simple echo server self.transport.write(data, addr) def main(): log.startLogging(sys.stdout) reactor.listenUDP(1700, LoRaWANPktFwd()) reactor.run() if __name__ == "__main__": main() LoRaWANPktFwd_plugin.py: from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.application import internet from twisted.plugin import IPlugin from twisted.python import usage from LoRaWANPktFwd import LoRaWANPktFwd class Options(usage.Options): optParameters = "port","p", 1700, "The port number to listen on." class LoRaWANPktFwdServiceMaker(object): implements(IServiceMaker, IPlugin) tapname = "LoRaWAN" description = "A Raw UDP-based LoRaWAN Packet Forwarder server." options = Options def makeService(self, options): return internet.UDPServer(int(options["port"]), LoRaWANPktFwd()) serviceMaker = LoRaWANPktFwdServiceMaker() If I type: twistd LoRaWAN then Ubuntu 18.04 will complain following: /usr/bin/twistd: Unknown command: LoRaWAN And Ubuntu 12.04 will start to run, with twistd.pid and twistd.log created in same folder. I have n…
answer count: 1
tagged with: ubuntu
accepted answer: http://stackoverflow.com/a/52499285
linked to: http://stackoverflow.com/q/7275295
tagged with: python
has answer: http://stackoverflow.com/a/52499285
type: AnsweredQuestion

http://stackoverflow.com/q/52582689
has comment: http://stackoverflow.com/comment/92100402
favorite count: 0
has title: Trying to construct a greedy algorithm with python
has body: So i'm trying to create a greedy algorithm for a knapsack problem. The txt file below is the knap20.txt file. The first line gives the number of items, in this case 20. The last line gives the capacity of the knapsack, in this case 524. The remaining lines give the index, value and weight of each item. My function is to ideally return the solution in a list and the value of the weights From what I can tell by my results, my program is working correctly. Is it working as you would expect, and how can i improve it? txt file 20 1 91 29 2 60 65 3 61 71 4 9 60 5 79 45 6 46 71 7 19 22 8 57 97 9 8 6 10 84 91 11 20 57 12 72 60 13 32 49 14 31 89 15 28 2 16 81 30 17 55 90 18 43 25 19 100 82 20 27 19 524 python file import os import matplotlib.pyplot as plt def get_optimal_value(capacity, weights, values): value = 0. numItems = len(values) valuePerWeight = sorted([[values[i] / weights[i], weights[i]] for i in range(numItems)], reverse=True) while capacity &gt; 0 and numItems &gt; 0: maxi = 0 idx = None for i in range(numItems): if valuePerWeight[i][1] &gt; 0 and maxi &lt; valuePerWeight[i][0]: maxi = valuePerWeight[i][0] idx = i if idx is None: return 0. if valuePerWeight[idx][1] &lt;= capacity: value += valuePerWeight[idx][0]*valuePerWeight[idx][1] capacity -= valuePerWeight[idx][1] else: if valuePerWeight[idx][1] &gt; 0: value += (capacity / valuePerWeight[idx][1]) * valuePerWeight[idx][1] * valuePerWeight[idx][0] return values, value valuePerWeight.pop(idx) numItems -= 1 return value def read_kfile(fname): print('file started') with open(fname) as kfile: print('fname found', fname) lines = kfile.readlines() # reads the whole file n = int(lines[0]) c = int(lines[n+1]) vs = [] ws = [] lines = lines[1:n+1] # Removes the first and last line for l in lines: numbers = l.split() # Converts the string into a list vs.append(int(numbers[1])) # Appends value, need to convert to int ws.append(int(numbers[2])) # Appends weigth, need to convert to int return n, c, vs, ws dir_path = os.pa…
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92100421
upvote count: 1

http://stackoverflow.com/q/52455778
has answer: http://stackoverflow.com/a/52455811
has comment: http://stackoverflow.com/comment/91854080
tagged with: python
has body: I'm trying to dynamically create variable names in a for loop. In the contrived example below, I simply want to create a separate dataframe for each ticker: tickers = ['FB', 'AMZN', 'NFLX', 'GOOG'] for ticker in tickers: 'df_' + ticker = pd.read_excel('my_data.xlsx', sheet_name=ticker) #SyntaxError: can't assign to operator However, this seems to work: for ticker in tickers: locals()['df_' + str(ticker)] = pd.read_excel('my_data.xlsx', sheet_name=ticker) I've seen similar examples of this question posted previously, but responses range from dicts, to locals, to setattr. I'm trying to learn and understand the most Pythonic way to handle this. Hard for me to understand from others' examples and often responses that suggest a non-optimal way of handling.
favorite count: 0
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
has title: How are variable names created in a Python for loop? Is the locals() function the best way?
has comment: http://stackoverflow.com/comment/91853929
type: Question
has comment: http://stackoverflow.com/comment/91854135
has comment: http://stackoverflow.com/comment/91854145
has answer: http://stackoverflow.com/a/52455919
score: -1
answer count: 2
downvote count: 1

http://stackoverflow.com/comment/91953951
comment on: http://stackoverflow.com/q/52505501
score: 1
type: Comment
type: QuestionComment
has text: You're right, I've now corrected the last high. Thanks for your respond.

http://stackoverflow.com/comment/91896827
type: Comment
type: QuestionComment
score: 0
has text: i will initiate from `foo.py`. That script will get references from other packages.
comment on: http://stackoverflow.com/q/52476959

http://stackoverflow.com/comment/92062720
comment on: http://stackoverflow.com/q/52555508
score: 0
has text: I was trying to track the leftover qty and thought it would be easier if it's the same value. But I liked your method. I can just find the min(leftover) for each itemid to see if any item has leftovers after the allocation process. :)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52453412
tagged with: python
tagged with: restructuredtext
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2481414
score: 1
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52453608
has answer: http://stackoverflow.com/a/52453856
has answer: http://stackoverflow.com/a/52453608
accepted answer: http://stackoverflow.com/a/52453856
answer count: 2
downvote count: 0
has title: Centered Heading With Sphinx
favorite count: 0
has body: I'm writing a document in sphinx with three main types of elements in it: headings, images and plain text. Occasionally, some elements need to be centered: Heading ======= .. rst-class:: center A centered paragraph, followed by non-centered image. .. image:: /_static/exhibit_a.png A non-centered paragraph, followed by centered image. .. image:: /_static/exhibit_b.png :class: center The regular text and image get centered just fine because I register a CSS file that looks like this: .center { text-align: center; } img.center { display: block; margin: auto; } However, the following does not work as intended: .. rst-class: center =================== A Heading 1 Element =================== Some generic text The reST class (sphinx rst-class) directive is only supposed to apply to the element that immediately follows it, but in this case, the whole section becomes center aligned, with everything in it. In this example, Some generic text comes out centered, but should be left-aligned. In fact, centering the first heading in the document like this pretty much centers the entire document. How do I center align a heading in a way that makes it apply only to the &lt;h1&gt; tag and not the whole section? I am using the Read the Docs theme on sphinx 1.8.0, in case that matters. Additional Thoughts In my case, I need to modify all &lt;h1&gt; and &lt;h2&gt; instances and no other headings. I know that this is trivial to do in CSS with just h1 h2 { text-align: center; } However, this particular document is part of a much larger project, in which I want to keep all the original styles intact. The only way to do this would be to include my CSS customization only for this one document. Is this a possible alternative? Some More Thoughts The error is happening because the center class is being attached to the &lt;div&gt; surrounding the whole section, not the&lt;h1&gt; tag. However, I'd like to be able to allow some divs (like extended lines) to be allowed to have the center class. Just…
tagged with: python-sphinx

http://stackoverflow.com/q/52465291
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53850665
tagged with: python
score: 2
has title: pylatex Add Horizontal Line
upvote count: 2
type: Question
tagged with: pylatex
answer count: 1
downvote count: 0
favorite count: 0
tagged with: latex
has body: If I have a simple document set up with pylatex... import pylatex as pl geometry_options = { "head": "1pt", "margin": "0.2in", "bottom": "0.2in", "includeheadfoot": False} doc = pl.Document(geometry_options=geometry_options) doc.append("text") ... how can I add a black horizontal seperation line of a certain thickness after the text block ?

http://stackoverflow.com/comment/91998792
type: AnswerComment
type: Comment
has text: This changes all the Sold values where cost_price < 800 to 1. I want to change only 6000 values in the sold column where cost_price < 800. right now there are around 15000 values in the sold column where cost_price < 800
comment on: http://stackoverflow.com/a/52529750
score: 0

http://stackoverflow.com/q/52486303
type: Question
has body: In my Store model, I have author attribute so I can tack who wrote and updated a store. However, I would like to have who created and who updated separately. I think I have to get who created in my save_model in admin.py. Is there a way to get a creator and updater separately in Django admin? models.py class Store(models.Model): ... author = ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='promotions_of_author', null=True, blank=True) admin.py class StoreAdmin(SummernoteModelAdmin): ... def save_model(self, request, obj, form, change): if getattr(obj, 'author', None) is None: obj.author = request.user obj.save()
tagged with: django-admin
has title: Is it possible to have creator and updater separately in Django admin?
has answer: http://stackoverflow.com/a/52491281
answer count: 1
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/52491281
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/91867022
has text: @CharlesDuffy LGTM. Already cast a reopen vote ☺
type: Comment
comment on: http://stackoverflow.com/q/52462030
type: QuestionComment
score: 0

http://stackoverflow.com/a/52484664
has comment: http://stackoverflow.com/comment/91914297
has comment: http://stackoverflow.com/comment/91915692
upvote count: 1
has comment: http://stackoverflow.com/comment/91913965
has body: Run printenv on both Python and terminal, and check the PATH variable. Use os.environ['PATH'] = 'My path' to set it to what you saw on the terminal. For future issues (That I've run into): A quick way to check if it's an exported environment variable is to run os.system("/bin/sh -c \"MYCMD\""), and then run the same "/bin/sh -c \"MYCMD\"" string in your terminal. If there's still a problem, then it must be an export (And this is the likely issue). To resolve this, try printenv in both python and the terminal to see the list of exports. You should see a discrepancy. The format is simple as you can simple copy the output of the terminal's printenv (Which should be a series of declares), and paste it into python so python will get the same variables. Then your "/bin/sh CMD" calls should align. The wrapped /bin/sh is in case they're running different shells or have different local variables. echo $SHELL can confirm this, at which point you can compare sets and printenvs and copy paste in the same way. Wrapped you only have to compare exports, as that's what get passed to child processes.
accepted answer of: http://stackoverflow.com/q/52484581
answers question: http://stackoverflow.com/q/52484581
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/52433011
tagged with: patch
favorite count: 0
has comment: http://stackoverflow.com/comment/91818822
has title: How to mock cx_Oracle cursor in Python
has answer: http://stackoverflow.com/a/52452937
tagged with: python
type: AnsweredQuestion
tagged with: python-unittest
has body: I have two below functions in a class and I need to mock the database connection and cursor results. cx_Oracle.connect successfully patched it works as expected. But the cursor, callfunc, fetch_all doesn't get mock. Any idea what would be the correct syntax ? class dbconnect: def db_connect(self, connection_details): connection = cx_Oracle.connect(user_name,pwd,&lt;connection_string&gt;) return connection def execute_function(self, sqlFunction, args): cursor = self.connection.cursor() res=cursor.callfunc(sqlFunction, cursor.var(cx_Oracle.CURSOR), args) results = {'headers' : [x[0] for x in res.description], 'data': res.fetchall() } cursor.close() return results My Mocking code with mock.patch('dbconnect.cx_Oracle.connect') as mockOracle: result_set = {} mockOracle.cursor.callfunc.fetch_all = result_set
type: Question
upvote count: 4
answer count: 2
tagged with: mocking
accepted answer: http://stackoverflow.com/a/52452937
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91822104
possible better answer: http://stackoverflow.com/a/71293184
tagged with: cx-oracle
has answer: http://stackoverflow.com/a/71293184

http://stackoverflow.com/a/52541098
upvote count: 2
has body: The two commenters are correct, the UUID is not your primary key here. Any foreign keys relating to your campaign are holding the primary key (PK), which is just an auto-incrementing integer here. Unfortunately it can sometimes be a pain to change primary keys for exactly the reason you're worried about. I've gone through this before, here's what I suggest: Leave your primary keys as they are. It will ensure that you won't have any problems with relations. If you want a UUID field to be able to look up objects or pass around the reference without the potential issues caused by integer PKs. An example of such an issue would be if you're using a REST API, it would look weird if someone saw this link: GET /campaigns/6 &lt;-- because they would know to just try GET /campaigns/7 and maybe they'd see something they weren't meant to see. clearly GET /campaigns/7182c679-f728-44ca-83c9-648a120bb066 is better. You can add unique=True to your UUID field to ensure django creates an index for it, then the performance wouldn't differ. Does this answer you question?
type: Answer
answers question: http://stackoverflow.com/q/52511804
score: 2
downvote count: 0

http://stackoverflow.com/comment/91897960
comment on: http://stackoverflow.com/a/52476145
score: 0
has text: @AlmaasShah many IDES as the one you point out do not handle some error messages and only say: *... terminated (returncode: xxx) ...*, so in those cases I recommend using the terminal since there you will get more information.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91989520
type: AnswerComment
comment on: http://stackoverflow.com/a/52524878
type: Comment
score: 1
has text: I also tried `df.replace('\s+', '',regex=True,inplace=True)` and worked. Anyway, thank you all for the answers!

http://stackoverflow.com/q/52488117
has answer: http://stackoverflow.com/a/52489159
score: 15
has answer: http://stackoverflow.com/a/64604185
upvote count: 15
answer count: 3
has comment: http://stackoverflow.com/comment/91919327
downvote count: 0
has body: I have been debugging for hours why my code randomly breaks with this error: JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is the code I have: while True: try: submissions = requests.get('http://reymisterio.net/data-dump/api.php/submission?filter[]=form,cs,'+client+'&amp;filter[]=date,cs,'+since).json()['submission']['records'] break except requests.exceptions.ConnectionError: time.sleep(100) And I've been debugging by printing requests.get(url) and requests.get(url).text and I have encountered the following "special "cases: requests.get(url) returns a successful 200 response and requests.get(url).text returns html. I have read online that this should fail when using requests.get(url).json(), because it won't be able to read the html, but somehow it doesn't break. Why is this? requests.get(url) returns a successful 200 response and requests.get(url).text is in json format. I don't understand why when it goes to the requests.get(url).json() line it breaks with the JSONDecodeError? The exact value of requests.get(url).text for case 2 is: { "submission": { "columns": [ "pk", "form", "date", "ip" ], "records": [ [ "21197", "mistico-form-contacto-form", "2018-09-21 09:04:41", "186.179.71.106" ] ] } }
has answer: http://stackoverflow.com/a/79246666
favorite count: 0
tagged with: python
type: UnansweredQuestion
tagged with: python-requests
has title: python requests randomly breaks with JSONDecodeError
type: Question

http://stackoverflow.com/a/52531730
has comment: http://stackoverflow.com/comment/92009773
type: Answer
has comment: http://stackoverflow.com/comment/92006906
answers question: http://stackoverflow.com/q/52528417
has comment: http://stackoverflow.com/comment/92002865
score: 3
has comment: http://stackoverflow.com/comment/112795577
upvote count: 3
has comment: http://stackoverflow.com/comment/92033969
has body: The problem is that MG.selfloop_edges() is an iterator (more precisely generator) over the selfloop edges in the graph, and by removing the edges you are changing the iterator's edges during the iteration. According to the documentation: Parameters: ebunch (list or container of edge tuples) - ... That means that the ebunch parameter should be a container, while MG.selfloop_edges() returns a generator. You can read more about the difference between the two here. The issue can be solved by passing list(MG.selfloop_edges()) to MG.remove_edges_from (instead of passing MG.selfloop_edges() directly).
has comment: http://stackoverflow.com/comment/92003230
downvote count: 0

http://stackoverflow.com/comment/91980949
comment on: http://stackoverflow.com/q/52520457
score: 0
type: Comment
type: QuestionComment
has text: Thank you!! That works. And yeah it was inside the else, it didn't copy and paste properly @juvian

http://stackoverflow.com/q/52545069
score: 0
has title: Interpolate python lists at different rates to get equally spaced values
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92030151
has comment: http://stackoverflow.com/comment/92030179
has comment: http://stackoverflow.com/comment/92068950
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92030163
tagged with: interpolation
answer count: 0
has comment: http://stackoverflow.com/comment/92030328
has comment: http://stackoverflow.com/comment/92030132
has comment: http://stackoverflow.com/comment/92030230
has body: I have two lists in Python, which correspond to the x-coordinates and the y-coordinates in a 2d array while circling around an ellipse. The x-coordinates look something like this: x_coords = [299.97, 298, 297, 296, 295.41, 295, 294.91, 295.012, 295.58, 296.1, ...], and y_coords is the same length but has different values. As you can see, the values are not equally spaced, and they increase and decrease throughout the list (as they are going around the ellipse). I can compute the distance between any two adjacent (x,y) points on the ellipse with: import numpy as np distances = [] for i in range(len(x_coords)): if i==len(x_coords)-1: break dist = np.sqrt((x_coords[i+1]-x_coords[i])**2 + (y_coords[i+1]-y_coords[i])**2) distances.append(dist) When I print distances, I can see that they are all different. So my (x, y) coordinate pairs are not equally spaced. I would like to find a way to make them all equally spaced. I imagine this would involve interpolating in between each value within x_coords and y_coords such that distances returns values that are all equal. Of course, x_coords and y_coords also need to still have equal lengths so that (x_coords[i], y_coords[i]) will correspond to an (x, y) point at the same position in space. How can I accomplish this?
type: Question
tagged with: distance

http://stackoverflow.com/a/52462259
has body: What is my understanding of the difference between mutable vs immutable in python is the that the first can be changed by indexing. For example, the following x list can be changed by indexing! x = [1,2,3] x[0] = 10 y = (1,2,3) y[0] = 10 # this will raise an error. tuple is not mutable. y = x id(y) == id(x) #gives true. since y is a reference to x y[0] = 10 print(y) [10, 2, 3] print(x) [10, 2, 3] # x is changed as well! y and x are same same. every time you create lists or sets or tuples with unique names even though they contain the same dataset, still they are not the same list mapped into the memory. each has its unique id.
answers question: http://stackoverflow.com/q/52462209
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/52444262
score: 3
has answer: http://stackoverflow.com/a/52444382
upvote count: 3
has title: PyCharm Python - Display __str__ of object instead of memory address in debugger
possible better answer: http://stackoverflow.com/a/70716817
linked to: http://stackoverflow.com/q/50891018
accepted answer: http://stackoverflow.com/a/52444382
type: Question
answer count: 2
downvote count: 0
has body: As far as I remember, in IntelliJ, the debug window has the option to view the toString() of an object instead of its memory address. Is there a way to do this in PyCharm with an object's __str__(self)?
tagged with: python
favorite count: 0
tagged with: pycharm
has answer: http://stackoverflow.com/a/70716817
type: AnsweredQuestion

http://stackoverflow.com/comment/92057333
comment on: http://stackoverflow.com/q/52559302
type: Comment
type: QuestionComment
has text: Haven't tested, but apparently you can store it [as a function attribute](https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function)
score: 1

http://stackoverflow.com/comment/91935051
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52497326
type: Comment
has text: thank you @Mike for your answer. Unfortunately I've this error message: | => make /Library/Developer/CommandLineTools/usr/bin/make -C dir/dir1/dir11 build lambda_update make: *** dir/dir2/dir22: No such file or directory. Stop. make: *** [dir/dir3/dir33] Error 2

http://stackoverflow.com/a/52442193
accepted answer of: http://stackoverflow.com/q/52442106
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91827780
answers question: http://stackoverflow.com/q/52442106
type: Answer
has comment: http://stackoverflow.com/comment/91827210
has body: You can add custom clean_&lt;field&gt; method to your form to check value and raise error if value is no valid: class ParticipantRegisterForm(forms.ModelForm): class Meta: model = Participant fields = [ 'first_name', 'last_name', 'date_of_birth', 'has_health_cover', ] def clean_has_health_cover(self): data = self.cleaned_data['has_health_cover'] if data == '0': return data raise forms.ValidationError("Participant is ineligible")
has comment: http://stackoverflow.com/comment/91827432
has comment: http://stackoverflow.com/comment/91833464
score: 0

http://stackoverflow.com/a/52505857
type: Answer
has body: If I understand your question correctly, can't you just replace the string? with open(title, 'w') as f: f.write(res.replace("¥r¥n","¥n"))
score: 0
answers question: http://stackoverflow.com/q/52505583
has comment: http://stackoverflow.com/comment/91952761

http://stackoverflow.com/a/55587119
answers question: http://stackoverflow.com/q/52466522
upvote count: 0
score: -1
has body: template Staff Admin urls.py url(r'^admin/', authors_admin, name='admin'), url(r'^staff/', authors_staff, name='staff'), views.py def authors_admin(request): authors = Author.objects.all() if request.method="GET": authors = Author.objects.filter(status = 'admin') return render(request, 'template.html', { 'authors ': authors }) def authors_staff(request): authors = Author.objects.all() if request.method="GET": authors = Author.objects.filter(status = 'staff') return render(request, 'template.html', { 'authors ': authors })
downvote count: 1
type: Answer

http://stackoverflow.com/q/52487313
type: UnansweredQuestion
score: 3
has body: Jamspell is an excellent spell checking algorithm which allows the spell checker to be trained on particular models before it can be used. I am having some troubles running it on windows. On Linux it is working fine. The procedure for installation on windows is a bit involved. First you have to install Swig, also you need to have Microsoft Visual Studios build tools. It is recommended 2015, however, 2017 also works somewhat. This was the prerequisites before pip install jamspell worked with the following status. Collecting jamspell Using cached https://files.pythonhosted.org/packages/5a/16/0a808e926a835604007066085cb2183b337694a06240a99945b31fa14f27/jamspell-0.0.11.tar.gz Installing collected packages: jamspell Running setup.py install for jamspell ... done Could not find .egg-info directory in install record for jamspell from https://files.pythonhosted.org/packages/5a/16/0a808e926a835604007066085cb2183b337694a06240a99945b31fa14f27/jamspell-0.0.11.tar. gz#sha256=6dcaf1ae631af6c0904f9ba016bf2404e930237eb73e4d471ee92a77327af8f1 Successfully installed jamspell Once this is imported into the code, it is seen that, any model trained on linux is unable to be loaded using this module. The code is stuck infinitely in corrector = jamspell.TSpellCorrector() corrector.LoadLangModel("en.bin") However, through experimentation it was found that any model trained on Windows can be loaded into Windows. However, the model is incapable of any corrections, although it provides suggestions. Examples corrector.FixFragment("appel") appel corrector.GetCandidates("An apple a day keeps the doctor away".split(), 1) ('apple', 'apples', 'appln', 'apply', 'pple', 'appe', 'appel', 'appli', 'applie', 'ample', 'appl', 'appre') corrector.FixFragment("sherluck") sherluck Python Version 3.7. Having unsuccessful in this attempt, I tried to check the python files which were installed for Jamspell, only the following files were present __pycache__, EGG-INFO, _jamspell.cp37-win_amd64.pyd, _jamspell.py, j…
type: Question
tagged with: python-2.7
tagged with: spell-checking
downvote count: 0
has title: Unable to get Jamspell to work on windows
favorite count: 0
tagged with: python-3.7
tagged with: python
answer count: 0
upvote count: 3

http://stackoverflow.com/a/55751280
has body: I Found the way to get the output as same as Netezza ! And we need to create 4 Different UDF with different Inputs ! Here I've added the UDF for (TIMESTAMP, TIMESTAMP) create or replace function AGE_UDF_V2 (START_DATE TIMESTAMP, END_DATE TIMESTAMP) returns VARCHAR stable as $$ # -*- coding: utf-8 -*- """ Created on Wed Sep 26 12:59:24 2018 @author: pnataraj """ from dateutil import relativedelta from dateutil.parser import parse if (START_DATE is None or END_DATE is None): return None else: START_DATE = str(START_DATE).strip() END_DATE = str(END_DATE).strip() START_DATE = parse(START_DATE) END_DATE = parse(END_DATE) difference = relativedelta.relativedelta(START_DATE, END_DATE) years = difference.years months = difference.months days = difference.days hours = difference.hours minutes = difference.minutes seconds = difference.seconds age='' if years != 0: if years == 1 or years == -1: age+=str(years)+' year ' else: age+=str(years)+' years ' if months != 0: if months == 1 or months == -1: age+=str(months)+' mon ' else: age+=str(months)+' mons ' if days != 0: if days == 1 or days == -1: age+=str(days)+' day ' else: age+=str(days)+' days ' if (hours !=0 or minutes !=0 or seconds != 0): if (hours &lt; 0 or minutes &lt; 0 or seconds &lt; 0): age+=str("-"+format(abs(hours),"02")+":"+format(abs(minutes),"02")+":"+format(abs(seconds),"02")) else: age+=str(format(hours,"02")+":"+format(minutes,"02")+":"+format(seconds,"02")) elif(hours == 0 and minutes ==0 and seconds == 0): if len(age)&gt;0: age = age else: age = "00:00:00" return age.strip() $$ language plpythonu; Thanks for all the suggestions and Helps ! Hope It'll be helpful for those who're doing Nz to AWS RS Migration !
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52491128
accepted answer of: http://stackoverflow.com/q/52491128
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52534569
has answer: http://stackoverflow.com/a/52534774
has answer: http://stackoverflow.com/a/52534739
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52535097
type: Question
has body: I have a data set like this As you can see there is one categorical variable which is state later I encode categorical variable If I want to test my model with specific data I do something like this print(regressor.predict([[1,0,1000,2000,3000]])) Which works fine . But what I want to do is , while testing I directly want to input the city name , like New York or Florida How can I achieve this ?
tagged with: categorical-data
has answer: http://stackoverflow.com/a/52534700
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52534849
has title: test machine learning model with categorical variable in python
answer count: 5
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/92119956
comment on: http://stackoverflow.com/q/52588453
score: 0
has text: Sorry, I must have misunderstood the question. I don't have setup.py, but the code runs under Python 3.6.6 without any problems in a virtual environment. A setup with the following steps works for me: mkdir graph_stack_tmp python3 -m venv graph_stack_tmp cd graph_stack_tmp source bin/activate pip install networkx matplotlib <execute my code now>
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92032840
type: QuestionComment
comment on: http://stackoverflow.com/q/52546482
has text: As suggested above but with dict comprehension: `data = {n: np.array([monte_carlo1(n) for i in range(100)]) for n in (10,50,100,...)}`
score: 0
type: Comment

http://stackoverflow.com/q/52482947
has comment: http://stackoverflow.com/comment/91928225
has comment: http://stackoverflow.com/comment/91912189
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91915404
tagged with: yocto
accepted answer: http://stackoverflow.com/a/52494134
type: Question
upvote count: 2
has title: Use python3-pytz for an Application in Krogoth branch in yocto
has body: I am dependent on a board whose development is on the Krogoth branch in Yocto. The problem is when looking through the layers for the krogoth layer I obtain a python-pytz recipe which is dependent on meta-python and works only with python2.7. My application for which I am writing a recipe is Python3 dependent. I tried this by adding it to my local.conf as follows: IMAGE_INSTALL_append = " python3-pytz" which throws the following error: ERROR: Nothing RPROVIDES 'python3-pytz' on the contrary when I use IMAGE_INSTALL_append = " python-pytz" the bitbake process runs successfully and when I try to run the Python3 interpreter on the board as follows: # python3 &gt;&gt; import influxdb .... No module pytz found On the contrary when I run python which opens the 2.7 interpreter: # python &gt;&gt; import pytz .. no module threading. which is okay since I have not included python-threading in IMAGE_INSTALL_append. How do I use python3-pytz which is not available on krogoth's meta-python layer? There is a python3-pytz in a meta-homeassitant layer for the krogoth branch. I tried adding the layer to my bblayers.conf and tried adding python3-pytz but throws the same error as mentioned above.
has answer: http://stackoverflow.com/a/52494134
has comment: http://stackoverflow.com/comment/91915871
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/91913982
type: QuestionComment
has text: What exactly do you want to "sort" and "group" in your output? I think I understand that you want to compare all the lists in your list of lists and output the indices of the compared lists along with the difference in lengths, but I am not sure how you want the output sorted or grouped.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52485896

http://stackoverflow.com/comment/127285706
score: 0
type: AnswerComment
type: Comment
has text: Could this be possible in 3D?
comment on: http://stackoverflow.com/a/52470447

featuretools
tag name: featuretools
tags question: http://stackoverflow.com/q/52463225
type: Tag
tags question: http://stackoverflow.com/q/52463356
tags question: http://stackoverflow.com/q/52472930
tags question: http://stackoverflow.com/q/52463472
tags question: http://stackoverflow.com/q/52492335

http://stackoverflow.com/q/52513802
downvote count: 1
has comment: http://stackoverflow.com/comment/91971121
favorite count: 0
possible better answer: http://stackoverflow.com/a/62631941
has comment: http://stackoverflow.com/comment/91983223
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52518139
has body: Which dimension should softmax be applied to ? This code : %reset -f import torch.nn as nn import numpy as np import torch my_softmax = nn.Softmax(dim=-1) mu, sigma = 0, 0.1 # mean and standard deviation train_dataset = [] image = [] image_x = np.random.normal(mu, sigma, 24).reshape((3 , 4, 2)) train_dataset.append(image_x) x = torch.tensor(train_dataset).float() print(x) print(my_softmax(x)) my_softmax = nn.Softmax(dim=1) print(my_softmax(x)) prints following : tensor([[[[-0.1500, 0.0243], [ 0.0226, 0.0772], [-0.0180, -0.0278], [ 0.0782, -0.0853]], [[-0.0134, -0.1139], [ 0.0385, -0.1367], [-0.0447, 0.1493], [-0.0633, -0.2964]], [[ 0.0123, 0.0061], [ 0.1086, -0.0049], [-0.0918, -0.1308], [-0.0100, 0.1730]]]]) tensor([[[[ 0.4565, 0.5435], [ 0.4864, 0.5136], [ 0.5025, 0.4975], [ 0.5408, 0.4592]], [[ 0.5251, 0.4749], [ 0.5437, 0.4563], [ 0.4517, 0.5483], [ 0.5580, 0.4420]], [[ 0.5016, 0.4984], [ 0.5284, 0.4716], [ 0.5098, 0.4902], [ 0.4544, 0.5456]]]]) tensor([[[[ 0.3010, 0.3505], [ 0.3220, 0.3665], [ 0.3445, 0.3230], [ 0.3592, 0.3221]], [[ 0.3450, 0.3053], [ 0.3271, 0.2959], [ 0.3355, 0.3856], [ 0.3118, 0.2608]], [[ 0.3540, 0.3442], [ 0.3509, 0.3376], [ 0.3200, 0.2914], [ 0.3289, 0.4171]]]]) So first tensor is prior to softmax being applied, second tensor is result of softmax applied to tensor with dim=-1 and third tensor is result of softmax applied to tensor with dim=1 . For result of first softmax can see corresponding elements sum to 1, for example [ 0.4565, 0.5435] -> 0.4565 + 0.5435 == 1. What is summing to 1 as result of of second softmax ? Which dim value should I choose ? Update : The dimension (3 , 4, 2) corresponds to image dimension where 3 is the RGB value , 4 is the number of horizontal pixels (width) , 2 is the number of vertical pixels (height). This is an image classification problem. I'm using cross entropy loss function. Also, I'm using softmax in final layer in order to back-propagate probabilities.
tagged with: pytorch
tagged with: softmax
type: Question
has answer: http://stackoverflow.com/a/62631941
has answer: http://stackoverflow.com/a/52518139
has title: PyTorch softmax with dim
upvote count: 6
answer count: 2
score: 5
tagged with: deep-learning

http://stackoverflow.com/comment/91991255
has text: @MadPhysicist I added the link to the repo with the function. Please check it out if you would like to know the details.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52504622

http://stackoverflow.com/a/52560553
answers question: http://stackoverflow.com/q/52560439
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52560439
type: Answer
has comment: http://stackoverflow.com/comment/92061619
has comment: http://stackoverflow.com/comment/92237559
score: 3
has body: You can create an pool of data that have the most counts and then pick from there: import numpy as np a = [2, 2, 3, 1, 2] data = [i + 1 for i, e in enumerate(a) for _ in range(e)] print(data) result = np.random.choice(data, 6, replace=False) print(result) Output [1, 1, 2, 2, 3, 3, 3, 4, 5, 5] [1 3 2 2 3 1] Note that data is array that has for each element the specified count, then we pick randomly from data this way we ensure that you won't have more elements that the specify count. UPDATE If you need that each number appears at least one time, you can start with a list of each of the numbers, sample from the rest and then shuffle: import numpy as np result = [1, 2, 3, 4, 5] a = [1, 1, 2, 0, 1] data = [i + 1 for i, e in enumerate(a) for _ in range(e)] print(data) result = result + np.random.choice(data, 1, replace=False).tolist() np.random.shuffle(result) print(result) Output [1, 2, 3, 3, 5] [3, 4, 2, 5, 1, 2] Notice that I subtract 1 from each of the original values of a, also the original 6 was change to 1 because you already have 5 numbers in the variable result.
upvote count: 3

http://stackoverflow.com/a/52443681
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/123377046
answers question: http://stackoverflow.com/q/52443176
accepted answer of: http://stackoverflow.com/q/52443176
has body: The problem is not in your XPath expression, but in the assumption that the element you are looking for is in the page raw HTML file downloaded by Scrapy. Scrapy doesn't run any JavaScript files so that in many cases the response you get in Scrapy is different than what you see in the developer tools. If you open the same website using the "view page source" option from your browser, you'll see that the element you're looking for is not there. This means that such element is generated dynamically using JavaScript. There are some ways to solve this and I'd approach it in this order: check the page HTML and look for JS code containing the data you need; inspect the requests that your browser is doing in the requests panel in developer tools and try to find a request that is bringing that content for you; use a headless browser to render the page for you;
score: 4
has comment: http://stackoverflow.com/comment/91830366

http://stackoverflow.com/q/52458158
accepted answer: http://stackoverflow.com/a/52474184
has answer: http://stackoverflow.com/a/52458955
has comment: http://stackoverflow.com/comment/91867576
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/91871372
tagged with: python
possible better answer: http://stackoverflow.com/a/52458955
tagged with: pivot-table
score: 0
has body: I am dealing with the dataset titanic from [seaborn]. titanic = seaborn.load_dataset('titanic') I cut the age column into categorical bins. age = pd.cut(titanic['age'], [0, 18, 80]) Then the problem comes, the groupby and pivot_table give totally different results: titanic.groupby(['sex', age, 'class'])['survived'].mean().unstack(-1) titanic.pivot_table('survived', ['sex', age], 'class') groupby and pivot_table results At first, I guess it is because the nan in age, then I used dataset processed by dropna to redo it. titanic = titanic.dropna() age = pd.cut(titanic['age'], [0, 18, 80], right = True) titanic.groupby(['sex', age, 'class'])['survived'].mean().unstack(-1) titanic.pivot_table('survived', ['sex', age], 'class') This time I even got a totally different result. groupby and pivot_table results after dropna My python version is:Python 3.6.5 :: Anaconda, Inc. pandas: 0.23.0 My operating system is MaxOS High Sierra 10.13.6 I tried again with python 3.7.0 and pandas 0.23.4, and no error occurs. result under python 3..7.0 So I am wondering whether it is a bug of Anaconda?
has comment: http://stackoverflow.com/comment/91867566
type: Question
has answer: http://stackoverflow.com/a/52474184
type: AnsweredQuestion
tagged with: anaconda
answer count: 2
has title: Python: pivot_table and groupby get totally opposite result
has comment: http://stackoverflow.com/comment/91867759

http://stackoverflow.com/comment/91977674
type: QuestionComment
has text: does that work when you're running `"C:\Program Files\Anaconda2\python" my_script.py` from a terminal (not in python system cmd)
comment on: http://stackoverflow.com/q/52519022
score: 0
type: Comment

http://stackoverflow.com/a/76535419
has body: A little late, but I ran into the same problem today. Here was my solution: headers = [header["VarCharValue"] for header in results["ResultSet"]["Rows"][0]["Data"]] parsed_results = [ { headers[i]: results["ResultSet"]["Rows"][j]["Data"][i]["VarCharValue"] for i in range(0, len(headers)) } for j in range(1, len(results["ResultSet"]["Rows"])) ]
has comment: http://stackoverflow.com/comment/134963679
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52584104

http://stackoverflow.com/a/56044381
type: Answer
has body: Really appreciate both the question and @Teoretic's workaround. However in my case the merged cells for the Multiindex columns are very useful, and those are lost with @Teoretic's. I've done an alternative workaround hiding the entire row before writing, it works, thus I include it here in case is useful for anybody. writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='test1') writer.sheets['test1'].set_row(2, None, None, {'hidden': True}) writer.save()
score: 18
upvote count: 18
downvote count: 0
answers question: http://stackoverflow.com/q/52497554

http://stackoverflow.com/comment/91822626
type: QuestionComment
has text: That sounds extremely error prone to use just a number... one wrong digit and someone else is getting paid
comment on: http://stackoverflow.com/q/52439639
score: 2
type: Comment

http://stackoverflow.com/comment/91977366
type: Comment
comment on: http://stackoverflow.com/a/52518666
type: AnswerComment
score: 0
has text: Have a look at [stackoverflow_link](https://stackoverflow.com/a/18345890/8868822) .Aktually you can try to install it manually

http://stackoverflow.com/a/52495593
answers question: http://stackoverflow.com/q/52495309
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91932583
has body: I suggest you use MultiIndex columns for this, e.g. via pd.pivot_table. You can flatten columns as a separate step, although your data will lose structure. res = pd.pivot_table(df, index=['load', 'mapping'], columns='freq', values=['99th', 'energy'], aggfunc='first') Result: 99th energy freq 1.20GHz 2.10GHz 1.20GHz 2.10GHz load mapping 175.0k 5CN0-5CN1 0.937662 0.39128 18952.056063 19051.052048
type: Answer
has comment: http://stackoverflow.com/comment/91933500
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52495309

http://stackoverflow.com/comment/92032255
score: 1
has text: @Qudus: That's not a "break down", that's inefficiency of your algorithm. I'm having trouble mapping either your algorithm or your output form to the problem you linked. Also, *linking* to the main problem description is not generally allowed on Stack Overflow.
comment on: http://stackoverflow.com/q/52546154
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52527277
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52527232
upvote count: 2
answers question: http://stackoverflow.com/q/52527232
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91995134
has body: A head is not a kind of body, it's a part of the body AFAIK. So you should be using composition instead of inheritance: class Head: def __init__(self): # ...Set-up head... def head_actions(): print('Head does something') class Body: def __init__(self): self.head = Head() # ...Set-up body... def body_actions: print('Body does something') Now you can do: body = Body() body.body_actions() body.head.head_actions() The reason you get infinite recursion is that your Body is the superclass of Head, so when you call super().__init__() you instantiate a Body, which in your implementation creates a Head, which calls super().__init__() and so forth. Composition (if that's what you mean by 'nesting') is not bad practice, it's standard practice and often makes more sense than inheritance. Edit in response to comment To access the Body methods from the Head you can pass a reference to the Body on creation. So redefine the classes as follows: class Head: def __init__(self, body): self.body = body def head_actions(): print('Head does something') class Body: def __init__(self): self.head = Head(self) def body_actions: print('Body does something') Now you can access the head from the body and the body from the head: body = Body() head = body.head head.body.body_actions() Or even body.head.body.body_actions()
type: AcceptedAnswer

twilio
tag name: twilio
type: Tag
tags question: http://stackoverflow.com/q/52527390

http://stackoverflow.com/comment/91957497
type: AnswerComment
type: Comment
has text: Yes, enclosing the xpath in () and then we can iterate through all elements found using that xpath by using [index] where index starts from '1' unlike our programming array which starts with '0'
score: 1
comment on: http://stackoverflow.com/a/52453446

http://stackoverflow.com/comment/92053927
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52549001
type: QuestionComment
has text: (*Spyder maintainer here*) If you really are a *Noob programmer*, please switch to use Anaconda, conda and the conda envs instead of fighting with pip, which is much harder to make it work correctly. Other than that, I refrain from giving you further help because you don't want to accept this simple piece of advice, which we mention time and time again.

http://stackoverflow.com/q/52472531
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52484067
accepted answer: http://stackoverflow.com/a/52484067
downvote count: 0
type: Question
tagged with: numpy
upvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/91887375
has answer: http://stackoverflow.com/a/52475349
favorite count: 0
has comment: http://stackoverflow.com/comment/91897920
possible better answer: http://stackoverflow.com/a/52472639
has body: I have a python function given below: def myfun(x): if x &gt; 0: return 0 else: return np.exp(x) where np is the numpy library. I want to make the function vectorized in numpy, so I use: vec_myfun = np.vectorize(myfun) I did a test to evaluate the efficiency. First I generate a vector of 100 random numbers: x = np.random.randn(100) Then I run the following code to obtain the runtime: %timeit np.exp(x) %timeit vec_myfun(x) The runtime for np.exp(x) is 1.07 µs ± 24.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each). The runtime for vec_myfun(x) is 71.2 µs ± 1.68 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) My question is: compared to np.exp, vec_myfun has only one extra step to check the value of $x$, but it runs much slowly than np.exp. Is there an efficient way to vectorize myfun to make it as efficient as np.exp?
has answer: http://stackoverflow.com/a/52472639
has comment: http://stackoverflow.com/comment/91893113
tagged with: python
has title: Efficiency problem of customizing numpy's vectorized operation
tagged with: vectorization
has comment: http://stackoverflow.com/comment/91887346
has comment: http://stackoverflow.com/comment/91901706

http://stackoverflow.com/comment/91975144
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52517464
type: Comment
has text: I already had that solution in my mind, but it always takes the first reaction and then shows it as often as there are reactions

http://stackoverflow.com/comment/91936606
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52497149
has text: @Marein "not necessarily but they might" is not a problem that I can solve for you. How does ``Xi`` know which ``Xj`` to use? If you have to tell it anyway, might as well write that single line... Either way, I have added an example of creating an ``X2_with_Y`` from ``X2.specialise(Y)`` and ``X2[Y]``.
type: AnswerComment

http://stackoverflow.com/comment/91988672
score: 1
comment on: http://stackoverflow.com/a/52524403
type: AnswerComment
type: Comment
has text: Thanks for the hint. By the way is there a book or good place to get an overview of such principles?

http://stackoverflow.com/comment/133720000
has text: I'm currently using dearpygui but I'm interested in pyqt. I'd like to look at the code. I don't think I'll be actively contributing, but if you're about to archive the project, that'd be cool. https://github.com/willmendil
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52514618

http://stackoverflow.com/comment/91976400
score: 0
has text: Prefer using Ctrl + F5 in the future.
type: QuestionComment
comment on: http://stackoverflow.com/q/52518305
type: Comment

http://stackoverflow.com/q/52466901
score: 0
has comment: http://stackoverflow.com/comment/91875571
answer count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/52466983
favorite count: 0
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91875624
has body: I'm trying to generate a Sudoku. I thought about using an array for this. THis is how I create the array (ignore the fact that these are not correct Sudoku numbers): row_array = [[1, 99],[2],[3], [4], [5], [6], [7], [8], [9]] It does work fine. The problem is with an if statement. If I do: print(row_array[0][1]) or: r = 1 print(row_array[0][r]) to get the "99" it does work fine! But if I use this variable method in an if statement like this: if y not in row_array[1] and y not in row_array[0][r]: row_array[1].append(y) I get the following ERROR: TypeError: argument of type 'int' is not iterable I had the Sudoku working, but it took to much code, so I want to set up a counter to replace the rows and columns with an it. I'm aware of you guys probably already having a much better code for a sudoku, but I want to teach myself, and make the code better and shorter over time. I don't learn to code real good, by just copy someone else's idea or way to code.
upvote count: 1
has title: Python - If Statement with two-dimensional array
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91875765
tagged with: if-statement

http://stackoverflow.com/q/52449207
tagged with: python
has comment: http://stackoverflow.com/comment/91892958
accepted answer: http://stackoverflow.com/a/52449858
answer count: 3
tagged with: image-processing
possible better answer: http://stackoverflow.com/a/52449744
has comment: http://stackoverflow.com/comment/91842690
has answer: http://stackoverflow.com/a/52449744
upvote count: 5
has answer: http://stackoverflow.com/a/68722636
tagged with: deep-learning
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91965389
downvote count: 0
has answer: http://stackoverflow.com/a/52449858
has title: how to merge different dimensions arrays in python?
favorite count: 0
has body: I am analyzing some image represented datasets using keras. I am stuck that I have two different dimensions of images. Please see the snapshot. Features has 14637 images having dimension (10,10,3) and features2 has dimension (10,10,100) Is there any way that I can merge/concatenate these two data together.?
has comment: http://stackoverflow.com/comment/91842447
has comment: http://stackoverflow.com/comment/91901509
type: Question
score: 5

http://stackoverflow.com/comment/91941529
type: Comment
comment on: http://stackoverflow.com/q/52498858
type: QuestionComment
has text: It'll work [as expected](https://i.sstatic.net/egAgq.png) when using more colors per decade to define the colormap, e.g. `mapColS = list(plt.cm.gray(np.linspace(0,1,100)))`. However you will notice that the lowest is not completely black and the highest not completely white. This is due to the problem shown in [this question](https://stackoverflow.com/questions/46768028/how-does-pyplot-contourf-choose-colors-from-a-colormap/46777627#46777627). But one would need to look deeper in how the the solution there is applicable to a lognorm.
score: 0

memoization
type: Tag
tags question: http://stackoverflow.com/q/52536463
tags question: http://stackoverflow.com/q/52531165
tag name: memoization

http://stackoverflow.com/comment/92055136
has text: Start by creating a blank window. Try to add one image. There are plenty of examples in the internet. Next, add a second. If you get stuck, show what you've tried. Stackoverflow isn't intended to be a tutorial site.
type: Comment
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/52558118

http://stackoverflow.com/comment/96731995
has text: If you found the solution please share . Thanks
comment on: http://stackoverflow.com/q/52471464
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91810694
has text: Which functionality do you mean?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52432726

http://stackoverflow.com/q/52468312
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52468811
score: 3
downvote count: 0
has title: Pandas merging dataframes, overwriting values on key
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91878774
upvote count: 3
answer count: 2
accepted answer: http://stackoverflow.com/a/52468448
tagged with: pandas
has body: My apologies if this question is a duplicate. I really cannot find the answer to this specific case. Is it possible to merge/join two dataframes, while overwriting the values in the first dataframe if the key ('id') also exists in the second dataframe? Kind of like the 'INSERT - ON DUPLICATE KEY UPDATE' command in SQL. The first dataframe 'df1': id value 0 100010 25 1 100011 22 2 100012 30 The second dataframe 'df2': id value 0 100012 35 1 100013 36 Merging the dataframes results in new columns and keeps the old data for 'id' '100012': df3 = pd.merge(df1, df2, on='id', how='outer') print(df3) id value_x value_y 0 100010 25.0 NaN 1 100011 22.0 NaN 2 100012 30.0 35.0 3 100013 NaN 36.0 Is it possible to get to the desired output directly from the merge function? So only 'id' '100012' is updated and new row '100013' is added? id value 0 100010 25 1 100011 22 2 100012 35 3 100013 36 I've tried merge, join, update and combine_first, all without success. Thanks for your help!
favorite count: 0
has comment: http://stackoverflow.com/comment/91878804
possible better answer: http://stackoverflow.com/a/52468811
has answer: http://stackoverflow.com/a/52468448
tagged with: python
has comment: http://stackoverflow.com/comment/91878465

http://stackoverflow.com/comment/91908331
score: 0
type: AnswerComment
type: Comment
has text: I can help on that as well, but will need more details on the error. If you feel it's a small thing then add it to this question, else create a new one.
comment on: http://stackoverflow.com/a/52481937

http://stackoverflow.com/comment/91824219
has text: `b = 3` is not *modifying* an existing value; it binds a *new* value to `b`.
type: Comment
score: 4
comment on: http://stackoverflow.com/q/52440701
type: QuestionComment

http://stackoverflow.com/q/52561167
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/92061185
has comment: http://stackoverflow.com/comment/92061023
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92060943
tagged with: python
has title: I need to use User Defined Functions to create lists
type: AnsweredQuestion
upvote count: 0
has body: I'm writing code that involves user defines functions, something which I'm new at. from statistics import * years = [2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016] woodDeaths = [19.6, 10.4 ,10.5 ,13.8, 23.1, 19.6, 26.7, 27.8, 53.7] mcdowellDeaths = [102.2, 103.3, 108.5, 119.7, 70.3, 105.4, 107.6, 141.2, 73.1] mercerDeaths = [46.9, 22.5, 54.6, 81.6, 59.2, 40.3, 76.1, 62.1, 74.4] raleighDeaths = [24.2, 15.2, 57.1, 75.8, 73.4, 46.9, 49.8, 80, 58.7] def get_average(raw_data): raw_data = sum(raw_data) / len(raw_data) return raw_data def calculate_z_scores(raw_data): z_scores = [] for i in raw_data: z_score = i - (sum(raw_data) / len(raw_data)) / raw_data.stdev append.z_scores(z_score) return z_scores def print_stats(deaths_data, county): get_average(deaths_data) print (f" In {county} the average deaths was {deaths_data}") calculate_z_scores(deaths_data) z_scores = calculate_z_scores for i in years: print (f" In {years}, the z-score is: {z_score}") def main(): print_stats (woodDeaths, "Wood County") print_stats (mcdowellDeaths, "McDowell County") print_stats (mercerDeaths, "Mercer County") print_stats (raleighDeaths, "Raleigh County") if __name__ == "__main__": main() But whenever I try to run the code, I get one error, fix it, then get another error. Could anyone help me with how to fix this? The Example Output In Wood County the average deaths was [19.6, 10.4, 10.5, 13.8, 23.1, 19.6, 26.7, 27.8, 53.7] Traceback (most recent call last): File "C:\Users\brenn\Documents\python\bouillion_brennan_hw3_ocp.py", line 33, in &lt;module&gt; main() File "C:\Users\brenn\Documents\python\bouillion_brennan_hw3_ocp.py", line 28, in main print_stats (woodDeaths, "Wood County") File "C:\Users\brenn\Documents\python\bouillion_brennan_hw3_ocp.py", line 23, in print_stats calculate_z_scores(deaths_data) File "C:\Users\brenn\Documents\python\bouillion_brennan_hw3_ocp.py", line 17, in calculate_z_scores z_score = i - (sum(raw_data) / len(raw_data)) / raw_data.stdev AttributeError: 'lis…
has comment: http://stackoverflow.com/comment/92061275
has answer: http://stackoverflow.com/a/52561737
type: Question
accepted answer: http://stackoverflow.com/a/52561737
score: -2
has comment: http://stackoverflow.com/comment/92060956

http://stackoverflow.com/a/52462088
has comment: http://stackoverflow.com/comment/91866375
has body: The variable procLine has the in shear flow past a flat plate And procLine.split() ['the', 'in', 'shear', 'flow', 'past', 'a', 'flat', 'plate'] In for loop, it finds a and replaces a in procLine with empty or removes the character. Note: it would do same if some word was with in e.g. string to strg. Instead I would suggest something like list comprehension may work: procLine = ' '.join([w for w in procLine.split() if len(w)&gt;2])
has comment: http://stackoverflow.com/comment/91866685
score: 6
accepted answer of: http://stackoverflow.com/q/52462066
has comment: http://stackoverflow.com/comment/91866692
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52462066
downvote count: 0
has comment: http://stackoverflow.com/comment/91866641
has comment: http://stackoverflow.com/comment/91866678
type: Answer
has comment: http://stackoverflow.com/comment/91866450
upvote count: 6
has comment: http://stackoverflow.com/comment/91866669

http://stackoverflow.com/q/52579981
has answer: http://stackoverflow.com/a/52580178
score: -3
has title: Splitting string that has \u inside
has body: I know that u"string" refers to Unicode. If I am not mistaken this is where I ran into a problem. I was not able to find a solution that ultimately helps me to split the string into 2 strings if that string has '\u' inside. I have a list of strings that are divided by ',' where the first part is the crime committed and the second part is the location where the crime was committed. for example: SHOPLIFT, NE MILL PL VANDALISM, 136TH AVE NE SUSPICIOUS CIRCUMSTANCES, GARDEN WAY MENTAL PROBLEMS, NE WOODINVILLE DUVALL RD TRESPASS – 19200 BLK 168TH AVE NE when I use the data.split(',')i get the following results: [u'SHOPLIFT', u' NE MILL PL '] [u'VANDALISM', u' 136TH AVE NE '] [u'SUSPICIOUS CIRCUMSTANCES', u' GARDEN WAY '] [u'MENTAL PROBLEMS', u' NE WOODINVILLE DUVALL RD '] [u'TRESPASS \u2013 19200 BLK 168TH AVE NE '] as you can see the split method worked fine for the first 4 items. The fifth item: [u'TRESPASS \u2013 19200 BLK 168TH AVE NE '] is the one I have the problem with. How can I split that item so it would show the following: [u'TRESPASS', u'2013 19200 BLK 168TH AVE NE '] split('–') does not work either TRESPASS – 19200 BLK 168TH AVE NE gives the following error: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128) thank you.
downvote count: 4
accepted answer: http://stackoverflow.com/a/52580178
answer count: 1
tagged with: string
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/92095146
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92095185
upvote count: 1
type: Question
tagged with: split

http://stackoverflow.com/comment/91879116
has text: Anyway. Thanks for answering.
comment on: http://stackoverflow.com/a/52466524
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52494061
type: Question
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/52494890
has body: I have a numpy array with a shape of (9099, 2, 26). From this array I would like to get a new one with a shape of (9099, 2, 1), where the value for the 3rd dimension will be defined by another 1d array (9099,). This 1d array each value is actually an index of required value of 3rd dimension in my main array. So, for example, the 9th element of my main array looks like this: In [1]: a[9,:,:] Out [1]: array([[ 0, 1011165, 1098400, 1140065, 1172240, 1203971, 1439189, 1600540, 2281575, 8888888, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 280000, 263998, 974020, 653653, 888965, 851341, 466195, 424801, 0, 9999999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) The 9th element of 1d array is: In [2]: b[9] Out [2]: 9 So the 10th element of the desired output should looks like this: In [3]: c[9,:,:] Out [3]: array([[8888888], [9999999]]) I guess it should be done somehow with fancy indexing? Thanks!
has title: NumPy array fancy indexing
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91929553
score: -1
has comment: http://stackoverflow.com/comment/91929384
has comment: http://stackoverflow.com/comment/91928822
downvote count: 1

http://stackoverflow.com/comment/91924736
score: 0
has text: What is the output that you are expecting.?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52491900

http://stackoverflow.com/comment/91952112
type: QuestionComment
comment on: http://stackoverflow.com/q/52505649
has text: If you followed this [guidelines](https://python-packaging.readthedocs.io/en/latest/dependencies.html) pip will install all necessary dependencies.
score: 0
type: Comment

http://stackoverflow.com/comment/91961879
type: QuestionComment
has text: @MohitSolanki TIMEZONE = 'UTC' apart form this do i want to change anything in models.py bcoz after adding TIMEZONE = 'UTC' in setting also im getting same output like `2018-09-26T06:07:15.626452Z`
comment on: http://stackoverflow.com/q/52510834
score: 0
type: Comment

http://stackoverflow.com/comment/91877267
type: QuestionComment
comment on: http://stackoverflow.com/q/52467727
has text: Hi, shouldn't you have another ")" at the end of return statement? Also, isn't it `match_object != None`? The second part seems to be on the next line for some reason. Also could you give traceback of the error?
score: 0
type: Comment

http://stackoverflow.com/q/52518134
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: cuda
has comment: http://stackoverflow.com/comment/91976397
tagged with: tensorflow
type: Question
has body: Is there any documentation about what versions of TensorFlow work with which versions of CUDA Toolkit? From their GPU Support page, I see that the latest stable version of TensorFlow (1.10 at the time of writing) requires CUDA 9.0. I need to install TF/CUDA on a PC with a slightly older graphics card (latest driver version 377.83) that supports only CUDA 8.0 (according to this listing). Now I wonder what is the newest version of TensorFlow I can use that is compatible with CUDA 8? Is there a comprehensive table of compatible versions anywhere?
has title: Which versions of TensorFlow work with which versions of CUDA
linked to: http://stackoverflow.com/q/50622525
favorite count: 0
duplicate of: http://stackoverflow.com/q/50622525
score: 0
tagged with: cudnn
has comment: http://stackoverflow.com/comment/91976155
answer count: 0

http://stackoverflow.com/comment/91812372
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52433957
has text: @Waterman Please open the CSV file in a text editor (Notepad, Sublime, etc.) and paste the line from there. The first screenshot only shows how the program you opened it in understood that line. (You can always [edit] the question)
score: 0

http://stackoverflow.com/q/52440377
downvote count: 0
has title: no module named pyrebase?
score: 1
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/64642760
has answer: http://stackoverflow.com/a/64642760
tagged with: python
tagged with: firebase
accepted answer: http://stackoverflow.com/a/52440448
type: AnsweredQuestion
has body: i have been trying to access my firebase DB through a python program on my rapberry pi 3, but i have been encountering the same import error File "/home/pi/Desktop/testFB.py", line 1, in &lt;module&gt; import pyrebase ImportError: No module named 'pyrebase' Here is the code import pyrebase config = { "apiKey": "apikey", "authDomain": "db.firebaseapp.com", "databaseURL": "https://db.firebaseio.com/", "storageBucket": "db.appspot.com" } firebase = Pyrebase.initialize_app(config) db=firebase.database() print(db.get()) upon running 'pip3 list', 'Pyrebase==3.0.27' is in there but in the file /usr/lib/python3.5 (where the rest of my modules are) Pyrebase.py is not there? any help is appreciated, although similar questions have solutions that have not been working for me... thanks in advance, 3NiGMa
has comment: http://stackoverflow.com/comment/91823607
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91824304
has comment: http://stackoverflow.com/comment/91824043
answer count: 2
has answer: http://stackoverflow.com/a/52440448

http://stackoverflow.com/q/52565850
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52565932
possible better answer: http://stackoverflow.com/a/52566046
has answer: http://stackoverflow.com/a/52566046
score: 0
has title: Trying to determine whether an object is a function, and datetime.datetime.now caused a strange problem
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92069465
tagged with: python
has answer: http://stackoverflow.com/a/52565932
type: AnsweredQuestion
has body: Environment: Linux &amp; CPython 3.6.4 Hi everyone, I'm trying to determine if an object is a function. And I do this with the types library, the code I wrote is like the following. class Foo: @classmethod def is_function(cls, obj): ''' determines whether an object is a function ''' return isinstance(obj, types.FunctionType) @classmethod def is_classmethod(cls, obj): ''' determines whether an object is a class method ''' type_ = type(cls.is_classmethod) return isinstance(obj, type_) The first function "is_function" dosn't works on class methods. So, I wrote the second function "is_classmethod". And I read the code of the types library in order to find something like "ClassmethodType", but I found the following code, so the type I'm using in the second function is "type(cls.is_classmethod)". # lib/python3.6/types.py at line 11 def _f(): pass FunctionType = type(_f) Then, I did some experiment with it: class Bar: @classmethod def b(cls): pass Foo.is_function(Bar.b) # False Foo.is_classmethod(Bar.b) # True These 2 functions work as expected. But, when I pass datetime.datetime.now into these functions, both of them return False. And I already read the code of datetime library before doing this, datetime.datetime.now is definitely a class method. # lib/python3.6/datetime.py at line 1475 @classmethod def now(cls, tz=None): "Construct a datetime from time.time() and optional time zone info." t = _time.time() return cls.fromtimestamp(t, tz) I cannot even imagine about this, how could it be? The second function has already been proven, it do detects class methods and I found nothing special on datetime.datetime.now, it just a normal classmethod. So, what caused this?

http://stackoverflow.com/comment/92074888
type: AnswerComment
type: Comment
has text: I tried all of them, but the result is still object and not integer. Can I mix int(x) with str.extract? something like int.extract? thanks again!
comment on: http://stackoverflow.com/a/52545974
score: 0

http://stackoverflow.com/q/52491656
score: 7
has answer: http://stackoverflow.com/a/52492169
accepted answer: http://stackoverflow.com/a/52504408
has title: Extracting images from presentation file
downvote count: 1
has answer: http://stackoverflow.com/a/68843746
type: Question
has comment: http://stackoverflow.com/comment/91924909
tagged with: python-2.7
has answer: http://stackoverflow.com/a/77766814
has answer: http://stackoverflow.com/a/52504408
favorite count: 0
upvote count: 8
answer count: 5
has body: I am working on python-pptx package. For my code I need to extract all the images that are present inside the presentation file. Can anybody help me through this ? Thanks in advance for help. my code looks like this: import pptx prs = pptx.Presentation(filename) for slide in prs.slides: for shape in slide.shapes: print(shape.shape_type) while using shape_type it is showing PICTURE(13) present in the ppt. But i want the pictures extracted in the folder where the code is present.
tagged with: python-pptx
tagged with: python
has comment: http://stackoverflow.com/comment/91924053
possible better answer: http://stackoverflow.com/a/53855752
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53855752
linked to: http://stackoverflow.com/q/44673401

http://stackoverflow.com/comment/91904751
has text: IMO, `cons` should return a tuple, not a function
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52481607

http://stackoverflow.com/q/52498373
type: Question
has title: retrieve/search for emails using message ID through python IMAP
has comment: http://stackoverflow.com/comment/91948358
tagged with: imap
has comment: http://stackoverflow.com/comment/91937691
has answer: http://stackoverflow.com/a/52512896
accepted answer: http://stackoverflow.com/a/52512896
answer count: 2
score: 5
tagged with: email
favorite count: 0
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/91937921
possible better answer: http://stackoverflow.com/a/58305076
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58305076
downvote count: 0
has body: Is there a way to retrieve/search for emails using message ID through python IMAP programmatically.I want to extract attachments of the mail using message ID. Any help would be much appreciated. Thank you

http://stackoverflow.com/comment/92037607
comment on: http://stackoverflow.com/q/52549254
has text: This is correct over a large sample size but easily missed on such a small one: 12. I’d suggest you roll the die several thousand or tens of thousands of times and compare the number of times you saw each face.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52474045
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91890036
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91889938
has answer: http://stackoverflow.com/a/52474753
type: Question
has body: I have some discrete coordinates with their heights and I need to create a smooth surface which I will continue to use. I need to have heights for all the coordinates in that surface. I was considering using a 3D spline but I am having trouble applying the methods suggested in comparable kind of questions. I am not an experienced programmer so I would probably find any suggestions helpful. Please forgive me if I may asked something very similar to what was already discussed before. I am using Python 3.6. EDIT I made a tiny list (similar to what I have). Z=[] Z.append([20.2, 20.1, 35]) Z.append([20.1, 24.5, 36]) Z.append([21.0, 23.2, 33]) Z.append([22.3, 20.0, 34]) Z.append([22.3, 19.5, 28]) Z.append([20.1, 19.5, 27]) Z.append([20.1, 24.6, 31]) Z.append([22.3, 24.6, 32]) The first number here represents longitude, the second - latitude and the third - altitude. I need to make a "surface" (not necessarily to plot it) which would contain the information about all the coordinates in between this rectangle. I believe this could sound unclear but maybie the problem is that I do not know the exact structure or the type of data I am looking for.
score: 0
has comment: http://stackoverflow.com/comment/91889742
tagged with: 3d
answer count: 1
tagged with: spline
accepted answer: http://stackoverflow.com/a/52474753
favorite count: 0
has title: How to create a 3D surface from given coordinates with python?
tagged with: python
tagged with: interpolation

http://stackoverflow.com/q/52558118
has title: How to display multiple images inside tkinter window?
answer count: 2
tagged with: tkinter-canvas
favorite count: 0
has comment: http://stackoverflow.com/comment/92055073
downvote count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92054881
tagged with: tkinter
score: -3
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/92055132
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52568052
has answer: http://stackoverflow.com/a/52733292
has body: I want to display 7 different images and plot them inside tkinter window. I only know to display it using OpenCV which actually displays the image outside the Tkinter GUI window. How to plot the images inside the GUI window? Tkinter GUI:
upvote count: 2
has comment: http://stackoverflow.com/comment/92055136

http://stackoverflow.com/a/59602574
answers question: http://stackoverflow.com/q/52556939
downvote count: 0
has comment: http://stackoverflow.com/comment/108378045
type: Answer
has body: Simple usage example of JobQueue Extention from python-telegram-bot from telegram.ext import Updater, CommandHandler def callback_alarm(bot, job): bot.send_message(chat_id=job.context, text='Wait for another 10 Seconds') def callback_timer(bot, update, job_queue): bot.send_message(chat_id=update.message.chat_id, text='Wait for 10 seconds') job_queue.run_repeating(callback_alarm, 10, context=update.message.chat_id) def stop_timer(bot, update, job_queue): bot.send_message(chat_id=update.message.chat_id, text='Stopped!') job_queue.stop() updater = Updater("YOUR_TOKEN") updater.dispatcher.add_handler(CommandHandler('start', callback_timer, pass_job_queue=True)) updater.dispatcher.add_handler(CommandHandler('stop', stop_timer, pass_job_queue=True)) updater.start_polling() the /start command will start the JobQueue and will send a message with an interval of 5 seconds, and the queue can be stopped by /stop command.
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/116022381

http://stackoverflow.com/comment/91838442
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52447815
has text: Look up dimensionality reduction, tf-idf, countvectorizer, etc.
score: 1

http://stackoverflow.com/comment/91957667
comment on: http://stackoverflow.com/q/52508293
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. However, if you follow whatever resources you find on line, make an honest coding attempt, and run into a problem, you'd have a good example to post.
type: Comment
score: 0

http://stackoverflow.com/a/52564885
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92171696
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52564511
accepted answer of: http://stackoverflow.com/q/52564511
downvote count: 0
score: 1
has body: You have both both y and hue set to the same column, impact_action_yn_new. This might be the source of the error, though I can't reproduce it using Seaborn 0.9.0. In any case, having y equal to hue is probably not that useful! Using y='value' and hue='impact_action_yn_new' gives the following: sns.barplot(x=stacked_imp_eng.Engagement, y=stacked_imp_eng.value, hue=stacked_imp_eng.impact_action_yn_new)

http://stackoverflow.com/q/52465660
has body: I'm a Linux Mint user who's been trying to import bs4 and nltk in VSCode and Sublime Text, but the error ImportError: No module named nltk [or bs4] always pops up. I've tried: importing them in the terminal, which somehow always works. Have tried changing the python path settings to python3.5 and python3.7, which doesn't fix the problem. I've also tried importing them in Sublime Text and the Reticulate package in R, both of which have resulted in failure. But despite hours of trying and searching, it just does not seem to be working. Any help on the matter would be appreciated, thank you!
tagged with: python-module
tagged with: linux-mint
has comment: http://stackoverflow.com/comment/91873273
has title: Python modules can't be loaded in text editors (but work in the command line) on Linux Mint
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/91873201
type: Question
tagged with: visual-studio-code
upvote count: 0
has answer: http://stackoverflow.com/a/52470493
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52470493

http://stackoverflow.com/comment/91911425
type: Comment
type: QuestionComment
has text: I didnt think i needed to solve the second function for the first to run correctly
score: 0
comment on: http://stackoverflow.com/q/52484901

http://stackoverflow.com/comment/91859955
type: QuestionComment
comment on: http://stackoverflow.com/q/52458406
has text: @LéopoldHoudin, I want to return the IDs along with some corresponding data. Will work on getting a toy example soon!
score: 0
type: Comment

http://stackoverflow.com/q/52492400
has answer: http://stackoverflow.com/a/52492487
accepted answer: http://stackoverflow.com/a/52492487
tagged with: django
type: Question
upvote count: 2
answer count: 1
has title: Django delete confirmation view displaying variable name instead of information
favorite count: 0
has body: Can anyone help me with the following scenario? I have 3 tables like bellow. 1 &amp; 2 is my data tables. And 3 keeps the relationship with 1 &amp; 2. 1.Qa table ------------- |ID | QA | ------------- |1 |qa1 | |2 |qa2 | |3 |qa3 | ------------- a field of my Qa model tags = select2.fields.ManyToManyField(Tag, blank=True, verbose_name='Tag') 2.Tag table ------------- |ID | Tag | ------------- |1 |tag1 | |2 |tag2 | |3 |tag3 | ------------- 3.qa tag relation --------------------- |ID |QA_ID |Tag_ID | --------------------- |1 |1 |2 | |2 |1 |3 | |3 |2 |1 | |4 |3 |1 | |5 |3 |2 | |6 |3 |3 | --------------------- Edit qa model class Qa(models.Model): question_text = models.CharField(max_length=1000, verbose_name='Question') tags = select2.fields.ManyToManyField(Tag, blank=True, verbose_name='Tag') """ And some more fields. """ def __str__(self): return self.question_text class Meta: ordering = ("id",) verbose_name = 'QA data' tag model class Tag(models.Model): tag_text = models.CharField(max_length=30, unique=True, verbose_name='Tag') def __str__(self): return self.tag_text class Meta: verbose_name = 'QA Tag' ※I do not have qa_tag model If I delete the list of Tag (from above 2.Tag Table), it redirects to the confirmation table. And it displays the list with some variable name like bellow Tag: tag1 Qa-tag relation: Qa_tags object Qa-tag relation: Qa_tags object Tag: tag2 Qa-tag relation: Qa_tags object Tag: tag3 Qa-tag relation: Qa_tags object Qa-tag relation: Qa_tags object Qa-tag relation: Qa_tags object what I really expect is (something user readable information) Tag: tag1 Qa-tag relation: qa2 Qa-tag relation: qa3 Tag: tag2 Qa-tag relation: qa1 Tag: tag3 Qa-tag relation: qa1 Qa-tag relation: qa2 Qa-tag relation: qa3 I cannot figure out why this happens and how to fix it. Any help would be much appreciated. Edit2: After Daniel Roseman's Answer I tried to create an own model to handle the many to many relation class Qa_Tag(models.Model): def __str__(self): return self.tag…
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52507438
answer count: 1
downvote count: 0
favorite count: 0
tagged with: qgridlayout
tagged with: python
has answer: http://stackoverflow.com/a/52507635
has title: QGridlayout and QGroupbox alignment
type: AnsweredQuestion
upvote count: 3
tagged with: pyqt5
type: Question
score: 3
tagged with: qgroupbox
accepted answer: http://stackoverflow.com/a/52507635
has body: I've created a widget with contents of 3 QGroupbox, I am trying to place and align them respectively with QGridLayout. Strange behaviour of QGroupboxsmakes this question. What looks like currently. As shown above figure when Qwidget screen stretchs in and out, Every group overlap each other and by outstretching replaces strangely and unwanted. What I want to be.... By stretching in want all groups keeping its own position Fixed and scrollbar would appear instead. The code is: import sys from PyQt5 import QtCore, QtGui, QtWidgets class ClassWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(ClassWidget, self).__init__(parent) self.setGeometry(QtCore.QRect(200, 100, 670, 360)) self.A = ClassA() self.B = ClassB() self.C = ClassC() grid = QtWidgets.QGridLayout(self) grid.addWidget(self.A, 0, 0) grid.addWidget(self.B, 0, 1, 1, 2) grid.addWidget(self.C, 1, 0, 1, 2) class ClassA(QtWidgets.QWidget): def __init__(self, parent=None): super(ClassA, self).__init__(parent) self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False)) self.c_lay = QtWidgets.QHBoxLayout() fctd = "One\n\nTwo\n\nThree" con_strength = QtWidgets.QLabel(fctd) self.value = QtWidgets.QLineEdit('Test') self.c_lay.addWidget(con_strength) self.c_lay.addWidget(self.value, alignment=QtCore.Qt.AlignRight) self.combo = QtWidgets.QComboBox() self.combo.addItems(["10","12","14","16"]) self.hbox = QtWidgets.QHBoxLayout() self.con = QtWidgets.QLabel("Number: ") self.hbox.addWidget(self.con) self.hbox.addWidget(self.combo) self.vlay = QtWidgets.QVBoxLayout() self.vlay.addLayout(self.hbox) self.vlay.addLayout(self.c_lay) self.vlay.addStretch() Concrete_Group = QtWidgets.QGroupBox(self) Concrete_Group.setTitle("&amp;GroupA") Concrete_Group.setLayout(self.vlay) self.comth = ["10","12","14","16"] self.combo.activated.connect(self.setdatastrength) @QtCore.pyqtSlot(int) def setdatastrength(self, index): value = self.comth[index] self.display_data(value) def display_data(self, value): try: f =…
tagged with: pyqt

http://stackoverflow.com/comment/91867979
has text: @dow replace that line with this raise ValueError('new value = '+str(new_val)+' doesn\'t match with orignal value = '+str(old_v)+' of key: '+str(old_k))
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52453274

http://stackoverflow.com/comment/92082258
comment on: http://stackoverflow.com/q/52572874
has text: because the class itself is not a parameter in the function. A `@classmethod` should only be used if you process the `cls` itself (or a subchild might do that). But you can still override the method in a `User`'s subclass.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52484359
has comment: http://stackoverflow.com/comment/91910734
score: -1
has answer: http://stackoverflow.com/a/52484948
accepted answer: http://stackoverflow.com/a/52484948
upvote count: 0
answer count: 1
has title: How to select all instances of a widget in tkinter?
favorite count: 0
has body: So does anyone know of a way to 'get' all Labels, for example from a program or window in Tk. i.e like root.winfo.children but only for a type of widget. Also I know you can use lists, but i want to know if there is a better way?
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
downvote count: 1
type: Question

http://stackoverflow.com/q/52516237
tagged with: python
has comment: http://stackoverflow.com/comment/91972098
duplicate of: http://stackoverflow.com/q/1301346
linked to: http://stackoverflow.com/q/7456807
has title: What is good practice way of data hiding in python?
has comment: http://stackoverflow.com/comment/91972476
downvote count: 1
type: Question
score: -1
linked to: http://stackoverflow.com/q/70528
linked to: http://stackoverflow.com/q/15047122
has body: What is good practice way of data hiding in python ? Is it the same as java ? private is with double underscore ? protected is with single underscore ? public function is possible, member public is not recommended ? Right ?
has answer: http://stackoverflow.com/a/52516302
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91972059
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91972064

http://stackoverflow.com/a/52557551
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92315156
type: Answer
has body: Is it possible to have repetitive GUI elements generated by a function, and if so, is that a lambda function? Yes, it's possible to create gui elements with a function, and no, it's not a lambda function. Not only is it possible, it's arguably a best practice to create gui elements in a function, though you could also just use a simple loop or a conventional function. When creating groups of widgets that are somehow tied together, it's even better to create a custom class that can encapsulate all of the behavior and provide a simple interface for the rest of the program. Example In the following example, we want to create a series of widgets with a label, an entry, and a submit button. It is going to be implemented as a class, since we are in effect creating an object that represents one form field. Note: the following code assumes you imported tkinter with import tkinter as tk. First, lets create a callback that sets a value in a dictionary, and also prints out the value for debugging purposes. The callback will be given the name of the field, and the value that the user entered: data = {} def handle_submit(name, value): print("you submitted '%s' for %s" % (value, name)) data[name] = value Next, the code to create 10 items would might look like this: root = tk.Tk() for i in range(1, 11): field_name = "field %s" % i row = CustomWidget(root, name=field_name, callback=handle_submit) Finally, we need to create our class. We inherit from tk.Frame so that we can use it like any other tkinter widget. It needs to take parameters for its parent, the field name, and the function to call when the user presses submit: class CustomWidget(tk.Frame): def __init__(self, parent, name, callback): tk.Frame.__init__(self, parent) self.name = name label_text = name.title() + ":" self.callback = callback self.label = tk.Label(self, text=label_text, anchor="e") self.entry = tk.Entry(self) self.button = tk.Button(self, text="Submit", command=self.submit) self.button.pack(side="right") sel…
upvote count: 2
has comment: http://stackoverflow.com/comment/92315304
has comment: http://stackoverflow.com/comment/92315324
has comment: http://stackoverflow.com/comment/92059615
has comment: http://stackoverflow.com/comment/92315292
answers question: http://stackoverflow.com/q/52556781
accepted answer of: http://stackoverflow.com/q/52556781
score: 2
has comment: http://stackoverflow.com/comment/92315243

http://stackoverflow.com/comment/91858353
type: Comment
has text: Yes from webpage I am able to use it. Let me clean it completely
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52456197

http://stackoverflow.com/comment/91988758
comment on: http://stackoverflow.com/q/52516043
has text: Just a random idea. Use existing contour line code: https://stackoverflow.com/a/18309914/7207392
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52540693
type: Question
has comment: http://stackoverflow.com/comment/108259628
has comment: http://stackoverflow.com/comment/92023697
has comment: http://stackoverflow.com/comment/108244180
has comment: http://stackoverflow.com/comment/108069101
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/108293928
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/108288216
has answer: http://stackoverflow.com/a/71488566
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92021556
has title: When is it acceptable to use features from a later minor version update of python in a setup.py script?
upvote count: 2
has comment: http://stackoverflow.com/comment/92021632
tagged with: python
has comment: http://stackoverflow.com/comment/108069237
has comment: http://stackoverflow.com/comment/92230637
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92021603
tagged with: f-string
tagged with: setuptools
has body: Original question title: Should we use python 3.6 features in setup.py? I've created a setup.py for a private library installer which depends on python 3.6. I attempted to make the file a little more friendly for anyone trying to install it on python versions prior and realized I had a major flaw in my thinking. I'm using f-strings in the setup.py which only work in >=3.6! Anyone trying to run the setup.py in a previous version of python won't even get to the first line of code which checks the interpreter version. So this got me thinking about guidelines for creating a setup.py file and what other syntactical limitations might exist which would prevent setup.py from running properly in multiple environments. #!/usr/bin/env python3 """ PIP Install script for XXXXXX packages """ import sys if sys.version_info &lt; (3,6): sys.exit('Sorry, Python &lt; 3.6 is not supported') from setuptools import setup NAME = 'abcutil' AUTHOR = 'XXXXXXXXXX' CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers Programming Language :: Python Programming Language :: Python :: 3 Topic :: Software Development Operating System :: Microsoft :: Windows Operating System :: Unix Operating System :: MacOS """ MAJOR = 1 MINOR = 1 MICRO = 0 ISRELEASED = False VERSION = f'{MAJOR}.{MINOR}.{MICRO}' setup(name = NAME, maintainer = AUTHOR, version=VERSION, maintainer_email = 'XXXXXXX', description='XXXXXXX utility packages', author = AUTHOR, download_url = 'https://gitlabXXXXXXXX/XXXXXXX', license = 'BSD', classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], python_requires="&gt;=3.6", packages=[NAME, f"{NAME}.selenium", f"{NAME}.regression_helpers"], install_requires = ['selenium==3.9', 'requests&gt;=2.18.4', 'python-dateutil', 'pytz'], dependency_links=[''] ) Running the above will give you this: $ python setup.py File "setup.py", line 30 VERSION = f'{MAJOR}.{MINOR}.{MICRO}' ^ SyntaxError: invalid syntax My question is What is recommended for setup.py whe…
accepted answer: http://stackoverflow.com/a/71488566
has comment: http://stackoverflow.com/comment/108296133
has comment: http://stackoverflow.com/comment/92169832

http://stackoverflow.com/q/52448103
has comment: http://stackoverflow.com/comment/91843267
has comment: http://stackoverflow.com/comment/91839903
favorite count: 0
has answer: http://stackoverflow.com/a/52451323
tagged with: python
has answer: http://stackoverflow.com/a/52449999
has comment: http://stackoverflow.com/comment/91840208
possible better answer: http://stackoverflow.com/a/52449999
has comment: http://stackoverflow.com/comment/91839325
upvote count: 1
accepted answer: http://stackoverflow.com/a/52451323
has title: Creating waterfall/stacked line plot in Matpotlib using transforms
downvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91843098
tagged with: matplotlib
has body: I'm trying to plot a series of waveforms such that they are distributed equally along the y-axis. I believe that matplotlib.transforms is the way to go. I have something rudimentary working using this code: import matplotlib.transforms import matplotlib as mp import numpy as np import pylab as pl %matplotlib inline ax = pl.gca() n_levels = 10 t = np.arange(1000)/1000 offset_step = 1/(n_levels + 1) for i in range(n_levels): offset = offset_step * (i + 1) o = mp.transforms.ScaledTranslation(0, offset, ax.transAxes) trans = mp.transforms.blended_transform_factory(ax.transData, ax.transData + o) y = np.sin(t*2*np.pi*10*i) p, = ax.plot(t, y, 'k-', transform=trans) ax.axis(ymin=0, ymax=25) This creates the following plot. Even thought the actual offsets, in axes coordinates, are 0.09 0.18 ... 0.82 0.91, the lines clearly are not appearing at those exact offsets! What am I doing wrong? Edit: To answer some of the questions regarding why I can't just apply the offset in data-space rather than using an transform. This is a simpler form of a more complex transform I need to do where I want to be able to scale the amplitude of individual lines without having to adjust the y-axes limits. To do this, the actual y-transform is: boxin = mp.transforms.Bbox([[0, 0], [1, 1]]) boxout = mp.transforms.Bbox([[0, 0], [1, 1]]) y_trans = mp.transforms.BboxTransform(boxin, boxout) + \ axes.transData + \ mp.transforms.ScaledTranslation(0, offset_step * (i + 1), axes.transAxes) Then, in my interactive application, I can modify the scaling of each individual waveform using: scale = 2 box = np.array([[0, 0], [scale, scale]]) boxout.set_points(box) figure.canvas.redraw() It works really well. However, for varying choices of n_levels, I need to initially adjust ymin and ymax when generating the plot to ensure the lines are spaced equally along the y-axis. The desired result is:
has comment: http://stackoverflow.com/comment/91839153
has comment: http://stackoverflow.com/comment/91840583
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91839895

http://stackoverflow.com/q/52475303
upvote count: 4
has title: Sharing database relations across micro-services with Django rest framework
type: AnsweredQuestion
downvote count: 0
has body: I have two django REST API projects which I have decoupled them into micro services architecture, one of the services is an (SSO) that handles authentication (I'm using JWT token based authentication) and manage Users info and the other is a payroll service. The problem is the user has a relation to some model in payroll service. To be specific I have an Employee class in payroll service which has a user_id field. This is where I will add a user UUID which I will get from querying the SSO service. How do I share database across micro-services taking into consideration each service has its own database.
tagged with: django
type: Question
tagged with: database
has comment: http://stackoverflow.com/comment/91921173
score: 4
has comment: http://stackoverflow.com/comment/91920607
answer count: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: microservices
has answer: http://stackoverflow.com/a/52490138
accepted answer: http://stackoverflow.com/a/52490138
tagged with: python

http://stackoverflow.com/comment/92050912
comment on: http://stackoverflow.com/a/52556099
score: 2
has text: @FarzinNasiri No! `map` applies the same function to *every* element in an iterable; you don't want to do that.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52570620
answers question: http://stackoverflow.com/q/52570401
has comment: http://stackoverflow.com/comment/92077936
has comment: http://stackoverflow.com/comment/92081327
score: 1
downvote count: 0
has body: Can you try adding this to your code? This should bypass ssl verification. import ssl ssl._create_default_https_context = ssl._create_unverified_context
type: Answer
upvote count: 1

http://stackoverflow.com/q/52569810
has title: Pandas: Aggregate rows based on index labels vs. columns labels condition
has answer: http://stackoverflow.com/a/52571567
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52571567
has answer: http://stackoverflow.com/a/52570071
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52570071
score: -1
has body: I have a (400,328) dataframe which structure looks like this: row_idx = pd.MultiIndex.from_product([['EU', 'ROW'], ['p01.a', 'p01.b', 'p02.1.a', 'p02.1.b', 'p02.1.c', 'p03']], names=['Region', 'Prod_code']) col_idx = pd.MultiIndex.from_product([['EU', 'ROW'], ['i01.a', 'i01.b', 'i02.1.a', 'i03']], names=['Region', 'Ind_code']) df_in = pd.DataFrame(np.random.randint(1,10,(12,8)), index=row_idx, columns=col_idx) print(df) Region EU ROW Ind_code i01.a i01.b i02.1.a i03 i01.a i01.b i02.1.a i03 Region Prod_code EU p01.a 1 9 7 4 2 1 6 7 p01.b 1 5 1 7 2 4 2 2 p02.1.a 1 1 2 8 8 4 4 7 p02.1.b 7 7 7 5 6 7 1 3 p02.1.c 4 2 4 4 6 4 3 8 p03 7 2 9 8 8 8 4 3 ROW p01.a 4 4 5 5 5 1 6 2 p01.b 5 2 3 4 9 4 9 6 p02.1.a 4 4 8 8 4 7 6 6 p02.1.b 7 9 3 2 1 5 4 1 p02.1.c 4 2 1 2 9 8 8 5 p03 6 7 6 6 6 9 7 5 I need to obtain a symmetric Dataframe (328,328) by summing all rows for which the respective Prod_code has no correspondence to Ind_code (ignoring the initial letters "i" and "p"). The "extra" rows - in this case ('..', 'p02.1.b') and ('..', 'p02.1.c') - should be summed to the first row with a corresponded parent code - in this case ('..', 'p02.1.a'), like below. #Desired output print(df_out) Region EU ROW Ind_code i01.a i01.b i02.1.a i03 i01.a i01.b i02.1.a i03 Region Prod_code EU p01.a 1 9 7 4 2 1 6 7 p01.b 1 5 1 7 2 4 2 2 p02.1.a 12 11 13 17 20 15 8 18 p03 7 2 9 8 8 8 4 3 ROW p01.a 4 4 5 5 5 1 6 2 p01.b 5 2 3 4 9 4 9 6 p02.1.a 15 15 12 12 14 20 18 12 p03 6 7 6 6 6 9 7 5 How can I do this in an elegant "Pythonic" way?
answer count: 2
tagged with: pandas
upvote count: 0

http://stackoverflow.com/q/52444502
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52445103
upvote count: 3
answer count: 1
tagged with: netcdf4
has title: num2date does not support 'months since...'
has body: Hello i have a neetcdf4 file with monthly precipitation data for over 10 years. what i am trying to do is : read the file select a subset area based on longitude latitude i need to calculate the moving average per 3 years plot the results dataset = Dataset('test.nc','r',format='NETCDF4') lons = dataset.variables['lon'][:] lats = dataset.variables['lat'][:] times = dataset.variables['time'][:] times_units = dataset.variables['time'].units prep_solide = dataset.variables['PREC'][:,:,:] prec_units =dataset.variables['PREC'].units dates = num2date(times[:],' months since 1801-01-01 00:00:00') The error i keep getting is ValueError: unsupported time units is there any other way to fix this error ?
has answer: http://stackoverflow.com/a/52445103
type: AnsweredQuestion
score: 3
downvote count: 0

http://stackoverflow.com/a/52533501
score: 4
answers question: http://stackoverflow.com/q/52532460
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: No, there is no direct method to retrieve the exact state of a WebElement through Selenium. find_element_by_xpath(xpath) find_element_by_xpath() would simply find the first matching WebElement using the xpath. If no matching element is found it will raise NoSuchElementException But Selenium offers multiple methods to validate the state of a WebElement as follows: is_displayed(): Returns a Boolean value (true / false) whether the element is visible to a user or not. is_enabled(): Returns a Boolean value (true / false) whether the element is enabled or not. is_selected(): Returns a Boolean value (true / false) whether the element is selected or not. WebDriverWait() in-conjunction with expected_conditions class The canned expected_conditions are generally useful to access the elements when they achieves a definite state as follows: presence_of_element_located(locator) mentions : class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator) An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. visibility_of_element_located(locator) mentions : class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator) An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element_to_be_clickable(locator) mentions: class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator) An Expectation for checking an element is visible and enabled such that you can click it.
type: Answer
accepted answer of: http://stackoverflow.com/q/52532460

http://stackoverflow.com/q/52583613
answer count: 2
tagged with: django-queryset
has body: I have the following models class Client(models.Model): ... class Request(models.Model): ... client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) completed = models.BooleanField() I want to get the count of all completed requests for a queryset of clients. The following statement gets me all the requests, but it does not check for whether the request is completed. clients = Client.objects.filter(...).annotate(Count('request')) What I want is this: clients = Client.objects.filter(...).annotate(Count(request__completed=True)) How do I achieve this?
has comment: http://stackoverflow.com/comment/92102885
favorite count: 0
has comment: http://stackoverflow.com/comment/92102696
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92102351
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52584591
score: 1
has comment: http://stackoverflow.com/comment/92102845
upvote count: 1
has comment: http://stackoverflow.com/comment/92102546
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/92127132
has answer: http://stackoverflow.com/a/52584664
has title: Django - Is it possible to do a queryset within Count()
has comment: http://stackoverflow.com/comment/92106081

http://stackoverflow.com/comment/91923442
has text: and if i want to do this just for the 0th element?
comment on: http://stackoverflow.com/q/52491417
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91981832
comment on: http://stackoverflow.com/a/52520580
type: AnswerComment
score: 0
has text: @Mark ... try nesting `for` loop INSIDE `with()`.
type: Comment

http://stackoverflow.com/comment/92016637
type: AnswerComment
comment on: http://stackoverflow.com/a/52538237
score: 0
type: Comment
has text: how would one then plot a function of three variables with this method? I.e., mat(z)=z**2*(np.cos(x)*np.cos(y)) with again the x and ys being from 1 to 5? would one have to use the symbol package on python then define a function?

http://stackoverflow.com/a/69838644
has body: In order to debug Django commands in a Docker Container you can create a new Run/Debug Configuration with following setup: Use a Python configuration template Script path: absolut location of manage.py Parameters: the Django command you want to debug/execute !important! Python interpreter: Docker Compose interpreter
type: Answer
answers question: http://stackoverflow.com/q/52462866
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/91919992
has text: @Hamms that is 1 dictionary, here I have dictionary inside dictionary
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52489440
score: 0

http://stackoverflow.com/q/52572679
has answer: http://stackoverflow.com/a/52574968
has body: I'm using postgres with SQLAlchemy. I want to create Profile objects and have them autogenerate a GUID. However currently my profile IDs don't store any values, e.g: profile = Profile(name='some_profile') -&gt; print(profile.name) some_profile -&gt; print(profile.id) None I've looked into how others are implementing GUIDs into their models (How can I use UUIDs in SQLAlchemy?) I understand that many people don't recommend using GUIDs as IDs, but I would like to know where I'm going wrong despite this. Here's my current implementation: from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String from sqlalchemy.types import TypeDecorator, CHAR import uuid Base = declarative_base() class GUID(TypeDecorator): """Platform-independent GUID type. Uses Postgresql's UUID type, otherwise uses CHAR(32), storing as stringified hex values. """ impl = CHAR def process_bind_param(self, value, dialect): if value is None: return value elif dialect.name == 'postgresql': return str(value) else: if not isinstance(value, uuid.UUID): return "%.32x" % uuid.UUID(value).int else: # hexstring return "%.32x" % value.int def process_result_value(self, value, dialect): if value is None: return value else: if not isinstance(value, uuid.UUID): value = uuid.UUID(value) return value class Profile(Base): __tablename__ = 'profile' id = Column(GUID(), primary_key=True, default=uuid.uuid4) name = Column(String) I'm still a beginner to python, but as far as I understand I'm declaring the type of my Profile id column as a GUID (setup by the GUID class). A default GUID value should therefore be successfully stored when generated in that column through uuid.uuid4(). My guess is that there isn't anything wrong with the GUID class, but instead in how I'm trying to generate the default value within the id column. Any help would be appreciated!
linked to: http://stackoverflow.com/q/183042
tagged with: postgresql
has title: Generate GUID when creating model object using SQLAlchemy (Python)
answer count: 1
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52574968
tagged with: guid
downvote count: 0
tagged with: uuid
tagged with: sqlalchemy
type: Question
upvote count: 2

http://stackoverflow.com/q/52577950
has comment: http://stackoverflow.com/comment/92095769
score: 0
has comment: http://stackoverflow.com/comment/92294677
has answer: http://stackoverflow.com/a/52700757
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: django
has title: Need help troubleshooting Google App Engine job that worked in dev but not production
tagged with: python
has comment: http://stackoverflow.com/comment/92135182
has comment: http://stackoverflow.com/comment/92301684
type: Question
has body: I have been working on a website for over a year now, using Django and Python3 primarily. A few of my buddies and I built a front end where a user enters some parameters and submits, this goes to the GAE to run the job and return the results. In my local dev environment, everything works well. I have two separate dev environments. One builds the entire service up in a docker container. This produces the desired results in roughly 11 seconds. The other environment runs the source files locally on my computer and connects to the Postgres database hosted in Google Cloud. The Python application runs locally. It takes roughly 2 minutes for it to run locally, a lot of latency between the cloud and the post/gets from my local machine. Once I perform the Gcloud app deploy and attempt to run in production, it never finishes. I have some print statements built into the code, I know it gets to the part where the submitted parameters go to the Python code. I monitor via this command on my local computer: gcloud app logs read. I suspect that since my local computer is a beast (i7-7770 processor with 64 GB of RAM), it runs the whole thing no problem. But in the GAE, I don't think it's providing the proper machines to do the job efficiently (not enough compute, not enough RAM). That's my guess. So, I need help in how to troubleshoot this. I tried changing my app.yaml file so that resources would scale to 16 GB of memory, but it would never deploy. I received an error 13. One other note, after it spins around trying to run the job for 60 minutes, the website crashes and displays this message: 502 Server Error Error: Server Error The server encountered a temporary error and could not complete your request. Please try again in 30 seconds.
answer count: 1
has comment: http://stackoverflow.com/comment/92146089

http://stackoverflow.com/q/52518636
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91977526
has comment: http://stackoverflow.com/comment/91977350
tagged with: python-3.x
has body: When i use my skip command, my program stops playing music, instead of skipping a song. Here's the code: queues = {} players = {} opts = { 'default_search': 'auto', 'quiet': True, } voice_states = {} class voice: def __init__(self, client): self.client = client @commands.command(pass_context=True) async def skip(self, ctx): id = ctx.message.server.id players[id].stop() @commands.command( pass_context=True ) async def play(self, ctx, url): server = ctx.message.server channel = ctx.message.author.voice.voice_channel try: await self.client.join_voice_channel(channel) except: print(" ") if server.id not in players or players[server.id].is_done(): server = ctx.message.server voice_client = self.client.voice_client_in(server) player = await voice_client.create_ytdl_player(url, after=lambda: queue(server.id), ytdl_options=opts) players[server.id] = player await self.client.say('Now Playing ' ) player.start() else: server = ctx.message.server voice_client = self.client.voice_client_in(server) player = await voice_client.create_ytdl_player(url, after=lambda: queue(server.id), ytdl_options=opts) if server.id in queues: queues[server.id].append(player) else: queues[server.id] = [player] await self.client.say('Now Playing ' ) await self.client.say('Video queued.') def queue(self, id): if queues[id] != []: player = queues[id].pop(0) players[id] = player player.start() def setup(client): client.add_cog(voice(client)) i receive no error codes, just no queue. Fixes to my code or own solutions are appreciated. Sorry, for long code, but you need all the context
answer count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91977565
has comment: http://stackoverflow.com/comment/91978198
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91986618
tagged with: discord.py
has title: music bot stopping music entirely instead of skipping one song discord.py
has comment: http://stackoverflow.com/comment/91978078
has comment: http://stackoverflow.com/comment/91977743
type: Question
has comment: http://stackoverflow.com/comment/91977594
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/91977599
score: 0
has comment: http://stackoverflow.com/comment/92025578

http://stackoverflow.com/q/52462472
score: 1
tagged with: netcdf
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52473988
accepted answer: http://stackoverflow.com/a/52473988
has answer: http://stackoverflow.com/a/63940760
possible better answer: http://stackoverflow.com/a/52466672
tagged with: python-2.7
answer count: 3
downvote count: 0
favorite count: 0
has body: I need to calculate monthly, seasonal and annualy anomalies of air temperature of netcdf monthly files of 44 years with some function that allows me to obtain anomalies in the period on a monthly, seasonal and annualy automatically and save the results in a folder. I only know how to do It for one year and not for several years with a function. from netCDF4 import Dataset, num2date import xarray as xr import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeat import matplotlib.pyplot as plt import numpy as np import pandas as pd from mpl_toolkits.basemap import Basemap ds = Dataset('./interim_t2m_19792017.nc') lats = ds.variables['latitude'][:] # extract/copy the data lons = ds.variables['longitude'][:] time = ds.variables['time'] var = ds.variables['t2m'] lon, lat = np.meshgrid(lons, lats) dates = num2date(time[:], time.units) dates_pd = pd.to_datetime(dates) periods = dates_pd.to_period(freq='M') def plt_map(data): m = Basemap(projection='mill',llcrnrlat=-80,urcrnrlat=80,\ llcrnrlon=0,urcrnrlon=360,lat_ts=20,resolution='c') x, y = m(lon, lat) plt.figure(figsize=(10,7)) m.drawcoastlines() m.drawparallels(np.arange(-80.,81.,20.)) m.drawmeridians(np.arange(-180.,181.,20.)) m.drawmapboundary(fill_color='white') m.contourf(x,y,data, extend="both",cmap="jet"); plt.colorbar(orientation='horizontal', pad=0.05) plt_map(var[0,:,:]) mask_2016 = periods.year==2016 data = var[mask_2016,:,:].mean(axis=0) plt_map(data)
has comment: http://stackoverflow.com/comment/91874505
tagged with: python
has answer: http://stackoverflow.com/a/52466672
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91873810
has title: Calculate yearly anomalies for several years on netcdf files in python

http://stackoverflow.com/q/52480524
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52480583
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
has answer: http://stackoverflow.com/a/52480578
score: 1
upvote count: 1
type: Question
has title: Appending an empty list with list in recursive function
has body: def permute(nums): result = [] get_permute([], nums, result) return result def get_permute(current, num, result): if not num: result.append(current+[]) for i, v in enumerate(num): current.append(num[i]) get_permute(current, num[:i] + num[i + 1:], result) current.pop() if __name__ == "__main__": r = permute([1,2,3]) for perm in r: print(perm) What does current + [] do in result.append(current+[]) if I remove +[] it printing blank lists.
answer count: 2
linked to: http://stackoverflow.com/q/2612802

http://stackoverflow.com/q/52503156
has comment: http://stackoverflow.com/comment/91947244
type: Question
has title: Adding href link to image attachment while sending email through python smtplib
score: 0
tagged with: mime
tagged with: email
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91947169
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91946996
has body: I'm sending images as attachments using smtplib, and attaching them as email.mime.base.MIMEBase objects. These images show up inline with the email body. I want these images to be clickable. Is it possible to add hrefs to each of these images? Here's the code for attaching the image: msg = MIMEMultipart() msg['From'] = email_username msg['To'] = ", ".join(destination_list) msg['Subject'] = "Subject goes here" message_body = "Message body" msg.attach(MIMEText(message_body, 'html')) part = MIMEBase('application', 'octet-stream') part.set_payload(open('attachment.png','rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition') msg.attach(part)
tagged with: smtplib
tagged with: attachment

http://stackoverflow.com/q/52451407
score: 1
has body: I would like to update a larger DataFrame, using a smaller one. They have the same columns, but the larger DataFrame contains many more rows than the smaller DataFrame. It is for updating hockey stats, updating the DataFrame containing all NHL players with a DataFrame containing stats from a single game, both indexed by players' names, as below: In [95]: total_stats Out[95]: G A Chris Chelios 1 1 Zdeno Chara 2 2 Viktor Kozlov 3 3 Adam Oates 4 4 Wes Waltz 5 5 In [97]: game_stats Out[97]: G A Chris Chelios 1 1 Zdeno Chara 0 0 I want to update the total_stats df (but not using df.update() or df.add() as it fills any non-overlapping rows with NaN) with the stats in the game_stats df, so that it looks like: In [95]: total_stats Out[95]: G A Chris Chelios 2 2 Zdeno Chara 2 2 Viktor Kozlov 3 3 Adam Oates 4 4 Wes Waltz 5 5 I've looked extensively online and while this seems like a fairly simple procedure, I'm having a rough time finding an answer Thank you!
type: Question
has title: Adding values of differently-sized pandas DataFrames
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91846212
has answer: http://stackoverflow.com/a/52451473
accepted answer: http://stackoverflow.com/a/52451473
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/52526917
has comment: http://stackoverflow.com/comment/92062493
has comment: http://stackoverflow.com/comment/92028535
has comment: http://stackoverflow.com/comment/92028288
has comment: http://stackoverflow.com/comment/92039102
score: 0
type: Answer
has body: Maybe the element you're trying to reach has not loaded properly. Try adding a wait statement, something along the lines of from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By ... browser = webdriver.Chrome() browser.get(url) #url was defined before browser.find_element_by_css_selector("#hamburger-btn").click() browser.find_element_by_css_selector("div.menu-item.menu-item-selected&gt;span.menu-item-title").click() WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'div.menu-item.menu-item-selected&gt;div.menu-panel-content&gt;div.menu-category-cont&gt;div.menu-category-sub&gt;div.menu-category-sub-item.menu-category-sub-item-selected&gt;span.menu-category-sub-item-title'))) browser.find_element_by_css_selector('div.menu-item.menu-item-selected&gt;div.menu-panel-content&gt;div.menu-category-cont&gt;div.menu-category-sub&gt;div.menu-category-sub-item.menu-category-sub-item-selected&gt;span.menu-category-sub-item-title').click() This is considering this element in fact exists in you page and you're correctly addressing it with your css selector.
answers question: http://stackoverflow.com/q/52526404
has comment: http://stackoverflow.com/comment/92049995

http://stackoverflow.com/comment/101121629
type: QuestionComment
has text: Did you find any solution to this? I am struggling with a similar issue https://stackoverflow.com/q/57307107/9318372
comment on: http://stackoverflow.com/q/52548643
score: 0
type: Comment

http://stackoverflow.com/q/52569579
accepted answer: http://stackoverflow.com/a/52569700
type: AnsweredQuestion
type: Question
score: 2
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52569700
tagged with: python-2.7
tagged with: python
has body: Is it possible to override a property in a base class by a regular attribute in a derived class, something like this: class A(object): @property def x(self): return self._x @x.setter def x(self, y): self._x = y class B(A): def __init__(self, y): self.x = y #the descriptor methods are not called and #"x" is a regular attribute in the object dict. The reason I am asking is because I have a complex base class in which one of the descriptor attributes typically performs a complicated calculation. However, in one of the derived classes, the returned value is trivial and it seems like a waste to have to override with another descriptor and not just a regular storage attribute.
upvote count: 2
has title: Overriding a descriptor with a regular attribute

http://stackoverflow.com/comment/91974356
has text: If I understand correctly, you are trying to automate some processing. Open a program if a particular file is written inside a folder. Right?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52515810

http://stackoverflow.com/comment/92103649
has text: your iteration doesn't doing calculation for products that are not purchased, number off elements in `d` must be same with number of `Product`. Althought is multiplied by zero, it must be included in the dictionary
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52583988
type: Comment

http://stackoverflow.com/comment/92037809
type: Comment
has text: Please post your view and template.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52532684

http://stackoverflow.com/a/52543348
type: AcceptedAnswer
type: Answer
has body: I'm interpreting this question as "why does my program always display 'Decrypted text is Couldnt find', even though I can see the decrypted text in the earlier output?". There are three reasons. First, you initialize cipher and dec_test with a space: cipher = ' ' #... dec_text = ' ' When you should instead initialize them with empty strings. If you don't do this, then all of your decrypted strings will have two spaces at the beginning, and they'll never compare equal to your original message. cipher = '' #... dec_text = '' Additionally, this conditional: if (dec_text == msg): word = dec_text else: word = 'Couldnt find' Appears outside of the for key in range(len(alphabets)) loop. This means that it executes exactly once, when dec_text has whatever value it was given during the 51st iteration of the loop. If you want to compare msg against all the different values that dec_text has, then you need to compare within the loop. word = 'Couldnt find' for key in range(len(alphabets)): dec_text = '' for alphas in decrypt: if alphas in alphabets: sol_dec = alphabets.find(alphas) sol_dec = sol_dec - key if sol_dec &lt; 0: sol_dec = sol_dec + len(alphabets) dec_text = dec_text + alphabets[sol_dec] else: dec_text = dec_text + alphas print('key {} {}'.format(key, dec_text)) if (dec_text == msg): word = dec_text Note that I've completely removed the else block, instead unconditionally initializing word to "Couldnt find" at the beginning. Simply adding the else alongside the if inside the loop wouldn't have worked, because there's nothing stopping "Couldnt find" from overwriting word even after it had attained a value in an earlier iteration. This means you would always get "Couldnt find" unless the decrypted text was found in the very last iteration. Having only the if without the else solves this issue. Finally, you may want to compare the decrypted text to the original text in a case-insensitive way. Otherwise, you can only match messages that are in all-caps. if (dec_text == m…
accepted answer of: http://stackoverflow.com/q/52542885
answers question: http://stackoverflow.com/q/52542885
has comment: http://stackoverflow.com/comment/92031376
score: 0

http://stackoverflow.com/q/52513455
favorite count: 0
has answer: http://stackoverflow.com/a/52513864
tagged with: python
accepted answer: http://stackoverflow.com/a/52513864
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46942587
has body: I'm looking to create category-specific columns based the corresponding category for some of the columns. I've accomplished this in a round-about way by (1) slicing the 2 categories into two separate dataframes, (2) merging the two dataframes on the date (3) deleting redundant columns (4) creating new columns (category agnostic) (4) delete category specific columns. Do you know of a more efficient way to do this transfomration? My code is below the example input/output Input: wk start car rims color Autopilot$ Sunroof$ 0 2018-09-09 tesla model x 17 black 3000 0 1 2018-09-16 tesla model x 14 yellow 3000 0 2 2018-09-23 tesla model x 13 white 3000 0 3 2018-09-09 tesla model 3 19 grey 0 2000 4 2018-09-16 tesla model 3 21 pink 0 2000 Ideal Output: wk rims-mod3 rims-modx color-mod3 color-modx Auto$ roof$ 0 2018-09-09 17 0 black grey 3000 2000 1 2018-09-16 14 19 yellow pink 3000 2000 2 2018-09-23 13 21 white NaN 3000 0 My code: import pandas as pd df = pd.DataFrame({'wk start': ['2018-09-09', '2018-09-16', '2018-09-23','2018-09-09', '2018-09-16'], 'car': [ 'tesla model x', 'tesla model x', 'tesla model x','tesla model 3','tesla model 3'], 'rims': [17,14,13,19,21], 'color':['black','yellow','white','grey','pink'], 'Autopilot$':[3000,3000, 3000,0,0], 'Sunroof$':[0,0,0,2000,2000]}) model3 = df[df['car']=='tesla model 3'] modelx = df[df['car']=='tesla model x'] example = model3.merge(modelx, how='outer',left_on='wk start',right_on='wk start',suffixes=('_model3', '_modelx')) del example['car_model3'] del example['car_modelx'] example['AUTOPILOT']=example['Autopilot$_model3']+example['Autopilot$_modelx'] example['SUNROOF']=example['Sunroof$_model3']+example['Sunroof$_modelx'] del example['Autopilot$_model3'] del example['Autopilot$_modelx'] del example['Sunroof$_modelx'] del example['Sunroof$_model3'] Other resources used are question1, question2
score: 1
linked to: http://stackoverflow.com/q/48667118
type: Question
has title: Add category specific columns and values to dataframe
tagged with: dataframe
tagged with: pandas
upvote count: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/91927122
type: Comment
type: QuestionComment
has text: The encoding of your Python script and the encoding used by I/O functions such as `read()` or `input()` are two completely different and unrelated things.
score: 0
comment on: http://stackoverflow.com/q/52493202

http://stackoverflow.com/q/52493104
has comment: http://stackoverflow.com/comment/91929661
has title: Returning multiple values from Python Dict with range of datetime
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52494537
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/52494537
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91927137
favorite count: 0
has body: I'm running into a problem with using DateTime as a dict key. My goal is to bring in information from one data source that includes Datetime, and then look up in a dictionary and return all values for keys that are within 2 days +- of the input DateTime. For example, my input would be: datetime.datetime(2018, 9, 20, 12, 48) My dictionary to reference would be: example = {datetime.datetime(2018, 9, 20, 14, 43):'A', datetime.datetime(2018, 9, 18, 19, 41):'B', datetime.datetime(2018, 9, 15, 9, 12):'C'} In that case, I would return: A, B I have considered sorting the dictionary and then creating a dictionary of indexes maybe for odd-numbered dates, then taking in my input date, figuring the base date +- 2 of the input date, referencing the index dict, and then using those indexes to loop through the reference dict only between the indexes and return all values that are there. My main issue is that I can't predict what the dict datetimes will be or the input datetimes so I'm just not certain if I can return values for a range of keys in a dict other than by looping through the index of the keys in a sorted order. Doing a for loop for all keys is not efficient here because of the number of keys to look through -- I am already reducing this list by deduplicating down as much as possible and only bringing in the minimum amount of reference data. One other item is that my inputs will be 100,000s of datetimes to look up, many of which will be minutes, seconds, or hours off from each other, so reducing the number of lookups and for looping will be essential to keep the runtime down. I apologize if this isn't quite a proper question with full code to look at but I basically am not sure where to start on this issue, so I didn't think it would help anyone to put anything else in except for example input and dictionary with output goal.
has comment: http://stackoverflow.com/comment/91927764
tagged with: datetime
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/91827465
score: 0
has text: just make new tuple for the both. or use `zip`
comment on: http://stackoverflow.com/q/52442388
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91873075
type: QuestionComment
has text: In the future, could you please paste error messages into code blocks, rather than as a quote. This way, the lines of the message will be separated, making it much easier to read.
type: Comment
comment on: http://stackoverflow.com/q/52465658
score: 0

http://stackoverflow.com/q/52448236
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Scrape Standard Deviation from Yahoo Finance using Beautiful Soup
has answer: http://stackoverflow.com/a/52449408
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/52448713
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/17585787
favorite count: 0
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/52448713
accepted answer: http://stackoverflow.com/a/52449408
has body: I'm trying to scrape some numbers from the Risk Statistics table on a yahoo finance webpage using BeautifulSoup and Python 2.7: https://finance.yahoo.com/quote/SHSAX/risk So far, I've looked at the html using https://codebeautify.org: #!/usr/bin/python from bs4 import BeautifulSoup, Comment import urllib riskURL = "https://finance.yahoo.com/quote/SHSAX/risk" page = urllib.urlopen(riskURL) content = page.read().decode('utf-8') soup = BeautifulSoup(content, 'html.parser') My trouble is actually getting the numbers using soup.find. For example, standard deviation: # std should be 13.44 stdevValue = float(soup.find("span",{"data-reactid":"124","class":"W(39%) Fl(start)"}).text) # std of category should be 0.18 stdevCat = float(soup.find("span",{"data-reactid":"125","class":"W(57%) Mend(5px) Fl(end)"}).text) Both of these calls to soup.find return none. What am I missing?
tagged with: python

http://stackoverflow.com/comment/92083471
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52573623
has text: @coldspeed Would the for loop only change the element l[1]?

http://stackoverflow.com/comment/91929042
score: 2
type: AnswerComment
type: Comment
has text: This treats `p1 = None` the same of course, possibly what is wanted (or irrelevant) but worth noting perhaps
comment on: http://stackoverflow.com/a/52494213

http://stackoverflow.com/a/52517050
has comment: http://stackoverflow.com/comment/91973709
downvote count: 0
has comment: http://stackoverflow.com/comment/91973633
type: Answer
has comment: http://stackoverflow.com/comment/91973700
upvote count: 1
has body: For this relation, "User has many Feedbacks", the Feedback class should have stored the User it corresponds to instead of the reverse which you have now. Then you can fetch a list (queryset) of Feedbacks which contain a specific user using: Feedback.objects.filter(user=user_you_want) Where "user_you_want" is an object of User class
score: 1
answers question: http://stackoverflow.com/q/52516937

http://stackoverflow.com/comment/91815045
comment on: http://stackoverflow.com/q/52435815
has text: `sort_values` should work. Can you show exactly how you're doing it and explain *why* it is not working? (e.g. returns an error?)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52517516
has title: PyQt5 Fixed Window Size
tagged with: pyqt5
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52517831
accepted answer: http://stackoverflow.com/a/52517831
score: 7
possible better answer: http://stackoverflow.com/a/59803134
upvote count: 8
has answer: http://stackoverflow.com/a/59803134
type: Question
answer count: 2
tagged with: pyqt
downvote count: 1
has body: I am trying to set my window / QDialog to not be resizable. I found the following example self.setFixedSize(self.size()) I'm not sure how to implement this. I can put it in the .py file generated from Qt Designer or explicitly using: QtWidgets.QDialog().setFixedSize(self.size()) without errors but it's not working. Thanks.
favorite count: 0
tagged with: qt-designer
tagged with: python
has comment: http://stackoverflow.com/comment/91978527

http://stackoverflow.com/comment/92016217
comment on: http://stackoverflow.com/q/52484087
score: 0
type: Comment
type: QuestionComment
has text: Good point. That's actually what I'm doing with my 'keep alive' message. So that does not have a delay. But processing the actual (non-keep alive) messages and then appending them to the csv file is what gets more and more delayed throughout the day.

http://stackoverflow.com/comment/91967598
score: 0
type: AnswerComment
has text: @Mohit Solanki Yeah I thought about it but in my project I just need to to this that way. I'm saving time and avoiding changeing "milions" lines of code.
type: Comment
comment on: http://stackoverflow.com/a/52513682

http://stackoverflow.com/q/52503940
has body: I have several million history objects that I need to save to Elasticsearch. What would be the best way to do this, without going into the internals of elasticsearch? Here is the pattern I'm currently using: ACTIONS = [] NUM_ACTIONS_TO_BULK = 10000 for num, item in enumerate(HISTORY_DATA.values()): ACTIONS.append({ "_index": ES_INDEX_NAME, "_type": "_doc", "_id": item.pop('_id'), "_source": item }) # Save every 10k and again at the end if (len(ACTIONS) == NUM_ACTIONS_TO_BULK) or (num == len(HISTORY_DATA) - 1): log.info('%s/%s - Saving %s items to ES...' % (num, len(HISTORY_DATA), len(ACTIONS)) _ = helpers.bulk(self.es, ACTIONS) ACTIONS = [] The above saves it to ES in batches of 10k. Is this the best/most efficient way to save things to ES? For example, what if I tried saving all 15M objects directly to ES using helpers.bulk -- does that chunk the items, or does it try saving it all at once? Does it look like I'm missing anything in the above?
tagged with: elasticsearch
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52504942
linked to: http://stackoverflow.com/q/18488747
has title: Efficiently bulk saving items to Elasticsearch
type: Question
answer count: 1
score: 0

http://stackoverflow.com/q/52502874
has title: Apply filtfilt on successive blocks with initial conditions (to avoid discontinuity)
tagged with: scipy
linked to: http://stackoverflow.com/q/52403589
tagged with: signal-processing
type: Question
has comment: http://stackoverflow.com/comment/91977101
has comment: http://stackoverflow.com/comment/91977018
has comment: http://stackoverflow.com/comment/91977538
score: 0
has comment: http://stackoverflow.com/comment/91977356
tagged with: python
has comment: http://stackoverflow.com/comment/91977242
has comment: http://stackoverflow.com/comment/91976787
tagged with: audio-processing
linked to: http://stackoverflow.com/q/52468563
answer count: 0
has body: We have two lowpass filters with a different cutoff value: b, a = signal.butter(2, 0.125) b2, a2 = signal.butter(2, 0.140) When applying the first filter to x[0:10000] and the second to x[10000:20000] with lfilter, we have to use initial conditions for the output to be "continuous", as seen here in the answer of Continuity issue when applying an IIR filter on successive time-frames: zi = lfilter_zi(b, a) x[0:10000], zi = lfilter(b, a, x[0:10000], zi=zi) x[10000:20000], zi = lfilter(b2, a2, x[10000:20000], zi=zi) Question: how to do the same when applying filtfilt (forward and backwards filtering), to ensure continuity when using filters on consecutive blocks, as there is no zi initial conditions parameter?
type: UnansweredQuestion
tagged with: filtering
has comment: http://stackoverflow.com/comment/91977444

http://stackoverflow.com/q/52505225
has title: Python multiprocessing pool; wait for iteration to complete
possible better answer: http://stackoverflow.com/a/52506100
tagged with: multiprocessing
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52522725
answer count: 2
has answer: http://stackoverflow.com/a/52506100
has comment: http://stackoverflow.com/comment/91951007
has body: I've got a large dataset which I want my script to iterate through, perform a series of operations on each entry, then arrange the results for storage to HDD. Because the datasets can be relatively large (~250 GB), RAM availability requires that the dataset be processed in chunks (what I've called dataBlock in the code below) of 1000 entries at a time. I also use the multiprocessing.Pool class to facilitate use of multiple CPU cores for this task. I've essentially got things arranged so that each dataBlock is passed to the Pool, the Pool executes the desired calculations on the dataBlock using the imap method, the Pool returns the calculation results, and the results for the data chunk are appended to a list. This list (processed_data) is the desired end product of the set of calculations. processed_data = [] multiprocessing.Pool(processor_cap) as pool: for blockIndex, block in enumerate(range(1000, height-remainder, 1000)): #Read-in 1000 spectra from source dataset dataBlock = np.asarray(raw_dset[blockIndex*1000:block][:]) ''' Pass data block to processor pool, which iterates through data block. Each spectrum is handed off to a CPU in the pool, which centroids it and appends the result to "processed_block". ''' processed_block = pool.imap(centroid_spectrum, dataBlock) #Append processed spectra to processed data bin for idx, processed_spectrum in enumerate(processed_block): processed_data.append(processed_spectrum) What I'd like to know is how to make the script pause after the call of pool.imap() until the full processed_block has been returned without closing the pool. Currently, it progresses right into the for loop which immediately follows in the snippit above without waiting for processed_block to be returned by pool.imap. I've tried calling pool.join() immediately after the pool.imap() call, but it only returns ***AssertionError and again continues to the for loop below it. I can eventually successfully call pool.close() and pool.join() later in the script on…
has comment: http://stackoverflow.com/comment/91951677
has comment: http://stackoverflow.com/comment/91951318
downvote count: 0
has comment: http://stackoverflow.com/comment/91952086
favorite count: 0
has answer: http://stackoverflow.com/a/52522725
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91984868

http://stackoverflow.com/a/52556890
downvote count: 0
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/52556744
has body: Based on that module, it looks like the file you're trying to run is meant for python3 which you don't seem to have installed. Easily remedied though: https://www.python.org/downloads/

http://stackoverflow.com/comment/91877993
type: QuestionComment
comment on: http://stackoverflow.com/q/52468068
type: Comment
has text: Welcome to Stackoverflow! In order to get a good answer, it is really helpful if you provide a [MCVE] (code and data). Please post both the code and the data as text, not as images (the search engine doesn't play well with images and we can't copy images to our text editors).
score: 0

http://stackoverflow.com/comment/91894783
has text: Sounds like it would be much clearer to just made a trade class, make a list of that, then query that list as required. (Rather than parsing everything individually)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52476747

http://stackoverflow.com/comment/111604359
has text: I have a (C code and links to Matlab scripts) example [here](https://stackoverflow.com/questions/22947469).
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52496635

http://stackoverflow.com/a/52595175
has body: There is an excellent solution created by user @Anderson Carlos Woss. Here, adapted for English: As discussed, one option for displaying variable debug is using the inspect module. With the help of the inspect.stack function you can check the context where the function was executed and access the local and global variables in this context. So, instead of passing the variable itself to function, you can only pass its name so that the function will be in charge of accessing its value by inspection. For this example I still used the tabulate module to format the output easily and legibly. import inspect import tabulate def debug(*args): # Find the context of who called the debug function: context = inspect.stack()[1][0] # Results to be displayed: result = [] # Scroll through all the variables to display: for name in args: # Checks whether it is a local variable in context: if name in context.f_locals: result.append([name, context.f_locals[name]]) # Checks whether it is a global variable in context: elif name in context.f_globals: result.append([name, context.f_globals[name]]) # Variable not found in context: else: result.append([name, 'Not found']) # Displays the results in tabular form: print(tabulate.tabulate(result, headers=['Variable', 'Content'])) An example of use would be: &gt;&gt;&gt; x, y, nome = 1, 2, 'Anderson Carlos Woss' &gt;&gt;&gt; debug('x', 'y', 'nome', 'foo') Variable Content ---------- -------------------- x 1 y 2 nome Anderson Carlos Woss foo Não encontrada See on Repl.it Example call within a function Debugging a local and a global variable: author = "Anderson Carlos Woss" def hello(name): debug('name', 'author') print(f'Hi, {name} (by {author})') hello('John Doe') See on Repl.it Variable Content ---------- -------------------- name John Doe author Anderson Carlos Woss Hi, John Doe (by Anderson Carlos Woss) However, for expression, like doing x + y * 2 the function will not work. It is possible to implement the function for this, but I believe it w…
type: Answer
answers question: http://stackoverflow.com/q/52580892
score: 0

http://stackoverflow.com/q/52471860
has comment: http://stackoverflow.com/comment/91885653
downvote count: 1
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/91885663
answer count: 4
possible better answer: http://stackoverflow.com/a/52471913
score: 2
has comment: http://stackoverflow.com/comment/91885665
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52471913
has answer: http://stackoverflow.com/a/57834213
has title: Python 3.7 input() doesnt work but raw_input does
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/52482610
tagged with: input
tagged with: python
accepted answer: http://stackoverflow.com/a/52482610
has answer: http://stackoverflow.com/a/52472297
upvote count: 3
has body: So classic beginner problem here... Ive been trying to use Python on various text editors like VSCode and Atom and none of them seem to work (After installing python 3.7). If I ask for a simple input the program crashes labelling the input as undefined, but when I use raw_input() it works just fine for some reason. However, raw_input() was changed to input() in Python 3 so why does this keep happening to me?

http://stackoverflow.com/a/52562403
score: 1
has body: There are some issues in your code: In XPath, you should refer to attributes with the @ prefix: //span[@itemprop="name"]/text() You should use relative XPath in your for loop: .//span[@itemprop="name"]/text() You should use the .extract_first() method instead of .extract() (which returns a list) So, your code should be something along these lines: for selector in selectors: name = selector.xpath('.//span[@itemprop="name"]/text()').extract_first() phone = selector.xpath('.//span[@itemprop="telephone"]/text()').extract_first() ...
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52561725
answers question: http://stackoverflow.com/q/52561725
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91862433
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52460014
has text: Yes, two different ways to get the same result. The second one is just a small modification to your code to save the output in a list and plot it. The first one is a bit more direct but not the only alternative. There are many more but that's not the purpose of this post. So I guess it's ok to leave both the codes

http://stackoverflow.com/a/52580037
answers question: http://stackoverflow.com/q/52579539
type: Answer
has body: You have your answer from Ralf, but I wanted to point out another little bug you might have in your code. I modified your code a little to show it, and also used a slightly more concise way of calculating sums and averages of lists: import random def age_func(size): age_list = list() for _ in range(size): age = random.randint(0, 100) age_list.append(age) print('Age is {}'.format(age)) average_int = sum(age_list) / len(age_list) average_float = float(sum(age_list)) / float(len(age_list)) print('Average age (int): {}'.format(average_int)) print('Average age (float): {}'.format(average_float)) print('total Sum: {}'.format(sum(age_list))) return age_list my_list = age_func(6) print (sum(my_list)) A few things I changed: for _ in range(size) - using _ as the variable name means something like "I don't actually use this variable for anything" imported random as random - ensures anyone going through your code realises this is the default random module, not some custom module. use format strings everywhere - format strings are the best :) use sum(age_list) and len(age_list) once your loop is done. No need to calculate these at every step in the loop, only needed once. if you ask python to divide an integer by another integer, it will return an integer. Often, that's not what you want, as in this case. Try asking python to do evaluate 7 / 4 and see what happens :) By forcing our integers to become floats, the results will also be a float. Retry the previous calculation as 7.0 / 4.0. changed variable names to snake_case
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52579539

http://stackoverflow.com/a/52504635
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52504299
has body: Try this: a = re.findall(r'[\d]+', s) b = re.findall(r'[a-zA-Z]+', s) c = '' for i, j in zip(a, b): c+=(int(i)*str(j)) print(c)
has comment: http://stackoverflow.com/comment/91983605

http://stackoverflow.com/q/52479813
has answer: http://stackoverflow.com/a/52481473
has title: Control of mutlthreads without sleep function in python
type: AnsweredQuestion
favorite count: 0
accepted answer: http://stackoverflow.com/a/52481473
has body: If we are having 10 threads ,out of 10 i want to start first 5 threads at time and after completion/excution of these 5 threads only i want to start other 5 threads that also should be done automaticlally ,with out using any sleep function in python import threading import os import sys import time from datetime import datetime,timedelta now=datetime.now() print ("starting time ",now) emptylist=[] list=[1,2,3,4,5,6,7,8,9,10,11,12] def Add(num1): num2=1234 num3=num1+num2 #print num3 #print("\n") return num3 #print list count=0 for i in list: t=threading.Thread(target=Add, args=(i,)) emptylist.append(t) for j in range(0,len(emptylist)+1,1): emptylist[j].start() count+=1 if count%5 ==0: for k in emptylist: k.join()
has comment: http://stackoverflow.com/comment/91903114
type: Question
tagged with: python-multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/91903113
score: 0
has comment: http://stackoverflow.com/comment/91903803
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/a/52532616
score: 1
downvote count: 0
has body: dflist = [df1, df2, df3 ...] for df in dflist: df.index = pd.to_datetime(df.index,errors ='coerce') df_all = pd.concat(df1, df2, df3 ..,axis=1)
answers question: http://stackoverflow.com/q/52532519
type: Answer
upvote count: 1

http://stackoverflow.com/a/52493987
answers question: http://stackoverflow.com/q/52493328
has body: numpy can do this pretty concisely, too! a = np.array(my_list).reshape(-1, n + m) a[:, n:] = 0 result = a.ravel().tolist()
has comment: http://stackoverflow.com/comment/91931505
has comment: http://stackoverflow.com/comment/91931400
type: Answer
downvote count: 2
has comment: http://stackoverflow.com/comment/91931438
score: 3
upvote count: 5
has comment: http://stackoverflow.com/comment/91931210

http://stackoverflow.com/q/52570736
has comment: http://stackoverflow.com/comment/92078148
possible better answer: http://stackoverflow.com/a/52570754
answer count: 2
accepted answer: http://stackoverflow.com/a/52571384
has answer: http://stackoverflow.com/a/52570754
has body: I have two python files and I am import one into another with: in test1.py import test2 test2.py import os from socket import * host = "192.168.1.253" # set to IP address of target computer port = 8081 addr = (host, port) UDPSock = socket(AF_INET, SOCK_DGRAM) data = "102" UDPSock.sendto(data, addr) UDPSock.close() Is there any way to import test2.py with delay time in seconds? Thanks
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92078120
tagged with: python
has title: How to delay import python file
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92078118
score: 1
has answer: http://stackoverflow.com/a/52571384
upvote count: 1
type: Question

http://stackoverflow.com/comment/92115066
score: 1
comment on: http://stackoverflow.com/q/52579218
has text: replace `uttryck` with `expression` in your not_function(uttryck)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52564529
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52564587
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52564587
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52564608
score: 1
has answer: http://stackoverflow.com/a/52566284
type: Question
has answer: http://stackoverflow.com/a/52564608
has comment: http://stackoverflow.com/comment/92067249
has body: The code is very long so I won't type it in. What I am confused about as a beginner programmer, is function calling. So I had a csv file that the function divided all the content (they were integers) by 95 to get the normalised scores. I finished the function by returning the result. its called return sudentp_file Now I want to continue this new variable into another function. So this new function will get the average of the studentp_file. So I made a new function. Ill add the other function as a template of what im doing. def normalise(student_file, units_file) ~ Do stuff here ~ return studentp_file def mean(studentp_file): mean() What I get confused about is what to put in the mean(). Do I keep it or remove it? I understand you guys don't know the file I'm working with my a little basic understanding of how functions and function calling works would be appreciated. Thanks.
has title: Calling the result of a function in another function
upvote count: 1
has answer: http://stackoverflow.com/a/52564584

http://stackoverflow.com/q/52550766
linked to: http://stackoverflow.com/q/4828406
downvote count: 0
has comment: http://stackoverflow.com/comment/92040489
favorite count: 0
tagged with: python
has title: How to open a file and get content from a jinja template
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
has body: I want a put a random line from a file using jinja template. for ex: I have a list of names (1000+) stored in a file. I want to pick a random name from that file and put it in template. something like below: Name= Is it possible? How can we achieve so using jinja without changing the rendering logic? Note: I can not modified the rendering logic (python file), as I am using a rest api to render.
tagged with: jinja2
type: Question
has comment: http://stackoverflow.com/comment/92040582

http://stackoverflow.com/q/52538196
has comment: http://stackoverflow.com/comment/92016246
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52538907
tagged with: python
type: AnsweredQuestion
has body: I current have a dataframe that looks like this: Account Date Region Type Measure Value Bob 31-Jan East A Sales 7 Bob 31-Jan West A Sales 8 Bob 31-Jan East B Expense 5 Bob 31-Jan West B Expense 10 The only difference is my actual dataframe has several different fields for the "account", "date", and "type" dimensions. My goal here is to change the value of only Bob's accounts to be a 50/50 split between the regions for example it would look like: Account Date Region Type Measure Value Bob 31-Jan East A Sales 7.5 Bob 31-Jan West A Sales 7.5 Bob 31-Jan East B Expense 5 Bob 31-Jan West B Expense 10 I've tried filtering my df on Bob and sales to start: df = df[df['Account'] == 'Bob'] df = df[df['Measure'] == 'Sales'] Next I make all of the Regions the same: df['Region'] = 'East and West' Once here, I've tried several groupby functions, but I can't get to seem any of them to return the correct values. Should I try to transpose my df and work from there?
upvote count: 2
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92016557
has title: Transform row value using like dimensions
has answer: http://stackoverflow.com/a/52538907
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/52545099
type: UnansweredQuestion
tagged with: python
has title: Function to iterate over every column in a pandas DataFrame
answer count: 0
has body: Hi, I created a function in Python that takes a dataframe as the first argument, and a column as the second argument.The goal is to find the total number of null values in that field. I'd like to loop over every column in the dataframe and apply the same function. Thanks! def count_nulls(df, col_name): col = df[col_name] bool_col = pd.isna(col) total_nulls = pd.Series.sum(bool_col) total_rows = len(col) pct_null = round((total_nulls / total_rows) * 100,2) print("The","\'"+ str(col_name) + "\'", "field has", str(total_nulls), "nulls which account for", str(pct_null) + "% of all values") ****Image**** enter image description here
type: Question
tagged with: function
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92030119
has comment: http://stackoverflow.com/comment/92030183
linked to: http://stackoverflow.com/q/26266362
tagged with: python-3.x

http://stackoverflow.com/a/52547000
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Python has a great library for importing and reading from CSV files. never reinvent the wheel CSV Python 2.X from the document a short example explaining how to read from a CSV file. import csv with open('eggs.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print ', '.join(row) CSV Python 3.x This module works similarly except now it returns an OrderedDict[] type which makes it a bit easier to navigate the file. import csv with open('names.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['first_name'], row['last_name'])
answers question: http://stackoverflow.com/q/52546624

http://stackoverflow.com/q/52464329
tagged with: python
has body: x=[1,2,3,4] In [91]: x[:1] Out[91]: [1] x[:n] select up to 'n' (exclusive) columns? In [93]: x[:-1] Out[93]: [1, 2, 3] How does x[:-1] work? In [94]: x[::-1] Out[94]: [4, 3, 2, 1] And what about x[::-1]? There are two :: here.
has answer: http://stackoverflow.com/a/52464384
has answer: http://stackoverflow.com/a/52464460
has answer: http://stackoverflow.com/a/52464490
accepted answer: http://stackoverflow.com/a/52464490
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52464384
duplicate of: http://stackoverflow.com/q/509211
has title: Can someone explain how does this slicing work?
answer count: 3
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/509211
favorite count: 0
score: 0

http://stackoverflow.com/comment/91888967
comment on: http://stackoverflow.com/q/52473548
has text: The sign in pop Up which asks for user name and password to enter into the site.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52441958
upvote count: 9
has title: How can use Try/Catch in Python
has answer: http://stackoverflow.com/a/52442226
tagged with: python
has answer: http://stackoverflow.com/a/52442137
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52441992
has body: I want use try...catch in Python but Python give me an error what's can I do? try: input('enter your number'); catch: print('please give integer');
accepted answer: http://stackoverflow.com/a/52441992
type: Question
tagged with: try-catch
score: 3
has comment: http://stackoverflow.com/comment/91826617
possible better answer: http://stackoverflow.com/a/52442137
answer count: 3
tagged with: try-except
has comment: http://stackoverflow.com/comment/91826569
has comment: http://stackoverflow.com/comment/91826607
downvote count: 6
favorite count: 0

http://stackoverflow.com/q/52461751
favorite count: 0
answer count: 0
type: UnansweredQuestion
has body: I installed Bokeh into a virtual environment using pip in the terminal. However, when launching a Jupyter notebook server from this virtual environment, and opening a notebook, the version of bokeh (0.12.9) appears different from the version I installed in the terminal (0.13.0). From the Jupyter notebook server terminal: pip3 install --upgrade bokeh ... python3 Python 3.6.4 (default, Mar 9 2018, 23:15:03) GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bokeh &gt;&gt;&gt; bokeh.__version__ '0.13.0' From a new iPython notebook: import sys print(sys.version) import bokeh print(bokeh.__version__) &gt;&gt;&gt; 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 13:14:59) &gt;&gt;&gt; [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] &gt;&gt;&gt; '0.12.9' I have checked that the notebook is also running Python 3 (though it is a different version, which seems suspicious...) How do I upgrade the version of Bokeh that runs in the notebook? The most closely related questions that I can find on Stack Overflow (old sklearn version in Jupyter Notebook, Conflicting python version in jupyter notebook(Conda)) do not seem to work, probably because they are specific to conda, which I do not have installed.
tagged with: python
downvote count: 0
score: 1
has title: Python package version (bokeh) in Jupyter Notebook different from version in Terminal
type: Question
has comment: http://stackoverflow.com/comment/91888841
has comment: http://stackoverflow.com/comment/91941616
linked to: http://stackoverflow.com/q/41768292
upvote count: 1
linked to: http://stackoverflow.com/q/50675004
tagged with: jupyter
tagged with: virtualenv
tagged with: jupyter-notebook

http://stackoverflow.com/comment/91819433
has text: [ask]... [mcve]...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52438218

http://stackoverflow.com/a/52458155
type: Answer
answers question: http://stackoverflow.com/q/52457989
has comment: http://stackoverflow.com/comment/97651297
has body: Interesting question! I believe the behavior you're seeing is an artifact of the way you use apply. As you correctly indicate, apply is not intended to be used to modify a dataframe. However, since apply takes an arbitrary function, it doesn't guarantee that applying the function will be idempotent and will not change the dataframe. Here, you've found a great example of that behavior, because your function foo attempts to modify the row that it is passed by apply. Using apply to modify a row could lead to these side effects. This isn't the best practice. Instead, consider this idiomatic approach for apply. The function apply is often used to create a new column. Here's an example of how apply is typically used, which I believe would steer you away from this potentially troublesome area: import pandas as pd # construct df2 just like you did df2 = pd.DataFrame(columns=['a', 'b']) df2['a'] = ['a0','b0'] df2['b'] = ['a1','b1'] df2['b_copy'] = df2.apply(lambda row: row['b'], axis=1) # apply to each row df2['b_replace'] = df2.apply(lambda row: '42', axis=1) df2['b_reverse'] = df2['b'].apply(lambda val: val[::-1]) # apply to each value in b column print(df2) # output: # a b b_copy b_replace b_reverse # 0 a0 a1 a1 42 1a # 1 b0 b1 b1 42 1b Notice that pandas passed a row or a cell to the function you give as the first argument to apply, then stores the function's output in a column of your choice. If you'd like to modify a dataframe row-by-row, take a look at iterrows and loc for the most idiomatic route.
score: 6
upvote count: 6
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52457989

http://stackoverflow.com/comment/91865822
type: AnswerComment
has text: After all its not just a japanese character that could appear, it could be german, french, russian etc. Though this method would work it doesn't fit the over all needs I have.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52461822

http://stackoverflow.com/q/52433872
has body: I want to use CNN network to segment 2 objects (binary: "0: object not present, 1: object present") into shapes but I have an issue with data. The train data is 150 images and in "jpg" format and the ground truth (label data) is also 150 images of "png" rasters of 0 and 1 (resulting in black white images). Now the question is how to load this hybrid of train images and label images in Keras/Tensorflow and if there`s a dummy example and/or demonstration on how to do that in Python, I would be grateful.
tagged with: keras
favorite count: 0
tagged with: convolution
tagged with: python
tagged with: conv-neural-network
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91811577
accepted answer: http://stackoverflow.com/a/52434600
has comment: http://stackoverflow.com/comment/91812461
has comment: http://stackoverflow.com/comment/91812334
has title: how to load label data presented in raster format into Keras/Tensorflow
has comment: http://stackoverflow.com/comment/91812361
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52434600

http://stackoverflow.com/comment/121454463
score: 0
type: AnswerComment
type: Comment
has text: https://numpy.org/doc/stable/reference/random/legacy.html `RandomState()` is actually legacy now - how would you replace it?
comment on: http://stackoverflow.com/a/52545091

http://stackoverflow.com/q/52560700
has answer: http://stackoverflow.com/a/52560907
linked to: http://stackoverflow.com/q/9535954
has answer: http://stackoverflow.com/a/52560763
score: 1
upvote count: 1
type: Question
has title: How do I add column headers for each row of data in a loop?
has body: I am using Python3.6. Database table example: column1 . .column2 . .column3 ....10 ...........20..............30 ....100 ....... 200.............300 Code: # extracts all data for the rows without the column names rows=cursor.fetchall() for row in rows: print(row) 10 20 30 100 200 300 How do I add the column names manually to this loop so that it is included in the output? I am new to stackoverflow so this post will need improvements in formatting, content, etc., so I welcome any feedback. Thank you!
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52560771
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52594238
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/130602414
has comment: http://stackoverflow.com/comment/92327681
downvote count: 0
has comment: http://stackoverflow.com/comment/120029361
has body: The reason your solution did not work is because in order for device verifier and salt to work, they have to be calculated based on device_group_key and device_key. Also calculation of a challenge response for device authentication differs from the standard password SRP flow. Here is how it worked out for me: First, confirm and remember the device (Amazon Cognito Identity SDK for JavaScript source): from warrant import aws_srp from warrant.aws_srp import AWSSRP import boto3 import base64 import os def generate_hash_device(device_group_key, device_key): # source: https://github.com/amazon-archives/amazon-cognito-identity-js/blob/6b87f1a30a998072b4d98facb49dcaf8780d15b0/src/AuthenticationHelper.js#L137 # random device password, which will be used for DEVICE_SRP_AUTH flow device_password = base64.standard_b64encode(os.urandom(40)).decode('utf-8') combined_string = '%s%s:%s' % (device_group_key, device_key, device_password) combined_string_hash = aws_srp.hash_sha256(combined_string.encode('utf-8')) salt = aws_srp.pad_hex(aws_srp.get_random(16)) x_value = aws_srp.hex_to_long(aws_srp.hex_hash(salt + combined_string_hash)) g = aws_srp.hex_to_long(aws_srp.g_hex) big_n = aws_srp.hex_to_long(aws_srp.n_hex) verifier_device_not_padded = pow(g, x_value, big_n) verifier = aws_srp.pad_hex(verifier_device_not_padded) device_secret_verifier_config = { "PasswordVerifier": base64.standard_b64encode(bytearray.fromhex(verifier)).decode('utf-8'), "Salt": base64.standard_b64encode(bytearray.fromhex(salt)).decode('utf-8') } return device_password, device_secret_verifier_config client = boto3.client('cognito-idp') username='xxx' password='xxx' client_id='xxx' client_secret='xxx' pool_id='xxx' # 1. Login with the password via standard SRP flow aws = AWSSRP(username=username, password=password, pool_id=pool_id, client_id=client_id, client_secret=client_secret, client=client) auth_init = client.initiate_auth( AuthFlow='USER_SRP_AUTH', AuthParameters=aws.get_auth_params(), ClientId=client_id, )…
has comment: http://stackoverflow.com/comment/138640555
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52499526
has comment: http://stackoverflow.com/comment/92481588
has comment: http://stackoverflow.com/comment/92187543
answers question: http://stackoverflow.com/q/52499526
has comment: http://stackoverflow.com/comment/138599185
type: AcceptedAnswer

http://stackoverflow.com/comment/92082265
type: Comment
type: QuestionComment
score: 0
has text: Hm, it seems that second one is working and the problem was in sleeping inside loop
comment on: http://stackoverflow.com/q/52544117

http://stackoverflow.com/comment/92034957
comment on: http://stackoverflow.com/q/52546456
has text: Thank you, I think you were right. I used pandas in my views to manipulate the data and was able to easily get a total to render on the template. I appreciate the input.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/65534186
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/117388201
has comment: http://stackoverflow.com/comment/117390988
downvote count: 0
has body: pyenv can be used in Linux/MacOS for python version management. pyenv-win is the fork of pyenv which can be used on Windows. Installation MacOS Tested on Mac Catalina Install pyenv. brew install pyenv Add following to your shell config file: .bashrc/.bash_profile - For Bash .zshrc - For Zsh export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init -)" Restart your shell. Start a new shell or run exec "$SHELL" in your current shell. Linux / Windows on Linux Subsystem Tested on Arch Linux Install pyenv on your system. curl https://pyenv.run | bash Follow same steps as in Step 2 and 3 of MacOS installation. Windows Install pyenv-win on Windows. In Powershell pip install pyenv-win --target "$HOME\.pyenv" In cmd.exe pip install pyenv-win --target "%USERPROFILE%\.pyenv" Setup the environment variables using Powershell/Terminal. [System.Environment]::SetEnvironmentVariable('PYENV',$env:USERPROFILE + "\.pyenv\pyenv-win\","User") [System.Environment]::SetEnvironmentVariable('PYENV_HOME',$env:USERPROFILE + "\.pyenv\pyenv-win\","User") [System.Environment]::SetEnvironmentVariable('path', $HOME + "\.pyenv\pyenv-win\bin;" + $HOME + "\.pyenv\pyenv-win\shims;" + $env:Path,"User") Close and re-open your terminal. Run pyenv --version on the terminal. a. If the return value is the installed version of pyenv, then continue below. b. If you receive a command not found error, ensure the environment variables are properly set via the GUI: This PC → Properties → Advanced system settings → Advanced → Environment Variables... → PATH c. If you receive a command not found error and you are using Visual Studio Code or another IDE with a built in terminal, restart it and try again. Run pyenv rehash from the home directory. Usage Check installed python versions pyenv versions Example $ pyenv versions * system (set by /home/souser/.pyenv/version) 3.6.9 Installed a specific python version pyenv install <version-number> Uninstall an installed python version pyenv unins…
score: 6
answers question: http://stackoverflow.com/q/52584907

http://stackoverflow.com/comment/91952625
has text: Maybe I'll have to re-code as the event only wants 2 signatures.
score: 0
comment on: http://stackoverflow.com/q/52505861
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91928764
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52493730
type: AnswerComment
has text: What that error means is that it can't find the column "Datum" in the DataFrame. That's likely to be caused by it not being read in correctly (or maybe there are spaces in your column names). Without having the data it's hard for me to say why. But you can type `print(df.columns)` to see the names of the columns that have been loaded in, which might give you a clue.

http://stackoverflow.com/q/52458326
tagged with: python-2.7
tagged with: ta-lib
has body: In my Python 2.7 project I need to install the ta-lib library. On the target environment I do not have root or sudo permissions, therfore the Python application runs in a virtual environment. For unknown reasons the installation of the ta-lib library with pip fails, when libta_lib.so resides in the user directory structure (instead of the system's /usr folder). What I did: I'm using Python 2.7 to create a fresh virtual environment: ec2-user:~/environment $ python -V Python 2.7.14 ec2-user:~/environment $ virtualenv -p /usr/bin/python27 my_env Running virtualenv with interpreter /usr/bin/python27 New python executable in /home/ec2-user/environment/my_env/bin/python27 Also creating executable in /home/ec2-user/environment/my_env/bin/python Installing setuptools, pip, wheel...done. ec2-user:~/environment $ source my_env/bin/activate (my_env) ec2-user:~/environment $ Within my_env I download and untar the latest ta-lib. I use the prefix-flag to configure the installation path to be within the virtual env. (my_env) ec2-user:~/environment/my_env $ ./configure --prefix=/home/ec2-user/environment/my_env (my_env) ec2-user:~/environment/my_env $ make (my_env) ec2-user:~/environment/my_env $ make install Configure, make and install work just fine. At the end the system tells me someting like: Libraries have been installed in: /home/ec2-user/environment/my_env/lib If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR' flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - add LIBDIR to the `LD_RUN_PATH' environment variable during linking [...] So I added /home/ec2-user/environment/my_env/lib to $LD_LIBRARY_PATH and $LD_RUN_PATH. So far everyting looks fine, but when I (my_env) ec2-user:~/environment/my_env $ pip install ta-lib Collecting ta-lib Using cached https:/…
upvote count: 1
downvote count: 0
favorite count: 0
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/52458594
accepted answer: http://stackoverflow.com/a/52458594
type: AnsweredQuestion
score: 1
has title: Issues installing Python library with binary dependency in virtualenv without sudo
type: Question
answer count: 1
tagged with: virtualenv

http://stackoverflow.com/q/52483656
has comment: http://stackoverflow.com/comment/91909130
has comment: http://stackoverflow.com/comment/91908971
has comment: http://stackoverflow.com/comment/91909148
has comment: http://stackoverflow.com/comment/91908884
has title: Python function with many optional arguments
has comment: http://stackoverflow.com/comment/91909123
has comment: http://stackoverflow.com/comment/91909050
answer count: 1
has comment: http://stackoverflow.com/comment/91908974
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52484122
has comment: http://stackoverflow.com/comment/91909254
has comment: http://stackoverflow.com/comment/91908755
tagged with: design-patterns
linked to: http://stackoverflow.com/q/14017996
has comment: http://stackoverflow.com/comment/91908943
has comment: http://stackoverflow.com/comment/91908837
upvote count: 3
score: 1
has comment: http://stackoverflow.com/comment/91909154
has body: I currently have a function with many optional arguments, something like this: def many_argument_function(required1, required2, optional1=1, optional2=2, optional3=None, optional4="Test", optional5="g", optional6=2, optional7=(0, 255, 0), optional8=0.5): # Do stuff But in reality, it has over 20 optional arguments which take five lines even with 120 character line limit. Is there a design pattern to simplify this/make it prettier? P.S. I have considered making a separate configuration file for this function, but then calling it would be annoying since most of the time only one or two optional arguments are used. EDIT1: I don't want to use kwargs as I want names of arguments and default values visible in my IDE (PyCharm)
type: Question

http://stackoverflow.com/comment/91808823
type: QuestionComment
score: 1
has text: `pd.rolling` https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html
comment on: http://stackoverflow.com/q/52432557
type: Comment

http://stackoverflow.com/q/52489258
has title: Dockerized Django application refuses connections
has comment: http://stackoverflow.com/comment/91920264
type: Question
has comment: http://stackoverflow.com/comment/92002023
has comment: http://stackoverflow.com/comment/91920210
downvote count: 0
tagged with: docker
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/117210158
answer count: 0
has comment: http://stackoverflow.com/comment/91920191
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91920138
has comment: http://stackoverflow.com/comment/91920074
tagged with: django
tagged with: dockerfile
has comment: http://stackoverflow.com/comment/91920150
has comment: http://stackoverflow.com/comment/91920292
score: 2
tagged with: docker-compose
has comment: http://stackoverflow.com/comment/91920088
has body: My Django application that is running on Docker won't allow me to connect to it when I type 0.0.0.0:8000 or even my docker-machine ip. The error shows as below: Safari can’t open the page “‎0.0.0.0:8000” because the server unexpectedly dropped the connection. This sometimes occurs when the server is busy. Wait for a few minutes, and then try again. Also when I try docker-machine ssh default I then type wget -qO- 127.0.0.1:8000 to see if the server will let me connect from within the docker vm, I get this error response: docker@default:~$ wget -qO- 127.0.0.1:8000 wget: can't connect to remote host (127.0.0.1): Connection refused Dockerfile FROM python:3.6-alpine # Copying requirements files for python modules ADD requirements.txt /requirements.txt # Installing build deps for running images RUN apk add --no-cache --virtual .build-deps \ build-base postgresql-dev libffi-dev \ &amp;&amp; pip install -r requirements.txt \ &amp;&amp; find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ &amp;&amp; runDeps="$( \ scanelf --needed --nobanner --recursive /usr/local \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u \ )" \ &amp;&amp; apk add --virtual .rundeps $runDeps \ &amp;&amp; apk del .build-deps # Copying application code for the docker container to persist RUN mkdir /src COPY src/ /src WORKDIR /src # uWSGI port opening EXPOSE 8000 # DJANGO enviroment settings RUN DATABASE_URL=none /usr/local/bin/python manage.py collectstatic --noinput docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 382f6202153d dronerestapi_app "python manage.py ru…" 4 minutes ago Up 4 minutes 0.0.0.0:8000-&gt;8000/tcp dronerestapi_app_1 db6e0145a5da postgres:9.6 "docker-entrypoint.s…" 4 minutes ago Up 4 minutes 0.0.0.0:5432-&gt;5432/tcp dronerestapi_db_1 docker-compose.yml version: '2' services: db: environment: POSTGRES_DB: drone_db POSTGRES_U…

http://stackoverflow.com/q/52488043
has comment: http://stackoverflow.com/comment/91917502
has body: I'm doing a python code that: Take data from an API parse the data build a query and send it to my PGadmin database Here's my code: # -*- coding: utf-8 -*- import requests import json import datetime import os import psycopg2 from urlparse import urlparse try: conn = psycopg2.connect("dbname='tp_1' user='postgres' host='localhost' password='senha'") except psycopg2.DatabaseError, ex: print 'I am unable to connect the database: ' + str(ex) cur = conn.cursor() url = "https://www.mercadobitcoin.net/api/BTC/day-summary/2013/6/20/" moeda = url.split('/')[4] response = requests.get(url) print("---------------------") data = response.text print(data) print("---------------------") parsed = json.loads(data) opening = parsed["opening"] closing = parsed["closing"] lowest = parsed["lowest"] highest = parsed["highest"] volume = parsed["volume"] quantity = parsed["quantity"] amount = parsed["amount"] avg_price = parsed["avg_price"] date = parsed["date"] print(opening) print(closing) print(lowest) print(highest) print(volume) print(quantity) print(amount) print(avg_price) print(date) SQL = "INSERT INTO day_summary (id_day, data_day, opening, closing, lowest, highest ,volume,quantity, amount, avg_price ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" data = (1,datetime.date(date), opening, closing, lowest, highest, volume, quantity, amount, avg_price) cur.execute(SQL, data) conn.commit() cur.close() conn.close() This is the outputs from my prints: --------------------- {"date": "2013-06-20", "opening": 262.99999, "closing": 269.0, "lowest": 260.00002, "highest": 269.0, "volume": 7253.13363568, "quantity": 27.11390588, "amount": 28, "avg_price": 267.50604165} --------------------- 262.99999 269.0 260.00002 269.0 7253.13363568 27.11390588 28 267.50604165 2013-06-20 And here's my traceback: Traceback (most recent call last): File "dados_api_day.py", line 56, in &lt;module&gt; data = (1,datetime.date(date), opening, closing, lowest, highest, volume, quantity, amount, avg_price) TypeError: an…
has title: TypeError: an integer is required on my python script
has comment: http://stackoverflow.com/comment/91918448
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91919510
has comment: http://stackoverflow.com/comment/91918004
favorite count: 0
tagged with: pgadmin
tagged with: postgresql
tagged with: python
has comment: http://stackoverflow.com/comment/91917346
upvote count: 0
has answer: http://stackoverflow.com/a/52505023
accepted answer: http://stackoverflow.com/a/52505023
tagged with: psycopg2
type: Question
type: AnsweredQuestion
score: -1

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/52527893
tags question: http://stackoverflow.com/q/52539110
tags question: http://stackoverflow.com/q/52452269
tags question: http://stackoverflow.com/q/52432324
type: Tag
tags question: http://stackoverflow.com/q/52523514
tags question: http://stackoverflow.com/q/52514778
tags question: http://stackoverflow.com/q/52558506

http://stackoverflow.com/q/52469712
type: Question
has comment: http://stackoverflow.com/comment/92941939
upvote count: 0
score: -2
tagged with: marshmallow
tagged with: flask
has answer: http://stackoverflow.com/a/52470397
answer count: 1
favorite count: 0
has title: virtualenv dependencies don't respond well to Ubuntu 18.04
downvote count: 2
accepted answer: http://stackoverflow.com/a/52470397
tagged with: python
has comment: http://stackoverflow.com/comment/91881458
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91881563
has comment: http://stackoverflow.com/comment/91881651
has body: I am building this project on two computers, windows 10 and ubuntu 18.04. Actually I never succeeded to fully use the ubuntu pc. Whenever I try to make a post request to the database I get this error: File "/home/user/venv1/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/home/user/venv1/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "/home/user/venv1/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/home/user/venv1/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/home/user/venv1/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/home/user/venv1/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/user/venv1/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "/home/user/venv1/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/user/venv1/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/home/user/venv1/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/home/user/venv1/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/user/venv1/lib/python3.6/site-packages/flask/views.py", line 84, in view return self.dispatch_request(*args, **kwargs) File "/home/user/venv1/lib/python3.6/site-packages/flask/views.py", line 149, in dispatch_request return meth(*args, **kwargs) File "/home/user/venv1/lib/python3.6/site-packages…

http://stackoverflow.com/a/52523292
downvote count: 0
answers question: http://stackoverflow.com/q/52522845
type: Answer
accepted answer of: http://stackoverflow.com/q/52522845
upvote count: 11
score: 11
has body: Thanks to @Abdou, I just found the answer in this link resize ipython notebook output window. The original answer is by @keflavich. I am keeping this question just for the reference purpose. It will be closed soon. %%javascript IPython.OutputArea.auto_scroll_threshold = 9999; # another cell import matplotlib.pyplot as plt %matplotlib inline for i in range(10): plt.plot(range(10)) plt.show() Now the output window will be large and we can see all the outputs without scrolling. Date: Sep 26, 2018 Browser: Safari 10.1.2 Platform: OSX Yosemite 10.10
type: AcceptedAnswer

http://stackoverflow.com/comment/92013766
has text: As I see your Edit2. Looks like you want to update doc only for perticular users, So you dont need to doc.pop(''user). Below one lines are wrong. item.pop('user') collection.update({'_id': _id, 'user': _user }, {$set: item}) you dont need them
type: AnswerComment
comment on: http://stackoverflow.com/a/52536111
type: Comment
score: 1

http://stackoverflow.com/comment/91926864
comment on: http://stackoverflow.com/q/52475458
type: Comment
type: QuestionComment
has text: There is an [issue](https://github.com/pandas-dev/pandas/issues/3942) filed on GitHub related to this.
score: 1

http://stackoverflow.com/q/52485041
has answer: http://stackoverflow.com/a/52485123
type: Question
has comment: http://stackoverflow.com/comment/91915682
has answer: http://stackoverflow.com/a/52485262
has answer: http://stackoverflow.com/a/52485091
tagged with: pandas
has answer: http://stackoverflow.com/a/52485344
downvote count: 0
has title: How to split a column based on a string (when it exists) into a separate column
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: regex
answer count: 4
has body: I have a dataframe as follows: df = pd.DataFrame({ 'Event':['2018 Green Meeting','2018 Yellow Meeting','2018 Red Meeting', '2017 Green Meeting','2017 Yellow Meeting','2017 Red Meeting', '2016 Green Meeting','2016 Yellow Meeting','2016 Red Meeting', 'Blue Meeting','Purple Meeting','Green Meeting'], 'Count':[1,2,3,4,5,6,7,8,9,10,11,12] }) I want to split the Event Column into two columns 'Year' and 'Event_Name' to get the following output: df2 = pd.DataFrame({ 'Year':['2018','2018','2018', '2017','2017','2017', '2016','2016','2016', 'Blue Meeting','Purple Meeting','Green Meeting'], 'Event_Name':['Green Meeting','Yellow Meeting','Red Meeting', 'Green Meeting','Yellow Meeting','Red Meeting', 'Green Meeting','Yellow Meeting','Red Meeting', 'Blue Meeting','Purple Meeting','Green Meeting'], 'Count':[1,2,3,4,5,6,7,8,9,10,11,12] }) When I try to use regex to do this. It dones not seem to be working. I am getting two columns 'Year' and 'Event_Name'. But the year is empty. This is what I am using: df'Year','Event_Name' = df['Event'].str.split(r'\d{4}',expand=True) How do I get this to work correctly?
score: 1

http://stackoverflow.com/comment/91995219
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52527750
score: 1
has text: Why are you using `self.d` instead of `self.accountType`?

http://stackoverflow.com/comment/92006950
type: QuestionComment
has text: This question should help: https://stackoverflow.com/questions/11964972/django-template-for-tag-add-li-every-4th-element
comment on: http://stackoverflow.com/q/52533812
score: 0
type: Comment

http://stackoverflow.com/a/52488140
type: Answer
answers question: http://stackoverflow.com/q/52487490
upvote count: 1
has comment: http://stackoverflow.com/comment/121585260
downvote count: 0
score: 1
has body: actually i don't think this needs to be that complicated the fibonacci sequence is very interesting in a maltitude of ways for example, if you want the sum up the 7th fibonacci number, then have checked what the 9th fibonacci number - 1 is? Now how do we find the n'th fibonacci number? p = (1+5**.5)/2 q = (1-5**.5)/2 def fibo(n): return 1/5**.5*(p**n-q**n) and now we can can find the sum up to any number in one calculation! for example for 7 fibo(9)- 1 output 33 and what is the actual answer 1+1+2+3+5+8+13=33 summa summarum: the fibonachi number that is two places further down the sequence minus 1 is the sum of the fibonachi numbers up to the number

http://stackoverflow.com/comment/92076215
has text: @JonClements thx
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52568384

http://stackoverflow.com/q/52447494
tagged with: pyqt
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: qtabwidget
has body: I am trying to have a function change the text listed on a tab, but I am having trouble figuring out how to properly reference the tab. The below code works, but does nothing since the one line is commented out. I know the issue is with the "self" in that line (un-commenting the line causes the error when the button is clicked), but I do not know what is supposed to go there to make it work. I am guessing that my issue is with the tab being created by a different class, but I want to be able to open multiple tabs with the same widgets in each one (as this code does). Will I have to restructure the code to make this work? from PyQt5.QtWidgets import (QMainWindow, QApplication, QAction, qApp, QPushButton, QWidget, QMenu, QVBoxLayout, QTabWidget, QLineEdit, QLabel, QHBoxLayout) import sys class MainWin(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): exitAct = QAction('&amp;Exit', self) exitAct.triggered.connect(qApp.quit) newAct = QAction('&amp;New Tab', self) newAct.triggered.connect(self.newTab) menubar = self.menuBar() fileMenu = menubar.addMenu('&amp;File') fileMenu.addAction(newAct) fileMenu.addAction(exitAct) self.layout = QVBoxLayout() self.tabbed = QTabWidget(self) self.layout.addWidget(self.tabbed) self.setCentralWidget(self.tabbed) self.show() def newTab(self): self.tab1 = tabbedFrame(self.tabbed) self.tabbed.addTab(self.tab1, self.tab1.tabName) class tabbedFrame(QWidget): def __init__(self, parent): super(tabbedFrame, self).__init__(parent) layout = QVBoxLayout() self.updateButton = QPushButton("Update") self.updateButton.clicked.connect(self.updateTab) layout.addWidget(QLabel("Tab Name")) self.nameLineEdit = QLineEdit("New Tab") self.tabName = self.nameLineEdit.text() layout.addWidget(self.nameLineEdit) layout.addWidget(self.updateButton) self.setLayout(layout) def updateTab(self): tabindex = win.tabbed.currentIndex #win.tabbed.setTabText(self, tabindex, self.tabName) if __name__ == '__main__': app = QApplication(sys.arg…
tagged with: python
accepted answer: http://stackoverflow.com/a/52448592
has title: Edit tab name from child class
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: pyqt5
has answer: http://stackoverflow.com/a/52448592
type: Question
upvote count: 1

http://stackoverflow.com/comment/91897158
has text: Remove your `try ... except` to get the Traceback output. Reread the [BeautifulSoup/bs4/doc/#find](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find). `find()` just returns the result not a list.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52476935
score: 0

http://stackoverflow.com/comment/91947541
comment on: http://stackoverflow.com/a/52489307
type: AnswerComment
score: 0
has text: I'd like to know how to make these unnecessary list() and iter() calls unnecessary even under mypy checking.
type: Comment

http://stackoverflow.com/q/52510387
upvote count: 1
favorite count: 0
tagged with: python
tagged with: artificial-intelligence
has comment: http://stackoverflow.com/comment/91962400
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
has body: Everytime I try to train this network, the loss keeps going farther negative. Like for step 1 to step 2 it goes down to like -230192809 and keeps going down. Also, the accuracy then ends up being 0.0238 or something. I have no idea what's happening. Since it keeps continually decreasing, I'm not sure whether that's a CPU issue or there's something wrong with the code that I have written below. If it is the code or the CPU/GPU, please let me know as I've been struggling with this for quite a while now. Thanks for the help! import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data old_v = tf.logging.get_verbosity() tf.logging.set_verbosity(tf.logging.ERROR) mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) train_data = mnist.train.images # Returns np.array train_labels = np.asarray(mnist.train.labels, dtype=np.int32) eval_data = mnist.test.images # Returns np.array eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) tf.logging.set_verbosity(old_v) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 10 batch_size = 100 # height by width x = tf.placeholder(tf.float32, shape=(None, 784)) y = tf.placeholder('float') def neural_network_model(data): hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784, n_nodes_hl1])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'biases': tf.Variable(tf.random_normal([n_classes]))} l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) l2 = tf.nn.relu(l…
type: Question
score: 1
has title: MNIST Neural Network Accuracy 0.0238 and very Random Losses
has comment: http://stackoverflow.com/comment/91994111

http://stackoverflow.com/comment/91988733
score: 0
type: Comment
type: QuestionComment
has text: When you create a user you can set `is_staff` to `True` like `User(..., is_staff=True) or using https://docs.djangoproject.com/en/2.1/ref/contrib/auth/#manager-methods
comment on: http://stackoverflow.com/q/52523419

http://stackoverflow.com/comment/91833483
comment on: http://stackoverflow.com/a/52445270
score: 2
type: AnswerComment
type: Comment
has text: @JoshuaSchlichting oops, I missed a " there - thanks for noticing. Edited and fixed.

http://stackoverflow.com/a/52572020
accepted answer of: http://stackoverflow.com/q/52562969
has body: uWSGI can not find your main inside main.py you need to return an instance of your app and then pass it in uwsgi ini file. like this. in main.py: def main(): app = .... // whatever you want return app app = main() then in uwsgi file: [uwsgi] http = 127.0.0.1:5000 module = main callable = app default wsgi in flask works because it looks inside serve() function in which you have made an instance of your app. but uwsgi has nothing to do with that serve() function. it just looks for callable instance in your main file.
has comment: http://stackoverflow.com/comment/110794383
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92095637
type: Answer
answers question: http://stackoverflow.com/q/52562969
score: 2
upvote count: 2

http://stackoverflow.com/q/52450964
has comment: http://stackoverflow.com/comment/91845895
has comment: http://stackoverflow.com/comment/91845293
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91847742
type: Question
score: 0
has title: Incorrect Python Matplotlib Polar Plotting
tagged with: python
answer count: 0
has body: I'm trying to plot a polar plot using the code below ax = plt.subplot(111,polar=True) plt.scatter(ts,rds,c=cs, s=[(y*100)+10 for y in ys], cmap='gist_rainbow') ax.set_yticklabels([]) for i in range(len(names)): ax.text(ts[i],rds[i],"{}".format(i+1),size=12) plt.show() There are 42 points, the first 7 of which are # Theta Radius 1 249.25 0.39 2 66.25 0.40 3 239.09 0.71 4 31.82 1.05 5 114.02 0.54 6 189.15 0.46 7 359.00 0.05 However, the resulting figure/plot at the below link is incorrect https://i.sstatic.net/fs5zf.png Before taking a screenshot, I mouse hovered over point 7. You can see that point 7 is plotted at 41.186 degrees and not 359 as it should be. Any idea why this is? Thanks
type: UnansweredQuestion

http://stackoverflow.com/a/52581851
answers question: http://stackoverflow.com/q/52570869
score: 0
type: Answer
has body: If you annotate the root node of the YAML file with a tag, you can define Python classes deriving from YAMLObject to deal with this as described in the PyYAML documentation. However, if you prefer your YAML to stay clean from tags, you can construct the nested classes yourself (taken from my answer to a similar question): import yaml class BItem: def __init__(self, q, r, s): self.q, self.r, self.s = q, r, s class CItem: def __init__(self, raw): self.d, self.e, self.f = raw['d'], raw['e'], raw['f'] class Root: def __init__(self, raw): self.a = raw['a'] self.b = [BItem(i['q'], i['r'], i['s']) for i in raw['b']] self.c = CItem(raw['c']) mydict = Root(yaml.safe_load(""" a: 1 b: - q: "foo" r: 99 s: 98 - q: "bar" r: 97 s: 96 c: d: 7 e: 8 f: [9,10,11] """)) However, this approach only works if your YAML is structured homogeneously. You gave a heterogeneous structure by having differently named fields in the list of b (q, r, s in the first item; x, y, z in the second item). I changed the YAML input to have the same field names because with different fields, this approach does not work. I am unsure whether your YAML is actually heterogeneous or you just accidentally made it so for an example. If your YAML actually is heterogeneous, accessing the items via dict access is the only viable way since then, the keys in the YAML file do not correspond to class fields; they are dynamic mapping entries.

http://stackoverflow.com/comment/91811039
has text: I just struggle to see the difference between my posts and other posts (which get loads of +1s)
type: Comment
comment on: http://stackoverflow.com/q/52431102
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91830627
type: QuestionComment
comment on: http://stackoverflow.com/q/52443855
has text: Using request.form e.g. searchText = request.form['teamDropdown']
score: 0
type: Comment

http://stackoverflow.com/a/52525271
type: Answer
has body: To mock this function def myFunction(self): auth_token_path = self.authTokenPath() import json if os.path.exists(auth_token_path): auth_token = json.load(open(auth_token_path, 'r')) return auth_token All we need to do is add the decorator PATCH() related to the import's function one needs to mock: @patch('json.load') def myFunction(self,json): auth_token_path = self.authTokenPath() import json if os.path.exists(auth_token_path): auth_token = json.load(open(auth_token_path, 'r')) return auth_token
answers question: http://stackoverflow.com/q/52472932
score: 0
has comment: http://stackoverflow.com/comment/91990760

http://stackoverflow.com/q/52523735
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52523875
has body: I have a dataframe that lists SystemIDs and the number of alarms of certain types and class which happened on certain dates: df SystemID AlarmClass AlarmType Day AlarmCount 0 95EE8B57-6BE9-4175-B901-B6B3BEE1844D Service Unexpected Status 06/08/2018 3 1 95EE8B57-6BE9-4175-B901-B6B3BEE1844D Service Unexpected Status 05/08/2018 2 2 95EE8B57-6BE9-4175-B901-B6B3BEE1844D Service Unexpected Status 06/08/2018 1 3 5F891F03-3114-4E62-9A7D-CD2A04061364 Service Unexpected Status 04/08/2018 2 4 5F891F03-3114-4E62-9A7D-CD2A04061364 Service Unexpected Status 04/08/2018 2 5 5F891F03-3114-4E62-9A7D-CD2A04061364 Event Log Monitor Application Log 05/08/2018 2 I would like to aggregate this data by grouping on SystemID and Day and listing the number of alarms of each type and class. The result for the above dataframe would look like this: SystemID Day AlarmClass-S AlarmClass-ELM AlarmType-US AlarmType-AL 0 95EE8B57-6BE9-4175-B901-B6B3BEE1844D 06/08/2018 4 0 4 0 1 95EE8B57-6BE9-4175-B901-B6B3BEE1844D 05/08/2018 2 0 2 0 2 5F891F03-3114-4E62-9A7D-CD2A04061364 04/08/2018 4 0 4 0 3 5F891F03-3114-4E62-9A7D-CD2A04061364 05/08/2018 0 2 0 2 How to do this most efficiently? The dataframe has millions of records.
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52523875
has title: Aggregating a large pandas dataframe
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/comment/92037218
has text: `key=lambda d: d.size`?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52549032

http://stackoverflow.com/a/52502098
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52501879
type: Answer
has body: I would personally approach this problem using a for loop for plotting each bar separately. There might be other direct ways too. I am using a test data to provide an answer. # imports m = [10, 20, 13, 15, 18, 5, 7] Categories = ('CO','IT','CU','RE','AC','IN','Other') labels =['Contract','ITEM','CUSTOMER','REQUEST','ACCOUNT','INQUIRY','OTHER'] colors = ['black', 'red', 'green', 'blue', 'orange','purple','brown'] for j in range(len(m)): plt.bar(j, m[j], width=0.5,align='center', colors = color[j], label=labels[j]) plt.xticks(np.arange(len(m)), Categories) plt.legend(loc=1) Output

http://stackoverflow.com/a/52552243
has body: Your problem is the following: The MDF constructor needs the full path of the file. But os.listdir() only gives you the filenames. Try adding the path to the dir to your f variable. I got this idea from the MDF source code: def __init__(self, name=None, memory='full', version='4.10', **kwargs): if name: memory = validate_memory_argument(memory) if is_file_like(name): file_stream = name else: if os.path.isfile(name): file_stream = open(name, 'rb') else: raise MdfException('File "{}" does not exist'.format(name)) file_stream.seek(0) like that: i=1 for f in os.listdir('/media/data2/jupyter_notebooks/sacherr/Daten/'): f = '/media/data2/jupyter_notebooks/sacherr/Daten/'+f mdf = MDF(f) df = mdf.export('pandas') print(i) i=i+1
has comment: http://stackoverflow.com/comment/92045955
type: Answer
has comment: http://stackoverflow.com/comment/92045626
has comment: http://stackoverflow.com/comment/92045672
has comment: http://stackoverflow.com/comment/92046277
has comment: http://stackoverflow.com/comment/92046144
has comment: http://stackoverflow.com/comment/92046385
accepted answer of: http://stackoverflow.com/q/52551575
answers question: http://stackoverflow.com/q/52551575
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92046005

http://stackoverflow.com/comment/92084799
score: 1
type: Comment
type: QuestionComment
has text: Your desired functionality will give you the opposite: unlimited ancestor projects.
comment on: http://stackoverflow.com/q/52574349

http://stackoverflow.com/q/52582159
answer count: 1
has body: I ran into the problem, I am new with this kind of usage of Python, I hope some one helps me in this issue. I have a code using RungeKutta algorithm. As I do print(vH), it prints: [70, 98.72259439054349, 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, 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, 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, 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] How could I juts have 98.72259439054349 in out put when I write print(vH)? This is the RungeKutta part of the code and nrk=300. Using nrk we have accurate out put, but with this code as you see we have 300 zeros in output. def rk4(dH_func, H0, A, B, alpha, b, rho_de0, rho_dm0, z0, z1, nrk): if dH_func != False and drho_dm_func != False and drho_de_func != False : vH = [0] * (nrk + 1) h = (z1 - z0) / float(nrk) vH[0] = H = H0 for i in range(1, nrk + 1): k1_H = h * dH_func(z, H, rho_de, rho_dm) k2_H = h * dH_func(z + 0.5 * h, H + 0.5 * k1_H, rho_de + 0.5 * k1_rho_de, rho_dm + 0.5 * k1_rho_dm) k3_H = h * dH_func(z + 0.5 * h, H + 0.5 * k2_H, rho_de + 0.5 * k2_rho_de, rho_dm + 0.5 * k2_rho_dm) k4_H = h * dH_func(z + h, H + k3_H, rho_de + k2_rho_de, rho_dm + k2_rho_dm) vH[i] = H = H + (k1_H + k2_H + k2_H + k3_H + k3_H + k4_H) / 6 return vH
tagged with: arraylist
has comment: http://stackoverflow.com/comment/92099360
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52582189
has comment: http://stackoverflow.com/comment/92099410
tagged with: python
tagged with: runge-kutta
has comment: http://stackoverflow.com/comment/92099355
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52582189
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92099395
tagged with: output
has title: The output is list of numbers instead of one number
type: Question
tagged with: arrays

http://stackoverflow.com/q/52499339
tagged with: pypdf
score: 6
has comment: http://stackoverflow.com/comment/91961560
has comment: http://stackoverflow.com/comment/91962502
has comment: http://stackoverflow.com/comment/91944493
type: AnsweredQuestion
has body: I am trying to modify text in a PDF file. The text can be in an object of type Tj or BDC. I find the correct objects and if I read them directly after changing them they show the updated values. But if I pass the complete page to PdfFileWriter the change is lost. I might be updating a copy and not the real object. I checked the id() and it was different. Does someone have an idea how to fix this? from PyPDF2 import PdfFileReader, PdfFileWriter from PyPDF2.generic import TextStringObject, NameObject, ContentStream from PyPDF2.utils import b_ reader = PdfFileReader("some.pdf") writer = PdfFileWriter() for page_idx in range(0, 1): # Get the current page and it's contents page = reader.getPage(page_idx) content_object = page["/Contents"].getObject() content = ContentStream(content_object, reader) for operands, operator in content.operations: if operator == b_("BDC"): operands[1][NameObject("/Contents")] = TextStringObject("xyz") if operator == b_("Tj"): operands[0] = TextStringObject("xyz") writer.addPage(page) # Write the stream with open("output.pdf", "wb") as fp: writer.write(fp)
linked to: http://stackoverflow.com/q/50306870
has comment: http://stackoverflow.com/comment/91945772
type: Question
has answer: http://stackoverflow.com/a/52587747
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91964701
has comment: http://stackoverflow.com/comment/91963767
linked to: http://stackoverflow.com/q/26529269
tagged with: http://stackoverflow.com/tag/pdf
linked to: http://stackoverflow.com/q/72451312
tagged with: python
upvote count: 6
tagged with: pdf-generation
has comment: http://stackoverflow.com/comment/91943434
has comment: http://stackoverflow.com/comment/91961603
has title: Why does PyPDF2.PdfFileWriter forget changes I made to a document?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52587747

http://stackoverflow.com/comment/91852185
score: 1
has text: Where does the print statement come in your code?
comment on: http://stackoverflow.com/q/52454775
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52460262
score: 0
answers question: http://stackoverflow.com/q/52440606
type: Answer
has body: The problem was with my use of requirements.txt. I created it on my laptop with pip freeze, uploaded it to the VM and used pip to install all the requirements. In this way my requirements.txt included tensorflow. As the result, pip installed the repository version that did not include GPU support, replacing pre-installed tensorflow with GPU support. I was able to figure this out by repeating my steps and checking GPU per second suggestion of @Shintlor (thanks!) along the way. I have created another VM and did not use requirements.txt; rather, I installed all the missing packages one by one. After that my model trains now 20 times faster than on my laptop.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52440606

http://stackoverflow.com/comment/91875025
has text: That's a great idea. I think that what I'll end up doing is splitting my classes into two files: `classes.py` and `classes_async.py`. If they want to use the async versions, they'll have to explicitly import `classes_async` (which will re-implement funcs that should be async), and then just use it with await regularly. So practically what you suggested. That way both files will be relatively thin. Thank you very much, you helped with a big design challenge.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52466625
type: Comment

http://stackoverflow.com/a/52522364
has comment: http://stackoverflow.com/comment/92003086
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/52513365
has comment: http://stackoverflow.com/comment/92012467
has body: You can create a recursive function: d = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],[13, 14, 15]] def create_triplet(nums, original, current = []): if len(current) == 3: yield sorted(current) else: for i in nums: yield from create_triplet(nums, original, current+[i]) _original = [d] def triplets(source, current=[]): if len(current) == len(d): _original.append(current) yield current else: _flattened, seen = [i for b in current for i in b], [] _options = list(create_triplet([i for i in source if i not in current], _original)) for i in _options: if i not in seen and all(all(c not in b for c in i) for b in current) and all(i not in c for c in _original): _test = current+[i] if all(all(sum(h in c for h in i) &lt; 2 for i in _test for c in b) for b in _original): yield from triplets(source, current=_test) seen.append(i) _ = list(triplets([i for b in d for i in b])) print(_original) Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] [[1, 4, 7], [2, 5, 8], [3, 10, 13], [6, 11, 14], [9, 12, 15]] [[1, 5, 9], [2, 4, 10], [3, 6, 15], [7, 11, 13], [8, 12, 14]] [[1, 6, 8], [2, 7, 14], [3, 9, 11], [4, 12, 13], [5, 10, 15]] [[1, 10, 14], [2, 11, 15], [3, 4, 8], [5, 7, 12], [6, 9, 13]]
has comment: http://stackoverflow.com/comment/92012521
upvote count: 2
type: Answer

http://stackoverflow.com/comment/92015488
comment on: http://stackoverflow.com/a/52534376
has text: Welcome :-) @JohnathanBrown
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52526404
answer count: 1
tagged with: selenium-chromedriver
tagged with: selenium
upvote count: 1
type: UnansweredQuestion
has body: This is my first experience with Selenium and HTML. I tried to use IDE and then follow "the way" it indicated. My IDE recorded script says Command | Target ----------------------------------------------- click | css=#hamburger-btn click | css=div.menu-item.menu-item-selected &gt; span.menu-item-title click | css=div.menu-item.menu-item-selected &gt; div.menu-panel-content &gt; div.menu-category-cont &gt; div.menu-category-sub &gt; div.menu-category-sub-item.menu-category-sub-item-selected &gt; span.menu-category-sub-item-title And I tried to implement it this way: browser = webdriver.Chrome() browser.get(url) #url was defined before browser.find_element_by_css_selector("#hamburger-btn").click() browser.find_element_by_css_selector("div.menu-item.menu-item-selected&gt;span.menu-item-title").click() browser.find_element_by_css_selector('div.menu-item.menu-item-selected&gt;div.menu-panel-content&gt;div.menu-category-cont&gt;div.menu-category-sub&gt;div.menu-category-sub-item.menu-category-sub-item-selected&gt;span.menu-category-sub-item-title').click() but I get this "No such element" message/error browser.find_element_by_css_selector('div.menu-item.menu-item-selected&gt;div.menu-panel-content&gt;div.menu-category-cont&gt;div.menu-category-sub&gt;div.menu-category-sub-item.menu-category-sub-item-selected&gt;span.menu-category-sub-item-title').click() File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 597, in find_element_by_css_selector return self.find_element(by=By.CSS_SELECTOR, value=css_selector) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 966, in find_element 'value': value})['value'] File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.…
downvote count: 0
has title: Following Selenium IDE to Python - No such element
has answer: http://stackoverflow.com/a/52526917
score: 1
favorite count: 0
tagged with: selenium-ide
type: Question
tagged with: python

http://stackoverflow.com/comment/137125912
type: AnswerComment
comment on: http://stackoverflow.com/a/77775336
has text: @E.Zeytinci 1) google is a thing. if it moves, you can google. 2) If official docs disappear off the face of the net, there are bigger problems. 3) https://web.archive.org/web/20240109003954/https://cdlib.readthedocs.io/en/v0.2.2/reference/eval/cdlib.evaluation.modularity_overlap.html
score: 0
type: Comment

http://stackoverflow.com/a/52438713
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52438568
answers question: http://stackoverflow.com/q/52438568
type: Answer
has body: If you want a copy of the string, then it can be done using iterators or substr: std::string my_name("InAFlash"); std::string slice = my_name.substr(1, 4); // Note this is start index, count If you want to slice it without creating a new string, then std::string_view (C++17) would be the way to go: std::string_view slice(&my_name[0], 4);
downvote count: 1
upvote count: 3

http://stackoverflow.com/comment/91936842
comment on: http://stackoverflow.com/q/52496532
has text: I need to restore all the widgets to the values as they were saved. And if it is also possible to restore some results. For example, if I have a Spinbox with some value, restore this value. It is posible using external .ini files?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91823257
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52434334
has text: @Martineau thank you for your contribution. I've had a look at your post but I don't really understand how I can transfert it to my problem. Perhaps, using the print method is not the best way to do it ?!
score: 0

http://stackoverflow.com/comment/92103352
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52584237
type: Comment
has text: My question is what if I dont. If I dont then also I am able to access parents method from childs object.

http://stackoverflow.com/comment/91955641
type: QuestionComment
has text: @AldoInáciodaSilva What about without the `app.debug`? I managed to get it running with just the `app.run` call in Jupyter notebook (with Python 2.7). But with `app.debug` I got an error, albeit different from yours.
comment on: http://stackoverflow.com/q/52457582
score: 0
type: Comment

http://stackoverflow.com/comment/92100460
type: Comment
type: QuestionComment
has text: Hi Robin, yeah I realized I changed my question. Please take a look.
comment on: http://stackoverflow.com/q/52582637
score: 0

http://stackoverflow.com/q/52447767
has title: Using pytest_addoptions in a non-root conftest.py
has body: I have a project that has the following structure: Project/ | +-- src/ | | | +-- proj/ | | | +-- __init__.py | +-- code.py | +-- tests/ | | | +-- __init__.py | +-- conftest.py | +-- test_code.py +-- doc/ +-- pytest.ini +-- setup.py The importable package proj lives under the src directory. Tests are installed along with it, in the proj.tests sub-package. The code, the tests themselves, and the installation all work fine. However, I have trouble passing options to the tests. I have an option, --plots, that is defined in conftest.py (under Project/src/proj/tests/), which creates a .plots/ folder in the root folder and places some graphical debugging there: # conftest.py def pytest_addoption(parser): parser.addoption("--plots", action="store_true", default=False) There are two different ways I'd like to have to run this test: The first is from the command line, in the Project directory: $ pytest --plots This fails immediately with usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --plots inifile: /.../Project/pytest.ini rootdir: /.../Project If I add the package directory, the run goes fine: $ pytest src/proj --plots ... rootdir: /.../Project, inifile: pytest.ini ... It also goes well if I specify the tests sub-directory: $ pytest src/proj/tests --plots ... rootdir: /.../Project, inifile: pytest.ini ... The second way is to run the test function of the package itself. The test function is defined in Project/src/proj/__init__.py like this: # __init__.py def test(*args, **kwargs): from pytest import main cmd = ['--pyargs', 'proj.tests'] cmd.extend(args) return main(cmd, **kwargs) The function is intended to be run after Project is installed like this: >>> import proj >>> proj.test() Generally, this works OK, but if I do >>> proj.test('--plots') I get the same error as usual: usage: [options] [file_or_dir] [file_or_dir] [...] : error: unrecognized arguments: --plots inifile: None rootdir: /some/other/folder For this test, I r…
has answer: http://stackoverflow.com/a/52458082
type: Question
tagged with: testing
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52458082
favorite count: 0
upvote count: 8
downvote count: 1
type: AnsweredQuestion
tagged with: pytest
score: 7

http://stackoverflow.com/comment/91880951
comment on: http://stackoverflow.com/q/52469491
has text: Imagine you want to write the word "banana", but you want to do it really fast, so you hire 3 people to divide the work of writing the letters between them. It's not going to go any faster than doing it yourself; there's too little work and too much contention. One person's probably going to write all 6 letters, and if they don't, it's probably going to take even longer than if they did.
type: Comment
score: 1
type: QuestionComment

import
tags question: http://stackoverflow.com/q/52576230
type: Tag
tags question: http://stackoverflow.com/q/52519022
tags question: http://stackoverflow.com/q/52436626
tags question: http://stackoverflow.com/q/52437746
tag name: import
tags question: http://stackoverflow.com/q/52522770
tags question: http://stackoverflow.com/q/52538252
tags question: http://stackoverflow.com/q/52562454
tags question: http://stackoverflow.com/q/52571832
tags question: http://stackoverflow.com/q/52551661
tags question: http://stackoverflow.com/q/52519910
tags question: http://stackoverflow.com/q/52439437
tags question: http://stackoverflow.com/q/52524396
tags question: http://stackoverflow.com/q/52588463
tags question: http://stackoverflow.com/q/52584676
tags question: http://stackoverflow.com/q/52460980
tags question: http://stackoverflow.com/q/52466092
tags question: http://stackoverflow.com/q/52520894
tags question: http://stackoverflow.com/q/52462548

http://stackoverflow.com/comment/92031143
type: AnswerComment
type: Comment
has text: Unfortunately, G.Anderson - these recommendations did not work. Thanks.
comment on: http://stackoverflow.com/a/52542429
score: 0

http://stackoverflow.com/comment/91872963
type: Comment
has text: Sorry I didn't make it clear, Code is running without any error, I have few columns with CSV values it should not get delimit . . . Out of 22 columns, i want only 3 columns with CSV to be delimited. . So is there any way to restrict delimitation to only 3 columns?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52465339

http://stackoverflow.com/a/52460133
has body: You can see middleware as a list of implicit decorators around every view. In short, middelware is thus used for pre-processing requests, and post-processing responses. It can also be used for example to perform diagnostics (measure the time between a request and a response). Before a HttpRequest is processed by a specific view, and before the HttpResponse the view generates is sent to the client, middleware (can) interact with the request, or post-process the response. A common example is an authentication system. By default this is middleware that is put in the MIDDLEWARE list in the settings. You probably frequently do something with request.user, but where does that attribute originates from? It is added to the request by django.contrib.auth.middleware.AuthenticationMiddleware [GitHub]: class AuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE%s setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) % ("_CLASSES" if settings.MIDDLEWARE is None else "") request.user = SimpleLazyObject(lambda: get_user(request)) As you can see, it patches the request, by adding an attribute: request.user = .... Without this middelware, a HttpRequest will not carry a (lazily fetched) user. Another example of middleware could be a system that measures how long every view takes, and logs this to the console: when fetching the request, it for example attaches a timestamp to the request before it enters the view, and when it obtains the response, it looks how much time has passed. Post-processing responses is possible as well. Imagine that you each time want to set a certain cookie in the HTTP response, then again middleware is definitely a good idea. You could for example implement middleware that keeps track on how many tim…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52460030
type: Answer
answers question: http://stackoverflow.com/q/52460030
score: 0

http://stackoverflow.com/a/52469494
type: Answer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/52461970
answers question: http://stackoverflow.com/q/52461970
type: AcceptedAnswer
has body: You are at that point out of Python territory. os.execv() ultimately caused execve(2) syscall to be made and as its man page states: All process attributes are preserved during an execve(), except the following: The dispositions of any signals that are being caught are reset to the default (signal(7)). ... Which does make sense, you shouldn't really want to run some new code while having old handlers registered for it (and no idea how that could even work since handlers would also be replaced). If you implemented cat-like behavior in python and did not execve a new process, it would have (more or less) worked the way you expected: import signal import time import os import sys import multiprocessing as mp def handler(signal, frame): print "Alarmed" os.system('echo Alarmed &gt;&gt; /tmp/log_alarm') sys.exit(0) def launch(): signal.signal(signal.SIGALRM, handler) signal.alarm(5) print "Process launched" stdin = os.fdopen(0) stdout = os.fdopen(1, 'w') line = stdin.readline() while line: stdout.write(line) line = stdin.readline() print "You may end here if EOF was reached before being alarmed." p = mp.Process(target=launch) p.start() print "Process started" p.join() Note: I've just hard coded handling of stdin/stdout in the child process. And since you've mentioned python 2.7 I've avoided using for line in stdin:.
upvote count: 3

gdal
tags question: http://stackoverflow.com/q/52530200
tag name: gdal
tags question: http://stackoverflow.com/q/52438313
tags question: http://stackoverflow.com/q/52455187
tags question: http://stackoverflow.com/q/52563621
tags question: http://stackoverflow.com/q/52443906
tags question: http://stackoverflow.com/q/52550415
type: Tag

http://stackoverflow.com/comment/111198413
type: Comment
comment on: http://stackoverflow.com/a/55750128
has text: I wonder if your comment of storage efficiency only applies to `np.save` or it also applies to `np.savez`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92056840
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52559131
has text: How are you reading the data?

http://stackoverflow.com/comment/91956542
comment on: http://stackoverflow.com/a/52468667
has text: @bit-by-bit [pprint](https://docs.python.org/3/library/pprint.html#pprint.pprint) is fairly primitive. It's intended to give pretty output to programmers, not for output to display to the user. You have some control over how it formats stuff, but not a lot. Try reducing the `width` arg & see what it does. For data like this you can often get much nicer output using `json.dumps`, although because it creates JSON output it does some conversions that you may not want, eg it converts `None` to `null`, and it converts numeric keys to strings.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92055689
has text: Thanks, CristiFati for help, it works now.
score: 0
comment on: http://stackoverflow.com/q/52539262
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91830778
type: AnswerComment
comment on: http://stackoverflow.com/a/52443969
type: Comment
score: 0
has text: just noticed. not the heart of the problem but okay:)

http://stackoverflow.com/a/52545091
has comment: http://stackoverflow.com/comment/121454463
score: 20
has comment: http://stackoverflow.com/comment/127586453
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/121455087
accepted answer of: http://stackoverflow.com/q/52544935
type: Answer
answers question: http://stackoverflow.com/q/52544935
has body: You're going down the wrong path. Instead of trying to unseed the global RNG used by numpy.random, use a separate RNG for the parts that need to be repeatable. This RNG can have a completely independent state from the numpy.random default RNG: def test(): rng = numpy.random.RandomState(2) print("Repeatable test:", [rng.randint(10) for i in range(3)]) While it is technically possible to save and restore the state of the global numpy.random RNG, it is a very specialized operation and rarely a good idea. It may be useful, for example, if you're debugging a piece of code and you want to "rewind" the random state after jumping backward through the code, though you need to save the state in advance, and it won't rewind any other random number generators: # Don't abuse this. state = numpy.random.get_state() do_stuff() numpy.random.set_state(state)
upvote count: 20

http://stackoverflow.com/comment/91844145
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52450506
type: Comment
has text: It's worth noting that JSON will not accept ints as keys. They automatically get converted to strings. Bitten by that before :)

http://stackoverflow.com/q/52500359
answer count: 3
has title: how to store a appended list into a .txt file in python
has comment: http://stackoverflow.com/comment/91941426
upvote count: 0
has comment: http://stackoverflow.com/comment/91942013
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/52500643
tagged with: list
tagged with: file
has comment: http://stackoverflow.com/comment/91941363
type: Question
has answer: http://stackoverflow.com/a/52500627
has answer: http://stackoverflow.com/a/52500431
has body: I have a list which is a list of appended items if words[0] == "[" or words[len(words)-1] == "]": if words in combinations1: line.append(words) when i try to put this list into a single file i am able to get only the last item in the list. my code to write this into a file is : with open("file.txt", "w") as output_file: output_file.write(str(line)) I need to write all the list items into the file. How to do it

http://stackoverflow.com/comment/91850130
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52453540
has text: Oh okay... thanks for the information. I was simply following what tensorflow folks are doing... Btw `np.asarray(pil_image)` is super fast... takes only 1ms...

http://stackoverflow.com/comment/92317416
type: Comment
has text: @Angela it is quite a simple foreign key: `source = models.ForeignKey('broadcast.Platform', models.PROTECT, related_name='bookings', verbose_name=_("source"))`
comment on: http://stackoverflow.com/q/52575054
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91955175
score: 0
type: AnswerComment
type: Comment
has text: that worked! wondering why this doesnt work: `df['concat'] = pd.Series(df.dropna(axis=1).values.tolist()).str.join(',')`
comment on: http://stackoverflow.com/a/52507332

http://stackoverflow.com/a/52572471
has comment: http://stackoverflow.com/comment/92081743
type: AcceptedAnswer
has body: Here is a corrected working version of what you want import math p = input("Enter type of polyhedral: ") a = float(input("Enter the value of a: ")) if p == 'T': volume =(math.sqrt(2) / 12) * (a ** 3) elif p == 'C': volume = a**3 elif p == 'O': volume = (math.sqrt(2) / 3) * (a ** 3) elif p == 'D': volume = (15 + 7 * math.sqrt(5)) / 4 * (a ** 3) elif p == 'I': volume = 5 * (3 + math.sqrt(5)) / 12 * (a ** 3) else: print('Polyèdre non connu') volume = "Not Yet Defined" print ("The volume of p=%s is %s" %(p, volume)) Sample output Enter type of polyhedral: O Enter the value of a: 12.45 The volume of p=O is 909.71 Enter type of polyhedral: K Enter the value of a: 12 Polyèdre non connu The volume of p=K is Not Yet Defined
has comment: http://stackoverflow.com/comment/92081801
has comment: http://stackoverflow.com/comment/92081570
type: Answer
has comment: http://stackoverflow.com/comment/92081492
has comment: http://stackoverflow.com/comment/92081776
has comment: http://stackoverflow.com/comment/92081840
has comment: http://stackoverflow.com/comment/92081533
has comment: http://stackoverflow.com/comment/92081710
has comment: http://stackoverflow.com/comment/92081693
has comment: http://stackoverflow.com/comment/92081883
has comment: http://stackoverflow.com/comment/92081755
has comment: http://stackoverflow.com/comment/92081702
accepted answer of: http://stackoverflow.com/q/52572412
has comment: http://stackoverflow.com/comment/92081789
score: 0
answers question: http://stackoverflow.com/q/52572412
has comment: http://stackoverflow.com/comment/92081940

confusion-matrix
tags question: http://stackoverflow.com/q/52508359
tag name: confusion-matrix
type: Tag

http://stackoverflow.com/q/52547846
has body: I am trying to break up a string with multiple lists inside them with different formatting. What is the best way to do this? string = "something here: 1) A i) great ii) awesome 2) B" another_string = "But sometimes it is different (1) yep (2) not the same i. or this ii. another bullet (3.1) getting difficult huh? 3.1.1 okay i'm done" Ideally, I would want to be able to split any possible numbering or bullet list. Desired output for string: something here: 1) A i) great ii) awesome 2) B Desired output for another_string: But sometimes it is different (1) yep (2) not the same i. or this ii. another bullet (3.1) getting difficult huh? 3.1.1 okay i'm done
type: AnsweredQuestion
score: 1
downvote count: 1
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/92035034
has comment: http://stackoverflow.com/comment/92035394
has comment: http://stackoverflow.com/comment/92035484
has comment: http://stackoverflow.com/comment/92035156
has answer: http://stackoverflow.com/a/52548143
accepted answer: http://stackoverflow.com/a/52548143
answer count: 1
linked to: http://stackoverflow.com/q/46331543
favorite count: 0
has comment: http://stackoverflow.com/comment/92035225
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/267399
tagged with: regex
has comment: http://stackoverflow.com/comment/92035014
has comment: http://stackoverflow.com/comment/92035237
has title: What is the best way to split a string containing lists of numbers, roman numbers, and bullets?

http://stackoverflow.com/comment/92066091
comment on: http://stackoverflow.com/q/52563757
score: 3
has text: You can do this with just a plain SQL INSERT statement. No need for python.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52445621
has comment: http://stackoverflow.com/comment/91834081
answer count: 1
has answer: http://stackoverflow.com/a/52445820
tagged with: list
downvote count: 3
score: -3
tagged with: substring
upvote count: 0
linked to: http://stackoverflow.com/q/22214086
type: UnansweredQuestion
has title: How to check for consecutive repeating characters in a string
has body: I'm trying to figure out how to check if certain characters are repeated after each other in a single string, and if so, how often are they repeated. Example: str.x = 'abbbjjaaaal' As the return I need the integer 4, as in this case the longest consecutive repetition of a single character in the string x is a, and it is repeated 4 times.
tagged with: python
favorite count: 0
duplicate of: http://stackoverflow.com/q/22214086
type: Question

http://stackoverflow.com/q/52488247
tagged with: gstreamer
has title: Creating gstreamer uridecodebin element inside loop with videomixer
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 2
type: Question
downvote count: 0
has body: So the problem I'm trying to solve is to take an unknown of incoming URI streams and mix them into one outgoing stream. What I am essentially doing right now is using a for each loop where each iteration I create a source, add in elements like videoscale and the capsfilter, and then link it to the videomixer. Currently I have it working if I just pass in a usb webcam feed with autovideosrc. However, it completely falls apart when I try to use a uridecodebin, due to linking errors. I know that normally when creating a uridecodebin you have to use the pad-added signal with something like this example. #!/usr/bin/python import pygst pygst.require('0.10') import gst import pygtk pygtk.require('2.0') import gtk # this is very important, without this, callbacks from gstreamer thread # will messed our program up gtk.gdk.threads_init() def on_new_decoded_pad(dbin, pad, islast): decode = pad.get_parent() pipeline = decode.get_parent() convert = pipeline.get_by_name('convert') decode.link(convert) pipeline.set_state(gst.STATE_PLAYING) print "linked!" def main(): pipeline = gst.Pipeline('pipleline') filesrc = gst.element_factory_make("filesrc", "filesrc") filesrc.set_property('location', 'C:/a.mp3') decode = gst.element_factory_make("decodebin", "decode") convert = gst.element_factory_make('audioconvert', 'convert') sink = gst.element_factory_make("autoaudiosink", "sink") pipeline.add(filesrc, decode, convert, sink) gst.element_link_many(filesrc, decode) gst.element_link_many(convert, sink) decode.connect("new-decoded-pad", on_new_decoded_pad) pipeline.set_state(gst.STATE_PAUSED) gtk.main() main() However, every example of this that I have found has been assuming that I would always be connecting one uridecodebin to one other element. How would I go about implementing something where the element represented by 'convert' in this example would be different each time I call the function?
tagged with: python
favorite count: 0

http://stackoverflow.com/a/52506060
has body: Yes sets contain unique elements and are much faster for comparisons like checking if an item exists than lists for example. As well as having lots of other nice properties. so another example would be set([1,1,1,2,3]) returns {1,2,3} the unique items. One thing to note is that sets are not ordered like lists, which has both positives and negatives
score: 0
answers question: http://stackoverflow.com/q/52506042
type: Answer

http://stackoverflow.com/comment/92071040
type: AnswerComment
type: Comment
has text: but you still get user unchanged? can you `print(request.data, user_serializer.validated_data)` inside `if user_serializer.is_valid()` and post it to question
comment on: http://stackoverflow.com/a/52566767
score: 0

http://stackoverflow.com/q/52544562
has title: Urllib returning html but no closing paragraph tags
score: 1
has answer: http://stackoverflow.com/a/52560362
favorite count: 0
has comment: http://stackoverflow.com/comment/92059115
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/92059264
accepted answer: http://stackoverflow.com/a/52560362
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/92029305
tagged with: urllib
type: AnsweredQuestion
type: Question
has body: I am scraping the Presidential debate transcripts. I noticed that when my scraper pulls the html elements it never pulls a paragraph-end tag (&lt;/p&gt;). eg Checking the source in browser url_to_scrape = 'http://www.presidency.ucsb.edu/ws/index.php?pid=119039' req = urllib.request.Request(url_to_scrape) resp = urllib.request.urlopen(req) resp.read() I figure there are one of two things going on: urllib is somehow dropping closing tags (for just paragraphs, the rest are fine) The raw source doesn't include closing tags, and the browser is filling them in. How do I figure out which one it is, and then correct for it?
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52545447
type: Answer
has comment: http://stackoverflow.com/comment/92053664
score: 2
has body: The solution you want here is a Lambda function triggered by a S3 event notification. https://docs.aws.amazon.com/lambda/latest/dg/with-s3.html The idea is that whenever a new object is uploaded to your S3, it will trigger this Lambda function you define(e.g., do your ELT, cleanup and more...) This is more like a 'push' style workflow so that you don't need to worry about comparing. An S3 event notification allows you to define a rule that filter on a prefix and/or a suffix of object name and add event trigger to them. https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html
answers question: http://stackoverflow.com/q/52545067
has comment: http://stackoverflow.com/comment/92030858
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/52495111
score: 12
type: Answer
has comment: http://stackoverflow.com/comment/91935736
upvote count: 14
downvote count: 2
answers question: http://stackoverflow.com/q/52494128
has body: although ** is definitely a language feature, it's surely not created for solving this particular problem. Your suggestion works, so does mine. Which one works better depends on the rest of the OP's code. However, there is still no way to write f(x or dont_pass_it_at_all) - blue_note Thanks to your great answers, I thought I'd try to do just that: # gen.py def callWithNonNoneArgs(f, *args, **kwargs): kwargsNotNone = {k: v for k, v in kwargs.items() if v is not None} return f(*args, **kwargsNotNone) # python interpreter &gt;&gt;&gt; import gen &gt;&gt;&gt; def alpha(p1="foo", p2="bar"): ... print('{0},{1}'.format(p1,p2)) ... &gt;&gt;&gt; gen.callWithNonNoneArgs(alpha, p1="FOO", p2=None) FOO,bar &gt;&gt;&gt; def beta(ree, p1="foo", p2="bar"): ... print('{0},{1},{2}'.format(ree,p1,p2)) ... &gt;&gt;&gt; beta('hello', p2="world") hello,foo,world &gt;&gt;&gt; beta('hello', p2=None) hello,foo,None &gt;&gt;&gt; gen.callWithNonNoneArgs(beta, 'hello', p2=None) hello,foo,bar This is probably not perfect, but it seems to work: It's a function that you can call with another function and it's arguments, and it applies deceze's answer to filter out the arguments that are None.

http://stackoverflow.com/q/52536056
has answer: http://stackoverflow.com/a/52561234
upvote count: 0
type: UnansweredQuestion
score: -3
has body: I have a list (in Excel) of the names of several companies. When I run a Google search on the "company name" and "address", I get the address as the first result in a box. I would like to get this result in the cell opposite to each company name. Could someone please help me with the script and the right packages to run the search and scrape the first result into excel?
tagged with: vba
favorite count: 0
has title: Google search using python and scrape first result
type: Question
tagged with: python
answer count: 1
tagged with: excel
tagged with: selenium
downvote count: 3
tagged with: web-scraping

http://stackoverflow.com/comment/92034567
score: 1
comment on: http://stackoverflow.com/a/52498748
type: AnswerComment
has text: this worked thanks man
type: Comment

http://stackoverflow.com/comment/91996982
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52528048
type: Comment
has text: `a['date'][0]` and `a['date'][1]` throw KeyErrors since `a` is a dataframe with only one index: 2. It kept that index from the original dataframe, df. Now `a['date']` makes a series (it converts the column 'date' into a series, and keeps the original index). Thus the series will have only one index: 2.

http://stackoverflow.com/comment/91872044
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52465131
has text: @Aran-Fey Thanks a lot, that fixed it! I wasn't aware enough while writing it...
score: 0

http://stackoverflow.com/a/52432309
score: 0
has body: While it may not be a 'good' idea in general, it could be a good idea for you. If you create a script in a folder with your imports and import that as a module elsewhere, you can import the other modules with it. The syntax would be from my_convenience_imports import *
answers question: http://stackoverflow.com/q/52432042
type: Answer

http://stackoverflow.com/a/52584887
answers question: http://stackoverflow.com/q/52584656
has comment: http://stackoverflow.com/comment/92104720
type: Answer
upvote count: 0
score: -2
has body: Simply Use list.sort() function to arrange the numbers in ascending/descending order. For more information help(list.sort()) in your ipython notebook
downvote count: 2

http://stackoverflow.com/a/52582964
score: 0
type: Answer
has body: If the name is too big(over 6 char) the tab will be moved one more down. You can either check if the name is too big and move it down own tab.By using something like numTabs = '\t' * (2-len(last_name)//6 Or a better approach would use something like str.format as mentioned by @Michael Butscher in the comments.
answers question: http://stackoverflow.com/q/52582853

http://stackoverflow.com/a/52549732
type: Answer
has comment: http://stackoverflow.com/comment/92248795
accepted answer of: http://stackoverflow.com/q/52549113
has comment: http://stackoverflow.com/comment/92257606
answers question: http://stackoverflow.com/q/52549113
has comment: http://stackoverflow.com/comment/92041313
has comment: http://stackoverflow.com/comment/92253237
has comment: http://stackoverflow.com/comment/92254698
has body: You need to have a separate collections.Counter for each word. This code uses defaultdict to create a dictionary of counters, without checking every word to see if it is known. from collections import Counter, defaultdict counts = defaultdict(Counter) for row in file: # read one line into `row` if not row.strip(): continue # ignore empty lines pos, word, tag = row.split() counts[word.lower()][tag] += 1 That's it, you can now check the most common tag of any word: print(counts["food"].most_common(1)) # Prints [("NN", 3)] or whatever
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/92253378
has comment: http://stackoverflow.com/comment/92252219
has comment: http://stackoverflow.com/comment/92038623

http://stackoverflow.com/comment/92130930
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52584609
has text: The idea is not to hard code the response. For example, the STUDENTNUM value might change, depends on the student number I enter (in yaml). As long the header has values, I can assume the student number I put is a valid student number.

gmail
type: Tag
tags question: http://stackoverflow.com/q/52503056
tags question: http://stackoverflow.com/q/52480275
tag name: gmail
tags question: http://stackoverflow.com/q/52438533

http://stackoverflow.com/comment/91951919
score: 6
type: Comment
comment on: http://stackoverflow.com/q/52505696
type: QuestionComment
has text: Option 3. Definitely option 3. Neither of the two options you posted is good.

http://stackoverflow.com/comment/91966829
type: QuestionComment
has text: I added the answer to the above comment. Or see Piotrek's answer
comment on: http://stackoverflow.com/q/52513495
score: 0
type: Comment

http://stackoverflow.com/a/52524798
answers question: http://stackoverflow.com/q/52524716
type: Answer
score: 0
has body: Cant you just: SELECT * FROM transactions WHERE id = :user_id and shares &gt; 0 ORDER BY transaction_id ASC to get shares they own, and then shares &lt; 0 to get shares they've sold?

http://stackoverflow.com/a/52440032
score: 1
has body: Because there are two spaces between the div classes (geodir_more_info and post_address). Input: response.xpath('//div[@class="geodir_more_info post_address"]/span[@itemprop]/text()').extract() Output: [u'Chennai', u'Chennai', u'Tamil Nadu', u'India']
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52439718
accepted answer of: http://stackoverflow.com/q/52439718
type: Answer
downvote count: 0

http://stackoverflow.com/comment/92085159
score: 1
comment on: http://stackoverflow.com/q/52574557
has text: U have provided 2 sample examples but both are different one is a list that has only one tuple and in another one only list is input? So input can be of which type???? Your both sample examples have different set of input and output??????
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52573623
has title: How to change an element from string to float in a nested list
has answer: http://stackoverflow.com/a/52573663
score: 0
answer count: 3
tagged with: string
has answer: http://stackoverflow.com/a/52583390
has comment: http://stackoverflow.com/comment/92083478
has comment: http://stackoverflow.com/comment/92083471
has body: I want to use list comprehension to change an element within a nested list to float. lines = [[1, '74.37000326528938', 'Psychologist'], [2, '67.49686206937491', 'Psychologist'], [3, '74.92356434760966', 'Psychologist']] &gt;&gt;&gt; lines = [[line[0]] + [float(x) for x in line[1]] + [line[2]] for line in lines] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: could not convert string to float: . I also don't understand why this would work for a different example: mylist = [['1','2','3'],['5','6','7']] datl3 = [[int(x) for x in line[0]] + line[1:] for line in mylist] datl4 = [[line[0]] + [float(x) for x in line[1]] + [line[2]] for line in datl3] &gt;&gt;&gt; datl4 [[1, 2.0, '3'], [5, 6.0, '7']] I think it has to do with decimal points, because the code won't work for this example: mylist = [['1','2.555','3'],['5','6.777','7']] datl3 = [[int(x) for x in line[0]] + line[1:] for line in mylist] datl4 = [[line[0]] + [float(x) for x in line[1]] + [line[2]] for line in datl3] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: could not convert string to float: .
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52573651
accepted answer: http://stackoverflow.com/a/52573651
has comment: http://stackoverflow.com/comment/92083452
type: Question
possible better answer: http://stackoverflow.com/a/52573663

http://stackoverflow.com/comment/91847379
score: 2
has text: what do you mean "long time compared to". please be more detailed about the benchmark results.
comment on: http://stackoverflow.com/q/52452007
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52471380
has answer: http://stackoverflow.com/a/52475826
has comment: http://stackoverflow.com/comment/91885913
tagged with: tkinter
has title: How do I print value of tk slider every time it is updated?
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91889347
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5767228
has comment: http://stackoverflow.com/comment/91885036
downvote count: 0
score: 1
favorite count: 0
type: Question
has body: I have a tk slider in my python program and I am trying to get its value every time I move it. Program does read out the initial value of the slider, but that is all that gets read out. Here is my code: valuelist[50, 100, 150, 200] class MainApp(Frame): def valuecheck(val, self, scale): scalepic = scale print scalepic.get() def createControls(self): scalepic = Scale(self, from_=min(valuelist), to=max(valuelist), resolution = 25, orient=HORIZONTAL) scalepic.set(100) scalepic.configure(command = self.valuecheck(val, scalepic)) scalepic.pack() def __init__(self, parent): Frame.__init__(self, parent, width = 800, height = 600) self.pack() self.createControls() I tried adding this to the body of valuecheck: newval = min(valueList, key=lambda x:abs(x-float(val))) scalepic.set(newval) print newval and got rid of resolution option when defining scalepic. I also tried passing scalepic.get() as an argument for val. I also tried removing val as an argument in valuecheck What else should I try?
tagged with: python

http://stackoverflow.com/q/52557263
tagged with: kaggle
tagged with: python
tagged with: artificial-intelligence
upvote count: 0
has title: Kaggle airbus ship detection challenge.How to deal with class imbalance?
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/52560147
has body: My model always predict under probability 0.5 for all pixels. I dropped all images without ships and have tried focal loss,iou loss,weighted loss to deal with imbalance . But the result is same.After few batches the masks i predicted gradually became all zeros. Here is my notebook: enter link description here Kaggle discussion:enter link description here In the notebook , basically what i did is : （1）discard all samples where there is no ship （2）build a plain u-net （3）define three custom loss function(iouloss,focal_binarycrossentropy,biased_crossentropy), all of which i have tried. （4）train and submit #define different losses to try def iouloss(y_true,y_pred): intersection = K.sum(y_true * y_pred, axis=-1) sum_ = K.sum(y_true + y_pred, axis=-1) jac = intersection / (sum_ - intersection) return 1 - jac def focal_binarycrossentropy(y_true,y_pred): #focal loss with gamma 8 t1=K.binary_crossentropy(y_true, y_pred) t2=tf.where(tf.equal(y_true,0),t1*(y_pred**8),t1*((1-y_pred)**8)) return t2 def biased_crossentropy(y_true,y_pred): #apply 1000 times heavier punishment to ship pixels t1=K.binary_crossentropy(y_true, y_pred) t2=tf.where(tf.equal(y_true,0),t1*1000,t1) return t2 ... #try different loss function unet.compile(loss=iouloss, optimizer="adam", metrics=[ioumetric]) or unet.compile(loss=focal_binarycrossentropy, optimizer="adam", metrics=[ioumetric]) or unet.compile(loss=biased_crossentropy, optimizer="adam", metrics=[ioumetric]) ... #start training unet.train_on_batch(x=image_batch,y=mask_batch)
type: Question
score: -1
has answer: http://stackoverflow.com/a/52557796
answer count: 2
downvote count: 1
tagged with: keras
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52452978
has title: Cannot understand how is a function looped without loop function in python while finding factorial number
score: 0
has body: def factorial(num): if num == 0: return 1 return num * factorial(num-1) print('Enter an integer') num = int(input()) print(factorial(num) If I input number 4, output is 24. Inside the above code block, I cannot understand line 4. Though there isn't any loop, how does that function multiply all the numbers under a given number and returns the value that we expected?
answer count: 1
tagged with: factorial
tagged with: python
has comment: http://stackoverflow.com/comment/91849153
tagged with: recursion
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52453005
accepted answer: http://stackoverflow.com/a/52453005

http://stackoverflow.com/q/52495198
tagged with: parsing
accepted answer: http://stackoverflow.com/a/52495399
type: AnsweredQuestion
tagged with: django
type: Question
tagged with: object
has body: How can we parse json array of objects in python. I have the ff code below in getting the data. How to parse it where in we can load the p_id and item_name on the tempalte select option value ? products = requests.get('http://123.89.166.42:803/api/1.0/data', headers=headers).json() context['products'] = products template : &lt;select&gt; {% for product in products.result %} &lt;option value="{{ product.p_id }}"&gt;{{ product.item_name }}&lt;/option&gt; {% endfor %} &lt;/select&gt; Data : http://dpaste.com/0BHS9TP
tagged with: http://stackoverflow.com/tag/json
score: 0
has answer: http://stackoverflow.com/a/52495399
answer count: 1
has title: How to parse JSON Array of objects in python and load it to template?
linked to: http://stackoverflow.com/q/8000022
has comment: http://stackoverflow.com/comment/91930914
tagged with: python

http://stackoverflow.com/a/52563975
answers question: http://stackoverflow.com/q/52563116
type: Answer
has body: You need to replace two_weeks_ago = now - timedelta(days=0) this line to two_weeks_ago = now - dt.timedelta(days=0) or change the way you are importing datetime and timedelta.
score: 0
accepted answer of: http://stackoverflow.com/q/52563116
type: AcceptedAnswer

http://stackoverflow.com/comment/91813387
type: QuestionComment
has text: Recommendations for renaming the title are very welcome..
comment on: http://stackoverflow.com/q/52434946
score: 0
type: Comment

http://stackoverflow.com/a/52528114
has comment: http://stackoverflow.com/comment/91996032
answers question: http://stackoverflow.com/q/52527995
accepted answer of: http://stackoverflow.com/q/52527995
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91996059
has comment: http://stackoverflow.com/comment/91995923
has comment: http://stackoverflow.com/comment/91995940
has comment: http://stackoverflow.com/comment/91996011
type: AcceptedAnswer
downvote count: 0
has body: In Qt there is a basic rule: the QWidget children are drawn with respect to the parent QWidget, and if it does not have a parent this will be a window, which is called top-level. Another concept is QPushButton, QLabel, QSpinBox, etc. are QWidgets since they inherit from this class. So, since QPushButton does not have a parent, it should show itself as a window, and for that you should use show(): def start(self): [w.show() for name, w in self.widgets.items()] [button.show() for name, button in self.buttons.items()] [label.show() for name, label in self.labels.items()] sys.exit(self.app.exec_()) If your intention is that some QLabel or QPushButton be part of some QWidget then we must indicate that widget as parent, for example in my next solution I propose to add the name of the widget, and if the widget does not exist it should be created: import sys from PyQt4 import QtGui class Graphics: def __init__(self): self.app=QtGui.QApplication(sys.argv) self.widgets={} self.labels={} self.buttons={} def getApp(self): return self.app def newWidget(self, name:str): w = QtGui.QWidget() self.widgets[name] = w return w def addButton(self, widget_name:str, name:str, text:str): if widget_name in self.widgets: w = self.widgets[widget_name] else: w = self.newWidget(widget_name) button = QtGui.QPushButton(text, parent=w) self.buttons[name] = button return button def addLabel(self, widget_name:str, name:str, text:str): if widget_name in self.widgets: w = self.widgets[widget_name] else: w = self.newWidget(widget_name) label = QtGui.QLabel(text, parent=w) self.labels[name] = label return label def start(self): [w.show() for name, w in self.widgets.items()] sys.exit(self.app.exec_()) If you want to add a parent after the button is created then you can use setParent(): graphics.py import sys from PyQt4 import QtGui class Graphics: def __init__(self): self.app=QtGui.QApplication(sys.argv) self.widgets={} self.labels={} self.buttons={} def getApp(self): return self.app def newWidget(self, …
has comment: http://stackoverflow.com/comment/91996050
has comment: http://stackoverflow.com/comment/91999625
has comment: http://stackoverflow.com/comment/91999389
type: Answer
has comment: http://stackoverflow.com/comment/91996100

http://stackoverflow.com/comment/91822540
has text: Sorry, didnt get your point. Could you please elaborate it a bit. Furthermore: do you have a solution?
type: Comment
comment on: http://stackoverflow.com/q/52439904
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92008066
has text: if columns names atleast have some specific words name , address in common, you can try of using regex in segregating as individual @kaundinya5
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52512861
type: Comment

http://stackoverflow.com/q/52527255
tagged with: python
has title: How to I pass my file into the top function to split it?
has answer: http://stackoverflow.com/a/52527275
type: Question
answer count: 1
score: 0
has body: my program is supposed to make a list of the count of each word in a file. I am trying to pass my file into the first function to remove all punctuation.. how can I make my file into a string to do this? Thanks. #def extract_words(string): """Returns a list containing each word in the string, ignoring #punctuation, numbers, etc.""" l = [] word = '' for c in string+' ': if c.isalpha(): word += c else: if word != '': l.append(word.lower()) word = '' return l #def count_words(filename): """Returns a dictionary containing the number of occurrences of each #word in the file.""" # create a dictionary mydict = {} # open the file and read the text with open(filename, 'r') as myfile: # extract each word in the file # count the number of times each work occurs. for i in myfile.read().split(): if i in mydict.keys(): mydict[i] += 1 else: mydict[i] = 1 # return the dictionary with the word count. return mydict
type: UnansweredQuestion

http://stackoverflow.com/a/52546327
has body: The answer in dyld: Library not loaded ... Reason: Image not loaded pointed me into the right direction, suggesting to rewrite the dynamic library paths using otool. Listing all libraries loaded by _hou.so, shows the following list, with @rpath/Houdini.framework/Versions/16.5.571/Houdini being the one that causes the issue. otool -L /Applications/Houdini/Houdini16.5.571/Frameworks/Houdini.framework/Versions/Current/Resources/houdini/python2.7libs/_hou.so /Applications/Houdini/Houdini16.5.571/Frameworks/Houdini.framework/Versions/Current/Resources/houdini/python2.7libs/_hou.so: @rpath/Houdini.framework/Versions/16.5.571/Houdini (compatibility version 1.0.0, current version 16.5.255) /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation (compatibility version 300.0.0, current version 1443.14.0) /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0, current version 275.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0) /System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa (compatibility version 1.0.0, current version 22.0.0) /System/Library/Frameworks/QTKit.framework/Versions/A/QTKit (compatibility version 1.0.0, current version 1.0.0) /System/Library/Frameworks/OpenCL.framework/Versions/A/OpenCL (compatibility version 1.0.0, current version 1.0.0) /System/Library/Frameworks/AudioToolbox.framework/Versions/A/AudioToolbox (compatibility version 1.0.0, current version 492.0.0) /System/Library/Frameworks/OpenGL.framework/Versions/A/OpenGL (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0) Rewriting the path can be done using install_name_tool -change. install_name_tool -change @rpath/Houdini.framework/Versions/16.5.571/Houdini /Applications/Houdini/Houdini16.5.571/Frameworks/Houdini.framework/Versions/16.5.571/Houdini /Applications/Houdini/Houdini16.5.571/Frameworks/Houdini.framework/Versions/Current…
type: Answer
accepted answer of: http://stackoverflow.com/q/52540606
upvote count: 1
answers question: http://stackoverflow.com/q/52540606
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92038820
type: AnswerComment
has text: The error does not necessarily occur because you're putting `new_ordered_parkstop_dict.pop(key)` in a conditional block, so with a different input it may or may not trigger the error by satisfying or not satisfying the condition.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52549728

forms
tags question: http://stackoverflow.com/q/52441203
tags question: http://stackoverflow.com/q/52495354
type: Tag
tags question: http://stackoverflow.com/q/52501470
tags question: http://stackoverflow.com/q/52431362
tag name: forms
tags question: http://stackoverflow.com/q/52521109

http://stackoverflow.com/q/52438198
upvote count: 5
possible better answer: http://stackoverflow.com/a/52445041
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/91819856
downvote count: 0
has title: Struggling with utf-16 encoding/decoding
linked to: http://stackoverflow.com/q/11546351
favorite count: 0
linked to: http://stackoverflow.com/q/8827419
tagged with: utf-16
has comment: http://stackoverflow.com/comment/91819516
has comment: http://stackoverflow.com/comment/91820378
tagged with: python
has answer: http://stackoverflow.com/a/52445041
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52438681
accepted answer: http://stackoverflow.com/a/52438681
has body: I'm parsing a document that have some UTF-16 encoded string. I have a byte string that contains the following: my_var = b'\xc3\xbe\xc3\xbf\x004\x004\x000\x003\x006\x006\x000\x006\x00-\x001\x000\x000\x003\x008\x000\x006\x002\x002\x008\x005' When converting to utf-8, I get the following output: print(my_var.decode('utf-8')) #&gt; þÿ44036606-10038062285 The first two chars þÿ indicate it's a BOM for UTF-16BE, as indicated on Wikipedia But, what I don't understand is that if I try the UTF16 BOM like this: if value.startswith(codecs.BOM_UTF16_BE) This returns false. In fact, printing codecs.BOM_UTF16_BE doesn't show the same results: print(codecs.BOM_UTF16_BE) #&gt; b'\xfe\xff' Why is that? I'm suspecting some enconding issues on the higher end but not sure how to fix that one. There are already a few mentions of how to decode UTF-16 on Stackoverflow (like this one), and they all say one thing: Decode using utf-16 and Python will handle the BOM. ... But that doesn't work for me. print(my_var.decode('utf-16') #&gt; 뻃뿃㐀㐀 ㌀㘀㘀 㘀ⴀ㄀ ㌀㠀 㘀㈀㈀㠀㔀 But with UTF-16BE: print(my_var.decode('utf-16be') #&gt; 쎾쎿44036606-10038062285 (the bom is not removed) And with UTF-16LE: print(my_var.decode('utf-16le') #&gt; 뻃뿃㐀㐀 ㌀㘀㘀 㘀ⴀ㄀ ㌀㠀 㘀㈀㈀㠀㔀 So, for a reason I can't explain, using only .decode('UTF-16') doesn't work for me. Why? UPDATE The original source string isn't the one I mentioned, but this one: source = '\376\377\0004\0004\0000\0003\0006\0006\0000\0006\000-\0001\0000\0000\0003\0008\0000\0006\0002\0002\0008\0005' I converted it using the following: def decode_8bit(cls, match): value = match.group().replace(b'\\', b'') return chr(int(value, base=8)).encode('utf-8') my_var = re.sub(b'\\\\[0-9]{1,3}', decode_8bit, source) Maybe I did something wrong here?
type: Question

http://stackoverflow.com/q/52436259
has answer: http://stackoverflow.com/a/52581007
type: AnsweredQuestion
has body: In praw, I can create either a subreddit.stream.comments() or subreddit.stream.submissions(). For those unfamiliar, the two above praw functions return comments/posts as they come in. Is there a way to combine the two? I've tried using Python's built-in function zip as well as itertools's zip_longest but they both only give a result as fast as the posts come in. (Comments are much more frequent).
type: Question
tagged with: python-itertools
downvote count: 0
accepted answer: http://stackoverflow.com/a/52581007
score: 4
upvote count: 4
answer count: 1
has title: Is there a way to combine posts/comment streams?
tagged with: praw
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/52475622
has body: I hope I understand your problem correctly. To swap the position of any sequence of non-space characters surrounding a slash, you can use a regex: import re s = "a/b 3/4 hello/goodbye blah blah this/again" print(re.sub(r"([^\s/]+)/([^\s/]+)", r"\2/\1", s)) Output: b/a 4/3 goodbye/hello blah blah again/this
type: Answer
answers question: http://stackoverflow.com/q/52475551
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/91812740
comment on: http://stackoverflow.com/q/52433859
type: Comment
score: 0
type: QuestionComment
has text: You are mixing `re_path` with path: https://docs.djangoproject.com/en/2.1/ref/urls/#re-path. Use `path('world/<int:some_id>/<some_val>/<some_val_2>/'`

http://stackoverflow.com/comment/92061312
comment on: http://stackoverflow.com/a/52560942
has text: I now see how the `for` feature can be used to do each row separately. Apologies for editing the question once more, but can this be extended to loop through two dimensions of `x`?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52489218
has body: That's exactly what a break statement does. while True: function() if blah blah: break Of course, if possible you should move the test to the loop condition. while not blah blah: function()
answers question: http://stackoverflow.com/q/52489201
score: 0
type: Answer

http://stackoverflow.com/q/52481460
tagged with: artificial-intelligence
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91907612
accepted answer: http://stackoverflow.com/a/52516494
downvote count: 1
has comment: http://stackoverflow.com/comment/91911340
type: Question
score: -1
has body: I want to create an artificial intelligence program using Python. I found out that I need gTTS but it doesn't save mp3 files. Help me, please. #gtts is imported def talkToMe(audio, lgg = 'en'): #print(audio) tts = gTTS(text = audio, lang = lgg) #tts.save('audio.mp3') #doesn't work with open("audio.mp3") as fp: #doesn't work tts.write_to_fp(fp) os.system('mpg123\mpg123.exe audio.mp3') Traceback (most recent call last): File "C:\Users\zigzag\Desktop\gtts_test1\main.py", line 9, in &lt;module&gt; talkToMe("hello") File "C:\Users\zigzag\Desktop\gtts_test1\main.py", line 7, in talkToMe tts.write_to_fp(fp) File "B:\Python36\lib\site-packages\gtts\tts.py", line 187, in write_to_fp part_tk = self.token.calculate_token(part) File "B:\Python36\lib\site-packages\gtts_token\gtts_token.py", line 28, in calculate_token seed = self._get_token_key() File "B:\Python36\lib\site-packages\gtts_token\gtts_token.py", line 62, in _get_token_key a = re.search("a\\\\x3d(-?\d+);", tkk_expr).group(1) AttributeError: 'NoneType' object has no attribute 'group'
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52516494
favorite count: 0
has title: gTTS Doesn't Save MP3 Files
tagged with: google-text-to-speech
tagged with: python

http://stackoverflow.com/a/52493876
has comment: http://stackoverflow.com/comment/91929352
has comment: http://stackoverflow.com/comment/91929734
type: Answer
answers question: http://stackoverflow.com/q/52492913
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52492913
upvote count: 1
type: AcceptedAnswer
has body: Dictionaries are unordered and there is not much you can do to change that, short of writing your own subclass of dict (not recommended). Using OrderedDict will work, as shown in hiro protagonists's comment, as long as you keep in mind that the order in an OrderedDict is the order of insertion and is not related to the values of the keys. (The same is true of the ordering of Python 3 dicts.) If a and b have the same elements but in a different order then the resulting OrderedDicts will not be equal, unless you sort a and b beforehand. If you want to compare two dicts where you can't easily determine the order of insertion, you need a data structure that supports unordered comparisons. I didn't have your data so I had to make some up. I started with this input &gt;&gt;&gt; a [[1, 3, 5, 7, 9], [4, 9, 14, 19, 24, 29, 34, 39], [8, 17, 26, 35, 44, 53, 62, 71], [9, 19, 29, 39, 49, 59, 69, 79, 89]] &gt;&gt;&gt; b [[1, 3, 5, 7, 9], [4, 9, 14, 19, 24, 29, 34, 39], [8, 17, 26, 35, 44, 53, 62, 71]] As you can see, a has one extra element beginning 9. Modify your dictionary construction code to make the values tuples not lists, because the dict values need to be hashable for the next step to work: &gt;&gt;&gt; d = { k[0]: tuple(k[1:]) for k in a } &gt;&gt;&gt; d2= { k[0]: tuple(k[1:]) for k in b } Then you can convert the dictionaries to sets to do an unordered comparison: &gt;&gt;&gt; s = set(d.items()) &gt;&gt;&gt; s2 = set(d2.items()) &gt;&gt;&gt; s == s2 False And you can use the set operators to discover what the difference is: &gt;&gt;&gt; s2 &lt;= s True &gt;&gt;&gt; s - s2 set([(9, (19, 29, 39, 49, 59, 69, 79, 89))])

http://stackoverflow.com/comment/92087856
type: QuestionComment
has text: When I place this line at the top of your code "import warnings;warnings.filterwarnings('error')" I get more detail on the problem, showing that np.sqrt(1/T) is receiving an invalid, or negative, number.
comment on: http://stackoverflow.com/q/52573085
score: 0
type: Comment

http://stackoverflow.com/a/52585910
accepted answer of: http://stackoverflow.com/q/52585881
answers question: http://stackoverflow.com/q/52585881
has body: How about using .values: x=df1.loc[df1['VAR_NAME_'] == 'employmentType'] x1 = x.ix[:,47].values print(x1) Prints out: Employed
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/52555809
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/92051260
has title: Python Venn diagrams - fill and edge color
type: Question
tagged with: matplotlib-venn
has comment: http://stackoverflow.com/comment/92050522
score: 0
has comment: http://stackoverflow.com/comment/92050443
has body: I want to use matplotlib_venn library in Python3 to draw venn diagrams with transparent fill and only edge colored, almost like in the attached but I will only have 2 circles. I could not find any straightforward way to control the colors. Any ideas, please? Currently I have the code: set1 = set([1,2,3]) set2 = set([2,3,4,5,6,7,8]) c = venn2_circles(subsets = [set1,set2], linewidth=1) c[0].set_color("red") plt.title("Sample Venn diagram") plt.show() But this result in coloring the fill and edge together.
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/95736276

http://stackoverflow.com/comment/91979514
type: AnswerComment
comment on: http://stackoverflow.com/a/52519810
type: Comment
has text: Changing it I obtain another error: _InvalidSchema: ("No connection adapters were found for 'ip_address http://ipapi..., dtype: object'", 'occurred at index 0')_ I have followed the solutions on this [link] (https://stackoverflow.com/questions/15115328/python-requests-no-connection-adapters) and I am still getting the error.
score: 0

http://stackoverflow.com/q/52496341
has title: regular expression in python [to get text after number phone]
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52497834
type: Question
score: -2
answer count: 2
upvote count: 0
favorite count: 0
has body: I have a little worry with my regular expressions. I would like to retrieve all the texts that come after the phone number to each.The text is as follows: 22/06/2018 à 10:16 PM - Les messages envoyés dans ce groupe sont désormais protégés avec le chiffrement de bout en bout. Appuyez pour plus d'informations. 28/05/2018 à 4:34 PM - ‎‪+60 17-751 1232‬ a créé le groupe "SE&amp;E(SEE)Asia✈⛴Travelers group" 22/06/2018 à 10:16 PM - Vous avez intégré le groupe en utilisant le lien d'invitation 22/06/2018 à 10:17 PM - Kdm: I need help i want to travel to China. so i need visa can i help me about information 22/06/2018 à 10:17 PM - Kdm: Hey everyone 22/06/2018 à 10:18 PM - ‪+62 857-1592-9544‬: yes, you can help yourself 22/06/2018 à 10:19 PM - Kdm: Lol 22/06/2018 à 10:20 PM - ‪+91 96500 52277‬: Where do u wantbto go in chian ? 22/06/2018 à 10:21 PM - Kdm: Capital because i have a problem with my passport . So i want to apply for a new passport ; am student in hanoi match = re.search(r'((?:\+|00)[17](?: |\-)?|(?:\+|00)[1-9]\d{0,2}(?: |\-)?|(?:\+|00)1\-\d{3}(?: |\-)?)?(0\d|\([0-9]{3}\)|[1-9]{0,3})(?:((?: |\-)[0-9]{2}){4}|((?:[0-9]{2}){4})|((?: |\-)[0-9]{3}(?: |\-)[0-9]{4})|([0-9]{7}))(.*?)\s(.*)',splitstring[i])
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52497616

http://stackoverflow.com/comment/91941455
type: Comment
comment on: http://stackoverflow.com/a/52500431
score: 0
type: AnswerComment
has text: what is your desired output with that list?

http://stackoverflow.com/q/52435128
has title: python if statement on empty list
score: 0
has comment: http://stackoverflow.com/comment/91813765
has comment: http://stackoverflow.com/comment/91813845
tagged with: python-2.7
tagged with: python
has body: The python if statement can be used in the following way a = [] if a: # do something i.e., the conditional can be an object (in this case a list). In this case, as far as I understand it, the conditional is evaluated by bool([]) which evaluates to False. On the other hand, bool([1]) evaluates to True and hence something is done. I personally like this behaviour - it seems clear, but colleagues have pointed out it is unclear. Is this recommended? What are the potential gotcha's? Is it pythonic or should something more explicit be done?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91813746
has comment: http://stackoverflow.com/comment/91813789
linked to: http://stackoverflow.com/q/53513
tagged with: if-statement
has comment: http://stackoverflow.com/comment/91813909
duplicate of: http://stackoverflow.com/q/53513
type: Question

svd
type: Tag
tags question: http://stackoverflow.com/q/52486435
tag name: svd
tags question: http://stackoverflow.com/q/52503054

http://stackoverflow.com/comment/115724255
comment on: http://stackoverflow.com/a/52450682
has text: Is there any method that can be implemented in real-time?
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/52554314
tagged with: windows
upvote count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52559018
tagged with: pytorch
type: UnansweredQuestion
tagged with: python
has title: Problem when using py.test with a pytorch project via the python extension of visual studio code
tagged with: pytest
type: Question
tagged with: visual-studio-code
has body: I'm working on a pytorch project using visual studio code and trying to use py.test. However, when trying to discover (or run) tests using the vs-code extension, I get an error (see log) importing torch. When I run pytest from the terminal, everything works fine. Question: What is VS-code doing differently compared to me running pytest myself? How can I fix this? Thanks Config and further info Win10, custom conda env, python=3.7, pytest=3.8, pytorch=0.4.1 [cuda92], vscode 1.27.2 When I remove some tests so that all remaining tests do not call any torch code, everything works fine (i.e. pytest config inside vs-code should be correct) Python path pointing to correct env is set in vs-code Workspace Settings VS Code seems to be using the correct conda env and pytest version according to Python Test Log (see below) Running pytest directly from terminal works fine (see below) I can successfully call modules using torch via python or import torch inside ipython Edit 1: I'm aware of https://github.com/pytorch/pytorch/issues/4518 and have tried some of the more recent suggestions in that thread. (However, I don't think that's really my problem, because as said above I can import torch just fine.) Edit 2: I'm getting the same error when running any modules that import torch inside vs-code's debugger Output of Vs-Code Pytest Test Log after failed 'Discover Tests' ============================= test session starts ============================= platform win32 -- Python 3.7.0, pytest-3.8.0, py-1.6.0, pluggy-0.7.1 rootdir: c:\Users\stefan\dev\bnelearn, inifile: pytest.ini collected 0 items / 1 errors =================================== ERRORS ==================================== _____________ ERROR collecting bnelearn/tests/test_mechanisms.py ______________ ImportError while importing test module 'c:\Users\stefan\dev\bnelearn\bnelearn\tests\test_mechanisms.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: bnelearn\tests\test_mechanisms.py:3: in &lt…
answer count: 1
downvote count: 0
score: 4

http://stackoverflow.com/comment/91809818
has text: @carefullynamed I just used `Dense` as an example. Whatever layer you use as the last layer, use this softmax activation on it.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52432508

http://stackoverflow.com/comment/91910556
has text: Try [dask](http://dask.pydata.org) in case you are using numpy or numpy based libraries (e.g. scikit-image) to process your images.
comment on: http://stackoverflow.com/q/52483836
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91992702
comment on: http://stackoverflow.com/a/52526352
score: 0
type: Comment
has text: Yes. just like you are importing `func.py` (or a function from it) in your main
type: AnswerComment

http://stackoverflow.com/comment/91933357
type: Comment
has text: Yes. The approach of separating the src and test in folders is so common (especially in CMake projects) that I assume, someone is doing this already. See related questions: https://stackoverflow.com/questions/47859986/usual-pytest-workflow-cant-run-tests-in-a-file (but answer was like: "pytest requires installation of src")
score: 0
comment on: http://stackoverflow.com/q/52494425
type: QuestionComment

http://stackoverflow.com/a/52462026
answers question: http://stackoverflow.com/q/52462004
score: -1
downvote count: 1
upvote count: 0
has body: Look into using dictionaries instead of lists. lines = {} for i in range(1000): for j in range(4): f=fl.readline() lines[j] = f print(lines[0,1])
type: Answer

http://stackoverflow.com/a/57887637
score: 1
downvote count: 0
has body: pyenv installs Python into $PYENV_ROOT, defaults to $HOME/.pyenv, for each user. When you're using sudo, you switch to root user temporarily in this very command. There's no python installed by pyenv for user root under directory /root/.pyenv. So python version 2.7.9 was not found.
type: Answer
answers question: http://stackoverflow.com/q/52486591
upvote count: 1

http://stackoverflow.com/a/52490624
answers question: http://stackoverflow.com/q/52490516
downvote count: 0
has comment: http://stackoverflow.com/comment/91940022
accepted answer of: http://stackoverflow.com/q/52490516
has body: import math def pol2cart(rho, phi): x = rho * math.cos(math.radians(phi)) y = rho * math.sin(math.radians(phi)) return(x, y) rho=float(input("Enter the value of rho:")) phi=float(input("Enter the value of phi in degrees:")) print("For the polar coordinates x = ", rho, "and y = ", phi, "the cartesian coordinates are = ", pol2cart(rho, phi)) Use math.radians to convert the angles from degrees to radians. Since you are asking for input in degree but math.cos take in angles in radians.
type: AcceptedAnswer
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/52469166
tagged with: dataframe
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91880307
tagged with: pandas-groupby
tagged with: pandas
type: Question
has answer: http://stackoverflow.com/a/52469410
has title: pandas concat list of dataframes to one dataframe
answer count: 2
tagged with: python
has body: Trying to combine a list of dataframes to one dataframe. Data looks like: Date station_id Hour Temp 0 2004-01-01 1 1 46.0 1 2004-01-01 1 2 46.0 2 2004-01-01 1 3 45.0 3 2004-01-01 1 4 41.0 ... 433730 2008-06-30 11 3 64.0 433731 2008-06-30 11 4 64.0 433732 2008-06-30 11 5 64.0 433733 2008-06-30 11 6 64.0 This gives me a list of dataframes: stations = [x for _,x in df.groupby('station_id')] When I reset the indices for "stations", and concat, I can get a dataframe, but it doesn't look like I'd like: for i in range(0,11): stations[i].reset_index(drop=True,inplace=True) pd.concat(stations,axis=1) Date station_id Hour Temp Date station_id Hour Temp 0 2004-01-01 1 1 46.0 2004-01-01 2 1 38.0 1 2004-01-01 1 2 46.0 2004-01-01 2 2 36.0 2 2004-01-01 1 3 45.0 2004-01-01 2 3 35.0 3 2004-01-01 1 4 41.0 2004-01-01 2 4 30.0 I'm much rather get towards a df like this: Date Hour Stn1 Stn2 0 2004-01-01 1 46.0 38.0 1 2004-01-01 2 46.0 6.0 2 2004-01-01 3 45.0 35.0 3 2004-01-01 4 41.0 30.0 How do I do this?
score: 0
has answer: http://stackoverflow.com/a/52469330
has comment: http://stackoverflow.com/comment/91880559

http://stackoverflow.com/q/52431170
linked to: http://stackoverflow.com/q/5250744
score: 0
upvote count: 1
downvote count: 1
has title: Error in writing Unicode charters using python
has comment: http://stackoverflow.com/comment/91806286
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52431922
has body: I am trying to write unicode char in to text file using the following python code with codecs.open("File.txt", mode='wb', encoding='utf-8') as f: f.write(str(u'文学学士 2005年3月： 获大学英语六级证书')) f.write(' ') f.close() I am getting the following error 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) Please help me in resolving this issue
type: Question
answer count: 1

http://stackoverflow.com/q/52490359
tagged with: http://stackoverflow.com/tag/r
tagged with: multidimensional-array
tagged with: python
favorite count: 0
has title: Python parallel with R to covert arrays to data table
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52509454
score: 1
has body: I want to convert a multidimensional arrays to a data table (or a matrix). I usually use R, thus I realize the purpose to write R codes as x = array(1:24, dim=c(3,4,2)) # a toy 3-dim array library(data.table) y = data.table(as.table(x)) y # V1 V2 V3 N # 1: A A A 1 # 2: B A A 2 # 3: C A A 3 # 4: A B A 4 # 5: B B A 5 # 6: C B A 6 # 7: A C A 7 # 8: B C A 8 # 9: C C A 9 # 10: A D A 10 # 11: B D A 11 # 12: C D A 12 # 13: A A B 13 # 14: B A B 14 # 15: C A B 15 # 16: A B B 16 # 17: B B B 17 # 18: C B B 18 # 19: A C B 19 # 20: B C B 20 # 21: C C B 21 # 22: A D B 22 # 23: B D B 23 # 24: C D B 24 # V1 V2 V3 N colnames(y) = c("a","b","c","Y") # rename the columns of y write.table(y, "y_out.txt", col.names=TRUE, row.names=FALSE, quote=FALSE) # save to external file # a b c Y # A A A 1 # B A A 2 # C A A 3 # A B A 4 # B B A 5 # C B A 6 # A C A 7 # B C A 8 # C C A 9 # A D A 10 # B D A 11 # C D A 12 # A A B 13 # B A B 14 # C A B 15 # A B B 16 # B B B 17 # C B B 18 # A C B 19 # B C B 20 # C C B 21 # A D B 22 # B D B 23 # C D B 24 Most recently, I am learning the Python. Then I want to convert the above R codes into Python codes, and I search on Google (especially the Stack Overflow) and try to write Python codes as import numpy as np import pandas as pd x = np.arange(1,24+1).reshape(3,4,2) # a toy 3-dim array # ??? pd.DataFrame # ??? np.savetxt("y_out.txt", x, fmt='%.4f', delimiter=' ', newline='\n') Problems always happen. BTW, I use Python 3.4. Any help?
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52525887
score: 1
has comment: http://stackoverflow.com/comment/91998516
answers question: http://stackoverflow.com/q/52524590
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/92101261
has body: I think I know what course you're doing, I had a great time with that a year ago, keep it up! The simplest/fastest way I've found to concatenate a bunch of sliced dataframes is to append each df to a list, then at the end just concatenate that list. See the working code below (it does what I interpret you meant). I agree with David's suggestion on sorting, easier to use sort and then just slice the first 3. As nlargest() works on and returns a Series I believe and not a dataframe, whereas you want to keep the whole dataframe structure (all the columns) for concatenation. Also why is your function returning 1? Typo? I guess you want to return your desired output if you're putting it in a function, so I changed that too. import pandas as pd import numpy as np #create fake data random numbers data = np.random.randint(2,11,(40,3)) census_df = pd.DataFrame(index=range(40), columns=['Blah', 'Blah2','CENSUS2010POP'], data=data) #create fake STNAME column census_df['STNAME'] = list('aaaabbbbccccddddeeeeffffgggghhhhiiiijjjj') #Function: def test(census_df): states_list = census_df.STNAME.unique() #changed naming to _list as it's not a df. list_of_dfs = list() #more efficient to append each df to a list for st in states_list: temp_df = census_df[census_df['STNAME']==st] temp_df = temp_df.sort_values(by=['CENSUS2010POP'], ascending=False).iloc[:3] list_of_dfs.append(temp_df) population_df = pd.concat(list_of_dfs,ignore_index=True) return population_df population_df = test(census_df)
downvote count: 0

http://stackoverflow.com/comment/91924318
type: QuestionComment
has text: Yes, it is running on the server, the same server where I can connect using 'sqlplus /'
comment on: http://stackoverflow.com/q/52480681
score: 0
type: Comment

http://stackoverflow.com/comment/91886980
type: Comment
type: QuestionComment
has text: You want to count the number of times a user has appeared in a given month, with `first_appearance` being the first date of appearance for the user in that month? Are you sure your `user_id` column is right?
comment on: http://stackoverflow.com/q/52472616
score: 0

http://stackoverflow.com/comment/92089403
has text: Thanks a lot for your help, and thanks for your detailed explanation!
type: AnswerComment
comment on: http://stackoverflow.com/a/52439374
score: 0
type: Comment

http://stackoverflow.com/comment/91846113
has text: Then I misinterpreted what was meant by "uniformity over the entire space of such sequences". It needs to be pseudo-random, so random as far the constraints will allow
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52449039

http://stackoverflow.com/q/52553867
has comment: http://stackoverflow.com/comment/92047131
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92047322
has body: I want to choose a random dictionary in Python3. I have a function foobar like so: def foobar(region_name, table_name, key=None, regex=None): dynamodb = boto3.resource('dynamodb', region_name=region_name) table = dynamodb.Table(table_name) regex = regex response = table.scan( Select="ALL_ATTRIBUTES" ) if regex: r = re.compile(regex) slots = [slot for slot in response['Items'] if r.search(slot[key])] for slot in slots: print(slot) else: print(response['Items']) that returns multiple dictionaries like so: {'A': 'none', 'B': 'none', 'C': 'off', 'D': 'none', 'E': 'none'} {'A': 'foobar', 'B': 'foobar', 'C': 'off', 'D': 'foobar', 'E': 'none'} {'A': 'magic', 'B': 'none', 'C': 'off', 'D': 'magic', 'E': 'none'} I am creating another function to be able to choose a random dictionary. My first step was to put the outcome of the function foobar into a variable like so: hello = foobar(region_name, table_name, key, regex) And then apply the random method to it: print(random.choice(hello)) It gives me an error TypeError: object of type 'NoneType' has no len() Moreover, if I print the type of the variable hello, it gives me &lt;class 'NoneType'&gt; I imagine it is because the dictionaries are different entities but I am not sure how to tackle this. What is the best way to select a random dictionary in that case? Thank you for your help from a newbie in Python.
has title: python3 choose a random dictionary
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52563678
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92046421
has comment: http://stackoverflow.com/comment/92046889
has comment: http://stackoverflow.com/comment/92046422
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52563781

http://stackoverflow.com/a/52591691
answers question: http://stackoverflow.com/q/52436923
type: Answer
has body: If you only want to return the generated PDF as http-response, the following solution is working for me. I don't know your template. I use {{ content.invoid_id }} for example to access the context values in template. def generate_pdf(request): # Model data students = Student.objects.all().order_by('last_name') context = { 'invoice_id': 18001, 'street_name': 'Rue 76', 'postal_code': '3100', 'city': 'Washington', 'customer_name': 'John Cooper', 'customer_mail': 'customer@customer.at', 'amount': 1339.99, 'today': 'Today', } content = Context() content.update(context) template = loader.get_template('yourtemplate.html') # render and return html = template.render(context={'content':content}, request=request) response = HttpResponse(content_type='application/pdf') HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response) return response No need for a temporary file. Hope this helps! Edit: if you need the file bytes you can do it this way: def generate_pdf(request): # Model data students = Student.objects.all().order_by('last_name') context = { 'invoice_id': 18001, 'street_name': 'Rue 76', 'postal_code': '3100', 'city': 'Washington', 'customer_name': 'John Cooper', 'customer_mail': 'customer@customer.at', 'amount': 1339.99, 'today': 'Today', } content = Context() content.update(context) template = loader.get_template('yourtemplate.html') html = template.render(context={'content':content}) with TemporaryFile() as pdf: HTML(string=html, base_url=url).write_pdf(pdf) pdf.seek(0) # do what every you want with pdf.read())
score: 0

http://stackoverflow.com/q/52539947
accepted answer: http://stackoverflow.com/a/52540060
favorite count: 0
tagged with: chain
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92019934
linked to: http://stackoverflow.com/q/25824005
has comment: http://stackoverflow.com/comment/92019622
tagged with: python
has title: how can i chain two none stop lists in python3?
tagged with: generator
duplicate of: http://stackoverflow.com/q/25824005
type: AnsweredQuestion
tagged with: list
has body: I have two functions generate two none stop lists, I want to print both list, but in chain function, the second list only start to print once the first list is finished, how can I print both lists, but in turns generator = chain(nonestoplist1(), nonestoplist2()) for item in generator: print(item) like: first_list=[1,2,3,4,5,6,......] second_list=[a,b,c,d,e,f,g,.....] generator print: 1,a,2,b,3,c,4,d,.....
downvote count: 1
has answer: http://stackoverflow.com/a/52540060
type: Question
score: -1
linked to: http://stackoverflow.com/q/1663807
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/92020674
score: 0
type: Comment
has text: love this solution! the only issue i have is that it's taking the average of all of my dates, where i want it to only average when dates are equal... do you know how to incorporate this?
type: AnswerComment
comment on: http://stackoverflow.com/a/52538907

http://stackoverflow.com/comment/92065570
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52562874
has text: Thanks, both pdist and np.where are good to know about! This doesn't actually quite solve the problem though, as the output should be vectors in 3-space, not just their magnitudes. That's also why there was a cube rather than square factor in the original code.
type: AnswerComment

http://stackoverflow.com/a/52510448
score: 2
has body: Use concat with parameter ignore_index=True for avoid duplicated index values: df = pd.concat([df,df1], ignore_index=True) print (df) A B 0 foo 0 1 foo 1 2 foo 1 3 bar 1 4 Panda 0 5 Panda 1 6 Zootopia 1 7 Zootopia 1
answers question: http://stackoverflow.com/q/52510403
downvote count: 0
upvote count: 2
type: Answer

opencv
tags question: http://stackoverflow.com/q/52465856
type: Tag
tags question: http://stackoverflow.com/q/52437002
tags question: http://stackoverflow.com/q/52505906
tags question: http://stackoverflow.com/q/52543550
tags question: http://stackoverflow.com/q/52494592
tags question: http://stackoverflow.com/q/52511267
tags question: http://stackoverflow.com/q/52508440
tags question: http://stackoverflow.com/q/52498495
tags question: http://stackoverflow.com/q/52467033
tags question: http://stackoverflow.com/q/52495105
tags question: http://stackoverflow.com/q/52572051
tags question: http://stackoverflow.com/q/52509986
tags question: http://stackoverflow.com/q/52458725
tags question: http://stackoverflow.com/q/52454255
tags question: http://stackoverflow.com/q/52446599
tags question: http://stackoverflow.com/q/52486840
tags question: http://stackoverflow.com/q/52578621
tags question: http://stackoverflow.com/q/52455337
tags question: http://stackoverflow.com/q/52576498
tags question: http://stackoverflow.com/q/52496387
tags question: http://stackoverflow.com/q/52512936
tags question: http://stackoverflow.com/q/52553077
tags question: http://stackoverflow.com/q/52498777
tags question: http://stackoverflow.com/q/52503187
tags question: http://stackoverflow.com/q/52483613
tags question: http://stackoverflow.com/q/52504472
tags question: http://stackoverflow.com/q/52576117
tags question: http://stackoverflow.com/q/52558617
tags question: http://stackoverflow.com/q/52461803
tags question: http://stackoverflow.com/q/52545207
tags question: http://stackoverflow.com/q/52503222
tags question: http://stackoverflow.com/q/52512769
tags question: http://stackoverflow.com/q/52484507
tags question: http://stackoverflow.com/q/52452155
tags question: http://stackoverflow.com/q/52437701
tags question: http://stackoverflow.com/q/52536059
tags question: http://stackoverflow.com/q/52445834
tags question: http://stackoverflow.com/q/52448804
tag name: opencv
tags question: http://stackoverflow.com/q/52533860
tags question: http://stackoverflow.com/q/52534892
tags question: http://stackoverflow.com/q/52456170
tags question: http://stackoverflow.com/q/52450602
tags question: http://stackoverflow.com/q/52530563
tags question: http://stackoverflow.com/q/52509316
tags question: http://stackoverflow.com/q/52525903
tags question: http://stackoverflow.com/q/52446597
tags question: http://stackoverflow.com/q/52561715
tags question: http://stackoverflow.com/q/52467929
tags question: http://stackoverflow.com/q/52473773
tags question: http://stackoverflow.com/q/52555016
tags question: http://stackoverflow.com/q/52464967
tags question: http://stackoverflow.com/q/52516689
tags question: http://stackoverflow.com/q/52432549
tags question: http://stackoverflow.com/q/52454250
tags question: http://stackoverflow.com/q/52528251
tags question: http://stackoverflow.com/q/52471456
tags question: http://stackoverflow.com/q/52581738
tags question: http://stackoverflow.com/q/52551210
tags question: http://stackoverflow.com/q/52441089
tags question: http://stackoverflow.com/q/52534907
tags question: http://stackoverflow.com/q/52535609
tags question: http://stackoverflow.com/q/52474645
tags question: http://stackoverflow.com/q/52556885
tags question: http://stackoverflow.com/q/52510969
tags question: http://stackoverflow.com/q/52450681
tags question: http://stackoverflow.com/q/52479045
tags question: http://stackoverflow.com/q/52456871
tags question: http://stackoverflow.com/q/52466265
tags question: http://stackoverflow.com/q/52557646
tags question: http://stackoverflow.com/q/52459794
tags question: http://stackoverflow.com/q/52547833
tags question: http://stackoverflow.com/q/52506430
tags question: http://stackoverflow.com/q/52480804
tags question: http://stackoverflow.com/q/52455195
tags question: http://stackoverflow.com/q/52565314
tags question: http://stackoverflow.com/q/52440435
tags question: http://stackoverflow.com/q/52562800
tags question: http://stackoverflow.com/q/52501817

http://stackoverflow.com/comment/91854551
comment on: http://stackoverflow.com/a/52455943
type: Comment
score: 1
type: AnswerComment
has text: @BipulJain not sure on your performance concerns - you would have to change _all_ 255,255,255 pixels of your background to 254,254,254 (or smth) which would not make much impact on the resulting image when viewing it. Alternatively search all pixels of your image for a "not used" color and use that as background - whats more feasable you would have to evaluate. Maybe some PIL-Users will pipe in, just leave this answer as is and hope for someone to come up with some code would be my advice. There might be an ever better solution using PIL. Maybe something with paste options

http://stackoverflow.com/q/52567701
has body: I use read only in Python but I setter and deleter still work. This code class Character(): def __init__(self, name): self._name = name def getname(self): return self._name name = property(fget=getname, fset=None, fdel=None, doc=None) c = Character('c') c._name #Output 'c' c.name #Output 'c' c.name = 'd' del c.name _name is private attribute, why I still use c._name In property for getter but setter and deleter still work.
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 1
linked to: http://stackoverflow.com/q/598077
score: 1
type: Question
tagged with: python-2.7
has title: Why setter and deleter still work when use only read in Python 2.7
duplicate of: http://stackoverflow.com/q/598077
tagged with: python

http://stackoverflow.com/comment/91872236
comment on: http://stackoverflow.com/q/52465250
type: QuestionComment
type: Comment
score: 1
has text: or move this question to https://ru.stackoverflow.com/

http://stackoverflow.com/a/52466899
downvote count: 0
has body: &gt;&gt;&gt; def crossovers(p1,p2): ... a = [] ... high = True ... for i in range(len(p1)): ... if p1[i] is not None and p2[i] is not None: ... if high and p1[i] &lt; p2[i]: ... a.append([i,2]) ... high = False ... if not high and p1[i] &gt; p2[i]: ... a.append([i,1]) ... high = True ... return a ... &gt;&gt;&gt; This solution might work. &gt;&gt;&gt; p1 = [1, 2, 4, 5] &gt;&gt;&gt; p2 = [0, 2.5, 5, 3] &gt;&gt;&gt; &gt;&gt;&gt; print(crossovers(p1,p2)) [[1, 2], [3, 1]] &gt;&gt;&gt; &gt;&gt;&gt; p1 = [None, 2.5, 3.5, 4.5, 4.5, 3.5, 2.5, 1.5, 3.5, 3.5] &gt;&gt;&gt; p2 = [None, None, 3.0, 4.0, 4.333333333333333, 4.0, 3.0, 2.0, 3.0, 2.6666666666666665] &gt;&gt;&gt; print(crossovers(p1,p2)) [[5, 2], [8, 1]]
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52465855
upvote count: 1
has comment: http://stackoverflow.com/comment/91876888

http://stackoverflow.com/a/52586132
has comment: http://stackoverflow.com/comment/92109764
has comment: http://stackoverflow.com/comment/92108751
has comment: http://stackoverflow.com/comment/92109662
has comment: http://stackoverflow.com/comment/92108321
score: 0
has comment: http://stackoverflow.com/comment/92109801
has comment: http://stackoverflow.com/comment/92108710
has comment: http://stackoverflow.com/comment/92109509
has body: Try this: from itertools import chain new_list = list(chain(*arr_cat))
answers question: http://stackoverflow.com/q/52583932
type: Answer
has comment: http://stackoverflow.com/comment/92109631
has comment: http://stackoverflow.com/comment/92109443
has comment: http://stackoverflow.com/comment/92108666

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/52574859
tags question: http://stackoverflow.com/q/52526369
tags question: http://stackoverflow.com/q/52455488

http://stackoverflow.com/comment/91824107
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52440606
type: QuestionComment
has text: When you run TensorFlow code, it is printed in the terminal if its using the GPU or not, please include that information. Something like Found device 0 with properties: name: GeForce GTX 1060 6GB major: 6 minor: 1 emoryClockRate(GHz): 1.7085

http://stackoverflow.com/comment/91868729
comment on: http://stackoverflow.com/q/52460913
has text: Usually setup.py doesn't pick the c++-standard library - it doesn't call the linker directly but via g++-frontend, something similar to `g++ ... objfile.o ... -o result.so`. The `g++` knows which standard libraries are used and pass them to the linker. Whitout seen the link-command issued by the setup.py-file it is just guessing what is going on.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92065992
type: Comment
comment on: http://stackoverflow.com/q/52545316
has text: some feedback??
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91878036
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52465379
has text: Thank you it helps!

http://stackoverflow.com/comment/91995764
score: 0
type: Comment
type: QuestionComment
has text: Is there a method to add a button to a certain widget?I looked up a PyQt tutorial,and they were only using a single widget,so i couldn't learn further
comment on: http://stackoverflow.com/q/52527995

http://stackoverflow.com/a/52533431
type: Answer
has body: you forget the quotation marks dataset = pd.read_csv('.../input/train.cvs',encoding = "utf-8",header = None)
score: 0
answers question: http://stackoverflow.com/q/52511300

http://stackoverflow.com/a/52538912
accepted answer of: http://stackoverflow.com/q/52538795
answers question: http://stackoverflow.com/q/52538795
type: Answer
has body: You can use join with pop + tolist: d = [{"key":1000000, "name":"Aelf", "level":0, "hasData":"true", "fields":{"id":"elf"}}, {"key":2000000, "name":"Cdaf", "level":1, "hasData":"false", "fields":{"id":"deer"}}] df = pd.DataFrame(d) res = df.join(pd.DataFrame(df.pop('fields').tolist())) Result: hasData key level name id 0 true 1000000 0 Aelf elf 1 false 2000000 1 Cdaf deer
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/52476614
has body: Assuming you are only concerned with looping and not splitting the dataframes into 51 subparts, here is my attempt to your question: Lets say, you define your OLS function as: def OLSfunction(y): y_train = traindf[y] y_test = testdf[y] from statsmodels.api import OLS x_train = x_traindf x_test = x_testdf model = OLS(y_train, x_train) result = model.fit() print (result.summary()) pred_OLS = result.predict(x_test) print("R2", r2_score(y_test, pred_OLS)) Y_s = ['1','2',.....'51'] for y in Y_s: y=y OLSfunction(y) Please note you will have to have your traindf and testdf appropriately derived for the specific Y you are looking to build the model. And these will have to be correctly passed into the OLSfunction. Since I do not have any view of how your data looks like, am not getting into splitting/creation of traindf/ testdf...
score: 1
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52475119

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/52458158
tags question: http://stackoverflow.com/q/52519115
tags question: http://stackoverflow.com/q/52540186
type: Tag

http://stackoverflow.com/q/52473158
has answer: http://stackoverflow.com/a/52475932
score: 0
tagged with: aws-lambda
has answer: http://stackoverflow.com/a/59112073
has title: python error sending mail with amazon ses with aws lambda
type: UnansweredQuestion
tagged with: python
tagged with: amazon-ses
has comment: http://stackoverflow.com/comment/91892925
has body: I am new to aws lambda. I am trying to send mail with aws ses with aws lambda, without any triggers. Here is my code import boto3 from botocore.exceptions import ClientError ses = boto3.client('ses') email_from = 'proteeti@cloudly.io' email_to = 'proteeti13@gmail.com' emaiL_subject = 'Subject' email_body = 'Body' def lambda_handler(event, context): response = ses.send_email( Source = email_from, Destination={ 'ToAddresses': [ email_to, ], }, Message={ 'Subject': { 'Data': emaiL_subject }, 'Body': { 'Text': { 'Data': email_body } } } ) I've created a custome role with simple microservices permission. The event is set to hello world. I saved and clicked on test, it shows this errors { "errorMessage": "An error occurred (AccessDenied) when calling the SendEmail operation: User `arn:aws:sts::990458801115:assumed-role/basic-lambda-role/sendmail' is not authorized to perform `ses:SendEmail' on resource `arn:aws:ses:us-east-1:990458801115:identity/proteeti@cloudly.io'", "errorType": "ClientError", "stackTrace": [ [ "/var/task/lambda_function.py", 28, "lambda_handler", "'Data': email_body" ], [ "/var/runtime/botocore/client.py", 314, "_api_call", "return self._make_api_call(operation_name, kwargs)" ], [ "/var/runtime/botocore/client.py", 612, "_make_api_call", "raise error_class(parsed_response, operation_name)" ] ] } I wrote the code from here, it runs perfectly locally.
has comment: http://stackoverflow.com/comment/91910867
type: Question
answer count: 2
tagged with: amazon-web-services

http://stackoverflow.com/comment/103737509
type: AnswerComment
comment on: http://stackoverflow.com/a/52495126
type: Comment
has text: Interesting! I guess this just affect displaying, if I train a model use `BGR`, there will be no difference, right?
score: 0

http://stackoverflow.com/a/53532102
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52566503
score: 3
has body: I'm not sure if you've already figured this out, but you have to make sure that while building python that it can find openssl libraries. So specifically: If you're not using the system ssl libraries or they're not in your path, at --configure you need to specify where they are. I would give you the exact line but I myself havn't done this recently. If you've done this correctly, you will not see a report at the end of the build that python skipped building 'ssl' module. When you see the error you have above about (_ssl), this specifically means python was not built with it. You'll face the same problem in 3.6 if you using the same steps without changing --configure.
upvote count: 3

http://stackoverflow.com/comment/120282100
score: 0
type: AnswerComment
has text: It does work. However, u passed the parameter to a function to python code. If it means that if one what to pass parameters to a python script, he should call a function? Sometimes, It may not be convenient. Can python script access variables from R code above？
type: Comment
comment on: http://stackoverflow.com/a/52542230

http://stackoverflow.com/a/52530343
downvote count: 0
has body: Use GroupBy.transform for return Series with same size as original DataFrame, divide by div, multiple by mul and if necessary round: #if input is Series create one column DataFrame df = s.to_frame('Count') s = df.groupby('Pclass')['Count'].transform('sum') #if use oldier pandas version #s = df.groupby(level='Pclass')['Count'].transform('sum') df['Percentage'] = df['Count'].div(s).mul(100).round() print (df) Count Percentage Pclass Survived 1 0 80 37.0 1 136 63.0 2 0 97 53.0 1 87 47.0 3 0 372 76.0 1 119 24.0 EDIT: dont you have to forward fill on PClass ? It is not necessary, because default in MultiIndex are not shown, but if set multi_sparse to False is possible verify repeating values: with pd.option_context('display.multi_sparse', False): print (df) Count Pclass Survived 1 0 80 1 1 136 2 0 97 2 1 87 3 0 372 3 1 119
type: Answer
answers question: http://stackoverflow.com/q/52530316
has comment: http://stackoverflow.com/comment/92000024
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/92000030

http://stackoverflow.com/q/52433235
has body: I am just learning Django and have hit my first question. In the HTML page itself, I can view the page and see the header I created. However, when I type in the url (http://127.0.0.1:8000/) it will not show. Instead, it says PAGE NOT FOUND. Here is my code. This is the relevant portion of code from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is the code from urls.py: from django.conf.urls import url from django.contrib import admin from .views import home_page urlpatterns = [ url(r'^$/', home_page), url(r'^admin/', admin.site.urls), ] This is the code from views.py: from django.http import HttpResponse from django.shortcuts import render def home_page(request): return render(request, "home_page.html", {}) This is the code from home_page.html: home Hello World! The first three files are in a directory within the src folder and the last file is in another directory but still within the src folder. I did notice that I did not have a pycache folder when I started the project for some reason (even though the instructor from the video did have one when he started) but I am not sure if that has anything to do with anything. What am I doing wrong and how do I fix it. Thank you.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52433427
score: 0
has title: PAGE NOT FOUND with url in Django Project
possible better answer: http://stackoverflow.com/a/52433479
has answer: http://stackoverflow.com/a/52433479
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/52433427
type: AnsweredQuestion
tagged with: django-views

http://stackoverflow.com/a/52436778
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52436679
has body: You should concatenate the format operations (TIP: you need to ward your {} with doubles {{}} for each format nesting level): baseFmtStr = "'{{{{:{{pad}}&gt;{num}}}}}'" resultStr = baseFmtStr.format(num=10).format(pad='-').format(12345) This let us to result '-----12345' Here you have a live example

http://stackoverflow.com/q/52440435
tagged with: python
linked to: http://stackoverflow.com/q/37159714
score: 2
has title: In python's unittest, how do I mock a fake folder with fake images inside?
upvote count: 2
has answer: http://stackoverflow.com/a/52452210
tagged with: unit-testing
type: Question
has body: I am trying to create a unit test for a function that reads every image from a folder and saves them in a list. Here is a simplified version of the function: def read_images(directory): image_paths = os.listdir(directory) images = [] for im in image_paths: images.append(cv2.imread(os.path.join(directory, im))) return images This other question brought me close to the solution, but in my case I want the fake files created to be images (basically, arrays) so I can read them with cv2.imread. My idea is not having to create any temporary folder and, of course, not having to connect with any external folder or database. Is this possible? Edit: to be clear, I'd like to not have to create temporary folders, nor temporary image files. I'd like to know if there is a way of telling the program: "There is a folder here, and inside it there are some images/arrays with this shape", but with actually not having to create anything in memory.
tagged with: opencv
has comment: http://stackoverflow.com/comment/91825740
has answer: http://stackoverflow.com/a/52440632
has comment: http://stackoverflow.com/comment/91829539
tagged with: image
answer count: 2
tagged with: mocking
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91830096
type: UnansweredQuestion

http://stackoverflow.com/comment/91949236
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52504274
type: QuestionComment
has text: What do you get if you use print(change_response.text) or print(change_response.headers)?

http://stackoverflow.com/comment/92052559
has text: `import inspect; set(filter(inspect.isfunction, dir(module1))).intersection(filter(inspect.isfunction, dir(module2)))` would find matching function names from 2 different modules named `module1` and `module2`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52556750
score: 0

http://stackoverflow.com/comment/92077156
type: Comment
comment on: http://stackoverflow.com/q/52570005
score: 0
has text: Hi MisterMiyagi, I did not get your statement, Can you explain
type: QuestionComment

jython
tags question: http://stackoverflow.com/q/52584795
tag name: jython
tags question: http://stackoverflow.com/q/52445324
type: Tag
tags question: http://stackoverflow.com/q/52544063

http://stackoverflow.com/q/52580573
type: Question
tagged with: numpy
has body: I have a panda table where I am trying to look backwards from a certain row for the index of a condition. Index column1 column2 0 True False 1 True False 2 False False 3 True False 4 False False 5 False False 6 False True 7 False True So given the above table. I know the index of column2 and am using that so I have 6 now I want to look back and then find the first instance of a different column changing (column1) In this case it would return 3 Is there a good efficient way to do this in pandas?
score: 0
tagged with: pandas
has title: Search in Pandas for first instance of condition
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52580604
accepted answer: http://stackoverflow.com/a/52580604
type: AnsweredQuestion

http://stackoverflow.com/a/52577114
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52576825
has body: Here's one possibility to write the code with only one pass, no need for external library or python's min/max: def high_low(list_or_number): if isinstance(list_or_number, list): current_min = float('inf') current_max = float('-inf') for x in list_or_number: x_max, x_min = high_low(x) if x_max &gt; current_max: current_max = x_max if x_min &lt; current_min: current_min = x_min return (current_max, current_min) else: return (list_or_number, list_or_number) As an example: &gt;&gt;&gt; high_low([1, 5, [7, 10, [[12, 16], -10]]]) (16, -10) &gt;&gt;&gt; high_low(3) (3, 3) &gt;&gt;&gt; high_low([3,4,5]) (5, 3)

http://stackoverflow.com/comment/92026111
score: 0
comment on: http://stackoverflow.com/q/52543058
has text: Seems that your problems are tied to the behavior of `sensor.sense()`. Do you have documentation you can provide on this method?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52548517
answers question: http://stackoverflow.com/q/52548493
type: AcceptedAnswer
downvote count: 0
has body: You are resetting the unknown_counter to zero in your for loop. Therefore, the image is overwriting every time. Just move it outside the loops.
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52548493

jupyter
tags question: http://stackoverflow.com/q/52586506
tags question: http://stackoverflow.com/q/52502187
type: Tag
tags question: http://stackoverflow.com/q/52512650
tags question: http://stackoverflow.com/q/52461751
tags question: http://stackoverflow.com/q/52551909
tags question: http://stackoverflow.com/q/52568135
tag name: jupyter
tags question: http://stackoverflow.com/q/52551878
tags question: http://stackoverflow.com/q/52443200
tags question: http://stackoverflow.com/q/52539871
tags question: http://stackoverflow.com/q/52467912
tags question: http://stackoverflow.com/q/52436268
tags question: http://stackoverflow.com/q/52551575
tags question: http://stackoverflow.com/q/52494975
tags question: http://stackoverflow.com/q/52494318

http://stackoverflow.com/q/52529537
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has title: I've set up a RNG and a continue button but it wont update the result after continuing
has answer: http://stackoverflow.com/a/52529659
answer count: 2
tagged with: random
downvote count: 0
linked to: http://stackoverflow.com/q/394809
favorite count: 0
tagged with: python-3.x
has body: #Setting up RNG loop = "y" while loop == "y" or loop == "yes": from random import randint dice = (randint(1,10)) dice2 = (randint(1,10)) roll = (dice + dice2) win = 3 loss = 2 cash = 20 if roll == 3 or roll == 7 or roll == 11 or roll == 17: cash += (win) else: cash -= (loss) #Starting game print("""Welcome to, Gambling for School! You have $20 and must earn as much money as possible If you roll a 3, 7, 11, or 17, you will win $3 but any other number takes $2 You have a 20% of winning """) x = input("Press ENTER to start.") #Results if roll == 11 or roll == 8 or roll == 18: print("You rolled an " + str(roll) + "!") else: print("You rolled a " + str(roll) + "!") print("") print("Cash - $" + str(cash)) loop = input("Continue? (Y/N) ").lower() Had to change the indenting to show it as code When it runs, I hit enter to start the game and it adds and subtracts correctly but when I select continue, it plays as if I never lost or gained any money. It is 1AM and idk if my brain died but I can't think of anything to fix it
has answer: http://stackoverflow.com/a/52530775
tagged with: python

http://stackoverflow.com/comment/91934135
type: AnswerComment
score: 0
type: Comment
has text: I've updated the answer. The masks being in the original image size is indeed the issue.
comment on: http://stackoverflow.com/a/52495048

http://stackoverflow.com/a/52638380
has body: recently I also work on seq2seq model. I have encountered your problem before, in my case, I solve it by changing the loss function. You said you use mask, so I guess you use tf.contrib.seq2seq.sequence_loss as I did. I changed to tf.nn.softmax_cross_entropy_with_logits, and it works normally (and higher computation cost). (Edit 05/10/2018. Pardon me, I need to edit since I found there is an egregious mistake in my code) tf.contrib.seq2seq.sequence_loss can work really well, if the shape of logits ,targets , mask are right. As defined in official document : tf.contrib.seq2seq.sequence_loss loss=tf.contrib.seq2seq.sequence_loss(logits=decoder_logits, targets=decoder_targets, weights=masks) #logits: [batch_size, sequence_length, num_decoder_symbols] #targets: [batch_size, sequence_length] #weights: [batch_size, sequence_length] Well, it can still work even if the shape are not meet. But the result could be weird (lots of #EOS #PAD... etc). Since the decoder_outputs, and the decoder_targets might have the same shape as required ( In my case, my decoder_targets has the shape [sequence_length, batch_size] ). So try to use tf.transpose to help you reshape the tensor.
has comment: http://stackoverflow.com/comment/110054346
score: 0
answers question: http://stackoverflow.com/q/52562888
type: Answer

http://stackoverflow.com/a/52527331
type: Answer
has body: Here is a way to do this! from glob import glob for filename in glob("./*.hrt"): Sin,Sout,IR = np.genfromtxt(str(filename),skip_header=11,usecols=(5,7,9),delimiter=' ', unpack = True)
score: 0
answers question: http://stackoverflow.com/q/52527191

http://stackoverflow.com/q/52469015
has answer: http://stackoverflow.com/a/52469519
possible better answer: http://stackoverflow.com/a/52469324
type: AnsweredQuestion
tagged with: loops
has comment: http://stackoverflow.com/comment/91880335
type: Question
upvote count: 2
downvote count: 2
tagged with: for-loop
tagged with: min
has answer: http://stackoverflow.com/a/52469324
has body: I have to write a program that calculates and displays the highest and second highest value entered by te user. The program must also work with zero or one values entered. Here are some sample runs: enter a value or 'stop' -3.2 enter a value or 'stop' -5.6 enter a value or 'stop' 0.5 enter a value or 'stop' 0.3 enter a value or 'stop' stop the highest value = 0.5 the second highest value = 0.3 and enter a value or 'stop' stop the highest value could not be calculated the second highest value could not be calculated So i got a code, but it only gives me the minimum and the maximum. all i got so far is this: minimum = None maximum = None a = int(input("Enter a value or 'stop': ")) while True: a = input("Enter a value or stop: ") if a == 'stop': break try: number = int(a) except: print("Invalid input") continue if minimum is None or number &lt; minimum: minimum = number if maximum is None or number &gt; maximum: maximum = number print('Maximum= ', maximum) print('Minimum= ', minimum) Would be awesome if someone could help me out!
tagged with: max
favorite count: 0
has title: I don't get this simple for-loop exercise
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52469226
accepted answer: http://stackoverflow.com/a/52469226
tagged with: python

http://stackoverflow.com/q/52449649
type: UnansweredQuestion
tagged with: viewer
has comment: http://stackoverflow.com/comment/91849643
type: Question
tagged with: dxf
tagged with: autocad
has body: I'm working in a program which creates the different views of a structure (isometric, top, front, and right), as you can see in Figure 1. Figure 1. Final plan of the structure. To achieve this sort of things, the software basically asks the user some data about the geometry and the weight the structure has to support, to then develop an internal calculation process. At the end, the user can ask the software to print the plan of the structure (AutoCAD free) in .dxf format. This was made in Python, with the dxfwrite library. The problem I'm facing is that, as the goal of the project is to be completely Open Source, when I open the plan in a viewer, let's say "Autodesk DWG TrueView", initially I've got this: Figure 2. Initial plan. Comparing Figures 1 and 2 is evident that I can manually orientate the views. The problem is when I try to print the plan, because despite of the final orientation I gave to the views, it prints what's seen on Figure 2. My question is: Does anybody know if there's a way to print the views in the correct order with this viewer? If so, how can I do it? (off course, I googled it, but I haven't found anything useful). If not, I would be thankful if you suggest me a .dxf viewer that allows me to move and print my 3D CAD in the exact position I need. PS: I'd read the dxfwrite documentation, and there's a way to specify the location of views in the viewports, but I haven't found an easy way to set the preset views in the viewports (it would be useful to know how to, and would be also validated as an answer to my problem).
tagged with: python
has title: Print preset views with a CAD Viewer (AutoCAD free)
has comment: http://stackoverflow.com/comment/91901249
score: 0
tagged with: automation
answer count: 0

http://stackoverflow.com/comment/91924018
has text: This question is a follow up to the question linked which specifically deals with the case of shell=True... the dupe link clearly does not explain the cause behind `ResourceWarning`. I don't understand why this is still marked as a duplicate. I'm not asking how to terminate a python subprocess with shell=True, I'm asking why, when terminating a python subprocess with shell=True, I get a `ResourceWarning`
comment on: http://stackoverflow.com/q/52476265
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52552560
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92045660
has comment: http://stackoverflow.com/comment/92045577
has comment: http://stackoverflow.com/comment/92046250
score: -1
has answer: http://stackoverflow.com/a/52554530
has title: a list of identical elements in the merge list
answer count: 2
possible better answer: http://stackoverflow.com/a/52553930
upvote count: 0
has comment: http://stackoverflow.com/comment/92046074
accepted answer: http://stackoverflow.com/a/52554530
has answer: http://stackoverflow.com/a/52553930
has comment: http://stackoverflow.com/comment/92045518
favorite count: 0
has comment: http://stackoverflow.com/comment/92044029
has comment: http://stackoverflow.com/comment/92045624
has body: I need to merge the list and have a function that can be implemented, but when the number of merges is very slow and unbearable, I wonder if there is a more efficient way Consolidation conditions：Sub-lists contain identical numbers to each other Thank you Simple Association: [7,8,9] = [7,8]+[8,9] #The same number 8 Cascade contains： [1,2,3] = [1,2,3]+[3,4] #The same number 3 [3,4,5,6] = [3,4],[4,5,6] #The same number 4 [1,2,3,4,5,6] = [1,2,3]+[3,4,5,6] #The same number 3 Function： a = [ [1,2,3],[4,5,6],[3,4],[7,8],[8,9],[6,12,13] ] b = len(a) for i in range(b): for j in range(b): x = list(set(a[i]+a[j])) y = len(a[j])+len(a[i]) if i == j or a[i] == 0 or a[j] == 0: break elif len(x) &lt; y: a[i] = x a[j] = [0] print a print [i for i in a if i!= [0]] result： [[8, 9, 7], [1, 2, 3, 4, 5, 6, 10, 11]] Above is an example where each sub-list in the actual calculation has a length of only 2, a = [[1,3],[5,6],[3,4],[7,8],[8,9],[12,13]] I want to miss out more data, here is a simulation data. a = np.random.rand(150,150)&gt;0.99 a[np.tril_indices(a.shape[1], -1)] = 0 a[np.diag_indices(a.shape[1])] = 0 a = [list(x) for x in np.c_[np.where(a)]] consolidate(a)
has comment: http://stackoverflow.com/comment/92045141
tagged with: python
has comment: http://stackoverflow.com/comment/92043940
linked to: http://stackoverflow.com/q/52241214
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92044340

http://stackoverflow.com/comment/91927114
type: Comment
comment on: http://stackoverflow.com/q/52492085
score: 0
has text: @SreeramTP can you help please?
type: QuestionComment

http://stackoverflow.com/a/52542468
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92024864
has body: I would try following (untested): x = len(df) num_index = range(0,x,1) df = df.reset_index() df = df.set_index(num_index)
answers question: http://stackoverflow.com/q/52542408
type: Answer
has comment: http://stackoverflow.com/comment/137158712
score: 2

http://stackoverflow.com/comment/91945076
type: Comment
type: AnswerComment
has text: Thanks, I have attempted this also, but the issue I was facing was to get the "username:password" string as a variable. I think the code example I provided in the question may have misled you. I'll edit it.
score: 0
comment on: http://stackoverflow.com/a/52501866

http://stackoverflow.com/a/52452070
score: 0
answers question: http://stackoverflow.com/q/52433414
type: Answer
has body: If your project root directory is LoginAPI then you don't add it to call the modules. Assuming then from what you specify as folder structure # project root directory LoginAPI/ # app directories LoginAPI/ urls.py LoginApp/ views.py So you should call from LoginApp.views import register_view, login_view, logout_view

http://stackoverflow.com/comment/91986329
has text: @JPG Can you show an example how it could be done?
score: 0
comment on: http://stackoverflow.com/q/52523297
type: Comment
type: QuestionComment

http://stackoverflow.com/a/54981437
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52553735
has body: As I know Fuzzy Lookup use Jaccard similarity. Look into its documentation. As I play around you can also try SequenceMatcher and play with similarity levels - it gives very nice results after some unifying text strings.

http://stackoverflow.com/a/52511261
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91962732
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52510764
answers question: http://stackoverflow.com/q/52510764
type: Answer
has body: As I said in my comment: Use variables in Form class. class InputForm(forms.Form): name = forms.CharField(max_length=100) name_data = "" age = forms.CharField(max_length=100) age_date = 0 def logic(self): # I want to use views.py’s name&amp;age’s value here # You can play here with your age_data and name_data And views.py: def app(request): if request.method == "POST": form = InputForm(data=request.POST) if form.is_valid(): form.name_data = form.cleaned_data['name'] age.name_data = form.cleaned_data['age'] EDIT ( I needed a coffee, sorry.. ) I have just seen that your cleaned_data come from your form so why not working in it directly like this in form Class: class InputForm(forms.Form): name = forms.CharField(max_length=100) age = forms.CharField(max_length=100) def logic(self): # I want to use views.py’s name&amp;age’s value here # Why don't you use cleaned_data['name'] and age from here? name = cleaned_data['name'] and simply keep your view like this. def app(request): if request.method == "POST": form = InputForm(data=request.POST) if form.is_valid(): name = form.cleaned_data['name'] age = form.cleaned_data['age'] Not sure this will work at 100% procent but the goal of this answer is not to give you the exact solution but to let you experiment with your problem a bit. As a Python beginer you will learn more if you try by yourself and make a few reasearches. Also consider reading this: https://docs.djangoproject.com/en/2.1/topics/forms/#building-a-form-in-django
has comment: http://stackoverflow.com/comment/91962683

http://stackoverflow.com/a/52462006
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52460327
type: Answer
has comment: http://stackoverflow.com/comment/91954491
accepted answer of: http://stackoverflow.com/q/52460327
has body: As you already explained that you won't be able to insert data. So only thing is possible is first take the unique values to a list.df['column_name'].unique(). Then you can use the $in operator in .find() method and pass your list as a parameter. If it takes time or it is too much. Then break your list in equal chunks, I mean list of list [[id1, id2, id3], [id4, id5, id6] ... ] and do a for loop for sub-list in list: db.xyz.find({'key':{'$in': sublist}}, {'_id': 1}) and use the sub list as parameter in $in operator. Then for each iteration if the value exist in the db it will return the _id and we can easily store that in a empty list and append it and we will be able to get all the id's in such cases where the value exist in the collection. So it's just the way I would do. Not necessarily the best possible.
upvote count: 1

http://stackoverflow.com/q/52495310
has comment: http://stackoverflow.com/comment/92260639
accepted answer: http://stackoverflow.com/a/52645238
has comment: http://stackoverflow.com/comment/91933064
tagged with: pandas
has comment: http://stackoverflow.com/comment/92206619
tagged with: python
has body: I have a Pandas dataframe where I'd like to resample to every third Friday of the month. np.random.seed(0) #requested output: dates = pd.date_range("2018-01-01", "2018-08-31") dates_df = pd.DataFrame(data=np.random.random(len(dates)), index=dates) mask = (dates.weekday == 4) &amp; (14 &lt; dates.day) &amp; (dates.day &lt; 22) dates_df.loc[mask] But when a third Friday is missing (e.g. dropping Feb third Friday), I want to have the latest value (so as of 2018-02-15). Using the mask gives me the next value (Feb 17 instead of Feb 15): # remove February third Friday: dates_df = dates_df.drop([pd.to_datetime("2018-02-16")]) mask = (dates.weekday == 4) &amp; (14 &lt; dates.day) &amp; (dates.day &lt; 22) dates_df.loc[mask] Using monthly resample in combination with loffset gives the end of month values with offsetting the index, which is also not what I want: from pandas.tseries.offsets import WeekOfMonth dates_df.resample("M", loffset=WeekOfMonth(week=2, weekday=4)).last() Is there an alternative (preferably using resample) without having to resample to daily values first and then adding a mask (this takes a long time to complete on my dataframe)
has comment: http://stackoverflow.com/comment/91932042
favorite count: 0
has answer: http://stackoverflow.com/a/52645238
linked to: http://stackoverflow.com/q/29871564
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92265938
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/92266729
has comment: http://stackoverflow.com/comment/92259230
tagged with: time-series
answer count: 1
score: 4
has title: pandas resample to specific weekday in month
has comment: http://stackoverflow.com/comment/92196756

http://stackoverflow.com/a/70619972
downvote count: 1
answers question: http://stackoverflow.com/q/52530690
type: Answer
has body: If anyone comes here again, this is what I use def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.execute("ALTER TABLE {table_name} ALTER COlUMN {column_name} set DEFAULT {new_default_value};") # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.execute("ALTER TABLE {table_name} ALTER COlUMN {column_name} set DEFAULT {old_default_value};") # ### end Alembic commands ###
score: 5
upvote count: 6

http://stackoverflow.com/q/52558461
tagged with: python
downvote count: 1
has body: There are similar questions, but my datetime objects are very spatial and not ordered e.g. they are random timestamps in time. Basically what I need is to use rolling() but roll it over the 2nd index while remembering the group (1st index). There is a very similar GitHub issue that you might also want to contribute to: https://github.com/pandas-dev/pandas/issues/15584 Code to reproduce: import pandas as pd data = { 'id': ['A','A','A','B'], 'time': pd.to_datetime(['2018-01-04 08:13:51.181','2018-01-04 08:13:55.181','2018-01-04 09:13:51.181', '2018-01-04 08:13:51.183']), 'colA': [4,3,2,1], '30min_rolling_output': [4,7,2,1], '1day_rolling_output': [4,7,9,1] } test_df = pd.DataFrame(data=data).set_index(['id', 'time']) The desired output is assuming the 30m and 1h arguments. Visualising: colA 30min_rolling_output 1day_rolling_output id date A 2018-01-04 08:13:51.181 4 4 4 2018-01-04 08:13:55.181 3 7 7 2018-01-04 09:13:51.181 2 2 9 B 2018-01-04 08:13:51.183 1 1 1
type: AnsweredQuestion
has title: Pandas Rolling On DateTime Multi Index Frame
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/52558573
has comment: http://stackoverflow.com/comment/118404202
tagged with: pandas
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52558573
score: 6

http://stackoverflow.com/q/52459208
has body: I am trying to change a value in settings.py during run-time while creating migrations. settings.py: ... magicVar = "initValue" 0002_init: ... def change_magicVar(apps, schema_editor): settings.magicVar = "newValue" ... operations = [ migrations.RunPython(change_magicVar), ] ... 0003_changed_migrations: ... def print_magicVar(apps, schema_editor): # Yay! It prints the correct value print (settings.magicVar) # prints: newValue ... operations = [ migrations.RunPython(print_magicVar), migrations.CreateModel( name='MagicModel', fields=[ ('someMagic', models.ForeignKey( # Oops! This still has the old value, i.e *initValue* # I want to achieve the *newValue* here! default=settings.magicVar, ... )), I want the changed value in migrations, but it looks like the value is already been cached. Does django provide an abstraction to refresh the migrations cache and put a new value in it? If not, what possible options do i have to achieve that value in the defaults? Note: I am trying to avoid this solution because my database might give millions of records and iterating over them isn't ideal. For external reasons i am also trying to avoid django-livesettings Thank you!
type: Question
tagged with: django-migrations
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/29787853
has answer: http://stackoverflow.com/a/52580734
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52580734
has title: Django: Change settings value during run-time in migrations

http://stackoverflow.com/a/52486332
type: Answer
has body: OK. You're not assigning a return value, and print doesn't return anything to the client. This will return a response to the client: from django.http import JsonResponse def post(self, request, *args, **kwargs): some_text = 'A reply' return JsonResponse({'some_text': some_text})
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91914096
accepted answer of: http://stackoverflow.com/q/52485191
has comment: http://stackoverflow.com/comment/91915085
answers question: http://stackoverflow.com/q/52485191

tensorflow
tags question: http://stackoverflow.com/q/52431372
tags question: http://stackoverflow.com/q/52551296
tags question: http://stackoverflow.com/q/52575271
tags question: http://stackoverflow.com/q/52440940
tags question: http://stackoverflow.com/q/52582217
tags question: http://stackoverflow.com/q/52510737
tags question: http://stackoverflow.com/q/52453285
tags question: http://stackoverflow.com/q/52579346
tags question: http://stackoverflow.com/q/52452622
tags question: http://stackoverflow.com/q/52471819
tags question: http://stackoverflow.com/q/52562967
tags question: http://stackoverflow.com/q/52443804
tags question: http://stackoverflow.com/q/52479272
tags question: http://stackoverflow.com/q/52465370
tags question: http://stackoverflow.com/q/52538273
tags question: http://stackoverflow.com/q/52507334
tags question: http://stackoverflow.com/q/52525362
tags question: http://stackoverflow.com/q/52522590
tags question: http://stackoverflow.com/q/52555024
tags question: http://stackoverflow.com/q/52530724
tags question: http://stackoverflow.com/q/52485793
tags question: http://stackoverflow.com/q/52447345
tags question: http://stackoverflow.com/q/52507352
tags question: http://stackoverflow.com/q/52574989
tags question: http://stackoverflow.com/q/52494280
tags question: http://stackoverflow.com/q/52459843
tags question: http://stackoverflow.com/q/52519307
tags question: http://stackoverflow.com/q/52441790
tags question: http://stackoverflow.com/q/52522755
tags question: http://stackoverflow.com/q/52524352
tags question: http://stackoverflow.com/q/52493118
tags question: http://stackoverflow.com/q/52448652
tags question: http://stackoverflow.com/q/52507306
tags question: http://stackoverflow.com/q/52445630
tags question: http://stackoverflow.com/q/52454781
tags question: http://stackoverflow.com/q/52520825
tags question: http://stackoverflow.com/q/52481134
tags question: http://stackoverflow.com/q/52440541
tags question: http://stackoverflow.com/q/52528251
tags question: http://stackoverflow.com/q/52556337
tags question: http://stackoverflow.com/q/52577355
tags question: http://stackoverflow.com/q/52447908
tags question: http://stackoverflow.com/q/52573678
tags question: http://stackoverflow.com/q/52496804
tags question: http://stackoverflow.com/q/52548643
tags question: http://stackoverflow.com/q/52438344
tags question: http://stackoverflow.com/q/52553796
tags question: http://stackoverflow.com/q/52565404
tags question: http://stackoverflow.com/q/52542342
tags question: http://stackoverflow.com/q/52488547
tags question: http://stackoverflow.com/q/52509328
tags question: http://stackoverflow.com/q/52453530
tags question: http://stackoverflow.com/q/52543267
tags question: http://stackoverflow.com/q/52458697
tags question: http://stackoverflow.com/q/52490607
tags question: http://stackoverflow.com/q/52534202
tags question: http://stackoverflow.com/q/52475396
tags question: http://stackoverflow.com/q/52572508
tags question: http://stackoverflow.com/q/52562888
tags question: http://stackoverflow.com/q/52516101
tags question: http://stackoverflow.com/q/52521722
tags question: http://stackoverflow.com/q/52542275
tags question: http://stackoverflow.com/q/52583219
tags question: http://stackoverflow.com/q/52432681
tags question: http://stackoverflow.com/q/52512381
tags question: http://stackoverflow.com/q/52497450
tags question: http://stackoverflow.com/q/52481006
tags question: http://stackoverflow.com/q/52554272
tags question: http://stackoverflow.com/q/52539110
tags question: http://stackoverflow.com/q/52515273
tags question: http://stackoverflow.com/q/52500185
tags question: http://stackoverflow.com/q/52463551
tags question: http://stackoverflow.com/q/52442789
tags question: http://stackoverflow.com/q/52447384
tag name: tensorflow
tags question: http://stackoverflow.com/q/52518134
tags question: http://stackoverflow.com/q/52483437
tags question: http://stackoverflow.com/q/52561878
tags question: http://stackoverflow.com/q/52461624
tags question: http://stackoverflow.com/q/52463621

http://stackoverflow.com/comment/91848646
score: 0
has text: Try using https://regex101.com/ to test the regular expression you're trying to use. If the "findall" isn't returning anything, it's because the regular expression isn't matching.
comment on: http://stackoverflow.com/q/52452675
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52583329
has body: First of all I'd like to congratulate you on being so through with your first question! Many older contributors don't go into as much depth as you. So first let's get things straight. You mention that --lower-case-table-names=0 is enabled but collation is case insensitive. From the docs I see that the option forces case sensitivity for table names. I might just be reading it wrong but it looks like you're saying everything should be case insensitive. Also collation usually refers to the data itself, not column names in case you're unaware. That said as far as I know, all databases treat column names case-insensitively (I just tested in SQLite) so you might have just uncovered a bug in Django! I looked through the history of the file, and in the 5-odd years that code has existed I guess no one ran into this issue. It's understandable since usually people either a) just let django create the db from scratch and thus everything is in sync, or b) they use inspectdb to generate the code with the right case for the columns. It looks like you were just playing around so I don't think you are looking for a specific solution. Perhaps the next step is to file a bug ;)? From what I see there would be no downside to adding case-insensitive comparison there, but the guys working on Django 24/7 may have a different opinion.
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/92119801
has comment: http://stackoverflow.com/comment/92108588
accepted answer of: http://stackoverflow.com/q/52580751
answers question: http://stackoverflow.com/q/52580751
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91924131
has text: If you mean that you have a lot of keywords that are repeated in each call to `hist`, you could define a dict of keywords beforehand, say `my_style = dict(...)` and then pass that dict to the `hist` call as `ax.hist(..., **my_style)`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52491534
type: QuestionComment

http://stackoverflow.com/comment/92198938
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52480212
has text: I dont guess if there is anything related to flask, since u are updating the html, it will get executed, so u will have to validate data in the flask or just stop updating the html, get the json and then set it on your tag, but instead of html, set it as value or text
score: 0

http://stackoverflow.com/comment/91860774
type: AnswerComment
score: 0
type: Comment
has text: This is awesome! The only thing is my next step it to convert the ints into binary. That's the final goal. In other words:
comment on: http://stackoverflow.com/a/52459274

http://stackoverflow.com/comment/92083324
comment on: http://stackoverflow.com/q/52573540
score: 0
has text: Where is the code where you write to the file?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91948344
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52503728
has text: Thanks Brian. What happened to `loan_number`?
score: 0

http://stackoverflow.com/comment/91830340
comment on: http://stackoverflow.com/a/52443819
type: Comment
score: 7
has text: It would be great if you explain this one liner `re.findall(r"[A-Za-z]+", st)`. It would be helpful to understand how it works for a larger audience reading your answer now and in the future
type: AnswerComment

http://stackoverflow.com/q/52550304
type: Question
tagged with: python
upvote count: 3
has comment: http://stackoverflow.com/comment/92039421
score: 0
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/92039428
has comment: http://stackoverflow.com/comment/92039470
has body: I need to print a sequence of odd numbers in increasing order. I can solve it only in decreasing order. num = int(input(print("Type any integer: "))) count = 1 while count &lt;= num: num -= 1 if num % 2 != 0: print(num)
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21793424
has comment: http://stackoverflow.com/comment/92039395
has comment: http://stackoverflow.com/comment/92039616
has answer: http://stackoverflow.com/a/52550433
has comment: http://stackoverflow.com/comment/92039586
duplicate of: http://stackoverflow.com/q/21793424
has comment: http://stackoverflow.com/comment/92039675
has comment: http://stackoverflow.com/comment/92039543
has comment: http://stackoverflow.com/comment/92039452
has title: How to print odd numbers in increasing order?
favorite count: 0
has answer: http://stackoverflow.com/a/52550341

http://stackoverflow.com/a/52588697
downvote count: 0
score: 1
has body: You can query for the items which are excluded in a relationship by using the NOT EXISTS construct on a joined table. @property def potential_attendees(self): sq = db.session.query(contact_party_ass_tab.columns.contact_id).subquery() return db.session.query(Contact).filter( Contact.party_organiser_id==self.party_organiser_id, ~exists().where(sq.c.contact_id==Contact.id) ).all() As far as your other question is concerned, you can impose that constraint on the ORM level by adding attribute level validators for Party.attendees and Contact.intended_parties and ensuring that any new item added to those lists has a matching party_organiser_id. Here is the full code from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import exists from sqlalchemy.orm import validates app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' db = SQLAlchemy(app) class PartyOrganiser(db.Model): __tablename__ = 'party_organiser' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) parties = db.relationship("Party", back_populates='party_organiser') contacts = db.relationship("Contact", back_populates='party_organiser') def __repr__(self): return self.name contact_party_ass_tab = db.Table('contact_party', db.Model.metadata, db.Column('party_id', db.Integer, db.ForeignKey('party.id')), db.Column('contact_id', db.Integer, db.ForeignKey('contact.id'))) class Party(db.Model): __tablename__ = 'party' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) details = db.Column(db.String) party_organiser_id = db.Column(db.Integer, db.ForeignKey('party_organiser.id'), nullable=False) party_organiser = db.relationship("PartyOrganiser", back_populates="parties", uselist=False) attendees = db.relationship("Contact", secondary=contact_party_ass_tab, back_populates='intended_parties') def __repr__(self): return self.name @property def potential_attendees(self): sq = db.session.query(contact_party_ass_tab.columns.co…
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52587604
accepted answer of: http://stackoverflow.com/q/52587604

http://stackoverflow.com/comment/91899732
comment on: http://stackoverflow.com/q/52477795
type: Comment
has text: What happens if you use something like `printf ‘%s\n’ dude how are you | ./pycalc.py | cat`? This gives your script piped input and output; does it produce 4 base-64 encoded lines? Or does it produce just one?
score: 0
type: QuestionComment

joystick
type: Tag
tags question: http://stackoverflow.com/q/52457595
tag name: joystick

http://stackoverflow.com/q/52557689
accepted answer: http://stackoverflow.com/a/52557995
type: Question
tagged with: for-loop
has body: I'm trying to make a change maker with a for loop so it tells me how much coins (quarters, dimes, nickels, pennies) it takes to get to the inputted amount. Here is my code so far: amount = input("Enter the amount of change owed: ") amount = int(amount) coins = [25, 10, 5, 1] for coin in coins: I'm not exactly sure how to iterate through the list and have it tell me how much of each coin would be in the inputted amount. For example, it would probably look something like this: Enter the amount of change owed: 99 Quarters: 3 Dimes: 9 Nickels: 19 Pennies: 99 Sorry for the stupid question, I'm still getting used to python. Thank you for reading.
score: 0
answer count: 1
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92054104
has title: Change maker with for loop
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52557995

http://stackoverflow.com/q/52467177
has comment: http://stackoverflow.com/comment/91876613
tagged with: python
has comment: http://stackoverflow.com/comment/91877844
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/91882787
has answer: http://stackoverflow.com/a/52470415
tagged with: tensorflow
type: AnsweredQuestion
has body: I am getting an error on fit_generator. My generator returns the following: yield(row.values, label) For example, using it: myg = generate_array() for i in myg: print((i[0].shape)) print(i) break (9008,) (array([0.116516, 0.22419 , 0.03373 , ..., 0. , 0. , 0. ]), 0) But the following throws an exception: model = Sequential() model.add(Dense(84, activation='relu', input_dim=9008)) ValueError: Error when checking input: expected dense_1_input to have shape (9008,) but got array with shape (1,) Any idea?
type: Question
has title: Using Keras fit_generator gives an error of wrong shape
accepted answer: http://stackoverflow.com/a/52470415
answer count: 1
tagged with: keras
tagged with: keras-layer

http://stackoverflow.com/q/52431823
score: 0
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91811290
accepted answer: http://stackoverflow.com/a/52431865
answer count: 2
tagged with: pandas
tagged with: scikit-learn
favorite count: 0
possible better answer: http://stackoverflow.com/a/52445899
has answer: http://stackoverflow.com/a/52445899
has comment: http://stackoverflow.com/comment/91831860
tagged with: python
has body: I have completed a machine learning algorithm that classifies categories from text. I am 99 percent done however i do now know to to merge my prediction results back to the original dataframe to see a print view of what i started with and what the prediction was. here is my code below. #imports data from excel file and shows first 5 rows of data file_name = r'C:\Users\aac1928\Documents\Machine Learning\Training Data\RFP Training Data.xlsx' sheet = 'Sheet1' import pandas as pd import numpy import xlsxwriter import sklearn df = pd.read_excel(io=file_name,sheet_name=sheet) #extracts specifics rows from data data = df.iloc[: , [0,2]] print(data) #Gets data ready for model newdata = df.iloc[:,[1,2]] newdata = newdata.rename(columns={'Label':'label'}) newdata = newdata.rename(columns={'RFP Question':'question'}) print(newdata) # how to define X and yfor use with COUNTVECTORIZER X = newdata.question y = newdata.label print(X.shape) print(y.shape) # split X and y into training and testing sets X_train = X y_train = y X_test = newdata.question[:50] y_test = newdata.label[:50] print(X_train.shape) print(X_test.shape) print(y_train.shape) print(y_test.shape) # import and instantiate CountVectorizer (with the default parameters) from sklearn.feature_extraction.text import CountVectorizer vect = CountVectorizer() # equivalently: combine fit and transform into a single step X_train_dtm = vect.fit_transform(X_train) # transform testing data (using fitted vocabulary) into a document-term matrix X_test_dtm = vect.transform(X_test) X_test_dtm # import and instantiate a logistic regression model from sklearn.linear_model import LogisticRegression logreg = LogisticRegression() # train the model using X_train_dtm %time logreg.fit(X_train_dtm, y_train) # make class predictions for X_test_dtm y_pred_class = logreg.predict(X_test_dtm) y_pred_class # calculate predicted probabilities for X_test_dtm (well calibrated) y_pred_prob = logreg.predict_proba(X_test_dtm)[:, 1] y_pred_prob # calculat…
has title: Merging results from Prediction to Original Data frame?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91810402
tagged with: prediction
has answer: http://stackoverflow.com/a/52431865

http://stackoverflow.com/comment/92011316
type: Comment
comment on: http://stackoverflow.com/a/52533757
score: 2
type: AnswerComment
has text: Arf ! very creative work-around for a totally silly requirement !-)

http://stackoverflow.com/comment/92063704
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52562451
score: 0
has text: @wen yes I know I can pass '' to NaN - I am deciding whether to!

http://stackoverflow.com/a/52537000
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92013414
type: Answer
accepted answer of: http://stackoverflow.com/q/52536839
answers question: http://stackoverflow.com/q/52536839
has body: You have to rename the start_request method to start_requests, which is the method that you have to override from the base Spider class. More info here. What's happening is that your spider is not issuing any requests because of the missing start_requests method. This is how it is supposed to be: import scrapy class HackaholicSpider(scrapy.Spider): name = "hackaholic" def start_requests(self): urls = ['http://hackaholic.info'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) ...
score: 1

http://stackoverflow.com/comment/92013661
has text: because there are nested data also inside NAME and class...so thats why recursive is best
comment on: http://stackoverflow.com/q/52536958
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52559552
has title: python indentation, SyntaxError: invalid syntax
has comment: http://stackoverflow.com/comment/92057751
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/92057769
has comment: http://stackoverflow.com/comment/92057740
tagged with: python
has comment: http://stackoverflow.com/comment/92057848
linked to: http://stackoverflow.com/q/30981630
has answer: http://stackoverflow.com/a/52559658
duplicate of: http://stackoverflow.com/q/30981630
score: -1
upvote count: 1
type: Question
answer count: 2
has body: Please what's wrong with my python code, it always reports File "lake.py", line 28 SyntaxError: invalid syntax`. I wonder, is it the brackets? or what could be causing the error, I will appreciate any help thank you def count(m, n): if(n &lt; m): temp = n n = m m = temp return m * (m + 1) * (2 * m + 1) / 6 + (n - m) * m * (m + 1) / 2 arr = [] arr2 = [] foo = 100 n = foo if (n == 1): print('1') print('1 1') else: for m in range(n): n=(((6 * foo) - (m * (m + 1) * (2 * m + 1))) / (3 * ((m * m) + m))) + m if (count(m, n) == foo and m &lt;= n): arr.append(''+str(int(m))+' ' + str(int(n))+'') if(m != n): arr2.append(''+str(int(n)+' ' + str(int(m)+'') arr = arr + arr2 arrLength = len(arr) print(arrLength) for g in range(arrLength): print(arr[g])
has answer: http://stackoverflow.com/a/52559613

http://stackoverflow.com/q/52559576
has answer: http://stackoverflow.com/a/65854155
has comment: http://stackoverflow.com/comment/92058116
has body: In the MongoDB console, I know that you can use $ last and $ natural. In PyMongo, I could not use it, maybe I was doing something wrong?
tagged with: python
type: AnsweredQuestion
has title: PyMongo how to get the last item in the collection?
score: 1
has comment: http://stackoverflow.com/comment/92061477
has answer: http://stackoverflow.com/a/52561517
tagged with: pymongo
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52561517
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/65854155
favorite count: 0

http://stackoverflow.com/q/52516918
tagged with: python
has comment: http://stackoverflow.com/comment/91973566
has comment: http://stackoverflow.com/comment/91974172
has title: Having trouble with exempt url
type: AnsweredQuestion
score: 0
type: Question
has comment: http://stackoverflow.com/comment/91973913
has body: Hi I am trying to exempt a url in my project so that the user can bypass the middleware and reset their password without being logged in. However the urls I have placed in LOGIN_EXEMPT_URLS don't seem to fix this, instead the link to reset-password redirects the user to account/login. settings.py: LOGIN_EXEMPT_URLS = { r'^account/logout/$', r'^account/register/$', r'^account/reset-password$', r'^account/reset-password/done/$', r'^account/reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$', r'^account/reset-password/complete/$', } middleware.py: url_is_exempt = any(url.match(path)for url in EXEMPT_URLS) if path == reverse('accounts:logout').lstrip('/'): logout(request) if request.user.is_authenticated and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated or url_is_exempt: return None else: return redirect(settings.LOGIN_URL) urls.py: urlpatterns = [ url(r'^$', views.home), url(r'^login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.view_profile, name='view_profile'), url(r'^profile/edit/$', views.edit_profile, name='edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^reset-password/$', PasswordResetView.as_view(template_name='accounts/reset_password.html', success_url=reverse_lazy('accounts:password_reset_done')), name='reset_password'), url(r'^reset-password/done/$', PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] main/ur…
has comment: http://stackoverflow.com/comment/91973477
has comment: http://stackoverflow.com/comment/91973605
answer count: 1
has answer: http://stackoverflow.com/a/52517731
accepted answer: http://stackoverflow.com/a/52517731
tagged with: django

distribution
tags question: http://stackoverflow.com/q/52566855
tags question: http://stackoverflow.com/q/52455797
tags question: http://stackoverflow.com/q/52546617
tags question: http://stackoverflow.com/q/52470172
tag name: distribution
tags question: http://stackoverflow.com/q/52474817
type: Tag

http://stackoverflow.com/comment/92074089
comment on: http://stackoverflow.com/q/52568003
score: 0
type: Comment
type: QuestionComment
has text: The full test can be found here: https://github.com/sineadmcaleer/cs3012-1/blob/master/test_tree.py I am running using the following statement: coverage run -- tree.py -m test_tree.py and the out put is : Name Stmts Miss Cover ----------------------------- tree.py 28 22 21%

http://stackoverflow.com/a/52573663
score: 1
has body: The problem is that this line is trying to do too many things at once: datl4 = [[line[0]] + [float(x) for x in line[1]] + [line[2]] for line in datl3] The problem occurs in the inner list comprehension: [float(x) for x in line[1]] But what is line[1]? It comes from the iteration for line in datl3. So let's see what values it has: &gt;&gt;&gt; [line[1] for line in datl3] ['2.555', '6.777'] So when you do [float(x) for x in line[1]] you are iterating over the characters of each numerical string..."2" then "." then "5" then "5" then "5". But "." is not a valid float. I think what you want to do instead is just convert line[1] to a float: lines = [[line[0], float(line[1]), line[2]] for line in lines]
upvote count: 1
answers question: http://stackoverflow.com/q/52573623
type: Answer
downvote count: 0

http://stackoverflow.com/q/52578755
has comment: http://stackoverflow.com/comment/92166340
score: 1
has body: It is spotted on google cloud engine. Multiple instances of my script are created (by bash?). The reason might be that the script demands very high amount of memory. How is this division done exactly? Any performance impact? [UPDATE] My mistake. These instances are threads created by python.
type: Question
upvote count: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92094668
tagged with: linux
has comment: http://stackoverflow.com/comment/92092731
tagged with: python
accepted answer: http://stackoverflow.com/a/52579287
favorite count: 0
has title: Are resource demanding process divided into multiple processes?
tagged with: process
tagged with: google-compute-engine
has answer: http://stackoverflow.com/a/52579287
type: AnsweredQuestion

http://stackoverflow.com/comment/91911556
comment on: http://stackoverflow.com/a/52485016
type: AnswerComment
has text: You don't need to re-define the index. It is not a necessary step. You can proceed as such
score: 0
type: Comment

http://stackoverflow.com/q/52577413
answer count: 3
score: 2
favorite count: 0
tagged with: python-3.x
has title: Using two np.linspace, how to fill 2D array with complex values?
has answer: http://stackoverflow.com/a/52577542
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52577609
has answer: http://stackoverflow.com/a/52577582
upvote count: 3
downvote count: 1
type: Question
tagged with: numpy
has body: I'm trying to fill a 2D array with complex(x,y), where x and y are from two two arrays: xstep = np.linspace(xmin, xmax, Nx) ystep = np.linspace(ymin, ymax, Ny) However I can't figure out how to "spread" these values out on a 2D array. So far my attempts are not really working out. I was hoping for something along the lines of: result = np.array(xstep + (1j * ystep)) Maybe something from fromfunction, meshgrid or full, but I can't quite make it work. As an example, say I do this: xstep = np.linspace(0, 1, 2) # array([0., 1.]) ystep = np.linspace(0, 1, 3) # array([0. , 0.5, 1. ]) I'm trying to construct an answer: array([ [0+0j, 0+0.5j, 0+1j], [1+0j, 1+0.5j, 1+1j] ]) Note that I am not married to the linspace, so any quicker method would also do, it is just my natural starting point for creating this array, being new to Numpy.

http://stackoverflow.com/comment/91957619
score: 0
type: QuestionComment
type: Comment
has text: What arguments does `floodfill` require, and what did you feed it? There appears to be a mismatch.
comment on: http://stackoverflow.com/q/52508440

http://stackoverflow.com/q/52432356
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52432437
favorite count: 0
tagged with: pandas
has body: I would like to groupby one of the levels of a pandas dataframe whose index and columns are a Multindex. I'd like to do groupby one of the levels of the header but it gives me a key error and I am not sure why. This dataframe could be used as exemple: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) arrays2 = [['bar','baz','foo','qux'], ['one','two','one','two'], ['a','b','c','d']] tuples2 = list(zip(*arrays2)) header = pd.MultiIndex.from_tuples(tuples, names=['h1', 'h2']) index = pd.MultiIndex.from_tuples(tuples2, names=['first', 'second','third']) df2=pd.DataFrame(np.random.randn(3, 3), index=index[:3], columns=header[:3]) If I try to do df2.groupby('h1',axis=1).sum() I get a key error, but with the index works fine. df2.groupby(df2.index.names[0],axis=0).sum() what is the cause and how could I solve it?
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52432437
has title: pandas groupby multilevel header

http://stackoverflow.com/comment/91919327
comment on: http://stackoverflow.com/q/52488117
score: 1
has text: does it work when you try `json.loads(requests.get(url).text)`?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52481473
has body: In general, it is better to avoid using threads manually, and use a thread pool executor. Something like with futures.ThreadPoolExecutor(workers=5) as executor: result = executor.map(Add, [0, 1, 2, 3, 4]) and so on for your other arguments.
accepted answer of: http://stackoverflow.com/q/52479813
answers question: http://stackoverflow.com/q/52479813
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52462196
downvote count: 0
has body: Here's a short solution using more-itertools. from fnmatch import fnmatch from more_itertools import split_before with open('whatever_file.txt', 'rt') as infile: for group in split_before(infile, lambda s: fnmatch(s, '*/*, *:* * - *')): print(group) The output is: ['11/28/17, 10:00 AM - Bob: Lorem ipsum dolor sit amet\n'] ['11/28/17, 10:00 AM - Marley: Yes!\n'] ['11/28/17, 10:00 AM - Marley: consectetur adipiscing elit\n'] ['11/28/17, 10:00 AM - Bob: Barely dude. BARELY\n'] ['11/28/17, 10:01 AM - Bob: sed do eiusmod tempor incididunt ut labore et dolore magna aliqua\n'] ['11/28/17, 10:14 AM - Marley: Ut enim ad minim veniam\n'] ['11/28/17, 10:20 AM - Marley: quis nostrud exercitation\n', 'Duis aute irure dolor in\n'] ['11/28/17, 10:31 AM - Bob: Hahaha proud\n'] ["11/28/17, 10:31 AM - Bob: Can't imagine\n"] This works by splitting the iterable (here the lines of the file) any place there's a line that starts with the date format. I used fnmatch for this, but you could use a function that uses datetime.strptime as well.
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52435189
upvote count: 1

http://stackoverflow.com/comment/92021777
comment on: http://stackoverflow.com/q/52540892
has text: Have you called `reset` (or otherwise set the values of `curHP` and `maxHP`) before you call `gamestart`? Do you have more than one module involved? (Global variables aren't truly global; they are local to a module.) This is why we need a minimal, complete, and verifiable example to reproduce your error.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52498638
type: Question
has comment: http://stackoverflow.com/comment/91937864
has comment: http://stackoverflow.com/comment/91938273
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52498676
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52499045
has title: How to split a file into two separate arrays?
has answer: http://stackoverflow.com/a/52498929
has body: I need to split a file into 2 separate arrays. What I mean is to split a username:password file into a username and a password arrays and then be able to call them by the same index number, to make the usernames and passwords match. So far I have : with open('userlist.txt', 'r') as userlist: for line in userlist: user, pwd = line.strip().split(':') Instead of the code splitting in to 2 different variables, I want to split them into 2 different arrays. This way I can call them by the same index number to get the user:pass combo. Thanks.

http://stackoverflow.com/comment/91836249
type: AnswerComment
score: 0
type: Comment
has text: I guess simpler with : `myarray[(slice(None),)*N+(0,)*(myarray.ndim-N)]`. Existing one threw error.
comment on: http://stackoverflow.com/a/52446590

http://stackoverflow.com/a/52537818
accepted answer of: http://stackoverflow.com/q/52537561
type: Answer
upvote count: 2
has body: QMainWindow already provides the contextMenuEvent method which is called by the Qt framework. In your class, you are overriding this method so that your method is called instead of the one from QMainWindow. See also QMainWindow::contextMenuEvent() Qt Documentation: Menus Example
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52537561

http://stackoverflow.com/comment/91944425
comment on: http://stackoverflow.com/a/52501634
score: 0
type: AnswerComment
type: Comment
has text: I was under the impression that you were defining i_NP and j_NP and this was part of a larger function. That is the context within which this will work. If you just want to print the result and not yield it, change the `yield` for a `print(sentence)`

http://stackoverflow.com/a/52513296
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52513200
answers question: http://stackoverflow.com/q/52513200
type: Answer
has body: You can use collections.defaultdict() to have your values automatically added when the same key is encountered, something like: import collections listA = ['Apple', 'Apple', 'Banana', 'Orange', 'Pineapple', 'Pineapple'] listB = ['5.0', '9.0', '12.0', '2.0', '8.0', '1.0'] result = collections.defaultdict(float) for k, v in zip(listA, listB): result[k] += float(v) This will, however, produce a result with floats, i.e.: {'Apple': 14.0, 'Banana': 12.0, 'Orange': 2.0, 'Pineapple': 9.0} If you need string results, you can either post-process the result: result = {k: str(v) for k, v in result.iteritems()} # Python 3.x: result.items() # {'Apple': '14.0', 'Banana': '12.0', 'Orange': '2.0', 'Pineapple': '9.0'} Or you can handle the whole thing without collections.defaultdict(): listA = ['Apple', 'Apple', 'Banana', 'Orange', 'Pineapple', 'Pineapple'] listB = ['5.0', '9.0', '12.0', '2.0', '8.0', '1.0'] result = {} for k, v in zip(listA, listB): result[k] = str(float(result.get(k, 0)) + float(v)) # {'Apple': '14.0', 'Banana': '12.0', 'Orange': '2.0', 'Pineapple': '9.0'}
upvote count: 2

http://stackoverflow.com/a/52543387
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92028358
has body: pandas is experimenting with the input (Series by Series or the whole DataFrame) to see if the function can be applied more efficiently. The notes from the docstring: The current implementation imposes three requirements on f: f must return a value that either has the same shape as the input subframe or can be broadcast to the shape of the input subframe. For example, f returns a scalar it will be broadcast to have the same shape as the input subframe. if this is a DataFrame, f must support application column-by-column in the subframe. If f also supports application to the entire subframe, then a fast path is used starting from the second chunk. f must not mutate groups. Mutation is not supported and may produce unexpected results. The second call to the same function is also about finding a faster path. You see the same behavior with apply: In the current implementation apply calls func twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first column/row.
upvote count: 3
answers question: http://stackoverflow.com/q/52542995
accepted answer of: http://stackoverflow.com/q/52542995
score: 3
type: AcceptedAnswer

http://stackoverflow.com/q/52466216
has body: I have the following straightforward function in Python 3: def func(i,j): return lambda i,j: (i*j) Here's an example of what this function should do: IN: func(4,'Hello') OUT: ('Hello' 'Hello' 'Hello' 'Hello') However, the actual output is an address in memory where the result is stored. What modification do I need to make?
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91874144
type: Question
has title: Function with Lambda in Python
has comment: http://stackoverflow.com/comment/91874060
has comment: http://stackoverflow.com/comment/91874073
has comment: http://stackoverflow.com/comment/91874105
score: 0
has comment: http://stackoverflow.com/comment/91874128
upvote count: 1
has answer: http://stackoverflow.com/a/52466671
accepted answer: http://stackoverflow.com/a/52466671
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/92012490
type: Comment
type: QuestionComment
score: 0
has text: I still get the error `pyspark.sql.utils.AnalysisException: u"cannot resolve 'CASE WHEN (`is_inside` = 1) THEN <lambda>(c1, c2, c3) ELSE named_struct('col1', '0', 'col2', '0') END' due to data type mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;\`. I used `otherwise(func.struct(func.lit("xxx"),func.lit("yyy")))`
comment on: http://stackoverflow.com/q/52535303

http://stackoverflow.com/comment/92099355
comment on: http://stackoverflow.com/q/52582159
score: 1
has text: `print(vH[1])` like that
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52542344
score: 1
tagged with: selenium
upvote count: 1
has body: The purpose of this code is to scrape a bunch of data tables with different lengths (different number of rows per table), turn them into pandas data frames, remove some unnecessary columns and fix the date. All the above works ok but when I tried to rename a column I got an error. Here is data sample: Date Actual 0 Oct 15, 2018 21:30 1 Sep 09, 2018 21:30 0.7% 2 Aug 08, 2018 21:30 0.3% 3 Jul 09, 2018 21:30 -0.1% 4 Jun 08, 2018 21:30 -0.2% 5 May 09, 2018 21:30 -0.2% 6 Apr 10, 2018 21:30 -1.1% Here is the code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec import pandas as pd class DataEngine: def __init__(self): self.urls = open(r"C:\Users\Sayed\Desktop\script\sample.txt").readlines() self.driver = webdriver.Chrome(r"D:\Projects\Tutorial\Driver\chromedriver.exe") self.wait = WebDriverWait(self.driver, 10) def title(self): names = [] for url in self.urls: self.driver.get(url) title = self.driver.find_element_by_xpath('//*[@id="leftColumn"]/h1').text if title not in names: names.append(title) return names def table(self): DataFrames = [] for url in self.urls: self.driver.get(url) while True: try: item = self.wait.until( ec.visibility_of_element_located((By.XPATH, '//*[contains(@id,"showMoreHistory")]/a'))) self.driver.execute_script("arguments[0].click();", item) except Exception: break df = pd.DataFrame(columns=['Release Date', 'Time', 'Actual', 'Forecast', 'Previous']) pos = 0 for table in self.wait.until( ec.visibility_of_all_elements_located((By.XPATH, '//*[contains(@id,"eventHistoryTable")]//tr'))): data = [item.text for item in table.find_elements_by_xpath(".//*[self::td]")] if data: df.loc[pos] = data[0:5] pos += 1 df["Date"] = df["Release Date"].apply(lambda date: date[:12]) + " " + df["Time"] df.astype('unicode') df = df'Date', 'Actual', 'Forecast', 'Previous', 'Release Date', 'Time' pd.to_datetime(df['Date'],…
type: Question
has comment: http://stackoverflow.com/comment/92025038
has comment: http://stackoverflow.com/comment/92024736
has answer: http://stackoverflow.com/a/52542672
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92024655
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: python pandas rename data frame

http://stackoverflow.com/q/52545954
tagged with: python-3.x
has body: I'm trying to produce rolling regressions using the sklearn package and subsequently plot them in using matplotlib. I've been able to produce the rolling regression coefficients, but appending output is resulting in a 3-D list that I'm having difficulty plotting. Code below is giving the following error: ValueError: x and y can be no greater than 2-D, but have shapes (130,) and (130, 1, 5) rCoeff = [] lm = sk_l.LinearRegression() for iS in range(1, len(y)-(rollingN-1)): iE = iS+(rollingN-1) subX = X[iS:iE] suby = y[iS:iE] lm.fit(subX,suby) rCoeff.append(lm.coef_) x = df_cpf.loc[36:166,'Date'] plt.plot_date(x,rCoeff) Is there a method for 'squeezing' the 3D list into 2 dimensions, or some other method, to allow this to plot?
has title: Converting list of arrays for plotting using matplotlib in Python
tagged with: python
has answer: http://stackoverflow.com/a/52631710
accepted answer: http://stackoverflow.com/a/52631710
tagged with: sklearn-pandas
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/52546406
type: Question
has answer: http://stackoverflow.com/a/52546406
tagged with: matplotlib
answer count: 2
tagged with: pandas
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/52571237
type: Answer
has body: The generator was wrong. It incorrectly assumes a finite generator whilst keras expects an infinite one.
answers question: http://stackoverflow.com/q/52543817
score: 0

http://stackoverflow.com/q/52553593
downvote count: 0
has body: import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = tf.keras.utils.normalize(x_train, axis=1) x_test = tf.keras.utils.normalize(x_test, axis=1) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128,activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(128,activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) model.compile(optimizer ='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=3) When I tried to save the model model.save('epic_num_reader.model') I get a NotImplementedError: NotImplementedError Traceback (most recent call last) &lt;ipython-input-4-99efa4bdc06e&gt; in &lt;module&gt;() 1 ----&gt; 2 model.save('epic_num_reader.model') NotImplementedError: Currently `save` requires model to be a graph network. Consider using `save_weights`, in order to save the weights of the model. So how can I save the model defined in the code?
tagged with: keras
accepted answer: http://stackoverflow.com/a/52554595
favorite count: 0
has title: Tensorflow——keras model.save() raise NotImplementedError
answer count: 5
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/54054119
linked to: http://stackoverflow.com/q/44747343
has answer: http://stackoverflow.com/a/54233621
has answer: http://stackoverflow.com/a/56851110
possible better answer: http://stackoverflow.com/a/54305796
type: Question
has answer: http://stackoverflow.com/a/54305796
has answer: http://stackoverflow.com/a/52554595
has comment: http://stackoverflow.com/comment/95211790
score: 10
upvote count: 10
has answer: http://stackoverflow.com/a/54761949

http://stackoverflow.com/comment/91938883
score: 0
type: Comment
has text: @Cleb, I used the "function finder" on my open source zunzun.com curve fitting web site for the two equation searches, and did not code that part.
comment on: http://stackoverflow.com/a/52489856
type: AnswerComment

http://stackoverflow.com/q/52457733
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/91857850
has answer: http://stackoverflow.com/a/52458453
tagged with: python
tagged with: tkinter
tagged with: pycharm
score: 0
upvote count: 1
has title: how to install Tkinter module in pycharm in windows
answer count: 1
downvote count: 1
has body: hey i'am new in programming .. I am doing a mini project in python in pycharm.. I am getting an error which says Tkinter module not installed.. plzz anybody can help..!!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91867652

http://stackoverflow.com/a/53123298
has comment: http://stackoverflow.com/comment/93161525
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52508255
has body: I would add a Home class which has devices within it. Then add the Home to you agent schedule. For example: class Home(Agent): def __init__(self, unique_id, model): super().__init__(unique_id, model) self.fan1 = Fan(1, self) self.fan2 = Fan(2, self) self.light1 = Light(3, self) self.light2 = Light(4, self) class HomeModel(Model): def __init__(self): self.schedule = RandomActivation(self) for i in range(some_number_of_houses): a = Home(i, self) #This will then add a house with the devices you want # an object within an object
accepted answer of: http://stackoverflow.com/q/52508255
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52523553
has title: Thread class will not start or Initialize
has comment: http://stackoverflow.com/comment/91990979
has body: I am trying to create a ZMQ Subscriber that writes to a CSV every certain amount of time (The time doesn't matter as much). The problem I'm having is my write_csv1 class doesnt even start or initialize and the code for initialization is the same for my ZMQ thread class. It was working before I added the threading.Condition and the c.acquires/c.release. Any tips or pointers would be amazing. import zmq import pandas as pd import time import threading c = threading.Condition() df = pd.DataFrame() s = 0 m = 0 h = 0 d = 0 def counter(): global h,s,m,d while True: s += 1 print("Second:{}".format(s)) if s &gt;=60: m +=1 s = 0 if m &gt;= 60: h += 1 m = 0 if h &gt;= 24: d += 1 h = 0 time.sleep(1) class write(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.name = name def write_csv(self): global df while True: print('sleeping') time.sleep(12) c.acquire() print('acquired') print(df) with open("FILE", 'a') as f: df.to_csv(f, encoding = 'utf-8', index = False, header = False) c.release() z = zmq_thread() z.run() class zmq_thread(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.name = name def run(self): global df print('DF Created') context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://localhost:#####") socket.setsockopt_string(zmq.SUBSCRIBE, 'TOPIC') print('socket connected') count = 0 while True: c.acquire() try: count +=1 if count == 10: print('ZMQ Break') c.notify_all() c.release() print('Lock released') return df message = socket.recv_string() message2 = socket.recv_string() if message == 'TOPIC': message2_split = message2.split(",") message4 = pd.Series(message2_split) df = df.append(message4, ignore_index=True) print('ZMQ Running') except KeyboardInterrupt: break counter = threading.Thread(target = counter) write_csv1 = write("Write_csv") zmq_loop = zmq_thread('Start_ZMQ') counter.start() write_csv1.start() zmq_loop.start()
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52523645
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: multithreading
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52523645
tagged with: zeromq

http://stackoverflow.com/q/52537167
score: 1
favorite count: 0
type: Question
tagged with: odoo-10
tagged with: android
tagged with: python
tagged with: google-api
upvote count: 1
tagged with: odoo
type: UnansweredQuestion
has title: Extract CID & LAC from android device uisng api call(python)
has body: I am using Google's geolocation api and geocode api to track any android device using nearest tower location. For using geolocation, CID &amp; LAC needs to be sent as one of the required parameters to get the tower detials the device is connected to. I need this functionality in Odoo framework. Both the details I could see when I dial '##4636##' from the device. If I statically pass CID and LAC to google API, everything works fine. My question is how to get CID and LAC of a device using an api call ??
downvote count: 0
answer count: 0

http://stackoverflow.com/comment/91826085
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52441642
has text: I will return with an edit with my attempt at a while loop
score: 0

http://stackoverflow.com/q/52579328
has title: Subplot title in the same place as main title of a plot
score: 1
tagged with: matplotlib
has body: I am trying to add main title to plot and also minor titles to every single subplot. I cannot figure out how to do it properly. It happens that main title is located in the same place as a title of a subplot. How to move all subplots under main title? This is how I tried to do it: fig = plt.figure(figsize=(8.0, 5.0)) fig.suptitle('MAIN TITLE', horizontalalignment='left', fontsize=10) plt.subplot(2, 1, 1) plt.gca().set_title('SUBPLOT TITLE', fontsize=10)
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52579441
tagged with: python
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92094045
upvote count: 1
tagged with: plot

http://stackoverflow.com/a/52440997
accepted answer of: http://stackoverflow.com/q/52440960
answers question: http://stackoverflow.com/q/52440960
type: AcceptedAnswer
downvote count: 0
has body: The easiest way is to start iterating from the second element. Eg, instead of for line in res.split('\n') write for line in res.split('\n')[1:] Look up python's slicing of lists/iterables.
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/91873610
type: Comment
type: QuestionComment
has text: @PM2Ring why wouldn't it be 4 points in the parameter? one for each corner
comment on: http://stackoverflow.com/q/52461778
score: 0

http://stackoverflow.com/q/52490426
has comment: http://stackoverflow.com/comment/132457967
upvote count: 3
has body: I'm very new to NixOS, so please forgive my ignorance. I'm just trying to set up a Python environment---any kind of environment---for developing with SpaCy, the SpaCy data, pandas, and jenks-natural-breaks. Here's what I've tried so far: pypi2nix -V "3.6" -E gcc -E libffi -e spacy -e pandas -e numpy --default-overrides, followed by nix-build -r requirements.nix -A packages. I've managed to get the first command to work, but the second fails with Could not find a version that satisfies the requirement python-dateutil&gt;=2.5.0 (from pandas==0.23.4) Writing a default.nix that looks like this: with import &lt;nixpkgs&gt; {}; python36.withPackages (ps: with ps; [ spacy pandas scikitlearn ]). This fails with collision between /nix/store/9szpqlby9kvgif3mfm7fsw4y119an2kb-python3.6-msgpack-0.5.6/lib/python3.6/site-packages/msgpack/_packer.cpython-36m-x86_64-linux-gnu.so and /nix/store/d08bgskfbrp6dh70h3agv16s212zdn6w-python3.6-msgpack-python-0.5.6/lib/python3.6/site-packages/msgpack/_packer.cpython-36m-x86_64-linux-gnu.so Making a new virtualenv, and then running pip install on all these packages. Scikit-learn fails to install, with fish: Unknown command 'ar rc build/temp.linux-x86_64-3.6/liblibsvm-skl.a build/temp.linux-x86_64-3.6/sklearn/svm/src/libsvm/libsvm_template.o' I guess ideally I'd like to install this environment with nix, so that I could enter it with nix-shell, and so other environments could reuse the same python packages. How would I go about doing that? Especially since some of these packages exist in nixpkgs, and others are only on Pypi.
type: Question
score: 3
has comment: http://stackoverflow.com/comment/132255016
has answer: http://stackoverflow.com/a/74944857
downvote count: 0
answer count: 1
favorite count: 0
tagged with: nixos
has comment: http://stackoverflow.com/comment/100623148
tagged with: python
accepted answer: http://stackoverflow.com/a/74944857
has title: In NixOS, how can I install an environment with the Python packages SpaCy, pandas, and jenks-natural-breaks?
type: AnsweredQuestion

http://stackoverflow.com/q/52504189
has comment: http://stackoverflow.com/comment/91950795
has title: nohup with && hangs python
downvote count: 0
has body: I'm using pysftp in python 3.7 to connect to a Linux box and issue commands. I am running a dask-worker in the background. Here's the base command to start a dask-worker: dask-worker my_domain:8786 Here's the command that gets sent to the Linux box: (you can see I wrap it with nohup in order to allow it to continue to run, and not hang my local python process). nohup dask-worker my_domain:8786 &gt; /dev/null 2&gt;&amp;1 &amp; Issuing this command works great! But I have one more thing I want to include, and I can't get it to work with this nohup wrapper. Maybe you can tell me why. I want to run the dask-worker from a specific folder, like this: cd /home/user/some_folder/ &amp;&amp; dask-worker my_domain:8786 That works great, but when I wrap that in a nohup, it just hangs - my process on my machine issuing commands to Linux boxes doesn't move onto the next command. So this doesn't work: nohup cd /home/user/some_folder/ &amp;&amp; dask-worker my_domain:8786 &gt; /dev/null 2&gt;&amp;1 &amp; Do you know why? Or how I can get it to spin off my dask-worker process at that specific location? Is there a better way of doing this than chaining Linux commands together. Here's the reason I'm doing it this way - because I cannot get the pysftp.chdir() command to actually work. It doesn't change the directory on the Linux box, and maybe that's because it's Centos7, idk, but the prepackaged commands to set a working directory don't stick for me. Thank you kindly for your attention.
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/91949085
answer count: 0
type: UnansweredQuestion
tagged with: pysftp
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91948997
score: 1
has comment: http://stackoverflow.com/comment/91949252
type: Question

http://stackoverflow.com/comment/91866316
has text: Well yes ? Call them, then display them with pygame.display.flip() or display.update() ??? Oh dear ... you can see I'm a novice!
score: 0
comment on: http://stackoverflow.com/a/52461461
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52433109
has comment: http://stackoverflow.com/comment/111439449
tagged with: python
tagged with: mongodb-query
tagged with: python-3.x
score: 0
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52483962
tagged with: mongodb
has body: I am trying to write log from Python to Mongo DB. My code is executing and creating Database as 'DSLogSummary' but not writing entries to collection: from apscheduler.schedulers.blocking import BlockingScheduler from pymongo import MongoClient from pymongo import ASCENDING from pytz import utc import datetime client = MongoClient() db = client.DSLogSummary collection = db.ds_jobLogEntry collection.ensure_index([("timestamp", ASCENDING)]) def log(msg): entry = {} entry['timestamp'] = datetime.datetime.utcnow() entry['msg'] = msg collection_id = collection.insert_one(entry).inserted_id def job_test(): print ("Hello World") log('Job executed') jobstores = { 'mongo': {'type': 'mongodb'}, } sched = BlockingScheduler() sched.configure(jobstores=jobstores, timezone=utc) sched.add_job(job_test, trigger='cron', month='*', hour='*', minute = '*', second='*/5') sched.start() Output is: Hello World Hello World Hello World Hello World Hello World Hello World
tagged with: apscheduler
answer count: 1
has title: Writing log from Python to Mongo DB

http://stackoverflow.com/a/52561946
downvote count: 0
has comment: http://stackoverflow.com/comment/92278887
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/52559412
has comment: http://stackoverflow.com/comment/99354527
answers question: http://stackoverflow.com/q/52559412
upvote count: 1
has comment: http://stackoverflow.com/comment/92278460
has body: The example function below searches a dict (including all nested dicts) for key / value pairs matching a list of keys you would like to find. This function recursively loops through the dict and any nested dicts and lists it contains to build a list of all possible dicts to be checked for matching keys. def find_key_value_pairs(q, keys, dicts=None): if not dicts: dicts = [q] q = [q] data = q.pop(0) if isinstance(data, dict): data = data.values() for d in data: dtype = type(d) if dtype is dict or dtype is list: q.append(d) if dtype is dict: dicts.append(d) if q: return find_key_value_pairs(q, keys, dicts) return [(k, v) for d in dicts for k, v in d.items() if k in keys] Example below uses json.loads to convert an example dataset similar to your json to a dict before passing it to the function. import json json_data = """ {"results_count": 2, "results": [{"utc_start_at": "2018-09-29T16:45:00+0000", "counts": {"customer_count": "14", "other_count": "41"}, "capacity": {"non-resource": {"non_resource_bookable_capacity": "18", "other_non_resource_capacity": "1"}, "resource_capacity": "10"}}, {"utc_start_at": "2018-10-29T15:15:00+0000", "counts": {"customer_count": "7", "other_count": "41"}, "capacity": {"non-resource": {"non_resource_bookable_capacity": "25", "other_non_resource_capacity": "1"}, "resource_capacity": "10"}}]} """ data = json.loads(json_data) # json_data is a placeholder for your json keys = ['results_count', 'customer_count', 'utc_start_at', 'non_resource_bookable_capacity'] results = find_key_value_pairs(data, keys) for k, v in results: print(f'{k}: {v}') # results_count: 2 # utc_start_at: 2018-09-29T16:45:00+0000 # utc_start_at: 2018-10-29T15:15:00+0000 # customer_count: 14 # customer_count: 7 # non_resource_bookable_capacity: 18 # non_resource_bookable_capacity: 25
has comment: http://stackoverflow.com/comment/92279099
type: AcceptedAnswer

http://stackoverflow.com/comment/91861754
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52459780
has text: If your code works please post to Code Review

http://stackoverflow.com/q/52574728
has answer: http://stackoverflow.com/a/52575801
tagged with: python
linked to: http://stackoverflow.com/q/10844064
possible better answer: http://stackoverflow.com/a/52575801
type: AnsweredQuestion
has title: CSV to JSON using Pandas selected Columns
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52575754
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52575754
has body: I'm trying to extract data from a csv to a JSON file. The csv has several columns but I need only col1, col2, col3. I have been playing around with pandas and trying to get it to work but I can't figure out how to eliminate the other columns and get just col1,col2 and col3. I know that running the iteraterrows for pandas goes through all the rows and which is causing to get all the columns, I tried iloc but didn't get to the proper output. My code so far import pandas as pd import pdb from itertools import groupby from collections import OrderedDict import json df = pd.read_csv('test_old.csv', dtype={ "col1" : str, "col2" : str }) results = [] for (col1), bag in df.groupby(["col1"]): contents_df = bag.drop(["col1"], axis=1) labels = [OrderedDict(row) for i,row in contents_df.iterrows()] pdb.set_trace() results.append(OrderedDict([("col1", col1), ("subset", labels)])) print json.dumps(results[0], indent=4) with open('ExpectedJsonFile.json', 'w') as outfile: outfile.write(json.dumps(results, indent=4)) The CSV col1,col2,state,col3,val2,val3,val4,val5 95110,2015-05-01,CA,50,30.00,5.00,3.00,3 95110,2015-06-01,CA,67,31.00,5.00,3.00,4 95110,2015-07-01,CA,97,32.00,5.00,3.00,6 The expected JSON { "col1": "95110", "subset": [ { "col2": "2015-05-01", "col3": "50", }, { "col2": "2015-06-01", "col3": "67", }, { "col2": "2015-07-01", "col3": "97", } ] }

http://stackoverflow.com/comment/91840275
has text: seems like I was focusing on the wrong part of things hahaha. Thanks
score: 1
comment on: http://stackoverflow.com/a/52448658
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52542282
has answer: http://stackoverflow.com/a/52542442
type: Question
has answer: http://stackoverflow.com/a/52542543
has title: Python function returns none after 3 rd use of None
tagged with: python-2.7
score: 0
answer count: 2
has body: So i was trying to solve some questions and used the given logic for the same. But even after getting the correct value using print everytime i try to return that value the output is None. def rt(c): print "yep",c cc(c) def asa(): return 3 def klds(s): return s+4 def cc(k): if k!=7: print k print 3434 return k print 2 rt(k+2) print cc(klds(asa())) Expected output: The second last value 3434 is just to check whether function goes after print and 3rd last value is the value to be returned 2 yep 9 9 3434 9 Getting output: 2 yep 9 9 3434 None
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92024579
accepted answer: http://stackoverflow.com/a/52542442
possible better answer: http://stackoverflow.com/a/52542543
tagged with: python
type: AnsweredQuestion
downvote count: 2

scipy
tags question: http://stackoverflow.com/q/52450681
tags question: http://stackoverflow.com/q/52548812
tags question: http://stackoverflow.com/q/52451647
tags question: http://stackoverflow.com/q/52480804
tags question: http://stackoverflow.com/q/52536206
tags question: http://stackoverflow.com/q/52524211
tags question: http://stackoverflow.com/q/52447333
tags question: http://stackoverflow.com/q/52468409
tags question: http://stackoverflow.com/q/52502874
tags question: http://stackoverflow.com/q/52451007
tags question: http://stackoverflow.com/q/52541599
tags question: http://stackoverflow.com/q/52446464
tags question: http://stackoverflow.com/q/52450394
type: Tag
tag name: scipy
tags question: http://stackoverflow.com/q/52492515
tags question: http://stackoverflow.com/q/52525876
tags question: http://stackoverflow.com/q/52461883
tags question: http://stackoverflow.com/q/52431179
tags question: http://stackoverflow.com/q/52438263
tags question: http://stackoverflow.com/q/52566855
tags question: http://stackoverflow.com/q/52586643
tags question: http://stackoverflow.com/q/52529152
tags question: http://stackoverflow.com/q/52467705
tags question: http://stackoverflow.com/q/52472749
tags question: http://stackoverflow.com/q/52502563
tags question: http://stackoverflow.com/q/52522050
tags question: http://stackoverflow.com/q/52525976
tags question: http://stackoverflow.com/q/52450658
tags question: http://stackoverflow.com/q/52517438
tags question: http://stackoverflow.com/q/52572165
tags question: http://stackoverflow.com/q/52446424
tags question: http://stackoverflow.com/q/52510665
tags question: http://stackoverflow.com/q/52483191
tags question: http://stackoverflow.com/q/52524919
tags question: http://stackoverflow.com/q/52578862
tags question: http://stackoverflow.com/q/52562244
tags question: http://stackoverflow.com/q/52515077
tags question: http://stackoverflow.com/q/52439564
tags question: http://stackoverflow.com/q/52468563
tags question: http://stackoverflow.com/q/52460717
tags question: http://stackoverflow.com/q/52491800
tags question: http://stackoverflow.com/q/52563440
tags question: http://stackoverflow.com/q/52585356
tags question: http://stackoverflow.com/q/52447815
tags question: http://stackoverflow.com/q/52451794
tags question: http://stackoverflow.com/q/52572321
tags question: http://stackoverflow.com/q/52573085
tags question: http://stackoverflow.com/q/52473863
tags question: http://stackoverflow.com/q/52494298
tags question: http://stackoverflow.com/q/52433424
tags question: http://stackoverflow.com/q/52462144
tags question: http://stackoverflow.com/q/52450778
tags question: http://stackoverflow.com/q/52561135
tags question: http://stackoverflow.com/q/52561024

http://stackoverflow.com/comment/91824126
type: QuestionComment
has text: Yes, it can get to two million bits. OK, maybe stupid of me to code it like this I guess as well :)
comment on: http://stackoverflow.com/q/52440611
score: 0
type: Comment

http://stackoverflow.com/a/52514894
accepted answer of: http://stackoverflow.com/q/52514552
has comment: http://stackoverflow.com/comment/91969742
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91969501
type: Answer
upvote count: 1
score: 1
has body: You can use np.where on the DF. It's a bit dirty and I'm sure someone else can give you a cleaner solution but it works. df['code'] = np.where((df['code'] == 'NK') &amp; (df['items'] == 'countryName'), 'North Korea', df['code']) df['code'] = np.where((df['code'] == 'NK') &amp; (df['items'] == 'stateName'), 'North Kingstown', df['code']) ... add the rest of the examples How does it work: np.where((condition one) &amp; (condition two) &amp; (more conditions)... value to set for column 'code' if conditions are met, e.g. North Korea keep old value (NK) if conditions are not met EDIT: Addition of simple dynamic version replace_dict = {'North Korea':['NK','countryName'],'North Kingstown':['NK','stateName']} for key in replace_dict.keys(): df['code'] = np.where((df.code == replace_dict[key][0]) &amp; (df['items'] == replace_dict[key][1]), key, df['code'])
answers question: http://stackoverflow.com/q/52514552

http://stackoverflow.com/q/52537163
tagged with: python
has title: Google Analytics API for Python
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/52537297
tagged with: analytics
has body: How can I get data of all 30 days in a list (in python) from Google Analytics API in order to plot a line chart and see a trend? def get_users(service,profile_id): active_users = service.data().ga().get( ids='ga:'+profile_id, start_date = '2018-09-01', end_date = '2018-09-27', metrics= 'ga:users', start_index=1, max_results= 30).execute() this is my current code and it just gives me one number, when I want all users for each day in month and save that as a list or pandas dataframe. Any ideas????
answer count: 1
favorite count: 0
score: -1
type: UnansweredQuestion

http://stackoverflow.com/q/52462004
has comment: http://stackoverflow.com/comment/91866356
tagged with: text-files
has comment: http://stackoverflow.com/comment/91866439
has answer: http://stackoverflow.com/a/52462026
downvote count: 0
type: UnansweredQuestion
has body: how do you read a text file in 2-dim array, e.g. import numpy as np import matplotlib.pyplot as plt fl = open('input.sis','r') lines = [[]] line=[] for i in range(1000): for j in range(4): f= fl.readline() line[j].append(f) lines[i].append(line[j]) print(lines[0,1]) I am trying to read the first 4 lines and assign them indices from 0-3, and repeat that 1000 times. I am getting an error: Traceback (most recent call last): File "./plot_inputsis.py", line 13, in &lt;module&gt; line[j].append(f) IndexError: list index out of range It is important to me to access the array elements by lines[i,j]
type: Question
score: 1
has comment: http://stackoverflow.com/comment/91866389
has title: python read file into 2-dim array for loop
tagged with: for-loop
upvote count: 1
answer count: 1
tagged with: arrays
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/107082083
comment on: http://stackoverflow.com/a/52566582
type: Comment
score: 1
has text: @kjmerf Yes it is common
type: AnswerComment

http://stackoverflow.com/a/52537362
score: 2
has comment: http://stackoverflow.com/comment/92018151
has comment: http://stackoverflow.com/comment/92014468
has body: This code may help you: #!/usr/bin/python from google.cloud import translate from apiclient.discovery import build key = 'YOUR API KEY' translate_client = translate.Client() service = build('translate', 'v2', developerKey=key) translation = service.translations().list(source='es',target='en',q=['Esto es un texto traducido']).execute() print(translation) Consult this link for the Translation API methods Python reference document.
has comment: http://stackoverflow.com/comment/92014312
downvote count: 0
has comment: http://stackoverflow.com/comment/92019392
has comment: http://stackoverflow.com/comment/92018937
upvote count: 2
has comment: http://stackoverflow.com/comment/92016413
answers question: http://stackoverflow.com/q/52535703
type: Answer

http://stackoverflow.com/comment/91921508
score: 0
type: Comment
has text: this gaved me 6 extracted files i don't know why, not the contents of the 6 folders
type: AnswerComment
comment on: http://stackoverflow.com/a/52490143

http://stackoverflow.com/a/52520902
score: 3
has comment: http://stackoverflow.com/comment/91983567
answers question: http://stackoverflow.com/q/52520803
has comment: http://stackoverflow.com/comment/91982123
has comment: http://stackoverflow.com/comment/91983537
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91982094
has body: You can use collections.defaultdict with frozenset and itertools.combinations to form a dictionary of pairwise counts. Variations are possible. For example, you can use collections.Counter with sorted tuple instead, but fundamentally the same idea. from collections import defaultdict from itertools import combinations dd = defaultdict(int) L1 = ["cat", "toe", "man"] L2 = ["cat", "toe", "ice"] L3 = ["cat", "hat", "bed"] for L in [L1, L2, L3]: for pair in map(frozenset, (combinations(L, 2))): dd[pair] += 1 Result: defaultdict(int, {frozenset({'cat', 'toe'}): 2, frozenset({'cat', 'man'}): 1, frozenset({'man', 'toe'}): 1, frozenset({'cat', 'ice'}): 1, frozenset({'ice', 'toe'}): 1, frozenset({'cat', 'hat'}): 1, frozenset({'bed', 'cat'}): 1, frozenset({'bed', 'hat'}): 1})
type: Answer
accepted answer of: http://stackoverflow.com/q/52520803
has comment: http://stackoverflow.com/comment/91982163
upvote count: 3
has comment: http://stackoverflow.com/comment/91983579

http://stackoverflow.com/a/52448559
has body: You can leverage python list comprehension and the built-in sum function to do this quite easily: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] row_totals = [sum(row) for row in matrix] grand_total = sum(row_totals) Or, you could use vanilla loops and addition: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] row_totals = [] grand_total = 0 for row in matrix: row_total = 0 for value in row: row_total += value row_totals.append(row_total) grand_total += row_total
type: Answer
has comment: http://stackoverflow.com/comment/91840258
score: 0
has comment: http://stackoverflow.com/comment/91846456
answers question: http://stackoverflow.com/q/52448510

http://stackoverflow.com/comment/91904833
type: QuestionComment
has text: according to your ques speaker should only have one row and the speech should get combined maintaing the order, so how can you show two diff rows for speaker A.
score: 0
comment on: http://stackoverflow.com/q/52481342
type: Comment

http://stackoverflow.com/q/52514068
has answer: http://stackoverflow.com/a/52515768
type: AnsweredQuestion
downvote count: 2
tagged with: gis
type: Question
score: -2
accepted answer: http://stackoverflow.com/a/52515768
has title: Trying to find a CSV file of the UK's coastline coordinates
has comment: http://stackoverflow.com/comment/91970601
upvote count: 0
answer count: 1
favorite count: 0
has body: I've been trying to find a CSV file to be used with a python script, that contains detailed coordinates of the UK's coastline. I've looked on the OS website and found shapefiles, and I've tried to get coordinates out of them by using QGIS but I cant seem to make it work, it crashes almost every time I try something (I'm thinking this might be due to the size of the files) The script takes a ID letter and a set of coordinates (Lets call this set A) out of one CSV file, and finds the distance from A to all the coordinates in another CSV file, then writes the smallest distance along with the appropriate ID letter to a third CSV file and repeats this process for every ID letter and set of coordinates in the first file. Currently I've made up some coordinates, but i need a file with the real UK coastal coordinates. Whatever solutions you know of, I need them to be open source or free please. Thank you
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/93083042
has text: I had a sort-of similar problem, but in my case it still didn't work in 3.0.1 where your fix is no longer required. Turned out that there seems to be another bug ([now reported](https://github.com/matplotlib/matplotlib/issues/12687)) in matplotlib: adding text to 3d-axes breaks tight_layout() if added before the call. Having this as a known working example was instrumental in figuring it out, so thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/52487766
type: Comment
score: 1

http://stackoverflow.com/comment/91958168
type: Comment
comment on: http://stackoverflow.com/q/52508982
score: 1
type: QuestionComment
has text: Why not simply `2 <= number < 9`?

http://stackoverflow.com/q/52448004
answer count: 2
has comment: http://stackoverflow.com/comment/91839804
has answer: http://stackoverflow.com/a/52449197
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91839909
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91839608
has comment: http://stackoverflow.com/comment/91840232
tagged with: python
has title: Leaderboard from text file in Python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52449197
has comment: http://stackoverflow.com/comment/91839674
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52449645
has comment: http://stackoverflow.com/comment/91839525
has comment: http://stackoverflow.com/comment/91838915
has body: I need some help on an assignment I am doing in Python 3.5.0. I have a leader board text file, which displays the top 5 scores of the program in order of where they are. I need some help putting them into an array, and then using this array to then output the leader board. The leaderboard is in the format of: 1. User1, Points 2. User2, Points 3. User3, Points 4. User4, Points 5. User5, Points Thanks in advance leaderboard = [] f = open('Leaderboard.txt','r') for i in range(1,5): x = file.readline(i) leaderboard[i] = x
possible better answer: http://stackoverflow.com/a/52449645

http://stackoverflow.com/comment/91878333
has text: Okay, I updated my answer. Btw is there something you don't understand for the moment? Don't hesitate, I can clarify my answer :)
comment on: http://stackoverflow.com/a/52467670
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91853174
comment on: http://stackoverflow.com/q/52455322
score: 0
has text: `sharklist` is a list of strings, so `shark` is a string. You're passing that string to `print_return`, which obviously cannot work.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91992595
has text: Great read: [How to debug small programs (#1)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52526343
score: 0

http://stackoverflow.com/a/52524765
score: 0
answers question: http://stackoverflow.com/q/52524571
type: Answer
has body: If you don't process the files, you don't even need pandas. Just read the files line by line and write it to the new file: with open('outfile.csv', 'w') as outfile: for i, filename in enumerate(all_files): with open(filename, 'r') as infile: for rownum, line in enumerate(infile): if (i != 0) and (rownum == 0): # Only write header once continue outfile.write(line + '\n')

http://stackoverflow.com/comment/91990759
type: Comment
score: 1
has text: Belissmo! this worked perfectly just tested it with a few different variables *5, *25, *50. thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/52525294

http://stackoverflow.com/comment/91956386
comment on: http://stackoverflow.com/q/52507334
type: Comment
has text: The plan is: Run1: Lean an encoding for one image set. Run2: Learn an encoding for another corresponding image set. Run3: Learn encoding 2 given encoding 1. Run 4: given first image input and learned corresponding encoding for the second input, decode to produce image matching second input.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91978527
score: 1
comment on: http://stackoverflow.com/q/52517516
type: Comment
type: QuestionComment
has text: provide a [mcve]

http://stackoverflow.com/comment/121502608
score: 0
has text: This response helped me so immensely. I wish I could treat you to a fine dinner.
type: Comment
comment on: http://stackoverflow.com/a/68270329
type: AnswerComment

http://stackoverflow.com/comment/91918696
type: Comment
has text: and then he would want a total item value from those 5 items
type: AnswerComment
comment on: http://stackoverflow.com/a/52488721
score: 0

http://stackoverflow.com/q/52488411
accepted answer: http://stackoverflow.com/a/52488529
upvote count: 1
has body: Given the following code: https://bpaste.net/show/dd44a1fa01dc from ciscoconfparse import CiscoConfParse from pprint import pprint parse = CiscoConfParse("testconfig.txt", syntax="junos") interfaces = {} intfs = parse.find_objects_w_parents(r'^interface', r'^\s+ge-') for intfobj in intfs: intf_name = intfobj.text.strip() interfaces.update({'name': intf_name}) descr = intfobj.re_match_iter_typed(r'description\s+"(\S.+?)"$', group=1) interfaces.update({'description': descr}) mode = intfobj.re_match_iter_typed(r'port-mode\s+(\S+)\s*$', group=1, all_children=True) interfaces.update({'mode': mode}) print (interfaces) Using the following test data: https://bpaste.net/show/df422a96aaae interfaces { ge-2/0/0 { description "site1;;hostname1;ge-16/0/9;;;TRUST;"; unit 0 { family ethernet-switching { port-mode trunk; } } } ge-2/0/2 { description "site2;;hostname2;ge-16/0/8;;;TRUST;"; unit 0 { family ethernet-switching { port-mode trunk; } } } vstp { bpdu-block-on-edge; vlan VLAN_0005 { interface ge-2/0/0 { edge; } } vlan VLAN_0015 { interface ge-2/0/0 { edge; } interface ge-2/0/2 { edge; } } } } I'm trying to understand why my interfaces = {} just contains one row: {'name': 'ge-2/0/2', 'description': 'site2;;hostname2;ge-16/0/8;;;TRUST;', 'mode': 'trunk'} I would expect it to contain both interfaces from the test data: {'name': 'ge-2/0/0', 'description': 'site1;;hostname1;ge-16/0/9;;;TRUST;', 'mode': 'trunk'} {'name': 'ge-2/0/2', 'description': 'site2;;hostname2;ge-16/0/8;;;TRUST;', 'mode': 'trunk'}
tagged with: python
has comment: http://stackoverflow.com/comment/91918229
tagged with: ciscoconfparse
type: AnsweredQuestion
has title: My dict appears to overwrite and not update with new rows?
has comment: http://stackoverflow.com/comment/91918076
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91918203
answer count: 2
possible better answer: http://stackoverflow.com/a/52488569
has answer: http://stackoverflow.com/a/52488569
has answer: http://stackoverflow.com/a/52488529
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/52531942
downvote count: 0
linked to: http://stackoverflow.com/q/15456158
has comment: http://stackoverflow.com/comment/92003203
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/92003469
answer count: 0
type: UnansweredQuestion
upvote count: 1
duplicate of: http://stackoverflow.com/q/15456158
has comment: http://stackoverflow.com/comment/92003267
has body: In Python, You can either do a={} or a=dict() to make a dictionary, and a['a'] = 1 or a.update({'a':1}) to add a component. Which I think does the exactly the same thing. I am curious if there is any difference between those two ways of dealing with dictionary. It seems a little different from how a list is handled since you can also make a list either a = [] or a = list(), but can't do a[0] = 1 while a.append(1) works fine. Is it simply just a different way of doing things? or is there any difference?
score: 1
has comment: http://stackoverflow.com/comment/92003588
has comment: http://stackoverflow.com/comment/92003499
type: Question
has title: Is there a difference between dictionary['a'] = 1 and dictionary.update({'a':1})?
has comment: http://stackoverflow.com/comment/92003194

http://stackoverflow.com/comment/92046711
comment on: http://stackoverflow.com/q/52553470
type: Comment
has text: @YunLuo thanx got my answer!!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92082824
has text: use: `l = [[1,2,3],[1,2,3]]` `sum(map(len, l))` to get the 6, but for you an item is a number, but an item for a list is just an item that can be another list, number, floating, object, etc.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52573275

http://stackoverflow.com/q/52569622
favorite count: 0
has answer: http://stackoverflow.com/a/52569640
has body: I was wondering if there is way to get the sequence of proteins from uniprot protein ids. I did check few online softwares but they allow to get one sequence at a time but I have 5536 vlues. Is there any package in biopython to do this?
has answer: http://stackoverflow.com/a/52578571
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52590825
upvote count: 7
has answer: http://stackoverflow.com/a/54433251
has title: Protein sequence from uniprot protein id python
score: 7
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52723821
tagged with: bioinformatics
tagged with: python
tagged with: biopython

http://stackoverflow.com/a/52456382
has comment: http://stackoverflow.com/comment/91855111
score: 0
answers question: http://stackoverflow.com/q/52456357
has body: You can use pivot table pd.pivot_table(df,values='Amount',index='user_id',columns='Event',aggfunc='sum').fillna(0) Out: Event e1 e2 e3 user_id 28 50.0 55.0 0.0 32 0.0 16.0 0.0 33 0.0 0.0 18.0
has comment: http://stackoverflow.com/comment/91855195
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91855278
accepted answer of: http://stackoverflow.com/q/52456357
type: Answer
has comment: http://stackoverflow.com/comment/91855230

http://stackoverflow.com/comment/91939539
comment on: http://stackoverflow.com/a/52498288
score: 0
has text: Try this site [Python Standard Encoding](https://docs.python.org/2.4/lib/standard-encodings.html) It has a list of different encoding languages, see if any of these give you the desired output when encoding. What version of python are you using?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52506597
has comment: http://stackoverflow.com/comment/91956029
score: -1
has answer: http://stackoverflow.com/a/52506683
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91954349
tagged with: python-3.x
has body: In my code I am looping through a csv file, and for every line, an image is assigned based on one of the values.Like so: if 'V,S,M' in s.com: compic = Image.open('Com-VSM.png') elif "V,S" in s.com: compic = Image.open('Com-VS.png') elif "V,M" in s.com: compic = Image.open('Com-VM.png') elif "S,M" in s.com: compic = Image.open('Com-SM.png') elif "V" in s.com: compic = Image.open('Com-V.png') elif "S" in s.com: compic = Image.open('Com-S.png') elif "M" in s.com: compic = Image.open('Com-M.png') However, I notice that on occasion python holds onto the image used in the last loop, so if List[1] used 'Com-M.png' and List[2] uses 'Com-S.png' the result is that when the image is made, List[2] will have 'Com-S.png' superimposed over 'Com-M.png' any guesses as to how to fix this? Full loop (The garbage collector stuff was an attempt to severely purge memory): for s in L: scho = 0 if 'Necromancy' in s.school: scho = necromancy elif 'Abjuration' in s.school: scho = abjuration elif 'Conjuration' in s.school: scho = conjuration elif 'Divination' in s.school: scho = divination elif 'Evocation' in s.school: scho = evocation elif 'Enchantment' in s.school: scho = enchantment elif 'Illusion' in s.school: scho = illusion elif 'Transmutation' in s.school: scho = transmutation else: scho = abjuration compic = 0 font = ImageFont.truetype("Livingst.ttf", 48) #region Components if 'V,S,M' in s.com: compic = Image.open('Com-VSM.png') elif "V,S" in s.com: compic = Image.open('Com-VS.png') elif "V,M" in s.com: compic = Image.open('Com-VM.png') elif "S,M" in s.com: compic = Image.open('Com-SM.png') elif "V" in s.com: compic = Image.open('Com-V.png') elif "S" in s.com: compic = Image.open('Com-S.png') elif "M" in s.com: compic = Image.open('Com-M.png') else: compic = Image.open('Com-VSM.png') #endregion image_copy = scho.image image_copy.paste(compic, scho.point5, compic) imgpath = 's.name + '.png' image_copy.save(imgpath) del compic gc.collect()
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91953681
upvote count: 0
has comment: http://stackoverflow.com/comment/91955303
type: Question
tagged with: python-imaging-library
has title: Python PIL keeping last image in memory

http://stackoverflow.com/comment/92106296
score: 0
comment on: http://stackoverflow.com/q/52585602
type: Comment
has text: `set` is not a method, it is a type-constructor, and `set` objects are inherently unordered.
type: QuestionComment

http://stackoverflow.com/a/52530030
score: 0
has body: You are getting the error because of the difference in the total number of elements in the two cases: 360*640*3=691200 480*640* 3=921600 Numpy reshape only works when the number of elements in the previous and reshaped array are the same. You can try padding with 0's if you want.
type: Answer
answers question: http://stackoverflow.com/q/52529806

http://stackoverflow.com/a/52445914
has comment: http://stackoverflow.com/comment/91835172
score: 1
has comment: http://stackoverflow.com/comment/91834983
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52445705
has comment: http://stackoverflow.com/comment/91835144
answers question: http://stackoverflow.com/q/52445705
has comment: http://stackoverflow.com/comment/91835232
has comment: http://stackoverflow.com/comment/91835859
has comment: http://stackoverflow.com/comment/91835793
has comment: http://stackoverflow.com/comment/91835802
type: Answer
has body: Your way is fine. You values dictionary has a value for an integer field, which obviously gets a non integer value (1GB_dynPool_Plus_LTE). So you either have the wrong value for this field or your field definition is wrong or you have to parse your value to an integer for example through a mapping. Edit: Your field commercial_group is a many2one relation to model simcard.simcard. I don't know the definition for that model so i will assume the following: class Simcard(models.Model): _name = "simcard.simcard" name = fields.Char() Now on creation Odoo needs IDs or nothing for many2one fields. So either you search for an existing record for that model or create one or just let it empty. My following example uses a mix. First i will search, and if nothing found, my code example will create a simcard.simcard record and uses it later. commercial_group_name = commercial_group.text simcard = record.env['simcard.simcard'].search( [('name', '=', commercial_group_name)], limit=1) if not simcard: simcard = record.env['simcard.simcard'].create( {'name': commercial_group_name}) record.sudo().create({ # other values "commercial_group": simcard.id, # other values })
has comment: http://stackoverflow.com/comment/91835672
upvote count: 1

http://stackoverflow.com/a/52486067
has comment: http://stackoverflow.com/comment/91916511
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91916051
has comment: http://stackoverflow.com/comment/91915232
accepted answer of: http://stackoverflow.com/q/52485778
answers question: http://stackoverflow.com/q/52485778
type: Answer
downvote count: 0
has body: Without an entrypoint defined, it will try to start from a file called main.py. Create one, at the same level as app.yamlwith some simple logic in it: from project_portal.wsgi import application Edit: Since you have an entrypoint defined, it seems that is the issue. So, make sure you have gunicorn in your 'requirements.txt': gunicorn==19.9.0 This did not help: Try changing entrypoint: gunicorn -b :$PORT project_portal.wsgi to entrypoint: gunicorn -b :$PORT project_portal.wsgi:application
score: 3
has comment: http://stackoverflow.com/comment/91916841
has comment: http://stackoverflow.com/comment/91915015
has comment: http://stackoverflow.com/comment/91915423
upvote count: 3

http://stackoverflow.com/q/52555798
tagged with: django
has answer: http://stackoverflow.com/a/52986639
type: AnsweredQuestion
score: 1
has body: What is the best practice for either testing or making sure that all your template variables are in fact existing. Assume that we have the following template &lt;html&gt; &lt;div&gt;{{ existing_object.non_existing_attribute }}&lt;/div&gt; &lt;/html&gt; We have an existing object. So we can't really test the response context like in the following answer: Django Unitest Checking Value Of Template Variable There is string_if_invalid as described in the documentation. But that should only be used for debugging purposes. Any insight on how to best avoid this would be helpful! Edit: Let's assume that the non-existing attribute is a bug. Ie I misspelt the variable, because of this it's showing up as an empty string. Edit2: This question has a lot better answers: https://stackoverflow.com/a/7854404/554903
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92050358
upvote count: 1
duplicate of: http://stackoverflow.com/q/4300442
downvote count: 0
has answer: http://stackoverflow.com/a/52555939
favorite count: 0
linked to: http://stackoverflow.com/q/27190359
has comment: http://stackoverflow.com/comment/92050330
tagged with: python
has title: Non-existing template variables in Django
accepted answer: http://stackoverflow.com/a/52986639
linked to: http://stackoverflow.com/q/4300442
tagged with: django-templates
possible better answer: http://stackoverflow.com/a/52555939
has comment: http://stackoverflow.com/comment/92050486

http://stackoverflow.com/q/52447365
has comment: http://stackoverflow.com/comment/91837965
answer count: 1
tagged with: optimization
has answer: http://stackoverflow.com/a/52447591
score: 0
tagged with: python
tagged with: python-3.x
tagged with: pycharm
tagged with: time
type: UnansweredQuestion
has title: How to time a specific function of code block in Pycharm
type: Question
has body: I'm using Pycharm and playing with the profiler it has built in. I've keyed in on some areas where my code can be optimized but I was wondering if there was a way to step through the code and see how long each line took to execute as I stepped through without having to rerun all my code in the profiler.

http://stackoverflow.com/comment/91859123
score: 0
comment on: http://stackoverflow.com/q/52458406
type: Comment
has text: You might want to convert that `listof500` from a list to a `set()`. That way you can do a lookup for each `data[0]['id']` to see if it is in the set in a very fast way. Otherwise you would have to put in a nested for loop to check for a match of every value in the `listof500` for each `data[0]['id']`.
type: QuestionComment

http://stackoverflow.com/comment/92030725
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52545317
has text: Apologies but that was a Typo. In my actual notebook, both are specified as 'InvoiceNo'.
type: Comment

http://stackoverflow.com/comment/91910856
type: Comment
type: QuestionComment
has text: @wim. Fair enough.
comment on: http://stackoverflow.com/q/52484567
score: 0

http://stackoverflow.com/comment/92049032
has text: Exactly the one explained in my answer. In the first row you filter only companies associated with the user, and if there's only one, just get the first as the example shows. Anyway, I think you should really research a bit more about django and the django orm to understand what you need and what you're doing
comment on: http://stackoverflow.com/a/52554612
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52479045
tagged with: object-detection
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: opencv
score: 2
downvote count: 0
tagged with: image-processing
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/68992765
has title: Markered detected common elements on two images (OpenCV) - PYTHON
answer count: 1
has body: I found some example solution a detected common element on the two images. It's code on Python with OpenCV and I execute on my two examples images: ''' Feature-based image matching sample. Note, that you will need the https://github.com/opencv/opencv_contrib repo for SIFT and SURF USAGE find_obj.py [--feature=&lt;sift|surf|orb|akaze|brisk&gt;[-flann]] [ &lt;image1&gt; &lt;image2&gt; ] --feature - Feature to use. Can be sift, surf, orb or brisk. Append '-flann' to feature name to use Flann-based matcher instead bruteforce. Press left mouse button on a feature point to see its matching point. ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv from common import anorm, getsize FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing FLANN_INDEX_LSH = 6 def init_feature(name): chunks = name.split('-') if chunks[0] == 'sift': detector = cv.xfeatures2d.SIFT_create() norm = cv.NORM_L2 elif chunks[0] == 'surf': detector = cv.xfeatures2d.SURF_create(200) norm = cv.NORM_L2 elif chunks[0] == 'orb': detector = cv.ORB_create(1400) norm = cv.NORM_HAMMING elif chunks[0] == 'akaze': detector = cv.AKAZE_create() norm = cv.NORM_HAMMING elif chunks[0] == 'brisk': detector = cv.BRISK_create() norm = cv.NORM_HAMMING else: return None, None if 'flann' in chunks: if norm == cv.NORM_L2: flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) else: flann_params= dict(algorithm = FLANN_INDEX_LSH, table_number = 6, # 12 key_size = 12, # 20 multi_probe_level = 1) #2 matcher = cv.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329) else: matcher = cv.BFMatcher(norm) return detector, matcher def filter_matches(kp1, kp2, matches, ratio = 0.75): mkp1, mkp2 = [], [] for m in matches: if len(m) == 2 and m[0].distance &lt; m[1].distance * ratio: m = m[0] mkp1.append( kp1[m.queryIdx] ) mkp2.append( kp2[m.trainIdx] ) p1 = np.float32([kp.pt for kp in mkp1]) p2 = np.float32([kp.pt for kp in mkp2]) kp_pairs = zip(mkp1, mkp2) …

http://stackoverflow.com/comment/92137377
comment on: http://stackoverflow.com/q/52578654
has text: @jdehesa I need the text in the original language. so that later I can generate sparse tensor to pass it to CTC_LOSS. Later I figured out that out that I do not need to pass the text, I can pass encoded(character -> no) sequence in tfrecord and take there sparse tensor which for me will work perfectly fine. BTW, thanks for tf.py_func, I will definitely try that out.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91830623
has text: Okay I've modified it but still nothing appears to happen on the webpage. I changed the return to "hello world" again and search the webpage for it after submitting but it wasn't found. I've updated some info which might be useful
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52443948

http://stackoverflow.com/q/52492638
has comment: http://stackoverflow.com/comment/91925870
downvote count: 1
type: Question
tagged with: counter
has body: i've created program that looks like this: demo It works perfectly like i wanted, however how do i reverse this effect? i want to decrese the value to zero (with step value "1") after reaching 1280? The code is here: matrix=[] for i in range(0,6): matrix.append(0) matrix[5]=0x0A i = 1 print matrix while True: matrix[0]=i&amp;0xFF i += 1 if (i &gt; 255): matrix[0] = 255 matrix[1] = i&amp;0xFF if (i &gt; 512): matrix[1] = 255 matrix[2] = i&amp;0xFF if (i &gt; 768): matrix[2] = 255 matrix[3] = i&amp;0xFF if(i &gt; 1024): matrix[3] = 255 matrix[4] = i&amp;0xFF print matrix I cannot change the value of "i" to -1 because it's in while loop (i need it that way). So what might be solution in here?
score: -1
has comment: http://stackoverflow.com/comment/91926264
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52497026
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52497026
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91926074
has title: python - how to decrease elements of an array value

http://stackoverflow.com/q/52467697
has body: So, suppose I have this 2D array in python a = [[1,2] [2,3] [3,2] [1,3]] How do get all array entries with the same row value and store them in a new matrix. For example, I will have b = [1,2] [1,3] after the query. My approach is b = [a[i] for i in a if a[i][0] == 1][0]] but it didn't seem to work? I am new to Python and the whole index slicing thing is kind confusing. Thanks!
tagged with: matrix
accepted answer: http://stackoverflow.com/a/52467734
has title: Get all the rows with same values in python?
possible better answer: http://stackoverflow.com/a/52467787
favorite count: 0
has answer: http://stackoverflow.com/a/52467787
upvote count: 2
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52467734
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/91877196
tagged with: arrays

http://stackoverflow.com/a/52485292
answers question: http://stackoverflow.com/q/52485162
has comment: http://stackoverflow.com/comment/91913614
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91912818
type: AcceptedAnswer
downvote count: 0
has body: See if this helps: Go to the following path: File/ Settings/ Project: Project_Name/ Project Interpreter Click on the plus sign on the right, find the module there and install it. Also, if they are gray, it's because you have imported them but haven't used them yet. The only one which might have a problem is the last one with the red lines maybe. This was discussed here Also, below should be changed from bs4 import BeautifulSoup
has comment: http://stackoverflow.com/comment/91912943
type: Answer
accepted answer of: http://stackoverflow.com/q/52485162

http://stackoverflow.com/comment/92051496
has text: thanks, based on your abstract hint I came up with a try (see update), but it doesn't work. I think it is independent of the question whether I use after() or the time library. Do you see a solution?
type: Comment
comment on: http://stackoverflow.com/a/52556319
score: 0
type: AnswerComment

http://stackoverflow.com/a/52572175
type: Answer
upvote count: 6
score: 6
answers question: http://stackoverflow.com/q/52572094
downvote count: 0
has body: I'm guessing this is what you want to do? You'd just have to add xtick labels(see matplotlib documentation) import matplotlib.pyplot as plt import collections l = ['a', 'b', 'b', 'b', 'c'] count = collections.Counter(l) print(count) plt.bar(range(len(count)), count.values()) plt.show()

http://stackoverflow.com/q/52573049
tagged with: python
score: 2
has title: I still don't understand the point of memoryview
upvote count: 2
accepted answer: http://stackoverflow.com/a/52573409
type: Question
type: AnsweredQuestion
has body: I read through the questions and answers or What exactly is the point of memoryview in Python. I still don't see the point. The example in the answer seems logical at first, but when I construct a third test case, where I scan through the bytesobject by index, it as fast as with the memoryview. import time # Scan through a bytes object by slicing for n in (100000, 200000, 300000, 400000): data = b'x' * n start = time.time() b = data while b: b = b[1:] print('bytes sliced ', n, time.time() - start) # Scan through a bytes object with memoryview for n in (100000, 200000, 300000, 400000): data = b'x' * n start = time.time() b = memoryview(data) while b: b = b[1:] print('memoryview ', n, time.time() - start) # Scan through a bytes object by index for n in (100000, 200000, 300000, 400000): data = b'x' * n start = time.time() b = data for i in range(n): b = b[i+1:] print('bytes indexed ', n, time.time() - start) Output: bytes sliced 100000 0.16396498680114746 bytes sliced 200000 0.6180000305175781 bytes sliced 300000 1.541727066040039 bytes sliced 400000 2.8526365756988525 memoryview 100000 0.02300119400024414 memoryview 200000 0.04699897766113281 memoryview 300000 0.0709981918334961 memoryview 400000 0.0950019359588623 bytes indexed 100000 0.027998924255371094 bytes indexed 200000 0.05700063705444336 bytes indexed 300000 0.08800172805786133 bytes indexed 400000 0.1179966926574707 One of the arguments was, that you can simply pass a memoryview object to struct.unpack. But you can absolutely do the same with a bytes objects. In my understanding it boils down to the same as memoryview eventually has to copy the slice, too. Just sticking with bytes seems so much simpler, if you don't do stupid things.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52573409
linked to: http://stackoverflow.com/q/18655648
tagged with: memoryview

http://stackoverflow.com/comment/115908002
type: Comment
score: 2
comment on: http://stackoverflow.com/a/65213187
has text: I should also say, that for some reason this only seems to work when edges are directed. This is most certainly a bug and will probably be fixed when some decent person raises an issue and makes a PR on https://github.com/networkx/networkx
type: AnswerComment

http://stackoverflow.com/a/52468746
has comment: http://stackoverflow.com/comment/91880239
has comment: http://stackoverflow.com/comment/91880098
has comment: http://stackoverflow.com/comment/91879416
has comment: http://stackoverflow.com/comment/91879488
type: Answer
has comment: http://stackoverflow.com/comment/91879501
accepted answer of: http://stackoverflow.com/q/52468709
has comment: http://stackoverflow.com/comment/91880388
has comment: http://stackoverflow.com/comment/91879972
answers question: http://stackoverflow.com/q/52468709
has comment: http://stackoverflow.com/comment/91879868
has comment: http://stackoverflow.com/comment/91880068
downvote count: 0
has comment: http://stackoverflow.com/comment/91880102
has comment: http://stackoverflow.com/comment/91880261
has comment: http://stackoverflow.com/comment/91880133
score: 1
has body: The problem is that you wrote Class instead of class. Your code works fine when it is rectified You wrote Class Rectangle: You should write class Rectangle: Complete: class Rectangle: def __init__(self, topLeft = (0,0), bottomRight = (1,1)): self.topLeft = topLeft self.bottomRight = bottomRight r1 = Rectangle() print(r1.topLeft, r1.bottomRight) &gt; (0, 0) (1, 1) Use the following way to override the default values r1 = Rectangle(topLeft = (0,0.5), bottomRight = (1,1)) Edit 2: Overriding the defaults p1 = (3,5) p2 = (6,10) r1 = Rectangle() print (r1.topLeft, r1.bottomRight) &gt; (0, 0) (1, 1) r2 = Rectangle(p1, p2) print (r2.topLeft, r2.bottomRight) &gt; (3, 5) (6, 10)
has comment: http://stackoverflow.com/comment/91880006
upvote count: 1
has comment: http://stackoverflow.com/comment/91879903
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91879403
has comment: http://stackoverflow.com/comment/91879538

http://stackoverflow.com/q/52545458
tagged with: apache-spark
answer count: 1
score: 1
has title: Multiply two pyspark dataframes
favorite count: 0
has answer: http://stackoverflow.com/a/52546005
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52546005
upvote count: 1
type: Question
tagged with: apache-spark-sql
downvote count: 0
tagged with: pyspark
has body: I have a PySpark DataFrame, df1, that looks like: CustomerID CustomerValue CustomerValue2 15 10 2 16 10 3 18 3 3 I have a second PySpark DataFrame, df2 CustomerID CustomerValue 15 2 16 3 18 4 I want to multiply all the columns of df1(I have more than two columns) with the value of df2 join on customer ID. So i want to have something like that CustomerID CosineCustVal CosineCustVal 15 20 4 16 30 9 18 12 9

http://stackoverflow.com/a/52465180
type: Answer
has body: you can do import random random.sample(range(10000), 1000) this will generate 1000 random numbers for example to get 10 random number within range 10,000 random.sample(range(10000), 10) [3339, 2845, 9485, 2601, 3569, 1332, 7123, 4861, 9893, 9483]
answers question: http://stackoverflow.com/q/52465094
score: 0

http://stackoverflow.com/q/52430484
has answer: http://stackoverflow.com/a/52430545
has answer: http://stackoverflow.com/a/52430543
has answer: http://stackoverflow.com/a/52431134
score: -1
has answer: http://stackoverflow.com/a/57597066
has comment: http://stackoverflow.com/comment/91804660
favorite count: 0
accepted answer: http://stackoverflow.com/a/52430543
tagged with: python
has comment: http://stackoverflow.com/comment/91804565
answer count: 4
type: AnsweredQuestion
downvote count: 2
upvote count: 1
type: Question
has title: How can I create a list out of the arguments given in a function?
has body: I am a beginner in Python3 and I am trying to figure out how I can solve this exercise: Define a function called myfunc that takes in an arbitrary number of arguments ans returns a list containing only those arguments that are even. I tried this: def myfunc(*args): a= list(args) for num in a: if num%2==0: return num When trying to call out myfunc(1,2,3,4,5,6) it takes only the first even number:2.Why does this happen? How can I create a list that returns only the even numbers?
possible better answer: http://stackoverflow.com/a/52430545
tagged with: function

http://stackoverflow.com/comment/91958156
type: Comment
comment on: http://stackoverflow.com/a/52508994
has text: Noted. But this solution too converts the matrix to a list. How do I retain the original matrix format? I edited the question to show W
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92127366
type: Comment
has text: Thanks ! Just what I was looking for, works perfectly as described above. To have the dynamic steps execute after another step just add a[0].set_upstream(somePreviousTask)
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/52566582

http://stackoverflow.com/comment/92064920
comment on: http://stackoverflow.com/q/52563168
has text: Technically, `string.count` is not a command but a method.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52449651
tagged with: sql-server
has title: Install ODBC Driver for Mac pyodbc
tagged with: macos
has answer: http://stackoverflow.com/a/54704558
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: odbc
type: Question
has comment: http://stackoverflow.com/comment/91844234
has body: Working with my Mac trying to connect to SQL Server database. Following Microsoft's instructions. However, when I enter: brew install --no-sandbox msodbcsql@13.1.9.2 mssql-tools@14.0.6.0 I get the error: odbcinst: SQLInstallDriverEx failed with Invalid install path. If I install the ODBC driver (on top of Microsoft's instructions web page) and manually load into python script, is that possible? Here is my python code: import pyodbc import pandas as pd cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=server_name;" "Database=Sandbox;" "uid=username;pwd=password") df = pd.read_sql_query('select * from table', cnxn) In this code, how would I replace the zipped downloaded driver to the connect statement, thus bypassing brew?
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/92042682
type: AnswerComment
score: 0
type: Comment
has text: It really looks like a lame behavior, I agree. And there should be a way of compiling this code. The problem is actually not the loop itself. But the fact that as soon as `i` is updated, Numba is unable to guess its type properly at compile time to make sure that `func_tuple` slicing works properly. You can check this out by trying jitting `i = 0; results.append(func_tuple[i]()); i += 1; results.append(func_tuple[i]())`, but replacing `i += 1` with `i = 1` would work.
comment on: http://stackoverflow.com/a/52538328

http://stackoverflow.com/comment/91859596
comment on: http://stackoverflow.com/q/52435807
score: 0
type: Comment
type: QuestionComment
has text: Thank you @jarmod! Answer that worked for me is below

http://stackoverflow.com/comment/92075128
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52568791
type: Comment
has text: That helped a bunch! All set now! Thanks.

http://stackoverflow.com/comment/91972469
has text: Do a `print(response.body)` and see what you get.
comment on: http://stackoverflow.com/q/52515592
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91987891
comment on: http://stackoverflow.com/q/52524092
score: 2
type: QuestionComment
has text: @vash_the_stampede - sorting on string value rather than int value works in the sense that it won't throw errors, but it'll do things that are probably unintended like putting "100" before "99".
type: Comment

http://stackoverflow.com/q/52585244
has body: I'm learning Python and I'm practicing by creating a simple game: rock, paper, scissors. I have created two Python modules called random_number.py and ro_pa_sc.py. The first one includes the code to generate a random string and the second one implements the game itself. This is random_number.py: def r_p_s(): import random random.choice([1, 2, 3]) if random.choice([1, 2, 3]): return "r" if random.choice([1, 2, 3]): return "p" if random.choice([1, 2, 3]): return "s" And this is ro_pa_sc.py: #!/usr/bin/python import random_number def game(): random_number.r_p_s() print r_p_s() if __name__ == "__main__": game() However, when I try to run ro_pa_sc.py from the command line in Bash, I get the following error messages: Error 1: File "ro_pa_sc.py", in module "game()" Error 2: File "ro_pa_sc.py", in game print r_p_s() I don't know what the errors could be, since I have checked I imported the modules and I made sure the syntax was correct... It seems that the random_number module might be the problem, but again, I don't know why. Could anyone tell where my errors are?
tagged with: python
has title: Importing a python module and implementing it
has comment: http://stackoverflow.com/comment/92105581
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92105786
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/92105729
downvote count: 1
has answer: http://stackoverflow.com/a/52585348
type: Question
has comment: http://stackoverflow.com/comment/92106219
has comment: http://stackoverflow.com/comment/92105433
has comment: http://stackoverflow.com/comment/92105315
answer count: 2
accepted answer: http://stackoverflow.com/a/52585348
possible better answer: http://stackoverflow.com/a/52585411
favorite count: 0
has answer: http://stackoverflow.com/a/52585411
has comment: http://stackoverflow.com/comment/92105362

http://stackoverflow.com/q/52570941
tagged with: loops
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92081600
has comment: http://stackoverflow.com/comment/92078913
has comment: http://stackoverflow.com/comment/92079731
score: 0
tagged with: pandas
upvote count: 1
has title: How to Loop actions between CSV header and Dictionary Keys
favorite count: 0
has body: I have a dictionary with set of Keys &amp; Values and also have CSV file with columns have the same header name of the dictionary Keys. i need to apply common function which is if the value of the row of the header that has the name of the key is less than the value defined in the dictionary to write true in a new column in the data set. the problem is i need to make a loop for all columns to match the header name with the Key name and apply the function according to the value of the key on all column rows. Below code if i did it with out loop , but if the dictionary increased it will be not efficient way. Code: dict = {'RRC_SR%' : 99, 'RAB_SR%' : 97, 'UL_UE_Throughput' : 2, 'PS_CDR%' : 0.15, 'DL_UE_Throughput' : 17, 'INTRA HO SR %' : 99} kpi = pd.read_csv('KPIs for Triggering.csv') kpi['RRC_SR Result'] = kpi.loc[:, 'RRC_SR%'].apply(lambda x:x&gt;dict['RRC_SR%']) kpi['RAB_SR Result'] = kpi.loc[:, 'RAB_SR%'].apply(lambda x:x&gt;dict['RAB_SR%']) kpi['UL_UE_Throughput Result'] = kpi.loc[:, 'UL_UE_Throughput'].apply(lambda x:x&gt;dict['UL_UE_Throughput']) kpi['PS_CDR Result'] = kpi.loc[:, 'PS_CDR%'].apply(lambda x:x&gt;dict['PS_CDR%']) kpi['DL_UE_Throughput Result'] = kpi.loc[:, 'DL_UE_Throughput'].apply(lambda x:x&gt;dict['DL_UE_Throughput']) kpi['INTRA HO SR Result'] = kpi.loc[:, 'INTRA HO SR %'].apply(lambda x:x&gt;dict['INTRA HO SR %']) Time Object DL_UE_Throughput UL_UE_Throughput PS_CDR% RAB_SR% RRC_SR% INTRA HO SR % 0:00 A_1 4.76 1.04 0.17 99.88 99.98 98.22 0:00 B_2 8.1 1.04 0.15 99.92 99.99 97.8 0:00 C_3 5.63 0.72 0.11 99.94 99.98 96.17 0:00 D_4 8.65 1.06 0.25 99.75 99.95 99.51 0:00 E_5 10.21 0.59 0.37 99.67 99.97 99.18 0:00 F_6 7.46 0.34 0.38 99.3 99.95 99.56 0:00 G_7 10.08 2.31 0.6 99.38 99.73 93.63 0:00 H_8 10.29 1.29 0.84 99.5 99.84 99.22 0:00 I_9 10.19 4.76 0.92 99.26 99.75 97.66 0:00 J_10 7.45 8.6 0.85 99.29 99.72 98.55
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92079114
has comment: http://stackoverflow.com/comment/92088377
answer count: 0

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/52430334
tags question: http://stackoverflow.com/q/52561692
tags question: http://stackoverflow.com/q/52460513
tags question: http://stackoverflow.com/q/52572787
tags question: http://stackoverflow.com/q/52533615
tags question: http://stackoverflow.com/q/52576304
tags question: http://stackoverflow.com/q/52444993
tags question: http://stackoverflow.com/q/52465547
tag name: kivy-language
tags question: http://stackoverflow.com/q/52490598
tags question: http://stackoverflow.com/q/52458140

http://stackoverflow.com/q/52504203
tagged with: django-views
tagged with: django-models
tagged with: django-forms
accepted answer: http://stackoverflow.com/a/52504526
type: Question
answer count: 1
has body: I'm trying to have the DateField (created_at/updated_at) I have set up to be a readonly field that I can access through both the list_display and the form for adding in Django Admin. The way I have it set up it's showing as: %09/%24/%2018 I know it's pulling from DATE_FORMAT in settings.py: DATE_FORMAT = '%m/%d/%Y' I just haven't figured out how to remove the % before it is displayed in Admin. Is there a way to clean this up? I've tried already to access the created_at/updated_at fields to write an algorithm to remove the extra characters, but can't seem to extract the values. Here is my code if that helps. Thanks in advance! admin.py class BatchForm(forms.ModelForm): class Meta: model = Batch fields = '__all__' class BatchAdmin(admin.ModelAdmin): form = BatchForm readonly_fields = ('created_at', 'updated_at') list_display = ('item', 'active', 'desc', 'quantity', 'created_at', 'updated_at') models.py class Batch(models.Model): created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True)
has title: Remove extra characters from DateField in Django Admin form
score: 0
has comment: http://stackoverflow.com/comment/91949130
has answer: http://stackoverflow.com/a/52504526
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91827753
has text: Is the data all in this relatively flat format, or do you get more complicated nested structures sometimes?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52442154
score: 0

http://stackoverflow.com/comment/91883935
type: QuestionComment
has text: OH MY GOD!!! Thank you for the help that totally worked skrx, I spent 2 days trying to find out why it wouln't load. Your a life savior skrx, I'll add you in my WILL later in life.
comment on: http://stackoverflow.com/q/52470930
score: 1
type: Comment

http://stackoverflow.com/q/52556305
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52558194
has body: I have the following dataframe: import pandas as pd import numpy as np from plotnine import * df = pd.DataFrame.from_dict({'variable': {0: 'intercept', 1: 'intercept', 2: 'intercept', 3: 'intercept', 4: 'intercept', 5: 'intercept', 6: 'intercept', 7: 'intercept', 8: 'intercept', 9: 'intercept', 10: 'intercept', 11: 'intercept', 12: 'intercept', 13: 'intercept', 14: 'intercept', 15: 'intercept', 16: 'intercept', 17: 'intercept', 18: 'intercept', 19: 'intercept', 20: 'intercept', 21: 'intercept', 22: 'intercept', 23: 'intercept', 24: 'intercept', 25: 'intercept', 26: 'intercept', 27: 'intercept', 28: 'intercept', 29: 'intercept', 30: 'intercept', 31: 'intercept', 32: 'intercept', 33: 'intercept', 34: 'intercept', 35: 'intercept', 36: 'intercept', 37: 'intercept', 38: 'intercept', 39: 'intercept', 40: 'intercept', 41: 'intercept', 42: 'intercept', 43: 'intercept', 44: 'intercept', 45: 'intercept', 46: 'intercept', 47: 'intercept', 48: 'intercept', 49: 'intercept', 50: 'rsd_language_english', 51: 'rsd_language_english', 52: 'rsd_language_english', 53: 'rsd_language_english', 54: 'rsd_language_english', 55: 'rsd_language_english', 56: 'rsd_language_english', 57: 'rsd_language_english', 58: 'rsd_language_english', 59: 'rsd_language_english', 60: 'rsd_language_english', 61: 'rsd_language_english', 62: 'rsd_language_english', 63: 'rsd_language_english', 64: 'rsd_language_english', 65: 'rsd_language_english', 66: 'rsd_language_english', 67: 'rsd_language_english', 68: 'rsd_language_english', 69: 'rsd_language_english', 70: 'rsd_language_english', 71: 'rsd_language_english', 72: 'rsd_language_english', 73: 'rsd_language_english', 74: 'rsd_language_english', 75: 'rsd_language_english', 76: 'rsd_language_english', 77: 'rsd_language_english', 78: 'rsd_language_english', 79: 'rsd_language_english', 80: 'rsd_language_english', 81: 'rsd_language_english', 82: 'rsd_language_english', 83: 'rsd_language_english', 84: 'rsd_language_english', 85: 'rsd_language_english', 86: 'rsd_languag…
type: Question
answer count: 1
score: 0
has title: how to print quantiles using plotnine in python
tagged with: pandas
tagged with: python
tagged with: plotnine
tagged with: python-3.x

http://stackoverflow.com/q/52537801
has body: I am using Plotly API to draw line charts from a dataset in python. For example I have this dataset from the year 2018. Now I want to check weather the weekend days have higher demand in contrast to the weekdays. My goal is to mark the lines in the diagram for saturday and sunday. Does Plotly provide methods to do this? If not, is there any easy method to achieve this?
has answer: http://stackoverflow.com/a/52538565
has comment: http://stackoverflow.com/comment/92015035
answer count: 1
accepted answer: http://stackoverflow.com/a/52538565
favorite count: 0
upvote count: 1
tagged with: python
has title: Tag special days in plotly diagram
type: AnsweredQuestion
score: 1
tagged with: plotly
type: Question
has comment: http://stackoverflow.com/comment/92015314
downvote count: 0

for-loop
tags question: http://stackoverflow.com/q/52465658
tags question: http://stackoverflow.com/q/52458349
tags question: http://stackoverflow.com/q/52462898
tags question: http://stackoverflow.com/q/52499465
tags question: http://stackoverflow.com/q/52557689
tags question: http://stackoverflow.com/q/52473588
tags question: http://stackoverflow.com/q/52459681
tags question: http://stackoverflow.com/q/52467253
tags question: http://stackoverflow.com/q/52489729
tags question: http://stackoverflow.com/q/52462004
tags question: http://stackoverflow.com/q/52503374
tags question: http://stackoverflow.com/q/52554702
tags question: http://stackoverflow.com/q/52516504
tags question: http://stackoverflow.com/q/52551247
tags question: http://stackoverflow.com/q/52440960
tags question: http://stackoverflow.com/q/52448757
tags question: http://stackoverflow.com/q/52495137
tags question: http://stackoverflow.com/q/52577737
tags question: http://stackoverflow.com/q/52576669
tag name: for-loop
tags question: http://stackoverflow.com/q/52485805
tags question: http://stackoverflow.com/q/52542812
tags question: http://stackoverflow.com/q/52562394
tags question: http://stackoverflow.com/q/52442788
tags question: http://stackoverflow.com/q/52570850
tags question: http://stackoverflow.com/q/52578329
tags question: http://stackoverflow.com/q/52513200
tags question: http://stackoverflow.com/q/52452911
tags question: http://stackoverflow.com/q/52509500
tags question: http://stackoverflow.com/q/52435678
tags question: http://stackoverflow.com/q/52538032
tags question: http://stackoverflow.com/q/52475119
tags question: http://stackoverflow.com/q/52538597
tags question: http://stackoverflow.com/q/52432133
tags question: http://stackoverflow.com/q/52554197
tags question: http://stackoverflow.com/q/52508856
tags question: http://stackoverflow.com/q/52499991
tags question: http://stackoverflow.com/q/52469015
tags question: http://stackoverflow.com/q/52522232
tags question: http://stackoverflow.com/q/52541085
tags question: http://stackoverflow.com/q/52573441
tags question: http://stackoverflow.com/q/52455742
type: Tag
tags question: http://stackoverflow.com/q/52555229
tags question: http://stackoverflow.com/q/52539749
tags question: http://stackoverflow.com/q/52455712
tags question: http://stackoverflow.com/q/52451228
tags question: http://stackoverflow.com/q/52493092
tags question: http://stackoverflow.com/q/52498410
tags question: http://stackoverflow.com/q/52456836
tags question: http://stackoverflow.com/q/52549268
tags question: http://stackoverflow.com/q/52547323
tags question: http://stackoverflow.com/q/52442776
tags question: http://stackoverflow.com/q/52504708
tags question: http://stackoverflow.com/q/52547525
tags question: http://stackoverflow.com/q/52447970
tags question: http://stackoverflow.com/q/52582598
tags question: http://stackoverflow.com/q/52486822
tags question: http://stackoverflow.com/q/52462747
tags question: http://stackoverflow.com/q/52552178
tags question: http://stackoverflow.com/q/52519510
tags question: http://stackoverflow.com/q/52578360
tags question: http://stackoverflow.com/q/52468877
tags question: http://stackoverflow.com/q/52489103

http://stackoverflow.com/comment/91987408
type: Comment
type: QuestionComment
score: 0
has text: i was not able to find something in the docs. seen a 3rd party plugin but is for models, was not able to see something for the Django Default User creation part.
comment on: http://stackoverflow.com/q/52523419

http://stackoverflow.com/q/52587870
tagged with: python
has title: Filter pandas row where 1st letter in a column is/is-not a certain value
tagged with: python-3.x
answer count: 2
upvote count: 7
has answer: http://stackoverflow.com/a/52587890
tagged with: dataframe
type: UnansweredQuestion
downvote count: 0
score: 7
has answer: http://stackoverflow.com/a/52588314
favorite count: 0
tagged with: filter
type: Question
tagged with: pandas
has body: how do I filter out a series of data (in pandas dataFrame) where I do not want the 1st letter to be 'Z', or any other character. I have the following pandas dataFrame, df, (of which there are > 25,000 rows). TIME_STAMP Activity Action Quantity EPIC Price Sub-activity Venue 0 2017-08-30 08:00:05.000 Allocation BUY 50 RRS 77.6 CPTY 066 1 2017-08-30 08:00:05.000 Allocation BUY 50 RRS 77.6 CPTY 066 3 2017-08-30 08:00:09.000 Allocation BUY 91 BATS 47.875 CPTY PXINLN 4 2017-08-30 08:00:10.000 Allocation BUY 43 PNN 8.07 CPTY WCAPD 5 2017-08-30 08:00:10.000 Allocation BUY 270 SGE 6.93 CPTY PROBDMAD I am trying to remove all the rows where the 1st letter of the Venue is 'Z'. For example, my usual filter code would be something like (filtering out all rows where the Venue = '066' df = df[df.Venue != '066'] I can see this filter line filters out what I need by array, but I am not sure how to specify it within a filter context. [k for k in df.Venue if 'Z' not in k]

http://stackoverflow.com/comment/91870263
comment on: http://stackoverflow.com/a/52464135
type: Comment
score: 1
type: AnswerComment
has text: WOW! This method is the fastest by 4 orders of magnitude.

http://stackoverflow.com/comment/92101328
comment on: http://stackoverflow.com/a/52582983
type: AnswerComment
score: 0
type: Comment
has text: @ggezpython3 Using `break` may look prettier but that isn't the problem. Why do you set `point=0` in the `if dice_value==1:` block?

http://stackoverflow.com/a/52443044
upvote count: 1
has body: pd.merge returns a dataframe which is being assigned to a single column. Hence the error. You can replace your code code with the following myTradeFrame = pd.merge(myTradeFrame, specialsData, how='left', on=[ 'coll_cusip', 'tran_type'],suffixes=('_left','_right')) Tip : if keys in left and right dataframe are same just use on.
score: 1
accepted answer of: http://stackoverflow.com/q/52441715
answers question: http://stackoverflow.com/q/52441715
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92102590
score: 0
type: Comment
type: QuestionComment
has text: http://www.sharecsv.com/s/ef75f24132d4d7f285692f513d3817c4/17c.csv This one.. But, is there a general solution that I can implement in my code? I don't want to change the data for thousands of similar .csv files :(
comment on: http://stackoverflow.com/q/52583792

http://stackoverflow.com/q/52543649
favorite count: 0
tagged with: converters
linked to: http://stackoverflow.com/q/10759117
tagged with: dds-format
has comment: http://stackoverflow.com/comment/92027681
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: How can I TGA file format to DDS format?
tagged with: python
tagged with: http://stackoverflow.com/tag/jpeg
has comment: http://stackoverflow.com/comment/92027591
has comment: http://stackoverflow.com/comment/92028141
has body: I have a question. Could you help me, please? import os import sys def prozess_start(programmName, parameter): return os.execv(programName, parameter) def read_files(pfad): TGA_files = [] name_file = os.listdir(pfad) t = [] for i in name_file: if i.endswith(".TGA"): TGA_files.append(i) return TGA_files input_path = "..." outut_path = "..." parameter = ["input_file", "output_file", "1", "2", ..] l = read_files(pfad) for i in l: parameter[0] = input_path + i parameter[1] = outut_path + i[:-4] + ".DDS" prozess_start("...exe", parameter) The Code doesn't work. I have files with ending .TGA and I would like to format it to .DDS. Maybe You see mistakes? Thank you very much!
has comment: http://stackoverflow.com/comment/92027781
score: 1
type: Question
tagged with: tga
upvote count: 1

http://stackoverflow.com/comment/92001424
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52530863
has text: Added the sample data I'm trying to match. The file size is 3.84 MB with the exact same data provided with the question.

http://stackoverflow.com/comment/92104116
type: AnswerComment
comment on: http://stackoverflow.com/a/52584488
type: Comment
has text: > new variable per row? You want a [dictionary](https://docs.python.org/2/tutorial/datastructures.html#dictionaries).
score: 0

http://stackoverflow.com/q/52540227
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52540501
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52540501
has body: Consider the following example: from tkinter import * startingWin = Tk() canvas = Canvas(startingWin, height=600) canvas.grid(row=0, column=0,sticky="nsew") canvasFrame = Frame(canvas) canvas.create_window(0, 0, window=canvasFrame, anchor='nw') for i in range(70): element = Button(canvasFrame, text='Button %s ' % i) element.grid(row=i, column=0) yscrollbar = Scrollbar(startingWin, orient=VERTICAL) yscrollbar.config(command=canvas.yview) canvas.config(yscrollcommand=yscrollbar.set) yscrollbar.grid(row=0, column=1, sticky="ns") canvas.yview_moveto(0.5) canvasFrame.bind("&lt;Configure&gt;", lambda event: canvas.configure(scrollregion=canvas.bbox("all"))) startingWin.mainloop() Expected output: Scrollbar in the middle. However, I get the Scrollbar always on the top, regardless of the value I give to yview_moveto() like the following: How can I fix this?
has title: Tkinter Scrollbar position, yview_moveto() seems not working
score: 3

http://stackoverflow.com/comment/91964701
score: 0
type: Comment
type: QuestionComment
has text: Ok, thanks. Will look into that. I also asked the question on [github issues](https://github.com/mstamy2/PyPDF2/issues/459).
comment on: http://stackoverflow.com/q/52499339

http://stackoverflow.com/comment/92049455
type: AnswerComment
comment on: http://stackoverflow.com/a/52554530
type: Comment
has text: I tested the function, very good, accurate and fast, thank you. In addition I updated the simulation data.
score: 0

http://stackoverflow.com/q/52436769
has title: Using Python regex to ignore `:` from string
has answer: http://stackoverflow.com/a/52436857
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91816815
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52436857
has answer: http://stackoverflow.com/a/52436854
has body: I am new to the world of regex. Hence, I'm sorry if this might sound basic. I have finished reading regex community and Lopez's book on Mastering regex for Python to ensure that I am not posting beginner-level question. I have scraped data from a wiki (for learning), and I am trying to extract strings a) that start with \wiki b) that don't contain : Here's the text: /wiki/Template:Kevin_Bacon /wiki/Category:Best_Miniseries_or_Television_Movie_Actor_Golden_Globe_winners /wiki/Al_Pacino /wiki/Paul_Giamatti /wiki/Kevin_Costner /wiki/Kevin_Costner /wiki/Michael_Douglas /wiki/Mark_Ruffalo /wiki/Idris_Elba /wiki/Bryan_Cranston /wiki/Alexander_Skarsg%C3%A5rd /wiki/Biblioteca_Nacional_de_Espa%C3%B1a /wiki/Template:Kevin_Bacon https://hy.wikipedia.org/wiki/%D5%94%D6%87%D5%AB%D5%B6_%D4%B2%D5%A5%D5%B5%D6%84%D5%B8%D5%B6 The output must be grouped i.e. I should get a list (or tuple) of these strings: /wiki/Al_Pacino /wiki/Paul_Giamatti /wiki/Kevin_Costner /wiki/Kevin_Costner /wiki/Michael_Douglas /wiki/Mark_Ruffalo /wiki/Idris_Elba /wiki/Bryan_Cranston /wiki/Alexander_Skarsg%C3%A5rd /wiki/Biblioteca_Nacional_de_Espa%C3%B1a Here are my attempts at extracting the strings: a) Using negative look-ahead: The idea is to not select string that is followed by : r^/wiki/.*(?!:).* However, above code still selects strings with : i.e. /wiki/Template:Kevin_Bacon b) Force regex to not select : ^/wiki/.*[^:].* However, above code still selects strings with : i.e. /wiki/Template:Kevin_Bacon c) Use quantifier to specify that : should occur zero times ^/wiki/.*:{0}.*$ However, above code still selects strings with : i.e. /wiki/Template:Kevin_Bacon I have two questions: a) I really like regex. Can someone please explain what's wrong with above tries? b) How can I solve the problem using above approaches? I am going to use regex module in python. As per SO's guidelines, I tried to debug regex on regex101 website. Here's the link: https://regex101.com/r/Wt40Cz/1 I'd sincerely appreciate any help. T…
has comment: http://stackoverflow.com/comment/91817792
has comment: http://stackoverflow.com/comment/91816663
possible better answer: http://stackoverflow.com/a/52436854
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91816625
has comment: http://stackoverflow.com/comment/91816596
favorite count: 0
has comment: http://stackoverflow.com/comment/91816679

http://stackoverflow.com/q/52586506
tagged with: matplotlib
downvote count: 3
type: Question
has body: I need to present my data in various graphs. Usually what I do is to take a screenshot of my graph (I almost exclusively make them with matplotlib) and paste it into my PowerPoint. Unfortunately my direct superior seems not to be happy with the way I present them. Sometimes he wants certain things in log scale and sometimes he dislike my color palette. The data is all there, but because its an image there's no way I can change that in the meeting. My superior seems to really care about those things and spend quite a lot of time telling me how to make plots in every single meeting. He (usually) will not comment on my data before I make a plot the way he wants. That's where my question becomes relevant. Right now what I have in my mind is to have an interactive canvas embedded in my PowerPoint such that I can change the range of the axis, color of my data point, etc in real time. I have been searching online for such a thing but it comes out empty. I wonder if that could be done and how can it be done? For some simple graphs Excel plot may work, but usually I have to present things in 1D or 2D histograms/density plots with millions of entries. Sometimes I have to fit points with complicated mathematical formulas and that's something Excel is incapable of doing and I must use scipy and pandas. The closest thing to this I found online is rise with jupyter which convert a jupyter notebook into a slide show. I think that is a good start which allows me to run python code in real time inside the presentation, but I would like to use PowerPoint related solutions if possible, mostly because I am familiar with how PowerPoint works and I still find certain PowerPoint features useful. Thank you for all your help. While I do prefer PowerPoint, any other products that allows me to modify plots in my presentation in real time or alternatives of rise are welcomed.
has answer: http://stackoverflow.com/a/52589887
answer count: 3
possible better answer: http://stackoverflow.com/a/52590097
has answer: http://stackoverflow.com/a/52590097
tagged with: rise
tagged with: jupyter
favorite count: 0
accepted answer: http://stackoverflow.com/a/52589887
has answer: http://stackoverflow.com/a/52628588
tagged with: powerpoint
tagged with: python
upvote count: 6
has title: Possible ways to embed python matplotlib into my presentation interactively
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/52473432
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52472591
answers question: http://stackoverflow.com/q/52472591
type: Answer
has body: Found it!!! When the #:Run tab is open, Ctrl+Enter splits the line. But when the Python Console tab is open, Ctrl+Enter reruns the code.
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52524192
has comment: http://stackoverflow.com/comment/91988663
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91993211
tagged with: xlsxwriter
upvote count: 1
downvote count: 1
type: Question
has title: Write Xlsx file with python - Blank Lines on Excel file
has answer: http://stackoverflow.com/a/52534808
has comment: http://stackoverflow.com/comment/91987944
score: 0
has body: I'm trying to code a python script to parse a text file in an excel sheet. On this script, I'm trying to write a list of lists on the Xlsx file where each list's element is written in a single line of the Sheet. The problem is when I have two equals elements and they appear sequentially and using both python modules to generate the excel file (xlsxwriter and openpyxl) they just write one of the equals elements and they write a blank line instead of the second element. Example: The input list is: list = [['dog', 'cat', 'bat', 'jaguar'], ['dog', 'cat', 'bat', 'jaguar']] The excel file is written like this: A B C D 1 dog cat bat jaguar 2 blank line Does anyone know if I am doing anything wrong? This is my code: def criaExcel(filename, regras): nomeDoArquivo = filename.rstrip('.wri')+'.xlsx' workbook = xlsxwriter.Workbook(nomeDoArquivo) planilha = workbook.add_worksheet('Rules') indice = '' for regra in regras: indice = str(regras.index(regra)+1) planilha.write('A'+ indice, regra[0]) planilha.write('B'+ indice, regra[1]) planilha.write('C'+ indice, regra[2]) planilha.write('D'+ indice, regra[3]) planilha.write('E'+ indice, regra[4]) planilha.write('F'+ indice, regra[5]) planilha.write('G'+ indice, regra[6]) workbook.close() def parseV3(filename): manipulador = open(filename, 'r', encoding="Latin-1") regras = [] regras.append(['Zona', 'Origem', 'Destino', 'Serviço', 'Ação', 'Status', 'Comentário']) zona = origem = destino = servico = acao = status = comentario = '' padraoCabecalho = re.compile('^Rule.+ (Allow|Deny) Service Any -&gt; (.*) (\(Enabled\)|\(Disabled\))') padraoInformacoes = re.compile('^\s{7,8}IP: (.*) -&gt; (.*) .*') padroaComentario = re.compile('^Comment: (.*)') for linha in manipulador: if linha.startswith('From '): zonaTemp = linha.rstrip().lstrip('From ') if zona == '': zona = zonaTemp elif zona != zonaTemp: zona = zonaTemp elif padraoCabecalho.match(linha): objetos = padraoCabecalho.match(linha) acao, servico, status = objetos.groups() elif padraoInfor…
answer count: 1
accepted answer: http://stackoverflow.com/a/52534808
favorite count: 0

http://stackoverflow.com/a/52466672
answers question: http://stackoverflow.com/q/52462472
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: I think you cannot calculate the anomalies for different periods with just one call of some function, you need to do that in several steps. For example, if you have all the dates in vector datevec and data in var, you should be able to do: a) for monthly means: for mon in range(1,13): kkmon = [ii for ii,val in enumerate(datevec) if val.month == mon] monmean = var[kkmon,:,:].mean(axis=0) b) for seasonal means: seasons = {'DJF':[12,1,2],'MAM':[3,4,5],'JJA':[6,7,8],'SON':[9,10,11]} for seaskey in seasons.keys(): kkseas = [ii for ii,val in enumerate(datevec) if val.month in seasons[seaskey]] seasmean = var[kkseas,:,:].mean(axis=0) This is just an example how you could calculate the overall means for different months and seasons. You have to calculate the anomalies based on the data and resolution that you have. I would also suggest looking at possibilities of cdo (Climate Data Operators) as most of the averaging methods are built-in there and as it is written in C or C++, it works much faster compared to the Python. Of course, you can combine cdo and Python for your tasks - use the first to find the means and the second to calculate and plot anomalies afterwards.

http://stackoverflow.com/comment/91848819
type: Comment
type: QuestionComment
has text: OS is Windows 10
score: 0
comment on: http://stackoverflow.com/q/52451007

http://stackoverflow.com/q/52460035
type: Question
answer count: 2
downvote count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52465967
tagged with: python
has comment: http://stackoverflow.com/comment/91865245
favorite count: 0
has comment: http://stackoverflow.com/comment/91865527
has title: Beautifulsoup webscraping.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/65008888
upvote count: 1
has body: I am trying to scrape data from DnDbeyond. I am using Beautifulsoup and python and have been able to get some of the information that I need by using the "Div" tag and "Find_all" classes but I can't seem to find the info from these formatted blocks that contain the characters stats. Animal Handling I should be able to just be able to search for soup.find("div", {"class": "ct-skills__col--skill"}) right? This is what my current code looks like. from bs4 import BeautifulSoup import requests resp = requests.get('https://www.dndbeyond.com/characters/4741434') soup = BeautifulSoup(resp.text, 'lxml') divTag = soup.find_all("div", {"class": "container"}) Which gets me [ ] I know that my info is under "character-sheet-target" but I can't figure out how to get the info / class under there. Sorry if this is rambely I didn't know how to explain this well.
score: 1
has comment: http://stackoverflow.com/comment/91864985

http://stackoverflow.com/a/52461718
has comment: http://stackoverflow.com/comment/91866016
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91866000
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52461579
has comment: http://stackoverflow.com/comment/91865625
has body: I think it's a setting of your IDE, and not really a python issue. When I save the first line of your question into a txt file and read it: Copied from terminal: &gt;&gt;&gt; open('test.txt').read() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\joost\Desktop\pythontests\venv\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 19: character maps to &lt;undefined&gt; &gt;&gt;&gt; open('test.txt', encoding='utf-8').read() 'I have this (loudly crying\n' &gt;&gt;&gt; As a picture: Perhaps specify your encoding when opening the file?
has comment: http://stackoverflow.com/comment/91866108

http://stackoverflow.com/comment/92001732
has text: as metioned in the LINK I have already upgraded "openpyxl" and "pyexcel" but i still kept getting the same error
comment on: http://stackoverflow.com/q/52530922
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92101041
type: Comment
type: QuestionComment
has text: @Jesse Eh it is a typo. I was using the path you said.
score: 0
comment on: http://stackoverflow.com/q/52582966

http://stackoverflow.com/a/52503575
score: 0
answers question: http://stackoverflow.com/q/52503363
type: Answer
has body: As there is no particular requirement in your question, I can only point you to the Styling documentation. This was introduced in 0.17 and probably isn't widely known about compared to other Pandas functionality.

http://stackoverflow.com/comment/92069737
type: Comment
type: QuestionComment
has text: Generally speaking, painting the quadlit (assuming its in the same coords then your image) on a new image, setting all outside points to some value and using it as mask over your original image would work in PIL - for a PIL example see [here](https://stackoverflow.com/questions/52455886/transparency-not-working-consistently-while-saving-gifs-in-pil/52455943) (it's using a font-mask over a image to get a image-background font) - might help you find smth similar in torchvision which I havent used yet.
score: 0
comment on: http://stackoverflow.com/q/52566050

http://stackoverflow.com/comment/92071057
comment on: http://stackoverflow.com/q/52566851
type: Comment
has text: `print([sum(x) / len(x) for x in lst])` gives you averages where `lst` is your list.
score: 1
type: QuestionComment

http://stackoverflow.com/q/52499573
score: 0
has body: I'm working with Concept Drift, but when trying to run my code i get this error "ImportError: No module named detector_classifier" been trying to install the module with pip install, but all i get is no match found. Anyone had this problem before?
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/52499726
possible better answer: http://stackoverflow.com/a/52499750
has answer: http://stackoverflow.com/a/52499750
tagged with: python
type: AnsweredQuestion
upvote count: 1
accepted answer: http://stackoverflow.com/a/52499726
downvote count: 1
type: Question
has title: ImportError: No module named detector_classifier
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/91939975

http://stackoverflow.com/q/52583710
has answer: http://stackoverflow.com/a/52583904
score: 1
has comment: http://stackoverflow.com/comment/92102808
has title: Modifying strings in a pandas DataFrame by row
answer count: 2
downvote count: 0
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/52584278
tagged with: pandas
tagged with: python
linked to: http://stackoverflow.com/q/36249367
accepted answer: http://stackoverflow.com/a/52584278
upvote count: 1
has comment: http://stackoverflow.com/comment/92102737
has body: I have the following strings in a pandas DataFrame in Python3, column string1 and string2: import pandas as pd datainput = [ { 'string1': 'TTTABCDABCDTTTTT', 'string2': 'ABABABABABABABAA' }, { 'string1': 'AAAAAAAA', 'string2': 'TTAAAATT' }, { 'string1': 'TTABCDTTTTT', 'string2': 'ABABABABABA' } ] df = pd.DataFrame(datainput) df string1 string2 0 TTTABCDABCDTTTTT ABABABABABABABAA 1 AAAAAAAA TTAAAATT 2 TTABCDTTTTT ABABABABABA For each row, strings in columns string1 and string2 are defined to be the same length. For each row of the DataFrame, the strings may need to be "cleaned" of beginning/trailing letters 'T'. However, for each row, the strings need to both be stripped of the same number of characters, so as the strings remain the same length. The correct output is as follows: df string1 string2 0 ABCDABCD BABABABA 1 AAAA AAAA 2 ABCD ABAB If these were two variables, it would be straightforward to calculate this with strip(), e.g. string1 = "TTTABCDABCDTTTTT" string2 = "ABABABABABABABAA" length_original = len(string1) num_left_chars = len(string1) - len(string1.lstrip('T')) num_right_chars = len(string1.rstrip('T')) edited = string1[num_left_chars:num_right_chars] ## print(edited) ## 'ABCDABCD' However, in this case, one needs to iterate through all rows and redefine two rows at once. How could one modify each these strings row by row? EDIT: My main confusion is, given both columns could T, how do I re-define them both?
type: Question
has comment: http://stackoverflow.com/comment/92102692
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52583904
tagged with: strip

http://stackoverflow.com/a/52441994
type: Answer
answers question: http://stackoverflow.com/q/52441688
has body: Try this, print(line, end=' ') because in end of print() it takes new line character '\n' every time after successfully execution. end is default argument in print function which specify which character do you want to keep in end in print()...
has comment: http://stackoverflow.com/comment/91827476
score: 0

http://stackoverflow.com/a/52570388
has body: You had an error in writing move[playermove + ".txt",r]) It should be where you should also replace r by 'r' move[playermove] + ".txt",'r')
answers question: http://stackoverflow.com/q/52570369
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92077589
type: Answer
has comment: http://stackoverflow.com/comment/92077569
has comment: http://stackoverflow.com/comment/92077533
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92077596
accepted answer of: http://stackoverflow.com/q/52570369

http://stackoverflow.com/comment/91905586
comment on: http://stackoverflow.com/a/52481852
score: 0
type: AnswerComment
has text: @chepner: aa, ok then, makes more sense that way.
type: Comment

http://stackoverflow.com/comment/92298104
has text: You probably need to look at Elasticsearch then.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52565068

http://stackoverflow.com/comment/91835561
type: QuestionComment
score: 1
has text: I've updated my main post, thanks in advance
comment on: http://stackoverflow.com/q/52446075
type: Comment

http://stackoverflow.com/q/52439778
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: parallel-processing
has answer: http://stackoverflow.com/a/52440157
downvote count: 1
tagged with: multiprocessing
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/20360686
has body: I am in the following setting: I have a method that takes an objective function f as input. As a subrouting of that method i want to evaluate f on a small set of points. Since f has high complexity i considered doing that in parallel. All online examples hang up even for trivial functions like squaring on sets with 5 points. They are using the multiprocessing library - and i don't know what i am doing wrong. I am not sure how to encapsulate that __name__ == "__main__" statement in my method. (since it is part of a module - i guess instead of "__main__" i should use the module name?) Code i have been using looks like from multiprocessing.pool import Pool from multiprocessing import cpu_count x = [1,2,3,4,5] num_cores = cpu_count() def f(x): return x**2 if __name__ == "__main__": pool = Pool(num_cores) y = list(pool.map(f, x)) pool.join() print(y) When executing this code in my spyder it takes a bloody long time to finish. So my main questions are: What am i doing wrong in this code? How can i encapsulate the __name__-statement, when this code is part of a bigger method? Is it even worth it parallelizing this? (one function evaluation can take multiple minutes and in serial this adds up to a total runtime of hours...)
score: 0
has answer: http://stackoverflow.com/a/52440098
favorite count: 0
has title: Pythons parallel processing

http://stackoverflow.com/q/52509500
has answer: http://stackoverflow.com/a/52509533
has comment: http://stackoverflow.com/comment/91959154
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91959117
type: Question
has answer: http://stackoverflow.com/a/52509528
has comment: http://stackoverflow.com/comment/91959130
has title: Printing list of numbers as an array from for loop Python
tagged with: for-loop
tagged with: arrays
score: 0
answer count: 3
has body: With the code below, it prints the value 'phase' one by one. I am trying to print these values as an array outside of for loop. import math Period = 6.2 time1 = datafile1[:,0] magnitude1 = datafile1[:,1] for i in range(len(time1)): print(i,time1[i]) floor = math.floor((time1[i]-time1[0])/Period) phase = ((time1[i]-time1[0])/Period)-floor print (phase) It is printing like this: 0.002 0.003 0.004 0.005 I would like it to print like this: [0.002, 0.003, 0.004, 0.005]
has answer: http://stackoverflow.com/a/52509536
has comment: http://stackoverflow.com/comment/91959200

http://stackoverflow.com/comment/92103975
type: QuestionComment
has text: Yeah, look into the `struct` module for this. But you have 12 bytes there. you can use `len` on the bytes-object
score: 0
comment on: http://stackoverflow.com/q/52584499
type: Comment

http://stackoverflow.com/comment/91814363
type: Comment
score: 1
has text: Haha... both of us focusing on this question, can do `fillna` for replacing `nan`s with `''`
type: AnswerComment
comment on: http://stackoverflow.com/a/52435412

http://stackoverflow.com/q/52470149
has comment: http://stackoverflow.com/comment/91883228
has comment: http://stackoverflow.com/comment/91883560
upvote count: 1
tagged with: simulation
favorite count: 0
tagged with: fft
answer count: 0
tagged with: dft
type: UnansweredQuestion
has title: k-space vector for N-body simulation box DFTs
tagged with: python
has body: I'm trying to write a particle mesh N-body simulation. In such a simulation the potential field is found by solving Poisson's equation using Fourier transforms. I have been following a presentation by Andrey Kravtsov (http://astro.uchicago.edu/~andrey/talks/PM/pm.pdf), but slide 15 has me confused. So far, I have assigned densities to a 3d grid from particle positions, and Fourier transformed the density grid. The next step is to calculate Green's function in Fourier space and multiply it with the Fourier transformed density grid, and afterwards applying an inverse Fourier transform to real space to obtain the potential grid. Through trial and error I traced the part that wasn't working correctly to the potential calculation, and specifically the k-space vector. So, to calculate Green's function in Fourier space I need the Fourier axes usually called k-space vectors k_x, k_y, k_z. Using the slide it should be 2*pi*(k,l,m)/N_g for components k,l,m, where N_g is the number of grid cells. So far I've tried with these components running from 0,+1,+2,...,N_g. And -N_particle/2, ..., +N_particle/2 and several other iterations. The only thing that has produced reasonable results (can see a cluster in density slice projected on the same potential field slice) has been with using numpy.fft.freq in Python for specific values of the resolution/sample spacing. However, any resolution I chose (such as L/N_g, N_p/N_g, 2pi/N_g, etc.) did not scale properly with box size L, number of grid cells or number of particles and no longer worked for e.g. larger number of grid cells. My question is: How do I define my k-space vectors (i.e. the Fourier axes in reciprocal space) for a simulation with, along one direction, box size L, number of grid cells N_g and number of particles N_p? I should add that the particle positions and velocities are all in code units as defined in the first few slides. Minimum working example: #!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as …
has comment: http://stackoverflow.com/comment/91883322
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91882357

http://stackoverflow.com/q/52569134
has comment: http://stackoverflow.com/comment/92075270
has title: Understanding concepts of timedelta
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/92075321
upvote count: 1
type: Question
has body: I wrote a code to print 5 consecutive date and time each having 2 seconds of difference. Given below is the python code. import datetime import time lt = [] for i in range(5): now = datetime.datetime.now() after = (now + datetime.timedelta(seconds=2)) lt.append(after) for i in lt: print(i) it instead resulted in completely different output as provided below. 2018-09-29 18:05:50.791096 2018-09-29 18:05:50.791096 2018-09-29 18:05:50.791096 2018-09-29 18:05:50.791096 2018-09-29 18:05:50.791096 2018-09-29 18:08:56.935234 2018-09-29 18:08:56.935234 2018-09-29 18:08:56.935234 2018-09-29 18:08:56.935234 2018-09-29 18:08:56.935234 Although, I got the correct intended result using time.sleep(2) But what actually is wrong in the above provided code that output is coming out to be different.

qt
tags question: http://stackoverflow.com/q/52455017
type: Tag
tags question: http://stackoverflow.com/q/52503964
tags question: http://stackoverflow.com/q/52527137
tag name: qt

http://stackoverflow.com/comment/91819686
score: 0
type: Comment
type: QuestionComment
has text: `loginApi.loginApp` is not the same as `LoginApi.LoginApp`. Which is it?
comment on: http://stackoverflow.com/q/52433414

http://stackoverflow.com/q/52570489
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/20826725
has body: I am using celery + redis for tasks in Django web app. The problem is that I don't know at what point does celery store it's task result as JSON object into DB. Afterwards an issue is raised because it cannot store np array as JSON. import numpy as np from scipy.sparse import dok_matrix @shared_task(name="run_shortest_path_on_warehouse") def run_shortest_path_on_warehouse(adjacency_matrix): sparse_matrix = dok_matrix(adjacency_matrix) dist_matrix = dijkstra_algorithm(sparse_matrix).tolist() return {'optimal_distance_matrix': dist_matrix} Celery can't store the result, because of this exception: {"exc_type": "EncodeError", "exc_message": ["TypeError(\"Object of type 'ndarray' is not JSON serializable\",)"], "exc_module": "kombu.exceptions"} I know that numpy array isn't simply JSON serializable. That's why I used .tolist method in defining the dist_matrix variable. The question is, at what point does celery store it's variable and how can I store info from numpy array as task result?
answer count: 1
score: 0
has title: At what point does celery store result?
has answer: http://stackoverflow.com/a/52570902
accepted answer: http://stackoverflow.com/a/52570902
tagged with: redis
tagged with: django
tagged with: python
tagged with: celery
type: AnsweredQuestion

http://stackoverflow.com/comment/91910241
type: Comment
comment on: http://stackoverflow.com/a/52482007
type: AnswerComment
score: 0
has text: @elPastor: Glad I could help. I should put a short troubleshooting section [here](https://stackoverflow.com/questions/42579908/use-corr-to-get-the-correlation-between-two-columns/42580124#42580124) and refer to your question.

http://stackoverflow.com/a/52523312
has body: The error indicates that not every order has a customer field. So you need to check for that. if 'customer' in result: first_name = result['customer']['first_name'] else: first_name = 'unknown'
score: 0
answers question: http://stackoverflow.com/q/52522818
type: Answer

http://stackoverflow.com/q/52466092
tagged with: importerror
answer count: 1
has body: Given two files on the directory /khwarizmi such as /khwarizmi/linear.py and /khwarizmi/exceptions.py, importing functions and classes from one another works without problem when running the scripts through the OS command line (Ubuntu 18.04). Yet, when I run the scripts from Atom (whether it is from the Hydrogen, the python-run or the script packages, I get Traceback (most recent call last): File "/home/santiago/Documentos/ScriptLab/Repos/khwarizmi/khwarizmi/linear.py", line 1, in &lt;module&gt; from exceptions import (InvalidFormError, LinearSolutionError, ImportError: cannot import name InvalidFormError [Finished in 0.074s] This is how the imports are written: from exceptions import (InvalidFormError, LinearSolutionError, RedundantConversionError) # The following are other imports that, provided # they were executed, raise the same error. import equations from equations import operators from lib.misc import cond_assign, num I tried tweaking the packages settings that would seem relevant; for example, changing the Default CWD setting from first project directory to project directory of the script or directory of the script, but this didn't change anything. My question is, why doesn't this work when running the scripts from Atom packages, but it does from the command line? (If you want to see how the repository is structured, or the full code, see: https://github.com/lpereyrasantiago/khwarizmi )
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52466768
has title: ImportError: cannot import name <module> only when running file from atom
tagged with: import
type: Question
accepted answer: http://stackoverflow.com/a/52466768
tagged with: atom-editor

http://stackoverflow.com/comment/91857392
has text: This doesn't sound like a practical setup. Why do you want to run an app from Jupyter?
score: 2
comment on: http://stackoverflow.com/q/52457582
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52459081
has title: Python: Function to convert string to int
linked to: http://stackoverflow.com/q/379906
tagged with: function
has comment: http://stackoverflow.com/comment/91860855
tagged with: int
has comment: http://stackoverflow.com/comment/91860457
has comment: http://stackoverflow.com/comment/91860376
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91860405
possible better answer: http://stackoverflow.com/a/52459274
tagged with: string
has answer: http://stackoverflow.com/a/52459274
has answer: http://stackoverflow.com/a/52459445
tagged with: python
has comment: http://stackoverflow.com/comment/91860364
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91860343
has body: Good morning everyone! I am new to programming and am learning python. I am trying to create a function that converts each individual char in string into each corresponding individuals ints and displays them one after another. The first error it generates is "c is not defined". c='' def encode(secret_message): for c in secret_message: int_message=+ord(c) return int_message Example of what I want it to do: secret_message='You' (this is a string) return: 89 111 117 (this should be an int, not a list) note: 'Y'=89, 'o'=111, 'u'=117 the idea is that encode takes in a parameter secret message. It then iterates through each char in c and converts each char from a string to an int. Then it returns the entire message in ints. I'm also not sure how to get each char to appear in int_message. As of now, it looks like it will add all the ints together. I want it to simply place them together (like a string). Do I need to convert it back to a string after I get the int values then concatenate?
has answer: http://stackoverflow.com/a/52459335
accepted answer: http://stackoverflow.com/a/52459335
has comment: http://stackoverflow.com/comment/91860554
type: Question
has comment: http://stackoverflow.com/comment/91860412

http://stackoverflow.com/q/52467838
tagged with: pandas
has answer: http://stackoverflow.com/a/52467901
tagged with: python
favorite count: 0
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52467987
has body: I am currently trying to add some values of a list to a new column in my pandas table. First value of col3is the first of the list. Second value is the same in case the tuple of col1and col2is still the same. Condition to start adding the next item of the list is that it is a new unique combination of the items from column col1 and col2. Example: df = pd.DataFrame({'col1':[1,1,1,1,3,3,3,10], 'col2':[1,1,2,2,9,9,9,5]}) list1=[5,9,3,12] col1 col2 col1 col2 col3 1 1 1 1 5 1 1 1 1 5 1 2 should become 1 2 9 1 2 ------------------&gt; 1 2 9 3 9 3 9 3 3 9 3 9 3 3 9 3 9 3 10 5 10 5 12 I had it working with just 1 column as condition like that: di =dict(zip(df['col1'].unique(),list1)) df['col2'] = df_averageInPanda['col1'].map(di) To run it with the tuple condition I tried drop_duplicate(), as the unique()function does not work on multiple columns, but it does not work, but gives me an empty col3 di =dict(zip(df'col1','col2'.drop_duplicates(),list1)) df['col3'] = df['col1'].map(di) Any idea of how to fix it?
type: AnsweredQuestion
has title: Pandas add new column and fill it with item from list when tuple of other 2 columns is unique
accepted answer: http://stackoverflow.com/a/52467901
tagged with: list
possible better answer: http://stackoverflow.com/a/52467987
type: Question
answer count: 2
downvote count: 0
tagged with: multiple-columns

http://stackoverflow.com/q/52511080
tagged with: windows
tagged with: python
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91966183
type: Question
has title: Python crashes when using call (ntdll.dll)
tagged with: python-3.4
has comment: http://stackoverflow.com/comment/91962595
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91962613
has body: I have a script that combines around 1000 files by using an external program. It does so by copying the first file to combined.sym and then combining the this file with all other files, one by one. Code is as follows: # gets all .sym files symfiles = [] onlyfiles = [f for f in listdir(myPath) if isfile(join(myPath, f))] for f in onlyfiles: if '.sym' == splitext(f)[1]: symfiles.append(f) # copies one initial combined file (point to start from) combinedFileName = "combined.sym" copyfile(myPath + symfiles[0], myPath + combinedFileName) for sym in symfiles: print("processing " + str(sym)) cmdString = combinedFileName + " " cmdString += sym cmdString += " -a " + combinedFileName finalCmdString = r'cmd.exe /C fuseFiles.bat "' + myPath + '" "' + cmdString + '"' call(finalCmdString) print("done") The batchfile I'm calling looks like this, but that is not the issue: @set PATH=\path\to\executable\;%PATH% @cd %1 @FusingProgram "%2" Now, when I run this script, it runs for like 15 Minutes before it just stops and returns to the CMD. processing onefile.sym processing anotherfile.sym processing evenmorefiles.sym processing yougetit.sym C:\Users\test\&gt; As you can see, it misses the "done" print, and it didn't process all files. The combined.sym is created and expanded by the other .sym files When checking the Windows events, I can see, that it logs python as crashed and lists ntdll.dll as faulty module(sorry for german log): Name der fehlerhaften Anwendung: python.exe, Version: 0.0.0.0, Zeitstempel: 0x53787196 Name des fehlerhaften Moduls: ntdll.dll, Version: ****, Zeitstempel: 0x5b6db230 Ausnahmecode: 0xc0000005 Fehleroffset: 0x0002e2eb ID des fehlerhaften Prozesses: 0x6224 Startzeit der fehlerhaften Anwendung: 0x01d454e0ff20377c Pfad der fehlerhaften Anwendung: C:\pat\to\python\python.exe Pfad des fehlerhaften Moduls: C:\WINDOWS\SysWOW64\ntdll.dll Berichtskennung: 8b4254f0-c0d5-11e8-9a6f-901b0e5a6206 I've done some research and it seems like I'd have to resolve this by updati…
type: UnansweredQuestion

http://stackoverflow.com/q/52556720
possible better answer: http://stackoverflow.com/a/52556810
has answer: http://stackoverflow.com/a/52556848
accepted answer: http://stackoverflow.com/a/52556876
has answer: http://stackoverflow.com/a/52556838
has comment: http://stackoverflow.com/comment/92052079
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92052082
has comment: http://stackoverflow.com/comment/92052118
has comment: http://stackoverflow.com/comment/92052237
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/92052065
has title: List comprehension, value if not in second list
score: 2
upvote count: 2
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92052826
has answer: http://stackoverflow.com/a/52556810
has body: Is it possible to use list comprehension to get the sales for each week if the week exists in sales else 0? weeks = [{'week': 31}, {'week': 32}, {'week': 33}, {'week': 34}, {'week': 35}, {'week': 36}] weeks = [x['week'] for x in weeks] sales = [ {'week': 32, 'sales': 1167.26}, {'week': 33, 'sales': 1373.61}, {'week': 36, 'sales': 1491.43}, ] expected = [0, 1167.26, 1373.61, 0, 0, 1491.43]
has comment: http://stackoverflow.com/comment/92052149
has answer: http://stackoverflow.com/a/52556876

http://stackoverflow.com/a/52495046
accepted answer of: http://stackoverflow.com/q/52494608
answers question: http://stackoverflow.com/q/52494608
has body: In this case a number of useful tags (inside the doxygen configuration file, default can be generated by means of doxygen -g), especially with not yet documented code: RECURSIVE EXTRACT_... HAVE_DOT (note that you need the graphviz dot program installed as well). CALL_GRAPH CALLER_GRAPH
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91930725
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91930829
has comment: http://stackoverflow.com/comment/91930771

http://stackoverflow.com/q/52548474
tagged with: http://stackoverflow.com/tag/html
tagged with: django
has body: I'm trying to integrate Django-simple-math-captcha in my project, but the form doesn't render the question. I've followed all the steps in the docs, and render the form: {% for field in form %} {{ field.label_tag }} {{ field }} {% if field.errors %} {{ field.errors }} {% else %} {% endif %} {% endfor %} I get the captcha label i.e. Captcha: and the captcha answer input, all captcha error messages, but no question. What have I done wrong?
tagged with: python
tagged with: css
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52549513
has comment: http://stackoverflow.com/comment/92036830
has comment: http://stackoverflow.com/comment/92036535
type: Question
has comment: http://stackoverflow.com/comment/92036700
score: 0
answer count: 1
has title: Why doesn't Django-simple-math-captcha render question?
has answer: http://stackoverflow.com/a/52549513

math
tags question: http://stackoverflow.com/q/52465795
type: Tag
tags question: http://stackoverflow.com/q/52586108
tags question: http://stackoverflow.com/q/52529409
tags question: http://stackoverflow.com/q/52464309
tags question: http://stackoverflow.com/q/52445538
tags question: http://stackoverflow.com/q/52584447
tags question: http://stackoverflow.com/q/52574623
tag name: math

sitemap
type: Tag
tags question: http://stackoverflow.com/q/52486744
tag name: sitemap

http://stackoverflow.com/a/52466067
has comment: http://stackoverflow.com/comment/91874879
upvote count: 1
score: 1
has body: Pandas will only attempt to infer_datetime_format for what you specify in parse_dates. You currently have this set to False. You need to tell it which columns in your csv file contain dates. I'm not sure if this answers your question as I'm unsure what 'not have to manually call at date columns' means. Do you mean you don't want to have to convert the date columns separately from reading in the file or that you don't want to tell read_csv which columns contain dates?
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52466006
has comment: http://stackoverflow.com/comment/91873803

http://stackoverflow.com/comment/91914411
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52486243
has text: could you please attach a code or a smaller example which one could reproduce?
score: 0

http://stackoverflow.com/q/52554798
favorite count: 0
has comment: http://stackoverflow.com/comment/92050212
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92049927
tagged with: python
has comment: http://stackoverflow.com/comment/92050478
has comment: http://stackoverflow.com/comment/92048391
tagged with: c++
has comment: http://stackoverflow.com/comment/92050255
tagged with: dlib
answer count: 0
has comment: http://stackoverflow.com/comment/92051945
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/98972608
has comment: http://stackoverflow.com/comment/98994972
has title: dlib python face encoding vs c++ face encoding
score: 0
has body: I'm trying to produce the same face encoding in C++ that this python wrapper library gives: https://github.com/ageitgey/face_recognition/blob/master/face_recognition/api.py C++ code: frontal_face_detector detector; ... for (auto face : detector(img, numberOfTimesToUpsample)) { auto shape = sp(img, face); //sp = shape_predictor 5 face landmarks same as python lib matrix&lt;rgb_pixel&gt; face_chip; extract_image_chip(img, get_face_chip_details(shape,150,0.25), face_chip); // Chip size and padding same as dlib python settings faces.push_back(move(face_chip)); coords.push_back(face); } ... std::vector&lt;dlib::matrix&lt;float,0,1&gt;&gt; face_descriptors = net(faces, 16); // net is dlib_face_recognition_resnet_model_v1 same as python lib ... The python library upsamples once by default, and uses the small (5 point) shape predictor, so I invoke the c++ code with numberOfTimesToUpsample as 1, and as my c++ code doesn't do the jittering, then I invoke the python code as: encoding = face_recognition.face_encodings(image, num_jitters=0)[0] However, when I run an image with a face through both systems, the encodings come out quite different. For example, the c++ output of the first few dims: -0.131519 0.0520326 0.0556113 -0.101895 -0.165266 And the python: -0.14469159 0.04349349 0.03403644 -0.1062524 -0.18296713 I've examined the dlib C++-Python API for computing encodings here: https://github.com/davisking/dlib/blob/master/tools/python/src/face_recognition.cpp and cannot really see any major differences other than not casting everything to double. Edit: I've tried converting to double as well. All the numbers are just the same. I've tried building my project linked to the .so file that the python dlib library comes with. Still got the same numbers. I checked that my method of reading in the image data produces the same RGB pixel values as the python PIL.Image reading-into-numpy-array does. Everything looks fine there. I'd like to reliably be able to produce the same output. …

http://stackoverflow.com/comment/91971531
type: QuestionComment
comment on: http://stackoverflow.com/q/52515599
has text: What version of numpy are you using? I can't get this to run: `TypeError: Mismatch between array dtype ('float64') and format specifier ('%.18e')` in 1.13.3
score: 0
type: Comment

http://stackoverflow.com/q/52531484
has answer: http://stackoverflow.com/a/52531726
type: Question
tagged with: python-2.7
has title: how to input password from python script or shell script when asked during script execution
answer count: 2
score: 2
has body: Hi I have below python script with below line Script name : add_cert.py keytool -keystore client.truststore.jks -alias rby-yagpps -import -file rby-yagpps_1.crt keytool -keystore client.truststore.jks -alias rby-yagpps -import -file rby-yagpps_1.crt keytool -keystore client.truststore.jks -alias rby-yagpps -import -file rby-yagpps_1.crt keytool -keystore client.truststore.jks -alias rby-yagpps -import -file rby-yagpps_1.crt with each line executing by script , it asking password , i have same password for all of the above lines how to input password automatically without manual intervention ?
has answer: http://stackoverflow.com/a/52531734
downvote count: 0
favorite count: 0
tagged with: python
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: sh

http://stackoverflow.com/q/52472227
favorite count: 0
tagged with: binary-search
answer count: 1
has body: I know that binary search only works in a sorted list. I want to search ( O(log n) ) and be able to find an item in a list with 2 sorted sections. EX: [20,30,1,2,3,4,5] Is O(log n) binary search the only option? I want to split the list where the order is lost, however, as the list size changes it would no longer be at the complexity I want it?
has answer: http://stackoverflow.com/a/52472752
type: UnansweredQuestion
tagged with: python
downvote count: 1
has title: Binary search in a list which contains 2 sorted sections
score: -1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91886376

http://stackoverflow.com/q/52458085
accepted answer: http://stackoverflow.com/a/52458133
answer count: 1
downvote count: 0
tagged with: string
has body: I have a dataframe that looks like this: my data I used this to filter for users who's id's begin with b, c, e, f, 5 and was able to successfully execute this. df[df.userA.str.startswith(('b','c','e','f','5'))] I now want to do the same for columns userA and userB, and tried running this unsuccessfully: df[[df.userA.str.startswith(('b','c','e','f','5'))] and [df.userB.str.startswith(('b','c','e','f','5'))]] Any ideas?
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91858554
favorite count: 0
has comment: http://stackoverflow.com/comment/91858387
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52458133
has title: how to use str.startswith for multiple columns?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91858305
has comment: http://stackoverflow.com/comment/91858315
type: Question
tagged with: startswith

http://stackoverflow.com/a/52443517
answers question: http://stackoverflow.com/q/52443482
has body: Working solution for you. You also need to replace text.startswith('t') by twords.startswith('t') because you are now using twords to iterate through each word of your original statement stored in text. You used break which would only make your code print this since after finding the first word, it will break outside the for loop. To get all the words beginning with t, you need to get rid of the break. text = "this is a text sentence with words in it that start with letters" empty_list = [] for twords in text.split(): if twords.startswith('t') == True: empty_list.append(twords) print(empty_list) &gt; ['this', 'text', 'that']
score: 0
accepted answer of: http://stackoverflow.com/q/52443482
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/92035057
has text: It's seems that modules and classes are the way to go.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52547772

http://stackoverflow.com/a/52466164
has body: This should do it: import pandas as pd data = [[1, 2, 3], [3, 4], [4, 5, 5]] df = pd.DataFrame(data).transpose() df.columns = columns Output: a b c 0 1.0 3.0 4.0 1 2.0 4.0 5.0 2 3.0 NaN 5.0
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52466053
has comment: http://stackoverflow.com/comment/91874117
answers question: http://stackoverflow.com/q/52466053
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/52558526
has comment: http://stackoverflow.com/comment/92055843
type: Question
has answer: http://stackoverflow.com/a/52572986
has comment: http://stackoverflow.com/comment/92055669
has comment: http://stackoverflow.com/comment/92056162
has title: Randomly define the training size in train_test_split sklearn
has body: I am trying to split data that I have into 40% training and 60% validation, then I want to repeat this 30 times, each time with random training and different validation. How can I do this? (not using Kfold) This is what I wrote but I am getting the same results every time for accuracy, I do not know how to do this with different training and validation each time. My accuracy is the same for each iteration, I don't know why. for i in range (30): X_train, X_test, y_train, y_test =train_test_split(df,y, train_size=0.4, shuffle=True) metrics.accuracy_score(linsvc.predict(X_train), R_train)
tagged with: random
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52572986
has comment: http://stackoverflow.com/comment/92057102
tagged with: python
has comment: http://stackoverflow.com/comment/92056830
has comment: http://stackoverflow.com/comment/92056340
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/52430395
has answer: http://stackoverflow.com/a/52430643
answer count: 4
upvote count: 11
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52430643
type: Question
tagged with: numpy
has body: Not so much a question but something puzzling me. I have a column of dates that looks something like this: 0 NaT 1 1996-04-01 2 2000-03-01 3 NaT 4 NaT 5 NaT 6 NaT 7 NaT 8 NaT I'd like to convert it the NaTs to a static value. (Assume I imported pandas as pd and numpy as np). If I do: mydata['mynewdate'] = mydata.mydate.replace( np.NaN, pd.datetime(1994,6,30,0,0)) All is well, I get: 0 1994-06-30 1 1996-04-01 2 2000-03-01 3 1994-06-30 4 1994-06-30 5 1994-06-30 6 1994-06-30 7 1994-06-30 8 1994-06-30 But if I do: mydata['mynewdate'] = np.where( mydata['mydate'].isnull(), pd.datetime(1994,6,30,0,0),mydata['mydate']) I get: 0 1994-06-30 00:00:00 1 828316800000000000 2 951868800000000000 3 1994-06-30 00:00:00 4 1994-06-30 00:00:00 5 1994-06-30 00:00:00 6 1994-06-30 00:00:00 7 1994-06-30 00:00:00 8 1994-06-30 00:00:00 This operation converts the original, non-null dates to integers. I thought there might be a mix-up of data types, so I did this: mydata['mynewdate'] = np.where( mydata['mydate'].isnull(), pd.datetime(1994,6,30,0,0),pd.to_datetime(mydata['mydate'])) And still get: 0 1994-06-30 00:00:00 1 828316800000000000 2 951868800000000000 3 1994-06-30 00:00:00 4 1994-06-30 00:00:00 5 1994-06-30 00:00:00 6 1994-06-30 00:00:00 7 1994-06-30 00:00:00 8 1994-06-30 00:00:00 Please note (and don't ask): Yes, I have a better solution for replacing nulls. This question is not about replacing nulls (as the title indicates that it is not) but how numpy where is handling dates. I ask because I will have more complex conditions to select dates to replace in the future, and thought numpy where would do the job. Any ideas?
has answer: http://stackoverflow.com/a/73667750
has answer: http://stackoverflow.com/a/77168753
tagged with: where-clause
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/52430739
favorite count: 0
has answer: http://stackoverflow.com/a/52430739
has title: Numpy Where Changing Timestamps/Datetime to Integers
tagged with: datetime
tagged with: python
score: 11

http://stackoverflow.com/a/52528196
has comment: http://stackoverflow.com/comment/91995999
has body: Your list comprehension produces items according to the order of the values of the parm dict (which is pretty arbitrary prior to Python 3.6), so naturally it won't follow the order of the keys you use in the condition for the if statement. If you want the keys to be reordered in the same way as the keys used in the condition you should make it a separate list and use it for both the condition and the list comprehension: parm = {'r':'r', 'l':'l', 't':'t', 'u':'u', 'f':'f', 'b':'b'} keys = ['f', 'r', 'b', 'l', 't','u'] if all(key in parm for key in keys): parm = [parm[key] for key in keys for i in range(0,9)] print (parm)
accepted answer of: http://stackoverflow.com/q/52528090
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52528090

http://stackoverflow.com/comment/92041254
comment on: http://stackoverflow.com/a/52551159
type: Comment
has text: The question specifies: "*I am trying to do bubble sort in descending order*". But +1 anyway..
score: 2
type: AnswerComment

http://stackoverflow.com/q/52569322
tagged with: azure-cognitive-services
tagged with: azure
tagged with: python
has answer: http://stackoverflow.com/a/55351241
tagged with: computer-vision
type: AnsweredQuestion
has title: Ms Computer Vision API image url replace as local .jpg using Python
accepted answer: http://stackoverflow.com/a/52582489
has body: I am trying to write a python program on Pi to capture an image and get the description from Ms Computer Vision API. It is working with using image_url as "http://website.com/abc.jpg", but when I change to my local image "abc.jpg", it is have an error. File "ms.py", line 71, in response.raise_for_status() File "C:\Python27\lib\site-packages\requests-2.19.1-py2.7.egg\requests\models.py", line 939, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze?visualFeatures=Categories%2CDescription%2CColor The original working code is below: import requests import matplotlib.pyplot as plt import simplejson as json from PIL import Image from io import BytesIO subscription_key = "XXXX" assert subscription_key vision_base_url = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/" analyze_url = vision_base_url + "analyze" # Set image_url to the URL of an image that you want to analyze. image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/" + \ "Broadway_and_Times_Square_by_night.jpg/450px-Broadway_and_Times_Square_by_night.jpg" headers = {'Ocp-Apim-Subscription-Key': subscription_key } params = {'visualFeatures': 'Categories,Description,Color'} data = {'url': image_url} response = requests.post(analyze_url, headers=headers, params=params, json=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(json.dumps(response.json())) image_caption = analysis["description"]["captions"][0]["text"].capitalize() # Display the image and overlay it with the caption. image = Image.open(BytesIO(requests.get(image_url).content)) plt.imshow(image) plt.axis("off") _ = plt.title(image_caption, size="x-large", y=-0.1) plt.show() so when replacing image…
possible better answer: http://stackoverflow.com/a/55351241
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52582489
score: 0

http://stackoverflow.com/q/52545611
tagged with: python-3.7
tagged with: spyder
answer count: 0
linked to: http://stackoverflow.com/q/19124601
score: 0
type: UnansweredQuestion
tagged with: python
has body: I am new in python programming. I am working on a big matrix of data. While trying to use the pandas function .nunique, to count the elements referring to the elements of the first row, I am given back only the first 30 and the last 30 rows of the complete output. The mid part is missing and reported by the three dots (...) readCSV=pd.read_csv('/Users/.../test.csv',delimiter=',') nuniq=readCSV.groupby('#RIC')['Date-Time'].nunique() print(nuniq) Here I report the central part of the output as it appears in the console: DE113522= 1112256 DE113527= 1112256 ... IT512708= 307507 IT513584= 303438 Knowing my data, there are at least 50 other rows not appearing. Is there a way to get all the rows of the output? I am working with Mac.
has comment: http://stackoverflow.com/comment/92033266
has comment: http://stackoverflow.com/comment/92031248
has title: I have difficulties in getting the complete list of output in Spyder (Python 3.6)
type: Question

http://stackoverflow.com/comment/91918084
score: 1
comment on: http://stackoverflow.com/q/52488393
has text: You can't have code between your if and the preceding else that's not inside the if statement
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91950967
score: 0
comment on: http://stackoverflow.com/q/52502563
has text: What is the `if size()`? Have you varied initial conditions? probably a good idea to first "fit by eye" (plot the function for your initial guess). You could also use scipy's `differential_evolution` which might be more appropriate for such a function.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52518404
type: Answer
has comment: http://stackoverflow.com/comment/91980558
has comment: http://stackoverflow.com/comment/106150930
has comment: http://stackoverflow.com/comment/91980851
has body: I suggest you use pyinstaller, see here: https://www.pyinstaller.org/ To use it, open the terminal , and type pip install pyinstall to intall pyinstaller on your mechine. Then, open the terminal under the python file you desired to become executable file, and then write: pyinstaller --onefile yourfileName.py . It will create 3 folders. Your'e EXE file is under dist. That's it, it's ready to use.
score: 0
answers question: http://stackoverflow.com/q/52518199

http://stackoverflow.com/comment/91862218
has text: Sorry but i didn't worked for me. Problem is, output is not copied to the file.
comment on: http://stackoverflow.com/a/52459966
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91993533
has text: @Lin: Apply the decorators to `func` directly.
type: AnswerComment
comment on: http://stackoverflow.com/a/52518438
score: 0
type: Comment

http://stackoverflow.com/comment/91952014
type: QuestionComment
comment on: http://stackoverflow.com/q/52505696
score: 3
has text: It's unclear to me why you're even using a class. This is not how classes should be used. And I can't tell you how to do it properly because I don't know what "it" even is. I don't know what the point of your code is. My best guess is that `sayHello` and `driver` should be functions (not methods), and that there should be no class at all.
type: Comment

http://stackoverflow.com/a/52453446
has comment: http://stackoverflow.com/comment/91950873
has comment: http://stackoverflow.com/comment/91950949
has comment: http://stackoverflow.com/comment/91857442
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91920636
has comment: http://stackoverflow.com/comment/91911956
upvote count: 1
has comment: http://stackoverflow.com/comment/91957497
accepted answer of: http://stackoverflow.com/q/52452041
answers question: http://stackoverflow.com/q/52452041
has comment: http://stackoverflow.com/comment/91911930
type: Answer
has body: The simplest way to fetch all the headings and channels in the modal window is by using the below xpaths. Also, below xpaths are dynamic and not hardcoded. Even if new channels or headings are added in future, these xpaths will still work. headings = driver.find_elements_by_xpath("//div[@class='modal-content']//*[contains(@class,'Package-channels--heading ng-binding')]") print('all headings: '+str(len(headings))) channels= driver.find_elements_by_xpath("//div[@class='modal-content']//a[contains(@class,'PackageChannelImage')]") print('all channels: '+str(len(channels))) Output: all headings: 17 all channels: 243 You can use the below approach to fetch the channels per heading and print them. headingsCount = len(driver.find_elements_by_xpath("//div[@class='modal-content']//*[contains(@class,'Package-channels--heading ng-binding')]")) for index in range(headingsCount): print('For heading: '+ driver.find_element_by_xpath("(//div[@class='modal-content']//*[contains(@class,'Package-channels--heading ng-binding')])[index]".replace('index',str(index+1))).text+', Channels are:') channelsPerheading = driver.find_elements_by_xpath("(//div[@class='modal-content']//ul[@ng-if='vm.channels'])[index]/li[not (contains(@class,'Package-channels--heading ng-binding'))]".replace('index',str(index+1))) for channel in channelsPerheading: print(channel.text.encode('utf-8').strip()) I have pasted the output here
downvote count: 0
score: 1

http://stackoverflow.com/q/52434321
has title: Whenever I do pip3 freeze or any pip3 command in my mac terminal, it raises a syntax error
accepted answer: http://stackoverflow.com/a/52434411
type: Question
type: AnsweredQuestion
tagged with: pip
tagged with: python
linked to: http://stackoverflow.com/q/43875138
has comment: http://stackoverflow.com/comment/91812288
answer count: 1
has body: Usually, pip3 works normally, but after installing tenser flow using pip, for some reason pip is not working anymore. For example, I did pip freeze to get my packages, but it came up with this error. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_internal/index.py", line 24, in &lt;module&gt; from pip._internal.download import HAS_TLS, is_url, path_to_url, url_to_path File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_internal/download.py", line 39, in &lt;module&gt; from pip._internal.utils.logging import indent_log File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_internal/utils/logging.py", line 9, in &lt;module&gt; from pip._internal.utils.misc import ensure_dir File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_internal/utils/misc.py", line 21, in &lt;module&gt; from pip._vendor import pkg_resources File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3095, in &lt;module&gt; @_call_aside File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3079, in _call_aside f(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3123, in _initialize_master_working_set for dist in wo…
has answer: http://stackoverflow.com/a/52434411
score: 0

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/52584755
tag name: google-oauth

http://stackoverflow.com/a/52505023
downvote count: 0
has body: Got it working. It was caused by the date. In fact, when I parse the data from the URL, the date variable is UNICODE. What you need to do is convert it by doing: your_new_date = datetime.datetime.strptime(date_that_you_want_to_convert, '%Y-%m-%d') Hope it will help!
type: Answer
answers question: http://stackoverflow.com/q/52488043
accepted answer of: http://stackoverflow.com/q/52488043
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/92070805
type: Comment
has text: I agree that it is convoluted, but the constraint is a rather specific situation which altering would create other more major problems (not obvious from my User-Tool analogy) I appreciate the answer very much.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52557006

http://stackoverflow.com/q/52534147
has answer: http://stackoverflow.com/a/52534376
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52534376
score: 1
has comment: http://stackoverflow.com/comment/92007586
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/92007552
tagged with: pandas
linked to: http://stackoverflow.com/q/6269765
answer count: 1
has title: Unable to remove part of a string in pandas DataFrame
favorite count: 0
has body: I'm using the KDDCup to train a Neural Network, but I'm getting rather confused with the layout of the data. When I download the dataset using the scikit-learn dataset function: data = datasets.fetch_kddcup99(return_X_y = True, ) df = pd.DataFrame(np.column_stack((data[0], data[1]))) and then run the command df.head(), it returns the following information: 0 1 2 3 4 5 ... 36 37 38 39 40 41 0 0 b'tcp' b'http' b'SF' 181 5450 ... 0 0 0 0 0 b'normal.' 1 0 b'tcp' b'http' b'SF' 239 486 ... 0 0 0 0 0 b'normal.' 2 0 b'tcp' b'http' b'SF' 235 1337 ... 0 0 0 0 0 b'normal.' 3 0 b'tcp' b'http' b'SF' 219 1337 ... 0 0 0 0 0 b'normal.' 4 0 b'tcp' b'http' b'SF' 217 2032 ... 0 0 0 0 0 b'normal.' [5 rows x 42 columns] I'm trying to change the output class (element 41) to just be binary depending on what the label is (if normal then 0, else 1). Now this is proving difficult as the dtype is object, and whenever I do a df.str.contains, it turns ALL samples (half a million of them) to NaN. I thought a way around this would be to replace b ' with nothing, but I'm not able to successfully do this. I'm a bit stumped on how to manipulate this dataframe where all columns are type Object, even the scalar values.

http://stackoverflow.com/comment/91923607
score: 1
has text: What return `print (file1.columns.tolist())` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52491530

http://stackoverflow.com/comment/91943435
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52501191
score: 0
has text: and you could pack the coeffs into the ranges: `rangedict = {'f1': range(-3*1850, -3*1910, -3), 'f2': range(2401, 2482), 'f3': range(5150, 5850)}` and simplify the sum: `currentsolution = sum(combination)`.

http://stackoverflow.com/q/52474166
score: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52474268
has comment: http://stackoverflow.com/comment/91890056
upvote count: 1
downvote count: 1
has title: How can I reduce nested if statements in the python code
type: Question
tagged with: if-statement
has body: if flask.request.form['token'] == stored_token: if size_of_file &gt; 10000: logging.info('data ' + filename + ' is compressed and sent') return gzip_compress(resp(200, data)) else: logging.info(filename + ' data copy') return resp(200, data) else: logging.info(' data ' + filename + ' is not compressed, but copied and sent') return resp(401, {}) I do not like how this code looks to help fix it. Or tell me that this is a good code.
has comment: http://stackoverflow.com/comment/91889963
answer count: 1
has comment: http://stackoverflow.com/comment/91889993
has answer: http://stackoverflow.com/a/52474268

http://stackoverflow.com/a/52572985
type: Answer
answers question: http://stackoverflow.com/q/52572613
has body: def list_purge(lst, rem): purged = list() for l in lst: if isinstance(l, list): l = list_purge(l, rem) else: for c in rem: l = l.replace(c, '') if len(l) &gt; 0: purged.append(l) return purged Should give: &gt;&gt;&gt;&gt;list_purge(["a", ["j", "e", "o"], ["h", "n", "s", "w", "o"], ["i", "c", "k"]], "johnwick") ['a', ['e'], ['s']] If your assignment is to leave empty strings in then just modify the code to do that.
has comment: http://stackoverflow.com/comment/92082373
score: 0

http://stackoverflow.com/comment/92052979
type: AnswerComment
comment on: http://stackoverflow.com/a/52557195
score: 0
type: Comment
has text: The next question is, I guess, does "the implementation of `int.__eq__`" require type conversion? Agree at Python level there's no conversion, but I'm not sure there's no conversion *anywhere*.

http://stackoverflow.com/comment/92075852
type: Comment
comment on: http://stackoverflow.com/q/52569391
type: QuestionComment
score: 0
has text: Does the CSV itself have column headers?

http://stackoverflow.com/a/52442825
score: 2
has body: Because you are using split() to a string which will return a list, then you are passing this list to int() that's why you are getting error. for changing datatype of list you need to use map() as below or first approach of your's. Try Below code x = [j for j in map(int,input().split())]
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52442793
answers question: http://stackoverflow.com/q/52442793
upvote count: 2

http://stackoverflow.com/q/52545850
score: 1
tagged with: scikit-image
has body: I generated a model of an ellipse using x- and y-coordinates as inputs into skimage.measure.EllipseModel. This worked well, and I now have parameters of the model ellipse: [x_center, y_center, a, b, theta]. Simply computing 2*a and 2*b will give me the full widths of the major and minor axes, respectively. But how can I find these widths at other locations? Specifically, I want to compute the widths along the horizontal, vertical, and both diagonals (which correspond to 45° and 135° from the x-axis, respectively). Since my ellipse is rotated (by 93° from the x-axis), the major and minor axis widths do not give me the ones I want. What is a simple way to measure these widths?
type: Question
has comment: http://stackoverflow.com/comment/92031625
upvote count: 1
tagged with: ellipse
favorite count: 0
tagged with: python-3.x
answer count: 0
has title: How to get widths along specific directions in model ellipse
type: UnansweredQuestion
tagged with: python
downvote count: 0

http://stackoverflow.com/q/52558306
has title: How to visit a page in my Firefox profile using Python
has answer: http://stackoverflow.com/a/52559773
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
score: 2
tagged with: selenium
has body: I'm want to visit a lit of URLs (about 3000) so I can add them to my browser history in Firefox. I'm trying to do with Selenium but it's not working. name = "C:\Users\Default\AppData\Roaming\Mozilla\Firefox\Profiles\2ccgbbg0.default" profile = webdriver.FirefoxProfile(profile_directory=name) driver = webdriver.Firefox(firefox_profile=profile) driver.get("http://www.python.org") The program takes minutes to make the profile and produces the following error when trying to make the driver. Traceback (most recent call last): File "C:/Users/Default/Documents/selenium_test.py", line 7, in &lt;module&gt; driver = webdriver.Firefox(firefox_profile=profile) File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 166, in __init__ capabilities.update(options.to_capabilities()) File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\options.py", line 180, in to_capabilities opts["profile"] = self._profile.encoded File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\firefox_profile.py", line 180, in encoded return base64.b64encode(fp.getvalue()).decode('UTF-8') File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) MemoryError What am I doing wrong? Is there a better way to go about doing this?
type: Question

http://stackoverflow.com/q/52458265
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52458333
score: -2
has comment: http://stackoverflow.com/comment/91858885
has comment: http://stackoverflow.com/comment/91858713
favorite count: 0
has comment: http://stackoverflow.com/comment/91858792
tagged with: python-3.x
type: Question
downvote count: 2
has comment: http://stackoverflow.com/comment/91858959
tagged with: python
has answer: http://stackoverflow.com/a/52458315
has body: I want to format the values correctly just under the headers. But i am unable to do so. dl-Frequency : Cell Id 3088 : 6926 dl-Frequency : Cell Id 3088 : 6917 dl-Frequency : Cell Id 10712 : 6918 I used the prints in the code as below : print('{:^10s} : {:^10s}'.format("dl-Frequency" , "Cell Id" )) print('{:^15s} : {:^15s}'.format(result.group(4), result.group(3))) Need your help. How to calculate the left or right justification to put correct value in the {:}?
has title: How to format output neatly?
has comment: http://stackoverflow.com/comment/91858731
has comment: http://stackoverflow.com/comment/91858898
answer count: 2
has comment: http://stackoverflow.com/comment/91858797

http://stackoverflow.com/comment/91907665
score: 0
has text: After following this set of instructions would python 3.6+ automatically work in VSCode?
comment on: http://stackoverflow.com/a/52482610
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92038365
has text: data.tolist() is better.
type: Comment
comment on: http://stackoverflow.com/a/52549737
score: 0
type: AnswerComment

http://stackoverflow.com/a/52573100
score: 0
answers question: http://stackoverflow.com/q/52572613
type: Answer
has body: Recurse, with a little bit of mutable parameter black magic: def purge(env, target, pos=None): if pos is None: pos = [0] for x in env: if pos[0] &gt;= len(target): yield x if isinstance(x, list): x = list(purge(x, target, pos=pos)) yield x elif x != target[pos[0]]: yield x else: pos[0] += 1 env = ["a", ["j", "e", "o"], ["h", "n", "s", "w", "o"], ["i", "c", "k"]] print(list(purge(env, "johnwick"))) Gives: ['a', ['e'], ['s', 'o'], []]

http://stackoverflow.com/comment/91951748
type: QuestionComment
comment on: http://stackoverflow.com/q/52505358
has text: @Adrian: `(55555555555555555555)` is not a `tuple`. It's a plain `int` with superfluous grouping parentheses around it. If you want a one-element `tuple`, you'd need to add a trailing comma: `(55555555555555555555,)`.
score: 3
type: Comment

http://stackoverflow.com/q/52538443
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52539681
has comment: http://stackoverflow.com/comment/92016929
score: 0
has comment: http://stackoverflow.com/comment/92016705
has title: strip out non valid and non-ascci character from my string in Python
tagged with: python
possible better answer: http://stackoverflow.com/a/52539807
has comment: http://stackoverflow.com/comment/92016789
has comment: http://stackoverflow.com/comment/92016649
tagged with: regex
has comment: http://stackoverflow.com/comment/92016344
has comment: http://stackoverflow.com/comment/92016501
has answer: http://stackoverflow.com/a/52539807
linked to: http://stackoverflow.com/q/2758921
has comment: http://stackoverflow.com/comment/92016618
has comment: http://stackoverflow.com/comment/92016400
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52539681
has body: Trying to format this string and strip out the non-ascii characters import re text = '&lt;phone_number&gt;&lt;![CDATA[0145236243 &lt;0x0C&gt;&lt;0x05&gt;&lt;0x4&gt; ]>' clean = re.sub('[^\x00-\x7f]',"", text) This does not seem to do the job properly.Does someone have a proper solution. I have also uploaded a file in case stackoverflow has formatted the non-ascci characters.
linked to: http://stackoverflow.com/q/8689795
tagged with: ascii

http://stackoverflow.com/q/52566169
has answer: http://stackoverflow.com/a/52566261
type: Question
has body: I'm trying to make a counter that ticks down from 1,000,000 to 0 in increments of 100,000 per second and displays this on one line, updating each second. However, the below code prints an extra zero at the end: counter = 1000000 while counter &gt; 0: sys.stdout.write("%s\r" % counter) sys.stdout.flush() counter -= 100000 time.sleep(1) I get the output (each writing over the previous line): 1000000 9000000 8000000 7000000 6000000 ... The script stops correctly at the end. When I replace \r with \n it prints the numbers correctly, but obviously I want it to refresh rather than create a new line each time.
answer count: 1
has comment: http://stackoverflow.com/comment/92069909
has comment: http://stackoverflow.com/comment/92069863
tagged with: python
has title: sys.stdout.write and sys.stdout.flush leave characters behind
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/92069896

http://stackoverflow.com/comment/92093735
score: 0
comment on: http://stackoverflow.com/a/52578847
type: AnswerComment
has text: @ChanKim, You should [convert to datetime](https://stackoverflow.com/questions/26763344/convert-pandas-column-to-datetime) first. Then use [`pd.Series.dt.year`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.year.html). If you're still stuck feel free to ask a new question.
type: Comment

http://stackoverflow.com/a/52563078
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92064788
answers question: http://stackoverflow.com/q/52562991
has body: The program is written well. The only think I would change is put registration = input('Are you registered to vote(Y/N)?: ') after checking if age &gt;= 18 (so the user won't be asked if they are registered if they are younger than 18). I wouldn't change anything else. def main(): # init messageOne = 'You are too young to vote.' messageTwo = 'You can vote.' messageThree = 'You need to register before you can vote.' # input age = int(input('Please enter your age: ')) # calculate / display if age &gt;= 18: registration = input('Are you registered to vote(Y/N)?: ') if registration.upper() == "Y": print(messageTwo) else: print(messageThree) else: print(messageOne) main()
type: Answer
accepted answer of: http://stackoverflow.com/q/52562991
has comment: http://stackoverflow.com/comment/92064756
has comment: http://stackoverflow.com/comment/92064811
score: 0

http://stackoverflow.com/comment/91979562
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52514405
has text: No, you should just do `B.search_result = None`, when you search and result is true you will just do `B.search_result = {'field_of_a_1': value1,'field_of_a_2': value2, ...}` and it is enough.
score: 0

http://stackoverflow.com/q/52497554
downvote count: 0
has answer: http://stackoverflow.com/a/64072196
favorite count: 0
has answer: http://stackoverflow.com/a/72525527
type: Question
tagged with: pandas
has title: Blank line below headers created when using MultiIndex and to_excel in Python
has answer: http://stackoverflow.com/a/52498899
tagged with: python
score: 26
answer count: 6
possible better answer: http://stackoverflow.com/a/56044381
has answer: http://stackoverflow.com/a/56044381
linked to: http://stackoverflow.com/q/43664902
accepted answer: http://stackoverflow.com/a/52498899
has answer: http://stackoverflow.com/a/71305025
has body: I am trying to save a Pandas dataframe to an excel file using the to_excel function with XlsxWriter. When I print the dataframe to the terminal then it reads as it should, but when I save it to excel and open the file, there is an extra blank line below the headers which shouldn't be there. This only happens when using MultiIndex for the headers, but I need the layered headers that it offers and I can't find a solution. Below is code from an online MultiIndex example which produces the same result as the project I'm working on. Any solutions would be greatly appreciated. import numpy as np import pandas as pd import xlsxwriter tuples = [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')] index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']] pd.MultiIndex.from_product(iterables, names=['first', 'second']) df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index) print(df) writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='test1') The excel output created:
tagged with: xlsxwriter
upvote count: 26
tagged with: multi-index
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69674617

http://stackoverflow.com/q/52555653
downvote count: 0
tagged with: timeout
tagged with: web-crawler
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/92051047
has comment: http://stackoverflow.com/comment/92050579
has comment: http://stackoverflow.com/comment/92050029
favorite count: 0
has body: I work on crawling the text from https://www.dailynews.co.th, and here is my question. My spider worked almost perfect at first, crawled about 4000 pages. 2018-09-28 20:05:00 [scrapy.extensions.logstats] INFO: Crawled 4161 pages (at 0 pages/min), scraped 0 items (at 0 items/min) And then it started to raise tons of TimeoutErrors from almost all urls, like this. 2018-09-28 20:06:06 [scrapy.core.scraper] ERROR: Error downloading &lt;GET https://www.dailynews.co.th/tags/When%20Will%20You%20Marry&gt; Traceback (most recent call last): File "/usr/local/app/.local/share/virtualenvs/monolingual-6kEg5ui2/lib/python2.7/site-packages/Twisted-18.7.0-py2.7-linux-x86_64.egg/twisted/internet/defer.py", line 1416, in _inlineCallbacks result = result.throwExceptionIntoGenerator(g) File "/usr/local/app/.local/share/virtualenvs/monolingual-6kEg5ui2/lib/python2.7/site-packages/Twisted-18.7.0-py2.7-linux-x86_64.egg/twisted/python/failure.py", line 491, in throwExceptionIntoGenerator return g.throw(self.type, self.value, self.tb) File "/usr/local/app/.local/share/virtualenvs/monolingual-6kEg5ui2/lib/python2.7/site-packages/scrapy/core/downloader/middleware.py", line 43, in process_request defer.returnValue((yield download_func(request=request,spider=spider))) File "/usr/local/app/.local/share/virtualenvs/monolingual-6kEg5ui2/lib/python2.7/site-packages/Twisted-18.7.0-py2.7-linux-x86_64.egg/twisted/internet/defer.py", line 654, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/usr/local/app/.local/share/virtualenvs/monolingual-6kEg5ui2/lib/python2.7/site-packages/scrapy/core/downloader/handlers/http11.py", line 351, in _cb_timeout raise TimeoutError("Getting %s took longer than %s seconds." % (url, timeout)) TimeoutError: User timeout caused connection failure: Getting https://www.dailynews.co.th/tags/When%20Will%20You%20Marry took longer than 5.0 seconds.. This was my second try and I decreased CONCURRENT_REQUESTS from 32 to 16, AUTOTHROTTLE_TARGET_CONCURREN…
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: scrapy
has title: Scrapy timeout after a while
score: 2

http://stackoverflow.com/q/52516043
favorite count: 0
tagged with: multidimensional-array
type: Question
has title: Get path of boundaries of contiguous regions in 2D array
tagged with: ndimage
tagged with: python
upvote count: 3
has body: Say I have an array like this: import numpy as np arr = np.array([ [1, 1, 3, 3, 1], [1, 3, 3, 1, 1], [4, 4, 3, 1, 1], [4, 4, 1, 1, 1] ]) There are 4 distinct regions: The top left 1s, 3s, 4s and right 1s. How would I get the paths for the bounds of each region? The coordinates of the vertices of the region, in order. For example, for the top left 1s, it is (0, 0), (0, 2), (1, 2), (1, 1), (2, 1), (2, 0) (I ultimately want to end up with something like start at 0, 0. Right 2. Down 1. Right -1. Down 1. Right -1. Down -2., but it's easy to convert, as it's just the difference between adjacent vertices) I can split it up into regions with scipy.ndimage.label: from scipy.ndimage import label regions = {} # region_value is the number in the region for region_value in np.unique(arr): labeled, n_regions = label(arr == region_value) regions[region_value] = [labeled == i for i in range(1, n_regions + 1)] Which looks more like this: {1: [ array([ [ True, True, False, False, False], [ True, False, False, False, False], [False, False, False, False, False], [False, False, False, False, False] ], dtype=bool), # Top left 1s region array([ [False, False, False, False, True], [False, False, False, True, True], [False, False, False, True, True], [False, False, True, True, True] ], dtype=bool) # Right 1s region ], 3: [ array([ [False, False, True, True, False], [False, True, True, False, False], [False, False, True, False, False], [False, False, False, False, False] ], dtype=bool) # 3s region ], 4: [ array([ [False, False, False, False, False], [False, False, False, False, False], [ True, True, False, False, False], [ True, True, False, False, False] ], dtype=bool) # 4s region ] } So how would I convert that into a path?
answer count: 1
tagged with: numpy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52516772
has comment: http://stackoverflow.com/comment/91988758
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/18304722

gnu-make
type: Tag
tags question: http://stackoverflow.com/q/52496058
tag name: gnu-make

http://stackoverflow.com/comment/92002129
has text: Tried both, but the problem is still there
comment on: http://stackoverflow.com/q/52530892
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52543267
has title: Understanding how TF implemention for CTC works
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52579619
upvote count: 1
has body: I'm trying to understand how CTC implementation works in TensorFlow. I've wrote a quick example just to test CTC function, but for some reason I'm gettign inf for some target/input values and I'm sure why is that happing!? Code: import tensorflow as tf import numpy as np # https://github.com/philipperemy/tensorflow-ctc-speech-recognition/blob/master/utils.py def sparse_tuple_from(sequences, dtype=np.int32): """Create a sparse representention of x. Args: sequences: a list of lists of type dtype where each element is a sequence Returns: A tuple with (indices, values, shape) """ indices = [] values = [] for n, seq in enumerate(sequences): indices.extend(zip([n] * len(seq), range(len(seq)))) values.extend(seq) indices = np.asarray(indices, dtype=np.int64) values = np.asarray(values, dtype=dtype) shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1] + 1], dtype=np.int64) return indices, values, shape batch_size = 1 seq_length = 2 n_labels = 2 seq_len = tf.placeholder(tf.int32, [None]) targets = tf.sparse_placeholder(tf.int32) logits = tf.constant(np.random.random((batch_size, seq_length, n_labels+1)),dtype=tf.float32) # +1 for the blank label loss = tf.reduce_mean(tf.nn.ctc_loss(targets, logits, seq_len, time_major = False)) with tf.Session() as sess: for it in range(10): rand_target = np.random.randint(n_labels, size=(seq_length)) sample_target = sparse_tuple_from([rand_target]) logitsval = sess.run(logits) lossval = sess.run(loss, feed_dict={seq_len: [seq_length], targets: sample_target}) print('******* Iter: %d *******'%it) print('logits:', logitsval) print('rand_target:', rand_target) print('rand_sparse_target:', sample_target) print('loss:', lossval) print() Sample Output: ******* Iter: 0 ******* logits: [[[ 0.10151503 0.88581538 0.56466645] [ 0.76043415 0.52718711 0.01166286]]] rand_target: [0 1] rand_sparse_target: (array([[0, 0], [0, 1]]), array([0, 1], dtype=int32), array([1, 2])) loss: 2.61521 ******* Iter: 1 ******* logits: [[[ 0.10151503 0.8858153…
tagged with: tensorflow
type: Question
type: AnsweredQuestion
score: 1
tagged with: loss-function
accepted answer: http://stackoverflow.com/a/52579619
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: ctc

http://stackoverflow.com/a/52513298
has body: Some of your solutions are very good, but it seems to me that there are more alternative options than using the function: values = 'This is a sentence' split_values = [] tmp = '' for words in values: if words == ' ': split_values.append(tmp) tmp = '' else: tmp += words if tmp: split_values.append(tmp) print(split_values)
answers question: http://stackoverflow.com/q/52495936
score: 0
type: Answer

http://stackoverflow.com/q/52574877
favorite count: 0
has answer: http://stackoverflow.com/a/52574927
accepted answer: http://stackoverflow.com/a/52575051
has body: I'm doing my Formal Languages assignment, and I got in some trouble trying to deal with Python Regex, using regex.split(param) I've the following text: {q0,q1,q2,q3},{a,b},q0,{q1,q3} Which must be splitted as: ["q0,q1,q2,q3", "a,b", "q0", "q1,q3"] It is always comma-separated, and it contains alpha-numeric values, which might start with a letter or a number. To achieve the above separation I created this incredibly long piece of code, dealing with String.join() and Array.split(): [x for x in ' '.join(' '.join(' '.join(args.split(',{')).split('}')).split('{')).split(' ') if x != ''] I tried the following with REGEX, but it simply doesn't work: re.compile("(,{)|}|{|(},)") It returns me: ['', None, None, 'q0,q1,q2,q3', None, None, '', ',{', None, 'a,b', None, None, ',q0', ',{', None, 'q1,q3', None, None, ''] It is easy to take care of all this falsey values, but why does it keeps stuff like ,{ in the array?
possible better answer: http://stackoverflow.com/a/52574927
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92085504
has comment: http://stackoverflow.com/comment/92085690
type: Question
upvote count: 4
tagged with: formal-languages
downvote count: 0
score: 4
answer count: 3
has answer: http://stackoverflow.com/a/52575051
has title: Python Regex Split interacting in a weird way
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52575027
has comment: http://stackoverflow.com/comment/92085776

http://stackoverflow.com/comment/91857607
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52457570
has text: Possible duplicate of [Python's Matplotlib plotting in wrong order](https://stackoverflow.com/questions/37414916/pythons-matplotlib-plotting-in-wrong-order)

http://stackoverflow.com/q/52552951
has comment: http://stackoverflow.com/comment/92046914
tagged with: python
answer count: 0
has title: Numpy element wise minimum for masked array return valid value instead of masked value
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92046759
has comment: http://stackoverflow.com/comment/92045734
score: 0
has comment: http://stackoverflow.com/comment/92058104
has body: I'm looping over a large masked array along a specified axis, using element-wise comparison between the current index values and the previous minima. Below is a simplified example to illustrate the problem. If one of the values is masked and the other is valid, numpy.minimum() returns a masked value. Is it possible to change this behaviour, such that the valid value is returned instead? x = np.random.randn(5).round(2) x[[2,4]] = np.nan print(x) print(np.minimum(x[-1], x[-2])) y = np.ma.masked_invalid(x) print(y) print(np.minimum(y[-1], y[-2])) &gt;&gt; [-1.21 2.02 nan -0.31 nan] &gt;&gt; nan &gt;&gt; [-1.21 2.02 -- -0.31 --] &gt;&gt; -- Instead, I would like the return value to be -0.31. In this simple example, I could use y.compressed() or something like that, but in my case, I have several dimensions, so that doesn't work. Currently, I use a very high fill_value, which works because there's a physical constraint on the data, but I would like to have a more general solution.
has comment: http://stackoverflow.com/comment/92045341
type: UnansweredQuestion

http://stackoverflow.com/comment/91917001
type: AnswerComment
comment on: http://stackoverflow.com/a/52487774
type: Comment
has text: @DanielJames I made a mistake with the function name, which I just corrected.
score: 0

http://stackoverflow.com/comment/92087972
type: QuestionComment
comment on: http://stackoverflow.com/q/52576218
has text: Could you please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
score: 0
type: Comment

http://stackoverflow.com/comment/92009303
type: Comment
type: QuestionComment
has text: @Marmeus .. would like to explore Fabric, i have a solution there which may be in interest?
score: 0
comment on: http://stackoverflow.com/q/52534012

http://stackoverflow.com/a/52487790
answers question: http://stackoverflow.com/q/52487712
score: 2
upvote count: 2
has body: Check to see whether you're going to be short in the last list chunk. If so, add exactly the needed quantity of elements, duplicated form the front of the list. def split_list(the_list, chunk_size): result_list = [] short = len(the_list) % chunk_size if short: # Add wrap-around elements from front of the_list the_list.extend(the_list[:chunk_size-short]) while the_list: result_list.append(the_list[:chunk_size]) the_list = the_list[chunk_size:] return result_list a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(split_list(a_list, 3)) Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52487712
type: Answer

http://stackoverflow.com/a/52467273
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52467160
answers question: http://stackoverflow.com/q/52467160
has body: Will this be something you are looking for? l1 =[2,5,8] l2 =[4,8,0] sums = [] # initialize the list of sums. minlen = min(len(l1), len(l2)) for i in range(minlen): sums.append(l1[i] + l2[i]) print(sums) [6, 13, 8]

http://stackoverflow.com/comment/91810592
type: Comment
comment on: http://stackoverflow.com/a/52432726
type: AnswerComment
has text: Thanks. Maybe I am missing something? Why is this functionality not native?
score: 0

http://stackoverflow.com/a/52521324
answers question: http://stackoverflow.com/q/52519823
accepted answer of: http://stackoverflow.com/q/52519823
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: Here is an example of how to do that: import threading import time ITERATIONS = 60 # this could be any function def afunc(t): # the 't' argument is just to clarify the output for i in range(2): print('in timer #' + str(t) + ': ' + str(i)) time.sleep(0.2) timers = [] for t in range(ITERATIONS): # create a timer for this iteration (note the interval will be from 1.0 to the number of iterations) ti = threading.Timer(1.0 + t, afunc, args=[t]) # save the timer in a list timers.append(ti) # start the timer ti.start() # wait for them all for ti in timers: ti.join() print( 'all finished, call any other method here')
score: 1

http://stackoverflow.com/comment/91837752
type: QuestionComment
comment on: http://stackoverflow.com/q/52447364
has text: @user190081 because it is considered a bad practice. How will you refer to these variables in code? You'll end up hackily using the `globals()` dict, but why? Just use your own `dict` object.
score: 0
type: Comment

http://stackoverflow.com/q/52549120
tagged with: python
tagged with: regex
upvote count: 3
has comment: http://stackoverflow.com/comment/92037336
accepted answer: http://stackoverflow.com/a/52549193
has comment: http://stackoverflow.com/comment/92039147
has comment: http://stackoverflow.com/comment/92037355
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/92037348
has body: In the code below: &gt;&gt;&gt; pattern = re.compile(r'^&lt;HTML&gt;') &gt;&gt;&gt; pattern.match("&lt;HTML&gt;") &lt;_sre.SRE_Match at 0x1043bc8b8&gt; &gt;&gt;&gt; pattern.match("⇢ ⇢ &lt;HTML&gt;", 2) # ⇢ stands for whitespace character. None When we are using ^ metacharacter and matching pattern then any whitespace character at the beginning as given below doesn't give a match even if the 'pos' argument is equal to 2, and the reason being given was that the metacharacter ^ couldn't be matched in such cases( &lt; is at position 2, and it cannot be matched with ^). &gt;&gt;&gt; pattern = re.compile(r'&lt;HTML&gt;$') &gt;&gt;&gt; pattern.match("&lt;HTML&gt;⇢", 0,6) # ⇢ stands for whitespace character. &lt;_sre.SRE_Match object at 0x1007033d8&gt; &gt;&gt;&gt; pattern.match("&lt;HTML&gt;⇢"[:6]) &lt;_sre.SRE_Match object at 0x100703370&gt; But, when we are using $ at the end of regular expression and giving the 'end' argument there is a match? Why the difference?
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52549193
favorite count: 0
has title: re.match pattern matching with ^,$

http://stackoverflow.com/q/52464273
accepted answer: http://stackoverflow.com/a/52464411
type: Question
score: 5
upvote count: 5
has body: I was installing pandas in pip using sudo pip install pandas and this huge error happened. Could not install packages due to an EnvironmentError: [('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/parser.pyc', '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/parser.pyc', "[Errno 1] Operation not permitted: '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/parser.pyc'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/relativedelta.py', '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/relativedelta.py', "[Errno 1] Operation not permitted: '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/relativedelta.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/zoneinfo/zoneinfo-2010g.tar.gz', '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/zoneinfo/zoneinfo-2010g.tar.gz', "[Errno 1] Operation not permitted: '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/zoneinfo/zoneinfo-2010g.tar.gz'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/zoneinfo/__init__.py', '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/zoneinfo/__init__.py', "[Errno 1] Operation not permitted: '/private/tmp/pip-uninstall-n5twe_/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/zoneinfo/__init__.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/zoneinfo/__init__.pyc', '/private/tmp/pip-uninstall-n5twe_/Syst…
answer count: 1
downvote count: 0
tagged with: macos
favorite count: 0
tagged with: terminal
has answer: http://stackoverflow.com/a/52464411
tagged with: python
type: AnsweredQuestion
has title: Pip - Could not install packages due to an EnvironmentError

http://stackoverflow.com/comment/91814662
score: 1
has text: You don't want to reindex... just select your data frame with all columns in the order you want.
comment on: http://stackoverflow.com/q/52435611
type: Comment
type: QuestionComment

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

http://stackoverflow.com/q/52492515
has title: Integral of a distribution returns nan value
has comment: http://stackoverflow.com/comment/91927198
accepted answer: http://stackoverflow.com/a/52493210
has comment: http://stackoverflow.com/comment/91940671
tagged with: python
linked to: http://stackoverflow.com/q/11973800
linked to: http://stackoverflow.com/q/44915116
has body: I have a distribution whose point on both axies are: x = [21.381625583382622 ,21.201155495759807 ,21.008654068962123 ,20.90037201638843 ,20.888340677213577 ,20.701854920003328 ,20.62365121536677, 20.467243806093656 ,20.395055771044525 ,20.196538674659422 ,20.094272291673157,20.040131265386314 ,19.949896221574896 ,19.727316446840085,19.619034394266393 ,19.57090903756697 ,19.33028225406988 ,19.167859175209337 ,19.119733818509914 ,18.975357748411653 ,18.86707569583797 ,18.69863694739 ,18.620433242753442 ,18.578323555641447 ,18.27754007627008 ,18.235430389158086 ,18.169258023696383 ,17.99480360566099 ,17.86847454432501 ,17.76019249175132 ,17.639879100002773 ,17.519565708254223 ,17.278938924757128 ,17.309017272694263 ,17.122531515484013 ,16.990186784560613 ,16.875889062399487 ,16.749560001063514 ,16.64729361807725 ,16.50291754797899 ,16.394635495405296 ,16.26830643406932 ,16.11189902479621 ,16.03369532015965 ,15.91939759799853 ,15.76299018872542 ,15.648692466564295 ,15.540410413990605 ,15.408065683067202 ,15.221579925856952 ,15.071188186171264 ,15.071188186171264 ,14.87267108978616 ,14.75837336762504 ,14.674153993401056 ,14.553840601652508 ,14.409464531554251 ,14.253057122281138 ,14.19891609599429 ,14.036493017133752 ,13.843991590336074 ,13.789850564049226 ,13.669537172300679 ,13.513129763027564 ,13.392816371279016 ,13.266487309943043 ,13.140158248607065 ,12.869453117172833 ,12.82734343006084 ,12.64085767285059 ,12.496481602752333 ,12.370152541416356 ,12.261870488842664 ,12.093431740394694 ,12.003196696583283 ,11.94304000070901 ,11.75655424349876 ,11.600146834225647 ,11.497880451239382 ,11.407645407427971 ,11.19709697186801 ,11.088814919294316 ,10.992564205895478 ,10.830141127034938 ,10.7338904136361 ,10.595530013125268 ,10.469200951789292 ,10.33685622086589 ,10.180448811592775 ,10.07818242860651 ,9.957869036857963 ,9.807477297172277 ,9.687163905423729 ,9.560834844087754 ,9.452552791514059 ,9.29012971265352 ,9.1758319904924 ,9.073565607506133 ,8.953252215757583 ,8.814891…
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/91926965
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91926033
score: 0
has answer: http://stackoverflow.com/a/52493210
has comment: http://stackoverflow.com/comment/91926734
answer count: 1

http://stackoverflow.com/q/52567524
tagged with: python
has answer: http://stackoverflow.com/a/52567607
linked to: http://stackoverflow.com/q/3969713
downvote count: 1
type: AnsweredQuestion
has body: I download Stack Overflow posts dump file to do my work.When I unpacked .7z file , the .xml dump file exceed 65G. I want to parse the .xml file, because there lots of contents I need not. And then I want to store the usage contents to Mysql database.(Java or Python are both ok) But the file is too large to handle it for me, it can overflow my memory(8G). What can I do to solve the tricky problem.
has comment: http://stackoverflow.com/comment/92072179
duplicate of: http://stackoverflow.com/q/3969713
tagged with: java
tagged with: mysql
type: Question
tagged with: xml-parsing
upvote count: 0
accepted answer: http://stackoverflow.com/a/52567607
favorite count: 0
tagged with: dump
answer count: 1
score: -1
has title: How to deal with HUGE dump xml file(about 70g) and save it to Mysql using Java or Python

http://stackoverflow.com/comment/91853044
score: 0
comment on: http://stackoverflow.com/q/52455000
type: Comment
has text: `The Google Web Search API is no longer available. Please migrate to the Google Custom Search API (https://developers.google.com/custom-search/)', 'responseStatus': 403}`
type: QuestionComment

http://stackoverflow.com/comment/92178182
comment on: http://stackoverflow.com/q/52575054
type: QuestionComment
type: Comment
has text: could you share code from `"/home/tony/Workspace/cocoonr/utils/views/common.py" in get_queryset` and `"/home/tony/Workspace/cocoonr/booking/views/manager.py" in get_queryset`?
score: 0

http://stackoverflow.com/q/52489260
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52489475
accepted answer: http://stackoverflow.com/a/52489475
has body: So I have a for loop for i in range(0, arr[0]): and I want the stop parameter of the range() function to be variable based on the value of the first element in an array. When I do this, however, even though the value of arr[0] is an integer, python comes back and gives me an error saying TypeError: 'list' object cannot be interpreted as an integer. How can I either convert this element in the list to an integer or find another way to use its value as a parameter? I am also using this same value to increment and decrement variables within this loop. Thanks! Full Code: def diagonalDifference(arr): stopInt = arr[0] primary = 0 secondary = 0 pArrIndex = 1 sArrIndex = -1 for i in range(0, stopInt): primary += arr[pArrIndex] pArrIndex += arr[0] for i in range(0, stopInt): secondary += arr[sArrIndex] sArrIndex -= arr[0] return abs(primary - secondary) This is for a challenge here The purpose of the diagonalDifference function can be found in that link.
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/91919682
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91919691
has comment: http://stackoverflow.com/comment/91919701
type: Question
has comment: http://stackoverflow.com/comment/91919635
upvote count: 1
score: -2
has comment: http://stackoverflow.com/comment/91919661
has comment: http://stackoverflow.com/comment/91919793
has title: How can I use an element in a list as a parameter in range()?
has comment: http://stackoverflow.com/comment/91919609
answer count: 1
has comment: http://stackoverflow.com/comment/91919761
favorite count: 0
tagged with: element
downvote count: 3

http://stackoverflow.com/comment/92276725
type: QuestionComment
score: 0
has text: @d_kennetz You might have the best solution, although it seems like even you are aware that this is not ideal. But it does solve all of what I want, albeit not easily and still allows for potential mistakes. This seems like a problem that *many* people must run across: using interpreted languages in larger scoped projects and ensuring your local computer environment does not "influence" how that project runs. If everything I did only required Python, then virtualenv would solve it. Alas, even Python itself requires more than just pure Python, due to Cython, etc.
type: Comment
comment on: http://stackoverflow.com/q/52485828

http://stackoverflow.com/comment/92102640
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52583747
has text: When you have multi-index'es. For above example, index on price table is just date. What if we have multi index {date, exchange}? Two level indexes now.
type: Comment

http://stackoverflow.com/comment/91894327
type: Comment
comment on: http://stackoverflow.com/a/52470926
score: 1
has text: Sorry, earlier I up-voted too soon. There is no point testing with `r4DQe.jpg`. We need a link of the original 16-bit TIF file, since JPG is 24-bit (8-bits per colour channel) it gives misleading results.
type: AnswerComment

http://stackoverflow.com/q/52450659
favorite count: 0
has title: pyodbc to sqlalchemy connection
linked to: http://stackoverflow.com/q/48818884
has answer: http://stackoverflow.com/a/52451469
tagged with: python
tagged with: pyodbc
has body: I am trying to switch a pyodbc connection to sqlalchemy. The working pyodbc connection is: import pyodbc con = 'DRIVER={ODBC Driver 11 for SQL Server};SERVER=server.com\pro;DATABASE=DBase;Trusted_Connection=yes' cnxn = pyodbc.connect(con) cursor = cnxn.cursor() query = "Select * from table" cursor.execute(query) I tried: from sqlalchemy import create_engine dns = 'mssql+pyodbc://server.com\pro/DBase?driver=SQL+Server' engine = create_engine(dns) engine.execute('Select * from table').fetchall() Based on: http://docs.sqlalchemy.org/en/latest/core/engines.html and: pandas.read_sql() is MUCH slower when using SQLAlchemy than pyodbc (trying to setup a connection with Trusted_Connection = Yes) But I receive the message: OperationalError: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]No existe el servidor SQL Server o se ha denegado el acceso al mismo. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)') (Background on this error at: http://sqlalche.me/e/e3q8) (Sorry for the spanish but it says that the SQL Server doesn't exist) I am almost sure that it has to do with me not understanding the sintax for the engine connection. Could someone please explain me in detail how to convert the conection from pyodbc to sqlalchemy? Thanks in advance! PD: I am trying to implement sqlalchemy to use later in my code pandas.DataFrame.to_sql(engine)
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/52451469
upvote count: 3
linked to: http://stackoverflow.com/q/24085352
tagged with: sqlalchemy
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: pandas-to-sql

http://stackoverflow.com/q/52478939
score: 1
has answer: http://stackoverflow.com/a/52479353
downvote count: 1
type: Question
tagged with: compilation
has comment: http://stackoverflow.com/comment/91899019
tagged with: python-2.7
answer count: 1
has title: How to compile python program ( convert to pyc) in python3
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: There are two ways to generate pyc in python2: 1. import py_compile py_compile.compile("file.py") 2. python -m compileall ./ How to do it python3? I tried both of the above approaches, both are not generating .pyc file in python3. Please help.
has comment: http://stackoverflow.com/comment/91898894
tagged with: python

http://stackoverflow.com/q/52575319
upvote count: 3
type: Question
has title: 'Group' object has no attribute 'user_set'
has body: Since the default django admin group form does not have field for selecting users in a group. I Wrote down some codes which i got online to add the selected users field.Everything is working just fine. Until i tried saving the group form i created, I get this error 'Group' object has no attribute 'user_set' class GroupAdminForm(forms.ModelForm): class Meta: model=group exclude=[] users=forms.ModelMultipleChoiceField(queryset=User,objects.all(),widget=FilteredSelectMultiple('users',False),required=False) def __int__(self,*args,**kwargs): super(GroupAdminForm,self).__int__(*args,**kwargs) if self.instance.pk: self.fields['users'].initial=self.instance.user_set.all() def save_m2m(self): self.instance.user_set.set(self.cleaned_data['users']) def save(self,*args,*kwargs): instance= super(GroupAdminForm,self).save() self.save_m2m() return instance I am getting this error 'Group' object has no attribute 'user_set' . I donot know on how to go about resolving this problem . Please help . I am navies in django. Help Hlep please
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/60605953
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/6097210
score: 3

http://stackoverflow.com/comment/91876806
type: Comment
has text: m using like this
comment on: http://stackoverflow.com/a/52467463
score: 0
type: AnswerComment

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/52467563
type: Tag

http://stackoverflow.com/comment/91810716
comment on: http://stackoverflow.com/a/52433412
score: 0
type: AnswerComment
has text: Double quotes would also be valid, but you used some fancy quote characters that wouldn't be recognised :)
type: Comment

http://stackoverflow.com/comment/91943424
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52501191
has text: Ah ok, thanks for clarifying. Also changing the sum to not be a list actually slowed it down. That is the sum builtin.sum time. With list: 3182 , without list: 11451 ms
score: 0

http://stackoverflow.com/a/52508993
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52508876
has comment: http://stackoverflow.com/comment/91958281
has body: This is a good use for divmod(), which does integer division and gives you both the quotient and the remainder: user_days = 762 DAYS_IN_YEAR = 365 DAYS_IN_MONTH = 30 # Calculate number of years and remainder years, rem = divmod(user_days, DAYS_IN_YEAR) # Calculate number of months and remainder months, days = divmod(rem, DAYS_IN_MONTH) # Display results print(user_days, "days are equivalent to: ") print("Years: ", years) print("Months: ", months) print("Days: ", days) # output: # 762 days are equivalent to: # Years: 2 # Months: 1 # Days: 2

http://stackoverflow.com/q/52473281
answer count: 3
possible better answer: http://stackoverflow.com/a/52473322
favorite count: 0
has answer: http://stackoverflow.com/a/52473322
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91891457
has answer: http://stackoverflow.com/a/52473431
has comment: http://stackoverflow.com/comment/91888329
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52473334
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91888271
linked to: http://stackoverflow.com/q/21892989
has body: import sys print (sys.version) def add_pair((a,b),(c,d)): return a+c, b+d print (add_pair((10,20),(30,40))) This works perfectly in python2.x but not on python3.x
has comment: http://stackoverflow.com/comment/91888270
type: Question
duplicate of: http://stackoverflow.com/q/21892989
downvote count: 5
score: -4
has answer: http://stackoverflow.com/a/52473334
has title: This works perfectly in python2.x but not on python3.x
tagged with: python-2.7

http://stackoverflow.com/comment/92107274
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52570949
has text: If your reference table is not that big, better to `collect` it and then match the names.
type: Comment

http://stackoverflow.com/a/52508752
answers question: http://stackoverflow.com/q/52508696
score: 6
type: AcceptedAnswer
upvote count: 6
has body: Dictionaries can't have duplicate keys, so in case of repeated keys it only keeps the last value, so check values (one-liner is your friend): print(('There are duplicates' if len(set(dict.values()))!=len(values) else 'No duplicates'))
type: Answer
accepted answer of: http://stackoverflow.com/q/52508696
downvote count: 0

http://stackoverflow.com/q/52438941
has title: Create a label to a str series depending on what keyword is contained in the str
has comment: http://stackoverflow.com/comment/91822164
has comment: http://stackoverflow.com/comment/91820777
downvote count: 2
accepted answer: http://stackoverflow.com/a/52439660
has comment: http://stackoverflow.com/comment/91820950
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91822011
has comment: http://stackoverflow.com/comment/91821083
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91821875
score: -1
type: Question
has body: I'm trying to create a label to a str series depending on what keyword is contained in the str. I've been puzzling over this for a while and not sure how to approach it. Tried this: mirantis['cat_label'] = np.where(pd.Series(mirantis.Mirantis_Address).str.contains('openstack|kubernetes'),'openstack', 'kubernetes') It limits me to two keywords but essentially I need unlimited keywords. Any thoughts? Example data: https://www.mirantis.com/ https://www.mirantis.com/blog/how-to-increase-the-probability-of-a-vnf-working-with-your-cloud-qa/ https://www.mirantis.com/careers/ https://www.mirantis.com/company/press-center/in-the-media/ https://www.mirantis.com/software/mcp/sdn/ https://training.mirantis.com/openstack-courses-exams/ https://www.mirantis.com/services/transfer/ https://training.mirantis.com/kubernetes-docker-courses-exams/ https://www.mirantis.com/solutions/big-data-analytics/ https://www.mirantis.com/cloud-case-studies/ https://www.mirantis.com/services/transfer-services/ https://www.mirantis.com/cloud-videos/ https://www.mirantis.com/company/locations/ https://www.mirantis.com/blog/admit-it-vnf-certification-is-marketing-bs/ https://info.mirantis.com/mirantis-application-platform-beta https://www.mirantis.com/support/enterprise-support-services/ https://www.mirantis.com/company/leadership/board-of-directors/ https://training.mirantis.com/certification/ https://www.mirantis.com/get-started/ https://www.mirantis.com/software/mcp/ https://docs.mirantis.com/ https://info.mirantis.com/live-demo https://www.mirantis.com/solutions/network-functions-virtualization-nfv/ https://www.mirantis.com/services/build/ https://training.mirantis.com/ https://www.mirantis.com/software/ceph/ https://www.mirantis.com/solutions/container-technologies/ https://info.mirantis.com/eBook-MCP-Deployment-Guide_Landing-Page https://www.mirantis.com/company/about/ https://www.mirantis.com/software/kubernetes/ https://www.mirantis.com/blog/how-to-deploy-spinnaker-on-kubernetes-a-quick-and-di…
has comment: http://stackoverflow.com/comment/91820795
has comment: http://stackoverflow.com/comment/91821129
answer count: 1
has comment: http://stackoverflow.com/comment/91822207
has answer: http://stackoverflow.com/a/52439660
favorite count: 0
has comment: http://stackoverflow.com/comment/91821840
tagged with: pandas

http://stackoverflow.com/comment/91911009
has text: Libraries shouldn't be messing with the root logger; that's only for use by the top-level script. Your package should have its own logger, created with `logging.getLogger(__name__)`, and any configuration you do should only be applied to that.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52484567
type: Comment

http://stackoverflow.com/a/52562934
has body: I think the reason your code hangs is because all the worker tasks end up waiting for something to appear on the input queue with the item = Qin.get() line at the same time because get() "blocks" waiting for something to be placed in the queue. One way to avoid that is to use the non-blocking get_nowait() method instead. Doing so requires code to handle any Empty exception it may raise, but it avoids having any further execution in that process effectively halted at that point. Also for things to work, you need to create and use a multiprocessing.Manager which creates a server process which holds Python objects and allows other processes to manipulate them via proxies. See the "Server process" part of the Sharing state between processes section of the documentation. Also, when using multiprocessing on Windows, it's very important to make sure the main process' code is executed conditionally by putting it inside an if __name__ == '__main__': statement. This is because of how the module has been implemented on that platform—otherwise that code will be executed again each time another concurrent task is started (which involves it being imported by them). Below is your code with the modification needed so it uses a multiprocessing.Manager. Note I changed the name of your manager() function to avoid confusion with the multiprocessing.Manager which it uses to create the shared objects. import multiprocessing from queue import Empty as QueueEmpty import os import time END_MARKER = 'end' def worker(id, Qin, Qout, event): while True: try: item = Qin.get_nowait() # Non-blocking. except QueueEmpty: if event.is_set(): # Last item seen? break continue # Keep polling. if item == END_MARKER: # Last item? event.set() break # Quit. Qout.put('{} via worker {}'.format(item, id)) time.sleep(.25) def pool_manager(): processes = os.cpu_count() pool = multiprocessing.Pool(processes=processes) manager = multiprocessing.Manager() Qin, Qout, event = manager.Queue(), manager.Queue(), manager.…
type: Answer
answers question: http://stackoverflow.com/q/52556941
score: 0

http://stackoverflow.com/q/52492085
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91927388
favorite count: 0
has comment: http://stackoverflow.com/comment/91924935
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91927725
has comment: http://stackoverflow.com/comment/91924777
has comment: http://stackoverflow.com/comment/91924796
has comment: http://stackoverflow.com/comment/91928101
downvote count: 2
has comment: http://stackoverflow.com/comment/91924743
has title: Python tabula- cannot import name wrapper
type: Question
score: -2
has body: I am facing an issue in importing the wrapper from tabula Line throwing error: from tabula import wrapper I am using Python 3.4 Error - "cannot import name wrapper"
has comment: http://stackoverflow.com/comment/91927114
has answer: http://stackoverflow.com/a/52493633

http://stackoverflow.com/comment/91819802
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52432603
has text: Where do you account for angle being in all three here?
type: AnswerComment

http://stackoverflow.com/comment/92025300
type: Comment
comment on: http://stackoverflow.com/q/52513297
score: 0
has text: Is pycharm auto detecting the type returned by that function/method?
type: QuestionComment

http://stackoverflow.com/comment/92063581
type: QuestionComment
comment on: http://stackoverflow.com/q/52562511
has text: See how to create a [mcve].
score: 0
type: Comment

http://stackoverflow.com/q/52465740
score: 1
type: Question
has body: I am trying to handle the django static and media content. This is my code in settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') In urls.py urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am uploading files and videos to my site, everything is working fine even static and media content is being displayed. My actual doubt is- I am actually running in development environment. In production for collecting the static content generally python manage.py collectstatic is used and then it is handled. But in development according to docs, app called django.contrib.staticfiles is used serve static files. But what about media files, how are they served actually ?? When I upload a image it is getting stored to project_name/media/app_name insted of project_name/app_name/media/app_name as static files are being accessed from path similar to latter, why are media files being stored in different manner. Finally: How the media files got served in development ? How to serve media files in production ?
has answer: http://stackoverflow.com/a/52466019
accepted answer: http://stackoverflow.com/a/52466019
linked to: http://stackoverflow.com/q/48012729
upvote count: 1
answer count: 1
favorite count: 0
has title: Handling media django
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/52499655
score: 1
accepted answer of: http://stackoverflow.com/q/52497450
answers question: http://stackoverflow.com/q/52497450
upvote count: 1
type: AcceptedAnswer
has body: If you look at the documentation of tf.SparseTensor, indices is expected to be a 2-dimensional tensor with dimensions (N, ndims), where N is the number of non-zero values in the sparse tensor and ndims is its number of dimensions. For a sparse matrix (two dimensions), each row will contain the row and the column of the corresponding value in values. In the snippet, coo_matrix.rows is an array of row indices of the sparse matrix, and coo_matrix.cols is an array of column indices. np.array([coo_matrix.rows, coo_matrix.cols]) will be an array with two rows and N columns, which is the opposite order of what a sparse tensor expects, so transposing it with .T you get the (N, 2) indices tensor. Not that you are not transposing the sparse matrix, the indices still remain the same, you are just giving them to tf.SparseTensorValue in the required order. You could get the same result by doing, for example, np.stack([coo_matrix.rows, coo_matrix.cols], axis=1).
downvote count: 0
type: Answer

http://stackoverflow.com/a/52551944
score: 5
has body: The parameter exclude of the describe() method requires a list-like of dtypes. Please see the documentation: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html So, in your case, the correct call would be recent_grads.describe(exclude=['object'])
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52474886
answers question: http://stackoverflow.com/q/52474886
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52462747
accepted answer: http://stackoverflow.com/a/52527944
has comment: http://stackoverflow.com/comment/91995367
has comment: http://stackoverflow.com/comment/91918734
favorite count: 0
has comment: http://stackoverflow.com/comment/91995521
upvote count: 1
tagged with: loops
downvote count: 1
has title: Python: Moving on to the next letter on For Loop
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91994653
type: Question
linked to: http://stackoverflow.com/q/8848294
tagged with: for-loop
answer count: 1
tagged with: iteration
has answer: http://stackoverflow.com/a/52527944
score: 0
has comment: http://stackoverflow.com/comment/91995524
tagged with: element
tagged with: python
has body: How can I move on to the next letter in a for loop before 1st iteration finishes? s = 'mmmmbobob' for letter in s: if letter is 'b': s = s + 1 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;RIGHT HERE&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; if letter is 'o': s = s + 1 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;THEN HERE&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; if letter is "b": counter_bob += 1 else: break else: break else: continue print('Number of times bob occurs is: %d' % (bob_name_counter))

http://stackoverflow.com/a/52551620
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52548467
accepted answer of: http://stackoverflow.com/q/52548467
type: Answer
downvote count: 0
has body: The problem is your are taking the mean and not using the quarter resampling. First create a mock series: periods = 10000 my_index = pd.date_range('2016-07-01', periods=periods, freq='D') data = np.random.randint(100,1000,periods) orig_ts = pd.Series(data=data, index=my_index, name='daily rates') Resample it so that it gets the data from last business day of the month. Use resample('Q') for just the last day. ts=orig_ts.resample('BQ').backfill() print(ts.head()) 2016-09-30 173.0 2016-12-30 243.0 2017-03-31 209.0 2017-06-30 124.0 2017-09-29 817.0 Freq: BQ-DEC, Name: daily rates, dtype: float64 Check the accuracy: print(orig_ts.get_value('2016-09-30')) Output: 173
score: 1
has comment: http://stackoverflow.com/comment/92062043

http://stackoverflow.com/q/52584053
has comment: http://stackoverflow.com/comment/92103347
possible better answer: http://stackoverflow.com/a/52584363
accepted answer: http://stackoverflow.com/a/52584445
has answer: http://stackoverflow.com/a/52584363
has title: Pandas: determine where 2 time series are intersecting and in which direction
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92103584
has comment: http://stackoverflow.com/comment/92103178
answer count: 2
has answer: http://stackoverflow.com/a/52584445
linked to: http://stackoverflow.com/q/33707150
score: 0
tagged with: pandas
tagged with: python
has body: This is a follow up to this question: determine the coordinates where two pandas time series cross, and how many times the time series cross I have 2 series in my Pandas dataframe, and would like to know where they intersect. A B 0 1 0.5 1 2 3.0 2 3 1.0 3 4 1.0 4 5 6.0 With this code, we can create a third column that will contain True everytime the two series intersect: df['difference'] = df.A - df.B df['cross'] = np.sign(df.difference.shift(1))!=np.sign(df.difference) np.sum(df.cross)-1 Now, instead of a simple True or False, I would to know in which direction the intersection took place. For example: from 1 to 2, it intersected upwards, from 2 to 3 downwards, from 3 to 4 no intersections, from 4 to 5 upwards. A B Cross_direction 0 1 0.5 None 1 2 3.0 Upwards 2 3 1.0 Downwards 3 4 1.0 None 4 5 6.0 Upwards In pseudo-code, it should be like this: cross_directions = [none, none, ... * series size] for item in df['difference']: if item &gt; 0 and next_item &lt; 0: cross_directions.append("up") elif item &lt; 0 and next_item &gt; 0: cross_directions.append("down") The problem is that next_item is unavailable with this syntax (we obtain that in the original syntax using .shift(1)) and that it takes a lot of code. Should I look into implementing the code above using something that can group the loop by 2 items at a time? Or is there a simpler and more elegant solution like the one from the previous question?

http://stackoverflow.com/q/52531853
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/52532276
answer count: 4
has title: Build regex that separates string of file names with 2 periods
has answer: http://stackoverflow.com/a/52532276
upvote count: 3
has answer: http://stackoverflow.com/a/52534180
has answer: http://stackoverflow.com/a/52532151
type: Question
type: AnsweredQuestion
score: 3
has body: I need to build a regex that, given a string of file names which may contain spaces and between 1 and 2 dots in the file names, returns a list of the file names. For example: 00.37.jpg 00.38.jpg Convert To 3 Channels.xml Deploy All Masks.ini should become: [00.37.jpg, 00.38.jpg, Convert To 3 Channels.xml, Deploy All Masks.ini] I currently have a regex that does this, but only if the file name has one period. Regex = \ ?(.+?\.\w+)
accepted answer: http://stackoverflow.com/a/52532151
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52532173

http://stackoverflow.com/comment/91811899
score: 0
has text: Thanks. Which part of your code is telling the .csv to escape all double quotation marks?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52434034

http://stackoverflow.com/comment/91872075
score: 0
has text: Always use up all of the parameters in the `__init__` function. That's usually by assigning it as `self.something = something`
type: Comment
comment on: http://stackoverflow.com/q/52465131
type: QuestionComment

http://stackoverflow.com/a/52537137
upvote count: 17
has comment: http://stackoverflow.com/comment/92015595
has comment: http://stackoverflow.com/comment/112107751
has comment: http://stackoverflow.com/comment/92432707
type: Answer
has comment: http://stackoverflow.com/comment/92109027
answers question: http://stackoverflow.com/q/52474999
has comment: http://stackoverflow.com/comment/92109185
has body: This error message... {'status': 500, 'value': '{"value":{"error":"unknown error","message":"connection refused","stacktrace":"stack backtra...s::imp::thread::{{impl}}::new::thread_start\n at /checkout/src/libstd/sys/unix/thread.rs:84"}}'} ...implies that the GeckoDriver was unable to initiate/spawn a new WebBrowsing Session i.e. Firefox Browser session. In a comment within the discussion DELETE '/session/{session id}' no longer working @andreastt mentions that: geckodriver is implicitly ending the (previous) session when the last window closes. If driver.quit() is called as the subsequent command it will fail because the session has already been implicitly deleted. In these cases GeckoDriver should detect that the session has been closed implicitly after driver.close() or ignore the response from driver.quit() in case the session has already been closed. In such cases the following trace logs are generated: 1505753594121 webdriver::server DEBUG Last window was closed, deleting session 1505753594121 webdriver::server DEBUG Deleting session 1505753594121 geckodriver::marionette DEBUG Stopping browser process 1505753594364 webdriver::server DEBUG &lt;- 200 OK {"value": []} 1505753594523 webdriver::server DEBUG -&gt; DELETE /session/a8312282-af00-4931-94d4-0d401abf01c9 1505753594524 webdriver::server DEBUG &lt;- 500 Internal Server Error {"value":{"error":"session not created","message":"Tried to run command without establishing a connection","stacktrace":"stack backtrace:\n 0: 0x4f388c - backtrace::backtrace::trace::h736111741fa0878e\n 1: 0x4f38c2 - backtrace::capture::Backtrace::new::h63b8a5c0787510c9\n 2: 0x442c61 - webdriver::error::WebDriverError::new::hc4fe6a1ced4e57dd\n 3: 0x42a926 - &lt;webdriver::server::Dispatcher&lt;T, U&gt;&gt;::run::hba9181b5aacf8f04\n 4: 0x402c59 - std::sys_common::backtrace::__rust_begin_short_backtrace::h19de262639927233\n 5: 0x40c065 - std::panicking::try::do_call::h6c1659fc4d01af51\n 6: 0x5e38ec - panic_unwind::__rust_maybe_catch_pani…
has comment: http://stackoverflow.com/comment/92015123
has comment: http://stackoverflow.com/comment/92014277
accepted answer of: http://stackoverflow.com/q/52474999
has comment: http://stackoverflow.com/comment/92014560
score: 15
downvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/52588057
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: elixir-iex
upvote count: 1
favorite count: 0
tagged with: filter
tagged with: pandas
answer count: 1
has title: Filtering long list of data from IEX
has answer: http://stackoverflow.com/a/52588205
accepted answer: http://stackoverflow.com/a/52588205
has body: I would like to filter my data so that I only get the symbol, close and sector. I tried using the code below but I get an error that 'list is not callable' . Also, do note that iexfinance uses filter_, as filter is a reserved word in Python print(losers(filter_=['symbol','close'])) Any help will be appreciated. Thanks guys!
tagged with: python

http://stackoverflow.com/comment/91960176
has text: The key is not the index, you need to find the unique word from the `script ` element you need. Just iterate all the script elements and store the one you need with the key word. Happy that my suggestion helped you!
type: AnswerComment
comment on: http://stackoverflow.com/a/52471798
score: 0
type: Comment

http://stackoverflow.com/q/52510969
score: 2
has comment: http://stackoverflow.com/comment/91962837
downvote count: 0
has comment: http://stackoverflow.com/comment/91964032
has body: Weird coding outcome which isn't making much sense. I am trying to capture from a raspberry pi camera using the V4L2 driver as I need to use cv2 for image processing. I am using python to write the code. The weirdness revolves around capturing images using cv2. when I type in the following commands import cv2 from matplotlib import pyplot camera = cv2.VideoCapture(0) grab,frame = camera.read() pyplot.imshow(frame) I am able to grab a frame and display it using matplotlib. When I grab a second frame grab,frame2 = camera.read() pyplot.imshow(frame2) The code will grab a second frame and display it perfectly fine. However when I try to use an existing variable like frame or frame2 the camera will not grab a new frame and just print the prior frame. I tried to clear the variable by typing frame = [] grab,frame = camera.read() pyplot.imshow(frame) but this didn't fix the issue, still printing the prior frame.
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91965539
has comment: http://stackoverflow.com/comment/91965081
has answer: http://stackoverflow.com/a/52513169
accepted answer: http://stackoverflow.com/a/52513169
type: Question
upvote count: 2
answer count: 1
has title: Weird outcomes using V4L2, python, on raspberry pi 3
favorite count: 0
has comment: http://stackoverflow.com/comment/91965880
tagged with: v4l2
tagged with: python

http://stackoverflow.com/comment/91848017
has text: Is it an image display thing? If the display scales down the binary image, it shows only a fraction of the pixels, likely not showing most of the edge pixels. Otherwise, it could be that upscaling the image 4x causes edges to be smoother, and therefore needing a lower threshold to detect.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52452155
score: 0

http://stackoverflow.com/a/52517343
type: Answer
answers question: http://stackoverflow.com/q/52516949
score: 1
upvote count: 1
has body: Using the slopes of two lines, you can just get the arc tangents to find their respective angles with respect to origin. Then, get the positive difference of two angles. All done! import math from math import pi as PI l1 = [(0,0), (1,1)] l2 = [(0.5, 1), (0.5, 2)] m1 = (l1[1][1]-l1[0][1])/(l1[1][0]-l1[0][0]) m2 = (l2[1][1]-l2[0][1])/(l2[1][0]-l2[0][0]) angle_rad = abs(math.atan(m1) - math.atan(m2)) angle_deg = angle_rad*180/PI There, with both radian and degree values.
downvote count: 0

http://stackoverflow.com/a/52545075
answers question: http://stackoverflow.com/q/52544400
has body: Transpose your dataframe. df=df.T done
score: 0
type: Answer

http://stackoverflow.com/a/52452185
has body: Try the following, it will do your job: from lxml import html import requests import xlsxwriter import datetime now = datetime.datetime.today().strftime('%Y-%m-%d') page = requests.get('http://econpy.pythonanywhere.com/ex/001.html') tree = html.fromstring(page.content) #This will create a list of buyers buyers = tree.xpath('//div[@title="buyer-name"]/text()') #This will create a list of prices prices = tree.xpath('//span[@class="item-price"]/text()') print( 'Buyers: ', buyers) print( 'Prices: ', prices) #creating excel sheet workbook = xlsxwriter.Workbook('sales' + str(now) + '.xlsx') worksheet = workbook.add_worksheet() # Start from the first cell. Rows and columns are zero indexed. row = 0 col = 0 #write data to excel for index, buyer in enumerate(buyers): worksheet.write(row, col, buyer) worksheet.write(row, col + 1, prices[index]) row += 1 workbook.close() Explanation Right now your expenses variable is a touple with two list. It's structure is ( ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes'], ['$29.95', '$8.37', '$15.26'] ) And for loop doesn't works like the way you'r using it on that data. It's basic syntax is: for item in collection: print(item) but you are using it like: for item, cost in (expenses): print(item, cost) You will not get item and cost separately when you are running the loop this way. You will get only one single element from your expenses touple at a time not multiple. Basically your syntax is wrong. So now if you run it like for single_item in (expenses): print(single_item) The the output will be: ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes'] # output for first iteration ['$29.95', '$8.37', '$15.26'] # output for second iteration You see we are not getting item and cost together. At first we are getting first list which is your item and at second iteration we are getting the second list which is cost. After examining buyers and prices variable I find that they excellently has same number of items and one list's corresponding item to oth…
answers question: http://stackoverflow.com/q/52451128
score: 0
has comment: http://stackoverflow.com/comment/91852442
type: Answer
has comment: http://stackoverflow.com/comment/91849989
has comment: http://stackoverflow.com/comment/91860464

http://stackoverflow.com/q/52526437
has answer: http://stackoverflow.com/a/76477335
has answer: http://stackoverflow.com/a/60149734
type: Question
tagged with: numpy
score: 4
tagged with: pandas
tagged with: datetime
upvote count: 4
answer count: 4
favorite count: 0
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52526492
has body: My series: dates = pd.date_range('2018-01-03', '2018-09-13') s = pd.Series(range(len(dates)), index=dates) I want to resample to months but starting from first date of index and not from first day of month. If I resample to "MS", first date is 2018-01-01, not 2018-01-03. Of course it's "month start" so that's expected. But how can I resample monthly without samples being picked from start of month, but rather from the same month day so resulting index is ["2018-01-03", "2018-02-03", etc.] (month starting from first datetime in the index)? Only way I found is create leading dates, do a negative shift, then use loffset parameter (because neither shift nor loffset respect alignment of the data to index). But this I'd like to avoid.
tagged with: python
has title: How to resample relative to first date?
has answer: http://stackoverflow.com/a/77244610

http://stackoverflow.com/a/52535855
accepted answer of: http://stackoverflow.com/q/52535828
has comment: http://stackoverflow.com/comment/92011158
has comment: http://stackoverflow.com/comment/92011114
has body: Change datetime.strptime(start_time, FMT) + datetime.timedelta( minutes = total_running_time) to datetime.strptime(start_time, FMT) + timedelta( minutes = total_running_time)
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52535828
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52579960
has body: Since you are open to NumPy, you may wish to consider Pandas, which uses NumPy internally: import pandas as pd a = pd.Series([1, 2, 2, 3]) b = pd.Series(['a', 'd', 'f', 'c']) flags = ~a.duplicated(keep=False) idx = flags[flags].index a = a[idx].values b = b[idx].values Result: print(a, b, sep='\n') array([1, 3], dtype=int64) array(['a', 'c'], dtype=object)
downvote count: 1
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52579935
upvote count: 3

http://stackoverflow.com/comment/92074717
score: 0
type: AnswerComment
type: Comment
has text: Hi John, I guess that would work before I saved my dataframe, but my original data format is already changed and I'm trying to convert that back to dictionaries. Thanks for your solution, I'll use in the future.
comment on: http://stackoverflow.com/a/52566256

http://stackoverflow.com/comment/91874879
has text: Perhaps tell it to attempt to parse all the columns as dates. It will only convert a column if every single value in the column can be parsed as a date.
type: Comment
comment on: http://stackoverflow.com/a/52466067
score: 0
type: AnswerComment

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

http://stackoverflow.com/a/52555132
type: Answer
score: 3
downvote count: 0
has body: You need to wrap up your code in a package in order to use relative imports. Set a setup script and use the pip -e install flag to install it as a development module. This is a very good in-depth explanation of the problem you are facing.
upvote count: 3
answers question: http://stackoverflow.com/q/52554853
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52554853

http://stackoverflow.com/comment/91951654
has text: I think what you're asking is "since `a += expr` is more-or-less equivalent to `a = a + expr`, do I need to worry about the precedence of addition compared to the precedence of the other operators in the expression?" I think the existing answer on your previous question covers that: the addition and the assignment always happen last.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52505489
score: 0

http://stackoverflow.com/q/52464947
type: Question
duplicate of: http://stackoverflow.com/q/26015489
tagged with: dataframe
tagged with: sorting
upvote count: 11
has title: How to get column name for second largest row value in pandas DataFrame
has answer: http://stackoverflow.com/a/52468939
tagged with: numpy
answer count: 2
tagged with: pandas
favorite count: 0
linked to: http://stackoverflow.com/q/26015489
has body: I have a pretty simple question - I think - but it seems I can't wrap my head around this one. I am a beginner with Python and Pandas. I searched the forum but couldn't get a (recent) answer that fits my need. I have a data frame such as this one: df = pd.DataFrame({'A': [1.1, 2.7, 5.3], 'B': [2, 10, 9], 'C': [3.3, 5.4, 1.5], 'D': [4, 7, 15]}, index = ['a1', 'a2', 'a3']) Which gives: A B C D a1 1.1 2 3.3 4 a2 2.7 10 5.4 7 a3 5.3 9 1.5 15 My question is simple : I would like to add a column that gives the column name of the second max value of each row. I have written a simple function which returns the second max value for each row def get_second_best(x): return sorted(x)[-2] df['value'] = df.apply(lambda row: get_second_best(row), axis=1) Which gives: A B C D value a1 1.1 2 3.3 4 3.3 a2 2.7 10 5.4 7 7.0 a3 5.3 9 1.5 15 9.0 But I can't find how to display the column name in the 'value' column, instead of the value... I'm thinking about boolean indexing (comparing the 'value' column values with each row), but I haven't figured out how to do it. To be clearer, I would like it to be: A B C D value a1 1.1 2 3.3 4 C a2 2.7 10 5.4 7 D a3 5.3 9 1.5 15 B Any help (and explanation) appreciated!
tagged with: python
score: 11
possible better answer: http://stackoverflow.com/a/52468939
has answer: http://stackoverflow.com/a/52464982
accepted answer: http://stackoverflow.com/a/52464982
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91963767
type: QuestionComment
score: 0
has text: The closest example i found: [a way to rename field name](https://github.com/mstamy2/PyPDF2/issues/407). There is a `.update(...)` function, also not in the docs. Relevant: [how-to-write-to-variable](https://stackoverflow.com/questions/26529269/how-to-write-to-variable-instead-of-to-file-in-python). Another module [PyMuPDF](https://stackoverflow.com/questions/50306870/place-a-vertical-or-rotated-text-in-a-pdf-with-python)
type: Comment
comment on: http://stackoverflow.com/q/52499339

http://stackoverflow.com/a/52503265
downvote count: 0
has body: The issue is that you are not using "or" (|), but instead a colon; Try using: \d{7}|\d{5} It should return the number in your string.
answers question: http://stackoverflow.com/q/52503170
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/comment/92040170
comment on: http://stackoverflow.com/a/52550576
has text: in pandas document i couldn't find that we can directly convert `2000Q1` to a date format. many thanks
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92055321
comment on: http://stackoverflow.com/q/52558016
has text: @HolyDanna Yes the prefix is dynamic, like what you said it can be `www.example.com/products/` or `www.example2.co.uk/`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91898230
score: 0
type: QuestionComment
has text: We can help you better if you give us at least a contrived example of what you actually want to do with the data, including desired output for the example input you gave.
comment on: http://stackoverflow.com/q/52478317
type: Comment

http://stackoverflow.com/a/52564696
type: Answer
has comment: http://stackoverflow.com/comment/92067461
downvote count: 2
upvote count: 1
answers question: http://stackoverflow.com/q/52564639
score: -1
has comment: http://stackoverflow.com/comment/92067467
has body: If you want to do it without recursion, it is impossible. So Here the solution for the RecursionError. Based on the doc of python. You could use sys.getrecursionlimit() to see the limit of recursion. You could also use sys.setrecursionlimit() to make the limit upper.

http://stackoverflow.com/a/65256261
type: Answer
answers question: http://stackoverflow.com/q/52467759
score: 0
has body: the following vectorized way seem to work fine. The idea behind is the same as Nick Klavoht's idea : find the difference between the current time in your timezone and the utc time. # Localized dates dataframe df = pd.DataFrame(data=pd.date_range('2018-1-1', '2019-1-1', freq='h', tz='America/Denver'), columns=['date_time']) df['utc_offset'] = df['date_time'].dt.strftime('%z').str[0:3].astype(float) df['utc_offset_shifted'] = df['utc_offset'].shift(-1) df['dst'] = df['utc_offset'] - df['utc_offset_shifted'] df_dst = df[(df['dst'] != 0) &amp; (df['dst'])] df_dst = df_dst.drop(['utc_offset', 'utc_offset_shifted'], axis=1).reset_index(drop=True) print(df_dst) This outputs : date_time dst 0 2018-03-11 01:00:00-07:00 -1.0 1 2018-11-04 01:00:00-06:00 1.0

http://stackoverflow.com/q/52430846
score: 0
has title: Pyomo Solver Windows pop-up
has comment: http://stackoverflow.com/comment/91917681
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: I am using the algebric modeling Pyomo within Python to solve my optimization problems. However, every time I am running a solver, i.e. Cplex, IPOPT there is a window popping up. Any idea on how to turn off the pop-up windows?
type: Question
has comment: http://stackoverflow.com/comment/92022436
tagged with: pyomo

http://stackoverflow.com/q/52563735
type: Question
tagged with: webhooks
tagged with: python
tagged with: curl
has comment: http://stackoverflow.com/comment/92097839
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52598372
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: zapier
has body: I need to get some data from the balance transaction of Stripe, but Zapier doesn't have the ability to do that directly. I'd like to send a curl command in order to get this data. This is what Stripe provides in their docs: $curl https://api.stripe.com/v1/balance/history/txn_1DFV3e2fooKYlo2CdUbarQBA \ -u sk_test_5z3BDUirhsfooIUypbari76o: I'm thinking I can use a custom request for this, but have no idea how the formatting would work for the secret key
has title: curl as a Zapier Webhook to Stripe
tagged with: stripe-payments
favorite count: 0
has comment: http://stackoverflow.com/comment/92126077
accepted answer: http://stackoverflow.com/a/52598372

http://stackoverflow.com/q/52572593
downvote count: 0
has title: Python program that simulates rolling a 6 sided die and adds up the result of each roll till you roll a 1
has answer: http://stackoverflow.com/a/52572953
type: Question
tagged with: dice
has answer: http://stackoverflow.com/a/52572651
has answer: http://stackoverflow.com/a/52572641
upvote count: 3
has answer: http://stackoverflow.com/a/52572689
tagged with: python
has body: so this is the code I wrote that attempts to answer the question in the title : import random print("Well, hello there.") while True: a = random.randint(1,6) sum = 0 if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver print("Pigged out!") break #To get out of the loop else: while(sum&lt;=20): sum += a print(sum) The program should hold the score till it reaches 20(or more) and display it. It essentially represents a single turn of 'Pig'. I am unable to figure out where I am going wrong with this? Any suggestions would be helpful. An example of a sample output: -rolled a 6 -rolled a 6 -rolled a 5 -rolled a 6 -Turn score is 23
answer count: 4
favorite count: 0
tagged with: python-3.x
tagged with: probability
accepted answer: http://stackoverflow.com/a/52572953
possible better answer: http://stackoverflow.com/a/52572641
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/91816670
comment on: http://stackoverflow.com/a/52436739
type: AnswerComment
type: Comment
score: 1
has text: My pleasure. Could u please give me one score for my answer? appreciate.

http://stackoverflow.com/comment/91967604
has text: Can you please include the full code with the loop?
comment on: http://stackoverflow.com/q/52513914
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/93737039
has text: @today, thanx, but I found many examples where they use the sequential API with, as ex.: https://statcompute.wordpress.com/2017/01/08/an-example-of-merge-layer-in-keras/
type: Comment
comment on: http://stackoverflow.com/a/52567474
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91842113
comment on: http://stackoverflow.com/a/52447641
type: Comment
has text: If you do want to use two servers, you need to make a request for `http://localhost:5000/ajax.html`, and there's no need to send back an entire HTML file if all you want is insert some text in a ` `.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92035341
type: Comment
has text: Interesting, my book hasn't gotten to the def functions but I've tried them and will play with this. Thanks!
comment on: http://stackoverflow.com/a/52547827
type: AnswerComment
score: 0

http://stackoverflow.com/a/66979854
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/118409481
answers question: http://stackoverflow.com/q/52578270
has body: Not related to the question directly, but some people may end up here looking for a different solution. To use Python within Powershell: Install Python from the Microsoft Store (an App in the programs list) Open the Powershell window (can hold SHIFT and right click in the window where your python file is located 'Open Powershell Window here') type 'python' a space and the name of the file Example: PS C:\Users...\Project&gt; python test.py
type: Answer
upvote count: 1

http://stackoverflow.com/a/53577732
has body: Update py-googletrans/googletrans/gtoken.py like the following: RE_TKK = re.compile(r'TKK=eval\(\'\(\(function\(\)\{(.+?)\}\)\(\)\)\'\);', re.DOTALL) RE_RAWTKK = re.compile(r'tkk:\'([^\']*)\'',re.DOTALL) def __init__(self, tkk='0', session=None, host='translate.google.com'): self.session = session or requests.Session() self.tkk = tkk self.host = host if 'http' in host else 'https://' + host def _update(self): """update tkk """ # we don't need to update the base TKK value when it is still valid now = math.floor(int(time.time() * 1000) / 3600000.0) if self.tkk and int(self.tkk.split('.')[0]) == now: return r = self.session.get(self.host) rawtkk = self.RE_RAWTKK.search(r.text) if rawtkk: self.tkk = rawtkk.group(1) return
downvote count: 0
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/52446811

http://stackoverflow.com/a/52506864
accepted answer of: http://stackoverflow.com/q/52506716
answers question: http://stackoverflow.com/q/52506716
type: AcceptedAnswer
downvote count: 0
has body: Another alternate solution is to use a widely separated x-positions for the center bar. The problem with your plot was that your bar width was 0.3 and you had 5 bars, so 5*0.3 = 1.5 total x-spacing per group. And since the spacing between your x-positions for centering bars was 1, you had an overlap of 0.5 between each group of bars. To avoid this, you can use a spacing of 2 between your x-indices for centering bars using the following. I also noticed that your were not using all the x-ticklabels properly. Add the following two lines to make things look good. ind = np.arange(0,2*N, 2) # the x locations for the groups ax.set_xticks(ind + 2*width)
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/91954205
score: 3

http://stackoverflow.com/q/52573400
tagged with: python
has comment: http://stackoverflow.com/comment/92083349
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92083561
has comment: http://stackoverflow.com/comment/92083122
type: Question
has answer: http://stackoverflow.com/a/52685243
answer count: 2
has comment: http://stackoverflow.com/comment/92083258
accepted answer: http://stackoverflow.com/a/52647001
tagged with: amazon-web-services
possible better answer: http://stackoverflow.com/a/52685243
has body: I'm new to AWS lambda; I have to return the result of my for loop as result of the lambda function, Below code will be giving users who have not used there AWS password for last 60 days; it has been tested in the jupyter notebook and its working fine import json import boto3 import datetime from dateutil.tz import tzutc resource = boto3.resource('iam') today = datetime.datetime.now() for user in resource.users.all(): if user.password_last_used is not None: delta = (today - user.password_last_used.replace(tzinfo=None)).days if delta &gt; 60: print("username: ", [user.user_name][0]," - ",delta , "days") How can I return the result as below output from the jupyter notebook Username: abc- 96 Days Username: def- 64 Days Username: ghi- 184 Days Username: mno- 158 Days Username: xyz- 95 Days Lambda code which I tried to append output to an array and return the array but returning Null:- import json import boto3 import datetime from dateutil.tz import tzutc def lambda_handler(event, context): resource = boto3.resource('iam') client = boto3.client('iam') today = datetime.datetime.now() userName = [] for user in resource.users.all(): if user.password_last_used is not None: delta = (today - user.password_last_used.replace(tzinfo=None)).days if delta &gt; 30: userName.append("username: ", [user.user_name][0]," - ",delta , "days") return userName
has comment: http://stackoverflow.com/comment/92083171
score: 0
has comment: http://stackoverflow.com/comment/92083486
has comment: http://stackoverflow.com/comment/92083341
tagged with: aws-lambda
has title: Need to return result of for loop as lambda result
has comment: http://stackoverflow.com/comment/92083467
has comment: http://stackoverflow.com/comment/92083149
has comment: http://stackoverflow.com/comment/92083556
has answer: http://stackoverflow.com/a/52647001

http://stackoverflow.com/q/52478324
has answer: http://stackoverflow.com/a/52478633
downvote count: 0
has comment: http://stackoverflow.com/comment/91897715
has body: i have a this list: my_list = ['Judy 88 5', 'animal 91 5', 'Mo 86 5', 'Geno 87 6', 'exhaled 87 6'] i want to remove all non-numeric items from this list i.e- ['88 5', '91 5', '86 5', '87 6', '87 6'] and i want just the double digit numbers i.e - ['88', '91', '86', '87', '87'] how can i make it happen without the index being changed? i tried using my_list = [elem for elem in my_list if not any(c.isalpha() for c in elem)] but it just returned me an empty list... edit: regex helped me on this list but what if the list was something like so: my_list = ['J55udy 88 5', 'anim31al 91 5', 'Mo2 86 5', 'Geno 87 6', 'exhaled 87 6'] my list all ways changing but it has a constant style to it, first a user name then two digit number then a one digit number, problem is sometimes the user is using digits in his name, how can i get only the 2 digits in the middle even if the list look's like this? my_list = ['J558udy 88 5', 'anim31al 91 5', 'Mo52 86 5', 'Gen3o 87 6', 'exhaled 87 6']
has answer: http://stackoverflow.com/a/52478581
has comment: http://stackoverflow.com/comment/91897633
possible better answer: http://stackoverflow.com/a/52478424
tagged with: python
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52478383
accepted answer: http://stackoverflow.com/a/52478383
has answer: http://stackoverflow.com/a/52478424
upvote count: 1
has comment: http://stackoverflow.com/comment/91897791
type: AnsweredQuestion
tagged with: list
has title: python - removing all non-numeric characters from a string inside a list
score: 1
tagged with: list-comprehension
type: Question

http://stackoverflow.com/q/52553757
has answer: http://stackoverflow.com/a/52553934
has comment: http://stackoverflow.com/comment/92046403
tagged with: python
has title: A For loop with embedded if statement to update a dataframe
has comment: http://stackoverflow.com/comment/92046457
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52553934
score: 1
upvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52553883
tagged with: dataframe
has body: I am a newcomer to python. I want to implement a "For" loop on the elements of a dataframe, with an embedded "if" statement. Code: import numpy as np import pandas as pd #Dataframes x = pd.DataFrame([1,-2,3]) y = pd.DataFrame() for i in x.iterrows(): for j in x.iteritems(): if x&gt;0: y = x*2 else: y = 0 With the previous loop, I want to go through each item in the x dataframe and generate a new dataframe y based on the condition in the "if" statement. When I run the code, I get the following error message. ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Any help would be much appreciated.
accepted answer: http://stackoverflow.com/a/52553883
has comment: http://stackoverflow.com/comment/92046479
answer count: 2
has comment: http://stackoverflow.com/comment/92046392
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/92046262
has comment: http://stackoverflow.com/comment/92046243
favorite count: 0

http://stackoverflow.com/q/52492404
has answer: http://stackoverflow.com/a/52492533
type: Question
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52492512
downvote count: 0
has body: I am trying to read this file of two columns into a dataframe. It doesn't read as datetime. INPUT : DATE DTB3 8/4/2014 0.0004 8/5/2014 0.0003 8/6/2014 0.0003 ........ Using this code : T1 = pd.read_csv(FRED_file,sep=',',header=None,names=['DATE','DTB3'],dtype= {'DATE':'str','DTB3':'str'},parse_dates=['DATE'],index_col='DATE') T1.drop(T1.index[0],inplace=True) T1.index = pd.to_datetime(T1.index, format = '%m/%d%Y') T1.index = T1.index.strftime('%Y-%m-%d') T1.index Output : Index(['2014-08-04', '2014-08-05', '2014-08-06', '2014-08-07', '2014-08-08', '2014-08-11', '2014-08-12', '2014-08-13', '2014-08-14', '2014-08-15', ... '2018-09-07', '2018-09-10', '2018-09-11', '2018-09-12', '2018-09-13', '2018-09-14', '2018-09-17', '2018-09-18', '2018-09-19', '2018-09-20'], dtype='object', length=1079)
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
has title: Pandas will not recognize datetimeindex from csv file
score: 2

http://stackoverflow.com/comment/91938602
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52498929
has text: @Bluecider you should also be looking into tutorials e.g. http://www.tutorialspoint.com/python/python_dictionary.htm because you are going to be using dictionaries a lot

http://stackoverflow.com/a/52578574
type: Answer
answers question: http://stackoverflow.com/q/52578522
has body: Python tries to be helpful (whether it actually helps is debatable) by printing bytes which correspond to an ASCII symbol as the ASCII symbol. &gt;&gt;&gt; t1 = b'test' &gt;&gt;&gt; t2 = b'\x74\x65\x73\x74' &gt;&gt;&gt; t1 == t2 True &gt;&gt;&gt; print(t1, t2) b'test' b'test'
score: 0

http://stackoverflow.com/comment/91848519
has text: Hint: Use a loop.
score: 3
comment on: http://stackoverflow.com/q/52452596
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52515535
type: Question
has body: matrix = [[1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1, 1]] def connect_nodes(node1, node2): y_distance = node2[0] - node1[0] x_distance = node2[1] - node1[1] print('distance between', node1, "and", node2, "is", y_distance, "on Y-axis and", x_distance, "on X-axis") if y_distance == 0: if x_distance &gt; 0: for i in range(node1[1]+1, node1[1]+x_distance, 1): matrix[node1[0]][i] = 0 if x_distance &lt; 0: for i in range(node1[1]+x_distance+1, node1[1], 1): matrix[node1[0]][i] = 0 if x_distance == 0: if y_distance &gt; 0: for i in range(node1[0]+1, node1[0]+y_distance, 1): matrix[i][node1[1]] = 0 if y_distance &lt; 0: for i in range(node1[0]+y_distance+1, node1[0], 1): matrix[i][node1[1]] = 0 connect_nodes([1,0], [1,5]) connect_nodes([1,5], [5,5]) for m in matrix: print(m) I get two coordinates which are two items of a 2D-array. Then I need to draw some kind of a line between 2 given coordinates - edit values of items on a particular row or column. Above is some code I wrote to solve this problem. But I'd like to know is there more elegant way to do the same? P.S. What if the coordinates are not on the same line (vertical or horizontal)? How do I draw a line between [1,1] and [9,3] ?
score: 0
has answer: http://stackoverflow.com/a/52515879
accepted answer: http://stackoverflow.com/a/52515879
answer count: 1
tagged with: python
type: AnsweredQuestion
has title: change values of array items between 2 given coordinates

http://stackoverflow.com/comment/92634861
type: AnswerComment
comment on: http://stackoverflow.com/a/52853054
type: Comment
has text: It works great, thank you that's going to save me a ton of time
score: 0

http://stackoverflow.com/q/52490135
answer count: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/52491107
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52491107
has answer: http://stackoverflow.com/a/52614983
upvote count: 1
type: Question
tagged with: algorithm
score: 1
has title: Can't spot the bug in my rotate matrix code
has body: I know there's an easy way using transpose to rotate a square-matrix 90 degrees, but I'm writing a solution as if I don't know that one (in other words, I want to do the swapping). The generally idea below is to swap layer by layer. The offset represents what layer (outward to inward) is being swapped. Here's the algorithm (note that it is wrapped in a class because that's a Leetcode thing): class Solution: def rotate(self, matrix): for start in range(len(matrix)//2): end = len(matrix) - start - 1 # swap all 4 coordinates: for offset in range(start, end): # swap top_left over top_right temp, matrix[start+offset][end] = matrix[start+offset][end], matrix[start][start+offset] # swap top_right -&gt; bottom_right temp, matrix[end][end-offset] = matrix[end][end-offset], temp # swap bottom_right -&gt; bottom_left temp, matrix[end-offset][start] = matrix[end-offset][start], temp # swap bottom_left -&gt; top_left matrix[start][start+offset] = temp This works for some hand tests with small matrices, as well as the smaller input test cases in the Leetcode submission. However, it fails on the following input: [[ 2, 29, 20, 26, 16, 28], [12, 27, 9, 25, 13, 21], [32, 33, 32, 2, 28, 14], [13, 14, 32, 27, 22, 26], [33, 1, 20, 7, 21, 7], [ 4, 24, 1, 6, 32, 34]] Expected output: [[ 4, 33, 13, 32, 12, 2], [24, 1, 14, 33, 27, 29], [ 1, 20, 32, 32, 9, 20], [ 6, 7, 27, 2, 25, 26], [32, 21, 22, 28, 13, 16], [34, 7, 26, 14, 21, 28]] My output: [[ 4, 33, 13, 32, 12, 2], [24, 1, 7, 33, 27, 29], [ 1, 20, 32, 2, 14, 20], [ 6, 28, 32, 27, 25, 26], [32, 21, 22, 9, 13, 16], [34, 7, 26, 14, 21, 28]] This matrix is just big enough to where it becomes tedious to walk through the algorithm by hand like I did for the smaller input cases to debug. Where is the bug in my implementation?
tagged with: matrix
accepted answer: http://stackoverflow.com/a/52614983
downvote count: 0
has answer: http://stackoverflow.com/a/52491131
favorite count: 0

http://stackoverflow.com/q/52456309
downvote count: 1
has title: Calculate lists in Python 3.7
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52456343
has comment: http://stackoverflow.com/comment/91873499
has answer: http://stackoverflow.com/a/52456343
type: Question
has comment: http://stackoverflow.com/comment/91854989
upvote count: 0
has answer: http://stackoverflow.com/a/52457365
linked to: http://stackoverflow.com/q/1832940
has answer: http://stackoverflow.com/a/52456437
answer count: 4
tagged with: operators
favorite count: 0
score: -1
has answer: http://stackoverflow.com/a/52456352
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52457365
tagged with: python
has body: I was wondering if it was possible to calculate a list, for example this one calculation = [1, "+", 2, "*", 15] so it returns 31.

http://stackoverflow.com/a/52502191
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52502083
has comment: http://stackoverflow.com/comment/91945526
has comment: http://stackoverflow.com/comment/91945646
has comment: http://stackoverflow.com/comment/91945711
type: Answer
has comment: http://stackoverflow.com/comment/91945792
has comment: http://stackoverflow.com/comment/91945228
has comment: http://stackoverflow.com/comment/91944940
has comment: http://stackoverflow.com/comment/91945257
has body: use strace on linux, it will show you every system call made by any program (including python). On windows you have to use something like wt or maybe Logger.exe which traces all library calls (not just system). You can use a debugger like gdb to look at the machine code in realtime, and since you have CPython source code, a better alternative is to just compile it with debugging symbols then run it in a C debugger, that can give you a high-level call stack, which will be a lot easier to understand.
downvote count: 1
has comment: http://stackoverflow.com/comment/91945171
has comment: http://stackoverflow.com/comment/91945617
accepted answer of: http://stackoverflow.com/q/52502083
upvote count: 5
score: 4
has comment: http://stackoverflow.com/comment/91945538
has comment: http://stackoverflow.com/comment/91945011

http://stackoverflow.com/comment/92078584
type: Comment
comment on: http://stackoverflow.com/a/52570754
score: 1
has text: @Chris Provided they have already two upvotes, the reputation penalty is fairly small. Furthermore, I'm giving a clear explanation of why I am downvoting, I think it is important for a new contributor to learn about XY problems. Finally, if that turns out to be, for some reason, the correct answer I will retract my downvote. It is ok to be downvoted, their is no shame in that.
type: AnswerComment

http://stackoverflow.com/a/52550916
has comment: http://stackoverflow.com/comment/92042238
answers question: http://stackoverflow.com/q/52550898
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/92042814
has comment: http://stackoverflow.com/comment/92041360
accepted answer of: http://stackoverflow.com/q/52550898
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92041215
has comment: http://stackoverflow.com/comment/92041398
type: Answer
has comment: http://stackoverflow.com/comment/92042724
has body: You forgot a percent sign between your sql string and (vardate). Therefore the python interpreter thinks you want to call that string as a function. Change your code to OPENdata = "select * from ts_data where substr(created_on,1,10)=%s" % (vardate) Nowadays, the suggestion for string formatting is using the str.format() method. "select * from ts_data where substr(created_on,1,10)={}".format(vardate) By the way, as stated by Willem Van Onsem you should never ever pass your input directly to the database as this makes your application vulnerable to sql injections. It is highly recommended to use whatever functionallity your library for database connections brings to exscape every user input.
has comment: http://stackoverflow.com/comment/92041925

http://stackoverflow.com/comment/92207337
type: QuestionComment
comment on: http://stackoverflow.com/q/52583498
has text: Thank you. the compiler doesn't resolve get_python_func_of_wrapped_object(). doesn't seems like a boost-python function. do you know where does it come from?
score: 0
type: Comment

http://stackoverflow.com/a/68847361
has body: Fourier curve fitting has a closed form solution. This function can calculate it for you. def fourier_curve_fit(ser, no_fourier=3, display_latex=True, series=False): &quot;&quot;&quot; Apply fourier curve fitting to series. ser: pandas.Series Contains data stored in Series. no_fourier: int degree of fourier series to be used. Returns pandas.Series &quot;&quot;&quot; from IPython.display import display, Math import numpy as np import pandas as pd ser_ = ser.reset_index(drop=True) x = ser_.index y = ser_.values A = (2/len(y))*np.matmul(y.reshape(1,-1), np.array([np.cos(2*np.pi/len(y)*n*np.arange(len(y))) for n in np.arange(no_fourier+1)]).T ).flatten() B = (2/len(y))*np.matmul(y.reshape(1,-1), np.array([np.sin(2*np.pi/len(y)*n*np.arange(len(y))) for n in np.arange(no_fourier+1)]).T ).flatten() L = max(x)-min(x) if display_latex: Omega = '\\frac{{2*\\pi}}{'+str(L)+'}' fourier_equation = '' for i,(a,b) in enumerate(zip(A,B)): if i==0: fourier_equation += f'f(x)={a:.4f} \\\\' else: fourier_equation += f' {a:+.4f}*\\cos({Omega}*{i}*x) {b:+.4f}*\\sin({Omega}*{i}*x) \\\\' display(Math(fourier_equation)) coeff = dict([(f'a{i}',j) for i,j in enumerate(A)]+[(f'b{i}',j) for i,j in enumerate(B)]) if series: As = np.matmul(A.reshape(1,-1), np.array([np.cos(2*np.pi/len(y)*n*np.arange(len(y))) for n in np.arange(no_fourier+1)])).flatten() Bs = np.matmul(B.reshape(1,-1), np.array([np.sin(2*np.pi/len(y)*n*np.arange(len(y))) for n in np.arange(no_fourier+1)])).flatten() return pd.Series(data=(As+Bs), index=ser.index, name='Fourier Fitted')-coeff['a0']/2 else: return pd.Series(data=coeff, name='Fourier Coefficients')
answers question: http://stackoverflow.com/q/52524919
score: 0
type: Answer

http://stackoverflow.com/comment/92030095
type: AnswerComment
comment on: http://stackoverflow.com/a/52541218
type: Comment
has text: @BowenLiu, Expensive means "costly in terms of performance", usually measured in time. Cheap, likewise, means efficient / performant.
score: 0

http://stackoverflow.com/comment/91877754
has text: Please use a short and informative title for your question and add the explanation to the body. Also, explain what's the problem and your efforts towards solving it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52467978
score: 3

http://stackoverflow.com/a/52475232
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52466380
has comment: http://stackoverflow.com/comment/91909620
has comment: http://stackoverflow.com/comment/92174357
type: Answer
score: 2
upvote count: 2
has body: My suspicion is that your database connection isn't actually being closed. You shouldn't be using the same database file between test runs anyway - it's important that Hypothesis tests be repeatable - so the easiest thing to do would be to create a temporary file in your tests and use that instead of a fixed test.db and see if the problem goes away. More generally, I think relying on things being closed in del tends to be a source of weird bugs and I would encourage the use of an explicit context manager or similar.
accepted answer of: http://stackoverflow.com/q/52466380

http://stackoverflow.com/q/52493504
tagged with: python
downvote count: 1
answer count: 0
score: 1
tagged with: matplotlib
type: Question
linked to: http://stackoverflow.com/q/48587997
has body: I have a piechart with so many slices, that is very hard to read it: Is it possible to reduce the number of slices, by grouping the smallest portions in one named "others" or just hide them?
has comment: http://stackoverflow.com/comment/91933921
has title: matplotlib: reduce the number of labels on piechart
favorite count: 0
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/48587997

http://stackoverflow.com/q/52520812
has body: I have the following df: Name Jan_2018 Feb_2018 Mar_2018 A 33% 40% 42% B 20% 35% 50% C 21% 31% 12% I'm doing some operations with the numeric data (sums, averages, etc) so I need to remove the % sign so pandas can stop treating them as strings. However my output needs to have the % signs back. Additionally I can't hardcode any columns since more may get added in the future. What's the easiest way to remove the % signs from the numeric data and add them back again later?
score: 1
tagged with: dataframe
has title: Pandas - replace % signs in data and put them back
accepted answer: http://stackoverflow.com/a/52521050
type: Question
downvote count: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52521131
favorite count: 0
has comment: http://stackoverflow.com/comment/91981215
has answer: http://stackoverflow.com/a/52521050
possible better answer: http://stackoverflow.com/a/52520878
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52520878
type: AnsweredQuestion

http://stackoverflow.com/q/52490126
upvote count: 1
tagged with: wagtail
answer count: 1
has comment: http://stackoverflow.com/comment/91921062
has title: Wagtail how to render an image: Unrecognised operation: orignal
favorite count: 0
score: 0
has body: How do I render an image from a ForeignKey('wagtailimages.Image') inside Productpage.html? I'm currently receiving the error: Unrecognised operation: orignal Why is this not working?: {% image page.productImage orignal %} Productpage.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}template-productspage{% endblock %} {% block content %} {{ page.title }} {{ page.count }} {{ page.intro }} {% image page.productImage orignal %} Return to blog {% endblock %} Products/models.py from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index from wagtail.images.models import Rendition class ProductPage(Page): intro = models.CharField(max_length=250) count = models.IntegerField(default=1) description = RichTextField(blank=True) productImage = models.ForeignKey( 'wagtailimages.Image', null=True, on_delete=models.CASCADE, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('description'), ] content_panels = Page.content_panels + [ FieldPanel('intro'), FieldPanel('count'), FieldPanel('description', classname="full"), ImageChooserPanel('productImage'), # ERRORS OUT IN HTML #InlinePanel('gallery_images', label="Gallery images"), # MULTPIPLE IMAGES ]
downvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/117250691
type: Question
tagged with: image
has answer: http://stackoverflow.com/a/52506331
accepted answer: http://stackoverflow.com/a/52506331

http://stackoverflow.com/comment/92024717
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52538374
has text: Dude you should really anonymize your input before you post it here. There are still people like myself on stackoverflow who understand Chinese and know what is bilibili.
score: 0

http://stackoverflow.com/comment/91807783
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52431056
type: QuestionComment
has text: Could you try adding this to your `settings.py` file and see if it fixes it? `STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]`

http://stackoverflow.com/q/52443042
has comment: http://stackoverflow.com/comment/91828880
has answer: http://stackoverflow.com/a/52445201
tagged with: python
has comment: http://stackoverflow.com/comment/91832558
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/123588648
tagged with: pycharm
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/123588728
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91830174
tagged with: anaconda
has body: I have an environment of Anaconda (apart of root) and I'm trying to install this two libraries with no success. I tried: Install libraries by the environment tools of Anaconda Navigator with 'Multiple Errors Encountered.' error. Could I get more info about it? The options that I saw didn't say anything more. 'Multiple Errors Encountered.' Install Jupyter with the install option of the apps of Anaconda Navigator with the same error too 'Multiple Errors Encountered.' Install with conda install jupyter and conda install matplotlib in the console and cd where the environment is located. The console made its process and it said that both libraries were already installed. I check it in the libraries list of Anaconda Navigator and it doesn't appear. (base) C:\Users...>cd C:\Users\Alvaro\Anaconda3\envs\tensorflow (base) C:\Users...\Anaconda3\envs\tensorflow>conda install matplotlib Solving environment: done All requested packages already installed. (base) C:\Users\Alvaro\Anaconda3\envs\tensorflow>conda install jupyter Solving environment: done All requested packages already installed. Install with pip install jupyter and pip install matplotlib with the similar result than conda install option. (base) C:\Users\Alvaro\Anaconda3\envs\tensorflow>pip install jupyter Requirement already satisfied: jupyter in c:\users\alvaro\anaconda3\lib\site-packages (1.0.0) Requirement already satisfied: notebook in c:\users\alvaro\anaconda3\lib\site-packages (from jupyter) (5.5.0) Requirement already satisfied: qtconsole in c:\users\alvaro\anaconda3\lib\site-packages (from jupyter) (4.3.1) Requirement already satisfied: jupyter-console in c:\users\alvaro\anaconda3\lib\site-packages (from jupyter) (5.2.0) Requirement already satisfied: nbconvert in c:\users\alvaro\anaconda3\lib\site-packages (from jupyter) (5.3.1) Requirement already satisfied: ipykernel in c:\users\alvaro\anaconda3\lib\site-packages (from jupyter) (4.8.2) Requirement already satisfied: ipywidgets in c:\users\alvaro\anaconda3\l…
has title: I can't install Jupyter and Matplotlib in my anaconda env
tagged with: matplotlib
has answer: http://stackoverflow.com/a/69915436
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92169595
score: 17
type: AnswerComment
type: Comment
has text: I'm writing about asyncio with `aiohttp` & [`aiofiles`](https://github.com/Tinche/aiofiles) and want to mention queues in a section---do you mind if I link to & cite this answer?
comment on: http://stackoverflow.com/a/52615705

http://stackoverflow.com/comment/91898147
score: 1
has text: how big can big_long_loop be? One of the easiest way to have issues with Celery is by exhausting resources like CPU or RAM, I suggest tracking the len of `subtasks` and see if that has any connection to the outages
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52455417

http://stackoverflow.com/comment/91935429
comment on: http://stackoverflow.com/a/52497376
type: AnswerComment
type: Comment
score: 1
has text: oh yah, could use `x[0:1]` instead

http://stackoverflow.com/comment/91909991
type: QuestionComment
comment on: http://stackoverflow.com/q/52484250
score: 1
has text: Why do you want to use XOR? It seems pointless.
type: Comment

http://stackoverflow.com/comment/92007060
comment on: http://stackoverflow.com/a/52533329
has text: This works beautifully. Thank you for your explanation!
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/52512785
has body: set default parameters and only call the function explicitely with those parameters which are different from the default parameters! e.g. def func(param1=0, param2="abc", param3=0.3) for definition and result = func(param1=3) when calling. (not tested, but I see no reason why this shouldn't work!)
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91967361
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52512725

http://stackoverflow.com/a/52446927
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/52446826
type: Answer
has body: You still need memory, read and write from the disk as far I know is not possible for sklearn ML tasks (you need to try other software), you can try to fit in the memory by using strategies listed below but is limited to what algorithms you can implement:Scaling with instances using out-of-core learning Performance and results will be impacted in this cases and also batches size also impact the results. Note: for read and write to and from the disk better suits SAS and hadoop(map-reduce) but sklearn requires RAM.
score: 0

http://stackoverflow.com/a/52511895
answers question: http://stackoverflow.com/q/52511733
type: Answer
score: 2
upvote count: 2
has body: or just that: option = None while option not in {'1', '2', '3'}: # or: while option not in set('123') option = input("Enter 1 2 or 3: ") option = int(option) with the restriction to the 3 strings '1', '2', '3' there is not even the need to catch a ValueError when casting to an int.
downvote count: 0

http://stackoverflow.com/comment/91925996
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52492723
has text: i want writable nested serializers.
score: 0

http://stackoverflow.com/comment/91809266
type: QuestionComment
comment on: http://stackoverflow.com/q/52432553
has text: @EricNordeloGaliano It seems confusing I know. This is more a question of elegance than utility I am seeing. Basically, I have all options under a giant if-else statement now, where if the mode is 'blah', I run function 'plot_blah', and if the mode is 'foo', I run 'plot_foo'. But that means I have to define those functions as so. I was wondering if there was a more elegant way.
score: 0
type: Comment

http://stackoverflow.com/a/52479235
type: Answer
upvote count: 5
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/52479184
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52479184
has body: If same columns names and index in both DataFrames subtract numpy array created by second DataFrame: self.dfresidualLoad=self.dfsupply - self.dfload.values Or use rename columns if positions of columns names matched: d = dict(zip(dfload.columns, dfsupply.columns)) df = dfsupply.subtract(dfload.rename(columns=d), axis='column') print (df) supply_1 supply_2 supply_3 supply_4 2018-01-01 00:00:00 -39.800552 -46.614811 -8.362779 -99.490238 2018-01-01 00:15:00 -100.739365 -98.091279 -13.046690 -18.506559 2018-01-01 00:30:00 -83.660493 -28.381557 -48.911892 -115.359383 2018-01-01 00:45:00 -3.561836 9.346799 -0.188290 -15.311739 2018-01-01 01:00:00 8.369661 -85.616954 7.580784 -18.063186

http://stackoverflow.com/q/52580084
type: Question
tagged with: python
tagged with: tkinter
score: 0
has body: I have got a question how to connect my classes to each other correctly. I have one main class with my first window where the user has to put in certain infos, after submitting that a new window opens where he has to make the next step. You can have a look down on my code, the "MyForm"-Class is the mainclass and the "popup"-class is supposed to be the following window. But Im not sure if I linked it properly. It is working but on a weird way. So how to improve this that I dont get in trouble with some more serious projects later. Code: from tkinter import Tk, Label, Entry, Button, W, Toplevel from tkinter import messagebox class MyForm: def thanx(self): if any((len(self.e.get().strip()) == 0, len(self.e2.get().strip()) == 0, len(self.e2.get().strip()) == 0)): messagebox.showerror("Error", "Please enter affordable infos") self.boo = False else: messagebox.showinfo("Submition done", "Thank you") self.boo = True def callback(self): #print("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get())) if self.boo: f = open("PrivatData.txt", "w+") f.write("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get())) def popup(self): self.root.quit() PopUp() def __init__(self): self.root = Tk() self.root.title("Your privat details") Label(self.root, text="Your Name").grid(row = 0, padx = 12, pady=5) Label(self.root, text="Password").grid(row=1, padx=12, pady=5) Label(self.root, text="Email").grid(row=2, padx=12, pady=5) self.e = Entry(self.root) self.e2 = Entry(self.root) self.e3= Entry(self.root) self.e.grid(row=0,column=1,columnspan=2) self.e2.grid(row=1, column=1, columnspan=2) self.e3.grid(row=2, column=1, columnspan=2) self.e.focus_set() self.show= Button(self.root, text="Submit", command=lambda:[self.thanx(),self.callback(),self.popup()]) self.quit = Button(self.root,text="Quit", command = self.root.quit) self.show.grid(row=3, column=1, pady=4) self.quit.grid(row=3, column=2, sticky = W, pady=4) self.root.geometry("230x140") …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92096747
has title: How do I correctly connect classes to each other in python with tkinter?
answer count: 0
has comment: http://stackoverflow.com/comment/92096585

http://stackoverflow.com/comment/114114257
type: Comment
has text: Also please edit your answer with correct formatting
comment on: http://stackoverflow.com/a/64534738
type: AnswerComment
score: 0

http://stackoverflow.com/q/52588298
favorite count: 0
upvote count: 18
tagged with: python
possible better answer: http://stackoverflow.com/a/52588470
tagged with: argmax
has answer: http://stackoverflow.com/a/52588470
type: AnsweredQuestion
tagged with: performance
downvote count: 0
has title: pandas idxmax: return all rows in case of ties
type: Question
has comment: http://stackoverflow.com/comment/92112453
answer count: 2
has answer: http://stackoverflow.com/a/52588438
accepted answer: http://stackoverflow.com/a/52588438
score: 18
has body: I am working with a dataframe where I have weight each row by its probability. Now, I want to select the row with the highest probability and I am using pandas idxmax() to do so, however when there are ties, it just returns the first row among the ones that tie. In my case, I want to get all the rows that tie. Furthermore, I am doing this as part of a research project where I am processing millions a dataframes like the one below, so keeping it fast is an issue. Example: My data looks like this: data = [['chr1',100,200,0.2], ['ch1',300,500,0.3], ['chr1', 300, 500, 0.3], ['chr1', 600, 800, 0.3]] From this list, I create a pandas dataframe as follows: weighted = pd.DataFrame.from_records(data,columns=['chrom','start','end','probability']) Which looks like this: chrom start end probability 0 chr1 100 200 0.2 1 ch1 300 500 0.3 2 chr1 300 500 0.3 3 chr1 600 800 0.3 Then select the row that fits argmax(probability) using: selected = weighted.ix[weighted['probability'].idxmax()] Which of course returns: chrom ch1 start 300 end 500 probability 0.3 Name: 1, dtype: object Is there a (fast) way to the get all the values when there are ties? thanks!
tagged with: pandas

http://stackoverflow.com/comment/92232981
type: Comment
type: QuestionComment
has text: @cryptonome you must have edited the comment because at first I didn't read this also I lost internet connection.. so maybe I was seeing the old comment.
comment on: http://stackoverflow.com/q/52488615
score: 0

http://stackoverflow.com/a/52559277
score: 0
has comment: http://stackoverflow.com/comment/92057528
type: Answer
answers question: http://stackoverflow.com/q/52558016
has body: Another option is to use urlparse instead of/along with re It will allow you to split a URL like this: import urlparse my_url = "http://www.example.com/products/ammaxxllx.html?spam=eggs#sometag" url_obj = urlparse.urlsplit(my_url) url_obj.scheme &gt;&gt;&gt; 'http' url_obj.netloc &gt;&gt;&gt; 'www.example.com' url_obj.path &gt;&gt;&gt; '/products/ammaxxllx.html' url_obj.query &gt;&gt;&gt; 'spam=eggs' url_obj.fragment &gt;&gt;&gt; 'sometag' # Now you're able to work with every chunk as wanted! prefix = '/products' if url_obj.path.startswith(prefix): # Do whatever you need, replacing the initial characters. You can use re here print url_obj.path[len(prefix) + 1:] &gt;&gt;&gt;&gt; ammaxxllx.html

http://stackoverflow.com/a/52476730
has body: I toyed around with this a bit more after reading your suggestions and found that blob detection is not the way to go. Using color recognition to find the contours solved the issue however as was suggested above. Thanks again! My solution looks like this: frame = cv2.imread("image.png") color = ((200, 145, 0), (255, 200, 50)) lower_color = numpy.array(color[0], dtype="uint8") upper_color = numpy.array(color[1], dtype="uint8") # Look for the color in the frame and identify contours color = cv2.GaussianBlur(cv2.inRange(frame, lower_color, upper_color), (3, 3), 0) contours, _ = cv2.findContours(color.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if contours: for c in contours: rectangle = numpy.int32(cv2.cv.BoxPoints(cv2.minAreaRect(c))) # Draw a rectangular frame around the detected object cv2.drawContours(frame, [rectangle], -1, (0, 0, 255), 4) cv2.imshow("frame", frame) cv2.waitKey(0) cv2.destroyAllWindows()
accepted answer of: http://stackoverflow.com/q/52445834
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52445834

http://stackoverflow.com/q/52470675
accepted answer: http://stackoverflow.com/a/52470830
has answer: http://stackoverflow.com/a/52471176
has comment: http://stackoverflow.com/comment/91883437
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91883516
has body: I am working on a data with pandas in which a maintenance work is done at a location. The maintenance is done every four years at each site. I want to find the years since the last maintenance action at each site. I am giving here only two sites in the following example but in the original dataset, I have thousands of them. My data only covers the years 2014 through 2017. Action = 0 means no action has been performed that year, Action = 1 means some action has been done. Measurement is a performance reading related to the effect of the action. The action can happen in any year. I know that if the action has been performed in Year Y, the previous maintenance has been performed in Year Y-4. Site Year Action Measurement A 2014 0 100 A 2015 0 150 A 2016 1 300 A 2017 0 80 B 2014 0 200 B 2015 1 250 B 2016 0 60 B 2017 0 110 Given this dataset; first, I want to have a temporary dataset like this: Item Year Action Measurement Years_Since_Last_Action A 2014 0 100 2 A 2015 0 150 3 A 2016 1 300 4 A 2017 0 80 1 B 2014 0 200 3 B 2015 1 250 4 B 2016 0 60 1 B 2017 0 110 2 Then, I want to have: Years_Since_Last_Action Mean_Measurement 1 70 2 105 3 175 4 275 Thanks in advance!
score: 4
type: Question
upvote count: 4
answer count: 3
tagged with: pandas
has title: Calculating distance to a row with a certain value
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52470830
has answer: http://stackoverflow.com/a/52470852
tagged with: python
possible better answer: http://stackoverflow.com/a/52471176

http://stackoverflow.com/comment/92109933
has text: can you show what do you mean by polygon intersection and what did you try ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52587434

http://stackoverflow.com/q/52470651
answer count: 2
downvote count: 0
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/57890571
has body: I am new to python and terminal so I apologize in advance and thank you for your time. I installed python as well as homebrew. I was trying to do $ sudo easy_install pip and received Password: Searching for pip Reading https://pypi.python.org/simple/pip/ Download error on https://pypi.python.org/simple/pip/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! Couldn't find index page for 'pip' (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/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! No local packages or download links found for pip error: Could not find suitable distribution for Requirement.parse('pip') I have spent most of the day looking up answers to fixing this issue but I feel as though I am just muddying up my directories. I am at a point where it might be better to just erase/uninstall anything python related and reinstall correctly. when I look up the path there are many different versions of python in different directories ~$ echo $PATH /Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin Any advice on how to fix this issue/troubleshoot would be greatly appreciated. Or a way to recursively uninstall/erase python so that I can start fresh if this would be easier. Thank You
has title: Pip command not found. Issues with Path
favorite count: 0
has answer: http://stackoverflow.com/a/55202069
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91886008
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/91883514
type: Question

http://stackoverflow.com/q/52571398
accepted answer: http://stackoverflow.com/a/52571570
has comment: http://stackoverflow.com/comment/92079396
answer count: 3
tagged with: python
linked to: http://stackoverflow.com/q/10950362
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92079456
upvote count: 1
has answer: http://stackoverflow.com/a/52572668
possible better answer: http://stackoverflow.com/a/52571776
type: Question
has answer: http://stackoverflow.com/a/52571776
tagged with: algorithm
has answer: http://stackoverflow.com/a/52571570
score: 1
has comment: http://stackoverflow.com/comment/92079529
has comment: http://stackoverflow.com/comment/92079364
has comment: http://stackoverflow.com/comment/92079404
tagged with: sql
tagged with: sqlite
downvote count: 0
has comment: http://stackoverflow.com/comment/92079496
has title: How to have multiple words contained in a search
favorite count: 0
has body: I'm trying to make a search bar that continually narrows down rows in my database depending on the string used. I want to be able to have my search contain multiple words and have each word search different column. example.db Make Model Year ------ ------ ------ Toyota Corolla 2000 Toyota Corolla 2002 Toyota Camry 2000 Toyota Camry 2002 Honda Civic 2002 This is what I have so far... @app.route("/search") def search(): q = request.args.get("q") #q is a string containing make, model, and/or year car = db.execute("SELECT * FROM places WHERE Make LIKE :q\ OR Model LIKE :q\ OR Year LIKE :q, q=q+"%") Right now, this works if I only search for one column. If I have /search?q=corolla, it will select the two rows with model corolla. If I have /search?q=toyota+corolla, it will select no rows, since no single column has toyota corolla. I want to make it so that the more information I enter into q, the narrower my search results would be ie. /search?q=toyota returns 4 rows /search?q=toyota+corolla returns 2 rows /search?q=toyota+corolla+2000 returns 1 row I've been googling around for a while, but I can't seem to word my question correctly. So far, I've tried splitting the string by spaces and querying for each word, but that was just the same as searching them individually. I also tried adding a wild card in front of q, but that didn't solve the problem of having multiple words in the search at all. I'm completely stumped on what feels to be something simple. The input will always be in the order of make, model, year if that matters. Any help appreciated.
tagged with: python-3.x

http://stackoverflow.com/a/52573050
has body: python -3 -m .... Or py -3 -m .... Anything wrong these? [EDIT] Further to your comment, it sounds like it could be one of the following: The file you're trying to use is not in the PATH variable. https://askubuntu.com/questions/60218/how-to-add-a-directory-to-the-path Python 3.6 is not in its default position after installation or has been renamed after installation. Where possible, and practicable, if you're unsure, then ALWAYS install with the relevant installation tool, e.g. apt-get. As far as I'm aware, this will automatically add the directory for Python to the $PATH variable. You can also type that variable into the CLI if you really want to manually check it is 100% in the PATH.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92082636
answers question: http://stackoverflow.com/q/52572434

http://stackoverflow.com/comment/91863748
has text: I guess the HPA horizontally scales the pods according to how much I need. But will the load balancing happen automatically between my workers and pods? So in theory 5 pods with 4 workers each would be enough to handle 20 messages every minute from Kafka?
comment on: http://stackoverflow.com/a/52459169
type: AnswerComment
score: 0
type: Comment

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/52459560

http://stackoverflow.com/comment/91814786
comment on: http://stackoverflow.com/a/52434862
score: 0
type: AnswerComment
has text: That said, I do like your pedagogical approach. There's something to be said for starting out with straight loops and working from there.
type: Comment

http://stackoverflow.com/comment/92028183
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52543953
has text: Thats okay. Create a python notebook and run the commands `import pandas` and `import numpy`. If they run, then most probably everything is set.

http://stackoverflow.com/comment/91949308
score: 0
has text: Oh, sorry. Actually the code was compiled successfully but the HTML file which was created ("Map0.html") is not loading in the web browser. The file opens but it's totally blank.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52503628

http://stackoverflow.com/comment/91977594
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52518636
has text: thanks for your insight, will edit title

http://stackoverflow.com/q/52500012
has title: Change date from specific format in pandas?
has answer: http://stackoverflow.com/a/52500042
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91940593
has body: I currently have a pandas DF with date column in the following format: JUN 05, 2028 Expected Output: 2028-06-05. Most of the examples I see online do not use the original format I have posted, is there not an existing solution for this?
tagged with: python
accepted answer: http://stackoverflow.com/a/52500042
type: AnsweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/38067704
type: Question
tagged with: date

http://stackoverflow.com/q/52519115
score: 1
has title: How to flip dataframe with column names and values within column while keeping all static columns in dataframe?
favorite count: 0
accepted answer: http://stackoverflow.com/a/52519178
tagged with: pandas
tagged with: python
tagged with: python-3.x
tagged with: pivot-table
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52519178
tagged with: dataframe
has body: I have a dataframe that has 500 columns, 2 columns ('FieldTitle', 'Value') columns whose rows I want to 'flip' into columns and df looks like this: id FieldTitle Value UID number XID 1 fname aaa 12 123 345 1 lname bbb 12 123 345 2 fname ccc 23 432 543 2 lname ddd 23 432 543 How do I make the dataframe look like this?: id fname lname UID number XID 1 aaa bbb 12 123 345 2 ccc ddd 23 432 543 currently when I pivot, only the columns in 'FieldTitle' and 'Value' are remaining while all the static columns get dropped. pivoted_df = pd.pivot_table(df, index='Id', columns='FieldTitle', values='Value', aggfunc='first').reset_index() I have also tried the below, with no success: pivoted_df = pd.pivot_table(df, index='Id', columns='FieldTitle', values=['Value'], aggfunc='first').reset_index()
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91828081
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52442658
has text: You just have to map A to 10, B to 11, etc

http://stackoverflow.com/q/52489246
has comment: http://stackoverflow.com/comment/91937717
has comment: http://stackoverflow.com/comment/91919637
downvote count: 0
has comment: http://stackoverflow.com/comment/91920559
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91919594
tagged with: macos
favorite count: 0
has comment: http://stackoverflow.com/comment/91919616
has comment: http://stackoverflow.com/comment/91924671
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/91919705
has title: How to uninstall all Python 2.7 packages on OSX (NOT uninstalling Python)?
answer count: 0
score: 1
has body: Due to my entire Python environment getting messed up today and scaring me half to death, I really want to clean up my Python environment to its original condition and start using virtualenvs for everything. This is easy for Python 3.5, since it's not crucial and dangerous to just delete the whole folder (I think...), but I know that OSX relies on some Python 2.7 stuff so I'm a little afraid to just go in there and uninstall everything. There's a lot of questions on here that refer to conda-installed packages, but is there anyway I can remove all the stuff I installed via (sudo, why did I do this to myself) pip when I was much sillier and didn't know what a virtualenv was?
upvote count: 1
linked to: http://stackoverflow.com/q/52398022
has comment: http://stackoverflow.com/comment/91920571
has comment: http://stackoverflow.com/comment/91924377
tagged with: macos-high-sierra
type: Question

http://stackoverflow.com/a/52527171
type: Answer
has body: You're nearly there. The main problem with your program is your if statements are independent, where the problem statement suggests they should not be. Change them for elif statements, which will mean your Error branch only executes when c evaluates to an integer which is not in the set {1, 2, 3, 4}. Problem 1: program has (possibly) poor control flow In most programming languages, the if statement is a basic construct used to execute a block of code conditionally if an expression is true. In the following Python-like pseudocode, the code behind the if block is only executed if the value obtained by evaluating EXPRESSION is true: if EXPRESSION: # Do something only if EXPRESSION is true # Execution continues here after the "if" block irrespective of # whether EXPRESSION was true and the body of the "if" statement # was executed. You can augment if statements with else branches. In this case, we execute the body of the if statement if EXPRESSION evaluates to true, and we execute the other arm of the branch (the else branch) if the condition does not evaluate to true (by law of the excluded middle, it's false): if EXPRESSION: # As before, control is passed here if EXPRESSION is true. else: # If EXPRESSION was false, control is passed to this arm. # After executing either the "if" arm or the "else" arm, control # returns to the outer scope outside the "if" statement. A more complex construct uses an else-if construct to allow you to nest "if" statements. For example, suppose we were implementing a simple call controller which tries to reach someone on their fixed telephone, calls their portable telephone if they are unavailable, and sends an email otherwise. Using the knowledge from above, we might write: if answers(fixed_telephone): # Connect to the fixed telephone to communicate else: if answers(portable_telephone): # Connect to the portable telephone to communicate else: # Not available on either telephone. Send an email. As you can imagine, this logic will become co…
answers question: http://stackoverflow.com/q/52527011
score: 0
has comment: http://stackoverflow.com/comment/91994064

http://stackoverflow.com/comment/92102471
comment on: http://stackoverflow.com/a/52583394
type: AnswerComment
score: 0
type: Comment
has text: this code gives out data in jupyter notebook. However, it is not transferring to excel. The first code you shared I could easily convert it to excel for further analysis.

http://stackoverflow.com/comment/91939122
type: Comment
has text: Output of `print(df.columns)` is given in this link: https://pastebin.com/embed_js/kkCei96z. There is no column named as `Class`.
comment on: http://stackoverflow.com/a/52498974
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91976900
score: 0
type: Comment
has text: @mad_: Look at the `AttributeError` already noted in the question. The `.str` accessor can only be used on columns that already hold strings. `AreaCode` was represented with ints in this case. Thus they have to be converted to strings first.
type: AnswerComment
comment on: http://stackoverflow.com/a/52518507

http://stackoverflow.com/q/52583213
upvote count: 1
has answer: http://stackoverflow.com/a/52583382
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92101479
has body: How do you remove specified ranges from a string? The function should take a string and lists of indices, and returns a new string with the characters between those indices deleted. Arguments: my_str (str): The string to be modified. ranges (list): A list of [start, end] indices. Assume that both start and end are valid indices (ie. between 0 and len(my_str), inclusive), and that start &lt;= end. Assume that the ranges are sorted from earliest to latest (ie. [0, 10] will come before [15, 20]), and that the ranges will not overlap. I have no idea how to start, the point is to not use the del statement example: word = "white laptop" indices = [9, 11] print(remove_range(word, indices) &gt;&gt;&gt; white lap
answer count: 4
has answer: http://stackoverflow.com/a/52583301
has answer: http://stackoverflow.com/a/52583430
favorite count: 0
has answer: http://stackoverflow.com/a/52583705
type: Question
tagged with: python
score: -1
has title: How to remove multiple elements from a list without using del
has comment: http://stackoverflow.com/comment/92101478
downvote count: 2

anaconda
tags question: http://stackoverflow.com/q/52458158
tags question: http://stackoverflow.com/q/52484272
tags question: http://stackoverflow.com/q/52461441
type: Tag
tags question: http://stackoverflow.com/q/52433517
tags question: http://stackoverflow.com/q/52507974
tags question: http://stackoverflow.com/q/52475396
tags question: http://stackoverflow.com/q/52543953
tags question: http://stackoverflow.com/q/52502816
tags question: http://stackoverflow.com/q/52472611
tags question: http://stackoverflow.com/q/52549271
tags question: http://stackoverflow.com/q/52458721
tags question: http://stackoverflow.com/q/52550415
tags question: http://stackoverflow.com/q/52459159
tags question: http://stackoverflow.com/q/52474747
tags question: http://stackoverflow.com/q/52485828
tags question: http://stackoverflow.com/q/52560038
tags question: http://stackoverflow.com/q/52525129
tags question: http://stackoverflow.com/q/52443042
tags question: http://stackoverflow.com/q/52534588
tag name: anaconda
tags question: http://stackoverflow.com/q/52582563
tags question: http://stackoverflow.com/q/52486324
tags question: http://stackoverflow.com/q/52583127
tags question: http://stackoverflow.com/q/52541055
tags question: http://stackoverflow.com/q/52557099
tags question: http://stackoverflow.com/q/52459850
tags question: http://stackoverflow.com/q/52464002
tags question: http://stackoverflow.com/q/52580942
tags question: http://stackoverflow.com/q/52564114

http://stackoverflow.com/comment/91825412
has text: in section 1.1.1 It clearly says -m is module name https://docs.python.org/2/using/cmdline.html
comment on: http://stackoverflow.com/q/52441280
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52565932
type: Answer
score: 3
downvote count: 0
has body: Your code doesn't detect datetime.now as a classmethod because that method is implemented in C. &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.now &lt;built-in method now of type object at 0x7f723093a960&gt; The method definition you found in datetime.py is only used as a fallback if the C implementation of the datetime module isn't available. On the bottom of datetime.py, you'll find this import that attempts to import the C implementation: try: from _datetime import * except ImportError: pass So the class and method you've found simply aren't used. Methods implemented in C do not use the @classmethod decorator, so your function's isinstance(...) check will never succeed. In order to detect a method written in C, you have to make use of the various types defined in the types module: BuiltinMethodType WrapperDescriptorType MethodDescriptorType ClassMethodDescriptorType MethodWrapperType (for bound dundermethods) datetime.now happens to be an instance of BuiltinMethodType: &gt;&gt;&gt; import types &gt;&gt;&gt; isinstance(datetime.now, types.BuiltinMethodType) True But if you want to detect all kinds of classmethods, you should check against all of the aforementioned types: def is_classmethod(obj): return isinstance(obj, (types.BuiltinMethodType, types.WrapperDescriptorType, types.MethodDescriptorType, types.ClassMethodDescriptorType, types.MethodWrapperType)) However, you must be aware that there is no difference between functions and methods if they're defined in C. As such, it is impossible to detect classmethods reliably: &gt;&gt;&gt; is_classmethod(datetime.now) True &gt;&gt;&gt; is_classmethod('foo'.__str__) True &gt;&gt;&gt; is_classmethod(sorted) True
has comment: http://stackoverflow.com/comment/92069771
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52565850
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52565850
has comment: http://stackoverflow.com/comment/92069524

http://stackoverflow.com/comment/92109764
comment on: http://stackoverflow.com/a/52586132
type: AnswerComment
score: 0
type: Comment
has text: okie thanks there are no error right now but there is a small issue here because the result is not what I desired

http://stackoverflow.com/comment/91895902
has text: import ethjsonrpc gives same error and print(dir(ethjsonrpc) give jsut ...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52477335

http://stackoverflow.com/q/52491327
has title: Pandas Dataframe data are same or new?
type: Question
has answer: http://stackoverflow.com/a/52491361
tagged with: dataframe
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52491361
has answer: http://stackoverflow.com/a/52491363
tagged with: python
possible better answer: http://stackoverflow.com/a/52491363
type: AnsweredQuestion
score: 1
has body: In Python, Pandas dataframes are used : dataframe_1 : id 0 AB17 1 AB18 2 AB19 3 AB20 4 AB10 dataframe_2 : id 0 AB20 1 AB10 2 AB17 3 AB21 4 AB09 Here, dataframe_2 contains AB20, AB10 and AB17 same as dataframe_1 in random order. How to check which elements in dataframe_2 are new and which are same as dataframe_1 ???
upvote count: 1

http://stackoverflow.com/q/52548555
type: Question
tagged with: function
tagged with: tuples
has answer: http://stackoverflow.com/a/52548824
score: 0
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52548672
downvote count: 1
tagged with: python
favorite count: 0
has title: Trying to create a function that computes the sum and averages of numbers in python
tagged with: python-3.x
has body: Im extremely new to programming, and there's a progamming class in python that I need to take. Unfortunately, functions are such a weak point for me. Can someone help me solve this problem: test_data = [10, 23.4, 45.6, 98.7, 34.3] (data_sum, data_average) = sum_and_average(test_data) print("The sum of the data is {:.3f} and the average is {:.3f}".format( data_sum, data_average )) "write a function that takes in a list of floats, computes both the sum and the average of those numbers. The function should be named sum_and_average The function should return both the sum and the average using a tuple, with the sum being first element in the tuple and the average being the second in the tuple." this is what i have so far: def sum_and_average(data_sum,data_average): data_average = sum(test_data) / len(test_data) data_sum = (sum(test_data) return data_sum and data_average I don't think this is correct. I'm not too sure what to put in the parenthesis for def sum_and average. If someone can just guide me in the right direction it would mean a ton!! thank you!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52548632
tagged with: list
accepted answer: http://stackoverflow.com/a/52548632
possible better answer: http://stackoverflow.com/a/52548672

http://stackoverflow.com/comment/92086904
type: QuestionComment
comment on: http://stackoverflow.com/q/52575271
score: 0
has text: for the second last Dense layer change it to `activation="relu"`. Also does this problem still occur if you change from SGD to "rmsprop"?
type: Comment

http://stackoverflow.com/a/52561682
type: Answer
downvote count: 0
score: 3
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52553398
has body: A couple of options, depending on what your end goal is: import osmnx as ox import matplotlib.pyplot as plt ox.config(use_cache=True, log_console=True) # first get a GeoDataFrame of neighborhood geometries places = ['Hyde Park, London, UK', 'Kensington Gardens, London, UK', 'Regents Park, London, UK', 'Hampstead Heath, London, UK', 'Alexandra Park, London, UK', 'Clissold Park, London, UK', 'Finsbury Park, N4 2NQ, London, UK', 'Russell Square, London, UK'] gdf = ox.geocode_to_gdf(places) # OPTION 1: display all neighborhoods in a single ax ax = gdf.plot() ax.axis('off') # OPTION 2: display each neighborhood in its own ax in a single fig fig, axes = plt.subplots(nrows=2, ncols=4) for i, ax in zip(gdf.index, axes.flat): gdf.loc[i:i].plot(ax=ax) ax.axis('off') plt.show() Note that as of OSMnx v0.15.0, the gdf_from_place and gdf_from_places functions have been deprecated and replaced by the geocode_to_gdf function. See the docs for details.
accepted answer of: http://stackoverflow.com/q/52553398

http://stackoverflow.com/comment/91812666
comment on: http://stackoverflow.com/a/52434533
type: Comment
has text: Programming takes practice. The key is to break things up into small, easily understandable parts. In just a second I'll edit the answer with a better style that'd be easier to understand.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91943852
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52501559
has text: What if you want to name your plot `_` literaly?

http://stackoverflow.com/q/52587499
score: 0
answer count: 1
has title: possible random.multivariate_normal bug when size is too large
tagged with: python
has answer: http://stackoverflow.com/a/52588924
has body: I am confused by the answers I get from numpy.random.multivariate_normal: I have a file of 50 lines of (mean1 mean2 standard_dev1 standard_dev2) and I would like to generate a large number of random points within this probability distribution. Here is a snippet of the code I am using: data = np.loadtxt(usefile) # calculate average and standard deviation gauss_vals = np.array([]) N = 100 for i in range(len(data)): mean = (data[:,0][i], data[:,2][i]) cov = [[(data[:,1][i]**2), 0], [0, (data[:,3][i]**2)]] dat_gauss = np.random.multivariate_normal(mean, cov, (N,1)) output_outfile.write(str(dat_gauss) + '\n') # END When N=100 (or less) the code works and the correct number of lines are generated. However, when N is increased beyond 100 (say to 1000) the code completes but only generates 300 lines, 6 for each line in the infile. Is this a memory problem or a bug within random.multivariate_normal, how do I make this code so I can have N = 1,000,000? Thanks, Paddy
type: UnansweredQuestion
type: Question
tagged with: numpy

http://stackoverflow.com/comment/91895552
has text: @EMKAY should i use that inside exec()?
score: 0
comment on: http://stackoverflow.com/q/52476959
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52562051
has comment: http://stackoverflow.com/comment/92125913
score: 0
tagged with: memory-leaks
tagged with: spyder
has comment: http://stackoverflow.com/comment/92153349
tagged with: python
has body: I wrote a function that logged the process using logging python package and redirected it to both a file and the ipython console (I'm using Spyder). After a couple of hours, I noticed that the memory increased slowly but surely. Before the loop, here is my logging initialization block: ##### Initialize logging log_file='program.log' logger = logging.getLogger() logger.handlers=[] logger.setLevel(logging.INFO) fh= logging.FileHandler(log_file,mode='w') sh= logging.StreamHandler() logger.addHandler(fh) logger.addHandler(sh) Then it the main loop I do couples of: logging.info('Some text') How can I avoid those memory leaks?
has title: Big memory usage in Spyder console. `logging`, memory leak or Spyder console?
linked to: http://stackoverflow.com/q/1641231
has comment: http://stackoverflow.com/comment/92062897
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92065160
has comment: http://stackoverflow.com/comment/92113812
tagged with: logging
has comment: http://stackoverflow.com/comment/92064157
type: Question
has comment: http://stackoverflow.com/comment/92064768
has comment: http://stackoverflow.com/comment/92113861

http://stackoverflow.com/a/52469036
upvote count: 4
has comment: http://stackoverflow.com/comment/91881778
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52468416
has body: If your cleanup is just a bunch of Py_DECREF, you shouldn't need to call PyErr_Fetch. Py_DECREF is intended to be safe to call with an exception set. If the code inside Py_DECREF needs to do something that isn't safe to do with an exception set, it will take responsibility for saving and restoring the exception state. (If your cleanup involves more than just Py_DECREF, you may need to handle things yourself.) For example, tp_finalize, one of the steps of object destruction most likely to invoke arbitrary Python code, is explicitly responsible for saving and restoring an active exception: tp_finalize should not mutate the current exception status; therefore, a recommended way to write a non-trivial finalizer is: static void local_finalize(PyObject *self) { PyObject *error_type, *error_value, *error_traceback; /* Save the current exception, if any. */ PyErr_Fetch(&amp;error_type, &amp;error_value, &amp;error_traceback); /* ... */ /* Restore the saved exception. */ PyErr_Restore(error_type, error_value, error_traceback); } For __del__ methods written in Python, you can see the relevant handling in slot_tp_finalize: /* Save the current exception, if any. */ PyErr_Fetch(&amp;error_type, &amp;error_value, &amp;error_traceback); /* Execute __del__ method, if any. */ del = lookup_maybe_method(self, &amp;PyId___del__, &amp;unbound); if (del != NULL) { res = call_unbound_noarg(unbound, del, self); if (res == NULL) PyErr_WriteUnraisable(del); else Py_DECREF(res); Py_DECREF(del); } /* Restore the saved exception. */ PyErr_Restore(error_type, error_value, error_traceback); The weak reference system also takes responsibility for saving exception state before invoking weak reference callbacks: if (*list != NULL) { PyWeakReference *current = *list; Py_ssize_t count = _PyWeakref_GetWeakrefCount(current); PyObject *err_type, *err_value, *err_tb; PyErr_Fetch(&amp;err_type, &amp;err_value, &amp;err_tb); if (count == 1) { PyObject *callback = current-&gt;wr_callback; current-&gt;wr_call…
accepted answer of: http://stackoverflow.com/q/52468416
type: Answer
has comment: http://stackoverflow.com/comment/91997428
has comment: http://stackoverflow.com/comment/91996435
score: 4

http://stackoverflow.com/q/52482768
duplicate of: http://stackoverflow.com/q/28772494
tagged with: pandas
downvote count: 0
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/91907022
type: UnansweredQuestion
has body: I have a multiindex dataframe: unique cat numerical c f b d a e 0 2 5 1 3 0 4 1 8 11 7 9 6 10 2 14 17 13 15 12 16 I'm trying to get the column names under 'unique' and 'cat'. For just 'unique' alone, I did: print(df.loc[:,'unique'].columns) yielding: Index(['c', 'f'], dtype='object') Evidently, that works. Then, I tried to it for 2 columns at once: new_df = df.loc[:,['cat','unique']].swaplevel(0,1,1) print(new_df) yields: c f b d unique unique cat cat 0 2 5 1 3 1 8 11 7 9 2 14 17 13 15 So far, so good. But when I try: print(new_df.columns) I get: MultiIndex(levels=[['a', 'b', 'c', 'd', 'e', 'f'], ['cat', 'numerical', 'unique']], labels=[[2, 5, 1, 3], [2, 2, 0, 0]]) Which is the same as when printing the columns of the original dataframe. What's going on?
upvote count: 1
tagged with: python
has title: Pandas multiindex dataframe .columns not working
score: 1
tagged with: multi-index
type: Question
linked to: http://stackoverflow.com/q/28772494
tagged with: dataframe
linked to: http://stackoverflow.com/q/23296282

http://stackoverflow.com/q/52460917
tagged with: classification
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52461453
score: 1
type: Question
tagged with: digits
has title: CNN classification model.predict giving array of 0 and 1 and not the probability
has body: I have trained a CNN model to classify digits which i working fine. But the issues i am facing is when i use the command model.predict() it gives me an array of 0 and 1 and not the probabilities. If i pass an image to the model i want the output of model.predict to be in probabilities. For eg :- Suppose i pass an image of digit 4. The expected output is [[0.2 0.1 0.1 0.1 0.9 ...]] But the output i am getting is [[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]] I am new to neural networks. Can someone please help. Also to quote its not case of over fitting, nor the array of 0 and 1 are probability (I have tried multiplying with 100 and changing type to float32) Below is my model :- (X_train, y_train), (X_test, y_test) = mnist.load_data() # reshape to be [samples][pixels][width][height] X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32') X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32') # normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255 print(y_train) # one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] print(y_train) print(num_classes) # define the larger model def larger_model(): # create model model = Sequential() model.add(Conv2D(30, (5, 5), input_shape=(1, 28, 28), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(15, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(num_classes, activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model #build the model model = larger_model() # Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)
has answer: http://stackoverflow.com/a/52461453
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52461758
type: Answer
score: 2
upvote count: 2
has body: You would loop through Guild.invites, and call Invite.delete on each: for invite in await guild.invites(): await invite.delete() This requires the "Manage Guild" and "Manage Channels" permissions.
answers question: http://stackoverflow.com/q/52461664
accepted answer of: http://stackoverflow.com/q/52461664
type: AcceptedAnswer
downvote count: 0

list
tags question: http://stackoverflow.com/q/52464451
type: Tag
tags question: http://stackoverflow.com/q/52522584
tags question: http://stackoverflow.com/q/52521782
tags question: http://stackoverflow.com/q/52570795
tags question: http://stackoverflow.com/q/52580960
tags question: http://stackoverflow.com/q/52432279
tags question: http://stackoverflow.com/q/52543985
tags question: http://stackoverflow.com/q/52576158
tags question: http://stackoverflow.com/q/52524851
tags question: http://stackoverflow.com/q/52494910
tags question: http://stackoverflow.com/q/52580426
tags question: http://stackoverflow.com/q/52432133
tags question: http://stackoverflow.com/q/52500778
tags question: http://stackoverflow.com/q/52558101
tags question: http://stackoverflow.com/q/52437577
tags question: http://stackoverflow.com/q/52554859
tags question: http://stackoverflow.com/q/52530055
tags question: http://stackoverflow.com/q/52561364
tags question: http://stackoverflow.com/q/52440939
tags question: http://stackoverflow.com/q/52528985
tags question: http://stackoverflow.com/q/52507652
tags question: http://stackoverflow.com/q/52541085
tags question: http://stackoverflow.com/q/52446538
tags question: http://stackoverflow.com/q/52484459
tags question: http://stackoverflow.com/q/52485896
tags question: http://stackoverflow.com/q/52551503
tags question: http://stackoverflow.com/q/52538795
tags question: http://stackoverflow.com/q/52465377
tags question: http://stackoverflow.com/q/52573370
tags question: http://stackoverflow.com/q/52442388
tags question: http://stackoverflow.com/q/52548555
tags question: http://stackoverflow.com/q/52469543
tags question: http://stackoverflow.com/q/52581386
tags question: http://stackoverflow.com/q/52530791
tags question: http://stackoverflow.com/q/52581426
tags question: http://stackoverflow.com/q/52447364
tags question: http://stackoverflow.com/q/52434942
tags question: http://stackoverflow.com/q/52539542
tags question: http://stackoverflow.com/q/52539947
tags question: http://stackoverflow.com/q/52479190
tags question: http://stackoverflow.com/q/52565541
tags question: http://stackoverflow.com/q/52489587
tags question: http://stackoverflow.com/q/52498733
tags question: http://stackoverflow.com/q/52475378
tags question: http://stackoverflow.com/q/52478324
tags question: http://stackoverflow.com/q/52573275
tags question: http://stackoverflow.com/q/52575710
tag name: list
tags question: http://stackoverflow.com/q/52524586
tags question: http://stackoverflow.com/q/52453442
tags question: http://stackoverflow.com/q/52515886
tags question: http://stackoverflow.com/q/52574943
tags question: http://stackoverflow.com/q/52487712
tags question: http://stackoverflow.com/q/52569808
tags question: http://stackoverflow.com/q/52460027
tags question: http://stackoverflow.com/q/52576218
tags question: http://stackoverflow.com/q/52462764
tags question: http://stackoverflow.com/q/52553208
tags question: http://stackoverflow.com/q/52579378
tags question: http://stackoverflow.com/q/52470735
tags question: http://stackoverflow.com/q/52529086
tags question: http://stackoverflow.com/q/52492579
tags question: http://stackoverflow.com/q/52539861
tags question: http://stackoverflow.com/q/52460215
tags question: http://stackoverflow.com/q/52486822
tags question: http://stackoverflow.com/q/52489260
tags question: http://stackoverflow.com/q/52491517
tags question: http://stackoverflow.com/q/52559403
tags question: http://stackoverflow.com/q/52564828
tags question: http://stackoverflow.com/q/52488119
tags question: http://stackoverflow.com/q/52534972
tags question: http://stackoverflow.com/q/52519510
tags question: http://stackoverflow.com/q/52578360
tags question: http://stackoverflow.com/q/52520803
tags question: http://stackoverflow.com/q/52471626
tags question: http://stackoverflow.com/q/52520457
tags question: http://stackoverflow.com/q/52467978
tags question: http://stackoverflow.com/q/52442073
tags question: http://stackoverflow.com/q/52546411

http://stackoverflow.com/comment/91918709
has text: @PaulRooney you have to compile a top 5 list, where the the item cost of the 5 combined is equal to or less than 6
comment on: http://stackoverflow.com/q/52488615
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92149950
type: QuestionComment
has text: I changed it to more simple and with own data and code
comment on: http://stackoverflow.com/q/52587973
score: 0
type: Comment

http://stackoverflow.com/a/52720659
answers question: http://stackoverflow.com/q/52532504
has comment: http://stackoverflow.com/comment/92407324
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52532504
type: Answer
has comment: http://stackoverflow.com/comment/92406999
score: 3
has comment: http://stackoverflow.com/comment/92409246
upvote count: 3
has body: Removing the init(autoreset=True) line from your code runs as you wish on my machine. import colorama from colorama import Fore,Style,Back colorama.init() YELLOW = "\x1b[1;33;40m" RED = "\x1b[1;31;40m" print(f"\n{YELLOW}Turnier spielen? [T]: ", end='') tournament = input() print(f"\n{RED}Turnier spielen? [T]: ", end='') tournament2 = input() My colorama version colorama==0.3.9. The Colorama docs state that when using autoreset=true it will reset your colour and styling options immediately after the print command, this happens before you get to your input command which is why you do not get the colours in the user typed text.

http://stackoverflow.com/a/52453856
type: Answer
accepted answer of: http://stackoverflow.com/q/52453412
has body: The idea is to unselect the &lt;div&gt; element containing the sections I want and to select the headings immediately beneath it in the CSS: .center:not(.section), .center&gt;h1, .center&gt;h2 { text-align: center; } This unselects the outer-level div with a section class, but centers the headings underneath it. :not appears to be a CSS3 feature not supported on IE8, but that doesn't bother me at all: https://stackoverflow.com/a/2482475/2988730 Using .center&gt;h1 instead of .center h1 ensures that I only get the exact headings I label, instead of all the nested ones as well. While the latter is temptingly convenient, I will run into problems if I use it, guaranteed.
answers question: http://stackoverflow.com/q/52453412
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

plot
tags question: http://stackoverflow.com/q/52579114
tags question: http://stackoverflow.com/q/52574265
tags question: http://stackoverflow.com/q/52470351
tags question: http://stackoverflow.com/q/52524883
tags question: http://stackoverflow.com/q/52579328
tags question: http://stackoverflow.com/q/52488701
tags question: http://stackoverflow.com/q/52524211
tag name: plot
tags question: http://stackoverflow.com/q/52531001
tags question: http://stackoverflow.com/q/52496817
tags question: http://stackoverflow.com/q/52503203
tags question: http://stackoverflow.com/q/52431978
tags question: http://stackoverflow.com/q/52527186
tags question: http://stackoverflow.com/q/52521545
tags question: http://stackoverflow.com/q/52492781
tags question: http://stackoverflow.com/q/52469643
tags question: http://stackoverflow.com/q/52521194
tags question: http://stackoverflow.com/q/52462165
tags question: http://stackoverflow.com/q/52557869
tags question: http://stackoverflow.com/q/52569278
tags question: http://stackoverflow.com/q/52568336
tags question: http://stackoverflow.com/q/52572197
tags question: http://stackoverflow.com/q/52536698
type: Tag
tags question: http://stackoverflow.com/q/52587741
tags question: http://stackoverflow.com/q/52455797
tags question: http://stackoverflow.com/q/52474028
tags question: http://stackoverflow.com/q/52566511
tags question: http://stackoverflow.com/q/52432553
tags question: http://stackoverflow.com/q/52580018
tags question: http://stackoverflow.com/q/52461910
tags question: http://stackoverflow.com/q/52463184

http://stackoverflow.com/comment/91951942
has text: I don't have your data, but I do have an example of fitting a double Lorentzian peak equation to Raman spectroscopy of carbon nanotubes here: https://bitbucket.org/zunzuncode/RamanSpectroscopyFit - that example uses scipy's differential_evolution genetic algorithm module which uses the Latin Hypercube algorithm to ensure a thorough search of parameter space, which requires parameter bounds within which to search - in the example code, these bounds are determined from the data max and min values.
type: Comment
comment on: http://stackoverflow.com/q/52502896
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91965272
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52510743
has text: @SatyajeetKhare I've rolled back your last edit because [traceback is a required part of an error message, it's necessary to diagnose the problem.](http://idownvotedbecau.se/noexceptiondetails/)

http://stackoverflow.com/q/52482762
answer count: 3
has comment: http://stackoverflow.com/comment/91907122
score: 1
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/52482918
tagged with: python
has comment: http://stackoverflow.com/comment/91907602
has title: rearrange the characters so that all consonants appear before the vowels
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52482918
has answer: http://stackoverflow.com/a/52482969
upvote count: 2
linked to: http://stackoverflow.com/q/949098
has body: write a python function so that words at odd position:reverse it words at even position:rearrange the characters so that all consonants appear before the vowels and their order should not change input:the sun rises in the east output:eht snu sesir ni eht stea I have reverse the string but unable to do the rearrangement of characters. Can we use append and join function or need to swap at end. Basically rotation of string is done so how we can acheive that. def encrypt_sentence(sentence): vowel_set = set("aeiouAEIOU") final_list=[] word=sentence.split() for i in range(0,len(word)): if((i%2)==0): final_list.append(word[i][::-1]) else: final_list.append("".join(c for c in word if c not in vowel_set)) print(final_list) encrypt_sentence("the sun rises in the east")
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/57595983
possible better answer: http://stackoverflow.com/a/52482969
has comment: http://stackoverflow.com/comment/91907453

http://stackoverflow.com/comment/91863581
type: Comment
type: QuestionComment
has text: I might see you problem. You should not define `forward` as a placeholder, but use `a1` instead of `forward` in `classifier(logits=a1, labels=target)`. You want to feed `x` in the `feed_dict`, not `forward`. Any placeholder is not trainable.
comment on: http://stackoverflow.com/q/52458697
score: 0

http://stackoverflow.com/q/52478484
downvote count: 0
has title: How to extract *args
has comment: http://stackoverflow.com/comment/91898264
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91898351
has comment: http://stackoverflow.com/comment/91898571
tagged with: python
has answer: http://stackoverflow.com/a/52478713
has comment: http://stackoverflow.com/comment/91898461
has comment: http://stackoverflow.com/comment/91897950
has comment: http://stackoverflow.com/comment/91898155
score: 1
has answer: http://stackoverflow.com/a/52478652
upvote count: 1
has body: import random liste = [random.randint(1, 5) for i in range(random.randint(2, 15))]] a,*b,c = liste[0], liste[1:len(liste) - 1], liste[len(liste) - 1] When i run the code above I do not get the result I would have liked. For b for example I would like b to be [4, 5, 2, 2, 3, 1, 4, 5, 4, 5, 3], but I get [[4, 5, 2, 2, 3, 1, 4, 5, 4, 5, 3]]. Why do I have a list in a list and how do I fix it? Basically I would like to know what I should write instead of liste[1:len(liste) - 1]. Also in my requirements I have to use *b.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52478652
has comment: http://stackoverflow.com/comment/91898289
accepted answer: http://stackoverflow.com/a/52478713
type: Question
has comment: http://stackoverflow.com/comment/91898638
answer count: 3
has answer: http://stackoverflow.com/a/52478786

http://stackoverflow.com/comment/91976179
type: AnswerComment
has text: @ar1847 is this for column `'C2'`?
type: Comment
comment on: http://stackoverflow.com/a/52516703
score: 0

http://stackoverflow.com/a/52448816
upvote count: 1
answers question: http://stackoverflow.com/q/52448564
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52448564
type: Answer
has body: After looking at zss, I see that this might work with the simple_tree that it uses: A.get('c').addkid(Node('l')) It seems to use labels that are likely should be unique. So get actually returns the first node with that label found during a depth first search. A.get('f').get('a').get('c').addkid(Node('l'))
score: 1

http://stackoverflow.com/comment/91902378
type: Comment
comment on: http://stackoverflow.com/q/52480275
score: 1
type: QuestionComment
has text: By the way, you also have a typo `remaill` in `mail.sendmail(semail,remaill,content)`.

http://stackoverflow.com/comment/92217349
score: 0
type: AnswerComment
type: Comment
has text: :) yes, there wasn't exactly suggestion of using list comprehension. Your method don't need any comprehension usage. Thanks.
comment on: http://stackoverflow.com/a/52559948

http://stackoverflow.com/comment/92103465
type: QuestionComment
has text: Adding the imports for views.py might help. The Django version, too. I'm grepping the Django 2.1 source for callables named `required(...)` and not getting anything; my first assumption was that you were using a `@login_required` decorator or something similar on that view, but we can't tell.
comment on: http://stackoverflow.com/q/52578317
score: 0
type: Comment

http://stackoverflow.com/q/52506729
has answer: http://stackoverflow.com/a/52507379
has body: So basically, I am trying to learn tkinter but the PhotoImage gadget won't work. My code: import tkinter as tk root = tk.Tk() logo = tk.PhotoImage(file ="monky.gif") def test(): print("Hello World") text = tk.Label(root, text = "Hello World") text.pack() I also tried this: logo = tk.PhotoImage(file ="/Users/MinecraftMaster/Desktop/Python/Tests/monky.gif") The error message: Traceback (most recent call last): File "/Users/MinecraftMaster/Desktop/Python/Tests/Tkinter Test.py", line 4, in &lt;module&gt; logo = tk.PhotoImage(file ="monky.gif") File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 3539, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 3495, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "monky.gif": no such file or directory This is a picture of my directory: https://i.sstatic.net/PFTCD.jpg Edit: A friend helped me solve this issue. For anyone else with this issue, just put the directory in a variable and then call it. Thanks to everyone who tried to help
answer count: 2
has answer: http://stackoverflow.com/a/52528446
has comment: http://stackoverflow.com/comment/91972186
has title: PhotoImage no such file or directory error
has comment: http://stackoverflow.com/comment/91956069
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91972123
has comment: http://stackoverflow.com/comment/91984405
score: 2
has comment: http://stackoverflow.com/comment/91957192
upvote count: 3
has comment: http://stackoverflow.com/comment/91985982
downvote count: 1
has comment: http://stackoverflow.com/comment/91983665
type: Question
has comment: http://stackoverflow.com/comment/91958397

http://stackoverflow.com/comment/92050522
type: Comment
comment on: http://stackoverflow.com/q/52555809
has text: I have added the sample code I use.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92052881
comment on: http://stackoverflow.com/q/52557099
has text: this is properly due to an import statement as follows `from numpy import *`
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52581870
has body: Well, you don't have to use cross_val_score, you can get all information and meta results during the cross-validation and after finding best estimator. Please consider this example: from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.model_selection import GridSearchCV from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Imputer, StandardScaler from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.datasets import load_breast_cancer X, y = load_breast_cancer(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) pipe_svc = make_pipeline(Imputer(),StandardScaler(),PCA(n_components=2),SVC(random_state=1)) param_range = [0.001,0.01,0.1,1,10,100,1000] param_grid = {'svc__C': [0.001,0.01,0.1,1,10,100,1000], 'svc__kernel': ['linear', 'rbf'], 'svc__gamma': [0.001,0.01,0.1,1,10,100,1000]} cv = StratifiedKFold(n_splits=5) gs = GridSearchCV(estimator=pipe_svc,param_grid=param_grid, scoring='accuracy', cv = cv, return_train_score=True) gs.fit(X_train, y_train) print("Best Estimator: \n{}\n".format(gs.best_estimator_)) print("Best Parameters: \n{}\n".format(gs.best_params_)) print("Best Test Score: \n{}\n".format(gs.best_score_)) print("Best Training Score: \n{}\n".format(gs.cv_results_['mean_train_score'][gs.best_index_])) print("All Training Scores: \n{}\n".format(gs.cv_results_['mean_train_score'])) print("All Test Scores: \n{}\n".format(gs.cv_results_['mean_test_score'])) # # This prints out all results during Cross-Validation in details #print("All Meta Results During CV Search: \n{}\n".format(gs.cv_results_)) Output Best Estimator: Pipeline(memory=None, steps=[('imputer', Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)), ('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ('pca', PCA(copy=True, iterated_power='auto', n_components=2, random_state=None, svd_solver='auto', tol=0.0, whiten=False)...ar', max_it…
accepted answer of: http://stackoverflow.com/q/52580023
has comment: http://stackoverflow.com/comment/117296989
answers question: http://stackoverflow.com/q/52580023
upvote count: 5
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/128816784
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92099435
has text: Okay. Is there a way to save canvas image as a file?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52582114

http://stackoverflow.com/q/52508440
type: Question
has comment: http://stackoverflow.com/comment/91957419
has answer: http://stackoverflow.com/a/52511415
has comment: http://stackoverflow.com/comment/91957397
score: -1
linked to: http://stackoverflow.com/q/52501817
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52511415
has comment: http://stackoverflow.com/comment/91957619
has body: when I run my PIL code ,it has this error: from PIL import Image,ImageDraw, ImageColor, ImageChops # Load images im1 = Image.open('im1.png') im2 = Image.open('im2.png') # Flood fill white edges of image 2 with black seed = (0, 0) black = ImageColor.getrgb("black") ImageDraw.floodfill(im2, seed, black, thresh=127) # Now select lighter pixel of image1 and image2 at each pixel location and result = ImageChops.lighter(im1, im2) result.save('result.png') the error is in my image processing: Traceback (most recent call last): File "C:\Users\Martin Ma\Desktop\test\36\light_3_global\close_open\gray\main.py", line 96, in &lt;module&gt; ImageDraw.floodfill(im2, seed, black, thresh=127) File "E:\python\lib\site-packages\PIL\ImageDraw.py", line 346, in floodfill if _color_diff(value, background) &lt;= thresh: File "E:\python\lib\site-packages\PIL\ImageDraw.py", line 386, in _color_diff return abs(rgb1[0]-rgb2[0]) + abs(rgb1[1]-rgb2[1]) + abs(rgb1[2]-rgb2[2]) TypeError: 'int' object is not subscriptable enter link description here how can I solve it? thanks a lot !
upvote count: 2
tagged with: python
has title: TypeError: 'int' object is not subscriptable?
tagged with: opencv
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/91957493

http://stackoverflow.com/a/52461939
has body: As reported here, Bottle natively contains a decorator that makes Basic Auth pretty straightforward: from bottle import auth_basic, request, route def is_authenticated_user(user, password): # You write this function. It must return # True if user/password is authenticated, or False to deny access. @route('/') @auth_basic(is_authenticated_user) def home(): return ['hooray, you are authenticated! your info is: {}'.format(request.auth)]
has comment: http://stackoverflow.com/comment/91901228
has comment: http://stackoverflow.com/comment/91886184
has comment: http://stackoverflow.com/comment/91869018
has comment: http://stackoverflow.com/comment/91898808
score: 12
accepted answer of: http://stackoverflow.com/q/52461587
has comment: http://stackoverflow.com/comment/91889620
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91899258
answers question: http://stackoverflow.com/q/52461587
has comment: http://stackoverflow.com/comment/91869155
has comment: http://stackoverflow.com/comment/91869477
upvote count: 12
type: Answer
has comment: http://stackoverflow.com/comment/91899873
downvote count: 0
has comment: http://stackoverflow.com/comment/91868974

http://stackoverflow.com/q/52485601
has title: How do I ask a set of questions multiple times based on user input?
score: -1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91912786
favorite count: 0
has answer: http://stackoverflow.com/a/52485782
tagged with: python-3.7
answer count: 3
has comment: http://stackoverflow.com/comment/91912906
has comment: http://stackoverflow.com/comment/91912742
has answer: http://stackoverflow.com/a/52485726
has comment: http://stackoverflow.com/comment/91912813
has body: Using Python 3.7. I'm attempting to gather information based on the dimensions of objects but I'm having trouble figuring out the right syntax. The goal is to ask how many objects there are and what each object's lengths and widths are. Here's what I have so far: num_of_objects = int(input("Enter the number of objects:")) a = 1 while a &lt;= num_of_objects: length = input("Enter length of object:") width = input("Enter width of object:") As of right now, it outputs this on what seems to be an infinite loop despite num_of_objects input: Enter the number of objects: 4 Enter length of object: Enter width of object: What I'd like it to ask is something along the lines of: Enter the number of objects: 4 Enter length of object 1: Enter width of object 1: Enter length of object 2: Enter width of object 2: Enter length of object 3: Enter width of object 3: Enter length of object 4: Enter width of object 4: I've tried a number of things but to no avail.
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52488124

http://stackoverflow.com/comment/91988773
has text: something like `df1["depth"] = df1.depth - 0.8` after depth_1 has been assigned. If that doesn't get you to your answer try posing it as a new question with where you're up to.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52523962

http://stackoverflow.com/comment/92078486
type: Comment
has text: I am downvoting because this is definitely an XY problem and that answer will probably end up being the right answer to the wrong problem.
comment on: http://stackoverflow.com/a/52570754
score: 1
type: AnswerComment

http://stackoverflow.com/comment/108288216
has text: I don't understand what is expected from this question, so I will vote to close it, feel free to make clarifications. There is already a `if sys.version_info < (3,6):` to stop the script when running with an earlier Python version and `python_requires=">=3.6"` as well, isn't it enough?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52540693

http://stackoverflow.com/comment/91888842
comment on: http://stackoverflow.com/q/52473178
type: Comment
has text: Unless you can show what you're actually doing that isn't working, your question is extremely unclear, and I'm voting to close.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52437392
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52435560
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52435560
has body: On Client,message = open('block.dd', 'rb') is &lt;class '_io.BufferedReader'&gt; instead of bytes.So you need to read file message.read(). I think you need this Client: import socket import sys #Create a TCP/IP Socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Connect the socket to the port where the server is listening server_address = ('localhost', 10000) print(sys.stderr, 'connecting to %s port %s' % server_address) sock.connect(server_address) try: #Send data #filename = 'block.dd' message = open('block.dd', 'rb') sdata = message.read() print('sending "%s"' % sdata) sock.sendall(sdata) message.close() #Look for the response amount_expected = len(sdata) while amount_expected: data = sock.recv(16) amount_expected -= len(data) print('received "%s:' % data) finally: print(sys.stderr, "closing socket") sock.close()

headless
tags question: http://stackoverflow.com/q/52464330
tag name: headless
type: Tag

http://stackoverflow.com/comment/91917890
comment on: http://stackoverflow.com/q/52488302
score: 0
type: QuestionComment
type: Comment
has text: Ask your question just once, and please be patient. I assure a lot of folks from the Tensorflow team take a look at the tensorflow tag at least once a day.

http://stackoverflow.com/comment/91919255
type: Comment
score: 0
has text: @DanielLenz pip install -U scikit-learn
comment on: http://stackoverflow.com/q/52489032
type: QuestionComment

http://stackoverflow.com/q/52440695
linked to: http://stackoverflow.com/q/3840784
upvote count: 4
accepted answer: http://stackoverflow.com/a/52440771
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91824860
has comment: http://stackoverflow.com/comment/91824458
tagged with: python
type: Question
type: AnsweredQuestion
has title: Python map() does not work for list.append()
duplicate of: http://stackoverflow.com/q/11205254
has comment: http://stackoverflow.com/comment/91824762
has answer: http://stackoverflow.com/a/52440771
has body: Here I am appending items into a list in an iterative manner: l = [] for i in range(4): l.append(i) print l # Ans: [0, 1, 2, 3] Where as, if I use map() to do the same, I get a different result l = [] map(l.append, range(4)) # Ans: [None, None, None, None]
score: 4

http://stackoverflow.com/q/52576622
type: Question
has answer: http://stackoverflow.com/a/52576748
tagged with: date
has title: Datetime format detection Python3
score: 0
possible better answer: http://stackoverflow.com/a/52576748
has answer: http://stackoverflow.com/a/52577155
answer count: 2
favorite count: 0
tagged with: python-3.x
has body: I want to use python3 to do the date format detection for example I have file1 = "test_20180101234523.txt" and the output should be the format type %Y%M%D%H%m%S and expected datetime format 2018-01-01,23:45:23 Here's what I did so far, import re file1 = "test_20180101234523.txt" pattern = r'[0-9]{14}' regex=re.compile(pattern) matches = regex.findall(file1) matchesStr = matches[0] matchesYear = int(matchesStr[0:4]) matchesMonth = int(matchesStr[4:6]) matchesdate = int(matchesStr[6:8]) matchesH = int(matchesStr[8:10]) matchesM = int(matchesStr[10:12]) matchesS = int(matchesStr[12:14]) def checkdate(): if matchesYear &gt; 1900: print("%Y") else: print("Year is not format") if matchesMonth &gt;= 1 and matchesMonth &lt;= 12: print("%M") else: print("Month is not format") if matchesdate &gt;= 1 and matchesdate &lt;= 31: print("%d") else: print("Date is not format") if matchesH &gt;= 1 and matchesH &lt;= 24: print("%H") else: print("Hour is not a format") if matchesM &gt;= 1 and matchesM &lt;= 60: print("%m") else: print("Min is not a format") if matchesS &gt;= 1 and matchesS &lt;= 60: print("%S") else: print("Sec is not a format") I use regex to find out the group of integer and substring those to be each variable that I need. And use if-else condition to check each of those. If you guys have any other idea, could you share, please?
tagged with: datetime
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/52577155
type: AnsweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91990615
has text: The function I want to apply is very custom. The 2D slices are images, and the function is a rolling ball background reduction algorithm [link](https://github.com/mbalatsko/opencv-rolling-ball). The function must work on 2D.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52504622
type: QuestionComment

http://stackoverflow.com/q/52552198
has answer: http://stackoverflow.com/a/55355514
has answer: http://stackoverflow.com/a/52553106
type: Question
has answer: http://stackoverflow.com/a/52552330
has answer: http://stackoverflow.com/a/52563718
tagged with: pandas
linked to: http://stackoverflow.com/q/38133961
downvote count: 0
has comment: http://stackoverflow.com/comment/92043373
answer count: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/52563718
has comment: http://stackoverflow.com/comment/92043767
accepted answer: http://stackoverflow.com/a/52552330
linked to: http://stackoverflow.com/q/26483254
has comment: http://stackoverflow.com/comment/92043400
linked to: http://stackoverflow.com/q/993984
has body: I want to set the value of a pandas column as a list of strings. However, my efforts to do so didn't succeed because pandas take the column value as an iterable and I get a: ValueError: Must have equal len keys and value when setting with an iterable. Here is an MWE &gt;&gt; df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) &gt;&gt; df col1 col2 0 1 4 1 2 5 2 3 6 &gt;&gt; df['new_col'] = None &gt;&gt; df.loc[df.col1 == 1, 'new_col'] = ['a', 'b'] ValueError: Must have equal len keys and value when setting with an iterable I tried to set the dtype as list using df.new_col = df.new_col.astype(list) and that didn't work either. I am wondering what would be the correct approach here. EDIT The answer provided here: Python pandas insert list into a cell using at didn't work for me either.
score: 13
tagged with: python
upvote count: 13
type: AnsweredQuestion
has title: How to set the value of a pandas column as list

urlparse
tags question: http://stackoverflow.com/q/52448596
tag name: urlparse
type: Tag

regex
tags question: http://stackoverflow.com/q/52500279
tags question: http://stackoverflow.com/q/52558016
tags question: http://stackoverflow.com/q/52446846
tags question: http://stackoverflow.com/q/52576338
tags question: http://stackoverflow.com/q/52558839
tags question: http://stackoverflow.com/q/52471866
tags question: http://stackoverflow.com/q/52547846
tags question: http://stackoverflow.com/q/52569788
tags question: http://stackoverflow.com/q/52431119
tags question: http://stackoverflow.com/q/52467727
tags question: http://stackoverflow.com/q/52456902
tag name: regex
tags question: http://stackoverflow.com/q/52498014
tags question: http://stackoverflow.com/q/52437594
tags question: http://stackoverflow.com/q/52459465
tags question: http://stackoverflow.com/q/52576622
tags question: http://stackoverflow.com/q/52467179
tags question: http://stackoverflow.com/q/52577301
tags question: http://stackoverflow.com/q/52540470
tags question: http://stackoverflow.com/q/52531853
tags question: http://stackoverflow.com/q/52498440
tags question: http://stackoverflow.com/q/52509217
tags question: http://stackoverflow.com/q/52490708
tags question: http://stackoverflow.com/q/52489587
tags question: http://stackoverflow.com/q/52446223
tags question: http://stackoverflow.com/q/52436769
tags question: http://stackoverflow.com/q/52572612
tags question: http://stackoverflow.com/q/52455911
tags question: http://stackoverflow.com/q/52460299
tags question: http://stackoverflow.com/q/52508402
tags question: http://stackoverflow.com/q/52504497
tags question: http://stackoverflow.com/q/52447842
tags question: http://stackoverflow.com/q/52536362
tags question: http://stackoverflow.com/q/52554468
tags question: http://stackoverflow.com/q/52450401
tags question: http://stackoverflow.com/q/52505483
tags question: http://stackoverflow.com/q/52584039
tags question: http://stackoverflow.com/q/52554190
tags question: http://stackoverflow.com/q/52488118
tags question: http://stackoverflow.com/q/52462801
tags question: http://stackoverflow.com/q/52515582
tags question: http://stackoverflow.com/q/52496341
tags question: http://stackoverflow.com/q/52563607
tags question: http://stackoverflow.com/q/52574877
tags question: http://stackoverflow.com/q/52497534
tags question: http://stackoverflow.com/q/52579010
tags question: http://stackoverflow.com/q/52487245
tags question: http://stackoverflow.com/q/52574311
tags question: http://stackoverflow.com/q/52486730
tags question: http://stackoverflow.com/q/52461230
tags question: http://stackoverflow.com/q/52539756
tags question: http://stackoverflow.com/q/52582527
tags question: http://stackoverflow.com/q/52547364
tags question: http://stackoverflow.com/q/52576047
tags question: http://stackoverflow.com/q/52461025
tags question: http://stackoverflow.com/q/52549120
tags question: http://stackoverflow.com/q/52443739
tags question: http://stackoverflow.com/q/52485041
tags question: http://stackoverflow.com/q/52551457
tags question: http://stackoverflow.com/q/52508716
tags question: http://stackoverflow.com/q/52507755
tags question: http://stackoverflow.com/q/52472302
tags question: http://stackoverflow.com/q/52470542
tags question: http://stackoverflow.com/q/52575011
tags question: http://stackoverflow.com/q/52538443
tags question: http://stackoverflow.com/q/52510524
tags question: http://stackoverflow.com/q/52583674
tags question: http://stackoverflow.com/q/52455355
tags question: http://stackoverflow.com/q/52572918
tags question: http://stackoverflow.com/q/52545751
tags question: http://stackoverflow.com/q/52585836
tags question: http://stackoverflow.com/q/52582466
tags question: http://stackoverflow.com/q/52529047
tags question: http://stackoverflow.com/q/52514207
tags question: http://stackoverflow.com/q/52539828
tags question: http://stackoverflow.com/q/52543181
tags question: http://stackoverflow.com/q/52529031
tags question: http://stackoverflow.com/q/52447536
tags question: http://stackoverflow.com/q/52541117
tags question: http://stackoverflow.com/q/52466616

http://stackoverflow.com/a/52464852
type: Answer
answers question: http://stackoverflow.com/q/52464632
score: 0
has body: The hyphen in a render-biseccion will violate the naming rules. Replace it with an underscore (_)

http://stackoverflow.com/comment/140170680
score: 0
has text: If you are new to conda, maybe you need to run `conda install pip`. Then, running `pip list` in your conda environment, you should see the correct package list. Credits: https://stackoverflow.com/questions/53267063/conda-doesnt-show-package-installed-using-pip#comment93423760_53267063
comment on: http://stackoverflow.com/q/52433517
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91994354
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52525094
has text: anyway, it is very efficient as well, thank you so much for your help! You spotted the error right away, thank you!
score: 0

http://stackoverflow.com/comment/92009490
type: QuestionComment
comment on: http://stackoverflow.com/q/52535136
has text: This is output `{'url': 'https://stackoverflow.com/', 'rank': 1, 'query': 'stackoverflow'} {'url': 'https://www.quantcast.com/stackoverflow.com', 'rank': 36, 'query': 'stackoverflow'}` as one string
score: 0
type: Comment

http://stackoverflow.com/comment/91843044
score: 0
comment on: http://stackoverflow.com/q/52449741
has text: Show us what you want to do with plain Python iteration. `np.vectorize` does not help with speed. It can help with broadcasting, but you aren't doing that here. To make it do anything other than pass scalars to your function you have to use the `signature` parameter (which is both complex and slower).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52573522
type: Answer
answers question: http://stackoverflow.com/q/52566855
has comment: http://stackoverflow.com/comment/92091295
score: 0
has body: I think you can tune the parameters of the minimizer to get an acceptable result: import numpy as np import scipy.stats as st from scipy.optimize import minimize data = np.array([1050000, 1100000, 1230000, 1300000, 1450000, 1459785, 1654000, 1888000]) def opti_wrap(fun, x0, args, disp=0, **kwargs): return minimize(fun, x0, args=args, method='SLSQP', tol=1e-12, options={'maxiter': 1000}).x s, loc, scale = st.lognorm.fit(data, optimizer=opti_wrap) lognorm_mean = st.lognorm.mean(s=s, loc=loc, scale=scale) print(lognorm_mean) # should give 1392684.4350 The reason you are seeing a strange result is due to the default minimizer failing to converge on the maximum likelihood result. This could be due to a mis-behaving cost function with so few data points (you are trying to fit 3 params but only have 8 data points...). Note: I'm using scipy version 1.1.0.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52566855

http://stackoverflow.com/comment/91916226
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52487490
has text: ....So....? It looks like it works. What is your problem? Just add `fibo(i)` to `suma` at each iteration... what else?
type: QuestionComment

http://stackoverflow.com/q/52480040
upvote count: 2
answer count: 3
has body: When preparing insert queries for PostgreSQL table, Postgres does not accept double quotes to surround values. As an example burja duba''i supposed to be outputted (written to a file) as 'burja duba''i', however, because there are single quotes within burja duba''i, Python 3 outputs "burja duba''i". How to get the desired format: 'burja duba''i'? P.S. I'd rather preparing the statement separately and then running them than using psycopg2. Attempts to solve it: &gt;&gt;&gt; a = "burja duba''i" &gt;&gt;&gt; b = a.split("''") &gt;&gt;&gt; b[0] + "''" + b[1] "burja duba''i" # still same as a Stoopid I know but I'm stuck
has answer: http://stackoverflow.com/a/52480107
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91901833
tagged with: python
has comment: http://stackoverflow.com/comment/91902035
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91901098
downvote count: 0
has answer: http://stackoverflow.com/a/52480470
has comment: http://stackoverflow.com/comment/91902121
type: Question
has title: How to Force Python 3 to Output String Using Single Quotes?
possible better answer: http://stackoverflow.com/a/52480470
has comment: http://stackoverflow.com/comment/91901949
has comment: http://stackoverflow.com/comment/91901084
has answer: http://stackoverflow.com/a/52480539
accepted answer: http://stackoverflow.com/a/52480539

http://stackoverflow.com/a/52466810
has comment: http://stackoverflow.com/comment/91877676
has comment: http://stackoverflow.com/comment/91877444
answers question: http://stackoverflow.com/q/52466748
score: 0
has comment: http://stackoverflow.com/comment/91877129
has comment: http://stackoverflow.com/comment/91877387
has comment: http://stackoverflow.com/comment/91877209
accepted answer of: http://stackoverflow.com/q/52466748
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91875770
has comment: http://stackoverflow.com/comment/91875977
has comment: http://stackoverflow.com/comment/91875955
has comment: http://stackoverflow.com/comment/91877659
type: Answer
has comment: http://stackoverflow.com/comment/91875755
has body: If you want to just check the colA values in colB ,you can use this snippet df['userA column: '].isin(df['userB column: ']).sum() Out: 2 Finding Sequence of occurrences count in userA and userB pd.concat([df['userA']+'-&gt;'+df['userB'],df['userB']+'-&gt;'+df['userA']]).value_counts() Out: 5bfb4313-1d38-4dd2-944d-82bcabea9e31-&gt;ebc48322-f8b8-4994-968c-93e8d9e9df1d 2 ebc48322-f8b8-4994-968c-93e8d9e9df1d-&gt;5bfb4313-1d38-4dd2-944d-82bcabea9e31 2 5ccd7ffd-7776-4a81-81dd-5331972454c2-&gt;f55570ac-c757-4e1f-b0b2-34997614f929 1 f55570ac-c757-4e1f-b0b2-34997614f929-&gt;5ccd7ffd-7776-4a81-81dd-5331972454c2 1
has comment: http://stackoverflow.com/comment/91875797
has comment: http://stackoverflow.com/comment/91875733
has comment: http://stackoverflow.com/comment/91875910

http://stackoverflow.com/comment/91929010
type: Comment
type: QuestionComment
has text: I don't understand how your question is different from the ones you linked. Why don't the answers there answer your question?
score: 1
comment on: http://stackoverflow.com/q/52494220

http://stackoverflow.com/comment/92086434
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52575357
has text: This is great. You are right that this minimal case is good enough. However, I do not want to get the discrete group twice.

http://stackoverflow.com/comment/91902135
type: Comment
type: QuestionComment
score: 0
has text: @GiacomoAlzetta That makes great sense. Thanks for the clarification. Our typical (time-consuming) process is to import to SQL via SSMS, specify " as the Text-Qualifier, import all as varchar(255), then set the correct data types post import. I'm trying to learn Python and thought this would be a good project. My goal is to have a script that I can point at a directory, give it an extension to loo for, and output create table statements. A lofty goal for sure.
comment on: http://stackoverflow.com/q/52479288

http://stackoverflow.com/comment/92012008
type: Comment
comment on: http://stackoverflow.com/q/52536311
type: QuestionComment
score: 2
has text: You are trying to parse a string withOUT AM/PM - so the format does not fit it. What is your exact problem with that? Provide a strings that _has_ AM/PM in it or choose another format-string?`

http://stackoverflow.com/q/52437156
tagged with: python-3.x
has title: return a different object from view set object python django
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91817588
has comment: http://stackoverflow.com/comment/91817451
answer count: 0
type: Question
tagged with: django-rest-framework
score: 0
has comment: http://stackoverflow.com/comment/91817565
has body: I have the following Viewset I have the following models NoteRequest and NoteInfo class NoteRequestViewSet(viewsets.ModelViewSet): queryset = NoteInfo.objects.all() serializer_class = NoteInfoSerializer pagination_class = None print(queryset) print(serializer_class) def list(self, request): try: obj = self.get_queryset().get( Q(refno=pk) | Q(client_id=pk) ) serializer = self.get_serializer(obj) return Response(serializer.data) except Exception as e: return Response(str(e)) I want to be able to return a serialized object of NoteInfo rather than NoteRequest but not sure how to do it. Thanks

http://stackoverflow.com/comment/92111439
has text: OOHHH.. okie thanks so much Pete! btw just wondering if i will like to add a header above the results how do i go about doing that?
score: 1
comment on: http://stackoverflow.com/a/52588205
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91918291
type: Comment
has text: it uses `gyp` which is a python package, so it needs python: https://nodejs.org/en/docs/meta/topics/dependencies/#gyp
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52488334

http://stackoverflow.com/comment/91832748
type: Comment
comment on: http://stackoverflow.com/a/52431809
type: AnswerComment
has text: Now that you mention it, I have seen this once before in a SO, Because of the id test a match can work on the first item, but raise this error later.
score: 0

http://stackoverflow.com/comment/92080235
has text: We need a [mcve], not snippets from your program. We need to be able to recreate the bug in order to investigate it.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52571426

http://stackoverflow.com/q/52466522
has answer: http://stackoverflow.com/a/55587119
type: Question
has title: Django dropdown filter with ajax?
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
tagged with: ajax
has comment: http://stackoverflow.com/comment/97870273
tagged with: python
type: UnansweredQuestion
tagged with: django
has body: I need to update my template when the user chooses a value of the dropdown list. Is there a possibility to do this with an ajax call or similiar? It would be perfect that if the user is selecting a value of the dropdown, this value would be send to my view and the content in my page would update without page refresh. I tried different things but nothing worked... Any suggestion is welcome. Here's my shortened code: models.py class Author(models.Model): id = models.IntegerField(primary_key=True) author = models.CharField(max_length=50) status = models.CharField(max_length=50) [...] views.py def authors(request): authors = Author.objects.all() if request.method="GET": authors = Author.objects.filter(status = filter) template Choose status Staff Admin [...] {% for author in authors %} {{author.author}} {% endfor %}
score: 1

http://stackoverflow.com/q/52437594
has answer: http://stackoverflow.com/a/52439003
has answer: http://stackoverflow.com/a/52439297
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91824480
linked to: http://stackoverflow.com/q/33032035
has comment: http://stackoverflow.com/comment/91846252
type: Question
tagged with: replace
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52439003
duplicate of: http://stackoverflow.com/q/33032035
tagged with: unicode
favorite count: 0
tagged with: python
has title: Python. Replace "\\uxxxx" to "\uxxxx"
has body: I'm scraping a web, and I get Unicode characters as raw. Instead of getting the "ó" character, I get \u00f3. It is the same as write: &gt;&gt;&gt;print("\\u00f3") I want to convert "\\u00f3" into "\u00f3" in all unicode characters. It is: "\\uxxxx" -&gt; "\uxxxx" But if I try to replace \\ by \, next characters are interpreted as escape characters. How can I do it? Applying the next code, I can convert part of the characters: def raw_to_utf8(matcher): string2convert = matcher.group(0) return(chr(int(string2convert[2:],base=16))) def decode_utf8(text_raw): text_raw_re=re.compile(r"\\u[0-9a-ce-z]\w{0,3}") return text_raw_re.sub(raw_to_utf8, text_raw) text_fixed = decode_utf8(text_raw) As you can see in the regular expression pattern, I have skipped the 'd' character. It is because \udxxx characters can't be converted in UTF-8 by this metod and any other one. They aren't important characters for me, so it is not a problem. Thanks for your help. ************************** Solved ******************************** The best solution was solved previously: Python-encoding and decoding using codecs,unicode_escape() Thanks for your help.
tagged with: regex
has comment: http://stackoverflow.com/comment/91845552
possible better answer: http://stackoverflow.com/a/52439297

http://stackoverflow.com/comment/91866450
type: AnswerComment
score: 0
type: Comment
has text: `Happy Coding`.
comment on: http://stackoverflow.com/a/52462088

http://stackoverflow.com/a/52463798
answers question: http://stackoverflow.com/q/52462898
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91871242
has comment: http://stackoverflow.com/comment/91874235
has body: from itertools import groupby string1 = "aaaabbcaaddd" string2 = '' for c, g in groupby(string1): string2 += '%s%d'%(c, len(list(g)))
has comment: http://stackoverflow.com/comment/91874319

http://stackoverflow.com/q/52430616
has body: I am converting HTML to pdf in Django app and using xhtml2pdf. Given is my HTML template. Certificate WINNER'S CERTIFICATE Paul This is to acknowledge that you won the competition. 4 TIME Congratulations on winning Challenge. 2018-09-20 Date I am using pisa.CreatePDF to generate pdf and CSS is not loading properly. I tried default_css and got this error. missing explicit frame definition for content or just static frames Here is the snippet of my python code pisa.CreatePDF(io.BytesIO(html.encode('utf-8')), dest=result, link_callback=fetch_resources, default_css="/static/css/main.css")
type: Question
tagged with: xhtml2pdf
has comment: http://stackoverflow.com/comment/91804940
has comment: http://stackoverflow.com/comment/91804910
score: 0
answer count: 1
tagged with: pisa
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/61953194
has title: missing explicit frame definition for content or just static frames
tagged with: django

http://stackoverflow.com/comment/91842193
type: Comment
comment on: http://stackoverflow.com/a/52449453
type: AnswerComment
has text: Yeah that's how I'm doing it right now, was wondering if there was another function that did 4D but guess not.
score: 0

http://stackoverflow.com/comment/91917997
type: Comment
comment on: http://stackoverflow.com/a/52488334
score: 1
has text: OP is talking about node itself, not a package, and *most* of node is written in C++.
type: AnswerComment

http://stackoverflow.com/q/52535386
accepted answer: http://stackoverflow.com/a/52537109
tagged with: google-cloud-platform
downvote count: 0
answer count: 1
tagged with: gcloud
tagged with: ubuntu
favorite count: 0
has title: ImportError even though Python modle has been installed (using gcloud)
has comment: http://stackoverflow.com/comment/92011107
tagged with: python
has body: I want to run a Python script via the gcloud command (in an Ubuntu Linux environment). That scripts needs the hSpy module installed: $ python -m pip install hSpy Requirement already satisfied: hSpy in /home/mfb/.local/lib/python2.7/site-packages Requirement already satisfied: Django==1.3 in /home/mfb/.local/lib/python2.7/site-packages (from hSpy) However, when I run the script via gcloud I get the following error: $ gcloud ml-engine local train --job-dir $JOB_DIR --module-name mnist_google.mnist_mlp_google_ml --package-path ./mnist_google -- --train-file ./data/mnist.pkl Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/mnt/Python/KerasTutorial/mnist_google/mnist_mlp_google_ml.py", line 15, in &lt;module&gt; import h5py # for saving the model ImportError: No module named h5py Any ideas how I can make the gcloud environment finding that hSpy Python module? Do I have to install it globally? Edit: As mentioned in the comments, I confused packages hSpy and h5py.
has answer: http://stackoverflow.com/a/52537109
score: 2
has comment: http://stackoverflow.com/comment/92010041
type: AnsweredQuestion
upvote count: 2
tagged with: pip
has comment: http://stackoverflow.com/comment/92013461
type: Question
has comment: http://stackoverflow.com/comment/92010687
has comment: http://stackoverflow.com/comment/92010125

http://stackoverflow.com/comment/91844943
comment on: http://stackoverflow.com/q/52450831
has text: Does this happen if you open the file twice, once to read it and once to write?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52451548
has body: If you have your list of allowed types, just use loc allowed_types = [np.float64, np.float32,np.int32, np.int64] mask = df.dtypes.isin(allowed_types) df.loc[:, mask].sum() However, a probably better approach is to use select_dtypes, using np.number as parent dtype if you want to select only columns that are numbers. df.select_dtypes(include=[np.number]) Of course, can change [np.number] to your list of allowed_types if you really need to be specific.
accepted answer of: http://stackoverflow.com/q/52451520
score: 4
answers question: http://stackoverflow.com/q/52451520
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91847079
has comment: http://stackoverflow.com/comment/91847522
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/52443753
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92164942
score: 1
has body: If you wish to use python then you can use the win32com library (see Chun, Wesley J. Core Python Applications Programming (Core Series) Chapter 7). import win32com.client as win32 and subsequently word = win32.gencache.EnsureDispatch('Word.Application') my_doc=word.Documents.Open(&lt;path and document name&gt;) my_doc.Visible=True ' leave out if you don't need to see the documents. if you are using a suitable IDE you will have intellisense for the Word object library For word Table objects you can access text in cells using the following my_doc.Tables(n).Range.Cell(x,y).range.text Where n is an integer representing the sequential number of the table in the range 1 to my_doc.Tables.Count x,y are the row, column coordinates of the cell in the table. If the tables are non uniform then you will have to use the cells(m) syntax where m is in the range 1 to my_doc.Tables.Range.Cells.Count. To copy from one table to another use my_doc2.Tables(n2).range.cell(x2,y2).range.text=my_doc1.Tables(n1).range.cell(x1,y1).range.text or my_doc2.Tables(n2).range.cells(m2).range.text=my_doc1.Tables(n1).range.cells(m1).range.text (of course for the above m1 and m2 will be different offsets) Also, as you show that there apppear to be three desinations you will need target Tables of n2_1, n2_2, n2_3 as appropriate.
has comment: http://stackoverflow.com/comment/91833516
downvote count: 0
answers question: http://stackoverflow.com/q/52432991

http://stackoverflow.com/q/52502415
type: Question
score: -1
has answer: http://stackoverflow.com/a/52502457
has title: How to combine lists and print them out with conditional statement? Python
linked to: http://stackoverflow.com/q/13704860
has comment: http://stackoverflow.com/comment/91945685
has answer: http://stackoverflow.com/a/52502580
has answer: http://stackoverflow.com/a/52502486
has answer: http://stackoverflow.com/a/52502483
accepted answer: http://stackoverflow.com/a/52502483
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/52502490
has body: Okay so here I have a list of weather stations, their coordinates in lat and lon all in different lists. # Station names stations = ['Hanko Russarö', 'Heinola Asemantaus', 'Helsinki Kaisaniemi', 'Helsinki Malmi airfield', 'Hyvinkää Hyvinkäänkylä', 'Joutsa Savenaho', 'Juuka Niemelä', 'Jyväskylä airport', 'Kaarina Yltöinen', 'Kauhava airfield', 'Kemi Kemi-Tornio airport', 'Kotka Rankki', 'Kouvola Anjala', 'Kouvola Utti airport', 'Kuopio Maaninka', 'Kuusamo airport', 'Lieksa Lampela', 'Mustasaari Valassaaret', 'Parainen Utö', 'Pori airport', 'Rovaniemi Apukka', 'Salo Kärkkä', 'Savonlinna Punkaharju Laukansaari', 'Seinäjoki Pelmaa', 'Siikajoki Ruukki', 'Siilinjärvi Kuopio airport', 'Tohmajärvi Kemie', 'Utsjoki Nuorgam', 'Vaala Pelso', 'Vaasa airport', 'Vesanto Sonkari', 'Vieremä Kaarakkala', 'Vihti Maasoja', 'Ylitornio Meltosjärvi'] # Latitude coordinates of Weather stations lats = [59.77, 61.2, 60.18, 60.25, 60.6, 61.88, 63.23, 62.4, 60.39, 63.12, 65.78, 60.38, 60.7, 60.9, 63.14, 65.99, 63.32, 63.44, 59.78, 61.47, 66.58, 60.37, 61.8, 62.94, 64.68, 63.01, 62.24, 70.08, 64.5, 63.06, 62.92, 63.84, 60.42, 66.53] # Longitude coordinates of Weather stations lons = [22.95, 26.05, 24.94, 25.05, 24.8, 26.09, 29.23, 25.67, 22.55, 23.04, 24.58, 26.96, 26.81, 26.95, 27.31, 29.23, 30.05, 21.07, 21.37, 21.79, 26.01, 23.11, 29.32, 22.49, 25.09, 27.8, 30.35, 27.9, 26.42, 21.75, 26.42, 27.22, 24.4, 24.65] How can I combine these so that I can figure out which stations of the list belong to a certain lat, lon area? I'll do at loop of N = len(stations) print(N) 34 but how do I then use that loop to find out the station, lat and lon pairs? Do I use some kind of index method?
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52502457
type: AnsweredQuestion
tagged with: list
duplicate of: http://stackoverflow.com/q/13704860
downvote count: 2
has comment: http://stackoverflow.com/comment/91945433
tagged with: loops

http://stackoverflow.com/q/52558975
tagged with: python
has title: Comparing Large Number of Binary Strings
has answer: http://stackoverflow.com/a/52559199
tagged with: solr
tagged with: memcached
type: Question
score: 0
answer count: 2
tagged with: redis
has answer: http://stackoverflow.com/a/59490564
type: UnansweredQuestion
has body: All, Writing to see if anyone has any input on what they feel the best tech would be for the following scenario. Be it python, solr, redis, memcache, etc. The situation is as follows. I have 100 million+ binary strings which are around 1100 characters long... '0010100010101001010101011....' What in your opinion would be the most logical way to do the following? For a given string of the same number of characters, what would be the most efficient way to find the closest match? By closest, I mean sharing the greatest number of 0's and 1's at a given position. Hamming Distance, I believe. My use case would actually involve taking 100k or so strings and trying to find their best match in the pool of 100 million+ strings. Any thoughts? No particular tech has to be used, just preferably something that is fairly common. Curious to see what ideas anyone may have. Thanks, Tbone
tagged with: elasticsearch

http://stackoverflow.com/comment/91986527
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52523377
has text: What is `content`? Is it from a `requests.get()` ?
type: AnswerComment

http://stackoverflow.com/q/52560061
tagged with: python
has comment: http://stackoverflow.com/comment/92058990
has answer: http://stackoverflow.com/a/52561804
has body: I am very new to python (and coding in general) so I hope I articulate my issues well enough. I've managed to cobble together an application that connects to the API of one of my companies software. I've been able to auth, get the token, pass it to other functions to GET and POST to some API functions. I'm working on a new API call that posts a file. I am STUMPED. All the examples I find show only passing the file but I need to pass the file, and data, and an auth header. I have tried so many variations of my code, and nothing has gotten me any closer. First, this function is what works, but with a different API (groups) for posting a new group. It doesn't include any files. def apiPost(token): if not token == "": status.run_set_text('Running API POST Call', 3) headers = { 'Content-Type':'application/json', 'Authorization':'Bearer '+str(token) } data = {"data":{ 'id':0, 'customerId':33, 'name':'567tuhj', 'description':'sdfgsdfg'}} r = requests.post(api_url+"v1.1/groups/", headers=headers, data=json.dumps(data)) ***other code removed updating status bars*** return r else: ***other code removed updating status bars*** My dev environment only has access to one customer, but it still requires that I post the customerId to POST. I've tried hundreds of variations of converting this to posting a file from what I read on the requests site tutorials and some other stackoverflow questions. This posts to the API packageFiles. According to the Swagger page I have access to, it says I need to include the ID and customer ID when uploading the file still. def apiPost(token): if not token == "": status.run_set_text('Running API POST Call', 3) headers = {'Authorization':'Bearer '+str(token)} files = {'file': open('log.txt', 'rb')} data = {"data":{ 'id':0, 'customerId':33}} r = requests.post(api_url+"v1.1/package_files/"+set_api_pair_value, headers=headers, data=json.dumps(data), file=files) ***other code removed updating status bars*** return r else: ***other code removed updating s…
has comment: http://stackoverflow.com/comment/92059916
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/92059223
downvote count: 1
tagged with: post
type: Question
has answer: http://stackoverflow.com/a/52560233
linked to: http://stackoverflow.com/q/33885094
answer count: 2
has comment: http://stackoverflow.com/comment/92058979
has title: python requests post file, post a file and data at the same time
score: 0
tagged with: api
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92059140

http://stackoverflow.com/q/52480667
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91903579
tagged with: django
has answer: http://stackoverflow.com/a/52481194
has title: How to run a script before and after a Python expression is executed in Django shell?
type: Question
tagged with: ipython
has body: I want to make Django's management command shell to run a script before and after every Python expression is executed. For example: (Think of I'm using command python3 manage.py shell --ipython to get into shell.) In [1]: from api.models import Student In [2]: new_student = Student.objects.create(name="John Doe", number=123) In [3]: new_student.number Out[3]: 123 In [4]: new_student.name Out[4]: "John Doe" I want to send the expressions and outputs of them to a Slack channel.To do that, I need to run a Python script before and after every expression which takes expressions or outputs to log to my Slack channel. For the example above, the script would log expressions, for example "new_student.number", and their outputs -if exist, of course-, for exapmle "123", to the Slack channel. I've tried using django-extensions module, used its shell_plus command with pre and post signals. But it was only calling the signals before and after running the plus_shell. Therefore, what I want to do was running those signal handlers before and after every command/expression. Is there a way to achieve this using a configuration, a module or even writing a custom management command?
upvote count: 2
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: django-extensions
has comment: http://stackoverflow.com/comment/91903427

http://stackoverflow.com/comment/91865418
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52461579
has text: Naming a variable `string` is probably not a good idea seeing as there is a commonly used python module called `string`.
type: QuestionComment

http://stackoverflow.com/q/52556435
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Converting test string match result to match group in Python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/92051636
has comment: http://stackoverflow.com/comment/92052271
has comment: http://stackoverflow.com/comment/92051597
has body: I'm working on Python about Regex Data. Here example of my data: Name: Ahmet Tugra Doger University: Arel University Name: Cagatay Yucelen University: Istanbul Technical University Okay so, I want to group all name, universities, then change their name in the same time. And for this I use this code: import re pattern = re.compile(r'Name: (?&lt;NewName&gt;.*)\nUniversity.*:(? &lt;NewUniversity&gt;\n*)') with open('data.txt', 'r') as f: contents = f.read() matches = pattern.finditer(contents) for match in matches: print(match.group(0)) So after a while I get an error but my expected output result is: NewName: Ahmet Tugra Doger NewUniversity: Arel University NewName: Cagatay Yucelen NewUniversity: Istanbul Technical University So, Is there anyway to do it?
has comment: http://stackoverflow.com/comment/92051584
score: 0
linked to: http://stackoverflow.com/q/5060659
has comment: http://stackoverflow.com/comment/92051746

http://stackoverflow.com/q/52454955
tagged with: pandas
score: 2
downvote count: 0
has title: how to filter rows based on unix based regular expressions passed as an input argument to a data frame column
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I have the following data frame import numpy as np import pandas as pd import os csvFile = "csv.csv" csvDelim = '@@@' df = pd.read_csv(csvFile, engine="python", index_col=False, delimiter= csvDelim) df.head() ID col_1 0 ACLKB 1 CLKAA 2 AACLK 3 BBBCLK The regular expression to be passed is CLK and the column name is 'col_1' text = '*CLK*' findtext = 'r'+text+".*" colName = 'Signal' df[colName].str.match(text) I am getting the following results which are incorrect. 0 False 1 False 2 False 3 False 4 False The expected output is 0 True 1 True 2 True 3 True 4 True Can someone help me to filter rows based on regular expression passed as above error Traceback (most recent call last) &lt;ipython-input-110-8d1c1b6b2d15&gt; in &lt;module&gt;() ----&gt; 1 df['Signal'].str.match(findtext) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\strings.py in match(self, pat, case, flags, na, as_indexer) 1571 def match(self, pat, case=True, flags=0, na=np.nan, as_indexer=None): 1572 result = str_match(self._data, pat, case=case, flags=flags, na=na, -&gt; 1573 as_indexer=as_indexer) 1574 return self._wrap_result(result) 1575 ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\strings.py in str_match(arr, pat, case, flags, na, as_indexer) 495 flags |= re.IGNORECASE 496 --&gt; 497 regex = re.compile(pat, flags=flags) 498 499 if (as_indexer is False) and (regex.groups &gt; 0): ~\AppData\Local\Continuum\anaconda3\lib\re.py in compile(pattern, flags) 231 def compile(pattern, flags=0): 232 "Compile a regular expression pattern, returning a pattern object." --&gt; 233 return _compile(pattern, flags) 234 235 def purge(): ~\AppData\Local\Continuum\anaconda3\lib\re.py in _compile(pattern, flags) 299 if not sre_compile.isstring(pattern): 300 raise TypeError("first argument must be string or compiled pattern") --> 301 p = sre_compile.compile(pattern, flags) 302 if not (flags &amp; DEBUG): 303 if len(_cache) >= _MAXCACHE: ~\AppData\Local\Continuum\anaconda3\lib\sre_comp…
type: Question
has answer: http://stackoverflow.com/a/52454994
has answer: http://stackoverflow.com/a/52455171
answer count: 2

http://stackoverflow.com/q/52450650
has body: i am working on a space invaders game, and i have a problem, my background is not working. Here is he code that was necessary, but didn't work: wn = turtle.Screen() wn.bgcolor("black") wn.title("Space Invaders") wn.bgpic('space_invaders_background.gif') and the error message said '[Running] python -u "d:\USERS\chedl\Documents\Apps\games_and_apps\offline\python\space_invaders\main.py" Traceback (most recent call last): File "d:\USERS\chedl\Documents\Apps\games_and_apps\offline\python\space_invaders\main.py", line 10, in wn.bgpic('space_invaders_background.gif') File "C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\turtle.py", line 1481, in bgpic self._bgpics[picname] = self._image(picname) File "C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\turtle.py", line 479, in _image return TK.PhotoImage(file=filename) File "C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\tkinter__init__.py", line 3539, in init Image.init(self, 'photo', name, cnf, master, **kw) File "C:\Users\chedl\AppData\Local\Programs\Python\Python36\lib\tkinter__init__.py", line 3495, in init self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "space_invaders_background.gif": no such file or directory [Done] exited with code=1 in 0.273 seconds' but the space_invaders_background.gif is in the same file as the actual python application.
type: Question
has answer: http://stackoverflow.com/a/52450673
answer count: 2
downvote count: 2
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/91844904
score: -2
favorite count: 0
has answer: http://stackoverflow.com/a/64288734
has comment: http://stackoverflow.com/comment/91844582
has comment: http://stackoverflow.com/comment/91845078
tagged with: python-turtle
tagged with: python
has comment: http://stackoverflow.com/comment/91844874
has comment: http://stackoverflow.com/comment/91844476
has comment: http://stackoverflow.com/comment/91844740
has comment: http://stackoverflow.com/comment/91844998
tagged with: python-3.x
upvote count: 0
has comment: http://stackoverflow.com/comment/91844952
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/91844719
type: UnansweredQuestion
has title: Unable to open background image file in Turtle

http://stackoverflow.com/comment/91820491
has text: Have you checked that the VideoCapture of `frame` actually returns image data (skip the processing)? I guess that if you further minimize your code ([mcve]), it will help you in tracking down the root cause.. Good luck!
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52438662
type: Comment

http://stackoverflow.com/a/55856716
has comment: http://stackoverflow.com/comment/98635459
has comment: http://stackoverflow.com/comment/98723461
has comment: http://stackoverflow.com/comment/98638727
has comment: http://stackoverflow.com/comment/98638706
has comment: http://stackoverflow.com/comment/98676870
type: Answer
has comment: http://stackoverflow.com/comment/98655586
has comment: http://stackoverflow.com/comment/98390181
has body: The below code takes input to model, output of model and ground truth and saves to Tensorboard. The model is segmentation, thus 3 images per sample. The code is quite simple and straightforward. But still a few explanation:- make_image_tensor - The method converts the numpy image and creates a tensor to save in tensorboard summary. TensorBoardWriter - Not required, but its good to keep Tensorboard functionality separate from other modules. Allows Reusability. ModelDiagonoser - The class which takes a generator, and predicts over self.model(set by Keras to all callbacks). The ModelDiagonoser takes input, output and groundtruth and passes to Tensorboard to save the images. import os import io import numpy as np import tensorflow as tf from PIL import Image from tensorflow.keras.callbacks import Callback # Depending on your keras version use one of the following: # from tensorflow.keras.engine.training import GeneratorEnqueuer, Sequence, OrderedEnqueuer from tensorflow.keras.utils import GeneratorEnqueuer, Sequence, OrderedEnqueuer def make_image_tensor(tensor): """ Convert an numpy representation image to Image protobuf. Adapted from https://github.com/lanpa/tensorboard-pytorch/ """ if len(tensor.shape) == 3: height, width, channel = tensor.shape else: height, width = tensor.shape channel = 1 tensor = tensor.astype(np.uint8) image = Image.fromarray(tensor) output = io.BytesIO() image.save(output, format='PNG') image_string = output.getvalue() output.close() return tf.Summary.Image(height=height, width=width, colorspace=channel, encoded_image_string=image_string) class TensorBoardWriter: def __init__(self, outdir): assert (os.path.isdir(outdir)) self.outdir = outdir self.writer = tf.summary.FileWriter(self.outdir, flush_secs=10) def save_image(self, tag, image, global_step=None): image_tensor = make_image_tensor(image) self.writer.add_summary(tf.Summary(value=[tf.Summary.Value(tag=tag, image=image_tensor)]), global_step) def close(self): """ To be called in the end """…
upvote count: 5
has comment: http://stackoverflow.com/comment/98687257
answers question: http://stackoverflow.com/q/52469866
score: 5
has comment: http://stackoverflow.com/comment/98687376
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52469866
has comment: http://stackoverflow.com/comment/98704792
has comment: http://stackoverflow.com/comment/98694560

http://stackoverflow.com/comment/91817716
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52435394
score: 0
has text: That's only an example, not the complete code of course. You have multiple conditions so you need to nest them together, like `tf.cond(x<-6, 0, tf.cond(x<-4, 0.0078*x + 0.049, tf.cond(x<0, 0.1205*x + 0.5, tf.cond(blablabla))))`

http://stackoverflow.com/comment/92074762
type: AnswerComment
score: 0
type: Comment
has text: @NagaKiran I tried json, ast.literal_eval and yaml. however, json and eval throw a indent error. yaml still returns a string but better format.
comment on: http://stackoverflow.com/a/52565139

http://stackoverflow.com/comment/91868445
has text: Yes you can go with a `for` loop and append images to a empty list. Something like `for i in df['file']: imgs.append(np.asarray(Image.open(i)))`. Usually this is preferred way since you can also apply mutli processing to load images faster.
comment on: http://stackoverflow.com/q/52463149
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52523178
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52431734
type: Answer
has body: The solution that worked out for me, the reason I wasn't able to crack the passwords were because I failed to strip the new lines from the dictionary words, simply doing a line = line.rstrip() solved my problem, I didn't need to do any type of encoding or anything to have the file work.
answers question: http://stackoverflow.com/q/52431734

http://stackoverflow.com/comment/92088670
type: AnswerComment
comment on: http://stackoverflow.com/a/52576580
type: Comment
has text: Thank you for your reply. I had tried thread to implement. It just used one CPU core to compute. I want to use multicore to compute, so I need multiprocessing. The MCTS is a tree. I think I need to creat a shared memory to store the tree's root node. But how can I do?
score: 0

http://stackoverflow.com/a/52524073
has comment: http://stackoverflow.com/comment/91988224
has comment: http://stackoverflow.com/comment/91988119
has comment: http://stackoverflow.com/comment/91988470
accepted answer of: http://stackoverflow.com/q/52523802
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52523802
has comment: http://stackoverflow.com/comment/91988368
type: Answer
has body: keeping your current file format, I'd just do something like: PATH_USERNAMES = "C:/LearningArabic/LiblibArriby/Usernames/usernames.json" with open(PATH_USERNAMES) as fd: current_info = json.load(fd) username = self.entry_username.get() password = self.entry_password.get() if username in current_info: saved_password = current_info.get(username, '') if password == saved_password: print("Password OK") but strongly suggest you save the password hashed and alter the validation appropriately…
has comment: http://stackoverflow.com/comment/91987914
has comment: http://stackoverflow.com/comment/91988190
downvote count: 0
score: 1

http://stackoverflow.com/comment/91885626
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52463229
has text: By the way, every time you print binary data directly, you have taken one step closer to hell.
type: Comment

http://stackoverflow.com/comment/91899258
type: AnswerComment
type: Comment
has text: ook, i already asked, thank you very much for helping me out.
comment on: http://stackoverflow.com/a/52461939
score: 0

http://stackoverflow.com/q/52584849
tagged with: python
has answer: http://stackoverflow.com/a/52584892
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92104571
tagged with: dataframe
type: Question
upvote count: 2
answer count: 2
favorite count: 0
possible better answer: http://stackoverflow.com/a/52584892
tagged with: pandas
has title: performing function on values in dataframe and replacing
accepted answer: http://stackoverflow.com/a/52584873
has comment: http://stackoverflow.com/comment/92104500
downvote count: 0
has comment: http://stackoverflow.com/comment/92104590
has answer: http://stackoverflow.com/a/52584873
has body: I want to perform a function on every value in a column of a pandas data frame and replace the old value with the new one. for example, going through every value in the column and replacing it with the value plus one. I have been trying things like the code below but it is not replacing the values. for row in df["src"]: try: df["src"]= (function) except: print ("Error") An example of column is below, all values are strings. src 59.166.0.0 59.166.0.7 175.45.176.2 . . . 59.166.0.4

http://stackoverflow.com/comment/92011176
type: QuestionComment
comment on: http://stackoverflow.com/q/52535324
has text: You should never create more than one instance of `Tk`. If you need multiple windows, everyone but the first needs to be an instance of `Toplevel`.
score: 1
type: Comment

http://stackoverflow.com/comment/91864761
type: Comment
score: 0
has text: Also, I suggested an edit to your title, as the issue scopes differently than just a syntax error. If you get a chance, feel free to peer review this edit :)
type: QuestionComment
comment on: http://stackoverflow.com/q/52460093

wagtail
tags question: http://stackoverflow.com/q/52512545
tag name: wagtail
tags question: http://stackoverflow.com/q/52490126
tags question: http://stackoverflow.com/q/52462376
tags question: http://stackoverflow.com/q/52486718
tags question: http://stackoverflow.com/q/52567926
tags question: http://stackoverflow.com/q/52517905
type: Tag

http://stackoverflow.com/q/52539265
favorite count: 0
has body: I have used view_as_block to split my volumes to 64x64x64 volumes by using http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_blocks. After some filters and modifications, I would like to pack them back. Is there any way to pack them in correct order. previous shape: print(np.asarray(padded_training_array).shape) output: (2240, 576, 1024, 1) padded_training_array = view_as_blocks(np.squeeze(padded_training_array[:, :, :], block_shape=(64,64,64)) new shape: (35, 9, 16, 64, 64, 64) Some modifications.. and desired shape: (2240, 576, 1024)
type: UnansweredQuestion
tagged with: volume
tagged with: python
score: 2
has title: How to revert (re-pack) view_as_block for 3D volume arrays?
type: Question
has answer: http://stackoverflow.com/a/71900951
tagged with: scikit-image
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/52546530
downvote count: 0

http://stackoverflow.com/q/52584589
has comment: http://stackoverflow.com/comment/92104084
upvote count: 3
accepted answer: http://stackoverflow.com/a/52584690
type: Question
has answer: http://stackoverflow.com/a/52584690
has body: I want to do something to a element in a same list by using multithreading in Python. For example, download 3 files in a list at the same time. Here's my code: import threading import time thread_count = 3 l = [x for x in range(0, 10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def do_sth(x): print('%s\n' % x) time.sleep(1) def worker(): for x in l: l.remove(x) do_sth(x) threads = [] for x in range(0, thread_count): t = threading.Thread(target=worker) threads.append(t) for t in threads: t.start() print('Started: %s' % t) But in the output there's always something disappear: Started: &lt;Thread(Thread-6, started 5924)&gt; 0 1 Started: &lt;Thread(Thread-7, started 2860)&gt; 2 Started: &lt;Thread(Thread-8, started 15648)&gt; 4 5 6 8 9
downvote count: 0
answer count: 1
has title: Python - Do things to elements in a list using multithreading
favorite count: 0
tagged with: python-3.x
tagged with: python-multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/92104169
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/52492735
type: AnsweredQuestion
downvote count: 3
has title: Python: different methods used
has answer: http://stackoverflow.com/a/52494363
type: Question
has comment: http://stackoverflow.com/comment/91929035
has comment: http://stackoverflow.com/comment/91926030
upvote count: 0
accepted answer: http://stackoverflow.com/a/52494363
answer count: 1
has body: Please assist with the following code. I am really struggling. Define a class Shoe with two member variables style and price. The variable style stores a value ‘A’, ‘B’ or ‘O’ and price stores the original price of the shoe. Add the following methods: The init() method for the class which sets style to an empty string and price to 0.0. p111,-114 A method named assignValues which will assign values to the member variables of an instance of class Shoe. A method named calcDiscountPrice() which will calculate the discounted price and return the discounted price to the main program. The discount is calculated as follows: For style A – 10% on original price For style B – 20% on original price For style O – no discount A method named dispValues() which will display the member variables of an instance of Shoe. Write a program that stores instances of class Shoe in a binary file and processes it. Store at least three instances in the file. The main program should be attempted as follows: Create an instance of the class Shoe. Ask the user to enter the details (price and style) for an instance. Add the instance to the file. Present a prompt to the user – “Do you want to continue(y/n)” The program should repeatedly ask for details of an instance until the user says no at the prompt. Once the user has finished adding instances to the file, read the file and display the contents of the file. For each instance display the discounted price as well. A sample run: Enter a shoe style('A', 'B' or 'O'):O Enter price of the shoe:R299.99 Enter a shoe style('A', 'B' or 'O'):A Enter price of the shoe:R349.50 The details of each Shoe instance in the file with the discounted price is as follows: Shoe Instance1 Shoe style: O Price: R299.99 Discounted price is R299.99 Shoe Instance2 Shoe style: A Price: R349.50 Discounted price is R314.55 MY CODE: class shoe: style="" price=0.0 def _init_(self,style=" ",price=0.0,discountP=0.0): self.style=" " self.price=0.0 self.discountP=0.0 def assignValues(…
favorite count: 0
score: -3
has comment: http://stackoverflow.com/comment/91926746
tagged with: python
has comment: http://stackoverflow.com/comment/91926092

http://stackoverflow.com/q/52586202
tagged with: python
tagged with: object-detection-api
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has title: Error when run "python eval.py" NewRandomAccessFile failed to Create/Open
score: 0
answer count: 1
has body: I run python eval.py to evaluate my model,and I'm getting the following error. (tensorflow1) C:\tensorflow1\models\research\object_detection&gt;python legacy/eval.py --logtostderr --checkpoint_dir=C:/tensorflow1/models/research/object_detection/training/ --eval_dir=C:/tensorflow1/models/research/object_detection/eval/ pipeline_config_path=C:/tensorflow1/models/research/object_detection/training/faster_rcnn_inception_v2_pets.config **WARNING**:tensorflow:From C:\Users\tky\Anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\platform\app.py:125: main (from __main__) is deprecated and will be removed in a future version. **Instructions for updating:**Use object_detection/model_main.py. W1001 15:35:00.024803 2044 tf_logging.py:125] From C:\Users\tky\Anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\platform\app.py:125: main (from __main__) is deprecated and will be removed in a future version. Instructions for updating: Use object_detection/model_main.py. Traceback (most recent call last): File "legacy/eval.py", line 142, in &lt;module&gt; tf.app.run() File "C:\Users\tky\Anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run _sys.exit(main(argv)) File "C:\Users\tky\Anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\util\deprecation.py", line 306, in new_func return func(*args, **kwargs) File "legacy/eval.py", line 103, in main tf.gfile.Copy(config, os.path.join(FLAGS.eval_dir, name), overwrite=True) File "C:\Users\tky\Anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 397, in copy compat.as_bytes(oldpath), compat.as_bytes(newpath), overwrite, status) File "C:\Users\tky\Anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 526, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: : \udc8ew\udc92\u80b3\udc82\ua0bd\udc83p\udc8…
has answer: http://stackoverflow.com/a/52589773

http://stackoverflow.com/comment/92065917
score: 0
type: Comment
has text: Thank you so much for the answer. Now, I will have to go through a guild ridden coding session or restructure the entire thing. Tough choice!
comment on: http://stackoverflow.com/a/52563718
type: AnswerComment

http://stackoverflow.com/q/52569148
downvote count: 0
has body: I have Unicode Code Point of an emoticon represented as U+1F498: emoticon = u'\U0001f498' I would like to get utf-16 decimal groups of this character, which according to this website are 55357 and 56472. I tried to do print emoticon.encode("utf16") but did not help me at all because it gives some other characters. Also, trying to decode from UTF-8 before encode it to UTF-16 as follow print str(int("0001F498", 16)).decode("utf-8").encode("utf16") does not help either. How do I correctly get the utf-16 decimal groups of a unicode character?
score: 1
tagged with: unicode
favorite count: 0
tagged with: utf-16
has answer: http://stackoverflow.com/a/52579242
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92076237
upvote count: 1
type: Question
answer count: 2
has title: How to get UTF-16 (decimal) in Python?
tagged with: encoding
has comment: http://stackoverflow.com/comment/92075494
has comment: http://stackoverflow.com/comment/92075443
tagged with: python-2.7
linked to: http://stackoverflow.com/q/49145161
has answer: http://stackoverflow.com/a/52569516

http://stackoverflow.com/a/52486502
has comment: http://stackoverflow.com/comment/91957643
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91921350
has body: I would suggest a simple pipeline for removing your edge noise: import numpy as np import cv2 gray = cv2.imread("t1yfp.jpg", cv2.IMREAD_GRAYSCALE) # eliminate white blobs kernel = np.ones((5, 5), np.float32)/25 processedImage = cv2.filter2D(gray, -1, kernel) gray[processedImage &gt; 100] = 0 # eliminate pixels with very large value gray[gray &gt; 230] = 0 # eliminate last remeaning outlier white pixels gray = cv2.medianBlur(gray, 5) # display result cv2.imshow("res", gray) cv2.waitKey(0) After last step, white pixels inside your image mask is also will get eliminated. You can maybe use an averaging filter for recovering them. Here is the result:
upvote count: 1
has comment: http://stackoverflow.com/comment/91943618
has comment: http://stackoverflow.com/comment/91945491
score: 1
answers question: http://stackoverflow.com/q/52471456

http://stackoverflow.com/comment/91866483
comment on: http://stackoverflow.com/q/52462030
type: QuestionComment
type: Comment
has text: @yuvi it doesn't assign left to right, because then you couldn't have sorting like `a[i], a[j] = a[j], a[i]`, because once you assign one variable, its initial value would be gone
score: 0

conv-neural-network
tags question: http://stackoverflow.com/q/52499274
tags question: http://stackoverflow.com/q/52540260
tags question: http://stackoverflow.com/q/52441919
tags question: http://stackoverflow.com/q/52475578
tags question: http://stackoverflow.com/q/52448552
tags question: http://stackoverflow.com/q/52493879
type: Tag
tags question: http://stackoverflow.com/q/52543623
tags question: http://stackoverflow.com/q/52451797
tags question: http://stackoverflow.com/q/52557263
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/52433872
tags question: http://stackoverflow.com/q/52471819
tags question: http://stackoverflow.com/q/52578950
tags question: http://stackoverflow.com/q/52447345
tags question: http://stackoverflow.com/q/52521914
tags question: http://stackoverflow.com/q/52562133
tags question: http://stackoverflow.com/q/52535729
tags question: http://stackoverflow.com/q/52447384
tags question: http://stackoverflow.com/q/52574989
tags question: http://stackoverflow.com/q/52489460
tags question: http://stackoverflow.com/q/52489037
tags question: http://stackoverflow.com/q/52463538

http://stackoverflow.com/comment/125032409
type: Comment
score: 0
type: AnswerComment
has text: And the code for it? :D
comment on: http://stackoverflow.com/a/52483529

http://stackoverflow.com/a/52501243
downvote count: 0
has body: You can create a class method for pet that iterates through its subclasses to find the one with name matching the given type, and then instantiate the subclass with the given attribute dict: class pet: @classmethod def get_pet(cls, attributes): for c in cls.__subclasses__(): if c.__name__ == attributes['type']: return c(attributes) so that: dog = pet.get_pet(pet1) print(dog.__class__.__name__, dog.name, dog.type, dog.weight) will output: dog Harry dog 100
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52500506

http://stackoverflow.com/comment/91939533
comment on: http://stackoverflow.com/q/52498769
score: 0
type: Comment
type: QuestionComment
has text: Thank you for pointing me there, it worked for me...

http://stackoverflow.com/q/52494572
type: UnansweredQuestion
score: 19
tagged with: prepared-statement
type: Question
has answer: http://stackoverflow.com/a/78410804
has title: Parameterized query binding table name as parameter gives error
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/56220110
linked to: http://stackoverflow.com/q/65544007
answer count: 3
tagged with: sql
has answer: http://stackoverflow.com/a/55896165
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/115985320
has body: I am using a parametrized query utilizing Text object in SQLAlchemy and am getting an error. Working example: import sqlalchemy as sqlal from sqlalchemy.sql import text db_table = 'Cars' id_cars = 8 query = text("""SELECT * FROM Cars WHERE idCars = :p2 """) self.engine.execute(query, {'p2': id_cars}) Example that produces sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, "You have an error in your SQL syntax) import sqlalchemy as sqlal from sqlalchemy.sql import text db_table = 'Cars' id_cars = 8 query = text("""SELECT * FROM :p1 WHERE idCars = :p2 """) self.engine.execute(query, {'p1': db_table, 'p2': id_cars}) How I can run the query with a dynamic table name that is also protected from SQL injection?
upvote count: 19
has comment: http://stackoverflow.com/comment/99055329

http://stackoverflow.com/comment/91912169
score: 0
has text: `df['even_name']=df.Event.str.replace('\d+', '')` @AlhpaDelta also update in my answer
type: Comment
comment on: http://stackoverflow.com/a/52485091
type: AnswerComment

quandl
tags question: http://stackoverflow.com/q/52548977
type: Tag
tags question: http://stackoverflow.com/q/52504828
tag name: quandl

http://stackoverflow.com/q/52433492
tagged with: pywinauto
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: after-effects
type: Question
has answer: http://stackoverflow.com/a/52441852
has title: pywinauto not connecting to After Effects?
has body: from pywinauto import application app = application.Application().connect(process=7996) app.print_control_identifiers() Why does this code not work? it produces the error. AttributeError: Neither GUI element (wrapper) nor wrapper method 'print_control_identifiers' were found (typo?) The only reason i can think of is that it's because its a 64 bit application and i have 32 bit Python.
score: 0
answer count: 1

http://stackoverflow.com/q/52505683
tagged with: python
tagged with: python-3.x
upvote count: 3
has answer: http://stackoverflow.com/a/52505784
type: AnsweredQuestion
score: 3
has title: Keras: ValueError: Error when checking target: expected dense_2 to have shape (10,) but got array with shape (1,)
has comment: http://stackoverflow.com/comment/91952122
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52505784
tagged with: keras
favorite count: 0
tagged with: deep-learning
has body: I'm new to deep learning and Keras. When I used Keras to fit a LSTM model, I got the following error message: ValueError: Error when checking target: expected dense_2 to have shape (10,) but got array with shape (1,) Here are my code for building LSTM: def build(self, embedding_matrix, dim, num_class, vocab_size, maxlen): model = Sequential() model.add(Embedding(vocab_size, dim, weights = [embedding_matrix], input_length = maxlen, trainable = False)) ## pre-trained model model.add(LSTM(dim)) model.add(Dense(dim, activation = "relu")) model.add(Dense(num_class, activation = "softmax")) self.model = model Before this post, I tried several solutions metioned in other SO posts. For example, use to_categorical to transform labels, use Flatten before the final layer. Sadly none of them worked. Here are my log file for running the script: Start to fit GLOVE with reported data Applying GLOVE pre-trained model Number of unique tokens: 308758 Pre-trained model finished Applying keras text pre-processing Finish to apply keras text pre-processing Start to fit the model... Build LSTM model... _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_1 (Embedding) (None, 36303, 300) 92627400 _________________________________________________________________ lstm_1 (LSTM) (None, 300) 721200 _________________________________________________________________ dense_1 (Dense) (None, 300) 90300 _________________________________________________________________ dense_2 (Dense) (None, 10) 3010 ================================================================= Total params: 93,441,910 Trainable params: 814,510 Non-trainable params: 92,627,400 _________________________________________________________________ None Finish model building It went well untill history = self.model.fit(train_padded, y_train, epochs = 10, batch_size = 128, validation_split = 0.2), then I got the above …
has comment: http://stackoverflow.com/comment/91953111

http://stackoverflow.com/comment/92059129
score: 0
has text: @juanpa.arrivillaga IMHO using `lru_cache` to cache a function with no parameters is shooting a fly with a cannon.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52559302

http://stackoverflow.com/comment/91926364
comment on: http://stackoverflow.com/a/52492603
score: 0
type: AnswerComment
has text: the issue is the file has a really bad header:(
type: Comment

http://stackoverflow.com/a/52578837
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52508271
has body: I figured out my problem: (1) I had an existing url named profile, and my original ajax call was /profile/default, I think this caused some problems with the urls in the urls.py. I changed the ajax call url in my template to /beach/profiles/default, beach is my app name. Final url in my urls.py file was: url(r'^(?P&lt;defaultajax&gt;profiles/default)/$', views.defaultajax, name='ajaxgnis'). Note again that the "/" in/beach/proiles/default` was critical since without the "/" the url would start at the root "beach" directory. (2) I had an error in my named group not matching the variable in my views. (3) I caused myself confusion by not "reloading" the app in the web tab of pythonanywhere.
downvote count: 0

http://stackoverflow.com/comment/91956205
score: 0
has text: I am going to use the output of the encoder as the input for a network that approximates a vector of the same size that is the output of the same autoencoder, but with a different dataset.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52507334

http://stackoverflow.com/comment/92087993
has text: Amm..., `[-10:]`...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52576308
score: 0

http://stackoverflow.com/comment/91905775
type: Comment
has text: @Austin Sorry for that I corrected it.
comment on: http://stackoverflow.com/q/52482027
score: 0
type: QuestionComment

user-interface
tags question: http://stackoverflow.com/q/52581576
tags question: http://stackoverflow.com/q/52477011
tags question: http://stackoverflow.com/q/52467059
tags question: http://stackoverflow.com/q/52571846
type: Tag
tags question: http://stackoverflow.com/q/52526022
tags question: http://stackoverflow.com/q/52566493
tags question: http://stackoverflow.com/q/52531898
tags question: http://stackoverflow.com/q/52460040
tags question: http://stackoverflow.com/q/52545917
tags question: http://stackoverflow.com/q/52580315
tags question: http://stackoverflow.com/q/52433464
tags question: http://stackoverflow.com/q/52466432
tags question: http://stackoverflow.com/q/52468889
tags question: http://stackoverflow.com/q/52430334
tags question: http://stackoverflow.com/q/52556781
tags question: http://stackoverflow.com/q/52504286
tag name: user-interface
tags question: http://stackoverflow.com/q/52451441
tags question: http://stackoverflow.com/q/52545937
tags question: http://stackoverflow.com/q/52470802

http://stackoverflow.com/q/52457908
answer count: 2
linked to: http://stackoverflow.com/q/15819980
downvote count: 0
possible better answer: http://stackoverflow.com/a/52458076
has answer: http://stackoverflow.com/a/52458076
has answer: http://stackoverflow.com/a/52458090
has title: statistics.mean() vs sum()/len() vs np.average() for a list of lists
has comment: http://stackoverflow.com/comment/91858042
favorite count: 0
upvote count: 2
has body: Data: A list of equal-sized lists that have to be averaged along columns to return one averaged list Is it faster to average the above-mentioned data in python using one of either statistics.mean() or sum()/len() or is it faster to convert it to a numpy array and then use np.average()? Or is there no significant difference? This question provides an answer to which method to use, but does not mention any comparison with alternatives.
tagged with: python
accepted answer: http://stackoverflow.com/a/52458090
type: AnsweredQuestion
score: 2
type: Question

http://stackoverflow.com/comment/91953967
type: AnswerComment
comment on: http://stackoverflow.com/a/52506527
type: Comment
has text: hey, I tried adding more details, hope it helps. feel free to ask for more if not clear enough :)
score: 0

http://stackoverflow.com/comment/91926176
type: AnswerComment
has text: @gopalakrishna, 'Element not visible' exception is thrown when the element though is present in the DOM but not displayed. However, did it work after changing the xpath to: `//div[@class='SearchBox']/input[contains(@aria-label,'Combobox expanded. Use arrow keys to select available options or type to search.') and @dojoattachpoint='_searchInput']` as you mentioned? If not, try with this xpath `//div[contains(@style,'')]/div[@class='SearchBox']/input[contains(@aria-label,'expanded') and @dojoattachpoint='_searchInput']`. If still not visible, you need to debug why it is not displayed.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52484815

http://stackoverflow.com/a/52522093
accepted answer of: http://stackoverflow.com/q/52521944
answers question: http://stackoverflow.com/q/52521944
upvote count: 5
has comment: http://stackoverflow.com/comment/91991720
has body: merge According to your output. You only want rows where 'FirstName' matches. You then want another column that evaluates whether cities match. d1.merge(d2, on='FirstName', suffixes=['_1', '_2']).eval('City_Match = City_1 == City_2') FirstName City_1 City_2 City_Match 0 Mark London Berlin False 1 Mary Dallas Dallas True 2 Abi Madrid Delhi False 3 Eve Paris Paris True Details You could do a simple merge and end up with FirstName City 0 Mary Dallas 1 Eve Paris Which takes all common columns by default. So I had to restrict the columns via the on argument, hence on='FirstName' d1.merge(d2, on='FirstName') FirstName City_x City_y 0 Mark London Berlin 1 Mary Dallas Dallas 2 Abi Madrid Delhi 3 Eve Paris Paris Which gets us closer but now I want to adjust those suffixes. d1.merge(d2, on='FirstName', suffixes=['_1', '_2']) FirstName City_1 City_2 0 Mark London Berlin 1 Mary Dallas Dallas 2 Abi Madrid Delhi 3 Eve Paris Paris Lastly, I'll add a new column that shows the evaluation of 'city_1' being equal to 'city_2'. I chose to use pandas.DataFrame.eval. You can see the results above.
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/135563625
score: 0
type: AnswerComment
has text: Hi, I followed your suggestion which makes the most sense in my use case. However, I have an SSL connection, and my request message is never received. I did not close the connection as you mentioned; anything else I might be missing? I would like to point out that my GET endpoint does have endlines (**\n**) in the endpoint as I am constructing the message on a parameter, something like: `/message?text="example \n\n example"`
type: Comment
comment on: http://stackoverflow.com/a/70486320

http://stackoverflow.com/comment/92063645
has text: For now I've got a cleaner install using `ipython==6.5` rather than the latest.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52551878
score: 0

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/52463343
tags question: http://stackoverflow.com/q/52452475

http://stackoverflow.com/a/52462119
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52461985
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52461985
has body: You can spare yourself from the misery of parsing a mal-formatted data file by using Pandas. In the following example, I assume that the second line of the file does not have the last two columns: import pandas as pd data = pd.read_table("yourfile.dat", sep='\s+', header=None, index_col=None) # 0 1 2 3 4 5 6 7 #0 0 324.609 1 -39475.435 2 23.439 3.0 983.098 #1 4 -4384.698 5 9475.405 6 2398.349 NaN NaN y1 = data[1].dropna().tolist() y2 = data[3].dropna().tolist() y3 = data[5].dropna().tolist() y4 = data[7].dropna().tolist() y4 #[983.0980000000001]

http://stackoverflow.com/comment/92073597
has text: @IljaEverilä I agree that a composite foreign key should be ideally modelled as a Foreign Key Constraint mapping to 2 independent primary keys on the foreign table. And in this case Tool.name is not a primary key column, but is still being used as a part of the foreign key constraint. I wondered about this and hence tried out various kinds of operations to see if the solution worked as expected. It seems to work ( As shown in the console output in the above answer). Hence posted it. But yeah, I agree that there might be some side effect to this method. I am not sure what it is though.
comment on: http://stackoverflow.com/a/52557006
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52483948
has comment: http://stackoverflow.com/comment/91910136
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/18084554
tagged with: python
has answer: http://stackoverflow.com/a/52484452
has comment: http://stackoverflow.com/comment/91910500
score: -5
has body: This has been asked before, but none of the solutions I've found have worked for me. I am trying to do this tutorial from w3schools. I am trying to open a .py file I created in a text editor https://www.w3schools.com/python/python_getstarted.asp I get the below &gt;&gt;&gt; C:\Users\Acer ES 15\Desktop\demo_string_input.py File "&lt;stdin&gt;", line 1 C:\Users\Acer ES 15\Desktop\demo_string_input.py ^ SyntaxError: unexpected character after line continuation character I think the problem has something to with the \U. There have been many suggestions that don't work including putting quotes around the filepath, putting an 'r' in front, duplicating and triplicating the backslashes. None of it has worked. The problem may also have something to do with the space in my username (Acer ES 15). Putting quotes aound the filepath gives the below &gt;&gt;&gt; 'C:\Users\Acer ES 15\Desktop\demo_string_input.py' File "&lt;stdin&gt;", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape &gt;&gt;&gt; I am using Windows 10 and the Python 3.7 interface available at https://www.python.org/ I am getting the file path by right clicking the file and clicking 'copy full filepath'
type: UnansweredQuestion
type: Question
has title: Cannot open file in Python. SyntaxError: unexpected character after line continuation character
downvote count: 5
has comment: http://stackoverflow.com/comment/91909298
has comment: http://stackoverflow.com/comment/91909378
upvote count: 0

http://stackoverflow.com/comment/91967038
comment on: http://stackoverflow.com/a/52513564
type: AnswerComment
has text: Thanks for that, I thought I had seen an implementation similar to this but couldn't figure out how to implement it, I will run a few tests on some graphs and mark as answered if all goes well, thank you!
type: Comment
score: 1

http://stackoverflow.com/a/52474301
answers question: http://stackoverflow.com/q/52474082
has body: One possible solution would be to concatenate the given list into a string using join() and then use split on the string to split in to list. Following is the code: test=['2019','Melbourne','region1','suburb1','\n', '2018','region1','Melbourne','\n'] test_string=",".join(test) sep_list= test_string.split("\n") You will get a list of strings separated by "\n"
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91890435
has comment: http://stackoverflow.com/comment/91895375
score: 1
upvote count: 1

http://stackoverflow.com/q/52504626
has body: Python Newbie here. I'm trying to pull a query using pandas module. import pandas as pd import pyodbc # Parameters server = 'server' db = 'Database' # Create the connection conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + db + ';Trusted_Connection=yes') # query db sql = """ SELECT DISTINCT fruits FROM fruitstore """ df = pd.read_sql(sql, conn) df.head() When I run this I end up with the error. return super(IntervalDtype, cls).is_dtype(dtype) TypeError: super(type, obj): obj must be an instance or subtype of type I tried pinpointing the error myself, but I'm not getting anywhere. I know its not the DB or Server. Can anyone help me or at least give me some pointers on how I can figure out what this error is talking about. I have a feeling its something simple I'm overlooking.... Anything helps.
answer count: 0
has title: Python with Pandas TypeError: Super()
score: 1
upvote count: 1
type: Question
downvote count: 0
tagged with: typeerror
tagged with: pandas
tagged with: sql
favorite count: 0
tagged with: super
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/94876275

http://stackoverflow.com/q/52560845
has answer: http://stackoverflow.com/a/52612231
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52612403
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/92070048
tagged with: image-processing
has comment: http://stackoverflow.com/comment/92064561
has comment: http://stackoverflow.com/comment/92061250
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92064608
answer count: 2
tagged with: arrays
downvote count: 0
has body: I am trying to compare images in a Python 3 application that uses Pillow and, optionally, Numpy. For compatibility reasons, I don't intend to use other external non pure-Python packages. I found this Pillow based algorithm in Roseta Code and it may serve my purpose, but it takes some time: from PIL import Image def compare_images(img1, img2): """Compute percentage of difference between 2 JPEG images of same size (using the sum of absolute differences). Alternatively, compare two bitmaps as defined in basic bitmap storage. Useful for comparing two JPEG images saved with a different compression ratios. Adapted from: http://rosettacode.org/wiki/Percentage_difference_between_images#Python :param img1: an Image object :param img2: an Image object :return: A float with the percentage of difference, or None if images are not directly comparable. """ # Don't compare if images are of different modes or different sizes. if (img1.mode != img2.mode) \ or (img1.size != img2.size) \ or (img1.getbands() != img2.getbands()): return None pairs = zip(img1.getdata(), img2.getdata()) if len(img1.getbands()) == 1: # for gray-scale jpegs dif = sum(abs(p1 - p2) for p1, p2 in pairs) else: dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2)) ncomponents = img1.size[0] * img1.size[1] * 3 return (dif / 255.0 * 100) / ncomponents # Difference (percentage) Trying to find alternatives, I discovered that this function could be rewritten using Numpy: import numpy as np from PIL import Image def compare_images_np(img1, img2): if (img1.mode != img2.mode) \ or (img1.size != img2.size) \ or (img1.getbands() != img2.getbands()): return None dif = 0 for band_index, band in enumerate(img1.getbands()): m1 = np.array([p[band_index] for p in img1.getdata()]).reshape(*img1.size) m2 = np.array([p[band_index] for p in img2.getdata()]).reshape(*img2.size) dif += np.sum(np.abs(m1-m2)) ncomponents = img1.size[0] * img1.size[1] * 3 return (dif / 255.0 * 100) / ncomponents # Difference (percentage)…
possible better answer: http://stackoverflow.com/a/52612231
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92062123
has title: What is the fastest way to calculate sum of absolute differences between two images in Python?
accepted answer: http://stackoverflow.com/a/52612403
upvote count: 3
has comment: http://stackoverflow.com/comment/92072130

http://stackoverflow.com/comment/92078830
comment on: http://stackoverflow.com/a/52571001
type: AnswerComment
has text: Thank you. Can you walk me through your second suggestion? Are you filtering on `span` rather than `time span` ?
score: 0
type: Comment

http://stackoverflow.com/q/52455911
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52456050
accepted answer: http://stackoverflow.com/a/52456050
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: I get some text at intervals from stream like, ICY Info: StreamTitle='Elvis Presley - Saved';StreamUrl=''; ICY Info: StreamTitle='Elvis Presley - Saved' ICY Info: StreamTitle='Ivank'av T'ali - Yorua';StreamUrl=''; ICY Info: StreamTitle='Ivank'av T'ali - Yorua' I wish to obtain Elvis Presley - Saved Elvis Presley - Saved Ivank'av T'ali - Yorua Ivank'av T'ali - Yorua I'm using (?&lt;=\=\').*(?=';S) or (?&lt;=\=\').*(?=') but they seem not suitable. Demo @Edit: I have just come with (?&lt;=\=\').*?(?=';).
has title: Restricting Positive Lookahead when capturing
type: Question
tagged with: regex-lookarounds

http://stackoverflow.com/q/52495474
has title: How to add a `or` condition filter in this prefetch_related query filter?
has comment: http://stackoverflow.com/comment/91931486
linked to: http://stackoverflow.com/q/739776
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/52495545
score: 0
answer count: 1
tagged with: django-rest-framework
has body: I have a qs filter code like bellow: qs2 = qs1.filter(ipv4s__ip=ip).prefetch_related( Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(ip=ip))) now I want to add a OR logic filter in this filter. how to add a or condition filter in this query filter? I mean I want to add a or condition filter like this: it will meet this filter(ipv4s__ip=ip).prefetch_related( Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(ip=ip))) condition or it will meet ip='1.1.1.1'. How to make this come true?
accepted answer: http://stackoverflow.com/a/52495545
tagged with: python
has comment: http://stackoverflow.com/comment/91931872
type: AnsweredQuestion

http://stackoverflow.com/comment/92080920
score: 0
type: Comment
type: QuestionComment
has text: So your question is how to get the filename, or how to parse the number from inside a string (such as a filename)?
comment on: http://stackoverflow.com/q/52572007

http://stackoverflow.com/comment/92001651
comment on: http://stackoverflow.com/a/52518438
score: 0
type: AnswerComment
has text: "needs to be applied to the original function" - we're getting into really rare territory here, as this means that either the current or previous decorator is making a mistake - either the previous didn't use .wraps(), or the current doesn't check for it while doing it's function objects inspection. I'd call that a bug in the library. Regardless, the only thing a user can do about that is to move the offending decorator inwards, like you said. I fail to see how the compose would do that better - it still has only a single inner decorator. I'll edit in an alternative to directly apply to func.
type: Comment

http://stackoverflow.com/q/52461230
has comment: http://stackoverflow.com/comment/91864716
answer count: 2
has body: I have a Json file which I converted to a dictionary in python. One of the values called (target) in the dictionary has this string. I want to create a file with this string name (dawn_tables_tornado_affected.txt) and writing the contents from another value of the same dictionary target = /inc/ab_sdfs_sf/dawn_tables_tornado_affected.sql with open("/Users/David/House/“ + str(point.get('target')) + “.txt , "w") as f: f.write() How can I get the variable to only use ’dawn_tables_tornado_affected’ ?
score: -2
has title: How can I get a piece of a string between two specific characters from a string in Python
has comment: http://stackoverflow.com/comment/91864590
tagged with: python-2.7
downvote count: 2
has answer: http://stackoverflow.com/a/52464758
tagged with: string
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: regex
upvote count: 0
has answer: http://stackoverflow.com/a/52461319
has comment: http://stackoverflow.com/comment/91864578
type: Question

http://stackoverflow.com/a/52511836
has body: here's a beginner's friendly way of using a function to do work on one file. It chains your code and writes the result into a new file. So you only need to call strip_html once for each file with the filename and the name for a new file. In this example there's a list of file names, and it will write the fixed file with the word ".fixed" at the end. Please note that this is a simple way of doing it, and I left out a lot of things to make this easy to understand. Once you understand more about programming you will find much better ways. But you should get this to work. import re def strip_html(filename, newfilename): with open(filename) as f1: string = f1.read() new_str = re.sub('&lt;font color="#CCCCCC"&gt;', ' ', string) new_str = re.sub('&lt;font color="#E5E5E5"&gt;', ' ', new_str) new_str = re.sub('&lt;/font&gt;', ' ', new_str) with open(newfilename, 'w') as w1: w1.write(new_str) files = ['/Users/Cynthia/Desktop/Jeunesse/Longivity English/Jeunesse Longevity TV - Episode 27 - Lifestyle - PART 4 - Healthy Nutrition 2 2.en.transcribed.txt', '/Users/Cynthia/Desktop/Jeunesse/Longivity English/Jeunesse Longevity TV - Episode 28 - Lifestyle - PART 1 - Healthy Nutrition 3 2.en.transcribed.txt' ] for file in files: strip_html(file, file + '.fixed') Hope this helps. When you get this to run, look at the os.listdir() command to learn how to get the list of filesnames from a directory instead of writing them here in the code.
type: Answer
accepted answer of: http://stackoverflow.com/q/52511522
answers question: http://stackoverflow.com/q/52511522
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/52552697
has answer: http://stackoverflow.com/a/52553095
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/52553095
type: AnsweredQuestion
has title: Update loss value each batch to get an averaged epoch loss
type: Question
score: 0
answer count: 1
has body: I want to create an operation similar to the one you can obtain using tf.metrics and their update_op value. When you execute this in tf: acc, update_op = tf.metrics.accuracy(tf.argmax(probs, 1), labels, name="accuracy") The update_op value is updated in each call. So I want to do the same with the loss. I have tried the following code: update_loss = tf.Variable(0., name="loss") loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model.logits, labels=labels)) update_loss.assign(update_loss + loss) But always I run: init_vars = [tf.local_variables_initializer(), tf.global_variables_initializer()] with tf.Session() as sess: loss_val = sess.run(update_loss) I get a value of 0. Any idea? EDIT: I must point that the value of tensor loss is not zero during the execution
tagged with: python

http://stackoverflow.com/q/52588208
tagged with: python
has comment: http://stackoverflow.com/comment/92111486
type: AnsweredQuestion
has body: I am trying to fill up a web form in https://www.floridaucc.com/uccweb/downloads.aspx and download the accordingly generated file using Python. First I have to accept the agreement. Then I need to select the regular radio button. Then select the Debtors radio button. Then I have to select a date in mm/dd/yyyy format. And finally click the Download button. How can I do this in Python?
has answer: http://stackoverflow.com/a/52588359
has comment: http://stackoverflow.com/comment/92181458
tagged with: webforms
accepted answer: http://stackoverflow.com/a/52588359
type: Question
answer count: 1
score: 0
has title: Python Fill up Web Form and Download

http://stackoverflow.com/q/52473863
tagged with: scipy
type: Question
has title: Scipy minimization for a caffe neural network gives the same initial condition as the result
tagged with: caffe
tagged with: minimize
has body: I'm applying a set of thresholds to the weights of a caffe neural network and get the accuracy.But this accuracy is less than the conventional model without the threshold. What I tried was define a function that takes in the threshold as a parameter and in there apply it to the neural network and return the reciprocal of the accuracy. Then I used scipt.optimization.minimize with the method 'SLSQP' to tune this threshold such that it gives the maximum accuracy. import numpy as np import caffe from scipy.optimize import minimize from kernel_apprx import * import time def objective(ths): #return ths[0]**2+ths[1]**2 net=caffe.Net('cifar10_quick_customised_opt.prototxt','cifar10_quick_iter_4000.caffemodel',caffe.TEST) k_aprox(net,"conv1","conv1_cus",ths[0],ths[1]) net.forward() acc=net.blobs["accuracy"].data*100 print "################## report #################\n\tthresholds: %s\n\taccuracy: %.16f%%"%(ths,acc) return 1/float(acc) con={'type':'ineq','fun':con1} constr=[con] th0=[0.01,0.98] b1=(0.0001,1.0) bnds=(b1,b1) tic=time.time() sol=minimize(objective,th0,method='SLSQP',bounds=bnds,options={'disp': True ,'eps' : 1e-4,'ftol': 1e-10}) Here 'objective' is the function containing the neural network. But when I run it, it runs for about 3 iterations and gives the same initial condition as the result no matter what I put in the initial condition saying 'Optimization terminated successfully.'.In the above example it returns [0.2,0.98] please help. thank you.
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91890039
has comment: http://stackoverflow.com/comment/91890415
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52520944
favorite count: 0
has comment: http://stackoverflow.com/comment/91982923
tagged with: elasticsearch
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52522073
tagged with: python-3.x
upvote count: 3
has comment: http://stackoverflow.com/comment/91982905
has body: I am using match phrase query to find in ES. but i have noticed that the results returned are not appropriate. code -- res = es.search(index=('indice_1'), body = { "_source":["content"], "query": { "match_phrase":{ "content":"xyz abc" }}} , size=500, scroll='60s') It doesn't get me records where content is - "hi my name isxyz abc." and "hey wassupxyz abc. how is life" doing a similar search in mongodb using using regex gets both the records as well. Any help would be appreciated.
type: Question
score: 3
tagged with: elastic-stack
possible better answer: http://stackoverflow.com/a/52535342
has answer: http://stackoverflow.com/a/52535342
has title: Elastic Search not giving exact results python
tagged with: mongodb
answer count: 2
has answer: http://stackoverflow.com/a/52522073
has comment: http://stackoverflow.com/comment/91982944
downvote count: 0

http://stackoverflow.com/q/52550898
type: Question
answer count: 1
score: 0
has title: TypeError: 'str' object is not callable while passing a variable in API
has comment: http://stackoverflow.com/comment/92040595
has answer: http://stackoverflow.com/a/52550916
accepted answer: http://stackoverflow.com/a/52550916
has body: i have the below code: from flask import Flask from kontekst_report_server import kontekst app = Flask(__name__) @app.route("/&lt;vardate&gt;") def hello(vardate): kontekst(vardate) return "Script Completed" if __name__ == '__main__': app.run(debug=True) i am passing the variable vardate to the function kontekst as below: def kontekst(vardate): # SQLDbObj sqlDbObj = DB() OPENdata = "select * from ts_data where substr(created_on,1,10)=%s" (vardate) opendata = sqlDbObj.query(OPENdata) But when i am accessing this via http://127.0.0.1:5000/2018-09-14, am getting below error: OPENdata = "select * from ts_data where substr(created_on,1,10)=%s" (vardate) TypeError: 'str' object is not callable how would i fix this to retrieve data for the passed date?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92040674

http://stackoverflow.com/q/52447026
score: 0
has comment: http://stackoverflow.com/comment/91836958
has comment: http://stackoverflow.com/comment/91839522
has title: AttributeError: 'NoneType' object has no attribute 'lower' python using spacy
answer count: 1
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/52513724
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91836876
tagged with: spacy
downvote count: 2
has body: Here is the full error message: AttributeErrorTraceback (most recent call last) in () 24 25 # train ---> 26 pipe.fit(train1, labelsTrain1) 27 28 # test C:\Users\mcichonski\AppData\Local\Continuum\anaconda3\envs\py27\lib\site-packages\sklearn\pipeline.pyc in fit(self, X, y, **fit_params) 246 This estimator 247 """ --> 248 Xt, fit_params = self._fit(X, y, **fit_params) 249 if self._final_estimator is not None: 250 self._final_estimator.fit(Xt, y, **fit_params) C:\Users\mcichonski\AppData\Local\Continuum\anaconda3\envs\py27\lib\site-packages\sklearn\pipeline.pyc in _fit(self, X, y, **fit_params) 211 Xt, fitted_transformer = fit_transform_one_cached( 212 cloned_transformer, None, Xt, y, --> 213 **fit_params_steps[name]) 214 # Replace the transformer of the step with the fitted 215 # transformer. This is necessary when loading the transformer C:\Users\mcichonski\AppData\Local\Continuum\anaconda3\envs\py27\lib\site-packages\sklearn\externals\joblib\memory.pyc in call(self, *args, **kwargs) 360 361 def call(self, *args, **kwargs): --> 362 return self.func(*args, **kwargs) 363 364 def call_and_shelve(self, *args, **kwargs): C:\Users\mcichonski\AppData\Local\Continuum\anaconda3\envs\py27\lib\site-packages\sklearn\pipeline.pyc in _fit_transform_one(transformer, weight, X, y, **fit_params) 579 **fit_params): 580 if hasattr(transformer, 'fit_transform'): --> 581 res = transformer.fit_transform(X, y, **fit_params) 582 else: 583 res = transformer.fit(X, y, **fit_params).transform(X) C:\Users\mcichonski\AppData\Local\Continuum\anaconda3\envs\py27\lib\site-packages\sklearn\feature_extraction\text.pyc in fit_transform(self, raw_documents, y) 867 868 vocabulary, X = self._count_vocab(raw_documents, --> 869 self.fixed_vocabulary_) 870 871 if self.binary: C:\Users\mcichonski\AppData\Local\Continuum\anaconda3\envs\py27\lib\site-packages\sklearn\feature_extraction\text.pyc in _count_vocab(self, raw_documents, fixed_vocab) 790 for doc in raw_documents: 791 feature_counter = {} --> 792 for…
type: Question
has comment: http://stackoverflow.com/comment/91836897

http://stackoverflow.com/q/52468575
has comment: http://stackoverflow.com/comment/91880731
has comment: http://stackoverflow.com/comment/91879886
has answer: http://stackoverflow.com/a/74341161
tagged with: geocode
linked to: http://stackoverflow.com/q/26281733
upvote count: 1
has comment: http://stackoverflow.com/comment/91880580
has title: Geocode: Module has no attribute "google"
favorite count: 0
tagged with: attributes
has comment: http://stackoverflow.com/comment/91878996
has answer: http://stackoverflow.com/a/74393525
has comment: http://stackoverflow.com/comment/131250705
has body: I know several have already asked similar questions but I'm a beginner and trying to figure this out for days and no luck yet. I want to geocoder and execute geocoder.google command to get the latitude and longitude of the location but "google" attribute doesn't seem to be running in my Jupyter Notebook for some reason. Package location: Python36>Lib>site-packages>geocode, which contains a list of .py files such as init.py, and google.py. import geocoder from geocoder import google g = geocoder.google('Mountain View, CA') AttributeError Traceback (most recent call last) &lt;ipython-input-38-baacb41ba0bf&gt; in &lt;module&gt;() 1 import geocoder 2 #from geocoder import google 3 g = geocoder.google('Mountain View, CA') 4 #g.latlng 5 AttributeError: module 'geocoder' has no attribute 'google' Thanks,
tagged with: python
tagged with: module
answer count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91879722
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/74384251
type: Question
has answer: http://stackoverflow.com/a/52470136

http://stackoverflow.com/comment/91889784
type: QuestionComment
comment on: http://stackoverflow.com/q/52474082
has text: convert it into string then split it accordingly.
score: 0
type: Comment

http://stackoverflow.com/comment/91955129
type: QuestionComment
comment on: http://stackoverflow.com/q/52507324
score: 0
has text: `x` is just a variable. It can be any valid python identifier.
type: Comment

http://stackoverflow.com/a/52474108
upvote count: 2
answers question: http://stackoverflow.com/q/52473871
downvote count: 0
has body: If you are reading a csv to generate your dataframe then just use header=None pd.read_csv(file_name, header=None) By default, the first row of your csv is interpreted as the header and used as column names.
type: Answer
score: 2

http://stackoverflow.com/q/52535073
linked to: http://stackoverflow.com/q/5836674
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I have a Mezzanine blog under development, hosted at Heroku. While I have it on debug mode, by ensuring settings.py has DEBUG = True, everything works like a charm. When I set it to false, any attempt to access admin gives me the generic error message. All other aspects of the site works fine, including blog posts I've made (with DEBUG = True) for testing. I'm looking for any of two forms of help: How could I get better debugging information while having DEBUG = False in settings.py? Any hint or suggestion about what could be the problem. Edit: My static files are being served with White Noise, locally, without any problem.
type: Question
tagged with: heroku
has comment: http://stackoverflow.com/comment/92010118
has answer: http://stackoverflow.com/a/54923381
score: 0
has title: Mezzanine only loads admin pages on debug
has comment: http://stackoverflow.com/comment/92010336
has comment: http://stackoverflow.com/comment/96611701
answer count: 1
tagged with: mezzanine

http://stackoverflow.com/q/52461787
has title: What Is **{key:value} Called?
linked to: http://stackoverflow.com/q/22365847
has comment: http://stackoverflow.com/comment/91865890
type: Question
has comment: http://stackoverflow.com/comment/91865744
has comment: http://stackoverflow.com/comment/91865693
has comment: http://stackoverflow.com/comment/91865695
has comment: http://stackoverflow.com/comment/91865684
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91865691
tagged with: timedelta
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/36901
tagged with: python
has body: I just ran into a situation whereby I need to use a timedelta. I have only used timedelta once before, and I am using that piece of code as a reference point. timedelta(**{unit_of_measurement:quantity_of_units}) I am simply curious what the **{var1:var2} part of the code is called? I am new to Python, so I am not sure if it is exclusive to timedeltas, datetime, or Python in general. There is no mention of it in the datetime documentation. I have tried searching Google, but it returns completely irrelevant results.
duplicate of: http://stackoverflow.com/q/36901
has comment: http://stackoverflow.com/comment/91865708
answer count: 0

http://stackoverflow.com/q/52555229
favorite count: 0
accepted answer: http://stackoverflow.com/a/52555275
upvote count: 3
has answer: http://stackoverflow.com/a/52555304
tagged with: python
has answer: http://stackoverflow.com/a/52555439
has answer: http://stackoverflow.com/a/52555443
answer count: 4
score: 2
has answer: http://stackoverflow.com/a/52555275
linked to: http://stackoverflow.com/q/1952464
has comment: http://stackoverflow.com/comment/92049079
type: Question
type: AnsweredQuestion
tagged with: for-loop
downvote count: 1
has title: Conditionally entering a for loop
has body: What is a way to avoid code repetition to loop if argument is a sequence (list, tuple) or to skip the loop but execute the action just once? def foo(arg1,sequence=None): # If possible, loop, else do it once if isinstance(sequence,(list,tuple)): for value in sequence: do_something(arg1) else: do_something(arg1) The actions I do in the for loop are way longer than this, and I was wondering what approach you normally use to avoid this, if you do avoid it. I often come across this issue and I haven't come up with something to 'solve' it. EDIT: Question is not a duplicate of In Python, how do I determine if an object is iterable?, as suggested. I do not want to introduce a different condition. I want to avoid the repetition.
possible better answer: http://stackoverflow.com/a/52555304

http://stackoverflow.com/comment/91834269
comment on: http://stackoverflow.com/a/52445411
has text: That is the posix-standard way of writing a file. Vim actually warns you when it opens a file with no newline (it says NOEOL at the bottom), but when it writes the file out, it will add the missing newline. https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92023828
type: QuestionComment
score: 1
has text: By default the installation is done in `~/.kivy/garden/`. Please provide the full traceback.
type: Comment
comment on: http://stackoverflow.com/q/52524647

http://stackoverflow.com/q/52479465
has comment: http://stackoverflow.com/comment/91899918
has comment: http://stackoverflow.com/comment/91900207
tagged with: python
score: 1
duplicate of: http://stackoverflow.com/q/47123035
has comment: http://stackoverflow.com/comment/91900263
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91900055
has comment: http://stackoverflow.com/comment/91901940
downvote count: 1
has title: Error when calculating long numbers in python
has comment: http://stackoverflow.com/comment/91903200
has comment: http://stackoverflow.com/comment/91903745
tagged with: numpy
has comment: http://stackoverflow.com/comment/91909091
has body: I am trying to calculate the square root of some large numbers for example: np.sqrt(324524513452345134623454326) but I get the following error: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.sqrt(324524513452345134623454326) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'int' object has no attribute 'sqrt' &gt;&gt;&gt; np &lt;module 'numpy' from '/.../site-packages/numpy/__init__.py'&gt; &gt;&gt;&gt; np.sqrt(324524) 569.6700799585669 Note: np is not an integer, it is bound to the numpy module still! For smaller integers, the function call works just fine. I am using python 3.6.
has comment: http://stackoverflow.com/comment/91900044
has comment: http://stackoverflow.com/comment/91900095
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52482961
answer count: 1
has body: I'm trying to use Dask to read and write from a google bucket. Using a bunch of csv files works, but is inconvenient (slower, can't compress, can't have the ability to read only some columns) so I tried using the apache parquet format. The writing seems to work fine: import dask.dataframe as dd pandas_df = pd.DataFrame({'x' : [2,3, 2], 'y': [1, 0, 0]}) dask_df = dd.from_pandas(pandas_df, npartitions=2) dask_df.to_parquet("gcs://my_google_bucket/test/") But when I try to read it back read_again_df = dd.read_parquet("gcs://my_google_bucket/test/") I get a non implemented error: AttributeError Traceback (most recent call last) ~/miniconda3/envs/env1/lib/python3.6/site-packages/dask/bytes/core.py in get_pyarrow_filesystem(fs) 520 try: --&gt; 521 return fs._get_pyarrow_filesystem() 522 except AttributeError: AttributeError: 'DaskGCSFileSystem' object has no attribute '_get_pyarrow_filesystem' During handling of the above exception, another exception occurred: NotImplementedError Traceback (most recent call last) &lt;ipython-input-42-ef1fc41d04d5&gt; in &lt;module&gt;() ----&gt; 1 read_again = dd.read_parquet("gcs://my_google_bucket/test/") ~/miniconda3/envs/env1/lib/python3.6/site-packages/dask/dataframe/io/parquet.py in read_parquet(path, columns, filters, categories, index, storage_options, engine, infer_divisions) 991 992 return read(fs, fs_token, paths, columns=columns, filters=filters, --&gt; 993 categories=categories, index=index, infer_divisions=infer_divisions) 994 995 ~/miniconda3/envs/env1/lib/python3.6/site-packages/dask/dataframe/io/parquet.py in _read_pyarrow(fs, fs_token, paths, columns, filters, categories, index, infer_divisions) 505 columns = list(columns) 506 --&gt; 507 dataset = pq.ParquetDataset(paths, filesystem=get_pyarrow_filesystem(fs)) 508 if dataset.partitions is not None: 509 partitions = [n for n in dataset.partitions.partition_names ~/miniconda3/envs/env1/lib/python3.6/site-packages/dask/bytes/core.py in get_pyarrow_filesystem(fs) 522 except …
tagged with: dask
tagged with: parquet
tagged with: pyarrow
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/52483227
type: AnsweredQuestion
has title: Using Dask to read parquet files from a google cloud storage
tagged with: google-cloud-storage
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52483227
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52563175
downvote count: 0
has body: @Ian's answer is better than my original answer. zip all of the lists to combine their elements columnwise, performing a transposition, and run each column into any: &gt;&gt;&gt; matrix = [ ... [True, False, True, False], ... [False, False, True, False], ... [True, False, True, True], ... ] &gt;&gt;&gt; [any(column) for column in zip(*matrix)] [True, False, True, True] I removed my original answer which is suboptimal.
answers question: http://stackoverflow.com/q/52562997
score: 3
upvote count: 3
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52562997

http://stackoverflow.com/q/52534916
has comment: http://stackoverflow.com/comment/92013397
tagged with: django
type: Question
has title: Django form - SelectMultiple changing the visible value
has body: I'm a junior dev. Working on the project in Django 1.8, Python 2.7.15. What do I want to achieve? I want to change the names of groups 'test_X' to another string (payment title), but not in the database... only in the visible layer of form. (SelectMultiple widget) In groups I have something like this: Super Group Extra Group New Group test_1 test_2 test_3 Great Group test_4 (...) The 'test_x' groups are connected via one to one field to Payments model. Just look on my code: class Payment(models.Model): (...) title = models.CharField(max_length=120, null=False) group = models.ManyToManyField(Group) virtual_group = models.OneToOneField( Group, null=True, related_name='virtual_group', ) class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = ( (...), 'group', ) labels = { (...), 'group': u'Choose specific group', } widgets = { 'group': forms.SelectMultiple(attrs={'class': 'form-control chosen', 'data-placeholder': 'Select group'}), } def __init__(self, *args, **kwargs): super(PaymentForm, self).__init__(*args, **kwargs) self.prepare() def prepare(self): (...) groups = Group.objects.all() # here I'm changing names of groups 'test_X' to the tournament title using one to one connection list_of_proper_names = [g.name if not 'test' in g.name else g.virtual_group.title for g in groups] # in ok I got proper values (this is list of strings -&gt; group names and Payment titles) # and here I'm trying to pass only group names and titles self.fields['group'].initial = list_of_proper_names but this doesn't work.... I always get REAL group names in the view so I still got "test_1", "test_2" etc. This is happening even after I changed these names in list comprehension above I tried also with self.fields['group'].queryset but here I can't pass a list of strings, the only query set so if I pass Group.objects.all() again I got the result with "test_1", "test_2" I don't know how to override the group names "test_X" with the title of Payment. It is still the same id/pk...…
tagged with: django-forms
linked to: http://stackoverflow.com/q/45168925
has comment: http://stackoverflow.com/comment/92009134
has comment: http://stackoverflow.com/comment/92012107
has comment: http://stackoverflow.com/comment/92011816
tagged with: python
answer count: 0
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91858698
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52457157
has text: Adding to the answer

http://stackoverflow.com/comment/91975775
type: Comment
has text: Do you perhaps have an example of such a loop?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52516800

http://stackoverflow.com/a/52502377
upvote count: 2
has body: You need to quote the EOF token. Otherwise, variables in the here-doc are expanded by the original shell, so $? contains the exit status of the last command you ran before su. # shell script su ossadm &lt;&lt;'EOF' . /opt/oss/manager/bin/engr_profile.sh # which only can be executed by ossadm python "${SRC_DIR}"/main.pyc status=$? echo $status if $status = 0 ; then echo "success" else echo "failure: $?" fi EOF If SRC_DIR is a variable set in the original shell, make sure you export it so that it will be inherited by the shell run by su, since it will no longer be expanded by the original shell. But if it's set by engr_profile.sh, quoting the token will make it expand correctly. The reason you're getting 1 and success in your second version is because the echo statement sets $? based on its own success. If you want to print an exit status and also test it, you need to save it in another variable, as I've done with the status variable above.
answers question: http://stackoverflow.com/q/52502061
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91945726
has comment: http://stackoverflow.com/comment/91945553

http://stackoverflow.com/comment/91857047
type: Comment
type: QuestionComment
score: 0
has text: It's parsed perfectly in JavaScript if you add spaces so it doesn't look like an increment operator: `2 + + + + + + + + + + + + + + 2`. I'd be more surprised to hear of a programming language or scientific calculator where this *doesn't* work.
comment on: http://stackoverflow.com/q/52456214

http://stackoverflow.com/comment/91920513
has text: And where am i using the regex here? Also, does it work if you have two or three ip's per line?
comment on: http://stackoverflow.com/a/52489694
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91870217
score: 0
comment on: http://stackoverflow.com/a/52460086
has text: Thank you very much!! This is exactly what I was looking for.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52433788
has comment: http://stackoverflow.com/comment/91811556
has comment: http://stackoverflow.com/comment/91811285
has body: What about replacing the first third of items with 0 then shuffle it as following weights = np.random.random(10) weights[: weights.size / 3] = 0 np.random.shuffle(weights)
answers question: http://stackoverflow.com/q/52433736
score: 0
type: Answer

http://stackoverflow.com/comment/92109631
has text: Hi @mehrdad-pedramfar the list is not callable means in ur codes list(chain(*arr_cat)) is not callable...
type: Comment
comment on: http://stackoverflow.com/a/52586132
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91928822
score: 2
comment on: http://stackoverflow.com/q/52494061
type: Comment
type: QuestionComment
has text: It's not completely clear what you want to achieve. Can you maybe add a code example with reduced array size? Is the index array to be applied to each slice of the 2nd dimension?

http://stackoverflow.com/comment/91976390
score: 0
has text: @John Zwinck this line - newData = `df.loc[firstDayMonth:lastDayMonth]`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52517399

http://stackoverflow.com/a/52585721
upvote count: 1
has body: &lt;img src="{% static 'projectweekapp/images/1.jpg' %}" alt=""&gt;, most common way. &lt;img src="{% static {{photo}} %}" alt=""&gt; # Incorrect &lt;img src="{% static photo %}" alt=""&gt; # Correct, no extra brackets required, but no quotes either, indicating photo is a variable. context = { 'photo': "{% static 'projectweekapp/images/1.jpg' %}" }, don't do this, it will never work.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52583543
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52583543
has comment: http://stackoverflow.com/comment/92116179
type: Answer

http://stackoverflow.com/comment/118138154
type: Comment
comment on: http://stackoverflow.com/a/66818656
type: AnswerComment
has text: Ah, I see. Thanks, but for my purpose I want to stick with `numpy.random` module.
score: 0

http://stackoverflow.com/q/52513309
type: Question
upvote count: 2
score: 0
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/52522575
favorite count: 0
has answer: http://stackoverflow.com/a/52522575
has title: Tracking depth in a breadth first search of a directed tree
accepted answer: http://stackoverflow.com/a/52513564
tagged with: python
tagged with: tree
type: AnsweredQuestion
tagged with: breadth-first-search
has answer: http://stackoverflow.com/a/52513564
has body: I'm trying to find the distance between the root and the depth of the node that is being traversed, for example if I had a the following adjancency list representing the tree { 1: [2, 3], 2: [4], 3: [5]} an associated list like the following would be created [0, 1, 1, 2, 2] denoting the level of each node. I have the following code and can't see where I'm meant to add counting functionality etc, ideally this would deal with cross and back edges as well def bfs(graph, root): seen, queue = set([root]), collections.deque([root]) visit_order = [] while queue: vertex = queue.popleft() visit_order.append(vertex) for node in graph[vertex]: if node not in seen: seen.add(node) queue.append(node) print(visit_order)

http://stackoverflow.com/q/52467253
score: -3
tagged with: while-loop
tagged with: for-loop
upvote count: 0
answer count: 1
favorite count: 0
has body: There is an infinite loop of the form: while True: #come code I need to make it run n times, after which the minute delay begins, after which the cycle is started again. And so infinitely run n times and waits 60 seconds. Thank you in advance. p.s. was the idea to shove in while True: something like this: for i in range(n):, after which there would be time.sleep(60), but I decided to ask here ...maybe there is something simpler.
tagged with: python
has answer: http://stackoverflow.com/a/52479216
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91876269
downvote count: 3
type: Question
has title: Python. How to make a timeout in While?

matplotlib
tags question: http://stackoverflow.com/q/52503899
tags question: http://stackoverflow.com/q/52446527
tags question: http://stackoverflow.com/q/52436054
tags question: http://stackoverflow.com/q/52467912
tags question: http://stackoverflow.com/q/52582721
tags question: http://stackoverflow.com/q/52569278
tags question: http://stackoverflow.com/q/52568336
tags question: http://stackoverflow.com/q/52492143
tags question: http://stackoverflow.com/q/52561745
tags question: http://stackoverflow.com/q/52587741
tags question: http://stackoverflow.com/q/52463343
tags question: http://stackoverflow.com/q/52501879
tags question: http://stackoverflow.com/q/52565666
tags question: http://stackoverflow.com/q/52550460
tags question: http://stackoverflow.com/q/52536052
tags question: http://stackoverflow.com/q/52543930
tags question: http://stackoverflow.com/q/52518140
tags question: http://stackoverflow.com/q/52517145
tags question: http://stackoverflow.com/q/52540143
tags question: http://stackoverflow.com/q/52569418
tags question: http://stackoverflow.com/q/52432281
tags question: http://stackoverflow.com/q/52569861
tags question: http://stackoverflow.com/q/52523710
tags question: http://stackoverflow.com/q/52542614
tags question: http://stackoverflow.com/q/52512681
tags question: http://stackoverflow.com/q/52479249
tags question: http://stackoverflow.com/q/52457570
tag name: matplotlib
tags question: http://stackoverflow.com/q/52566969
tags question: http://stackoverflow.com/q/52498777
tags question: http://stackoverflow.com/q/52571145
tags question: http://stackoverflow.com/q/52433350
tags question: http://stackoverflow.com/q/52432553
tags question: http://stackoverflow.com/q/52432588
tags question: http://stackoverflow.com/q/52534212
tags question: http://stackoverflow.com/q/52501513
tags question: http://stackoverflow.com/q/52563496
tags question: http://stackoverflow.com/q/52577902
tags question: http://stackoverflow.com/q/52467781
tags question: http://stackoverflow.com/q/52455597
tags question: http://stackoverflow.com/q/52458461
tags question: http://stackoverflow.com/q/52447199
tags question: http://stackoverflow.com/q/52479438
tags question: http://stackoverflow.com/q/52489602
tags question: http://stackoverflow.com/q/52557692
tags question: http://stackoverflow.com/q/52553398
tags question: http://stackoverflow.com/q/52517868
tags question: http://stackoverflow.com/q/52586506
tags question: http://stackoverflow.com/q/52456775
tags question: http://stackoverflow.com/q/52579114
tags question: http://stackoverflow.com/q/52494488
tags question: http://stackoverflow.com/q/52512790
tags question: http://stackoverflow.com/q/52520344
tags question: http://stackoverflow.com/q/52569623
tags question: http://stackoverflow.com/q/52580819
tags question: http://stackoverflow.com/q/52470351
tags question: http://stackoverflow.com/q/52541377
tags question: http://stackoverflow.com/q/52524883
tags question: http://stackoverflow.com/q/52457964
tags question: http://stackoverflow.com/q/52446571
tags question: http://stackoverflow.com/q/52455477
tags question: http://stackoverflow.com/q/52506716
tags question: http://stackoverflow.com/q/52572094
tags question: http://stackoverflow.com/q/52507345
tags question: http://stackoverflow.com/q/52487862
tags question: http://stackoverflow.com/q/52462435
tags question: http://stackoverflow.com/q/52578867
tags question: http://stackoverflow.com/q/52468325
tags question: http://stackoverflow.com/q/52573818
tags question: http://stackoverflow.com/q/52586723
tags question: http://stackoverflow.com/q/52464833
tags question: http://stackoverflow.com/q/52457705
tags question: http://stackoverflow.com/q/52560967
tags question: http://stackoverflow.com/q/52584339
tags question: http://stackoverflow.com/q/52533720
tags question: http://stackoverflow.com/q/52504828
tags question: http://stackoverflow.com/q/52547223
tags question: http://stackoverflow.com/q/52539134
tags question: http://stackoverflow.com/q/52580018
tags question: http://stackoverflow.com/q/52498858

http://stackoverflow.com/q/52512769
type: Question
tagged with: contour
downvote count: 0
upvote count: 1
answer count: 1
tagged with: python
favorite count: 0
has title: OpenCV - RETR_EXTERNAL not working after Otsu's binarization
type: UnansweredQuestion
has body: I have applied the Otsu's binarization to one image and got this result After that, I use this code to get boxes around the four main shapes: img = cv.imread('test_bin.jpg', 0) _, cnts, _ = cv.findContours(img.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE) for cnt in cnts: x,y,w,h = cv.boundingRect(cnt) cv.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) cv.imwrite('test_cnt.jpg', img) However, I'm not getting anything. It returns just one contour which I imagine it could be the full image itself. I saw it works for RETR_TREE, but I need it to work with RETR_EXTERNAL for the next operations. What is failing here?
tagged with: opencv
has answer: http://stackoverflow.com/a/52516399
score: 1

http://stackoverflow.com/comment/92101261
type: AnswerComment
score: 0
type: Comment
has text: @Declan - Thanks a bunch. Yes, I am working my way through course 1 of the specialization! No doubt you will see me here more often. The return 1 was only so that it doesn't get in my way, I was debugging using print statements.
comment on: http://stackoverflow.com/a/52525887

http://stackoverflow.com/q/52523916
answer count: 0
has body: I'm running Oracle Database 12c 12.1.0.2.0 - 64bit on Windows, but I would like to be able to use cx_Oracle through WSL. When running a Python script in WSL that uses cx_Oracle, I receive the following error: cx_Oracle.DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory." I read this article which mentions downloading Instant Client for Linux, but I don't know if that is still required if I already have Oracle Database 12c Client on Windows. There is a part in the article about creating symbolic links, one of them being libclntsh.so. Is there a way to link my Oracle 12c client on Windows to be used with cx_Oracle in WSL?
upvote count: 2
type: UnansweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92033987
has title: cx_Oracle on Windows Subsystem for Linux (WSL) with Existing Windows Oracle Installation
tagged with: cx-oracle
score: 1
tagged with: oracle12c
tagged with: oracle-database
tagged with: python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/92036310
comment on: http://stackoverflow.com/a/52548365
score: 0
type: AnswerComment
has text: @Vee Same concept you apply `.split()` first then wrap that in `''.join()`
type: Comment

http://stackoverflow.com/q/52502408
has answer: http://stackoverflow.com/a/52502516
downvote count: 1
type: Question
score: -1
accepted answer: http://stackoverflow.com/a/52503485
tagged with: batch-file
answer count: 2
upvote count: 0
tagged with: string
favorite count: 0
has title: Not able to remove last blank line with python or batch script
tagged with: python
type: AnsweredQuestion
has body: My excel file contains: ABC DEF GHI My requirement is to concatenate all the above rows into single string like below: ABC or DEF or GHI Below is the code which printed the excel rows into a text file. wb = xlrd.open_workbook("abc.xlsx") sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) with open("data.txt", "w") as dataFile: for i in range(sheet.nrows): dataSet = sheet.cell_value(i, 0) print(dataSet, file=dataFile) But the data.txt file is printed as: ABC DEF GHI &lt;---- this is a blank line ----&gt; So when i am using below code to concatenate the lines: with open("data.txt", "r") as data: for each_line in data: try: objList = each_line.replace("\n", " or ") print(objList, end='') except ValueError: pass This is resulting the below output: ABC or DEF or GHI or ---------&gt;This is wrong The required output is : ABC or DEF or GHI -------------&gt; this is correct Please suggest where i am missing? Thanks for the help.
has answer: http://stackoverflow.com/a/52503485
possible better answer: http://stackoverflow.com/a/52502516

http://stackoverflow.com/q/52512345
has answer: http://stackoverflow.com/a/52512432
has title: Error str object not callable in vowel counting program
has body: Hi I am trying to write a program that counts the vowels in a sentence and then prints out the count of each vowel individually. Sentence = input("Please enter sentence: ") a = 0 e = 0 i = 0 o = 0 u = 0 for index in range(0, len(Sentence) - 1): if Sentence(index) == "a": a = a + 1 elif Sentence(index) == "e": e = e + 1 elif Sentence(index) == "i": i = i + 1 elif Sentence(index) == "o": o = o + 1 elif Sentence(index) == "u": u = u + 1 print(a, e, i, o, u) Getting the following error : Please enter sentence: Traceback (most recent call last): File "script.py", line 8, in if Sentence(index) == "a": TypeError: 'str' object is not callable Command exited with non-zero status 1 Any help would be be appreciated. Thanks
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: if-statement
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/91965457
has comment: http://stackoverflow.com/comment/91965550
has comment: http://stackoverflow.com/comment/91966532
score: 0
has comment: http://stackoverflow.com/comment/91964916
answer count: 1

http://stackoverflow.com/comment/91904331
comment on: http://stackoverflow.com/q/52481093
type: QuestionComment
has text: I thought so and that's why I use tags such as python and R. but they were removed not sure why.
score: 0
type: Comment

http://stackoverflow.com/q/52436084
has answer: http://stackoverflow.com/a/52436287
has answer: http://stackoverflow.com/a/52452255
has title: count of words in a string from another list
type: Question
has comment: http://stackoverflow.com/comment/91815558
has body: I have a word list and I need to find the count of words that are present in the string. eg: text_string = 'I came, I saw, I conquered!' word_list=['I','saw','Britain'] I require a python script that prints {‘i’:3,’saw’:1,’britain':0}
upvote count: 1
score: -2
has comment: http://stackoverflow.com/comment/91815407
answer count: 3
downvote count: 3
tagged with: python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52437663

http://stackoverflow.com/q/52448510
score: 1
has answer: http://stackoverflow.com/a/52448559
has body: My question is about obtaining the sum of each row in a 2d list and then obtaining the total of all rows. Below is the information given to me-- We will pass in a 2 dimensional list of numbers. You should: *add up all the numbers in each row and output that number *output the grand total of all rows this is the code given to me: # Get our list from the command line arguments import sys numbers= sys.argv[1:] # Convert the command line arguments into 2d list for i in range(0,len(numbers)): numbers[i]= numbers[i].split(',') This work is completed via Codio. When I print my 2d list this is the output I get: print(numbers) [['1', '1', '-2'], ['-1', '-2', '-3'], ['1', '1', '1']] Based on previous problems and scenarios I have worked, these numbers have changed based on the coding I have developed to make sure it meets all the guidelines of the assignment. I have tried various attempts at the problem, listed below: row = len(numbers) column = len(numbers[0]) total = 0 for row in numbers: rowtotal = 0 for column in numbers: rowtotal = rowtotal + numbers[row][column] print(rowtotal) total = total + rowtotal print(total) This gives the error: Traceback (most recent call last): File "list.py", line 17, in rowtotal = rowtotal + numbers[row][column] TypeError: list indices must be integers, not list I have also tried: row = len(numbers) column = len(numbers[0]) total = 0 for row in range (len(numbers)): for col in range(len(numbers[0])): total = total + numbers[row][column] print(total) Which gives me the error: Traceback (most recent call last): File "list.py", line 16, in total = total + numbers[row][column] IndexError: list index out of range For my last attempt I tried: total = 0 for x in range (0, len(numbers)): rowtotal = 0 for y in range (0, len(numbers[0])): rowtotal = rowtotal = int(numbers[x][y]) print(rowtotal) total = total + rowtotal print(total) Which finally gave me numbers, but not the correct ones: Program Failed for Input: 1,1,-2 -1,-2,-3 1,1,1 Expected Output:…
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/57228723
answer count: 3
has title: 2D List (row total/grand total) in Python
possible better answer: http://stackoverflow.com/a/57228723
has comment: http://stackoverflow.com/comment/91841231
has answer: http://stackoverflow.com/a/52449135
favorite count: 0
accepted answer: http://stackoverflow.com/a/52449135
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/92099070
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52566469
has text: thanks everyone. I am new to python so stupid questions happen. Just was wondering why flush doesn't work

http://stackoverflow.com/comment/92009666
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52535136
has text: @NicolasMarek you can create json string as per this [link](https://stackoverflow.com/questions/23110383/how-to-dynamically-build-a-json-object-with-python)
score: 0

http://stackoverflow.com/q/52457656
type: Question
tagged with: if-statement
upvote count: 5
has title: Using conditional if/else logic with pandas dataframe columns
tagged with: dataframe
score: 5
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52457780
tagged with: python
accepted answer: http://stackoverflow.com/a/52457780
type: AnsweredQuestion
has body: My dataframe called pw2 looks something like this, where I have two columns, pw1 and pw2, which are probability of wins. I'd like to perform some conditional logic to create another column called WINNER based off pw1 and pw2. +-------------------------+-------------+-----------+-------------+ | Name1 | pw1 | Name2 | pw2 | +-------------------------+-------------+-----------+-------------+ | Seaking | 0.517184213 | Lickitung | 0.189236181 | | Ferrothorn | 0.172510623 | Quagsire | 0.260884258 | | Thundurus Therian Forme | 0.772536272 | Hitmonlee | 0.694069408 | | Flaaffy | 0.28681284 | NaN | NaN | +-------------------------+-------------+-----------+-------------+ I want to do this conditionally in a function but I'm having some trouble. if pw1 > pw2, populate with Name1 if pw2 > pw1, populate with Name2 if pw1 is populated but pw2 isn't, populate with Name1 if pw2 is populated but pw1 isn't, populate with Name2 But my function isn't working - for some reason checking if a value is null isn't working. def final_winner(df): # If PW1 is missing and PW2 is populated, Pokemon 1 wins if df['pw1'] = None and df['pw2'] != None: return df['Number1'] # If it's the same thing but the other way around, Pokemon 2 wins elif df['pw2'] = None and df['pw1'] != None: return df['Number2'] # If pw2 is greater than pw1, then Pokemon 2 wins elif df['pw2'] &gt; df['pw1']: return df['Number2'] else return df['Number1'] pw2['Winner'] = pw2.apply(final_winner, axis=1)

http://stackoverflow.com/comment/91999781
has text: getting this TypeError: request() got an unexpected keyword argument 'body'
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52530226

http://stackoverflow.com/q/52550415
score: 0
tagged with: gdal
has body: I have python 3.6.3 running with anaconda 1.8.7/spyder 3.3.1 my script starts with: import os from osgeo import gdal The script was working fine 2 days ago!!! but when I ran it today, I got this error: Python 3.6.3 |Anaconda, Inc.| (default, Oct 6 2017, 12:04:38) Type "copyright", "credits" or "license" for more information. IPython 6.2.1 -- An enhanced Interactive Python. runfile('/Users/planchon/Dropbox/Documents/Python_scripts/Fortuna/lire_points_dans-images.py', wdir='/Users/planchon/Dropbox/Documents/Python_scripts/Fortuna') Traceback (most recent call last): File "&lt;ipython-input-1-9738155f2c83&gt;", line 1, in &lt;module&gt; runfile('/Users/planchon/Dropbox/Documents/Python_scripts/Fortuna/lire_points_dans-images.py', wdir='/Users/planchon/Dropbox/Documents/Python_scripts/Fortuna') File "/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 678, in runfile execfile(filename, namespace) File "/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 106, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/Users/planchon/Dropbox/Documents/Python_scripts/Fortuna/lire_points_dans-images.py", line 30, in &lt;module&gt; from osgeo import gdal File "/anaconda3/lib/python3.6/site-packages/osgeo/__init__.py", line 21, in &lt;module&gt; _gdal = swig_import_helper() File "/anaconda3/lib/python3.6/site-packages/osgeo/__init__.py", line 17, in swig_import_helper _mod = imp.load_module('_gdal', fp, pathname, description) File "/anaconda3/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/anaconda3/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: dlopen(/anaconda3/lib/python3.6/site-packages/osgeo/_gdal.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libpoppler.71.dylib Referenced from: /anaconda3/lib/libgdal.20.dylib Reason: image not found Again, this does not looks like an installation problem since …
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: installation
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/52555352
has title: anaconda/python 3.6/MacOS 10: gdal unexpectedly stopped working (ImportError)

http://stackoverflow.com/comment/92077952
comment on: http://stackoverflow.com/q/52570112
type: QuestionComment
score: 0
type: Comment
has text: Read about [mcve]

http://stackoverflow.com/comment/91913813
type: AnswerComment
comment on: http://stackoverflow.com/a/52485955
has text: @SvenH. Yeah, I also got that and mentioned that in the question. But this 2 tuple structure seems a bit strange to me, and I have not seen it in any other place(without explicit zip) in python in my limited experience.
score: 0
type: Comment

http://stackoverflow.com/comment/91964383
score: 0
type: Comment
type: QuestionComment
has text: Thanks for the clarification, Jason. See my updated answer below. I create a list of dataframes, `dfs`. That way dfs[0] is the first data frame, dfs[1] is the second, etc...
comment on: http://stackoverflow.com/q/52507048

http://stackoverflow.com/comment/91898461
comment on: http://stackoverflow.com/q/52478484
has text: Also, you have an extra bracket on the end of your liste that causes an invalid syntax error.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52521370
tagged with: matrix
answer count: 1
favorite count: 0
has body: I have studied matrix chain multiplication, wherein given a sequence of matrices, the goal is to find the most efficient way to multiply matrices. The problem is not actually to perform the multiplications, but merely to decide the sequence of the matrix multiplications involved. So say for example. Given 2 matrices A and B, I can have one possible matrix combination which is (AB) and when my matrices are 3: A, B, C, I can have two possible combinations: (AB)C and A (BC). I want to implement a code given the number of matrices will output all possible matrix combinations in Python. The code below is not right because given n = 3 matrices it outputs 5 combinations, when in fact it should be 2 only. The code below is printing all combinations of balanced parentheses. def printParenthesis(str, n): if(n &gt; 0): _printParenthesis(str, 0, n, 0, 0,0); return; def _printParenthesis(str, pos, n, open, close, count): if(close == n): for i in str: print(i, end = ""); print(); return; else: if(open &gt; close): str[pos] = '}'; _printParenthesis(str, pos + 1, n, open, close + 1, count); if(open &lt; n): str[pos] = '{' + chr(65+count); _printParenthesis(str, pos + 1, n, open + 1, close, count+1); # Driver Code n = 3; //Number of matrices str = [""] * 2 * n; printParenthesis(str, n); How will I modify my code above to fit my problem? Please help .
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52522127
upvote count: 1
downvote count: 1
type: Question
has title: All Possible Groupings in a Matrix Chain Application
tagged with: matrix-multiplication
score: 0

http://stackoverflow.com/a/52552330
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92065835
type: Answer
has body: Not easy, one possible solution is create helper Series: df.loc[df.col1 == 1, 'new_col'] = pd.Series('a', 'b' * len(df)) print (df) col1 col2 new_col 0 1 4 [a, b] 1 2 5 NaN 2 3 6 NaN Another solution, if need set missing values to empty list too is use list comprehension: #df['new_col'] = [['a', 'b'] if x == 1 else np.nan for x in df['col1']] df['new_col'] = [['a', 'b'] if x == 1 else [] for x in df['col1']] print (df) col1 col2 new_col 0 1 4 [a, b] 1 2 5 [] 2 3 6 [] But then you lose the vectorised functionality which goes with using NumPy arrays held in contiguous memory blocks.
answers question: http://stackoverflow.com/q/52552198
accepted answer of: http://stackoverflow.com/q/52552198
score: 15
upvote count: 15

http://stackoverflow.com/a/52433888
accepted answer of: http://stackoverflow.com/q/52433778
has comment: http://stackoverflow.com/comment/91812806
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has body: If you want to generate "broken" fragment offset fields, you have to do that yourself. The scapy fragment() function is simple enough: def fragment(pkt, fragsize=1480): """Fragment a big IP datagram""" fragsize = (fragsize + 7) // 8 * 8 lst = [] for p in pkt: s = raw(p[IP].payload) nb = (len(s) + fragsize - 1) // fragsize for i in range(nb): q = p.copy() del(q[IP].payload) del(q[IP].chksum) del(q[IP].len) if i != nb - 1: q[IP].flags |= 1 q[IP].frag += i * fragsize // 8 # &lt;---- CHANGE THIS r = conf.raw_layer(load=s[i * fragsize:(i + 1) * fragsize]) r.overload_fields = p[IP].payload.overload_fields.copy() q.add_payload(r) lst.append(q) return lst Source: https://github.com/secdev/scapy/blob/652b77bf12499451b47609b89abc663aa0f69c55/scapy/layers/inet.py#L891 If you change the marked code line above, you can set the fragment offset to whatever you want.
answers question: http://stackoverflow.com/q/52433778

http://stackoverflow.com/a/54377521
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52458399
has body: Posting the comment of @Lukas Graf as the answer here Not a complete answer, but: logging.basicConfig will not do anything if the root logger already has handlers configured for it. So if it's invoked multiple times, only the first one will apply the given configuration to the root logger.
accepted answer of: http://stackoverflow.com/q/52458399

http://stackoverflow.com/a/52463195
score: 1
answers question: http://stackoverflow.com/q/52463162
type: AcceptedAnswer
downvote count: 0
has body: Looks like n is a (two-element?) tuple - say, (x,y). Then the line for a,b in n: is essentially equivalent to for a,b in (x,y):. At the first iteration of the loop, Python attempts to assign the first element of the tuple x to a,b, which is not possible. You should replace the loop with an assignment a,b=n, or just use n[0] and n[1] instead of a and b.
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52463162

http://stackoverflow.com/q/52556939
possible better answer: http://stackoverflow.com/a/59602574
type: Question
has answer: http://stackoverflow.com/a/59602574
has answer: http://stackoverflow.com/a/55777243
has title: How to use Jobqueue in Python-telegram-bot
downvote count: 0
favorite count: 0
score: 8
has answer: http://stackoverflow.com/a/65851155
tagged with: telegram-bot
tagged with: python-3.x
tagged with: python-telegram-bot
upvote count: 8
tagged with: python
accepted answer: http://stackoverflow.com/a/55777243
answer count: 4
type: AnsweredQuestion
has body: I have able to make a bot very easily by reading the docs but Jobqueue is not working as per it is written. The run_daily method uses a datetime.time object to send the message at a particular time but this code neither does its job of sending a message nor shows any errors. It just keeps running import datetime from telegram import bot from telegram.ext import Updater def callback_minute(bot, job): bot.send_message(chat_id=475838704, text='PlEaSe wOrK!') def main(): updater = Updater() bot = updater.bot job = updater.job_queue dispatcher = updater.dispatcher job.run_daily(callback_minute, time=datetime.time(6,33,00)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
tagged with: job-queue
has answer: http://stackoverflow.com/a/77071755

http://stackoverflow.com/comment/91856534
type: QuestionComment
comment on: http://stackoverflow.com/q/52457019
type: Comment
has text: @RafaelC , ideally, the code would look in series defined by the date range 'entrydate' and 'exitdate', i.e. for the 1st iteration, take a subsection of 's' between '2012-02-15' and '2012-02-17' , and look in there for the value. If in this subsection, there are duplicate values, then take the first is fine. In my actual data, I am working to 4dp so highly unlikely there would be dupes in there. Thank you!!
score: 0

http://stackoverflow.com/q/52501609
possible better answer: http://stackoverflow.com/a/52501866
has title: Securely passing credentials for API authentication - Python 3
score: 0
answer count: 2
tagged with: api
has body: In Python 3, I'm passing credentials to authenticate an API call and it works completely fine using the following line: userAndPass = b64encode(b"username:password").decode("ascii") For security purposes, what I would prefer to do is store the credentials externally (possibly a yaml file or elsewhere) rather than hard code it. I attempted to replace the username and pass with variables, but that doesn't seem to work. I've tried placing the variable 'credentials' in brackets and also tried adding a plus before hand, neither work. I would like it to work as follows: credentials = "username:password" userAndPass = b64encode(b'credentails').decode("ascii") Any suggestion is appreciated!
accepted answer: http://stackoverflow.com/a/52501841
tagged with: restful-authentication
tagged with: python
type: AnsweredQuestion
tagged with: authentication
tagged with: python-requests
has answer: http://stackoverflow.com/a/52501866
has answer: http://stackoverflow.com/a/52501841
type: Question

http://stackoverflow.com/comment/117487676
score: 0
type: AnswerComment
has text: Hi @Philipp , it is DTW. Inside the DTW algorithm one also needs to compute the distance between two datapoints, thus dtw(x,y) uses a subroutine inner_dist(x[t], y[t]). This inner distance is L2 for dtaidistance while some other toolboxes use L1. Most papers I know use L2 and I also think it makes most sense.
comment on: http://stackoverflow.com/a/55631753
type: Comment

http://stackoverflow.com/q/52526841
has answer: http://stackoverflow.com/a/52527495
downvote count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 1
type: Question
linked to: http://stackoverflow.com/q/47304291
answer count: 1
tagged with: amazon-web-services
has title: aws eb deployment error : No matching distribution found for anaconda-client==1.6.9
upvote count: 1
tagged with: amazon-elastic-beanstalk
favorite count: 0
has body: I am very new to AWS and in-general coding. I wrote a small Django application, and now I am trying to deploy it on AWS using elastic beanstalk with the help of this URL. https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html My application uses Postgres database for which I need psycopg2 package, which I have added in my requirements.txt file. (this is not part of the instructions on this URL but I knew I need psycopg2 so I added) when I create EB environment using eb create django-env, I get the following error: This log I took from EC2 /var/log/. Here is the error: [2018-09-26T21:44:20.502Z] INFO [3151] - [Application deployment app-d840-180926_224155@1/StartupStage0/AppDeployPreHo ok/03deploy.py] : Starting activity... [2018-09-26T21:44:21.774Z] INFO [3151] - [Application deployment app-d840-180926_224155@1/StartupStage0/AppDeployPreHo ok/03deploy.py] : Activity execution failed, because: Collecting alabaster==0.7.10 (from -r /opt/python/ondeck/app/requi rements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/2e/c3/9b7dcd8548cf2c00531763ba154e524af575e8f36701bacfe5bcadc674 40/alabaster-0.7.10-py2.py3-none-any.whl Collecting anaconda-client==1.6.9 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Could not find a version that satisfies the requirement anaconda-client==1.6.9 (from -r /opt/python/ondeck/app/requi rements.txt (line 2)) (from versions: 1.1.1, 1.2.2) No matching distribution found for anaconda-client==1.6.9 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) You are using pip version 9.0.1, however version 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2018-09-26 21:44:21,768 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/ python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in…

http://stackoverflow.com/comment/91805680
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52430427
has text: I did, and the GUI is definitely waiting anyway.

http://stackoverflow.com/q/52552467
has body: I doing a web app for a simple telecommunications stuff, and I'm having some problems. This is my code for showing diagrams for Bit Error Rate of BPSK and DPSK. BPSK: @app.route('/bpsk') def bpsk(): img = io.BytesIO() EbN0_dB = [] loi = [] i = 0 while i &lt;= 24: EbN0_dB.append(i) i += 1 for item in EbN0_dB: EbN0 = 10**(item/10) BER = 1/2*erfc(sqrt(EbN0)) loi.append(BER) plt.semilogy(EbN0_dB, loi, 'c-s', label = "BPSK") plt.legend() plt.grid(True) plt.ylabel('BER') plt.xlabel('Eb/N0 (dB)') plt.title('Bit Error Rate for Binary Phase-Shift Keying') plt.savefig(img, format='png') img.seek(0) plot_url = base64.b64encode(img.getvalue()).decode() return render_template('plot.html', plot_url=plot_url) DPSK: @app.route('/dpsk') def dpsk(): imga = io.BytesIO() EbN0_dB = [] loi = [] i = 0 while i &lt;= 24: EbN0_dB.append(i) i += 1 for item in EbN0_dB: EbN0 = 10**(item/10) BER = 1/2*exp(-EbN0) loi.append(BER) plt.semilogy(EbN0_dB, loi,'m-s', label = "DPSK") plt.legend() plt.grid(True) plt.ylabel('BER') plt.xlabel('Eb/N0 (dB)') plt.title('Bit Error Rate for Differential Phase Shift Keying') plt.savefig(imga, format='png') imga.seek(0) plot_urla = base64.b64encode(imga.getvalue()).decode() return render_template('plot.html', plot_url=plot_urla) plot.html: {% extends 'base.html' %} {% block app_content %} &lt;h1&gt; This is a chart I just created! &lt;/h1&gt; &lt;br&gt; &lt;body&gt; &lt;img src="data:image/png;base64, {{ plot_url }}"&gt; &lt;/body&gt; {% endblock %} This is the result I got: BPSK DPSK As you can see, when I first showed BPSK diagram, it was ok. But when I came to DPSK one, the previous blue line of BPSK diagram did not disappear, it was still there with the new purple line of DPSK. How can I only show new images without remaining the previous ones?
has title: Repeated images shown on Flask app (Using base64)
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
type: Question
tagged with: flask
tagged with: image
upvote count: 1

http://stackoverflow.com/comment/91889199
score: 0
has text: @Alex: Thanks. It seems that (TABLOCK, HOLDLOCK) is for the whole table. Sometimes, in my case, range lock is need while sometimes, table lock is needed. Also, it needs a dummy SQL statement in order to lock. Is it a proper way to do so or any other more elegant ways? After a few researches, it seems that it is the only way to do so. Just want to find out better way if any.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52467217

http://stackoverflow.com/comment/92064540
score: 0
type: Comment
has text: THANK YOU. Basicly, you've approved what I thought. thank you so much for the detailed explaination and samples, it's a great answer. Well, first of all I got to learn about JWT and try to understand what you've wrote here in Angular. As for JWT tokens API in flask, there's : https://flask-praetorian.readthedocs.io/en/latest/ Flask Praetorian which I heard is a great extension. Thank you, Thank you, Thank you!!!.
comment on: http://stackoverflow.com/a/52560927
type: AnswerComment

http://stackoverflow.com/comment/92089790
comment on: http://stackoverflow.com/q/52577250
has text: You are missing the semicolon ( : ) before -1 on your y in line 4...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52575011
has body: Is there a way of taking a given string and passing it through a regex to get a new formatting? I have two strings, a="PRO999" and b="JHE986" and the regex expression \D{3}_\d{3}. I want to be able to pass these strings and get PRO_999 and JHE_986. I could do this manually, but I know there will be times when I need the string to remain together and times when I need to apply the expression.
score: 0
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
has title: How to conform a given string to conform to regex
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52575022
accepted answer: http://stackoverflow.com/a/52575022
type: Question

http://stackoverflow.com/comment/91922550
comment on: http://stackoverflow.com/q/52489647
has text: Can you post any code, input, errors, or desired ouput
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91868660
comment on: http://stackoverflow.com/q/52437701
score: 0
has text: could you tell us the exact problem are you facing?? are you not able to crop 'u' the post some images with 'u' and you are not able to crop it properly.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52510681
has title: How can I access a constant of an inner class from a function definition?
type: Question
linked to: http://stackoverflow.com/q/13905741
tagged with: class
score: 0
has body: I have the class sprite with the inner class type. class sprite: class type: ThisValue = 10 OtherValue = 22 def __init__(self, type = sprite.type.ThisValue): self.type = type When I try this, it says that the name sprite is not defined; the error throws on the def __init__() line. How can I access ThisValue in the function definition? Is there a better way to write the type class?
answer count: 1
has answer: http://stackoverflow.com/a/52510732
accepted answer: http://stackoverflow.com/a/52510732
tagged with: subclass
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91880261
comment on: http://stackoverflow.com/a/52468746
type: Comment
has text: I was thinking on the lines of: def __init__(self, topLeft = Point(0,0), bottomRight = Point(1,1)): but that still returns a memory location.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91876113
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52433074
has text: If I add the line `cimport numpy as np` to the start, and add a slash the `ndarray = ` (for the line continuation) this code compiles fine in Cython. I suspect your error is at the C compiling stage. Since you don't show `main.h` this is impossible for anyone but you to diagnose. Please read the help on [mcve] and make sure that you have provided one.

nlp
tags question: http://stackoverflow.com/q/52557058
tags question: http://stackoverflow.com/q/52481933
tags question: http://stackoverflow.com/q/52469001
tags question: http://stackoverflow.com/q/52555270
tags question: http://stackoverflow.com/q/52561244
tags question: http://stackoverflow.com/q/52519157
tags question: http://stackoverflow.com/q/52543777
tags question: http://stackoverflow.com/q/52447573
tags question: http://stackoverflow.com/q/52486670
tags question: http://stackoverflow.com/q/52473653
tags question: http://stackoverflow.com/q/52537766
tags question: http://stackoverflow.com/q/52549113
tags question: http://stackoverflow.com/q/52519433
tags question: http://stackoverflow.com/q/52519326
tags question: http://stackoverflow.com/q/52556530
tags question: http://stackoverflow.com/q/52458404
tags question: http://stackoverflow.com/q/52467563
tags question: http://stackoverflow.com/q/52496230
tags question: http://stackoverflow.com/q/52578323
tag name: nlp
type: Tag
tags question: http://stackoverflow.com/q/52455774
tags question: http://stackoverflow.com/q/52580262
tags question: http://stackoverflow.com/q/52430623
tags question: http://stackoverflow.com/q/52573331

dask
tags question: http://stackoverflow.com/q/52482961
type: Tag
tags question: http://stackoverflow.com/q/52555140
tags question: http://stackoverflow.com/q/52583316
tags question: http://stackoverflow.com/q/52542335
tags question: http://stackoverflow.com/q/52538451
tags question: http://stackoverflow.com/q/52486658
tags question: http://stackoverflow.com/q/52449483
tags question: http://stackoverflow.com/q/52460620
tag name: dask
tags question: http://stackoverflow.com/q/52552066
tags question: http://stackoverflow.com/q/52538878
tags question: http://stackoverflow.com/q/52562962
tags question: http://stackoverflow.com/q/52501086
tags question: http://stackoverflow.com/q/52542961
tags question: http://stackoverflow.com/q/52561766
tags question: http://stackoverflow.com/q/52566462
tags question: http://stackoverflow.com/q/52472230

http://stackoverflow.com/comment/91807943
has text: Thought so. Thank you.
type: Comment
comment on: http://stackoverflow.com/q/52432042
type: QuestionComment
score: 0

http://stackoverflow.com/q/52579341
has comment: http://stackoverflow.com/comment/92094295
has comment: http://stackoverflow.com/comment/92094048
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52580337
has title: Displaying termcolor.colored in python
tagged with: arrays
has comment: http://stackoverflow.com/comment/92094802
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52580337
has comment: http://stackoverflow.com/comment/92094148
tagged with: colors
has body: I am creating a text based connect four game in python. For the two players I am using termcolor.colored for two different game pieces. The game board is a multidimensional numpy array. The problem is that when I assign an element in the numpy array to a color, instead of printing the colored text it prints it in unicode. Is there a fix for this? My code so far (just to test game mechanics): def connect4(): import numpy as np from termcolor import colored red = colored('0', 'red') yell = colored('0', 'yellow') gb = np.array([[" " for x in range(7)] for x in range(7)]).T for x in range(7): gb[0][x] = str(x+1) while 1: print(gb) rm = int(input(colored('Red\'s move(row): ', 'red'))) gb[6][rm-1] = red print(gb) break Output: [['1' '2' '3' '4' '5' '6' '7'] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' ']] Red\'s move(row): 2 [['1' '2' '3' '4' '5' '6' '7'] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' ' ' ' ' ' ' ' ' ' ' ' '] [' ' '\x1b' ' ' ' ' ' ' ' ' ' ']] How can I print colored text in an array?
tagged with: python
tagged with: text
type: AnsweredQuestion
score: 2
upvote count: 2

http://stackoverflow.com/comment/91917701
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52488119
has text: could you please add a simplified code which could be tested?
score: 0

http://stackoverflow.com/q/52443783
has comment: http://stackoverflow.com/comment/91830728
has answer: http://stackoverflow.com/a/52443847
type: Question
has body: I have been looking for a way to split a string by digits, for instance: st = "abc4ert" from string import digits st = st.split(digits) --&gt; st = ['abc','ert'] Is there a way to do that (without including the numbers in the list)?
has answer: http://stackoverflow.com/a/52443819
linked to: http://stackoverflow.com/q/13673781
answer count: 2
duplicate of: http://stackoverflow.com/q/13673781
downvote count: 2
has comment: http://stackoverflow.com/comment/91831675
favorite count: 0
has title: How to split a string into a list by digits?
type: UnansweredQuestion
tagged with: python
upvote count: 4
score: 2

http://stackoverflow.com/comment/91840403
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52448503
score: 3
has text: To quote [What topics can I ask about here?](https://stackoverflow.com/help/on-topic), SO's scope is limited to questions about *specific problems*. A generalized request for improvements to already-working code belongs on [codereview.se], not here. See [A Guide To Code Review For Stack Overflow Users](https://codereview.meta.stackexchange.com/a/5778/155649) for a discussion of which questions go on which site (and changes that may need to be made in the translation).

http://stackoverflow.com/a/52478439
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52478339
upvote count: 2
type: AcceptedAnswer
has body: You need to use command line arguments, like this; import time import subprocess def main(): while(True): a=input("Please enter parameter to pass to subprocess:") subprocess.Popen(["python", "child.py", a]) print(f"{a} was started") time.sleep(5) if __name__ == '__main__': main() child.py: import sys def main(a): while(True): print(a) if __name__ == '__main__': a = sys.argv[1] main(a)
type: Answer
accepted answer of: http://stackoverflow.com/q/52478339

http://stackoverflow.com/comment/92028202
score: 1
comment on: http://stackoverflow.com/q/52544119
has text: You are missing a `"` and your identation is way off. please fix. edit your question.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52483943
has body: I am trying to save urdu in csv file but symbols are stored in the file rather than urdu text also i have tried to add the iso code for urdu encoding but it is not working ISO-8859-1 import sys import json import time import csv import codecs auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) tweets = api.search(q="اردو"+" -filter:retweets",count="10000") for tweet in tweets: if tweet.lang == "ur": #print(tweet.text) with open('mytweets18.csv', 'w', encoding='ISO-8859-1') as f: writer = csv.writer(f, delimiter=';') writer.writerow(tweet.text) The problem is with encoding. I have also tried with encoding="utf-8", but both are not working. Need help regarding this.
has comment: http://stackoverflow.com/comment/91909490
has comment: http://stackoverflow.com/comment/91909723
has comment: http://stackoverflow.com/comment/91912481
has title: How to save urdu language characters in a csv file?
has comment: http://stackoverflow.com/comment/91909469
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/52484563
score: 1
type: Question

http://stackoverflow.com/comment/92004432
type: Comment
comment on: http://stackoverflow.com/q/52513050
type: QuestionComment
has text: Eh. Not necessarily, the thing is that you would probably need to let your computer think it's a router for a moment to initialize the table by scanning the network ... thinking about it, maybe a brute force approach would be easier. Anyway: my point is that nothing remains a mystery if you're curious enough ;>
score: 0

http://stackoverflow.com/q/52457989
has comment: http://stackoverflow.com/comment/91858236
favorite count: 0
has body: From my understanding, pandas.DataFrame.apply does not apply changes inplace and we should use its return object to persist any changes. However, I've found the following inconsistent behavior: Let's apply a dummy function for the sake of ensuring that the original df remains untouched: &gt;&gt;&gt; def foo(row: pd.Series): ... row['b'] = '42' &gt;&gt;&gt; df = pd.DataFrame([('a0','b0'),('a1','b1')], columns=['a', 'b']) &gt;&gt;&gt; df.apply(foo, axis=1) &gt;&gt;&gt; df a b 0 a0 b0 1 a1 b1 This behaves as expected. However, foo will apply the changes inplace if we modify the way we initialize this df: &gt;&gt;&gt; df2 = pd.DataFrame(columns=['a', 'b']) &gt;&gt;&gt; df2['a'] = ['a0','a1'] &gt;&gt;&gt; df2['b'] = ['b0','b1'] &gt;&gt;&gt; df2.apply(foo, axis=1) &gt;&gt;&gt; df2 a b 0 a0 42 1 a1 42 I've also noticed that the above is not true if the columns dtypes are not of type 'object'. Why does apply() behave differently in these two contexts? Python: 3.6.5 Pandas: 0.23.1
tagged with: pandas
tagged with: python
tagged with: pandas-apply
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52458155
upvote count: 14
possible better answer: http://stackoverflow.com/a/65485193
type: Question
score: 14
has answer: http://stackoverflow.com/a/65485193
has comment: http://stackoverflow.com/comment/91858307
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52458155
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91858234
has title: pandas df.apply unexpectedly changes dataframe inplace

http://stackoverflow.com/comment/91863360
type: Comment
type: QuestionComment
has text: What does your analysis tell you?
score: 0
comment on: http://stackoverflow.com/q/52459179

http://stackoverflow.com/comment/91872675
score: 0
type: Comment
has text: @FlashThunder I dont want to host a server just for a simple script like this, i found a website [link](https://www.easycron.com) where the site calls a url
type: QuestionComment
comment on: http://stackoverflow.com/q/52465469

http://stackoverflow.com/comment/91829644
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52441524
has text: Okay and what is now the solution ?

http://stackoverflow.com/comment/91825740
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52440435
has text: Then skip `imread` and related, and just generate the numpy arrays with the data you need programmatically (which you would need to do anyway).

http://stackoverflow.com/comment/91860685
type: QuestionComment
comment on: http://stackoverflow.com/q/52458349
score: 0
has text: Could you be more specific about the exact start and end dates?
type: Comment

http://stackoverflow.com/q/52484250
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91910175
favorite count: 0
has comment: http://stackoverflow.com/comment/91910031
has body: We have a problem where we are finding the begining of elements like below input_arr = [ 0, 0, 0,1,1,1,1] here i am intrested in finding the first occurence of one through XOR funtion def find_0_1_sep(self,arr): i=0 result=0 while(arr[i]!=1): result = 1 - result result=arr[i+1]^result if(result==1): print(i) i=i+1 This above function is working well for if the input is starting 0 and after it one is coming. I have tried to chnage the code so that it will work for both if the array is starting with 1 or zero any number arr = [ 1, 1,1,0,0,0] Code below def find_0_1_sep_genric(self,arr): i=0 result=arr[i] # initializing the first element 1 or 0 result = 1-result # invert the value while(arr[i]!=result): # traversing the array untill other element result = 1 - result # This step not sure ?? result=arr[i+1]^result # xor to find the result if(result==1): print(i) i=i+1 Here i am using the first element to find the number result=arr[i] But it is not workin for both cases . Please help me in this regard
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91910150
has comment: http://stackoverflow.com/comment/91910070
tagged with: python
has answer: http://stackoverflow.com/a/52484386
accepted answer: http://stackoverflow.com/a/52484386
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91910107
has comment: http://stackoverflow.com/comment/91910047
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91910044
has comment: http://stackoverflow.com/comment/91909991
has comment: http://stackoverflow.com/comment/91910081
has title: An array or size unknown with all zeros and ones find the starting with XOR function python
score: 0
has comment: http://stackoverflow.com/comment/91910071

http://stackoverflow.com/a/52461282
type: Answer
has comment: http://stackoverflow.com/comment/91864718
upvote count: 1
score: 1
has body: Annotate Category objects (with an extra attribute) First of all, I think it makes more sense to query from the Category object, then perhaps we do not even need to perform a proper group by, like: Category.objects.annotate(total=Sum('expenses__amount')) This will result in a QuerySet where every Category has an extra attribute .total. This might be better, since then you have access to all attributes of Category, and it will behave like a Category. Querying for a QuerySet of dictionaries If you only want a QuerySet of dictionaries, you need to add an .order_by(..) attribute at the end (yes, I know that sounds weird), like: qs = Category.objects.values( 'name' ).annotate( total=Sum('expenses__amount') ).order_by('name') This will then result in a: &lt;QuerySet [ { 'name': 'bar', 'total': 14.0 } { 'name': 'foo', 'total': 25.0 } ]&gt; Note however that if two categories have the same name, these will add up, which might not be ideal.
accepted answer of: http://stackoverflow.com/q/52461231
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52461231

http://stackoverflow.com/a/52573491
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52573441
upvote count: 2
has body: Sets are unordered collections. What you want is impossible. Consider these alternatives: list, ordered but permits duplicates. dict.keys in Python 3.6+, where dictionaries are insertion ordered. OrderedDict.keys in Python versions prior to 3.6. Create a custom class, e.g. this recipe. Use a 3rd party library, e.g. ordered-set. See also: Does Python have an ordered set?
has comment: http://stackoverflow.com/comment/92083209

http://stackoverflow.com/comment/92098313
type: QuestionComment
score: 1
has text: What happened to `colg` ?
comment on: http://stackoverflow.com/q/52563359
type: Comment

http://stackoverflow.com/a/52463120
score: 1
answers question: http://stackoverflow.com/q/52462931
type: Answer
has body: You can use Sum() here, self.World_population = Countries.objects.aggregate(Sum('Population')) https://docs.djangoproject.com/en/2.1/topics/db/aggregation/
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/52506394
has comment: http://stackoverflow.com/comment/91985460
upvote count: 1
has comment: http://stackoverflow.com/comment/92023391
has body: as brittenb noticed, try apply function in pandas. import pandas as pd df = pd.read_excel("somefile.xlsx") df['c'] = df.apply(lambda r: list(range(r['a'], r['b']+1)), axis=1) Update If you want to add rows, writing in pandas may get complicated. If you don't care much about speed and memory, classic python style seems easier to understand. ary = [] for i,r in df.iterrows(): for j in range(r['a'], r['b']+1): ary.append( (r['a'], r['b'], j) ) df = pd.DataFrame(ary, columns = ['a','b','c'])
has comment: http://stackoverflow.com/comment/91977520
downvote count: 0
has comment: http://stackoverflow.com/comment/92023400
type: Answer
answers question: http://stackoverflow.com/q/52505620
has comment: http://stackoverflow.com/comment/92012232
score: 1

http://stackoverflow.com/q/52570588
has answer: http://stackoverflow.com/a/52570799
has answer: http://stackoverflow.com/a/52596929
score: 0
answer count: 3
has body: I am writing a program that should have the output that looks like this. 111111111 222222222 333333333 444444444 555555555 666666666 777777777 888888888 999999999 I have written this code : for i in range(10): for j in range(10): print (str(i) * i) print() but this doesn't seem right! Any thoughts?
type: UnansweredQuestion
has title: What's wrong with this nested loop?
tagged with: python
has answer: http://stackoverflow.com/a/52570612
tagged with: loops
has comment: http://stackoverflow.com/comment/92077884
type: Question

http://stackoverflow.com/q/52452580
tagged with: python
tagged with: absolute-value
tagged with: integer
type: UnansweredQuestion
tagged with: addition
tagged with: floating-point
upvote count: 1
has answer: http://stackoverflow.com/a/52452586
type: Question
score: 1
has title: add floating point and integer and take absolute value
has body: Hello I am very new to code and I need to know how to output the value obtained by calculating |x+y| where x is a floating point and y is an integer, both unknown inputs. I have tried many things and cannot succeed please help me. This is what I have now but I know it is very wrong :( In most cases when trying things I get the error TypeError: unsupported operand type(s) for +: 'int' and 'str' This was my most recent attempt: x = int(input()) y = input() w = (x + y) print (abs(w))
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/68750820
answers question: http://stackoverflow.com/q/52461587
type: Answer
score: 2
downvote count: 0
has body: Adapted from ron rothman with a basic auth solution using werkzeug. from bottle import auth_basic, request, route from werkzeug.security import generate_password_hash, check_password_hash users = {'user1': generate_password_hash('pwd!')} def is_authenticated_user(user, password): # You write this function. It must return # True if user/password is authenticated, or False to deny access. return user in users and check_password_hash(users[user], password) @route('/') @auth_basic(is_authenticated_user) def home(): return ['hooray, you are authenticated! your info is: {}'.format(request.auth)]
upvote count: 2

http://stackoverflow.com/q/52587405
accepted answer: http://stackoverflow.com/a/52588425
tagged with: django
tagged with: python
has body: For a view that extends a generic ListAPIView and returns a queryset by simply assigning a collection to the View queryset attribute, like so: class MyView(ListAPIView): queryset = MyModel.objects.all() How can the queryset be retrieved in the TestCase for this view? def test_my_view(self): request = self.factory.get('my/url') # self.factory was set in the setUp method response = MyView.as_view()(request) self.assertEqual(response.status_code, 200) # I'd like to now test the query set, something like # self.assertQuerysetEqual(response.queryset, []) I've found that on querysets that are assigned to an attribute, the way to retrieve the queryset is this: response.context['queryset_attribute_name'] But I'd like my view to act like a simple REST endpoint for the front end and not add the attribute name to it. This seems like such a simple thing to do, but I'm new to Django and just can't figure out how to do it and already wasted way too much time searching for it...
type: AnsweredQuestion
tagged with: django-views
has title: Django REST TestCase: How to retrieve a response queryset that wasn't assigned to an attribute?
score: 0
type: Question
has comment: http://stackoverflow.com/comment/92111032
has answer: http://stackoverflow.com/a/52588425
tagged with: django-testing
has comment: http://stackoverflow.com/comment/92110863
has comment: http://stackoverflow.com/comment/92111202
tagged with: django-queryset
answer count: 1

http://stackoverflow.com/a/52582648
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92101241
accepted answer of: http://stackoverflow.com/q/52580706
has comment: http://stackoverflow.com/comment/92101255
answers question: http://stackoverflow.com/q/52580706
has comment: http://stackoverflow.com/comment/92101214
has comment: http://stackoverflow.com/comment/92100776
has comment: http://stackoverflow.com/comment/92101186
has body: You shouldn't need a manual loop here. You can compare a series to a shifted version for itself, then use pd.Series.cumsum and map via dictionary. Here's a demo: from itertools import chain file_days = [['17 Sep 2017'], ['15 Sep 2017'], ['12 Sep 2017'], ['11 Sep 2017'], ['10 Sep 2017'], ['08 Sep 2017'], ['01 Sep 2017'], ['31 Aug 2017'], ['28 Aug 2017'], ['27 Aug 2017'], ['26 Aug 2017'], ['25 Aug 2017'], ['24 Aug 2017']] d = dict(enumerate(chain.from_iterable(file_days[::-1]))) df['date'] = (df['game'] &lt; df['game'].shift()).cumsum().map(d) Result: print(df'game', 'date') game date 0 23:00 24 Aug 2017 1 23:30 24 Aug 2017 2 23:00 25 Aug 2017 3 00:00 26 Aug 2017 4 23:00 26 Aug 2017 5 23:00 26 Aug 2017 6 23:00 26 Aug 2017 7 23:30 26 Aug 2017 8 23:30 26 Aug 2017 9 00:00 27 Aug 2017 10 00:00 27 Aug 2017 11 00:00 27 Aug 2017 12 01:00 27 Aug 2017 13 17:00 27 Aug 2017 14 20:30 27 Aug 2017 15 00:00 28 Aug 2017 16 23:00 28 Aug 2017 17 23:00 28 Aug 2017 18 23:00 28 Aug 2017 19 23:00 28 Aug 2017 20 23:00 28 Aug 2017 21 23:30 28 Aug 2017 22 23:30 28 Aug 2017 23 23:30 28 Aug 2017 24 00:00 31 Aug 2017 25 00:00 31 Aug 2017 26 00:00 31 Aug 2017 27 00:00 31 Aug 2017 28 00:30 31 Aug 2017 29 01:00 31 Aug 2017 30 02:00 31 Aug 2017 31 02:00 31 Aug 2017 32 00:30 01 Sep 2017 33 17:00 01 Sep 2017 34 17:00 01 Sep 2017 35 17:00 01 Sep 2017 36 17:00 01 Sep 2017 37 17:00 01 Sep 2017 38 17:00 01 Sep 2017 39 17:00 01 Sep 2017 40 17:00 01 Sep 2017 41 20:05 01 Sep 2017 42 20:25 01 Sep 2017 43 20:25 01 Sep 2017 44 00:30 08 Sep 2017 45 23:10 08 Sep 2017 46 02:20 10 Sep 2017 47 00:25 11 Sep 2017 48 17:00 11 Sep 2017 49 17:00 11 Sep 2017
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92100834
has comment: http://stackoverflow.com/comment/92100826
has comment: http://stackoverflow.com/comment/92100729
type: Answer

http://stackoverflow.com/q/52488587
has answer: http://stackoverflow.com/a/73838535
type: Question
has answer: http://stackoverflow.com/a/52494464
has comment: http://stackoverflow.com/comment/91918492
score: 0
has comment: http://stackoverflow.com/comment/91918377
has answer: http://stackoverflow.com/a/52488804
has comment: http://stackoverflow.com/comment/91918454
has body: I am doing my assignment rn and there are some problems showed up, I want to return true or false in my function, but It shows nothing at the end. import math import decimal #1 def pythagorean_pair(): a = input("Type a number A(Must be an integer): ") if a.isdigit(): a=int(a) b = input("Type a number B(Must be an integer): ") if b.isdigit(): b = int(b) c = a**2 + b**2 ans = c**(1/2) ans = ans - int(ans) if ans == 0: return (True) print ("True, they are pythagorean pair!") else: return (False) print ("False, they are not pythagorean pair!") else: print ("Please input an integer!!") else: print ("Please input an integer!!") pythagorean_pair()
has comment: http://stackoverflow.com/comment/91918464
answer count: 4
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91918418
has comment: http://stackoverflow.com/comment/91920647
has comment: http://stackoverflow.com/comment/91919062
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91918478
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52489779
has title: Python Function return nothing

http://stackoverflow.com/q/52434246
downvote count: 2
has answer: http://stackoverflow.com/a/52434460
type: Question
upvote count: 0
score: -2
has body: Could you provide me an example in python how to extract text entries using starting reference and the end reference point? For example the file "test.txt" has content as follows: * start123 1234567 abcdefg xyz1234 * end123 I want python to search for "* start123" once found, look for end point "* end123" then any entries in between are extracted and saved into a new file "test2.txt" as is. I know it can be done in grep or awk but if you could provide me a sample in python, I could reuse that to accomplish my next step.
answer count: 2
has title: Extracting entries in a file base from reference point using python
favorite count: 0
has answer: http://stackoverflow.com/a/52434462
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52489440
has comment: http://stackoverflow.com/comment/91920148
type: Question
has comment: http://stackoverflow.com/comment/91920113
answer count: 1
has comment: http://stackoverflow.com/comment/91920196
has comment: http://stackoverflow.com/comment/91920068
favorite count: 0
has answer: http://stackoverflow.com/a/52489511
score: 0
has comment: http://stackoverflow.com/comment/91919992
linked to: http://stackoverflow.com/q/613183
has comment: http://stackoverflow.com/comment/91919959
has body: How to sort dictionary inside dictionary? dic={doc1: {'qq': 5, 'ww': 6, 'gg': 2}, doc2: {'xx': 1, 'cc': 9, 'hh': 4}} I want it to be like this (sorted desc on values of inner dictionary) dic={doc1: {'ww': 6, 'qq': 5, 'gg': 2}, doc2: {'cc': 9, 'hh': 4, 'xx': 1}} I've looked here, but that seems to solve only particular problem. I have thousands of keys (doc3, doc4,...), so I want something more generic. Thanks EDIT I figured it out. Since I can't post solution solution is here: import operator for q in dic: dummydict=dic[q] sorted_d = sorted(dummydict.items(), key=operator.itemgetter(1), reverse=True) sortedDic[q]=dict(sorted_d) I understand that you might say that dictionary will not necessarily preserve its order. I run on 3.6.4, and it preserves
duplicate of: http://stackoverflow.com/q/613183
tagged with: python-3.x
linked to: http://stackoverflow.com/q/16412563
has comment: http://stackoverflow.com/comment/91919986
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91920028
has title: Sorting dictionary inside dictionary

http://stackoverflow.com/comment/92076791
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52569791
has text: I updated the question @Feng

pexpect
tags question: http://stackoverflow.com/q/52562394
type: Tag
tags question: http://stackoverflow.com/q/52519659
tag name: pexpect
tags question: http://stackoverflow.com/q/52450875

http://stackoverflow.com/comment/92171326
has text: @buffcat i have change to `json = data` , may be it can help you
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52549460
type: Comment

http://stackoverflow.com/comment/91850492
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52452963
has text: right on. if not license_exists did work. :) more than one way to skin a cat?! :) Would you mind if i asked you a couple of other questions about this? Chat maybe?
type: AnswerComment

http://stackoverflow.com/comment/91809944
has text: The OP is to invert colors only between two contours and not the entire image. Added one more image to make the question more clear
comment on: http://stackoverflow.com/q/52432549
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92092112
type: Comment
type: QuestionComment
has text: Have you looked at `part.EdgeArray`? I believe you'll have to `import part` explicitly, and you can create a new EdgeArray from a list of edges (`allApps` in your case): `...edges=part.EdgeArray(allApps))`
comment on: http://stackoverflow.com/q/52573521
score: 0

http://stackoverflow.com/q/52557573
favorite count: 0
has answer: http://stackoverflow.com/a/52564144
has body: I have been trouble with trying to find a way to display a 3 element list in the form of a table. What I actually care about is drawing the table. I would like to draw a 1by3 table for each ylabel in a plot. Below is what I have so far. If I can get each Table instance to show up, I will have what I want. Right now a reference to a table appears and I'm not sure why. If you actually look in the center left where the reference locations appear, you can see one 1by3 table. Is it possible using matplotlib to generate a new table for each ylabel? The table info is directly related to each row in the bar graph, so it's important that I have a way that they line up. The number of rows in the bar graph is dynamic, so creating 1 table for the whole figure and trying to dynamically line up the rows with the corresponding bar graph is a difficult problem. # initialize figure fig = plt.figure() gs = gridspec.GridSpec(1, 2, width_ratios=[2, 1]) fig.set_size_inches(18.5, 10.5) ax = fig.add_subplot(gs[0]) #excluded bar graph code # create ylabels for row in range(1,len(data)): ylabel = [str(data[row][0]),str(data[row][1]),str(data[row][2])] ylabels.append(ylabel) #attempting to put each ylabel in a 1by3 table to display pos = np.arange(0.5,10.5,0.5) axTables = [None] * len(ylabels) for x in range(0,len(ylabels)): axTables[x] = fig.add_subplot(gs[0]) ylabels[x] = axTables[x].table(cellText=[ylabels[x]], loc='left') locsy, labelsy = plt.yticks(pos,ylabels)
tagged with: python
has comment: http://stackoverflow.com/comment/92054883
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Drawing a Table at the positions of yticks
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52564144
upvote count: 1
answer count: 1

http://stackoverflow.com/q/52580018
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52580075
downvote count: 0
answer count: 1
has title: Different colors for different datapoints for matplotlib
favorite count: 0
has body: I have my x and y coordinates saved in variable x and y respectively. Below is the plot that I get when I make a scatter plot using x,y coordinates. The code used to make the plot is: import matplotlib.pyplot as plt for i in range(len(x)): plt.scatter(x[i], y[i]) My question is that even though no color parameter was provided, plt.scatter automatically assigned different colors to the data points though the official documentation suggests that the default value is "b" as for "blue".
tagged with: python
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52580075
tagged with: plot
type: Question
score: 1

http://stackoverflow.com/q/52481693
has title: How to invoke events on a pod using kubectl
has comment: http://stackoverflow.com/comment/91907978
downvote count: 3
has comment: http://stackoverflow.com/comment/91924790
has body: I would like to monitor the pods running on my cluster, using a python script. I wrote that script, which will check if there are new events happening on my pods (+extra logic and custom logging). Now I would like to know if my script is correct. Is there a way to invoke events on the pods by hand, i.e. using kubectl? Thanks!
upvote count: 0
tagged with: monitoring
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/52497106
tagged with: kubernetes
tagged with: events
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91905303
tagged with: python
has comment: http://stackoverflow.com/comment/91905064
answer count: 1

http://stackoverflow.com/comment/92103562
type: Comment
type: QuestionComment
has text: do you really want to compare `idx` with itself in that if statement?
comment on: http://stackoverflow.com/q/52584291
score: 0

http://stackoverflow.com/a/73232232
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52581576
has body: I advise you to keep the file in the same path/location where you are running the terminal

http://stackoverflow.com/a/52527949
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91996131
type: Answer
has body: You can use the pexpect module for this. passwd will print out the word password on every interactive line (it may be capitalized, depending on your system), so the approach I will use here simply has pexpect wait for the interactive prompt to be printed before sending the next line. passwd typically asks for the old password once, and the new password twice. Something like this should work: import pexpect def change_password(username, sudo_password, new_password): process = pexpect.spawn("sudo passwd " + username) process.expect("password") process.sendline(sudo_password) process.expect("password") process.sendline(new_password) process.expect("password") process.sendline(new_password) process.close() username = "FakeUser" sudo_password = "sudopass" new_password = "new" change_password(username, sudo_password, new_password) Update: since you are using sudo, you will actually be asked for your sudo password first, and then you will be allowed to set the password for an arbitrary user without having to know their original password. I have re-labeled the variables to reflect this. If you want to do this from a user account without sudo privileges, you can still do this, but you will need to switch users first (and likely remove the use of sudo, which would fail for an unprivileged user).
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/52527861
answers question: http://stackoverflow.com/q/52527861

http://stackoverflow.com/comment/92005210
type: QuestionComment
has text: Err, that's completely different to the structure in your question. Please edit that into the question and remove the incorrect JSON structure. `data['data']['quotes']['USD']['price']`
score: 1
comment on: http://stackoverflow.com/q/52532637
type: Comment

http://stackoverflow.com/a/52554395
accepted answer of: http://stackoverflow.com/q/52553102
has comment: http://stackoverflow.com/comment/92049131
has body: Consider this line of code: for s in SOIList and valuesList: It is not doing what you expect. From the comments to an earlier version of this answer it appears you want to iterate over SOIList and valuesList in parallel (ie: each time through the loop you want one item from one list and one item for the other). The way to do that is explained nicely in the answers to this question: How to iterate through two lists in parallel? In your case the code would look like this: for s, v in zip(SOIList, valuesList): if s == selectedConfig.get() and v == selectedConfig.get(): ...
answers question: http://stackoverflow.com/q/52553102
type: Answer
has comment: http://stackoverflow.com/comment/92048043
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92049242
has comment: http://stackoverflow.com/comment/92048174
has comment: http://stackoverflow.com/comment/92048276
has comment: http://stackoverflow.com/comment/92048403
score: 0
has comment: http://stackoverflow.com/comment/92049679

http://stackoverflow.com/q/52509565
type: Question
tagged with: stdout
score: 0
has title: What is the best way to read a file from stdin using bash script and pass the read lines to a python script
tagged with: bash
has comment: http://stackoverflow.com/comment/91959631
answer count: 1
has comment: http://stackoverflow.com/comment/91959562
has answer: http://stackoverflow.com/a/52509740
tagged with: stdin
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91959683
has comment: http://stackoverflow.com/comment/91959715
has body: In my job there is an ancient piece of code written in C, that is called by some other code with the following command: ./codeName &lt; fileToRead.in &gt; fileToWrite.out The C code read the fileToRead.in file, perform some tasks and then print its results to the fileToWrite.out. The problem: The thing is that I'm trying to rewrite the C code in Python, but in order to keep the compatibility, the script must be called exactly the same way. Possible solution: Since to call python scripts you need to include the ".py" extension, my first thought was to write some bash code, that read the file via stdin, pass the values to a python script, and then write it to the respective file. Keep in mind that I have zero experience with bash scripts, but this piece of code seems to be promising for my task: cat&lt;&amp;0 | while read a; do # at this point, the current line is associated with $a # maybe I can send each line to the python script? done&gt;&amp;1 Finally, is there a way to read the file names provided with the "&lt;" and ">" operators in bash?
has comment: http://stackoverflow.com/comment/91959278

http://stackoverflow.com/comment/91989219
type: Comment
comment on: http://stackoverflow.com/q/52524586
has text: Okay, how can the desired output be achieved using that method?
score: 0
type: QuestionComment

multithreading
tags question: http://stackoverflow.com/q/52574381
tags question: http://stackoverflow.com/q/52523553
tags question: http://stackoverflow.com/q/52435492
type: Tag
tags question: http://stackoverflow.com/q/52547801
tags question: http://stackoverflow.com/q/52504199
tags question: http://stackoverflow.com/q/52471590
tags question: http://stackoverflow.com/q/52483655
tags question: http://stackoverflow.com/q/52549069
tags question: http://stackoverflow.com/q/52465237
tags question: http://stackoverflow.com/q/52507999
tags question: http://stackoverflow.com/q/52437978
tags question: http://stackoverflow.com/q/52582271
tags question: http://stackoverflow.com/q/52505078
tags question: http://stackoverflow.com/q/52501477
tags question: http://stackoverflow.com/q/52579021
tags question: http://stackoverflow.com/q/52462641
tags question: http://stackoverflow.com/q/52543336
tags question: http://stackoverflow.com/q/52559854
tags question: http://stackoverflow.com/q/52524790
tags question: http://stackoverflow.com/q/52468911
tags question: http://stackoverflow.com/q/52507601
tags question: http://stackoverflow.com/q/52490716
tags question: http://stackoverflow.com/q/52439021
tags question: http://stackoverflow.com/q/52474834
tags question: http://stackoverflow.com/q/52550444
tags question: http://stackoverflow.com/q/52511631
tags question: http://stackoverflow.com/q/52435589
tags question: http://stackoverflow.com/q/52461514
tags question: http://stackoverflow.com/q/52474282
tags question: http://stackoverflow.com/q/52539899
tags question: http://stackoverflow.com/q/52445427
tags question: http://stackoverflow.com/q/52497692
tags question: http://stackoverflow.com/q/52513254
tags question: http://stackoverflow.com/q/52475073
tags question: http://stackoverflow.com/q/52482614
tags question: http://stackoverflow.com/q/52507748
tags question: http://stackoverflow.com/q/52526022
tag name: multithreading
tags question: http://stackoverflow.com/q/52521602

http://stackoverflow.com/comment/91830527
comment on: http://stackoverflow.com/q/52436197
type: Comment
score: 0
has text: Not really, this is just the solution I had so far. So it would be better to have list of small dicts? Can you give me example on how to do that? Thanks
type: QuestionComment

http://stackoverflow.com/comment/91825180
score: 0
type: AnswerComment
has text: I don't know any specific resource for learning regular expressions but with just googling you can find lots of useful stuff like tutorials, trying your regular expressions online etc.
type: Comment
comment on: http://stackoverflow.com/a/52441091

http://stackoverflow.com/comment/92106247
score: 0
type: Comment
type: QuestionComment
has text: What do you want to do with `lookupTable`?
comment on: http://stackoverflow.com/q/52585529

http://stackoverflow.com/comment/91877898
comment on: http://stackoverflow.com/q/52468045
score: 1
type: Comment
has text: I'm curious to see how did you use `map`!
type: QuestionComment

http://stackoverflow.com/comment/108583522
has text: 1000 upvotes to this question. I scoured through 100s of tuts and none of them seem to answer this question.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52560419
type: Comment

http://stackoverflow.com/q/52506042
answer count: 4
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91952598
has answer: http://stackoverflow.com/a/52506060
has answer: http://stackoverflow.com/a/52506089
has answer: http://stackoverflow.com/a/52506138
has comment: http://stackoverflow.com/comment/91952577
favorite count: 0
score: -1
type: Question
has body: I was looking at the python documentation about set(), but I'm still trying to understand why does this function deletes repeated characters in a string, for example: set("apple") returns {"a","p","l","e"}. Is it a special property of sets?
has title: Python: Constructor Set()
tagged with: python
has answer: http://stackoverflow.com/a/52506079
tagged with: set
has comment: http://stackoverflow.com/comment/91952588
downvote count: 1

http://stackoverflow.com/comment/91942022
type: Comment
has text: @Fred Could you give me some of the ideas? What information do you need to clarify the question? I think what I want is the same as the above comment of brunodesthuilliers.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52500193

http://stackoverflow.com/comment/91818137
type: QuestionComment
has text: @Mr.T yes sorry .. it can be a list or np.array I am talking generally
comment on: http://stackoverflow.com/q/52437577
score: 1
type: Comment

http://stackoverflow.com/comment/92087666
score: 0
has text: Is there no way to access a graph from an excel file(if graph is plotted by matplotlib and then inserted in excel ) as on opening the Excel file by openpyxl graph is not lost - stovfl
comment on: http://stackoverflow.com/q/52569861
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52475712
has body: Few things to note: No need to use width and height option when using custom sized fonts because width and height varies with the font Don't set default value to empty string, rather set it to string containing a two space The size of the font is too big. Decrease it. I recommend to change the size of 70 to 30. The main point in your code is not t use width and height options. Use T1text.set(" ") rather than T1text.set("") so there will not too much difference of size when changing text. Here is an example code: import tkinter as Tk root = Tk.Tk() T1text = Tk.StringVar() T1 = Tk.Button(root, textvariable = T1text,font = ("Helvetica", 30) ,bg="red") T1.grid(row = 1, column = 0) T1text.set(" ") root.mainloop() Here is another example code that changes the text on click: import tkinter as Tk root = Tk.Tk() def upd(): print(str(T1text.get())) T1text.set("O" if str(T1text.get()) == "X" or str(T1text.get()) == " " else "X") T1text = Tk.StringVar() T1 = Tk.Button(root, textvariable = T1text,font = ("Helvetica", 30) ,bg="red",command=upd) T1.grid(row = 1, column = 0) T1text.set(" ") root.mainloop() You can change the size of font as smaller or larger you want!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52460939

http://stackoverflow.com/q/52525362
tagged with: python
accepted answer: http://stackoverflow.com/a/52526996
type: AnsweredQuestion
has title: Combining CNN with LSTM using Tensorflow Keras
possible better answer: http://stackoverflow.com/a/52850420
has body: I'm using pre-trained ResNet-50 model and want to feed the outputs of the penultimate layer to a LSTM Network. Here is my sample code containing only CNN (ResNet-50): N = NUMBER_OF_CLASSES #img_size = (224,224,3)....same as that of ImageNet base_model = ResNet50(include_top=False, weights='imagenet',pooling=None) x = base_model.output x = GlobalAveragePooling2D()(x) predictions = Dense(1024, activation='relu')(x) model = Model(inputs=base_model.input, outputs=predictions) Next, I want to feed it to a LSTM network, as follows... final_model = Sequential() final_model.add((model)) final_model.add(LSTM(64, return_sequences=True, stateful=True)) final_model.add(Dense(N, activation='softmax')) But I'm confused how to reshape the output to the LSTM input. My original input is (224*224*3) to CNN. Also, should I use TimeDistributed? Any kind of help is appreciated.
has answer: http://stackoverflow.com/a/52850420
tagged with: tensorflow
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/42313412
has comment: http://stackoverflow.com/comment/100902448
answer count: 2
tagged with: neural-network
has comment: http://stackoverflow.com/comment/100837634
downvote count: 0
score: 4
tagged with: lstm
has answer: http://stackoverflow.com/a/52526996
tagged with: keras
favorite count: 0

http://stackoverflow.com/comment/91823225
score: 0
comment on: http://stackoverflow.com/a/52438664
type: Comment
has text: @MaxS He doesn't have enough rep to upvote unless you +1 his question
type: AnswerComment

http://stackoverflow.com/comment/92102616
has text: `encoding='ISO-8859-1'`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52583792
score: 0

http://stackoverflow.com/comment/91909657
comment on: http://stackoverflow.com/q/52484094
type: Comment
has text: The question as is now is very abstract. Consider posting a [mcve]
score: 0
type: QuestionComment

http://stackoverflow.com/a/52440448
has comment: http://stackoverflow.com/comment/91823618
upvote count: 1
has comment: http://stackoverflow.com/comment/91823747
has comment: http://stackoverflow.com/comment/91824730
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91824258
downvote count: 0
has comment: http://stackoverflow.com/comment/91828681
accepted answer of: http://stackoverflow.com/q/52440377
has body: You have either not installed the module or the path where the module is installed is not included in your current python PATH. I recommend to use pip to install all modules. pip install pyrebase You can show your include paths with: python -c "import sys; print('\n'.join(sys.path))" Can you find your pyrebase folder in those paths? If not something is wrong with your config. I also recommend that you use virtualenv, for more information see https://docs.python-guide.org/dev/virtualenvs/ as you can choose python interpreter version and depedencies for every project and you don't have to mix modules needed by other projects. It also always creates a clean state for a new project.
answers question: http://stackoverflow.com/q/52440377
type: Answer
has comment: http://stackoverflow.com/comment/91824366
has comment: http://stackoverflow.com/comment/91847825
score: 1

http://stackoverflow.com/a/52582386
type: Answer
has body: This solution worked finally... import slumber class ParseAuth(AuthBase): def __call__(self, r): r.headers['x-api-key'] = '&lt;API KEY&gt;' r.headers['Content-Type'] = 'application/json' return r api = slumber.API('https://sample-billing-api.test/2/', append_slash=False, auth=ParseAuth()) response = getattr(self.api, "billing-accounts").get(id=2169)
answers question: http://stackoverflow.com/q/52562916
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52562916

http://stackoverflow.com/a/52468182
type: AcceptedAnswer
type: Answer
has body: You don't need to pass category_name, you only need the category id. The category name should be contained in each of the item fetched from the database. You're getting an error because cat_id is not defined when the function def getCategoryItems(category_name, cat_id) is called. I would suggest, however, if you want to really get all items to just use: @app.route('/') def getAllItems(): items = session.query(Item).all() ... For more info, have a look at the flask-sqlalchemy docs.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52465552
accepted answer of: http://stackoverflow.com/q/52465552
upvote count: 1

http://stackoverflow.com/a/55202069
downvote count: 0
type: Answer
upvote count: 6
has body: On xcode8.3 you need to use either pip2 or pip3 so for example; pip3 install flask
score: 6
answers question: http://stackoverflow.com/q/52470651

http://stackoverflow.com/comment/92083060
type: QuestionComment
has text: Just try using `new_range = random.sample(range(0, 1000), 100).reshape(10,10)` and by the way you don't need `new_range = []`
score: 1
comment on: http://stackoverflow.com/q/52573370
type: Comment

pyqt5
tags question: http://stackoverflow.com/q/52441372
type: Tag
tags question: http://stackoverflow.com/q/52558830
tags question: http://stackoverflow.com/q/52546461
tags question: http://stackoverflow.com/q/52566493
tags question: http://stackoverflow.com/q/52450219
tags question: http://stackoverflow.com/q/52522218
tags question: http://stackoverflow.com/q/52460040
tags question: http://stackoverflow.com/q/52471705
tags question: http://stackoverflow.com/q/52496532
tags question: http://stackoverflow.com/q/52526040
tags question: http://stackoverflow.com/q/52467210
tags question: http://stackoverflow.com/q/52470040
tags question: http://stackoverflow.com/q/52473040
tags question: http://stackoverflow.com/q/52545316
tags question: http://stackoverflow.com/q/52461568
tags question: http://stackoverflow.com/q/52463896
tags question: http://stackoverflow.com/q/52480526
tags question: http://stackoverflow.com/q/52461309
tags question: http://stackoverflow.com/q/52537561
tags question: http://stackoverflow.com/q/52450713
tags question: http://stackoverflow.com/q/52559854
tags question: http://stackoverflow.com/q/52507438
tags question: http://stackoverflow.com/q/52511042
tags question: http://stackoverflow.com/q/52517773
tags question: http://stackoverflow.com/q/52530402
tags question: http://stackoverflow.com/q/52472975
tags question: http://stackoverflow.com/q/52505410
tags question: http://stackoverflow.com/q/52451441
tags question: http://stackoverflow.com/q/52581727
tags question: http://stackoverflow.com/q/52561983
tags question: http://stackoverflow.com/q/52447494
tags question: http://stackoverflow.com/q/52560496
tag name: pyqt5
tags question: http://stackoverflow.com/q/52464699
tags question: http://stackoverflow.com/q/52463969
tags question: http://stackoverflow.com/q/52528627
tags question: http://stackoverflow.com/q/52517516
tags question: http://stackoverflow.com/q/52554477

http://stackoverflow.com/a/52453029
has body: So I saw this while at work when it was posted to code review. I wanted to answer I but had to wait until I got home. I broke your block out into two blocks, one that gets input (I hate redundant code) and one that executes the check and calls for input. I also added a clear error message for digits and non-digits. I am posting the complete code here: # -*-coding: utf-8-*- # !/usr/bin/python3.6 import sys def multi_digits(): digit = get_input() x = True while x: if digit in '23456789': print(f'Yes,you have entered {digit}.') x = False # In elif it looks like int(digit) may throw an error if it isn't a digit but # because of the way if statements work this wont happen. The if statement excutes # digit.isdigit() first, if it returns false it doesn't care about the second condition so # int(digit) only is checked after we confirm digit is actually a digit. elif digit.isdigit() and int(digit) &lt;= 1: print('Invalid input: Digit was not greater than 1') digit = get_input() else: print('Invalid input: no letters allowed') digit = get_input() def get_input() -&gt; str: return input('Enter an integer greater than 1: ') def main(): multi_digits() if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/92089390
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52439284
score: 1

http://stackoverflow.com/comment/92065380
type: QuestionComment
has text: Were you expecting `x` and `y` *not* to be arrays for some reason?
comment on: http://stackoverflow.com/q/52563440
score: 0
type: Comment

http://stackoverflow.com/comment/91849748
type: QuestionComment
comment on: http://stackoverflow.com/q/52452714
has text: How would you want this output to look like? Two arrays? Two dat frames? Everything together in a data frame with `NaN`s filling the missing spaces?
score: 0
type: Comment

http://stackoverflow.com/a/52451021
has body: You could try to open the file twice, once for reading and once for writing. filename = 'text.txt' with open(filename, 'r') as f: text = f.read() print('-' * 20) print('old text:') print(text) replacement_list = [ ('//a', 'Ä'), ('//o', 'Ö'), ('//u', 'Ü'), ('/a', 'ä'), ('/o', 'ö'), ('/u', 'ü'), ('/s', 'ß'), ] for s_old, s_new in replacement_list: text = text.replace(s_old, s_new) print('-' * 20) print('new text:') print(text) with open(filename, 'w') as f: f.write(text.strip())
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52450831

http://stackoverflow.com/comment/91880920
comment on: http://stackoverflow.com/q/52469467
has text: @ninesalt actually I am. I need to match an element in words with a value in values
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52578270
score: 29
possible better answer: http://stackoverflow.com/a/54501315
downvote count: 1
has comment: http://stackoverflow.com/comment/92100827
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52578838
linked to: http://stackoverflow.com/q/76863325
has body: My question is if you can install python with powershell, cmd, vbs or any other language built into Windows already? If this was already asked please redirect me to the answer. "How to install Python using Windows Command Prompt" explains how to install the python if you already have the exe installed, not how to install the exe. EDIT: I am trying to install python with a file on a pc that does not have python installed, only thing restricted might be that the account does not an administrator and if possible in the background.
linked to: http://stackoverflow.com/q/33876657
type: Question
has answer: http://stackoverflow.com/a/60277916
has answer: http://stackoverflow.com/a/75615087
has answer: http://stackoverflow.com/a/70482008
has comment: http://stackoverflow.com/comment/92091695
answer count: 7
tagged with: powershell
favorite count: 0
upvote count: 30
has answer: http://stackoverflow.com/a/52578838
has comment: http://stackoverflow.com/comment/92092617
tagged with: python
has title: Install Python with cmd or powershell
tagged with: cmd
linked to: http://stackoverflow.com/q/46056161
has answer: http://stackoverflow.com/a/54501315
has answer: http://stackoverflow.com/a/77249713
tagged with: python-3.x
has answer: http://stackoverflow.com/a/66979854
has comment: http://stackoverflow.com/comment/92091902

http://stackoverflow.com/comment/92010634
type: AnswerComment
comment on: http://stackoverflow.com/a/52535421
has text: Your indexes should be 9 and 12
type: Comment
score: 0

http://stackoverflow.com/a/52569280
score: 1
has comment: http://stackoverflow.com/comment/92075624
answers question: http://stackoverflow.com/q/52569196
has comment: http://stackoverflow.com/comment/92078867
has comment: http://stackoverflow.com/comment/92075634
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92075598
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92075534
has comment: http://stackoverflow.com/comment/92075704
accepted answer of: http://stackoverflow.com/q/52569196
has body: try to add logger and see what happening. (you can deliver logger to shutil.make_archive) sorry it answer and not comment, i can't comment yet

http://stackoverflow.com/comment/92038189
comment on: http://stackoverflow.com/q/52549370
score: 0
type: Comment
type: QuestionComment
has text: Regarding `sys.argv` `sys.argv[0]` gives the name of the script being called, and argv provides a list of all the arguments passed to the script so `python setup.py test` gives you `['setup.py', 'test']`. https://docs.python.org/3/library/sys.html#sys.argv

http://stackoverflow.com/comment/92039102
has text: Unfortunately it is not public... But why should it change by ID or by XPATH? I don't think it is a problem of loading though, I see the button that it should click when it gets stuck.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52526917

http://stackoverflow.com/comment/92071974
has text: You can get rid of that `float` cast, the OP's using Python 3.
comment on: http://stackoverflow.com/a/52567409
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92109765
comment on: http://stackoverflow.com/q/52587302
type: QuestionComment
type: Comment
score: 3
has text: Right when you open the documentation of the [`random` module for python2.7](https://docs.python.org/2/library/random.html) you can see highlighted in red: **Warning The pseudo-random generators of this module should not be used for security purposes. Use [`os.urandom()`](https://docs.python.org/2/library/os.html#os.urandom) or [`SystemRandom`](https://docs.python.org/2/library/random.html#random.SystemRandom) if you require a cryptographically secure pseudo-random number generator.** You cannot find anything if you don't even try to search for it.

http://stackoverflow.com/a/76370314
type: Answer
answers question: http://stackoverflow.com/q/52588601
upvote count: 2
downvote count: 2
has body: PYGAME ON WEB(Pygbag) Now you can run pygame in browser using the pygbag,for more details you can checkout : https://pygame-web.github.io/ https://github.com/pygame-web/pygbag https://pypi.org/project/pygbag/ For more information you can checkout The pygame-ce discord.(pygame-community discord)
score: 0

http://stackoverflow.com/comment/91807496
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52431827
has text: Thanks. This is useful feedback (both for me and OP).
type: AnswerComment

http://stackoverflow.com/comment/91833170
type: Comment
comment on: http://stackoverflow.com/a/52445156
score: 0
type: AnswerComment
has text: Dicts which are not in list2 should still be in the output list.

http://stackoverflow.com/q/52470363
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/52470411
has title: Storing multiple inputs from user entry
type: AnsweredQuestion
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52470411
score: 0
tagged with: python
has body: I want know how i can create a notifier that can store more than 1 time and note given by user entry from a little gui. this code is the very basic i am using: from datetime import datetime from threading import Timer from tkinter import messagebox from tkinter import * from inputer import * x = datetime.today() y = x.replace(day=q, hour=w, minute=e, second=0, microsecond=0) delta_t = y - x secs = delta_t.seconds+1 def Note(): # in this function i put the commands to open # a small window with the reminder/note print("hello world") #... t = Timer(secs, Note) t.start() "inputer" is the file taking the user input. if for example i want to get 2 reminders at the same day. how do i code that? because now the variables for day and time are fixed and can not store more info to use at a certain time. i am very new to coding sorry if this question seems stupid xd (using python btw)

http://stackoverflow.com/a/52542226
answers question: http://stackoverflow.com/q/52541117
has comment: http://stackoverflow.com/comment/92046774
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92047286
has comment: http://stackoverflow.com/comment/92025963
has comment: http://stackoverflow.com/comment/92028432
has body: Try this ^(\s*)(def.*(?:\n\1\s+.*|\n\s*)+$)

http://stackoverflow.com/comment/91983479
has text: What you describe is not an upsert. An upsert modifies existing data. You're trying to generate a new copy of the data.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52521944

http://stackoverflow.com/comment/92052792
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52556321
has text: with decorator, it's not possible ? with onchange for example ?

http://stackoverflow.com/comment/91922027
has text: updated with example @ImportanceOfBeingErnest
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52489602

http://stackoverflow.com/a/52569436
score: 1
has body: There is the dropna function, e.g. all_data.dropna('time', how='all') But as of now it is only implemented along a single dimension at once, so i am not sure if it does what you wish. I understand you want to remove those lat, lon pairs that are nan for all times? I think you have to turn lat, lon into a pandas multiindex coordinate and then use dropna along this new dimension.
type: Answer
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/52553925

http://stackoverflow.com/q/52535263
has title: Error in importing variables from one python script to another python script
answer count: 1
has body: I have a set of more than 10 variables defined in __main__ of one python script and they are needed to import into another python script to use their values inside different methods. I used from &lt;pythonfile&gt; import var1, var2 ...., var10 in the calling python script but it is giving me error like below:- ImportError: cannot import name 'envName' Sample structure of my A.py and B.py scripts are like this:- A.py if __name__ == '__main__': var1 = "text1" var2 = "text2" var3 = "text3" B.methodA() B.py from A import var1, var2, var3 def methodA() print(var1) This is something I am looking for. Basically I have like more than 10 variables to use in another script (both scripts are in same folder) so need some help to find out the best way to do it. I know the process above I am using could be very stupid and wrong. Can anyone please help me? I am using python3.6 Also what is the best way to import and use these many variables from one python script into another python script?
score: 0
has comment: http://stackoverflow.com/comment/92009944
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92009751
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92009820
type: Question
has answer: http://stackoverflow.com/a/52535482
tagged with: python-import

http://stackoverflow.com/comment/91921263
has text: @Blckknght am using Spyder. I got the solution from the answers below.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52490109
type: QuestionComment

http://stackoverflow.com/comment/92079072
has text: I think your answer is [there](https://stackoverflow.com/questions/42476504/python-get-second-smallest-value-in-nested-lists-recurssion)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52571085
type: QuestionComment

http://stackoverflow.com/comment/91847919
type: Comment
comment on: http://stackoverflow.com/q/52452286
has text: @dawg Ordering does matter. I'm not sure what you mean by "concerned about float values," but I can say that duplicates will be exact to the highest-precision digit.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52598942
has comment: http://stackoverflow.com/comment/92309368
type: Answer
score: 19
has body: You should downgrade your version of testpath: conda install 'testpath&lt;0.4' See issue here: https://github.com/conda-forge/testpath-feedstock/issues/7
downvote count: 0
has comment: http://stackoverflow.com/comment/92596520
upvote count: 19
accepted answer of: http://stackoverflow.com/q/52582563
answers question: http://stackoverflow.com/q/52582563
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92135582

http://stackoverflow.com/comment/91855839
has text: I have edited the question and could please suggest a generic solution when the string is with a regular expression. For example?CLK , ^CLK
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52455171

http://stackoverflow.com/a/52481852
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52481607
has comment: http://stackoverflow.com/comment/91905469
score: 2
has comment: http://stackoverflow.com/comment/91905586
downvote count: 0
has body: This is called a closure. Two basic elements the pair function knows the values of a and b. They are just like local variables in that respect the cons function returns a function, not a value. You have to call the result again So, when you call cons(a, b) you get a function that does something to a and b, only it doesn't know what yet. You have to pass another function for that. Eg my_f = cons(1, 2) result = my_f(lambda x, y: x + y) print(result) # 3 How this is related to your assignment is not very clear. I would only assume that for car, you only want the element a (the head), and for cdr you want the element b (the rest of the list). So, the functions would just return the one argument and ignore the other. Eg car_f = lambda x, y: x cdr_f = lambda x, y: y

http://stackoverflow.com/a/52535620
downvote count: 0
score: 5
has body: There is another way to plot pie chart subplots. You just need to specify domain and annotation(if you want to place name of the trace in the hole of pie chart). Code(based on data from examples in plotly docs): # import all the necessaries libraries import plotly.offline as py import plotly.graph_objs as go # change to your data labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen'] labels2 = ['Helium','Lithium','Aluminium','Phosphorus'] values = [4500,2500,1053,500] values2 = [6500,1500,2700,1286] colors = ['#FEBFB3', '#E1396C', '#96D38C', '#D0F9B1'] colors2 = ['#29ECEC', '#EC7029', '#5E6B6B','#B6E44C'] # Create one trace for each day (Monday, Tuesday and so on) trace1 = go.Pie(labels=labels, values=values, hoverinfo='label+percent', textinfo='value', textfont=dict(size=20), name = 'Monday', # Create hole in pie where we will place day name hole = 0.2, marker=dict(colors=colors, line=dict(color='#000000', width=2) ), # Set where first plot will be plotted domain=dict(x=[0,0.5]) ) trace2 = go.Pie(labels=labels2, values=values2, hoverinfo='label+percent', textinfo='value', textfont=dict(size=20), name='Tuesday', # Create hole in pie where we will place day name hole = 0.2, marker=dict(colors=colors2, line=dict(color='#000000', width=2) ), # Set where second plot will be plotted domain=dict(x=[0.5,1.0]) ) # Fill out the data wtih traces data = [trace1,trace2] # Create one annotation to each day (Monday, Tuesday and so on) ann1 = dict(font=dict(size=20), showarrow=False, text='Monday', # Specify text position (place text in a hole of pie) x=0.23, y=0.5 ) ann2 = dict(font=dict(size=20), showarrow=False, text='Tuesday', # Specify text position (place text in a hole of pie) x=0.78, y=0.5 ) # Specify layout to set the title and annotations to our traces layout = go.Layout(title ='Pie chart subplots', annotations=[ann1,ann2], # Hide legend if you want #showlegend=False ) # Create fig with data and layout fig = go.Figure(data=data,layout=layout) # Plot the plot and save…
answers question: http://stackoverflow.com/q/52521194
upvote count: 5
type: Answer

http://stackoverflow.com/a/52448474
has body: Here you go: def doesMatchPattern(self, string, patterns=[]): for p in patterns: # skip empty patterns if not p: continue # construct regex pattern pattern = '^{}$'.format(p.lower()) if '*' in pattern: pattern = pattern.replace('*', '[^\\s]*') if re.match(pattern, string, re.I): return True return False print doesMatchPattern('june', ['Ju*']) print doesMatchPattern('june', ['june']) print doesMatchPattern('june', ['*u*']) print doesMatchPattern('june', ['Junee']) print doesMatchPattern('june', ['October']) print doesMatchPattern('june', ['*'])
answers question: http://stackoverflow.com/q/52446975
has comment: http://stackoverflow.com/comment/91842055
accepted answer of: http://stackoverflow.com/q/52446975
has comment: http://stackoverflow.com/comment/107056498
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91840835
score: 0
type: Answer

http://stackoverflow.com/q/52586784
has answer: http://stackoverflow.com/a/52587319
downvote count: 0
tagged with: cython
has comment: http://stackoverflow.com/comment/92109232
type: Question
tagged with: http://stackoverflow.com/tag/c
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/92109084
favorite count: 0
has comment: http://stackoverflow.com/comment/92111161
has comment: http://stackoverflow.com/comment/92110365
type: UnansweredQuestion
tagged with: python
tagged with: visual-studio
score: 2
has title: Compiling with Cython and "next"
has body: Any time I use 'next' in my code, I'm thrown this error via VS. It does not seem to matter where or how it's used. The code works fine in Python. While I can write around using 'next', is there anything I can do to fix this more intelligently? error C2065: '__Pyx_PyIter_Next2': undeclared identifier Example code (edit): rand = None for i in range(10): if rand == None: next

http://stackoverflow.com/comment/92019464
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52539828
has text: Furthermore the above is usually not terribly inefficient. The performance boost is mainly due to the fact that a regular expression *can* use dynamic programming to check multiple substrings at once.
score: 0

http://stackoverflow.com/q/52503413
downvote count: 0
favorite count: 0
has body: Tried to paste the code from one book (TCP/IP learning) to send a message from client to server. But nothing happens, except the message "The server is ready to receive". Server code: from socket import * serverPort = 12000 serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('', serverPort)) serverSocket.listen(1) print('The server is ready to receive') while 1: connectionSocket, addr = serverSocket.accept() sentence = connectionSocket.recv(1024) capitalizedSentence = sentence.upper() connectionSocket.send(capitalizedSentence) connectionSocket.close() Client code: from socket import * serverName = '0.0.0.0.0' serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName, serverPort)) sentence = input('Input lowercase sentence: ') clientSocket.send(sentence) modifiedSentence = clientSocket.recv(1024) print('From Server: ', modifiedSentence) clientSocket.close()
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52504190
has answer: http://stackoverflow.com/a/52503537
score: 1
tagged with: tcp
has title: TCP client - server code. Doesn't do anything
type: Question
answer count: 2

http://stackoverflow.com/q/52507260
score: 0
tagged with: python
has title: Unable to install PyMySQL
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92031974
tagged with: pip
has comment: http://stackoverflow.com/comment/91958576
has comment: http://stackoverflow.com/comment/92033823
type: Question
tagged with: pymysql
has body: I am trying to install PyMySQL to my computer using pip and I am getting an error message (I am using Python version 3.6). Both of the errors I am getting appear to be traced back to basecommand.py file. The first line of code in question is this one: try: status = self.run(options, args) The error message is below C:\Users\Brian&gt;pip install pymysql Exception: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_internal\basecommand.py", line 228, in main status = self.run(options, args) File "C:\ProgramData\Anaconda3\lib\site-packages\pip\_internal\commands\install.py", line 275, in run build_isolation=options.build_isolation, TypeError: __init__() missing 1 required positional argument: 'req_tracker' I have literally tried coping the code from another Windows user who was able to download PyMySQL without error yet an error is appearing for me. Does anyone know why this might be?

http://stackoverflow.com/comment/91866917
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52458955
type: Comment
has text: I tried again in the command line with python 3.7.0, and the result matches. Then I think there is something wrong with anaconda:(

http://stackoverflow.com/a/52468811
score: 3
has body: EDIT: The simplest way is: &gt;&gt;&gt; df1=df1.set_index('id') &gt;&gt;&gt; df2=df2.set_index('id') use combine_first on df2 &gt;&gt;&gt; df2.combine_first(df1) value id 100010 25 100011 22 100012 35 100013 36 OLD post: As an alternative, you can use the standard python dictionary &gt;&gt;&gt; df1=df1.set_index('id') &gt;&gt;&gt; df2=df2.set_index('id') make a dictionary out of df1 &gt;&gt;&gt; d = df1.to_dict( 'index' ) &gt;&gt;&gt; d {'100012': {'value': '30'}, '100010': {'value': '25'}, '100011': {'value': '22'}} update() with the other dataframe dictionary - duplicate keys will be updated with the full row &gt;&gt;&gt; d.update( df2.to_dict( 'index' ) ) &gt;&gt;&gt; d {'100012': {'value': '35'}, '100013': {'value': '36'}, '100010': {'value': '25'}, '100011': {'value': '22'}} Turn it back into a dataframe: &gt;&gt;&gt; pd.DataFrame.from_dict( d, 'index' ) value 100010 25 100011 22 100012 35 100013 36 If you want to keep it all in pandas - RafaelC's solution is better
downvote count: 0
upvote count: 3
answers question: http://stackoverflow.com/q/52468312
type: Answer

http://stackoverflow.com/q/52474217
accepted answer: http://stackoverflow.com/a/52497096
has comment: http://stackoverflow.com/comment/91890673
type: Question
has comment: http://stackoverflow.com/comment/91890829
has comment: http://stackoverflow.com/comment/91891497
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91891106
favorite count: 0
has answer: http://stackoverflow.com/a/52497096
has answer: http://stackoverflow.com/a/52485184
tagged with: serial-port
upvote count: 1
tagged with: python
has body: I've created connection with python to stm32 usb port, and wanted to execute some actions while the certain button is pressed. (one transmit "1" and the other transmit "0"). Why this solution is not working as i wanted? def read(): while True: if ser.read(1) == 0: print "Zero received" report.send(SET_LEFT()) if ser.read(1) == 1: report.send(SET_RIGHT()) t = threading.Thread(target = read, name = 'thread1') t.start() Here is serial initialization and signal_handler function that close port connection. ser = serial.Serial( port='COM7', baudrate=9600, parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0) def signal_handler(signal, frame): ser.close() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) The error that i receive when i close connection with "crtl + c" is Exception in thread thread1: Traceback (most recent call last): File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner self.run() File "C:\Python27\lib\threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "C:\usbpy\usb_send.py", line 27, in read if ser.read() == 0: File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 269, in read win32.ResetEvent(self._overlapped_read.hEvent) AttributeError: 'NoneType' object has no attribute 'hEvent' It seems that the button are not detected during executing main program, when i checked the connection and data that i received with another python program the result was: link Best Regards
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52485184
score: 1
has title: python - reading serial data sent by stm

http://stackoverflow.com/q/52494425
favorite count: 0
has answer: http://stackoverflow.com/a/52496856
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91933593
has comment: http://stackoverflow.com/comment/91934092
tagged with: python
tagged with: cmake
has body: I have a CMake based project that uses both C++ and python sources. Tests are added via add_test for all C++ tests in a folder structure like: src mynamespace/foo.cpp mypyspace/mypkg/__init__.py mypyspace/mypkg/bar.py test mynamespace/testFoo.cpp mypyspace/testBar.py In testBar.py I have a import mypkg and want to run this with add_test(... COMMAND pytest WORKING_DIRECTORY .../test) Of course it does not find my package, but I also do not want to install it (it is required to generate some stuff during build and is actively developed as part of the other sources). What is the correct/preferred way of executing those tests? Notes: I don't want to move the sources out of src or tests out of test set_tests_properties may set environment variables. I think setting PYTHONPATH=.../src/mypyspace should work, but that would also ignore changes to the users PYTHONPATH.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91930856
has comment: http://stackoverflow.com/comment/91932809
has comment: http://stackoverflow.com/comment/91933198
tagged with: pytest
possible better answer: http://stackoverflow.com/a/78583839
type: Question
score: 5
linked to: http://stackoverflow.com/q/47859986
upvote count: 5
accepted answer: http://stackoverflow.com/a/52496856
answer count: 2
linked to: http://stackoverflow.com/q/1896918
downvote count: 0
has comment: http://stackoverflow.com/comment/91933357
has answer: http://stackoverflow.com/a/78583839
has title: Running a pytest test from CMake where the test and sources are in different folders

http://stackoverflow.com/comment/91843227
comment on: http://stackoverflow.com/a/52436815
has text: After testing this version against Alexander's one, for some reason this arithmetic turns out to be less efficient. When called with n = 1e8 this version is approximately .5 seconds less efficient than the other one on my PC. However, thank you for the tip!
type: AnswerComment
score: 0
type: Comment

python-sphinx
tags question: http://stackoverflow.com/q/52536132
tag name: python-sphinx
tags question: http://stackoverflow.com/q/52453412
tags question: http://stackoverflow.com/q/52474177
tags question: http://stackoverflow.com/q/52466582
tags question: http://stackoverflow.com/q/52444780
tags question: http://stackoverflow.com/q/52552081
tags question: http://stackoverflow.com/q/52547869
tags question: http://stackoverflow.com/q/52576040
type: Tag
tags question: http://stackoverflow.com/q/52560257

http://stackoverflow.com/q/52516137
has answer: http://stackoverflow.com/a/52516562
type: Question
has answer: http://stackoverflow.com/a/52516307
accepted answer: http://stackoverflow.com/a/52516307
possible better answer: http://stackoverflow.com/a/52516260
upvote count: 2
has answer: http://stackoverflow.com/a/52516260
has title: How to make a deck of cards with several variables in python?
has answer: http://stackoverflow.com/a/52516319
linked to: http://stackoverflow.com/q/976882
favorite count: 0
has body: I'm trying to make a abnormal deck of cards. Each card will have a color (red, green or blue), a degree (1, 2 or 3), a symbol (triangle, square or circle) and a number (1,2 or 3). I have a class that looks like this: class card: def __init__(self, color, degree, symbol, number): self.color = color self.degree = degree self.symbol = symbol self.number = number def __repr__(self): return "(%s,%s,%s,%s)" %(self.color, self.degree, self.symbol, self.number) I also have the following lists containg all the possible values for the fields and an empty deck where I want the cards to get into. colors = ["red", "green", "blue"] degrees = ["1", "2", "3"] symbols = ["triangle", "square", "circle"] numbers = ["1", "2", "3"] deck = [] I want to create a full deck with every possible card. Preferably, they would be in a random order, but that's not necessary. I know that if it was only a number and color, I could easily do it this way: deck = [card(value, color) for value in range(0, 2) for color in colors] But I can't figure out how to do it with a symbol and a degree as well. I tried to build on more if statements to loop all the list, but that didn't work. I also don't want the same card to appear twice, and I dont want a card that doesn't follow the class rules: they must all be strutured as [color, degree, symbol, number]. Does anyone have a idea how to do this this?
tagged with: python
tagged with: playing-cards
answer count: 4
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/92109275
comment on: http://stackoverflow.com/q/52545269
score: 2
has text: @user2357112 Thanks opening with `rb` does indeed account for the majority of the time difference!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52546386
has answer: http://stackoverflow.com/a/62730167
downvote count: 0
tagged with: pandas
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52546499
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: group-by
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52546499
has title: pandas: groupby multiple columns, concatenating one column while adding another
has body: If I had the following df: amount name role desc 0 1.0 a x f 1 2.0 a y g 2 3.0 b y h 3 4.0 b y j 4 5.0 c x k 5 6.0 c x l 6 6.0 c y p I want to group by the name and role columns, add up the amount, and also do a concatenation of the desc with a , : amount name role desc 0 1.0 a x f 1 2.0 a y g 2 7.0 b y h,j 4 11.0 c x k,l 6 6.0 c y p What would be the correct way of approaching this? Side question: say if the df was being read from a .csv and it had other unrelated columns, how do I do this calculation and then write to a new .csv along with the other columns (same schema as the one read)?
type: Question
possible better answer: http://stackoverflow.com/a/62730167
answer count: 2

http://stackoverflow.com/q/52529767
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91999047
type: Question
answer count: 2
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/52530468
possible better answer: http://stackoverflow.com/a/60458712
has answer: http://stackoverflow.com/a/60458712
has body: #from signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import User, Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() #from models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser from PIL import Image class User(AbstractUser): is_paying_customer = models.BooleanField(default=False) created_at = models.DateTimeField(editable=False) updated_at = models.DateTimeField() def __str__(self): return self.email def save(self, *args, **kwargs): if not self.id: self.created_at = timezone.now() self.updated_at = timezone.now() return super(User, self).save(*args, **kwargs) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=255, blank=True) address = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=255, blank=True) country = models.CharField(max_length=255, blank=True) linked_in = models.CharField(max_length=255, blank=True) objective = models.TextField(blank=True) profile_pic = models.ImageField(default="profile-pics/default.jpg/", upload_to="profile-pics") def __str__(self): return self.user.email def save(self): super().save() img = Image.open(self.profile_pic.path) if img.height &gt; 300 or img.width &gt; 300: output_size = (100, 100) img.thumbnail(output_size) img.save(self.profile_pic.path) #from apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals When I create users from Django admin but the profiles never get created with my users. I have included code from various files in my Django project. I believe I have the correct code but maybe a fresh set of eyes will hel…
has title: My django create user and profile signal doesn't work
upvote count: 1
tagged with: signals
tagged with: django-models
has answer: http://stackoverflow.com/a/52530468

http://stackoverflow.com/a/61846014
has comment: http://stackoverflow.com/comment/138275408
type: Answer
upvote count: 20
answers question: http://stackoverflow.com/q/52566756
downvote count: 0
score: 20
has body: As @grrr answered above, here is the code: conda install -c anaconda python-graphviz conda install -c anaconda pydot

http://stackoverflow.com/a/52565618
has body: It's a bug of the click package issue 1021. You can avoid it by running in the shell instead of in python idle.
accepted answer of: http://stackoverflow.com/q/52564356
answers question: http://stackoverflow.com/q/52564356
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/52482325
upvote count: 2
type: Answer
score: 2
has body: The best way is to build the URL in your view using build_absolute_uri method of HttpRequest, since this will also add the current protocol (https or http): url = request.build_absolute_uri(reverse('detail', kwargs={'driver_id': driver.id})) ctx = Context({'url': url}) template = mailt("""Please hit the link and book a car {{ url }}""") join_message = template.render(ctx) This should lead to http://localhost:8000/drivers/2 displayed in your email message.
has comment: http://stackoverflow.com/comment/91908376
answers question: http://stackoverflow.com/q/52479478
accepted answer of: http://stackoverflow.com/q/52479478
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52451792
type: AcceptedAnswer
has body: lista = [] for price_list_items in price_list: for values in price_list_items: x= values.rstrip(' zł') lsita.append(x) lista = ['479 000', '350 000'] for idx, item in enumerate(lista): item = item.split() item = ''.join(item) lista[idx] = int(item) print(lista) ~/python/stack$ python3.7 sum.py [479000, 350000] Change your last line to append to lista instead of print. Now we have lista = ['479 000', ...] but we want ints to perform operations on. So we can then enumerate our list, from there we can split() and join() to get to here lista = ['479000', ...] then we can just use int(item) and put them back into lista as ints For fun we could do some map and just go from: lista = ['479 000', '350 000'] lista = list(map(lambda x: int(''.join((x.split()))), lista))
type: Answer
has comment: http://stackoverflow.com/comment/91948153
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52451228
has comment: http://stackoverflow.com/comment/91948277
answers question: http://stackoverflow.com/q/52451228
upvote count: 1

http://stackoverflow.com/q/52485109
score: 4
has title: Python Gtk Glade app structure. What are the best practises?
has body: Since I discovered Python, I've created four little applications with Glade + Python + Gtk. For each of them, the structure is a folder, with the name of the app, containing : an "images" folder a main .py file which contains all classes that handle all project windows a .glade file which contains all windows (main app window, about dialog, config dialog, etc.) a style.css file (other files as sqlite file and/or json file if neccessary) Now I'm wondering if this organization is a good practise. Because I've seen a video tutorial in which each window has its own ".ui" file and .py file. Also, other apps seem to be organized like this too and Anjuta projects seem to follow this rule too. Furthermore, the tutorials that show how to create a Python-Gtk-Glade app are almost all one-window projects... So my question is : how do you organize your Python-Gtk-Glade projects or what is the best way to do it? Thanks in advance.
tagged with: project
upvote count: 4
has answer: http://stackoverflow.com/a/52489831
accepted answer: http://stackoverflow.com/a/52489831
type: AnsweredQuestion
downvote count: 0
tagged with: glade
favorite count: 0
type: Question
tagged with: python
tagged with: structure
answer count: 1
tagged with: gtk

http://stackoverflow.com/comment/91898575
comment on: http://stackoverflow.com/q/52474645
score: 0
type: QuestionComment
has text: Is there always a blue rectangle or did you just draw it on this image to help you get started?
type: Comment

http://stackoverflow.com/comment/92076851
score: 0
has text: the map_partition method doesn't exist in bag. I saw it is in dataframe only. I added more example on my question to show my expected outputs. Can you help me get the answer with the updated question? Thanks!
type: Comment
comment on: http://stackoverflow.com/a/52569052
type: AnswerComment

http://stackoverflow.com/comment/91849292
comment on: http://stackoverflow.com/a/52453033
type: Comment
has text: @udadub Both algorithms do a single traversal for a single characters. It just turns out find is done at the C level. This drops the overhead of assignation of indices and items, making it faster by a constant. Time complexity is the same.
score: 1
type: AnswerComment

http://stackoverflow.com/q/52465855
has answer: http://stackoverflow.com/a/52466899
downvote count: 0
favorite count: 0
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91873498
type: UnansweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52466849
tagged with: list
has comment: http://stackoverflow.com/comment/91873497
has title: How to build a function that detects crossover points on 2 lists
score: 1
has body: I have an assignment, I have to write a function that can detect cross over points in two lists. The function is to analyse financial data. So for example, I have two lists of prices (moving averages) as input, and as output I want two separate lists, 1 with the when those prices (moving averages) intersect (i.e times index), and 1 determining which list is higher at point of intersection (I.e higher indeX). I am having trouble coming up with the correct syntax to define the criteria above on python. So far I haven't written anything, since I am stuck. Has anybody done anything similar, are there any tips. Additional info, the assignment concerns moving averages and checking when moving averages intersect. I have been able to write a function that detects moving averages, but I am stuck on this part. Sorry for the lack of code and information. I am pretty sure copy pasting the entire assignment criteria is discouraged here so I tried to explain what my problem is. Identify cross-over indices for two equal-length lists of prices (here: moving averages) Parameters: prices1, prices2: lists of prices (ordered by time) Returns: list of crossover points Each item in the returned list is a list [time_index, higher_index], where: - time_index is the crossover time index (when it happends - higher_index indicates which price becomes higher at timeIndex: either 1 for first list or 2 for second list There are no crossovers before both price lists have values that are not None. You can start making comparisons from the point at which both have number values. Example use: &gt;&gt;&gt; p1 = [1, 2, 4, 5] &gt;&gt;&gt; p2 = [0, 2.5, 5, 3] &gt;&gt;&gt; cross_overs(p1, p2) [[1, 2], [3, 1]] &gt;&gt;&gt; p1 = [None, 2.5, 3.5, 4.5, 4.5, 3.5, 2.5, 1.5, 3.5, 3.5] &gt;&gt;&gt; p2 = [None, None, 3.0, 4.0, 4.333333333333333, 4.0, 3.0, 2.0, 3.0, 2.6666666666666665] &gt;&gt;&gt; cross_overs(p1, p2) [[5, 2], [8, 1]] """ for the first part (i.e identyfying when intersection happened this is what …
answer count: 2
has comment: http://stackoverflow.com/comment/91873958

http://stackoverflow.com/a/52526352
score: 0
has body: The best practice is to include at the beginning of your code in funcs.py There is no need and you should not include pandas in your main.py. Basically when you use import pandas pandas library becomes part of your code.
has comment: http://stackoverflow.com/comment/92015926
type: Answer
has comment: http://stackoverflow.com/comment/91992603
has comment: http://stackoverflow.com/comment/91992702
answers question: http://stackoverflow.com/q/52526269

http://stackoverflow.com/comment/91910507
type: AnswerComment
comment on: http://stackoverflow.com/a/52484193
type: Comment
has text: arr1 is for integer and arr2 is for storing + - * /
score: 0

http://stackoverflow.com/comment/92029037
type: QuestionComment
has text: What line causes the problem? Is there a stack trace?
score: 1
comment on: http://stackoverflow.com/q/52544527
type: Comment

http://stackoverflow.com/q/52575529
type: AnsweredQuestion
score: 2
favorite count: 0
linked to: http://stackoverflow.com/q/5629023
type: Question
answer count: 2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/92086591
has answer: http://stackoverflow.com/a/52575648
has title: How to sort Dictionary Keys in Python
has answer: http://stackoverflow.com/a/52575617
has comment: http://stackoverflow.com/comment/92086785
accepted answer: http://stackoverflow.com/a/52575648
possible better answer: http://stackoverflow.com/a/52575617
upvote count: 4
has body: i have this code: myDict = {} myDict['Hello'] = 's' myDict['Hallo'] = 'a' myDict['Test'] = 'b' myDict['Buy'] = 'hoo' myDict['Hehe'] = 'kkk' print(list(myDict.keys())) and it return random, like : ['Hallo','Buy','Hehe','Test,'Hello'] what I want is : ['Hello','Hallo','Test','Buy','Hehe'] 'Hello' is first ,'Hallo' is second, 'Test' is Third, 'Buy' is Fourth, 'Hehe' is Fifth it's very important because i want to make csv file : with open('names.csv', 'w', newline='') as csvfile: fieldnames = list(myDict.keys()) writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ";") writer.writeheader() writer.writerow(myDict)

http://stackoverflow.com/q/52483191
tagged with: spline
accepted answer: http://stackoverflow.com/a/52489856
answer count: 2
downvote count: 0
has title: Use UnivariateSpline to fit data tightly
favorite count: 0
has body: I have a bunch of x, y points that represent a sigmoidal function: x=[ 1.00094909 1.08787635 1.17481363 1.2617564 1.34867881 1.43562284 1.52259341 1.609522 1.69631283 1.78276102 1.86426648 1.92896789 1.9464453 1.94941586 2.00062852 2.073691 2.14982808 2.22808316 2.30634034 2.38456905 2.46280126 2.54106611 2.6193345 2.69748825] y=[-0.10057627 -0.10172142 -0.10320428 -0.10378959 -0.10348456 -0.10312503 -0.10276956 -0.10170055 -0.09778279 -0.08608644 -0.05797392 0.00063599 0.08732999 0.16429878 0.2223306 0.25368884 0.26830932 0.27313931 0.27308756 0.27048902 0.26626313 0.26139534 0.25634544 0.2509893 ] I use scipy.interpolate.UnivariateSpline() to fit to some cubic spline as follows: from scipy.interpolate import UnivariateSpline s = UnivariateSpline(x, y, k=3, s=0) xfit = np.linspace(x.min(), x.max(), 200) plt.scatter(x,y) plt.plot(xfit, s(xfit)) plt.show() This is what I get: Since I specify s=0, the spline adheres completely to the data, but there are too many wiggles. Using a higher k value leads to even more wiggles. So my questions are -- How should I correctly use scipy.interpolate.UnivariateSpline() to fit my data? More precisely, how do I make the spline minimise its wiggling? Is this even the correct choice for this kind of a sigmoidal function? Should I be using something like scipy.optimize.curve_fit() with a trial tanh(x) function instead?
tagged with: curve-fitting
tagged with: python
has answer: http://stackoverflow.com/a/52484882
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52489856
upvote count: 3
has comment: http://stackoverflow.com/comment/91940131
has comment: http://stackoverflow.com/comment/91955605
possible better answer: http://stackoverflow.com/a/52484882
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/91993740

http://stackoverflow.com/q/52567926
score: 0
has body: I need render more than 100 cards with image in the template. But I noticed that each render of a photo requires a query to the database. I upload pictures in low quality and I do not need to resize them using a template tag. Is there a way to render an image without using template tags?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92072845
has comment: http://stackoverflow.com/comment/92073726
tagged with: django
tagged with: python
answer count: 0
has title: Wagtail CMS render image in template without templatetags
type: Question
tagged with: wagtail

http://stackoverflow.com/q/52578066
tagged with: python
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92093976
score: 0
tagged with: batch-file
answer count: 3
has answer: http://stackoverflow.com/a/52598494
upvote count: 1
has title: Make a batch file run a python code with arguments
has answer: http://stackoverflow.com/a/52578498
favorite count: 0
has answer: http://stackoverflow.com/a/52579397
type: UnansweredQuestion
has body: how do I make a python code that runs a .bat (batch) file, and the .bat file calls another python with arguments? I know that if you want to call a python file using .bat you need to write: C:\python27\python.exe D:\XXX\XXX\XXX\XXX.py %* what about arguments? I need this D:\XXX\XXX\XXX\XXX.py file to get args... Thanks!

http://stackoverflow.com/a/52480869
has comment: http://stackoverflow.com/comment/91903090
answers question: http://stackoverflow.com/q/52480773
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52480773
type: Answer
has body: It seems that you need to create a new System class containing all the elements. Than you can pass the parameters to the constructor of this class. This is a code example: class System(object): def __init__(self, parameters): self.element0 = Class0 (parameters[0]) self.element1 = Class1 (parameters[1]) self.element2 = Class2 (parameters[2]) def compute(): .... def save_result(): .... if __name__ == '__main__': parameters = ... mySystem = System(parameters) mySystem.compute() mySystem.save_result() Alternatively, you could have a general class with only the elements common to all the systems (similar to the one above), and then create new classes that inherit from the previous one and have specialized behavior: class SpecificSystem(System): def __init__(self, parameters): super().__init__(parameters) # Additional elements specific to this system self.element3 = Class3 (parameters[3]) def compute(): # Behavior specific to this system .... # Retain save_result() from superclass
upvote count: 1
has comment: http://stackoverflow.com/comment/91905176

http://stackoverflow.com/a/52573192
has body: First, the GUI must run in main thread, and must not blocked by a infinite loop. Use after instead. To communicate, use some appropriate object from threading, e.g. Event: import tkinter as tk import time import threading class MyClass(tk.Frame): def __init__(self, master, event): super().__init__(master) self.master = master self.event = event self.label = tk.Label(master, text='') self.label.pack() self.after(100, self.blink_check) def blink_check(self): self.label['text'] = self.event.is_set() self.after(100, self.blink_check) def blink(event): while True: event.set() time.sleep(2.5) event.clear() time.sleep(2.5) def main(): root = tk.Tk() root.title("My Blinker") event = threading.Event() t = threading.Thread(target=blink, args=(event,)) t.daemon = True t.start() frame = MyClass(root, event) root.mainloop() if __name__=="__main__": main()
has comment: http://stackoverflow.com/comment/92127804
type: Answer
answers question: http://stackoverflow.com/q/52572956
score: 0

http://stackoverflow.com/comment/92114648
has text: I am not sure if the large screen shots help. I think you should at least (also) include some of your code here.
type: QuestionComment
comment on: http://stackoverflow.com/q/52587973
score: 0
type: Comment

http://stackoverflow.com/q/52578456
answer count: 1
downvote count: 1
favorite count: 0
has body: I have made a multidimensional list called finalMaze of size (n x n). I’m not really understanding how file i/o works in python so couldn't really edit what I had managed to put together from the internet.. import csv def writeMaze(finalMaze, filename): with open(filename, "w") as f: writer = csv.writer(f, delimiter=',') writer.writerows(finalMaze) The output is something like... 1, 1, 1 2, 2, 2 3, 3, 3 All that I want is to get rid of that comma (,) between numbers. If anyone can explain how I can do it, I would very appreciate it!
tagged with: file-io
tagged with: python
accepted answer: http://stackoverflow.com/a/52578487
tagged with: python-3.x
tagged with: list
has answer: http://stackoverflow.com/a/52578487
type: AnsweredQuestion
has title: txt file output of multidimensional list without comma ( , )
type: Question
score: 0
upvote count: 1

http://stackoverflow.com/q/52507748
has comment: http://stackoverflow.com/comment/92068610
tagged with: affinity
type: Question
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/92077857
tagged with: parallel-processing
linked to: http://stackoverflow.com/q/41525409
upvote count: 3
tagged with: multithreading
linked to: http://stackoverflow.com/q/45985641
has comment: http://stackoverflow.com/comment/92076806
has title: Using multiple CPU cores in TensorFlow
answer count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52879340
has body: I have extensively studied other answers on TensorFlow and I just cannot seem to get it to use multiple cores on my CPU. According to htop, the following program only uses a single CPU core: import tensorflow as tf n_cpus = 20 sess = tf.Session(config=tf.ConfigProto( device_count={ "CPU": n_cpus }, inter_op_parallelism_threads=n_cpus, intra_op_parallelism_threads=1, )) size = 100000 A = tf.ones([size, size], name="A") B = tf.ones([size, size], name="B") C = tf.ones([size, size], name="C") with tf.device("/cpu:0"): x = tf.matmul(A, B) with tf.device("/cpu:1"): y = tf.matmul(A, C) sess.run([x, y]) # run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) # run_metadata = tf.RunMetadata() # sess.run([x, y], options=run_options, run_metadata=run_metadata) # for device in run_metadata.step_stats.dev_stats: # device_name = device.device # print(device.device) # for node in device.node_stats: # print(" ", node.node_name) However, when I uncomment the lines at the bottom, and change size so that the computation actually finishes in a reasonable amount of time, I see that TensorFlow seems to think it's using at least 2 CPU devices: /job:localhost/replica:0/task:0/device:CPU:0 _SOURCE MatMul _retval_MatMul_0_0 _retval_MatMul_1_0_1 /job:localhost/replica:0/task:0/device:CPU:1 _SOURCE MatMul_1 Fundamentally, what I want to do here is execute different ops on different cores in parallel. I don't want to split a single op over multiple cores, though I know that happens to work in this contrived example. Both device_count and inter_op_parallelism_threads sound like what I want, but neither seems to actually result in using multiple cores. I've tried all combinations I can think of, including setting one or the other to 1 in case they conflict with each other, and nothing seems to work. I can also confirm with taskset that I'm not doing anything strange with my CPU affinity: $ taskset -p $$ pid 21395's current affinity mask: ffffffffff What exactly do I have to do to this…
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52879340
favorite count: 0

http://stackoverflow.com/q/52578621
accepted answer: http://stackoverflow.com/a/52578943
upvote count: 2
has comment: http://stackoverflow.com/comment/92093826
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92092723
has comment: http://stackoverflow.com/comment/92101878
tagged with: python
tagged with: computer-vision
has title: Best OpenCV algorithm for detecting fast moving ball?
tagged with: opencv
type: AnsweredQuestion
score: 2
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/92092744
tagged with: image-processing
type: Question
has body: I am new to OpenCV. I am working on a project that involves tracking and detecting a spinning roulette ball. Here is the video I want to use: https://www.youtube.com/watch?v=IzZNaVQ3FnA&amp;list=LL_a67IPXKsmu48W4swCQpMQ&amp;index=7&amp;t=0s I want to get the ball time for 1 revolution. But the ball is quite fast and hard to detect. I am not sure how to overcome this. What would be the best algorithm for doing this?
has answer: http://stackoverflow.com/a/52578943

http://stackoverflow.com/comment/91845981
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52451243
has text: Is there an option to trim the index once done? Secondly, I think the bottleneck probably is the database itself because I have tried closing all the applications and just running the script and in Task Manager I see write speed of around 3-4 MB/s. But when I am just reading the text files it shows around 30-35 MB/s
score: 0

http://stackoverflow.com/q/52485021
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/49234416
has comment: http://stackoverflow.com/comment/91911531
has body: I want to know what is the problem when I try to make a request to this URL. Here is my code: import requests as rq from bs4 import BeautifulSoup def make_request(Url): result = rq.get(Url) soup = BeautifulSoup(result.content, "html.parser") events = soup.find_all("a") for i in events: print(i) make_request("https://web.archive.org/web/20180507100019/https://bravenewcoin.com/industry-resources/events-calendar/bitcoin-and-blockchain-events/") I think the problem is the URL, in that case what can I do to solve this and parse the content of that website ? Thanks a lot !
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/44415551
has comment: http://stackoverflow.com/comment/91912379
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91913449
linked to: http://stackoverflow.com/q/19342111
has comment: http://stackoverflow.com/comment/91911781
tagged with: python
has comment: http://stackoverflow.com/comment/91913371
has comment: http://stackoverflow.com/comment/91914038
tagged with: python-requests
has answer: http://stackoverflow.com/a/52494781
has answer: http://stackoverflow.com/a/52568875
type: Question
has title: Why am I getting this ERRNO 110 - python requests
has comment: http://stackoverflow.com/comment/91911502
has comment: http://stackoverflow.com/comment/91911891

http://stackoverflow.com/a/52489000
score: 1
upvote count: 1
has body: __unicode__ should be __str__ for Python 3, and that method should be declared on the Post class, not the Meta class.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52488885
has comment: http://stackoverflow.com/comment/91956380
type: Answer
answers question: http://stackoverflow.com/q/52488885

http://stackoverflow.com/q/52562544
has title: Create and sort a 2D list in Python
type: Question
has comment: http://stackoverflow.com/comment/92063784
has comment: http://stackoverflow.com/comment/92063591
has comment: http://stackoverflow.com/comment/92063622
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52562633
has answer: http://stackoverflow.com/a/52563164
linked to: http://stackoverflow.com/q/3121979
tagged with: python-3.x
type: UnansweredQuestion
has body: I am new to Python. I need to traverse the list of files in a directory, and have a 2D list of files (keys) with a value. Then I need to sort it based on their values, and delete the files with lower half of values. How can I do that? This is what I did so far. I can't figure it out how to create such 2D array. dir = "images" num_files=len(os.listdir(dir)) for file in os.listdir(dir): print(file) value = my_function(file) #this is wrong: _list[0][0].append(value) #and then sorting, and removing the files associated with lower half Basically, the 2D array should look like [[file1, 0.876], [file2, 0.5], [file3, 1.24]], which needed to be sorted out based on second indexes.
has comment: http://stackoverflow.com/comment/92063601
tagged with: python
has comment: http://stackoverflow.com/comment/92063604
has comment: http://stackoverflow.com/comment/92063625

http://stackoverflow.com/q/52436814
answer count: 1
tagged with: yagmail
has answer: http://stackoverflow.com/a/52436874
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52436874
has body: The below code snippet sends email with status. If I want to add another line break with text as Sent from Scheduler. What could be the possible way ? def send_email(status,message): date = str(datetime.now().date())[-5:].replace('-', '/') yag.send(to=TO_EMAIL,subject="{} Rebuild Code: {}".format(date, status),contents=message) logging.info("Mail Sent!") Thanks!
has title: Add custom text message after break line
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/52531412
type: Answer
has body: Another approach could be to use collections to create a list of the duplicates in your original list and then create a new list of tuples by checking which element is duplicate. Then you create a new list checking which element is either not duplicate or if it is which one is not unknown: import collections # Create a list of elements that are duplicate in the original list duplicates = [item for item, count in collections.Counter([x[1] for x in ap]).items() if count &gt; 1] new = [] for elem in ap: if elem[1] in duplicates: if elem[0] != 'unknown': # Copy the duplicate element only if it's not unknown new.append(elem) else: new.append(elem) print 'New list: ',new Output is: new list: [('unknown', (96, 1142, 225, 1013)), ('Jenny', (558, 1033, 825, 765)), ('Garry', (53, 282, 182, 153)), ('Sam', (477, 1233, 632, 1078)), ('Chen', (593, 283, 779, 97)), ('Steve', (741, 1199, 868, 1070)), ('Harry', (81, 717, 236, 562))]
score: 0
answers question: http://stackoverflow.com/q/52530777

http://stackoverflow.com/comment/91810965
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52433270
has text: any idea how can I keep the 'id' as a column? @RickyKim

http://stackoverflow.com/q/52456516
has comment: http://stackoverflow.com/comment/91855305
has answer: http://stackoverflow.com/a/52456629
accepted answer: http://stackoverflow.com/a/52456610
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91855350
has comment: http://stackoverflow.com/comment/91857156
has comment: http://stackoverflow.com/comment/91855881
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52456626
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52456626
upvote count: 1
has comment: http://stackoverflow.com/comment/91855416
tagged with: python
has title: Python 3 list comprehension optimization
has answer: http://stackoverflow.com/a/52456610
type: AnsweredQuestion
has body: I am doing a list comprehension in python 3 for list of list serially numbers according to given range. My code works fine with but problem is with big range it slows down and take a lot of time. I there any way to do it other way? I don't want to use numpy. global xy xy = 0 a = 3 def func(x): global xy xy += 1 return xy my_list = [[func(x) for x in range(a)] for x in range(a)] xy = 0 print(my_list)
has comment: http://stackoverflow.com/comment/91855347
has comment: http://stackoverflow.com/comment/91855574

http://stackoverflow.com/q/52496458
accepted answer: http://stackoverflow.com/a/52496500
has comment: http://stackoverflow.com/comment/91933304
has comment: http://stackoverflow.com/comment/91933544
downvote count: 1
tagged with: definition
type: Question
tagged with: function
score: -1
has body: can someone explain what's wrong with the below code? def factorial(num): if num == 0 or 1: return 1 else: result = num * factorial(num-1) return result #print(factorial(30)) #output: 1 &amp; on the contrary when the if statement is slightly modified as below. The code seems to do what its meant to do. I would appreciate if someone could comment on why the code below provides desired output while the code above doesn't def factorial(num): if num == 1 or 0: return 1 else: result = num * factorial(num-1) return result #print(factorial(30)) #265252859812191058636308480000000
has title: what is wrong with the if statement in the code below?
duplicate of: http://stackoverflow.com/q/20002503
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/20002503
has answer: http://stackoverflow.com/a/52496500

http://stackoverflow.com/comment/91951928
comment on: http://stackoverflow.com/q/52505602
has text: Why do you find the values printed strange? They match nicely with your input range of `lon = numpy.arange(-180,180,1)` and `lat = numpy.arange(-90,90,1)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91996833
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52528514
type: Comment
has text: Is there a way to do this without recursion?

http://stackoverflow.com/comment/91922923
type: Comment
has text: Need more information regarding your question, such as are you using the cpu or gpu version? what have you installed prior to this? did you follow any guides?
comment on: http://stackoverflow.com/q/52441790
score: 0
type: QuestionComment

http://stackoverflow.com/q/52588109
favorite count: 0
has body: config.ini request = {"order": {"order_id": {order_id},"customer_id":10001, "prd_price":50, "quantity":{quantity}, "total_price": {total_price}, "product_id":1, "last_name": "lavanya"}} data = {'quantity': '315', 'total_price': '50', 'order_id': '102'} myscript.py req = config[reflowStep]['request'] req = req.format(**data) Exception: Traceback (most recent call last): File "myscript.py", line 247, in reflow req = req.format(**data) KeyError: '"order"' Expected Output: req = { "order":{ "order_id":102, "customer_id":10001, "prd_price":50, "quantity":315, "total_price":50, "product_id":1, "last_name":"lavanya" } } If I pass as a string(without '{/}'), it's working. For eg: request = "order_id": {order_id},"customer_id":10001, "prd_price":50, "quantity":{quantity}, "total_price": {total_price}, "product_id":1, "last_name": "lavanya" But my requirement is I need to populate the values into the json at runtime. Anyone, Could help me? Could anyone suggest the best way for my requirement?
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.x
type: Question
has title: Interpolation substitution on JSON string Using Python
tagged with: http://stackoverflow.com/tag/json
upvote count: 3
has comment: http://stackoverflow.com/comment/92114115
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52588288
accepted answer: http://stackoverflow.com/a/52588288

http://stackoverflow.com/q/52543753
has comment: http://stackoverflow.com/comment/92032181
answer count: 0
score: 1
upvote count: 1
has title: How to parse image to vector by python?
type: Question
has comment: http://stackoverflow.com/comment/92027414
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I want to parse the upper part of this and similar pics to numbers array. Have python or some lib function for this? Or I should do it via numply?
tagged with: python

http://stackoverflow.com/a/57009721
has comment: http://stackoverflow.com/comment/111522665
score: 32
type: Answer
has comment: http://stackoverflow.com/comment/134945474
upvote count: 32
has body: You can do it simply by : Model.fc = nn.Sequential() or alternatively you can create Identity layer: class Identity(nn.Module): def __init__(self): super().__init__() def forward(self, x): return x and replace fc layer with it : Model.fc = Identity()
answers question: http://stackoverflow.com/q/52548174
has comment: http://stackoverflow.com/comment/127868006
downvote count: 0

http://stackoverflow.com/a/52436387
accepted answer of: http://stackoverflow.com/q/52435852
has body: This will help: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() url='' //of webpage driver.maximize_window() driver.get(url) listofelements=driver.find_elements(By.XPATH,'//*[@name="fromMonth"]/option') //to take all elements matching xpath for i in range(len(listofelements)): print(listofelements[i].text) //print all elements of list
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/52435852

http://stackoverflow.com/q/52520457
answer count: 5
tagged with: python
has title: Python, how to not require an additional space at the end of the list?
has answer: http://stackoverflow.com/a/52520767
has answer: http://stackoverflow.com/a/52520721
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52521102
upvote count: 1
type: Question
tagged with: list
tagged with: algorithm
has answer: http://stackoverflow.com/a/52520655
score: 1
has comment: http://stackoverflow.com/comment/91980949
has body: I've written a program which can compress a sequence of characters. def compress(string): output = "" counter = 1 firstLoop = True for element in range(0, len(string)): # if statement checking if current character was last character if string[element] == string[element - 1]: # if it was, then the character has been written more than one # time in a row, so increase counter counter = counter + 1 else: # when we detect a new character reset the counter # and also record the character and how many times it was repeated if not firstLoop: output = output + string[element - 1] + str(counter) counter = 1 firstLoop = False return output data = "aaaabbbchhtttttttf" print(data) compressedData = compress(data) print(compressedData) The program outputs: aaaabbbchhtttttttf a4b3c1h2t7 So, it finds that there's '4' entries of 'a' so it writes 'a4', then 'b3' for three entries of b. The issue is that it forgets about the 'f1' at the end of the string. I know this is because of the line: output = output + string[element - 1] + str(counter) Since string[element-1] refers to the position in the string before the current element, thus, it will never reach the final position which is where 'f' is. The program doesn't work without the '-1' since it doesn't write the correct letter. How can I get around this problem and make it able to include f? The correct output should be a4b3c1h2t7f1. Thanks :) Edit: I forgot to mention that the program works if I include an additional character after the 'f', such as just a blank space. But that's of course because the final character in my string is just a space rather than a letter.
downvote count: 0
has comment: http://stackoverflow.com/comment/91980705
favorite count: 0
has answer: http://stackoverflow.com/a/52520985

beautifulsoup
tags question: http://stackoverflow.com/q/52481206
tags question: http://stackoverflow.com/q/52536527
tags question: http://stackoverflow.com/q/52445195
tags question: http://stackoverflow.com/q/52581359
tags question: http://stackoverflow.com/q/52562772
tags question: http://stackoverflow.com/q/52559161
tags question: http://stackoverflow.com/q/52446737
tags question: http://stackoverflow.com/q/52445010
tags question: http://stackoverflow.com/q/52434972
tags question: http://stackoverflow.com/q/52582830
tags question: http://stackoverflow.com/q/52564227
tags question: http://stackoverflow.com/q/52571362
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/52448236
tags question: http://stackoverflow.com/q/52446837
tags question: http://stackoverflow.com/q/52580875
tags question: http://stackoverflow.com/q/52537294
tags question: http://stackoverflow.com/q/52526729
tags question: http://stackoverflow.com/q/52465355
tags question: http://stackoverflow.com/q/52582418
tags question: http://stackoverflow.com/q/52489188
tags question: http://stackoverflow.com/q/52576618
tags question: http://stackoverflow.com/q/52454289
tags question: http://stackoverflow.com/q/52458442
tags question: http://stackoverflow.com/q/52440927
tags question: http://stackoverflow.com/q/52515833
tags question: http://stackoverflow.com/q/52564784
tags question: http://stackoverflow.com/q/52436604
tags question: http://stackoverflow.com/q/52520638
tags question: http://stackoverflow.com/q/52451631
tags question: http://stackoverflow.com/q/52563884
tags question: http://stackoverflow.com/q/52545284
tags question: http://stackoverflow.com/q/52522884
tags question: http://stackoverflow.com/q/52486992
tags question: http://stackoverflow.com/q/52529065
tags question: http://stackoverflow.com/q/52553065
tags question: http://stackoverflow.com/q/52503895
tags question: http://stackoverflow.com/q/52437091
tags question: http://stackoverflow.com/q/52588660
tags question: http://stackoverflow.com/q/52530092
tags question: http://stackoverflow.com/q/52572392
tags question: http://stackoverflow.com/q/52452491
tags question: http://stackoverflow.com/q/52516934
type: Tag
tags question: http://stackoverflow.com/q/52533385
tags question: http://stackoverflow.com/q/52570800
tags question: http://stackoverflow.com/q/52485021
tags question: http://stackoverflow.com/q/52475646
tags question: http://stackoverflow.com/q/52524725
tags question: http://stackoverflow.com/q/52553666
tags question: http://stackoverflow.com/q/52585737
tags question: http://stackoverflow.com/q/52536842
tags question: http://stackoverflow.com/q/52460035
tags question: http://stackoverflow.com/q/52582671
tags question: http://stackoverflow.com/q/52485162
tags question: http://stackoverflow.com/q/52527912
tags question: http://stackoverflow.com/q/52465642
tags question: http://stackoverflow.com/q/52578946
tags question: http://stackoverflow.com/q/52584207
tags question: http://stackoverflow.com/q/52578565
tags question: http://stackoverflow.com/q/52470792
tags question: http://stackoverflow.com/q/52470022
tags question: http://stackoverflow.com/q/52458279
tags question: http://stackoverflow.com/q/52468995
tags question: http://stackoverflow.com/q/52533473
tags question: http://stackoverflow.com/q/52531426

http://stackoverflow.com/a/52561180
has comment: http://stackoverflow.com/comment/92064391
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52546154
upvote count: 2
has body: Start with basic algebraic analysis. I derived my own formula for the sums of various sizes. From the initial analysis, we get that for a board of size n x m, there are (n-k)*(m-k) squares of size k. Summing this for k in [0, min(m, n)] we have a simple calculation formula: sum(((n-k) * (m-k) for k in range(0, min(n, m)))) I expanded the product to nm - k(n+m) + k^2, re-derived the individual series sums, and made a non-iterative formula, assuming n &lt;= m: n * n * m - n * (n - 1) / 2 * (n + m) + ((n - 1) * n * (2 * n - 1))/6 This first link then spoiled my fun with an even shorter formula: t = m - n n * (n + 1) / 6 * (2 * n + 3 * t + 1) which follows from mine with a bit of nifty rearrangement of terms. Now to the point of this exercise: given a desired count of squares, Q, find all rectangle dimensions (n, m) that have exactly that many squares. Starting with the formula above: q = n * (n + 1) / 6 * (2 * n + 3 * t + 1) Since we're given Q, the desired value for q, we can iterate through all values of n, finding whether there is a positive, integral value for t that satisfies the formula. Start by solving this for t: t = (6/(n*(n+1)) * q - 2*n - 1) / 3 combining the denominators: t = (6*q) / (3*n*(n+1)) - (2*n + 1)/3 I'll use the first version. Since a solution of n x m implies a solution of m x n, we can limit our search to only those cases n &lt;= m. Also, since the numerator shrinks (negative n^3 term), we can limit the search for values of n that allow t &gt;= 1 -- in other words, have the combined numerator at least as large as the denominator: numer = 6 * num_sqrs - n * (n+1) * (2*n+1) denom = 3 * n * (n+1) Solving this: num_sqrs &gt; (n * (n+1) * (n+2)) / 3 Thus, the (cube root of n) / 3 is a convenient upper bound for our loop limits. This gives us a simple iteration loop in the code: def dims(num_sqrs): dim = [(1, num_sqrs)] limit = ceil((3*num_sqrs)**(1.0/3.0)) for n in range(2, limit): numer = 6 * num_sqrs - n * (n+1) * (2*n+1) denom = 3 * n * (n+1) if …
has comment: http://stackoverflow.com/comment/92062696
type: Answer

http://stackoverflow.com/comment/92004930
has text: Possible duplicate of [IndexError: list index out of range and python](https://stackoverflow.com/questions/1098643/indexerror-list-index-out-of-range-and-python)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52532618
type: QuestionComment

http://stackoverflow.com/q/52510620
type: Question
upvote count: 2
tagged with: python-venv
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/99933705
has comment: http://stackoverflow.com/comment/99933667
downvote count: 1
has comment: http://stackoverflow.com/comment/91964908
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91965143
answer count: 0
type: UnansweredQuestion
has body: I tried in User settings {"python.pythonPath": "/home/vagrant/venv/bin/python"} Operating environment PC: MacBookPro OS: High sierra VM: Virtual Box (vagrant) guest OS：ubuntu16.04 Python3: 3.6.4 When I select python interpreter, new one dosen't displayed.
tagged with: python
has comment: http://stackoverflow.com/comment/91992099
tagged with: vagrant
score: 1
has title: How can I add virtual Python interpreter to VS code?

http://stackoverflow.com/q/52585431
has title: How to check if the document is empty by pymongo?
has body: I tried to prevent pymongo.errors.InvalidOperation: No operations to execute after getting aggregate function's result. However, the way I used still shows pymongo.errors.InvalidOperation: No operations to execute for db.collection.insert(). I believe the result is not null at the beginning case. Here is my code: import sys from pymongo import MongoClient client = MongoClient() db = client['movies'] for i in range(1,db.movies.count() + 1): res = db.ratings.aggregate([ {"$match": {"movieID":str(i)}}, {"$group": {"_id": "$movieID", "avg": {"$avg":"$rating"}}} ]) if list(res) != None: db.question1.insert(res) So how to check the document is empty in MongoDB?
tagged with: pymongo
has answer: http://stackoverflow.com/a/52602085
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/92106579
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91918677
score: 0
type: Comment
type: QuestionComment
has text: @PaulRooney if you read the `total item cost` must be equal to or less than 6, simply filtering wont account for that, you need to have a combination of 5 that has a total less than or equal to `6`
comment on: http://stackoverflow.com/q/52488615

http://stackoverflow.com/q/52572134
tagged with: javascript
tagged with: flask
has body: I have flask reactjs setup project that I cloned it below URL and its working fine. https://github.com/tonmcg/flask-react-example Now I made some changes to the below file by adding a console statement - https://github.com/tonmcg/flask-react-example/blob/master/scripts/main.js var App = React.createClass({ mixins: [Catalyst.LinkedStateMixin], getInitialState: function(){ var domain = { 'Sepal Width': [1.0, 5.0], 'Sepal Length': [3.5, 8.5], 'Petal Width': [0.0, 3.5], 'Petal Length': [0.0, 7.5] } var dimensions= Object.keys(domain); var features = {}; for(var j=0; j &lt; dimensions.length; j++){ var key = dimensions[j]; features[key] = 0.5 * (domain[key][0] + domain[key][1]) ; } console.log('domain = ', domain) console.log('features = ', features) return { domain: domain, features: features } }, render: function(){ return ( &lt;div&gt; &lt;Header /&gt; &lt;div className='container'&gt; &lt;div className='row'&gt; &lt;Features domain={this.state.domain} features={this.state.features} linkState={this.linkState} /&gt; &lt;div className='col-md-10'&gt; &lt;BarChart features={this.state.features}/&gt; &lt;ScatterNav features={this.state.features} domain={this.state.domain}/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; )} }); Now, when I run 'gulp' to build all the tasks it runs the server and I'm able to view the console log statements. Im trying to understand the workflow, should I start my flask server to test the changes or should I run the gulp command. Generally(for normal CSS, HTML, Javascript project), I do a auto reload of the flask server and the code changes will be reflected? How can I set the flask project to autoload as well make the gulp run its changes.
tagged with: gulp
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92080993
score: 2
has title: flask reactjs gulp setup auto reload
answer count: 0
has comment: http://stackoverflow.com/comment/92080876
has comment: http://stackoverflow.com/comment/92081083
type: Question
tagged with: reactjs
downvote count: 0

python-asyncio
tags question: http://stackoverflow.com/q/52533243
tags question: http://stackoverflow.com/q/52567601
tags question: http://stackoverflow.com/q/52532411
tags question: http://stackoverflow.com/q/52484087
tags question: http://stackoverflow.com/q/52467049
tags question: http://stackoverflow.com/q/52526353
tags question: http://stackoverflow.com/q/52565108
tags question: http://stackoverflow.com/q/52506066
tags question: http://stackoverflow.com/q/52477906
tags question: http://stackoverflow.com/q/52564283
tags question: http://stackoverflow.com/q/52527539
tags question: http://stackoverflow.com/q/52570247
tags question: http://stackoverflow.com/q/52572196
tags question: http://stackoverflow.com/q/52519568
tags question: http://stackoverflow.com/q/52582685
tags question: http://stackoverflow.com/q/52474282
tags question: http://stackoverflow.com/q/52544117
tags question: http://stackoverflow.com/q/52477655
tags question: http://stackoverflow.com/q/52498042
tag name: python-asyncio
type: Tag

http://stackoverflow.com/q/52548963
linked to: http://stackoverflow.com/q/2699008
score: 0
has answer: http://stackoverflow.com/a/52549145
has title: Signup with new email address with Python
tagged with: python
tagged with: web-scraping
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52549145
has body: For my project, I need to generate and register a new email address with my Flask api. Basically, when the users signup, an email address has to be generated specifically for that user where users can forward his emails and our service will scrape those emails. This is something like what Trello does after creating a board it assigns an email address and when you forward a mail to that address it makes a card out of it. I am unable to find any resources to do this task. If anyone has any idea how to get this done (if possible not just email but also the tracking service). A note about tracking service I can easily make a tracker that would listen to gmail every 3-4seconds and scrape any new mails and this process will run as daemon. But the problem is this approach is not scalable since I cannot run a new daemon for every single user that registers on the platform. If there is more efficient way to do it, please let me know. But the first point remains that I need to generate email addresses and signup with them through Python.
type: Question
has comment: http://stackoverflow.com/comment/92045628
answer count: 1
has comment: http://stackoverflow.com/comment/92037104

http://stackoverflow.com/a/73820949
answers question: http://stackoverflow.com/q/52531943
score: 0
has body: tl;dr Starred expressions with a single asterisk * in class definitions get processed before the keyword arguments even if they appear after the keyword arguments. This leads to *(10,) being interpretated as base class and since 10 is not a valid base class the error message occurs. Explanation The first point is that the argument list of the __new__ method in the metaclass contains *args. To better understand what's going on, *args could be replaced with name, bases, namespace which are the arguments that are passed to a metaclass when it is referenced in a class definition. So replace class Meta(type): def __new__(meta, *args, **kwargs): return super().__new__(meta, *args) with class Meta(type): def __new__(self, name, bases, namespace, **kwargs): return super().__new__(self, name, bases, namespace) The second point is that the class definition contains a starred expression. class A(metaclass=Meta, sandwich='tasty', *(10,)): pass A class definition however is not a function definition. They may appear similar, but they follow different rules because they serve different purposes. A function definition allows arbitrary positional arguments, keyword arguments and starred expressions with single asterisk * (variable number of positional arguments) and double asterisk ** (variable number of keyword arguments). A class definition usually includes a list of all base classes. A special case here is being able to define a metaclass with a keyword argument metaclass=Meta and an arbitrary number of further keyword arguments without any special meaning. The starred expression with double asterisk ** (variable number of keyword arguments) is also supported. A class definition is an executable statement. The inheritance list usually gives a list of base classes (see Metaclasses for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. https://docs.python.org/3/reference/compound_stmts.html#class-definitions I did not find off…
type: Answer

http://stackoverflow.com/q/52510586
type: Question
has answer: http://stackoverflow.com/a/52510990
has title: How to filter a Generic ListView?
tagged with: django-models
has body: I am using a CBV ListView, The problem is, the view returns a list of ALL notes on the system. What I would really prefer is for the list to only return the 'notes' that are associated with a particular CandProfile (model) The notes model is : class CandidateNote(models.Model): candidate = models.ForeignKey(CandProfile, on_delete=models.CASCADE, related_name='candidatenotes_cand') note_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name='candidatenotes_user') job_note = models.TextField(max_length=3000) date_added = models.DateTimeField(auto_now_add=True) I am new to Django and querying, and don't really know how to approach this in a Class based view....my initial thoughts were : Maybe I should modify the get_queryset method. Any help will be greatly appreciated.
upvote count: 2
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/91961219
tagged with: django-templates
tagged with: django-views
downvote count: 0

http://stackoverflow.com/a/52474415
answers question: http://stackoverflow.com/q/52436416
type: Answer
has body: The build_exe option to include files is named include_files, not included_files. Try to replace the corresponding lines of your setup script by options={'build.exe': {'excludes': [excludes], "packages": ["pygame"], 'include_files': [includedfiles]}},
score: 0

http://stackoverflow.com/a/52525486
has body: I ended up doing something like this: for month in df.index.month.unique(): df_month_avg = df[df.index.month == month].mean(axis=0, numeric_only=True) For count, I just replaced mean() with count() This seems to work ... even though my goal was to use a resample approach ... but I could not find a resample grouping key to do this.
score: 0
answers question: http://stackoverflow.com/q/52523455
type: Answer

http://stackoverflow.com/q/52560055
has comment: http://stackoverflow.com/comment/92058867
has comment: http://stackoverflow.com/comment/92528808
downvote count: 1
possible better answer: http://stackoverflow.com/a/52560114
has comment: http://stackoverflow.com/comment/92058780
type: Question
tagged with: nested-loops
has comment: http://stackoverflow.com/comment/92058842
score: -1
has answer: http://stackoverflow.com/a/52563819
has answer: http://stackoverflow.com/a/52560279
upvote count: 0
has answer: http://stackoverflow.com/a/52560135
has title: Nested Loops Fibonacci Sequence
has comment: http://stackoverflow.com/comment/92058816
favorite count: 0
has body: I am trying to write a program which will ask the user to enter a number. I then need to validate it is in the fib sequence Code: # asking the user to input number number = int(input("Enter a number: ")) # creating empty list to be filled sequence = [0, 1] x = -2 y = -1 # append items to list for i in range(number): x+=2 y+=2 # this code will be executed 'length' times sequence.append(x+y) # This should be somewhere in the loop: if number in sequence: print("The number is in the Fibonacci sequence") else: print("The number is not in the Fibonacci sequence") Expected Output: Fibonacci Sequence = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …. Enter a number: 5 &gt;&gt;&gt; The number is in the Fibonacci sequence
has answer: http://stackoverflow.com/a/52560566
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/52560114
accepted answer: http://stackoverflow.com/a/52560279
type: AnsweredQuestion

http://stackoverflow.com/q/52467339
type: AnsweredQuestion
has title: How to get all related_name fields in django with serializers?
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52467463
accepted answer: http://stackoverflow.com/a/52467463
upvote count: 1
tagged with: django
answer count: 1
has body: here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE) def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name 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) company_name = models.ForeignKey(Company,on_delete=models.CASCADE) def __str__(self): return self.name here is my seralizers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Avg,Max,Min,Count,F,Q class CatalogSerializer(serializers.HyperlinkedModelSerializer): dynamic_data = serializers.SerializerMethodField() class Meta: model = Catalog fields = '__all__' def get_dynamic_data(self, obj): totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs')) totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price')) return totalprice,totalpieces class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name', 'phone_number', 'catalog','user') class UserSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() company_name = serializers.StringRelatedField() class Meta: model = User fields = '__all__' here is my view.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset =…

http://stackoverflow.com/a/52451243
has comment: http://stackoverflow.com/comment/91846003
has comment: http://stackoverflow.com/comment/91851567
has comment: http://stackoverflow.com/comment/91846655
has comment: http://stackoverflow.com/comment/91846393
score: 0
has comment: http://stackoverflow.com/comment/91851926
has comment: http://stackoverflow.com/comment/91853682
type: Answer
answers question: http://stackoverflow.com/q/52451119
has comment: http://stackoverflow.com/comment/91845981
has comment: http://stackoverflow.com/comment/91851582
has body: The UNIQUE constraint on column "url" is creating an implicit index on the URL. That would explain the size increase. I don't think you can populate the table and afterwards add the unique constraint. Your bottleneck is surely the CPU. Try the following: Install toolz: pip install toolz Use this method: from toolz import partition_all def add_blacklist_url(self, urls): # print('add_blacklist_url:: entries = {}'.format(len(urls))) start_time = datetime.now() for batch in partition_all(100000, urls): try: start_commit = datetime.now() self.cursor.executemany('''INSERT OR IGNORE INTO blacklist(url) VALUES(:url)''', batch) end_commit = datetime.now() - start_commit print('add_blacklist_url:: total time for INSERT OR IGNORE INTO blacklist {} entries = {}'.format(len(templist), end_commit)) except sqlite3.Error as e: print("add_blacklist_url:: Database error: %s" % e) except Exception as e: print("add_blacklist_url:: Exception in _query: %s" % e) self.db.commit() time_elapsed = datetime.now() - start_time print('add_blacklist_url:: total time for {} entries = {}'.format(records, time_elapsed)) The code was not tested.
has comment: http://stackoverflow.com/comment/91846175
has comment: http://stackoverflow.com/comment/91847345
has comment: http://stackoverflow.com/comment/91846018

http://stackoverflow.com/q/52538892
type: UnansweredQuestion
tagged with: pyinstaller
has body: I'm working on a school project where we needs to create an app. I used a lot of wav files and also some png and gif files. I used pyinstaller to compile everything into one exe file and it gets the job done. However, it seems like the resources mentioned aren't coming with it. So I did some research and I messed around with the spec file and in the datas field, I added: datas=[('*.wav','.'),('*.png','.'),('*.gif','.')], Then I compile it again. I wrote py -m PyInstaller py -m PyInstaller Main.py --icon=icon.ico --name "Main" --distpath "Final Program" --noconsole and when I open the file, it freezes. How do I fix this? If I don't do --onefile, it works fine. If I do py -m PyInstaller Main.py --icon=icon.ico --name "Main" --distpath "Final Program" --add-data "*.wav;." --add-data "*.png;." --add-data "*.gif;." --noconsole It also works fine but it creates a folder. Are there any ways to make it all into one executable file? I'm really new to pyinstaller as well as pyglet. Thanks.
tagged with: python
tagged with: exe
score: 2
upvote count: 2
type: Question
tagged with: pyglet
has title: How do I compile my pyglet app and all the resources into one exe file?
tagged with: compilation
has comment: http://stackoverflow.com/comment/92017311
has answer: http://stackoverflow.com/a/52957074
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92046243
comment on: http://stackoverflow.com/q/52553757
has text: Do you perhaps mean `if j>0`?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/92132474
comment on: http://stackoverflow.com/a/52564500
type: AnswerComment
has text: Thanks for the thorough response! I'll test out these changes when I get a chance and will mark this answer as accepted assuming it works.
score: 0
type: Comment

http://stackoverflow.com/comment/91955637
type: Comment
type: QuestionComment
has text: What is `pem_bytes_as_cert_file()`?
comment on: http://stackoverflow.com/q/52507544
score: 0

http://stackoverflow.com/q/52480347
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52480478
accepted answer: http://stackoverflow.com/a/52480389
has body: I have two dataframes df1 and df2 and I want to merge them. Dataframe df1 is as follows: IDs Value1 Value2 AB 1 3 AB 1 1 AB 2 4 BC 2 2 BC 5 0 BG 1 1 RF 2 2 and dataframe df2 is as follows: IDs Issue AB AA AB AAA AB BA BC CC BC CA BG A RF D and the desired output is df3: IDs Value1 Value2 Issue AB 1 3 AA AB 1 1 AAA AB 2 4 BA BC 2 2 CC BC 5 0 CA BG 1 1 A RF 2 2 D Currently, the following: df3 = pd.merge(df1,df2,left_on='IDs',right_on='IDs',how='inner') df3 = pd.merge(df1,df2,left_on='IDs',right_on='IDs',how='left') df3 = pd.merge(df1,df2,left_on='IDs',right_on='IDs',how='outer') do not work, since they produce a result similar to the following: IDs Value1 Value2 Issue AB 1 3 AA AB 1 1 AA AB 2 4 AA BC 2 2 CC BC 5 0 CC BG 1 1 A RF 2 2 D meaning that they duplicate the first value of the Issue field from df2.
has title: Merge dataframes Python without duplications
possible better answer: http://stackoverflow.com/a/52480478
answer count: 2
tagged with: python
tagged with: merge
score: 0
has answer: http://stackoverflow.com/a/52480389
linked to: http://stackoverflow.com/q/42947303
type: Question

http://stackoverflow.com/comment/91886288
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52467217
has text: @GordThompson: I tried exactly the same at the link, but it failed with the following error [pyodbc.Error: ('HY011', u'[HY011] [Microsoft][ODBC SQL Server Driver]Operation invalid at this time (0) (SQLSetConnectAttr)')]. It seems that the isolation level cannot be changed after the connection is open [pyodbc.connect()]. However, it seems that pyodbc does not allow me to create an pyodbc.Connection directly without a connection str specified.

http://stackoverflow.com/a/52523694
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52523652
answers question: http://stackoverflow.com/q/52523652
type: Answer
score: 6
downvote count: 0
has body: They behave differently because that's how the languages are implemented. With C, a &gt; b &gt; c is evaluated left to right. There is no concept of "operator chaining" (I'll get to this shortly), so the expression is evaluated as (a &gt; b) &gt; c which is 1 &gt; c which is false (in C, logical expressions either return 1 or 0). In python, OTOH, a &gt; b &gt; c evaluates to a &gt; b and b &gt; c (as specified in the documentation on comparisons), which turns out to be True in this case.
type: AcceptedAnswer

http://stackoverflow.com/q/52468601
has comment: http://stackoverflow.com/comment/91879113
has title: Single line Output for the Factorial of a given number in Python
score: 0
has answer: http://stackoverflow.com/a/53957447
has answer: http://stackoverflow.com/a/52468789
has body: n=int(input("Enter the Value for n:")) result=1 for i in range(n, 1, -1): result=result*i print("factorial of",n,"is",result) output comes like this: Enter the Value for n:4 factorial of 4 is 4 factorial of 4 is 12 factorial of 4 is 24 My ask is - how to get the output only in single line i.e. the last line?
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91879052
type: Question
has answer: http://stackoverflow.com/a/52469008
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52468728
has answer: http://stackoverflow.com/a/52469108
tagged with: python

http://stackoverflow.com/comment/91841336
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52449039
has text: What do you mean by `consecutively` in this case? At the moment, you would only get 8 unique combinations so if you wanted a length of 48 you'd have 6 repeats for each combination.

http://stackoverflow.com/comment/91865063
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52461025
has text: Use `re'(starts|ends) in (\d{2})h (\d{2})m (\d){2})s'`. As you need to capture the value, you need to repeat the capture group. Unless you perform another match after ensuring the line starts with `starts in` or `ends in`.
score: 0

http://stackoverflow.com/q/52477036
answer count: 1
score: 0
tagged with: time-complexity
has title: Space Complexity (Python)
has answer: http://stackoverflow.com/a/52477107
tagged with: python
tagged with: space-complexity
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91895363
type: Question
accepted answer: http://stackoverflow.com/a/52477107
has body: I have a question, supposedly gdc(i, n) time and space complexity is O(1), what is the space complexity for this function? Time Complexity is O(n) because of a for loop. How about Space Complexity? The answer is O(1) but I don't understand why... result in a for loop is taking n space so shouldn't it be O(n)? def gcd_fun(n): for i in range(1, n+1): result += gcd(i, n) return result﻿

http://stackoverflow.com/comment/91976914
type: Comment
comment on: http://stackoverflow.com/a/52518438
has text: @Jacco but then I'd start wondering why I didn't ever see the authors of the libraries in the same room at the same time.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91925465
score: 0
type: Comment
has text: Divakar. Yes this will not work if there are negatives numbers in `a` and if there is no match in `label`.
comment on: http://stackoverflow.com/a/52491496
type: AnswerComment

http://stackoverflow.com/q/52498776
has comment: http://stackoverflow.com/comment/91938242
tagged with: file
upvote count: 1
has comment: http://stackoverflow.com/comment/91938148
has body: My question is when I for loop a file and using the index find to get the column. e.g. file1 = open(students_file, 'r') for line in file1: line = line.split(",") stu_first = (line[1]) print(stu_first) Now, this prints the output here: 57 61 92 51 51 The spaces are the cells that are empty. So this column is index[1]. I want just print out 57. I would like to note, I am not using module csv for a good reason. Also, no modules are used other than the os module. The reason I want to do this is I want to get 57 and times it by another number in another CSV file (yes I have 2 files I'm working with). Any other suggestion would be great. Thanks. EDIT: Ok sorry for the misconceptions. I'm new to python and am trying to explain the best I can. So the output above is the scores of 8 students. The blank spaces are those that did not take the course. The definition I am trying to do is normalise these scores by the highest mark in that course. In another csv file the highest score in the course is 95. Therefore what I want to do is loop through all these outputs above and divide it by 95 to get the normalised score. For example (57/95 = 0.6, 0/95 = None) etc.. I hope this explains a bit more? If not let me know.
type: Question
has answer: http://stackoverflow.com/a/52499581
has comment: http://stackoverflow.com/comment/91938536
answer count: 2
has comment: http://stackoverflow.com/comment/91938170
has title: How to get a cell in a column with csv files
downvote count: 0
has comment: http://stackoverflow.com/comment/91938193
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52499612
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/92063013
score: 0
comment on: http://stackoverflow.com/a/52561666
type: Comment
has text: Your code might be helpful, but it would be nice if you explain your answer, how your code works and why it is useful.
type: AnswerComment

http://stackoverflow.com/q/52474439
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/120682979
answer count: 5
score: 6
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52474911
downvote count: 0
tagged with: pytorch
linked to: http://stackoverflow.com/q/56262712
has answer: http://stackoverflow.com/a/54426001
type: Question
has title: How can I specify the flatten layer input size after many conv layers in PyTorch?
accepted answer: http://stackoverflow.com/a/52484974
upvote count: 6
possible better answer: http://stackoverflow.com/a/62418471
has body: Here is my problem, I do a small test on CIFAR10 dataset, how can I specify the flatten layer input size in PyTorch? like the following, the input size is 16*5*5, however I don't know how to calculate this and I want to get the input size through some function.Can someone just write a simple function in this Net class and solve this? class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3,6,5) self.conv2 = nn.Conv2d(6,16,5) # HERE , the input size is 16*5*5, but I don't know how to get it. self.fc1 = nn.Linear(16*5*5, 120) self.fc2 = nn.Linear(120,84) self.fc3 = nn.Linear(84,10) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)),(2,2)) x = F.max_pool2d(F.relu(self.conv2(x)),2) x = x.view(x.size()[0],-1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
has answer: http://stackoverflow.com/a/59012728
has answer: http://stackoverflow.com/a/52484974
has answer: http://stackoverflow.com/a/62418471

http://stackoverflow.com/q/52544935
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/69841533
has answer: http://stackoverflow.com/a/52545091
accepted answer: http://stackoverflow.com/a/52545091
has answer: http://stackoverflow.com/a/66818656
has comment: http://stackoverflow.com/comment/92030051
tagged with: python
answer count: 4
score: 14
has comment: http://stackoverflow.com/comment/92029906
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/60649974
has comment: http://stackoverflow.com/comment/92031176
has title: Best way to revert to a random seed after temporarily fixing it?
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/66818656
has comment: http://stackoverflow.com/comment/92030017
has comment: http://stackoverflow.com/comment/92030030
has comment: http://stackoverflow.com/comment/92029942
linked to: http://stackoverflow.com/q/32172054
has comment: http://stackoverflow.com/comment/92029937
tagged with: seed
has comment: http://stackoverflow.com/comment/92030268
tagged with: random
has body: Is this the only way to 'unseed' the random number generator: np.random.seed(int(time.time())) If you have some code that you want to be repeatable (e.g. a test) in a loop with other code that you want to be random each loop, how do you 'reset' the seed to random number generator after setting it? The following code illustrates the issue: import numpy as np def test(): np.random.seed(2) print("Repeatable test:", [np.random.randint(10) for i in range(3)]) for i in range(4): print("Random number:", np.random.randint(10)) test() Random number: 8 Repeatable test: [8, 8, 6] Random number: 2 Repeatable test: [8, 8, 6] Random number: 2 Repeatable test: [8, 8, 6] Random number: 2 Repeatable test: [8, 8, 6] Desired result: I want random number to be random each loop. I am happy to import the time module if this is the only way to do it but I thought there might be a simpler, more robust way. (You can't get the current seed according to this post)

http://stackoverflow.com/q/52573985
has title: How many function calls when I use pandas DataFrame groupby and then apply user-defined function?
has answer: http://stackoverflow.com/a/52574169
type: Question
score: 0
tagged with: pandas
has body: I have a pandas DataFrame: df = pd.DataFrame({'A':['a', 'a', 'a', 'a', 'a'], 'B':[1, 2, 3, 4, 5]}) and a user-defined function: def f(df): return df.max() - df.min() When I run the following code: df.groupby('A').apply(f) How many times the function f will be called? I tested this code, and found f will be called 4 times, could anybody explain this?
answer count: 1
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/52539899
tagged with: multithreading
tagged with: wpf
score: 2
type: Question
tagged with: python.net
has body: I am wondering how to start a new AppDomain and run a WPF window in that AppDomain? My code is something like: import clr clr.AddReference(r"wpf\PresentationFramework") from System.Windows import Application, Window from System.Threading import Thread, ThreadStart, ApartmentState from System import AppDomain, AppDomainSetup, CrossAppDomainDelegate class MyWindow(Window): ... if __name__ == '__main__': def start_thread(): thread1 = Thread(ThreadStart(MyWindow)) print ("Thread 1 domain:",thread1.GetDomain().FriendlyName) thread1.SetApartmentState(ApartmentState.STA) thread1.Start() thread1.Join() ads = AppDomainSetup() ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory ads.ConfigurationFile = \ AppDomain.CurrentDomain.SetupInformation.ConfigurationFile ad2 = AppDomain.CreateDomain("ad2", None, ads) cadd = CrossAppDomainDelegate(start_thread) ad2.DoCallBack(cadd) As a result, I got an error: System.Runtime.Serialization.SerializationException: Type '__System_CrossAppDomainDelegateDispatcher' in assembly '__CodeGenerator_Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. I guess the challenge is to set the cadd object as serializable. But when I looked up for solutions, I did not find anything about how to do it in Python. I am quite new to this field, probably I am wrong in the very beginning. Thank you for your help in advance!
downvote count: 0
tagged with: .net
tagged with: python
favorite count: 0
has title: Python.Net: Load a second window in second appdomain using Python.Net
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/52431179
answer count: 0
type: UnansweredQuestion
tagged with: minimize
has comment: http://stackoverflow.com/comment/91806113
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/91832970
has body: I'm trying to create a tool for an equal risk contribution portfolio,essentially following this article (https://quantdare.com/risk-parity-in-python/) but it is failing at the last step (def risk_parity_weights) as the scipy optimizer isn't working. It keeps giving me the initial weights as the optimized weights, and I know they aren't the optimized weights because even Excel Solver has been able to optimize this. All the others functions have been checked and are correct. Not sure what I'm doing wrong - please help! #Calculate portfolio st.dev portfolio_stdev = np.sqrt(weights*covariances*weights.T)[0,0] #Calculate Marginal Risk Contribution of each asset MRC = covariances*weights.T/portfolio_stdev #Calculate Risk Contribution of each asset RC = np.multiply(MRC,weights.T) return RC def risk_budget_objective_error(weights,*args): #Covariance table occupies the first position in args variable covariances = args[0] #State risk budgets assets_risk_budget = args[1] #Convert weights array to numpy matrix weights = np.matrix(weights) #Calculate portfolio st_dev portfolio_stdev = calculate_portfolio_stdev(ca_begweights,ca_cov) #Calculate risk contributions assets_risk_contribution = calculate_risk_contribution(ca_begweights,ca_cov) #Calculate desired risk contribution of each asset assets_risk_target = np.asmatrix(np.multiply(portfolio_stdev,assets_risk_budget)) #Calculate error between desired contribution and calculated distribution of each asset error = sum(np.square(assets_risk_contribution - assets_risk_target.T))[0,0] return error def risk_parity_weights(covariances,assets_risk_budget, initial_weights): #Constraints to optimization #sum equals 100% cons = ({'type':'eq','fun':lambda x: np.sum(x) - 1.0}, {'type':'ineq','fun':lambda x: x}) #Optimization in scipy optimize_result = minimize(risk_budget_objective_error, x0 = initial_weights, args = (covariances, assets_risk_budget), method = 'SLSQP', constraints = cons, tol = Tolerance, options = {'disp':True}) #Get optimi…
tagged with: optimization
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91807147
has title: Equal Risk Contribution portfolio scipy optimization not working

http://stackoverflow.com/comment/91905536
type: QuestionComment
type: Comment
has text: Draw a vertical line just to the left of the subject's arm and take the strip of background to the left of that and make it wider. Do the same on the right side. At the top, draw a horizontal line just above subject's head and take the part above that and make it taller. Paste all the new wide, tall parts onto a new, empty black canvas to touch the left, right and top edge and at each location select the lightest pixel. Paste the original image in at the centre along the bottom edge.
score: 0
comment on: http://stackoverflow.com/q/52480804

http://stackoverflow.com/q/52522526
has answer: http://stackoverflow.com/a/52522665
type: Question
answer count: 2
upvote count: 0
has title: Reversing a string recursion error python
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has body: When I return the .join method to reverse the string I call the function itself to do so. How can still reverse this string without using Built-in python methods such as the reversed method. def reverse_string_3(string): length = len(string) spaces = [' '] words = [] index_tracker = 0 while index_tracker &lt; length: if string[index_tracker] not in spaces: beginning_of_word = index_tracker # we only want to increment when the index tracker is a letter and not spaces while index_tracker &lt; length and string[index_tracker] not in spaces: index_tracker += 1 words.append(string[beginning_of_word:index_tracker]) index_tracker += 1 return "".join(reverse_string_3(string))
has comment: http://stackoverflow.com/comment/91984611
has comment: http://stackoverflow.com/comment/91984601
has answer: http://stackoverflow.com/a/52522568
downvote count: 3

http://stackoverflow.com/comment/91854231
type: QuestionComment
has text: I suggest providing an [MCVE](https://stackoverflow.com/help/mcve)
type: Comment
comment on: http://stackoverflow.com/q/52455618
score: 0

http://stackoverflow.com/a/52523601
has body: you just add " return all_t " as last statement of your All_traffic function definition. It would work .
score: 0
answers question: http://stackoverflow.com/q/52522346
type: Answer

http://stackoverflow.com/q/52539808
has body: I can get multiple strings starting with $startMsg$ and ending with $endMsg$. So following are acceptable and unacceptable: $startMsg$abcd$endMsg$ : Allowed $startMsg$abcd$endMsg$aaa : Not allowed as there is aaa after $endMsg$ Expecting $startMsg$, but found only $endMsg$. $startMsg$abcd$endMsg$xyz$endMsg$ : Not allowed No matching $endMsg$ found. $startMsg$abcd$endMsg$xyz$startMsg$ : Not allowed $startMsg$abcd$endMsg$xyz$startMsg$dad$endMsg$ : Allowed $endMsg$ found before $startMsg$. $startMsg$abcd$endMsg$xyz$endMsg$dad$startMsg$ : Not allowed aaa$startMsg$abcd$endMsg$ : Not allowed, as there is aaa before $startMsg$ I tried something like this: ^((\$startMsg\$[^(\$startMsg\$&gt;&gt;)(\$endMsg\$)]*\$endMsg\$))*$ I can get multiple strings starting with $startMsg$ and ending with $endMsg$. So following are acceptable and unacceptable: $startMsg$abcd$endMsg$ : Allowed $startMsg$abcd$endMsg$aaa : Not allowed as there is aaa after $endMsg$ Expecting $startMsg$, but found only $endMsg$. $startMsg$abcd$endMsg$xyz$endMsg$ : Not allowed No matching $endMsg$ found. $startMsg$abcd$endMsg$xyz$startMsg$ : Not allowed $startMsg$abcd$endMsg$xyz$startMsg$dad$endMsg$ : Allowed $endMsg$ found before $startMsg$. $startMsg$abcd$endMsg$xyz$endMsg$dad$startMsg$ : Not allowed aaa$startMsg$abcd$endMsg$ : Not allowed, as there is aaa before $startMsg$ I tried something like this: ^((\$startMsg\$[^(\$startMsg\$&gt;&gt;)(\$endMsg\$)]*\$endMsg\$))*$ ^ at start: start of the string \$: escaping $ $ at end: end of the string But it seems gross incorrect. But it seems gross incorrect. How I do this in python? Is [^(\$startMsg\$&gt;&gt;)(\$endMsg\$)]* allowed to match any string not containing $startMsg$ and $endMsg$. Seems that, plain no? But then how I am supposed to do this without complecating regex? Or this is simply undoable with regex as its related to pushdown automata and hence absolutely undoable with finite automate / regex.
has comment: http://stackoverflow.com/comment/92019953
favorite count: 0
has answer: http://stackoverflow.com/a/52541328
has comment: http://stackoverflow.com/comment/92019836
has comment: http://stackoverflow.com/comment/92019532
tagged with: python
tagged with: regex
upvote count: 2
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/92040584
has title: How do I write regular expression for multiple occurrences of delimited strings
has answer: http://stackoverflow.com/a/52545566
has comment: http://stackoverflow.com/comment/92019618
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/91847218
type: Comment
has text: To get a new console, use the creation flag `CREATE_NEW_CONSOLE` or `CREATE_NO_WINDOW` (i.e. new console without a window). To skip attaching to any console, use `DETACHED_PROCESS`. To create a new group, use `CREATE_NEW_PROCESS_GROUP`. With the latter, by default Ctrl+C will be disabled in the child if attached to a console; it can be enabled manually via `SetConsoleCtrlHandler`.
score: 1
comment on: http://stackoverflow.com/a/52450172
type: AnswerComment

http://stackoverflow.com/comment/91844675
type: AnswerComment
comment on: http://stackoverflow.com/a/52449937
has text: thanks for helping me out. I have tried using `...master/master.tar.gz#...` before I gave it a try again, to no avail. I will add the `--verbose` from pip to the question.
score: 0
type: Comment

regex-lookarounds
tags question: http://stackoverflow.com/q/52455911
tags question: http://stackoverflow.com/q/52508402
tag name: regex-lookarounds
type: Tag

http://stackoverflow.com/comment/92070433
type: QuestionComment
comment on: http://stackoverflow.com/q/52566559
score: 0
has text: Not per se, since if there are other constraints, it can result in dependency resolution. But if there are no other constraints,t hen normally yes.
type: Comment

http://stackoverflow.com/q/52491817
favorite count: 0
possible better answer: http://stackoverflow.com/a/52491856
accepted answer: http://stackoverflow.com/a/52491873
has answer: http://stackoverflow.com/a/52491856
has title: get average in pandas Series object
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91924464
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91924188
has answer: http://stackoverflow.com/a/52491873
has body: I have a pandas series in the following format: 23-08-2018 06803fe4-a504-4520-8304-a76a3adcd488 0 23-08-2018 89efbfda-6edc-45a9-a0dd-e520fd8a3e2a 2839 23-08-2018 88f7ff3f-ede7-4dd0-bce9-0d25b598004d 2639 23-08-2018 10f049cb-c165-424a-b2db-99637cc2668c 0 23-08-2018 11a7ec38-a535-4f1c-acc4-c93471401dbd 0 23-08-2018 1292f360-41e5-463e-8547-002858ac0226 0 23-08-2018 145d17c0-9711-4445-8eed-7e7d35f0f896 0 23-08-2018 188d7578-8a3b-4fe5-807a-d098bce1d227 0 23-08-2018 89tfbfda-6edc-45a9-a0dd-e520fd8a3e2a 0 24-08-2018 000a7843-432f-4c67-9d7c-5d3e2ffac439 14000 24-08-2018 000cd8c7-94c7-4cb7-ad70-a60aec275f31 14655 24-08-2018 000dd787-ab81-40a7-a036-a05e4d11fea9 15655 24-08-2018 00115f12-4a50-4412-bc90-940a21a1af65 14655 24-08-2018 0012467d-53c1-4b5e-be8b-fc285d130968 17700 27-08-2018 1e806edd-1c96-4bdb-87b8-b01cb09cdb02 15 27-08-2018 d2c45e73-d5ca-4e28-ba54-4e24b4ee9be3 30 And I want a dataframe in the following structure: Date AverageInteractionTime 23-08-2018 608.67 // (0+2839+2639+0+0+0+0+0+0)/9 24-08-2018 15333 // (14000+14655+15655+14655+17700)/5 27-08-2018 22.5 // (15+30)/2 Basically, I want to groupby the series according to chatdate and get the average of the third column How can I do this?
answer count: 2
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/92089760
score: 1
comment on: http://stackoverflow.com/q/52577152
type: Comment
type: QuestionComment
has text: Your string comparison is maybe not what you want: You compare objects with the `is` operator and not the string contents. So instead of `urlrule['rule'] is not 'nan'` you would want `urlrule['rule'] != 'nan'`. See also https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce

http://stackoverflow.com/comment/91961555
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52490156
has text: I had no idea it was getting an exit code, but that makes sense. Thank you cortruu
score: 0

http://stackoverflow.com/q/52499239
has comment: http://stackoverflow.com/comment/91939075
tagged with: search
answer count: 1
downvote count: 0
favorite count: 0
tagged with: model
has title: Save search query result into a model with django
has comment: http://stackoverflow.com/comment/91944470
tagged with: python
has body: I have the following code in my view. I want to save the query result (if it's true) into another model. How to achieve this? def scan(request): print(request.session) if request.method == 'POST': srch = request.POST['srh'] if srch: match = ReportModel.objects.filter(Q(serialNumber__iexact=srch)) if match: return render(request, 'admin/scan.html', {'sr': match}) else: messages.error(request, 'No result yet for the requested device!') else: return redirect('/scan/') return render(request, 'admin/scan.html')
has answer: http://stackoverflow.com/a/52514405
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91944344
tagged with: django
tagged with: updatemodel
upvote count: 1
type: Question

http://stackoverflow.com/q/52547769
answer count: 1
downvote count: 0
has body: I have a list of audio data that I want to display in a Jupyter notebook using IPython.display.Audio such that these controls are flowing from left to right next to one another. I tried using ipywidgets.HBox but I get the an error since IPython.display.Audio is not an instance of a Widget. My list of of audio data looks like the following, where y is the audio data and sr is the sampling rate. data = [(y1, sr1), (y2, sr2), ..., (yN, srN)] What I tried to do is something like the following. audio_widgets = [display.Audio(audio[0], sr=audio[1]) for audio in data] audio_hbox = widgets.HBox(audio_widgets) # TraitError happens here I get the following error. TraitError: Element of the 'children' trait of a HBox instance must be a Widget, but a value of &lt;IPython.lib.display.Audio object&gt; &lt;class 'IPython.lib.display.Audio'&gt; was specified. One way to get the audio displays to show is to simply show them one above the other (which takes up a lot of vertical space when there are a lot of audio data). for audio in data: audio_widget = display.Audio(audio[0], sr=audio[1]) display(audio_widget) Any ideas on how I can control the layout display of audio controls?
favorite count: 0
has title: How can I layout a list of IPython.display.Audio objects in a Jupyter notebook?
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
type: Question
score: 5
upvote count: 5
tagged with: ipython
has answer: http://stackoverflow.com/a/57825569

http://stackoverflow.com/q/52553597
has comment: http://stackoverflow.com/comment/92045917
has answer: http://stackoverflow.com/a/52553784
tagged with: python
has comment: http://stackoverflow.com/comment/92045908
upvote count: 2
downvote count: 1
has title: How to remove a string from a list with a common part
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52553784
score: 1
has body: I need to remove duplicate from a list with a common parts in python. My list is something like this: - Addition domainname1.com 80.80.80.80 + Addition domainname1.com 80.80.80.81 - Bitsquatting domainname2.com 104.160.171.87 + Bitsquatting domainname2.com 104.160.172.85 - Homoglyph domainname3.com 206.188.193.4 - Insertion domainname4.com 206.188.200.6 - Insertion domainname5.com 206.188.200.7 + Insertion domainname5.com 206.188.200.8 From this list I want to keep only the strings with unique domain name (and not string with common domain name and different IP) : - Homoglyph domainname3.com 206.188.193.4 - Insertion domainname4.com 206.188.200.6 I tried to use split() to get a list of the domain name: domainname1.com domainname1.com domainname2.com domainname2.com domainname3.com domainname4.com domainname5.com domainname5.com and remove the common domain name but I'm stuck to remove the corresponding string from the previous list. for line in change: name = line.split() domain_name = name[2] My way to get the domain name list (change is my initial list). Thanks
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/92046093
favorite count: 0

http://stackoverflow.com/comment/135847470
score: 0
type: AnswerComment
has text: The pythonpedia link (which was just the content scraped from another SO questions) is dead. The proper link is here: https://stackoverflow.com/questions/44863375/how-to-change-spacing-between-ticks
comment on: http://stackoverflow.com/a/65602635
type: Comment

http://stackoverflow.com/comment/91809933
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52432603
has text: I'll probably accept yours since Swift concedes 'elegance' :) but I don't want to make any enemies. I appreciate all of your help.

http://stackoverflow.com/a/52589220
downvote count: 0
score: 4
type: AcceptedAnswer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52587574
has comment: http://stackoverflow.com/comment/92114643
answers question: http://stackoverflow.com/q/52587574
type: Answer
has comment: http://stackoverflow.com/comment/92114521
has body: Do I need to Standardize the data using StandardScalar Generally speaking, this is called Features Scaling, and there are more than one Scaler for that purpose, in a nutshell: StandardScaler: usually your first option, it's very commonly used. It works via standardizing the data (i.e. centering them), that's to bring them to a STD=1 and Mean=0. It gets affected by outliers, and should only be used if your data have Gaussian-Like Distribution. MinMaxScaler: usually used when you want to bring all your data point into a specific range (e.g. [0-1]). It heavily gets affected by outliers simply because it uses the Range. RobustScaler: It's "robust" against outliers because it scales the data according to the quantile range. However, you should know that outliers will still exist in the scaled data. MaxAbsScaler: mainly used for sparse data. Unit Normalization: basically it scales the vector for each sample to have unit norm, independently of the distribution of the samples. Now as a rule of thumb, we usually scale features because of one (or more) of the following reasons: Some algorithms require features to be scaled, e.g. Neural Network. (to avoid for e.g. Vanishing Gradient Descent), another example is when we use RBF Kernel in SVM...etc. Feature Scaling improve/speed up convergence. When features highly vary in magnitudes, units and range (e.g. 5kg and 5000gms), because we don't want the algorithm to falsely think that one feature is more important (i.e. has higher impact on the model) than the other. As you can see, features scaling has nothing to do with the number of classes you have in Y. ..but for this iris dataset will need to classifiy 0 or 1 or 2 based on specified...How this works? I know LR works by prediction YES OR NO but here(iris) we have to predict 0 or 1 or 2 Well, in contrast to Binary Classification, this is called Multiclass Classification. The basic idea here is Scikit LogisticRegresser uses One-vs-Rest (OvR) scheme -by default- to solve it (a.k.a…

http://stackoverflow.com/q/52536055
type: AnsweredQuestion
upvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/92011800
downvote count: 2
tagged with: python
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/52536809
tagged with: linear-regression
has body: I have a regression coefficients matrix. The independent variables are x, x^2, x^3, till x^N where N is a parameter of my choice. I would like to print a line saying the following. "The regression model is: y= a1 x+ a2 x^2+ a3 x^3 + ... + x^N" The numbers from the coefficients matrix must be printed in place of a1, a2, etc. The code should work for different N equally well.
has title: How to print regression equation from coefficients matrix?
accepted answer: http://stackoverflow.com/a/52536809

http://stackoverflow.com/q/52484638
has comment: http://stackoverflow.com/comment/91910968
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52484684
has comment: http://stackoverflow.com/comment/91910810
tagged with: python
has title: Passing a Python argument to a module
type: AnsweredQuestion
score: 3
upvote count: 3
possible better answer: http://stackoverflow.com/a/52484692
accepted answer: http://stackoverflow.com/a/52484684
has answer: http://stackoverflow.com/a/52484692
type: Question
answer count: 2
downvote count: 0
has body: Simple NOOB question, but after an hour of searching I still can't find it. In Python 3.6 I've got a working module nhcparams with a dictionary, FOO. The following code is tested and works: import nhcparams def get_max_price(): my_price = nhcparams.FOO['Price'] I'd like to change it to: import nhcparams def get_max_price(ARG): my_price = nhcparams.ARG['Price'] get_max_price(FOO) That doesn't work, which I am hoping is just a syntax problem on my end. Any help getting me past my idiocy would be appreciated :)

http://stackoverflow.com/q/52588167
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1933451
downvote count: 2
upvote count: 1
tagged with: pastebin
type: Question
linked to: http://stackoverflow.com/q/27273987
has answer: http://stackoverflow.com/a/68162012
score: -1
has title: How to load a python script from a raw link (such as Pastebin)?
has body: I have a python script from a Pastebin link such as https://pastebin.com/raw/hz8p3B5Y: import requests requests.get('https://api.telegram.org/******/sendMessage?chat_id=******&amp;text=***** # Send notification to my Telegram I want to run a local python script that could load the raw Pastebin and execute it.
answer count: 2
has comment: http://stackoverflow.com/comment/92111308
favorite count: 0
has answer: http://stackoverflow.com/a/52588246
linked to: http://stackoverflow.com/q/701802
tagged with: python
tagged with: python-3.x

pyqt4
tags question: http://stackoverflow.com/q/52552680
tags question: http://stackoverflow.com/q/52527995
type: Tag
tags question: http://stackoverflow.com/q/52584644
tags question: http://stackoverflow.com/q/52486823
tags question: http://stackoverflow.com/q/52493439
tags question: http://stackoverflow.com/q/52585297
tags question: http://stackoverflow.com/q/52550903
tag name: pyqt4

http://stackoverflow.com/comment/91898544
type: QuestionComment
comment on: http://stackoverflow.com/q/52478005
has text: I did explain what I want to do in the question. I cannot post the entire code here, wouldn't make sense and no one would be able to run it anyway.
score: 0
type: Comment

http://stackoverflow.com/q/52431255
has body: I know this is a recurrent question, but I can't find a useful answer. In Python, for running a shell command one can use this. If I do the same inside Jupyter I got no output. How can I see the results of executing the command? Doing print subprocess.call(["ping", "-c 2", "www.cyberciti.biz"]) returns zero.
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91806500
tagged with: python
tagged with: shell
has answer: http://stackoverflow.com/a/52437922
type: UnansweredQuestion
type: Question
has title: Execute shell command and use it's output in Jupyter

http://stackoverflow.com/q/52522681
score: 2
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91985003
tagged with: http
has answer: http://stackoverflow.com/a/59863596
type: Question
tagged with: api
tagged with: rancher
downvote count: 0
has body: I'm able to create a rancher project via the rancher API using python, but can quite figure out how to do so to add users/members...?
has title: How do yo add members/users to Rancher Project via POST request using python?
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52466674
upvote count: 3
type: AcceptedAnswer
has body: I think because of the lvalue vs rvalue rule, since the rvalue is evaluated first, it is not possible to automatically infer the length like what you ask for. One way would be if you write a custom wrapper over numpy arrays and override __setitem__ correctly. But that's too much trouble than a convenience to me.
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52466624
answers question: http://stackoverflow.com/q/52466624

http://stackoverflow.com/a/79125006
score: 2
answers question: http://stackoverflow.com/q/52459123
downvote count: 0
upvote count: 2
has body: In arcade 2.6.17 (current stable version, and since arcade 2.4), this can be managed directly by arcade. In the window initializer, the parameter center_window is available (and defaults to False). So the OP code can be changed into: class MyGame(arcade.Window): def __init__(self, width, height): super().__init__(width, height, "Pong!", center_window=True) arcade.set_background_color(arcade.color.BLACK)
type: Answer

http://stackoverflow.com/comment/92038782
score: 0
comment on: http://stackoverflow.com/a/52487156
has text: Please consider marking this problem resolved by checking the checkmark to the left of the question. Thanks!
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91847940
comment on: http://stackoverflow.com/a/52452108
score: 0
type: Comment
has text: use string ie `""` . It will be easy to extract info using try/except
type: AnswerComment

http://stackoverflow.com/comment/91913205
comment on: http://stackoverflow.com/q/52484629
has text: It looks like a weird list of tuple, ex : [(2016-01-31 00:00:00,y),(2016-06-31 00:00:00,y),(2017-01-31 00:00:00,y),...etc...].
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52464543
has comment: http://stackoverflow.com/comment/91873469
has answer: http://stackoverflow.com/a/52786660
has body: I'm very new to Machine Learning! My problem concern a model created with LighGBM. I'm not the creator of this model, so I want to see the tree that this model generates. The model is in the format .joblib, and I want to know as much information as possible of it. On the LighGBMclassifier Documentation i don't find anything that can solve my problem. Thanks to the code below, I only know the number of classes. model = joblib.load("*.joblib.dat") model.classes_ Output: array([0, 1]) I want to know the number of rows, the rules and if it's possible, even the plot of the tree. Thank you all!
type: Question
has title: How to plot the tree of a Light GBM .joblib model?
tagged with: scikit-learn
score: 0
has comment: http://stackoverflow.com/comment/91906971
tagged with: lightgbm
has comment: http://stackoverflow.com/comment/91891645
answer count: 1
tagged with: joblib
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/a/52513510
has comment: http://stackoverflow.com/comment/91966745
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Use data['GDP'] = data['GDP'].str.replace(",", ".").astype(float) You are getting the error because of comma. Replacing it with dot should fix your issue. Demo: import pandas as pd df = pd.DataFrame({'GDP': ["1,21", "2.2", "3,4", "5,66", "77,09"]}) print df['GDP'].str.replace(",", ".").astype(float) Output: 0 1.21 1 2.20 2 3.40 3 5.66 4 77.09 Name: GDP, dtype: float64
accepted answer of: http://stackoverflow.com/q/52513472
upvote count: 1
answers question: http://stackoverflow.com/q/52513472
score: 1

http://stackoverflow.com/a/52526325
has body: Your project is most likely pointing to the wrong interpreter. E.G. Using a virtual environment when you want to use a global one. You must point PyCharm to the correct interpreter that you want to use. "File/Settings(Preferences On Mac)/Project: ... /Project Interpreter" takes you to the settings associated with the interpreters. This window shows all of the modules within the interpreter. From here you can click the settings wheel in the top right and configure your interpreters. (add virtual environments and what not) or you can select an existing interpreter from the drop down to use with your project.
type: Answer
answers question: http://stackoverflow.com/q/52526167
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/52533188
tagged with: lstm
has title: Number of indices mismatch, using Keras LSTM
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52533729
score: 0
has answer: http://stackoverflow.com/a/52534463
has body: I am trying to build a text classifier using LSTM: model = Sequential() model.add(Embedding(vocabulary_dim, 150, input_length=max_length)) model.add(LSTM(150, return_sequences=False)) model.add(Dense(1, activation='softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=5, batch_size=128) Where the parameter vocabulary_dim is calculated by: temp_list = [element for element in sentence_pad] vocabulary_dim = len(np.unique(temp_list)) When I run model.fit(...) I get this error: InvalidArgumentError: indices[3,0] = 25501 is not in [0, 19355) [[Node: embedding_2/Gather = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_2/embeddings/read, _arg_embedding_2_input_0_2)]] Caused by op 'embedding_2/Gather', defined at: File "C:\Users\Simone\Anaconda3\envs\keras\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\Simone\Anaconda3\envs\keras\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\__main__.py", line 3, in &lt;module&gt; app.launch_new_instance() File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance app.start() File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\ipykernel\kernelapp.py", line 474, in start ioloop.IOLoop.instance().start() File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start super(ZMQIOLoop, self).start() File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\ioloop.py", line 887, in start handler_func(fd_obj, events) File "C:\Users\Simone\Anaconda3\envs\keras\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper return fn(*args, **kwargs) File "C:\Users\Simone\Anaconda3\envs\keras\lib\…
type: UnansweredQuestion
tagged with: keras

http://stackoverflow.com/q/52443858
tagged with: regex
has title: Remove duplicate words in a string using regex
has answer: http://stackoverflow.com/a/52443969
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/52444003
has body: I'm working on my regex skills and i find one of my strings having duplicate words at the starting. I would like to remove the duplicate and just have one word of it - server_server_dev1_check_1233.zzz server_server_qa1_run_1233.xyz server_server_dev2_1233.qqa server_dev1_1233.zzz data_data_dev9_check_660.log I used the below regex but i get both server_server in my output, ((.*?))_(?!\D) How can i have my output just to one server_ if there are two or more and if its only one server_, then take as is? The output doesn't have to contain the digits and also the part after . i.e. .zzz, .xyz etc Expected output - server_dev1_check server_qa1_run server_dev2 server_dev1 data_dev9_check
type: Question
score: 3
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52444003
favorite count: 0
possible better answer: http://stackoverflow.com/a/52443969
tagged with: python

http://stackoverflow.com/q/52573615
type: Question
has body: Suppose I have a list of names names = ['Alex','Brad', 'Camilla'] If I had a numpy array like norder = array([0, 1, 2, 1, 0, 1, 0, 2, 1, 1]) Then I could use norder to access names by doing names[norder] &gt;&gt;&gt; array(['Alex', 'Brad', 'Camilla', 'Brad', 'Alex', 'Brad', 'Alex', 'Camilla', 'Brad', 'Brad'], dtype='&lt;U7') How do I go in the reverse? Given order= array(['Alex', 'Brad', 'Camilla', 'Brad', 'Alex', 'Brad', 'Alex', 'Camilla', 'Brad', 'Brad'], dtype='&lt;U7') and names, how do I return something that looks like norder?
tagged with: python
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52573645
has comment: http://stackoverflow.com/comment/92174784
accepted answer: http://stackoverflow.com/a/52573645
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/92083428
score: 1
has comment: http://stackoverflow.com/comment/92098011
favorite count: 0
has title: Getting index for numpy array

http://stackoverflow.com/q/52546783
score: 1
has title: Python inception of generators
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52547028
tagged with: generator
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52546799
has body: I'm trying to make a general way to generate all the combinations of multiple ranges or lists, for example, [range(0, 2), range(2, 5), range(4, 6), range(2, 3)], which should return a 2x3x2x1 = 12 element list. [[0, 2, 4, 2], [0, 2, 5, 2], [0, 3, 4, 2], [0, 3, 5, 2], [0, 4, 4, 2], [0, 4, 5, 2], [1, 2, 4, 2], [1, 2, 5, 2], [1, 3, 4, 2], [1, 3, 5, 2], [1, 4, 4, 2], [1, 4, 5, 2]] So far, everything is fine here. When I hardcode it, by doing x = [ ( [a,b] for a in rgs[0] for b in rgs[1] ) ] x.append( ( a + [b] for a in x[-1] for b in rgs[2]) ) x.append( ( a + [b] for a in x[-1] for b in rgs[3]) ) I get the good result. However, when I attempt to generalize it, by doing x = [ ( [a,b] for a in rgs[0] for b in rgs[1] ) ] for i in range(1,len(rgs)-1): x.append( ( a + [b] for a in x[-1] for b in rgs[i+1]) ) I obtain a 6-element list: [[0, 2, 2, 2], [0, 3, 2, 2], [0, 4, 2, 2], [1, 2, 2, 2], [1, 3, 2, 2], [1, 4, 2, 2]] Also, what I notice is that all the ranges generated after the first two use the range in rgs[-1] instead of the correct ones. I struggle to understand why this happens, as I beleive that those two code example are identical, except the latter is the more general form for arbitrary large number of ranges.
possible better answer: http://stackoverflow.com/a/52546799
has answer: http://stackoverflow.com/a/52547028
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91833667
type: Comment
has text: Please also do not post terminal/code output in images. Please see here for why: https://unix.meta.stackexchange.com/q/4086/40481
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52433517

http://stackoverflow.com/q/52499243
tagged with: mypy
has body: First I made a silly little class # cheese_helpers.py class Cheese: pass Then this happened # weird.py import lxml from typing import cast, List import cheese_helpers o: List[Any] = [] reveal_type(o) # builtins.List[Any] as expected y = cast(List[cheese_helpers.Cheese], o) reveal_type(y) # builtins.List[cheese_helpers.Cheese], as expected # so far so good. And then: z = cast(List[lxml.html.HtmlElement], o) reveal_type(z) # builtins.List[Any] ??????????????? That last line should be List[lxml.html.HtmlElement] if you ask me. Cheese isn't annotated either and that works just fine. I'm sure that to make the last line work I need to get/make some lxml annotations. But it seems very strange to me that my cast is being completely ignored. I cast to the Cheese class and it works. I cast to the HtmlElement class and it doesn't. My question is why?
has comment: http://stackoverflow.com/comment/91962309
upvote count: 3
has answer: http://stackoverflow.com/a/52505039
accepted answer: http://stackoverflow.com/a/52505039
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
has title: why does mypy `cast` only work some of the time?
type: Question

http://stackoverflow.com/q/52551511
score: 3
upvote count: 3
has title: GridSearch implementation for Keras Regression
type: Question
tagged with: grid-search
tagged with: keras
has answer: http://stackoverflow.com/a/55515649
answer count: 1
downvote count: 0
has body: Trying to understand and implement GridSearch method for the Keras Regression. Here is my simple producible regression application. import pandas as pd import numpy as np import sklearn from sklearn.model_selection import train_test_split from sklearn import metrics from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.callbacks import EarlyStopping from keras.callbacks import ModelCheckpoint df = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/concrete/slump/slump_test.data") df.drop(['No','FLOW(cm)','Compressive Strength (28-day)(Mpa)'],1,inplace=True) # Convert a Pandas dataframe to the x,y inputs that TensorFlow needs def to_xy(df, target): result = [] for x in df.columns: if x != target: result.append(x) # find out the type of the target column. Is it really this hard? :( target_type = df[target].dtypes target_type = target_type[0] if hasattr(target_type, '__iter__') else target_type # Encode to int for classification, float otherwise. TensorFlow likes 32 bits. if target_type in (np.int64, np.int32): # Classification dummies = pd.get_dummies(df[target]) return df.as_matrix(result).astype(np.float32), dummies.as_matrix().astype(np.float32) else: # Regression return df.as_matrix(result).astype(np.float32), df.as_matrix([target]).astype(np.float32) x,y = to_xy(df,'SLUMP(cm)') x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.25, random_state=42) #Create Model model = Sequential() model.add(Dense(128, input_dim=x.shape[1], activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') monitor = EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=5, mode='auto') checkpointer = ModelCheckpoint(filepath="best_weights.hdf5",save_best_only=True) # save best model model.fit(x_train,y_train,callbacks=[monitor,checkpointer],verbose=0,epochs=1000) #model.fit(x_train,y_train,validation_data=(x_test,y_test),cal…
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91934477
has text: Could you please provide the C code that might cause the problem? I think it will help a lot more than the dll itself
comment on: http://stackoverflow.com/q/52497031
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52484504
upvote count: 1
has title: Are Python's output streams thread-safe?
downvote count: 1
has comment: http://stackoverflow.com/comment/91910575
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91910637
has body: I'm using Dispy/pycos to run multiple jobs across a multitude of machines. The results of computations come back to the main script, which writes them out into a set of files -- from different threads. Do I need to explicitly synchronize output operations in my code -- to prevent lines output by different threads from garbling each other -- or is this already taken care of for me by Python? So far I have seen no such garbling, but, maybe, it was just luck?..
tagged with: python
favorite count: 0
tagged with: dispy
tagged with: python-3.x
type: Question
score: 0

http://stackoverflow.com/comment/91859321
type: QuestionComment
has text: which version of matplotlib are you using?
type: Comment
comment on: http://stackoverflow.com/q/52458461
score: 0

http://stackoverflow.com/comment/91951236
score: 0
type: AnswerComment
has text: I disagree with both of you @WillemVanOnsem and @SpencerWieczorek. The int cast is absolutely in the right place, and I just tested with `13(a)12(b)` and it works fine. It was also never stated in the OP that they were looking for a recursive solution. Not sure why you're throwing downvotes around w/o testing...
comment on: http://stackoverflow.com/a/52504369
type: Comment

http://stackoverflow.com/comment/91877403
score: 0
type: QuestionComment
has text: I would just like to add two things: the code that actually is clicking your button in your code is shown in the stack-trace and it doesn't seem to correspond with the code you posted on top. The line 41 in your code seems to be the problem and my guess is that 'nameField.click()' defaults to locating by X path which is then causing your 'NoSuchElement' Exception because x path is an unreliable locator that changes often. Another thing I notice is that your button seems to be 'unselectable' in your inspect element window. That might be causing the exception as well.
type: Comment
comment on: http://stackoverflow.com/q/52466353

http://stackoverflow.com/comment/92025034
comment on: http://stackoverflow.com/q/52542559
has text: You should use `json.dumps` and `json.loads` instead.
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/q/52540143
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92052055
has comment: http://stackoverflow.com/comment/92041582
tagged with: matplotlib
tagged with: loops
has comment: http://stackoverflow.com/comment/92020443
type: Question
has body: I looked at this solution: Multiple `subplot2grid` in a for loop , but it was unfortunately not working for me! So I am using the following code in order to produce plots: stations = ["A", "B", "C"] variables = ["d", "e", "f"] for i, variable in enumerate(variables): fig = plt.figure(0) ax = plt.subplot2grid((3,1), (i,0)) for j, station in enumerate(stations): fig1 = plt.figure(1) ax1 = plt.subplot2grid((1,3),(0,j)) plt.bar(A) plt.bar(B) plt.bar(C) plt.savefig(1.pdf) plt.close() plt.savefig(2.pdf) plt.close() But this code is just producing the plot inside the second loop (fig1). And the plots of the first loop are just empty pdf (fig). Does anyone knows why?
score: 0
linked to: http://stackoverflow.com/q/23896813
has title: Having two subplot2grid inside a loop

http://stackoverflow.com/comment/91870246
type: Comment
type: QuestionComment
has text: I assume Ubuntu has installed a newer driver for your graphics card. I had this problem on an ubuntu machine when I ran an update. So there's a mismatch between graphics driver and CUDA library versions. Look at [this answer](https://stackoverflow.com/questions/38009682/how-to-tell-if-tensorflow-is-using-gpu-acceleration-from-inside-python-shell) to see if your GPU is even being used. I suspect it isn't. I fixed my machine by reinstalling the NVIDIA driver I was using prior to the upgrade.
comment on: http://stackoverflow.com/q/52464059
score: 2

http://stackoverflow.com/a/52509167
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52508556
answers question: http://stackoverflow.com/q/52508556
type: Answer
has comment: http://stackoverflow.com/comment/91977797
has body: You're attempting to delete a string, which you also used to create the message. It has no relation to the actual discord.Message object that was sent. You need to capture that object, which is the return value of send_message text = "The word scramble is: `{}`! You have 10 seconds to solve...".format(scrambled) scramblemsg = await client.send_message(message.channel, text) ... await client.delete_message(scramblemsg)

http://stackoverflow.com/comment/92168828
comment on: http://stackoverflow.com/a/52558711
score: 0
type: AnswerComment
has text: that's better but still wrong ;-) The fact that ints are immuable is actually totally irrelevant, the problem is that rebinding a name only makes the name refer to another object. The behavior would be the same with mutable objects. The difference is not between mutable and immutable objects but between mutating and rebinding.
type: Comment

http://stackoverflow.com/q/52451039
possible better answer: http://stackoverflow.com/a/52451210
accepted answer: http://stackoverflow.com/a/52451190
has answer: http://stackoverflow.com/a/52451643
has answer: http://stackoverflow.com/a/52451210
tagged with: boolean
linked to: http://stackoverflow.com/q/12264834
has comment: http://stackoverflow.com/comment/91845418
has body: import random, math random.seed(1) def in_circle(x, origin = [0]*2): """ This function determines if a two-dimensional point falls within the unit circle. """ if len(x) != 2: return "x is not two-dimensional!" elif distance(x, origin) &lt; 1: return True else: return False print(in_circle((1,1))) Next, I want to determine whether each point in x falls within the unit circle centered at (0,0) using the function "in_circle". How do I do it? My level of programming - Beginner
linked to: http://stackoverflow.com/q/47789
has comment: http://stackoverflow.com/comment/92303028
downvote count: 0
favorite count: 0
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
has answer: http://stackoverflow.com/a/52451289
has title: How can I create a list of R=10000 booleans called inside in Python?
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52451190
score: 1

http://stackoverflow.com/comment/92083200
score: 0
has text: @martineau well how about that. It is using python 2.7.14 even though that version is no where to be found in the system path. Do you know how to fix this?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52571671

async-await
tags question: http://stackoverflow.com/q/52532075
type: Tag
tags question: http://stackoverflow.com/q/52582685
tags question: http://stackoverflow.com/q/52459138
tag name: async-await

http://stackoverflow.com/a/52583503
downvote count: 0
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/52544283
has body: I don't think you can pass a string for the FilterExpression, but you can obtain the Python expression you want using eval(). fe = "Attr('COLOR').eq('RED')" key = 'myKey' response = table.query(KeyConditionExpression=Key('key').eq(key), FilterExpression=eval(fe)) Of course, you need to really trust your input when using eval().
answers question: http://stackoverflow.com/q/52544283
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/q/52506364
has answer: http://stackoverflow.com/a/52506529
has body: I have a DataFrame with questionnaire data. The scores on some of the answers need to be inverted for further analysis. So what I want to do is the following: Select the rows with questions where the score is to be inverted; Map the score to the new score using a dictionary. All the relevant columns in my DataFrame are dtype 'category'. Below, I have set up a simplified example of what I am trying to accomplish: import pandas as pd # create a list of scores and a dictionary to invert the scores: lst = ['u', 'v', 'w', 'x', 'y'] lst_rev = list(reversed(lst)) dct = dict(zip(lst, lst_rev)) # create the example dataframe: df = pd.DataFrame({'A':['a', 'b', 'a', 'c', 'a'], 'B':lst}, dtype='category') # create a list for selecting the specific rows that need to be remapped: sel = ['b', 'c'] First method The first method I have tried: %timeit df['B'] = df.apply(lambda x: dct.get(x['B']) if x['A'] in sel else x['B'], axis=1) yields the following result: 2.6 ms ± 36.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Second method The second method was considerably slower (on my data set it seemed to perform far worse than this test would suggest): mask = df['A'].isin(sel) %timeit df.loc[mask, 'B'] = df.loc[mask, 'B'].map(dct) yielding: 3.56 ms ± 50.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) These approaches work, but both perform rather poorly on my data set. Does anyone have a faster method? Thanks in advance.
type: Question
possible better answer: http://stackoverflow.com/a/52506529
has answer: http://stackoverflow.com/a/52506415
downvote count: 0
has answer: http://stackoverflow.com/a/52506615
favorite count: 0
accepted answer: http://stackoverflow.com/a/52506415
answer count: 3
tagged with: pandas
has title: What is the fastest way to map a value from a dictionary to a subset of a column in Pandas?
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/52470290
answers question: http://stackoverflow.com/q/52469708
type: Answer
downvote count: 0
score: 1
has body: Two points to note: OrderedDict is insertion ordered, not ordered by size. Your keys are strings. For ordering by integer size, you need to convert them to integers. Considering these aspects, you can use sorted with a custom key defined to construct a list of tuples. Then feed this ordered collection to OrderedDict: d = {'17': 2, '19': 1, '8': 1, '9': 2, '12': 3, '23': 3} from collections import OrderedDict res = OrderedDict(sorted(d.items(), key=lambda x: int(x[0]))) Result: OrderedDict([('8', 1), ('9', 2), ('12', 3), ('17', 2), ('19', 1), ('23', 3)]) It is worth noting in Python 3.7 dictionaries are insertion ordered and this fact can be relied upon. In this case, OrderedDict can be replaced by dict provided the additional methods of OrderedDict are not required.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52469708

http://stackoverflow.com/comment/127586453
score: 0
type: Comment
has text: Also the shown `numpy.random.get_state()` seems to be legacy in the sense that it does not fit to the style of the new Generator API, where you can have several RNGs each with a separate state.
type: AnswerComment
comment on: http://stackoverflow.com/a/52545091

http://stackoverflow.com/comment/91873549
score: 0
comment on: http://stackoverflow.com/q/52465642
type: Comment
type: QuestionComment
has text: It's mp4 video.

http://stackoverflow.com/comment/91893552
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52475588
type: Comment
has text: thats why you have to parse to get the two text

http://stackoverflow.com/comment/92136260
comment on: http://stackoverflow.com/a/52584591
type: Comment
has text: Is that a problem ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92108711
score: 1
comment on: http://stackoverflow.com/q/52586723
type: Comment
type: QuestionComment
has text: Could you provide us the full code of the script you're trying to execute? In the code snippet you provided there is no actual line date = calendar.datetime.date

http://stackoverflow.com/a/52574039
has comment: http://stackoverflow.com/comment/92084528
has comment: http://stackoverflow.com/comment/92085059
has comment: http://stackoverflow.com/comment/92084389
score: 0
answers question: http://stackoverflow.com/q/52573892
has comment: http://stackoverflow.com/comment/92103599
type: Answer
has comment: http://stackoverflow.com/comment/92084839
has comment: http://stackoverflow.com/comment/92084501
has comment: http://stackoverflow.com/comment/92084624
has comment: http://stackoverflow.com/comment/92085850
has comment: http://stackoverflow.com/comment/92096432
has body: may be you want remove /Users/Library/Messages or /usr/Library/Messages,check the directory in your code is exist
has comment: http://stackoverflow.com/comment/92103192
has comment: http://stackoverflow.com/comment/92084712
has comment: http://stackoverflow.com/comment/92084685

http://stackoverflow.com/comment/91945157
comment on: http://stackoverflow.com/q/52496836
has text: @Lauren, any ideas? I have posted an answer below but I would like to listen to some explanations.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52514843
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52512761
accepted answer of: http://stackoverflow.com/q/52512761
type: AcceptedAnswer
downvote count: 0
has body: The reason you get this error message is that users.profile.get does not work with bot tokens. To mitigate just use the user token that you received along with your bot token when installing your Slack app.
type: Answer

http://stackoverflow.com/q/52468543
answer count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/91878945
tagged with: if-statement
score: 1
tagged with: dataframe
has body: Need a help with conditionals for pandas dataframe. Apologies in advance for the basic question or if it's covered elsewhere. Here's the example dataframe: employee sales revenue salary 12345 20 10000 100000 I have a few conditions based on data which will result in salary changing. scenarios: if sales >10 and revenue > $5,000, increase salary by 20% if sales &lt;5 and revenue > $5,000, increase salary by 10% otherwise, do nothing. variables: high_sales = 10 low_sales = 5 high_revenue = 5000 big_increase = 1.2 small_increase = 1.1 I know this requires some nesting but it's not clear to me how to do it. I want the outcome to be a dataframe with only the salary column adjusted. Here's the code: df['salary'] = np.where((df['sales']&gt;=high_sales &amp; df['revenue'] &gt;=high_revenue), df['salary'] * big_increase, (df['sales']&lt;=low_sales &amp; df['revenue'] &gt;=high_revenue), df['salary'] * small_increase, df['sales']) Is this right?
type: Question
downvote count: 0
has title: Conditional w/Pandas Dataframe
has answer: http://stackoverflow.com/a/52468570
tagged with: pandas

http://stackoverflow.com/comment/92068020
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52564701
has text: @AlexanderReynolds - thanks (and thanks for the answer below) - this is useful background information. I'll go and seek out some info on epoch timestamps because having potential errors like this lurking in my code makes me rather nervous.

http://stackoverflow.com/comment/92012680
score: 0
has text: @Gabriele in general you can expect that arguments valid for matplotlib are valid for analogous plot functions in seaborn. They are just marked as `**kwargs` in seaborn documentation
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52536219

http://stackoverflow.com/q/52490260
type: AnsweredQuestion
tagged with: join
accepted answer: http://stackoverflow.com/a/52490338
score: 1
upvote count: 1
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/52490356
has title: Python - Removing all punctuation from string and only printing words containing an "i" and are equal to or longer than five characters
has comment: http://stackoverflow.com/comment/91921292
possible better answer: http://stackoverflow.com/a/52490356
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52490338
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/5668947
tagged with: append
has body: testText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec mauris nec tellus mollis ullamcorper. Vestibulum sit amet arcu placerat, sagittis quam sed, rutrum sem. Morbi vulputate odio non lacus." splitText = testText.split(" ") print(splitText) cleanedText = '' for letter in testText: if letter in list('.,:;?!'): cleanedText.append(letter) ''.join(cleanedText) I am trying to remove all punctuation in the paragraph above, but I am running into an "Attribute Error: 'str' object has no attribute 'append'". What could potentially be going wrong and how should I go about resolving it? Additionally, how would I then only print worlds equal to or longer than five characters and contain an 'i'?

http://stackoverflow.com/q/52530316
type: Question
answer count: 3
score: 5
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: series
possible better answer: http://stackoverflow.com/a/52530343
has answer: http://stackoverflow.com/a/52530451
has answer: http://stackoverflow.com/a/52530343
accepted answer: http://stackoverflow.com/a/52531042
tagged with: python
has title: Get percentages of a column based off of another column but with different categories
tagged with: percentage
type: AnsweredQuestion
has body: I have the following Pandas Series: Count Pclass Survived 1 0 80 1 136 2 0 97 1 87 3 0 372 1 119 But I want something like this: Count Percentage Pclass Survived 1 0 80 37.0 1 136 63.0 2 0 97 52.7 1 87 47.3 3 0 372 75.8 1 119 24.2 I want to calculate the percentages based on only the counts in each category of Pclass (not the whole sum of counts). It would be great if these percentages are calculated using only the Count column. So far, what I did was I summed up the counts according to Pclass and used .repeat() to duplicate the values and tried to concatenate it to the original Series, which failed spectacularly. Count Pclass 1 216 1 216 2 184 2 184 3 491 3 491 My idea was to use this repeat column as the denominators in calculating the percentages, like this: 80 / 216 * 100 = 37.0% and then remove the repeat column after the percentages are calculated. Seems so simple but I can't seem to make it work. Any help is appreciated.
upvote count: 5
tagged with: dataframe
has answer: http://stackoverflow.com/a/52531042

http://stackoverflow.com/q/52504979
has body: Given a stack frame and a variable name, how do I tell if that variable is nonlocal? Example: import inspect def is_nonlocal(frame, varname): # How do I implement this? return varname not in frame.f_locals # This does NOT work def f(): x = 1 def g(): nonlocal x x += 1 assert is_nonlocal(inspect.currentframe(), 'x') g() assert not is_nonlocal(inspect.currentframe(), 'x') f()
answer count: 1
has comment: http://stackoverflow.com/comment/91950960
has answer: http://stackoverflow.com/a/52505101
has comment: http://stackoverflow.com/comment/91951015
has comment: http://stackoverflow.com/comment/91951009
has title: How to check if a variable with a given name is nonlocal?
type: AnsweredQuestion
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/22438219
has comment: http://stackoverflow.com/comment/91950757
favorite count: 0
accepted answer: http://stackoverflow.com/a/52505101
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/91950492
tagged with: python
has comment: http://stackoverflow.com/comment/91950401
tagged with: stack-frame
tagged with: python-nonlocal
upvote count: 3

http://stackoverflow.com/a/52510706
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Use SerializerMethodField as class CarrierStopSerializer(serializers.ModelSerializer): carrier = serializers.StringRelatedField() bus_stop = serializers.SerializerMethodField(read_only=True) def get_bus_stop(self, model): return [bus_stop.__str__() for bus_stop in model.bus_stop.all().order_by('id')] class Meta: model = CarrierStop fields = ['id', 'carrier', 'bus_stop']
answers question: http://stackoverflow.com/q/52507709
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52507709

http://stackoverflow.com/a/52570533
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/98087316
has comment: http://stackoverflow.com/comment/98024688
has body: There can be a number of reasons that makes your app slow, but first, check if it's common to all apps, or if it's something specific in yours. To do that, i'd encourage you to try with a simple app. from kivy.app import App from kivy.uix.button import Button class TestApp(App): def build(self): return Button(text='test') TestApp().run() is pressing this button slow? If it is, i'd encourage looking at kivy configuration in general, maybe try putting multisampling to 0 or 1 in the config, check the logs for use of the right window provider, etc. If it's decently performant, then try simplifying your app until the performances are decent again, you can enable the monitor module to check framerate easily, and the debugger module (flask required) to monitor memory usage. It's near impossible to give a general answer to this question, so a lot more specifics would be required, presumably after you narrowed the problem down a lot more.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/98057131
answers question: http://stackoverflow.com/q/52553499

http://stackoverflow.com/comment/92083258
comment on: http://stackoverflow.com/q/52573400
score: 0
type: QuestionComment
type: Comment
has text: Post the code you tried.

http://stackoverflow.com/q/52439531
downvote count: 0
answer count: 1
tagged with: parsing
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52439620
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: api
has body: How would i parse it to load store address id and title from the api to the select option value ? what i have tried so far &lt;select&gt; {% for store in stores.store_address %} &lt;option value="{{ store.store_address.id}}"&gt;{{ store.store_address.title}}&lt;/option&gt; {% endfor %} &lt;/select&gt; code in getting the data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) stores = requests.get('https://api.myjson.com/bins/16tdlw').json() context['stores'] = stores return context URL : https://api.myjson.com/bins/16tdlw (json data) Template : &lt;select&gt; {% for store in stores.store_address %} &lt;option value="{{ store.store_address.id}}"&gt;{{ store.store_address.title}}&lt;/option&gt; {% endfor %} &lt;/select&gt;
has title: How to parse json data and load it to django template

http://stackoverflow.com/comment/91952141
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52505640
has text: Where did you get the dataframe from? Just curious
type: Comment

http://stackoverflow.com/comment/92003588
has text: @BerryMan and note, in general, literal syntax works different than the constructor call, which will take as an argument an iterable of pairs and consume it. A literal is, well, a literal.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52531942
type: QuestionComment

http://stackoverflow.com/comment/91957562
comment on: http://stackoverflow.com/a/52508599
has text: @Ajax1234 Thanks a lot, i am going to also vote for you :-)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52459435
favorite count: 0
has answer: http://stackoverflow.com/a/52467667
has title: Online interface for Python GUI examples
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52459497
has body: Is there any online interface where I can execute my Python GUI scripts? Consider this script for an example: from tkinter import * window = Tk() window.title("Title window") lbl = Label(window, text="Hello") lbl.grid(column=0, row=0) window.mainloop() In most of the online interfaces, it gets stuck at second line itself.
tagged with: python
has comment: http://stackoverflow.com/comment/91861254
type: Question
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91876418

http://stackoverflow.com/comment/91997441
has text: Wait, i am trying NOT to capture that bit of information :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52529079
type: AnswerComment

http://stackoverflow.com/comment/92109935
type: AnswerComment
comment on: http://stackoverflow.com/a/52587203
type: Comment
has text: What do you mean by "using the user that is logged in"? `request.user` is always the logged in user.
score: 0

http://stackoverflow.com/comment/91858750
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52458292
type: Comment
has text: In my example above it does keep the list of evens in memory. So I guess my question was is the generator method any better than the original method above?

http://stackoverflow.com/q/52438304
favorite count: 0
accepted answer: http://stackoverflow.com/a/52438375
has comment: http://stackoverflow.com/comment/137404116
possible better answer: http://stackoverflow.com/a/64178983
tagged with: python
has answer: http://stackoverflow.com/a/52438418
answer count: 4
type: AnsweredQuestion
tagged with: python-requests
has answer: http://stackoverflow.com/a/52438410
has title: Capturing Response Body for a HTTP Error in python
type: Question
has answer: http://stackoverflow.com/a/52438375
score: 10
upvote count: 10
linked to: http://stackoverflow.com/q/16511337
downvote count: 0
has body: Need to capture the response body for a HTTP error in python. Currently using the python request module's raise_for_status(). This method only returns the Status Code and description. Need a way to capture the response body for a detailed error log. Please suggest alternatives to python requests module if similar required feature is present in some different module. If not then please suggest what changes can be done to existing code to capture the said response body. Current implementation contains just the following: resp.raise_for_status()
has answer: http://stackoverflow.com/a/64178983

http://stackoverflow.com/comment/91955457
type: Comment
has text: You could use `libvips` directly in Terminal `vips avg someImage.png`
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52505906

http://stackoverflow.com/a/52440947
has body: You're right, the implementation of the ttk Spinbox was omitted. This has been solved for python 3.7. You can copy this implementation to do this yourself though: import tkinter as tk from tkinter import ttk class Spinbox(ttk.Entry): def __init__(self, master=None, **kw): ttk.Entry.__init__(self, master, "ttk::spinbox", **kw) def set(self, value): self.tk.call(self._w, "set", value) root = tk.Tk() s = Spinbox(root, from_=0, to=10) s.set(5) s.pack() root.mainloop()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91845125
type: Answer
upvote count: 12
answers question: http://stackoverflow.com/q/52440314
downvote count: 0
has comment: http://stackoverflow.com/comment/91851998
accepted answer of: http://stackoverflow.com/q/52440314
score: 12
has comment: http://stackoverflow.com/comment/91840881

http://stackoverflow.com/comment/91813089
type: QuestionComment
comment on: http://stackoverflow.com/q/52434544
has text: Oh, thanks, I didn't know about the review site, though I did try and google it, I really didn't think this was the best place. I will post there. I also didn't know about the cross platform for c#, seriously checking that out. thanks guys
score: 0
type: Comment

http://stackoverflow.com/q/52460493
type: UnansweredQuestion
tagged with: python
has title: Class instance method call and @property access delegator
answer count: 0
has comment: http://stackoverflow.com/comment/91863232
has comment: http://stackoverflow.com/comment/91863178
has comment: http://stackoverflow.com/comment/91863185
type: Question
has comment: http://stackoverflow.com/comment/91863018
has comment: http://stackoverflow.com/comment/91863149
has body: I'd like to create a delegator D for an existing class A instance s.t. method calls and @property attribute access to A can be mocked in D: class D(object): def __init__(self, instance_of_A): self.instance_of_A = instance_of_A def __getattr__(self, attr): ... def attr_wrapper(*args, **kwargs): print('accessing attribute', attr) res = getattr(self.instance_of_A, attr)(*args, **kwargs) ... return res return attr_wrapper While that works for delegating to A's method calls that doesn't work for @property attributes of A. What's the best way to make it work? EDIT To clarify, this doesn't work if A has a @property attribute: class A(object): @property def foo(): return 1 EDIT2 Returning attr_wrapper is important since I want to intercept the return value that call.
score: 0

http://stackoverflow.com/comment/91963754
has text: As stated in the comments of the previous answer, I should not use a tree due to cyclic behaviour. But thanks for your answer, I may use it in a future project involving family trees
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52502257
type: Comment

http://stackoverflow.com/comment/92345107
type: Comment
has text: Don't forget to answer if it satisfies your question.
score: 1
comment on: http://stackoverflow.com/a/52579089
type: AnswerComment

http://stackoverflow.com/a/52588425
answers question: http://stackoverflow.com/q/52587405
type: Answer
has body: Instead of trying to capture the actual QuerySet that was used for the response and write a test for it, you should look at the response itself. Since you're writing an API I assume you want to assert that the JSON contains the correct data. For the django-rest-framework, a Response object has two attributes: response.data is the python serialised data used to render the JSON, while response.content is the JSON itself. So, if your MyModel doesn't have any objects yet, you could test: self.assertEqual(0, len(response.data)) or self.assertEqual("[]", response.content)
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52587405

http://stackoverflow.com/a/52509383
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/91974833
score: 2
has comment: http://stackoverflow.com/comment/91963386
has comment: http://stackoverflow.com/comment/91974563
answers question: http://stackoverflow.com/q/52509359
has comment: http://stackoverflow.com/comment/91958922
downvote count: 0
type: AcceptedAnswer
has body: I guess you want: values=['Value', 'number'] Or if you want all possible columns, don't pass values at all.
accepted answer of: http://stackoverflow.com/q/52509359

http://stackoverflow.com/a/52443422
has comment: http://stackoverflow.com/comment/91834455
score: 0
has comment: http://stackoverflow.com/comment/91829614
type: Answer
has body: Try @patch(__name__ + '.get_dict', MagicMock(return_value={'key': {}) to give a proper target to your mock.
has comment: http://stackoverflow.com/comment/91834282
answers question: http://stackoverflow.com/q/52442841

http://stackoverflow.com/comment/92104923
type: AnswerComment
comment on: http://stackoverflow.com/a/52585042
type: Comment
has text: not resolved.. is it working in your atom editor? in IDLE it is working but my daily driver is ATOM.. it is not working there
score: 0

http://stackoverflow.com/comment/91906540
type: Comment
has text: Could we also just `y = list(filter(lambda a: a > 5, f)` then `print(y)` now when we want to use `y` in the future we don't have to use `list` everytime we call `y`
type: AnswerComment
comment on: http://stackoverflow.com/a/52482260
score: 0

http://stackoverflow.com/q/52486718
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91914782
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/52487100
type: Question
score: 2
tagged with: wagtail
answer count: 1
downvote count: 0
has body: I need to have a wagtail DateField disabled by default, but if the content author checks a box (a wagtail BooleanField) then the field should be enabled and required. I'm struggling to find the best way to solve this, I haven't found documentation on how to do this. I was thinking about using Django signals or wagtail hooks but it does seem like a complex solution for what I think should be a common use case. So I was wondering if anyone has a better alternative or point me to the right direction.
has title: Enable wagtail DateField when a wagtail BooleanField is true
tagged with: python

http://stackoverflow.com/a/52534258
accepted answer of: http://stackoverflow.com/q/52533733
answers question: http://stackoverflow.com/q/52533733
upvote count: 2
score: 2
has body: It is not clear why you are trying to use LIKE on timestamps but this cannot work as the operator needs textual arguments. You can use equality operator on timestamps: WHERE bk_tenant = '%s' AND data_start = '%s'::timestamp AND data_stop = '%s'::timestamp or LIKE on texts: WHERE bk_tenant = '%s' AND data_start::text LIKE '%s' AND data_stop::text LIKE '%s' Note also that you should use Boolean operators AND instead of commas.
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52487352
downvote count: 0
has answer: http://stackoverflow.com/a/78419507
score: 13
favorite count: 0
has answer: http://stackoverflow.com/a/52487604
tagged with: seaborn
type: UnansweredQuestion
tagged with: boxplot
tagged with: python
has comment: http://stackoverflow.com/comment/93182856
has body: I was able to visualize my data in a boxplot using Seaborn. sns.boxplot( x=df['Score'].astype('float'), y=df['Group'] ) The visualization shows me: all four quartiles, lower and upper whisker, and some outliers. How can I also add the Mean line into the boxplots? See current visualization (without mean). Thanks!
upvote count: 13
linked to: http://stackoverflow.com/q/29777017
has title: How to add mean into boxplot visualization?
type: Question
answer count: 2

http://stackoverflow.com/q/52500193
type: Question
has comment: http://stackoverflow.com/comment/91941668
has comment: http://stackoverflow.com/comment/91941393
has comment: http://stackoverflow.com/comment/91941548
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91941367
has comment: http://stackoverflow.com/comment/91941120
answer count: 1
has comment: http://stackoverflow.com/comment/91941155
has comment: http://stackoverflow.com/comment/91941318
has comment: http://stackoverflow.com/comment/91940915
has comment: http://stackoverflow.com/comment/91941032
tagged with: python
has answer: http://stackoverflow.com/a/52500796
has body: I am implementing the classes in Python 2.7 as below: class MyClass(object): def do_something(self): """ do something here """ class MyClassManager(object): def get_my_class_obj(self): """read my_class_obj from db""" return instance # instance has type MyClass class MyClassUser(object): my_class_obj = new MyClass() # this is a class variable In main: MyClassUser.my_class_obj = MyClassManager().get_my_class_obj() """ do a lot of different things else in main """ From somewhere else: """only when some condition happens""" MyClassUser.my_class_obj.do_something() Is there a way I can defer the read obj (read from db inside get_my_class_obj) process in MyClassManager until obj.do_something method is actually invoked? Provided that I have to call MyClassManager.get_my_class_obj for some setup at the beginning. Suppose the situation is in the context of a web server and do_something will only be invoked when there is some request but I need to set up it first
has title: How to defer execution of a function?
has comment: http://stackoverflow.com/comment/91942022
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91942134
accepted answer: http://stackoverflow.com/a/52500796
has comment: http://stackoverflow.com/comment/91941742
has comment: http://stackoverflow.com/comment/91941240

http://stackoverflow.com/a/52464506
type: Answer
has body: This might not answer your question but this will be helpful for those who just started using pycharm for Django application. PyCharm does not give (It underlines some built in functions with red) auto-completion option for Django if you have started project with Pure Python. Pure Python option comes when you click on new project option from file menu or when you run pycharm to start new project. Pure Python is the default selected option on new project page. You should choose Django (the 2nd option) to get auto-completion option in PyCharm. Hope this would be helpful for others.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52463351
upvote count: 1

http://stackoverflow.com/q/52479133
tagged with: database
accepted answer: http://stackoverflow.com/a/52485667
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: linux
has body: I am using Ubuntu 16.04 and I installed PyCharm professional edition so I can run Django easy. I cloned Mayan EDMS from https://gitlab.com/mayan-edms/mayan-edms and after I installed all needed packages to run it in PyCharm. But I could not run it because I am getting error "unable to open database file". I am new to Django and can't figure out what to do. Nothing in tutorials said about fixing this. Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7f9fbe9438c8&gt; Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 198, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 127, in inner_run self.check_migrations() File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 20, in _init_ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 52, in _init_ self.build_graph() File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/loc…
has comment: http://stackoverflow.com/comment/91901606
has title: Unable to open database file - Mayan EDMS
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52485667
score: 1
linked to: http://stackoverflow.com/q/7670289
type: Question

timer
tag name: timer
tags question: http://stackoverflow.com/q/52522770
type: Tag
tags question: http://stackoverflow.com/q/52503187
tags question: http://stackoverflow.com/q/52460513
tags question: http://stackoverflow.com/q/52444993

http://stackoverflow.com/comment/92091760
comment on: http://stackoverflow.com/a/52575801
score: 0
type: Comment
has text: Yes, I validated this by saving your example and then running the code. My json export looks fine, so please check your example.
type: AnswerComment

http://stackoverflow.com/comment/91999065
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52528736
type: AnswerComment
has text: Thank you so much, sir. This gave me a clear understanding, so the coordinate is for us to define it initially and use it to detect which coordinate it should be for the data. Btw, just a little correction, "col[0] = 2", could you edit it so that the future reader could refer to it as well.

http://stackoverflow.com/a/52468190
upvote count: 3
has body: By looking at the output of model.summary() you would find out what causes this problem (i.e. which layers have too much parameters): Layer (type) Output Shape Param # ================================================================= conv2d_189 (Conv2D) (None, 328, 328, 16) 448 _________________________________________________________________ activation_189 (Activation) (None, 328, 328, 16) 0 _________________________________________________________________ conv2d_190 (Conv2D) (None, 326, 326, 16) 2320 _________________________________________________________________ activation_190 (Activation) (None, 326, 326, 16) 0 _________________________________________________________________ max_pooling2d_9 (MaxPooling2 (None, 163, 163, 16) 0 _________________________________________________________________ dropout_3 (Dropout) (None, 163, 163, 16) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 425104) 0 _________________________________________________________________ dense_5 (Dense) (None, 128) 54413440 _________________________________________________________________ activation_191 (Activation) (None, 128) 0 _________________________________________________________________ dropout_4 (Dropout) (None, 128) 0 _________________________________________________________________ dense_6 (Dense) (None, 17) 2193 _________________________________________________________________ activation_192 (Activation) (None, 17) 0 ================================================================= Total params: 54,418,401 Trainable params: 54,418,401 Non-trainable params: 0 _________________________________________________________________ ​As you can see, since the output of Flatten layer is so big, the Dense layer would have too much parameters: 425104 * 128 + 128 = 54413440, i.e. 54 million parameters for just one layer (and it is almost 99% of all the parameters in the model). So, how to reduce this number? You need to reduce the outputs size of con…
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52463538
score: 3

http://stackoverflow.com/comment/92036689
score: 1
comment on: http://stackoverflow.com/q/52547801
has text: All tkinter processes must use the same thread, so tkinter does not play a role in your question. Whatever computation goes into whatever is shown in the tab can be threaded or multiprocessed, but which to use is very dependent on what that computation is. As a general rule, use multiprocessing for CPU bound programs, and threading for IO bound programs.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52555624
type: AcceptedAnswer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52555388
type: Answer
answers question: http://stackoverflow.com/q/52555388
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/92075446
has comment: http://stackoverflow.com/comment/92050031
has body: Use Resampler.last for last value of duplicated datetimes and then replace missing rows by forward filling: s = df.expanding().mean().resample("1d").last().ffill() print (s) 2013-01-01 7.000000 2013-01-02 6.333333 2013-01-03 6.333333 2013-01-04 6.333333 2013-01-05 6.333333 2013-01-06 6.333333 2013-01-07 6.333333 2013-01-08 6.750000 2013-01-09 6.750000 2013-01-10 6.750000 2013-01-11 7.400000 2013-01-12 7.333333 Freq: D, Name: A, dtype: float64

http://stackoverflow.com/q/52482349
has comment: http://stackoverflow.com/comment/91907554
has comment: http://stackoverflow.com/comment/91906399
score: 0
tagged with: pandas
tagged with: sql
answer count: 1
has title: “'NoneType' object is not iterable” error when trying to read sql query with pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91906836
tagged with: python
has comment: http://stackoverflow.com/comment/91907024
linked to: http://stackoverflow.com/q/7744742
has body: I came across the below post, which is my exact situation. I have a large SQL query which has the below format: SET NOCOUNT ON CREATE TABLE x INSERT INTO x CREATE TABLE y INSERT INTO y . . . SELECT * FROM x join y where a UNION SELECT * FROM x join y where b The query works perfectly fine, returning over 15k rows as intended. When I try and read this into a dataframe in python, I get the 'NoneType' object is not iterable error, as described in the below link. I see the original poster converted his query into a stored procedure. I am wondering if there is another way to resolve this error, without writing a stored procedure. Python Pandas read_sql_query “'NoneType' object is not iterable” error UPDATE - inserting python code server = 'server' query = 'test.sql' db ='db' conn = pyodbc.connect(r'Driver={SQL Server};Server=' + dbserver + ';Database=' + database + ';Trusted_Connection=yes;') fd = open(query, 'r') df = pd.read_sql_query(fd.read(),conn) fd.close() conn.close()
has comment: http://stackoverflow.com/comment/91907392
has answer: http://stackoverflow.com/a/52483089
type: Question
has comment: http://stackoverflow.com/comment/91906667
linked to: http://stackoverflow.com/q/48287404
has comment: http://stackoverflow.com/comment/91906970

http://stackoverflow.com/a/52545609
type: AcceptedAnswer
has body: If I understand your question correctly, you're trying to alter your entry_points depending on the OS that is being used. If so you could just include something like this in setup.py, and specify setup(entry_points=entry_points): import os entry_points = {'gui_scripts': ['app = app.runApp:run']} if os.name == "nt": entry_points.update({'console_scripts': ['app-with-messages= app.runApp:run']}) print(entry_points) #&gt; {'console_scripts': ['app-with-messages= app.runApp:run'], 'gui_scripts': ['app = app.runApp:run']} Created on 2018-09-27 by the reprexpy package import reprexpy print(reprexpy.SessionInfo()) #&gt; Session info -------------------------------------------------------------------- #&gt; Python: 3.5 #&gt; Platform: Windows-7-6.1.7601-SP1 (64-bit) #&gt; Date: 2018-09-27 #&gt; Packages ------------------------------------------------------------------------ #&gt; reprexpy==0.1.1
has comment: http://stackoverflow.com/comment/92154942
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52545229
answers question: http://stackoverflow.com/q/52545229
has comment: http://stackoverflow.com/comment/92129800
upvote count: 2

http://stackoverflow.com/comment/92027083
type: QuestionComment
has text: So, please, tell me how to do the equivalent of Hex.parse() in my python code. I have a 64 character long string, and i want to use the first half as key and the second half as IV
score: 0
comment on: http://stackoverflow.com/q/52542923
type: Comment

http://stackoverflow.com/comment/91981402
comment on: http://stackoverflow.com/a/52520878
score: 0
type: AnswerComment
has text: @JesusMonroe what you mean ?
type: Comment

http://stackoverflow.com/q/52519433
has answer: http://stackoverflow.com/a/52537610
score: 0
answer count: 1
tagged with: similarity
tagged with: python
tagged with: semantics
tagged with: nlp
has title: Methods to extract keywords from large documents that are relevant to a set of predefined guidelines using NLP/ Semantic Similarity
type: AnsweredQuestion
tagged with: wordnet
has body: I'm in need of suggestions how to extract keywords from a large document. The keywords should be inline what we have defined as the intended search results. For example, I need the owner's name, where the office is situated, what the operating industry is when a document about a company is given, and the defined set of words would be, {owner, director, office, industry...}-(1) the intended output has to be something like, {Mr.Smith James, ,Main Street, Financial Banking}-(2) I was looking for a method related to Semantic Similarity where sentences containing words similar to the given corpus (1), would be extracted, and using POS tagging to extract nouns from those sentences. It would be a useful if further resources could be provided that support this approach.
type: Question
accepted answer: http://stackoverflow.com/a/52537610

http://stackoverflow.com/q/52471756
accepted answer: http://stackoverflow.com/a/52471779
has title: NameError: name 'Daniel' is not defined when using input()
tagged with: python
has comment: http://stackoverflow.com/comment/91917877
upvote count: 2
has comment: http://stackoverflow.com/comment/91885477
score: 0
downvote count: 2
has body: I'm brand new and am trying to make this incredibly basic code to work. When I run the code and type in my name, I get this error, Traceback (most recent call last): File "/Users/dbrown/Desktop/Name", line 2, in &lt;module&gt; name= input() File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'Daniel' is not defined This is the original code: print ("Please enter your name.") name= input() print ("Hello," , name)
has comment: http://stackoverflow.com/comment/91885480
answer count: 3
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52471779
favorite count: 0
possible better answer: http://stackoverflow.com/a/52471792
type: Question
has answer: http://stackoverflow.com/a/52471930
has answer: http://stackoverflow.com/a/52471792

http://stackoverflow.com/comment/91957267
score: 0
type: Comment
type: QuestionComment
has text: This is kind of too broad...
comment on: http://stackoverflow.com/q/52508479

http://stackoverflow.com/q/52512606
has comment: http://stackoverflow.com/comment/91965970
tagged with: python
has comment: http://stackoverflow.com/comment/91966681
answer count: 0
has comment: http://stackoverflow.com/comment/91966078
type: Question
has comment: http://stackoverflow.com/comment/91966453
has body: I want to create shared in-memory data base in one program(main.py) and want to connect to it from flask application(check_flask.py) program which runninng through apache server. I am successfully creating in-memory shared data base in main.py and but it gives OperationalError: unable to open database file error when i am trying to connect to it in Flask application program(check_flask.py) Here is my Code: main.py p = sqlite3.connect("file:fruits?mode=memory&amp;cache=shared") p.execute('CREATE TABLE foo (bar, baz)') p.execute("INSERT INTO foo VALUES ('apple', 'orange')") p.commit() check_flask.py app = Flask(__name__) @app.before_first_request def Initialization(): q = sqlite3.connect("file:fruits?mode=memory&amp;cache=shared") print list(q.execute('SELECT * FROM foo')) Giving OperationalError: unable to open database file error But i am succsfully connecting to fruits in-memory data base from the another program (check.py) which is not flask based. check.py q = sqlite3.connect("file:fruits?mode=memory&amp;cache=shared") print list(q.execute('SELECT * FROM foo')) and it is printing the result as [(u'apple', u'orange')] I have gone through many websites, but none of them seem to be working. Please Help! Thank you
has comment: http://stackoverflow.com/comment/91967706
has comment: http://stackoverflow.com/comment/91967974
score: 0
has comment: http://stackoverflow.com/comment/91967890
tagged with: apache
has title: Flask: OperationalError: unable to open database file (in memory data base file)
tagged with: sqlite
has comment: http://stackoverflow.com/comment/91967333
tagged with: flask
has comment: http://stackoverflow.com/comment/91983630
has comment: http://stackoverflow.com/comment/91983427
has comment: http://stackoverflow.com/comment/91967425
type: UnansweredQuestion

http://stackoverflow.com/a/52479712
has comment: http://stackoverflow.com/comment/91918211
has body: I think you just need to move 1 line into the while loop: import time awake = "06:00:00" # turn on the lights at 6am sleep = "22:00:00" # turn off the lights at 10pm while True: timenow = time.strftime("%X") #moved this line into the while loop print (timenow) # print the current time if awake &lt;= timenow: print ("Lights On") elif timenow &gt;= sleep: print ("Lights Off") The output should now look like: Lights On 08:50:22 Lights On 08:50:23 Lights On 08:50:24 In the question, timenow gets set and is never updated. So move that into the while loop flow so it gets created each time. Just as good programing practice you may also want to toss a pause in there so it's just not hammering the CPU in the loop. You could put this at the end of the while loop and it will wait 1 second before looping again: .... elif timenow &gt;= sleep: print ("Lights Off") time.sleep(1)
downvote count: 0
answers question: http://stackoverflow.com/q/52479666
type: Answer
has comment: http://stackoverflow.com/comment/91920169
upvote count: 3
score: 3

http://stackoverflow.com/q/52445406
has title: Windows: Installed numpy (conda): ModuleNotFoundError
type: Question
has body: I've conda installed numpy in my environment, and it seems to be working in the command line. Yet when I run a file which imports it, I get a ModuleNotFoundError These are my packages: (pandaenv) C:\Users\LorenzKort\OneDrive - ITDS Groep B.V\Documenten\Python&gt;webscraper_test.pyTraceback (most recent call last): File "C:\Users\LorenzKort\OneDrive - ITDS Groep B.V\Documenten\Python\webscraper_test.py", line 1, in &lt;module&gt; import numpy as np ModuleNotFoundError: No module named 'numpy' (pandaenv) C:\Users\LorenzKort\OneDrive - ITDS Groep B.V\Documenten\Python&gt;webscraper_test.pyTraceback (most recent call last): File "C:\Users\LorenzKort\OneDrive - ITDS Groep B.V\Documenten\Python\webscraper_test.py", line 1, in &lt;module&gt; import numpy as np ModuleNotFoundError: No module named 'numpy' (pandaenv) C:\Users\LorenzKort\OneDrive - ITDS Groep B.V\Documenten\Python&gt;python Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda custom (64-bit) on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy &gt;&gt;&gt; numpy &lt;module 'numpy' from 'C:\\Users\\LorenzKort\\Miniconda3\\envs\\pandaenv\\lib\\site-packages\\numpy\\__init__.py'&gt;
has comment: http://stackoverflow.com/comment/91891155
has comment: http://stackoverflow.com/comment/91836822
tagged with: conda
upvote count: 2
tagged with: numpy
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52447006
score: 2
downvote count: 0

http://stackoverflow.com/a/52503312
accepted answer of: http://stackoverflow.com/q/52503203
answers question: http://stackoverflow.com/q/52503203
score: 5
has body: You were close, you forgot to put ax.invert_xaxis(). But still, you assigned the y-ticks on the left-hand side y-axis. To assign the ticks on the right-hand side, you need to first create a twin x-axis (right-hand side y-axis) instance (here ax1) and then plot the bars on that. You can hide the left-hand side y-axis ticks and labels by passing []. I present two ways to solve it (rest of the code remains the same except that now you use ax1 instead of ax) Solution 1 ax.set_yticklabels([]) # Hide the left y-axis tick-labels ax.set_yticks([]) # Hide the left y-axis ticks ax1 = ax.twinx() # Create a twin x-axis ax1.barh(y_pos, performance, xerr=error, align='center', color='green', ecolor='black') # Plot using `ax1` instead of `ax` ax1.set_yticks(y_pos) ax1.set_yticklabels(people) Solution 2 (same output): Keep the plot on the left axis (ax), invert the x-axis, and set the y-ticklabels on ax1 ax.invert_yaxis() # labels read top-to-bottom ax.invert_xaxis() # labels read top-to-bottom ax2 = ax.twinx() ax2.set_ylim(ax.get_ylim()) ax2.set_yticks(y_pos) ax2.set_yticklabels(people)
type: AcceptedAnswer
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91864143
type: Comment
comment on: http://stackoverflow.com/a/52450993
has text: I think the same, it is something about layout somewhere is missing a self. I do not know, that is why I seek any help.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92006501
type: AnswerComment
has text: As per Python doc : when a submodules is loaded using any mechanism , a binding is placed in the parent module's namespace. https://docs.python.org/3/reference/import.html check 5.4.2. Submodules topic.
comment on: http://stackoverflow.com/a/52532547
type: Comment
score: 0

http://stackoverflow.com/a/52474184
type: Answer
type: AcceptedAnswer
score: 0
has body: I found out that it is a bug of pandas, which appeared in 0.23.0 version, released in May 2018, and was solved in 0.23.4 version, released in Sep 2018. So if you happens to meet some problems concerning pandas.pivot_table, especially when the there exist NaNs in your categorical data, you'd better first check your pandas version and upgrade it.:)
answers question: http://stackoverflow.com/q/52458158
accepted answer of: http://stackoverflow.com/q/52458158

http://stackoverflow.com/comment/92035875
score: 0
comment on: http://stackoverflow.com/q/52548218
type: Comment
type: QuestionComment
has text: 1. Find the line number of '{' 2. Use 'dom' in minidom and parse From that line number. This will do

http://stackoverflow.com/comment/92103409
score: 0
type: AnswerComment
type: Comment
has text: `__init__` just initialized an object - it doesn't create one. You might be thinking of [`__new__`](https://docs.python.org/3/reference/datamodel.html#object.__new__).
comment on: http://stackoverflow.com/a/52584237

http://stackoverflow.com/comment/91931365
type: QuestionComment
score: 0
has text: the firstlines are exactly like theones I added in the description of my problem
type: Comment
comment on: http://stackoverflow.com/q/52493079

http://stackoverflow.com/q/52519019
has body: I am new to scripting. Could you help me in finding my way to separate sequences based on the information in the header for example i have fasta file like this ERR1897927.533;barcodelabel=R40_1193R_F61_799F; GTAGTCCTAGCCCTAAACGATGGATACTTGGTGTGACTGGGATTGAATCCAGTCGTGCCG AAGCTAACGCATTAAGTATCCCGCCTGGGGAGTACGGTCGCAAGGCTGAAACTCAAAGGA ATTGACGGGGGCCCGCACAAGCGGTGGAGCATGTGGTTTAATTCGAAGCAACGCGCAGAA CCTTACCAGCGTTTGACATGGTAGGACGGTTTCCAGAGATGGATTCCTCCCCTTACGGGG CCTACACACAGGTGCTGCATGGCTGTCGTCAGCTCGTGTCGTGAGATGTTGGGTTAAGTC CCGCAACGAGCGCAACCCTCGTCTTTAGTTGCCACCATTTAGTTGGGCACTCTAAAGAAA ERR1897927.925;barcodelabel=R41_1193R_F62_799F; Now i would like to separate sequences in to separate fasta files based on "barcodelabel" (just based on the header, not from sequence itself as i already removed the barcodes) Please let me know the way, May thanks in advance, Best! Wasim
has answer: http://stackoverflow.com/a/52521379
has title: Splitting a fasta file on the basis of header information
type: Question
has comment: http://stackoverflow.com/comment/91984438
upvote count: 2
has comment: http://stackoverflow.com/comment/91977722
answer count: 1
linked to: http://stackoverflow.com/q/7654971
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/91982973
downvote count: 5
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/91977815

http://stackoverflow.com/a/52566686
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52563793
answers question: http://stackoverflow.com/q/52563793
has body: Unary operator + expects valid a operand (int, float etc) on the right side. In your code 3, + (2, 4), you are providing a tuple (2, 4) as an operand to + which is not a valid operand and so is the error. In your code: newtup = (3,) + (2, 4) These are 2 separate tuples (3,) and (2,4), so it works. newtup = 3, + (2, 4) Here its a single tuple with 2 elements 3 and +(2, 4) which fails due to above mentioned reason.

http://stackoverflow.com/q/52575701
score: 1
answer count: 1
downvote count: 0
favorite count: 0
has title: Running multiple statements with MySQLdb
tagged with: mysql-python
has answer: http://stackoverflow.com/a/52575719
tagged with: python
has body: I'd like to run multiple statements with one command. Is it possible: This is the SQL command: UPDATE toggle SET state='0' WHERE feature_name=‘feature_1; UPDATE toggle SET state=‘1’ WHERE feature_name=‘feature_2’; UPDATE toggle SET state=‘1’ WHERE feature_name=‘feature_3’; For one command I run something like that: import MySQLdb myDB = MySQLdb.connect(host=host, port=db_port, user=user, passwd=db_password, db=db) cHandler = myDB.cursor() cHandler.execute(query) But this obviously works only for a single statement Thanks!
type: AnsweredQuestion
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52575719

http://stackoverflow.com/comment/120029361
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52594238
type: AnswerComment
has text: works great with my pool also!! thanks so much Dmitry

system-calls
type: Tag
tags question: http://stackoverflow.com/q/52472824
tag name: system-calls

http://stackoverflow.com/a/52476430
downvote count: 1
has comment: http://stackoverflow.com/comment/91920033
answers question: http://stackoverflow.com/q/52472993
upvote count: 5
has body: For built-in formats all options are enumerated in the official documentation. Each format has its own set of option, so you have to refer to the one you use. For read open docs for DataFrameReader and expand docs for individual methods. Let's say for JSON format expand json method (only one variant contains full list of options) json options For write open docs for DataFrameWriter. For example for Parquet: parquet options However merging schema is performed not via options, but using session properties spark.conf.set("spark.sql.parquet.mergeSchema", "true")
score: 4
has comment: http://stackoverflow.com/comment/123246845
type: Answer

http://stackoverflow.com/comment/91918732
type: Comment
type: QuestionComment
has text: "You should verify [Wing] can actually use Python3." I am stating that Wing can use Python 3.
score: 0
comment on: http://stackoverflow.com/q/52488445

http://stackoverflow.com/comment/110233518
comment on: http://stackoverflow.com/a/52497714
has text: For future visitor, you can import firestore as `from google.cloud import firestore` and then do like `location = firestore.GeoPoint(latitude, longitude)`.
type: AnswerComment
score: 4
type: Comment

http://stackoverflow.com/comment/92052277
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52555918
has text: but the error/no error results are in the exact same environment?
score: 0

http://stackoverflow.com/a/55078172
score: 1
answers question: http://stackoverflow.com/q/52430188
type: Answer
has body: Ok, garbage collection solved it. Now I can press the button and it works every time! I may tweak the delays to get as tight as possible. Would be nice to query the urequests if busy instead of just a crude delay, but hey... Here's the my loop that sends out the requests: gc.enable() while True: time.sleep_ms(250) if (btn1.value() == 0): urequests.post(url, data=json.dumps(data_play)) time.sleep_ms(650) while (btn1.value() == 0): time.sleep_ms(200) pass gc.collect()
has comment: http://stackoverflow.com/comment/96983671
has comment: http://stackoverflow.com/comment/97038174
upvote count: 1
has comment: http://stackoverflow.com/comment/97043486
downvote count: 0

http://stackoverflow.com/comment/91881989
comment on: http://stackoverflow.com/q/52467592
has text: Your code doesn't appear to load any images or call your `luminance_edit()` function? Your description says you plan to *"mess"* with luminance and saturation which isn't much help at all. What is the question and what is your incomplete code trying to achieve and what aspect doesn't work?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92104549
comment on: http://stackoverflow.com/q/52584838
score: 1
has text: `os.makedirs('/home/a', exist_ok=True)` will create it if it doesn't exist (and do nothing if it does). `os.chdir('/home/a')` will change to it.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52440485
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91826480
tagged with: list
has comment: http://stackoverflow.com/comment/91824124
downvote count: 3
has answer: http://stackoverflow.com/a/52449410
has body: I would like to convert a list of strings into a dictionary. The list looks like such after I have split it into the seperate words: [['ice'], ['tea'], ['silver'], ['gold']] Which I want to convert to a dictionary which looks like such: { 1 : ['i', 'c', 'e'] 2 : ['t','e','a'] 3 : ['s','i','l','v','e','r'] 4 : ['g','o','l','d']} This is my code thus far: import itertools def anagram1(dict): with open('words.txt', 'r') as f: data = f.read() data = data.split() x = [] y = [] for word in data: x1 = word.split() x.append(x1) for letters in word: y1 = letters.split() y.append(y1) d = dict(itertools.zip_longest(*[iter(y)] * 2, fillvalue="")) To which I receive the following error: TypeError: 'dict' object is not callable
answer count: 2
has answer: http://stackoverflow.com/a/52440659
upvote count: 0
type: UnansweredQuestion
score: -3
linked to: http://stackoverflow.com/q/5942874
favorite count: 0
has title: Convert list of strings into dictionary
type: Question
tagged with: python

http://stackoverflow.com/q/52584455
has title: I want to join two dataframe columns but not getting desired ouput
type: Question
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/92104714
has comment: http://stackoverflow.com/comment/92104738
score: -1
has answer: http://stackoverflow.com/a/52585464
has comment: http://stackoverflow.com/comment/92104787
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/52584723
has comment: http://stackoverflow.com/comment/92132652
has body: I have two dataframe one is x and another is total which have a column pop but has datetime as index data of the dataframe are of this type: total[pop] dataframe data: DateTime 2016-08-20 12:00:00 NaN 2016-08-21 00:00:00 NaN 2016-08-21 12:00:00 NaN 2016-08-22 00:00:00 NaN 2016-08-22 12:00:00 NaN x Dataframe x 0 1 1 2 2 3 3 4 4 5 i wrote this query: data_Window=pd.concat([x.x,Total.pop[index_start:index_end].reset_index(drop=True)],axis=1,ignore_index=True) where index start and index end has some integer value to join some range of data with x. the output i got: 0 1 0 1 NaN 1 2 NaN 2 3 NaN 3 4 NaN 4 5 NaN 5 6 NaN 6 7 NaN 7 8 NaN even for some pop column where some value is present it is showing nan(i had just post some rows for example both dataframe has more than 100 rows) output I want : index x pop 0 1 2.09 1 2 1.30 2 3 2.10
tagged with: dataframe
type: UnansweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/92104659
favorite count: 0

http://stackoverflow.com/q/52583047
tagged with: python
linked to: http://stackoverflow.com/q/4605439
has answer: http://stackoverflow.com/a/52583082
type: Question
tagged with: python-3.6
has body: My question is: Extract: "agne" From: "Orange" I am trying to extract not ange but agne from Orange. How do I change n and gf?
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92101176
has comment: http://stackoverflow.com/comment/92101213
has answer: http://stackoverflow.com/a/52583766
has title: Python - how to extract text from list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92102012

http://stackoverflow.com/q/52471770
has answer: http://stackoverflow.com/a/52472933
has title: Merging two dataframes with different lengths
type: Question
has comment: http://stackoverflow.com/comment/91885774
accepted answer: http://stackoverflow.com/a/52471920
answer count: 3
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91885649
has answer: http://stackoverflow.com/a/52471852
favorite count: 0
has body: How can I merge two pandas dataframes with different lengths like those: df1 = Index block_id Ut_rec_0 0 0 7 1 1 10 2 2 2 3 3 0 4 4 10 5 5 3 6 6 6 7 7 9 df2 = Index block_id Ut_rec_1 0 0 3 2 2 5 3 3 5 5 5 9 7 7 4 result = Index block_id Ut_rec_0 Ut_rec_1 0 0 7 3 1 1 10 NaN 2 2 2 5 3 3 0 5 4 4 10 NaN 5 5 3 9 6 6 6 NaN 7 7 9 4 I already tried something like, but it did not work: df_result = pd.concat([df1, df2], join_axes=[df1['block_id']]) I already tried: df_result = pd.concat([df1,df2,axis = 1) But the result was: Index block_id Ut_rec_0 Index block_id Ut_rec_1 0 0 7 0.0 0.0 3.0 1 1 10 1.0 2.0 5.0 2 2 2 2.0 3.0 5.0 3 3 0 3.0 5.0 9.0 4 4 10 4.0 7.0 4.0 5 5 3 NaN NaN NaN 6 6 6 NaN NaN NaN 7 7 9 NaN NaN NaN
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/52471852
downvote count: 1
has comment: http://stackoverflow.com/comment/91885504
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52471920
score: 1

http://stackoverflow.com/comment/92107250
type: AnswerComment
has text: Oh cool, its more simple than I thought. And kind of trivial simple ;-)... Thanks
comment on: http://stackoverflow.com/a/52586173
type: Comment
score: 0

http://stackoverflow.com/comment/92090533
has text: @Scratch'N'Purr Could you point out to the line in the source code? [Line679](https://github.com/scikit-learn/scikit-learn/blob/bac89c253b35a8f1a3827389fbee0f5bebcbc985/sklearn/linear_model/sgd_fast.pyx#L679) looks slightly different.
score: 0
comment on: http://stackoverflow.com/q/52577305
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92293249
type: Comment
score: 0
type: AnswerComment
has text: Wow, thank you very much for your gift!!! I also want to mention that I didn't do it for the points :) .
comment on: http://stackoverflow.com/a/52604703

http://stackoverflow.com/q/52583987
has title: django allow_tags not working in changeview in sometimes
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question
downvote count: 0
has body: Django version:1.9.2 python version:2.7.5 my model: class User(models.Model): headimgurl = models.CharField(verbose_name=u"icon", default=None, null=True, max_length=512, blank=True) def head_img(self): default_img_url = "http://mat1.gtimg.com/bbs/life-admin/activity/assets/logo.png" html = u"&lt;img style=\"height:50px; width:50px;\" src=\"%s\"/&gt;" % (self.headimgurl or default_img_url) return html head_img.allow_tags = True head_img.short_description = u"icon" my admin: class UserAdmin(admin.ModelAdmin): fields = ( ('head_img', 'headimgurl',), ) readonly_fields = ("head_img", ) list_display = ('head_img', ) enter code here I run the program and visit the website, all the icon show in list view, but some icon not show in change view. All the icons show in list view. In change view the mokey icon was shown: But the cartoon boy icon not shown in change view: What is the problem? Why some icon shown in change view but others not shown?

http://stackoverflow.com/q/52568037
has comment: http://stackoverflow.com/comment/92081173
has comment: http://stackoverflow.com/comment/92087051
has comment: http://stackoverflow.com/comment/92073230
score: 2
answer count: 1
downvote count: 0
tagged with: binary-data
has body: I am writing sequences of floating points from Fortran into binary files and want to read them in Python. All works fine with single and double precision floats (kind=4) and (kind=8), but when I attempt to move to a real(kind=16) variable type, suddenly things no longer work (data array filled with zeros). I read here: python read 16 bytes long double from binary file That a workaround is needed for the np.fromfile function. I implemented the suggested change but am still not getting the right result. Mwe Python and Fortran code is below. I tried this both with Python 2.7 + Numpy 1.8 and Python 3.4 + Numpy 1.14 to the same effect. I also checked and the generated file seems to have the right amount of data (480 bytes for 30 floats with 16 bytes). Any help will be welcome! Python reader: import numpy as np inputfilename = "fortranData.bin" dp = 8 nVals = 30 with open(inputfilename, 'rb') as f: # both work fine for 4 or 8 byte floats (32 and 64) # but not for 16 byte floats (np.float128) data = np.fromfile(f, dtype=np.float64) data = np.frombuffer(f.read(dp*nVals), dtype=np.float64, count=nVals) print(data) Fortran writer (compiled with gfortran 4.8.6 on Ubuntu 14.04) program test implicit none integer, parameter :: dp=8 integer, parameter :: outFileUnit=51, nPts=10, nDim=3 character(len=100) :: binaryFile="fortranData.bin" real(kind=dp), dimension(nPts,nDim) :: data integer :: i, j ! - generate data - do i=1, nPts do j=1, nDim data(i,j) = (i-1)*nDim + j enddo enddo ! - open file and write data - open(unit=outFileUnit, file=binaryFile, form='unformatted', access='direct', &amp; status='replace', recl=nDim*sizeof(data(1,1))) do i=1, nPts write(outFileUnit, rec=i) data(i,:) enddo end program test EDIT: as requested, here's a few lines of the data at the top of the fortranData.bin file: $od fortranData.bin 0000000 000000 000000 000000 000000 000000 000000 000000 037777 0000020 000000 000000 000000 000000 000000 000000 000000 040000 0000040 000000 000000 000000 000000 000…
tagged with: binaryfiles
tagged with: python
linked to: http://stackoverflow.com/q/28775979
favorite count: 0
has title: Reading 16 byte Fortran floats into Python from a file
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/52568477
tagged with: fortran
type: Question
accepted answer: http://stackoverflow.com/a/52568477
has comment: http://stackoverflow.com/comment/92073196
linked to: http://stackoverflow.com/q/838310

http://stackoverflow.com/q/52477809
answer count: 2
has answer: http://stackoverflow.com/a/52483658
tagged with: python
has comment: http://stackoverflow.com/comment/92117908
has comment: http://stackoverflow.com/comment/91906603
score: 0
has title: Python Iterator strangely skipping items
has comment: http://stackoverflow.com/comment/92115227
has answer: http://stackoverflow.com/a/52514524
has comment: http://stackoverflow.com/comment/91896981
accepted answer: http://stackoverflow.com/a/52514524
tagged with: iterator
has comment: http://stackoverflow.com/comment/91907761
type: AnsweredQuestion
has body: As part of a program that decodes a communication protocol (EDIFACT MSCONS) I have a class that gives me the next 'segment' of the message. The segments are delimited by an apostrophe "'". There may be newlines after the "'" or not. Here's the code for that class: class SegmentGenerator: def __init__(self, filename): try: fh = open(filename) except IOError: print ("Error: file " + filename + " not found!") sys.exit(2) lines=[] for line in fh: line = line.rstrip() lines.append(line) if len(lines) == 1: msg = lines[0] else: msg = '' for line in lines: msg = msg + line.rstrip() self.segments=msg.split("'") self.iterator=iter(self.segments) def next(self): try: return next(self.iterator) except StopIteration: return None if __name__ == '__main__': #testing only sg = SegmentGenerator('MSCONS_21X000000001333E_20X-SUD-STROUM-M_20180807_000026404801.txt') for i in range(210436): if i &gt; 8940: break print(sg.next()) To give an idea what the file looks like here's an excerpt of it: UNB+UNOC:3+21X000000001333E:020+20X-SUD-STROUM-M:020+180807:1400+000026404801++TL'UNH+000026404802+MSCONS:D:04B:UN:1.0'BGM+7+000026404802+9'DTM+137:201808071400:203'RFF+AGI:6HYR67925RZUD_000000257860_00_E27'NAD+MS+21X000000001333E::020'NAD+MR+20X-SUD-STROUM-M::020'UNS+D'NAD+DP'LOC+172+LU0000010496200000000000050287886::89'DTM+163:201701010000?+01:303'DTM+164:201702010000?+01:303'LIN+1'PIA+5+1-1?:1.29.0:SRW'QTY+220:9.600'DTM+163:201701010000?+01:303'DTM+164:201701010015?+01:303'QTY+220:10.400'DTM+163:201701010015?+01:303'DTM+164:201701010030?+01:303'QTY+220:10.400'DTM+163:201701010030?+01:303'DTM+164:201701010045?+01:303'QTY+220:10.400'DTM+163:201701010045?+01:303'DTM+164:201701010100?+01:303'QTY+220:10.400'DTM+163:201701010100?+01:303'DTM+164:201701010115?+01:303'QTY+220:10.400'DTM+163:201701010115?+01:303'DTM+164:201701010130?+01:303'QTY+220:10.400'DTM+163:201701010130?+01:303'DTM+164:201701010145?+01:303'QTY+220:10.400'DTM+163:201701010145?+01:303'DTM+164:201701010200?+01:303'QTY+220:11.200'DTM…
type: Question
possible better answer: http://stackoverflow.com/a/52483658

http://stackoverflow.com/a/58175803
has body: You can format time in 'hh:mm:ss' format. so you can try '04:00:00' for 4 am and 16:00:00 for 4 pm.
downvote count: 0
upvote count: 1
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52485323

http://stackoverflow.com/a/52964832
score: 8
has comment: http://stackoverflow.com/comment/104559541
has body: You have to skip the enum-name to access the values from your enum. As can be seen in the protocol-buffers python-tutorial the enum is defined within a message message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phones = 4; } In the section Reading a Message the enum is accessed by import addressbook_pb2 addressbook_pb2.Person.MOBILE So in your example it should be data_node_pb2.DataNodeManagement.MQTT
has comment: http://stackoverflow.com/comment/104558608
answers question: http://stackoverflow.com/q/52533044
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/52533044

http://stackoverflow.com/comment/92093989
score: 0
type: Comment
has text: This is the way I do export my package API. BTW you are free to change your package without any impact to the external API.
type: QuestionComment
comment on: http://stackoverflow.com/q/52579358

http://stackoverflow.com/comment/92021182
type: Comment
has text: @roganjosh I don't see why. The total of weights is always equal to the number of values we still have to generate, and only the ones we can choose have non-zero weights. For the final value, for example, the weights would be something like [0, 0, 0, 1, 0, 0], so we are sure that 3 would be chosen. Am I missing something?
comment on: http://stackoverflow.com/a/52540553
score: 0
type: AnswerComment

http://stackoverflow.com/q/52573220
downvote count: 0
tagged with: text-mining
favorite count: 0
has title: Cropping PDF files cannot crop out text for text extraction (textract and pdfminer)
tagged with: python
answer count: 0
tagged with: pypdf
type: UnansweredQuestion
upvote count: 1
score: 1
tagged with: pdfminer
has comment: http://stackoverflow.com/comment/92083222
type: Question
has body: I’m using the python library PyPDF2 to crop many PDF files to cut out the useless information on top and bottom of academic papers (i.e. page numbers and journal information at the bottom). Then I used the library textract to extract the texts from the cropped PDF files to txt files. However, the output txt files still contains the cropped out information despite the cropping. This also applies to pdfminer, another text extraction library (not OCR). It seems that for text extraction, as opposed to OCR, the text cannot be eliminated by simply cropping. Can anyone explain why this is the case? Any idea on how else to eliminate useless information in PDF files for text extraction?

http://stackoverflow.com/q/52483977
has comment: http://stackoverflow.com/comment/91909342
has answer: http://stackoverflow.com/a/52484044
accepted answer: http://stackoverflow.com/a/52484062
has comment: http://stackoverflow.com/comment/91909326
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52484169
has comment: http://stackoverflow.com/comment/91909362
type: AnsweredQuestion
has title: Python .csv into dictionary
has answer: http://stackoverflow.com/a/52484062
score: -4
has body: I want to convert the following csv E1;4;6;7;1;3;6 E2;5;4;3;5;0;0 E3;2;3;3;0;0;0 into a Python dictionary withe the following structure: d = {"E1": np.array([4,6,7,1,3,6])} d["E2"] = np.array([5,4,3,5,0,0]) Is there an easy way of doing this? Thank you very much.
type: Question
has comment: http://stackoverflow.com/comment/91909360
possible better answer: http://stackoverflow.com/a/52484044
downvote count: 4
answer count: 3
upvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91896823
comment on: http://stackoverflow.com/a/52477308
has text: Looks like some of the columns are empty...check for emptiness first ...
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91813827
type: QuestionComment
has text: In Pandas, you'll have to align the index (the first column) to make that work.
comment on: http://stackoverflow.com/q/52435166
score: 0
type: Comment

http://stackoverflow.com/a/52547827
has comment: http://stackoverflow.com/comment/92035019
answers question: http://stackoverflow.com/q/52547747
type: Answer
has comment: http://stackoverflow.com/comment/92035341
score: 2
has comment: http://stackoverflow.com/comment/92035093
upvote count: 2
has comment: http://stackoverflow.com/comment/92035008
has body: You can use either a list or a dictionary here. I would tend toward a dictionary, which I think best represents the sort of sparse data structure you're going for here (what's the first element of your count list? It'll always be zero, but shouldn't it really be nothing? Does it make more sense that a zero has been rolled no times, or that it can't be rolled at all?) That dictionary would be best defined simply as: counts = {} # You can also generalize your rolling 2d6! def roll_dice(num_dice, sides): total = 0 for _ range(num_dice): dieroll = random.randint(1, sides) total += dieroll return total for _ in range(rolls): roll = roll_dice(2, 6) counts.setdefault(roll, 0) += 1 # this is using dict.setdefault for roll, count in sorted(counts.items()): print("You rolled {} {}s".format(count, roll)) You could also use a collections.Counter to do this. rolls = [roll_dice(2, 6) for _ in num_rolls] # this will generate a list like [3, 12, 6, 5, 9, 9, 7, ...], # just a flat list of rolls. result = collections.Counter(rolls)
downvote count: 0

http://stackoverflow.com/a/52568857
downvote count: 0
answers question: http://stackoverflow.com/q/52568816
has comment: http://stackoverflow.com/comment/92074814
type: Answer
score: 2
upvote count: 2
has body: Probably because self.current_char is in LETTER at the first iteration. Then, you do not change it inside the second if so it keeps being in LETTERS. You should do: def make_tokens(self): tokens = [] while self.current_char is not None: if self.current_char.isspace(): print("debug if") # self.advance() remove this # continue remove this elif self.current_char == "''": print("debug elif 1") tokens.append(Token(STRING, self.string())) elif self.current_char in LETTERS: print("debug elif 2") tokens.append(Token(IDENTIFIER, self.identifier)) self.advance() # add this return(tokens) print("debug make tokens end")

http://stackoverflow.com/comment/91911708
type: QuestionComment
comment on: http://stackoverflow.com/q/52485045
has text: did you set AUTH_USER_MODEL in settings.py ? That should reference your custom model.
score: 0
type: Comment

http://stackoverflow.com/a/52482130
accepted answer of: http://stackoverflow.com/q/52458475
has body: Found a solution with "annoying" workaround (extracting strings of day, month and year). v2x = r'E:\Model\Data\v2x.csv' outfile = r'E:\Model\ModelSpecific\Input_shat2.txt' data = pd.read_csv(v2x, sep=",") data['Year'] = data['Date'].str.slice(6, 10) #redo the index because of american timestamp data['Month'] = data['Date'].str.slice(3,5) data['Day'] = data['Date'].str.slice(0,2) datetime = pd.to_datetime(data'Year','Month','Day') data = data.drop(['Date','Year','Month','Day'],axis=1) data = pd.concat((datetime,data),axis=1) data = data.rename({0:'Date'},axis=1) data = data.set_index('Date')
type: Answer
answers question: http://stackoverflow.com/q/52458475
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91828250
score: 0
type: AnswerComment
has text: Could you explain how your first example works? Looks slightly magical (from a beginners perspective). Thanks in advance :)
type: Comment
comment on: http://stackoverflow.com/a/52442478

http://stackoverflow.com/comment/91854725
type: AnswerComment
type: Comment
has text: Thanks!In which location/file I have to put the code from https://github.com/ssut/py-googletrans/pull/78 for temporary fix ?
comment on: http://stackoverflow.com/a/52456197
score: 0

http://stackoverflow.com/a/52538748
accepted answer of: http://stackoverflow.com/q/52538464
has comment: http://stackoverflow.com/comment/92020444
type: Answer
has body: If the Classes is in the same folder as main.py, you should import it this way (notice the dot before Classes): from .Classes.stage_competition import Stage_competition Alternatively, you could add directory to Classes to PYTHONPATH, which allows you to import Classes from anywhere.
has comment: http://stackoverflow.com/comment/92017553
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52538464
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92017648

http://stackoverflow.com/q/52483503
score: 4
linked to: http://stackoverflow.com/q/21046717
answer count: 3
has answer: http://stackoverflow.com/a/52484017
downvote count: 0
possible better answer: http://stackoverflow.com/a/52483973
has answer: http://stackoverflow.com/a/52483973
has body: I have written a simple python program that takes user input, with the use of input(). There are some different commands available. I want to make sure that all available commands function as intended and that the program catches invalid commands. Since there are quite a few different commands, this is very time-consuming to do manually (i.e., start the program, and enter all commands, one by one). (I have separate test functions for the actual execution of all commands, but I'm struggling to find a nice way to test this functionality together with the input() loop.) How can I automate the process of giving (predetermined) user inputs, without messing up the rest of the code? In addition to using this to test the program, it would also serve as an example to the user, in order to see the possible usage of the program. My current solution is that I have two versions of the main() function, which is basically just an infinite loop that takes inputs until an exit command is given. The first version, "main()", is the version intended for use and takes inputs from input(), until the user decides to quit. The second version, "main_test()" is only used for testing, and takes the inputs from a predetermined list, specified in the code. This does the job, but I do not want the main_test() code in the final version. I also do not want to "pollute" main() by adding things only used for testing. def main(): while True: user_input = input() ... def main_test(): test_input = [...] test_iter = 0 while True: user_input = test_input[test_iter] test_iter += 1 ... I have not been able to find a nice way to do this in python, although I'm sure there must be a smart way. I'd prefer a way that does not need any additional imports. But if there is a nice way to do it with additional imports, I'm all ears. Anyway, striking out with python, my next thought was to specify the commands in a Makefile, where I would start the program and feed the program text input, emulating the user. The main…
favorite count: 0
tagged with: python-3.x
tagged with: input
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52503514
type: Question
upvote count: 4
has title: Emulating user input in python for testing
accepted answer: http://stackoverflow.com/a/52503514

http://stackoverflow.com/comment/122334455
type: Comment
type: QuestionComment
has text: How does that output come from that input? I tried running your code with the data assigned to `data` and `result = {}`, but at the end, `result` was `{489: {2018: {6: {}}}}`.
score: 0
comment on: http://stackoverflow.com/q/52437272

http://stackoverflow.com/a/52443627
upvote count: 1
score: 1
has body: See iter() and Iterator Types for a in something: pass If somethings type is a itereable, a will take all values of your iterable in turn. What exactly a becomes is hidden inside the __iter__(self): implementation of the object you are iterating over (afaik). If you iterate over a list, it will present you with all values in turns. If you iterate over a dict, it will present you with all dict.keys() in turns. If you iterate over a string, it will present you each character in turn. Generators and sequences also provide iterating over, see Understanding generators in Python and Sequence Types If you iterate over a file, you will get (textfile, not binary) it line by line, unless you call other methods on the file first (): Demodata: with open("f.txt","w") as f: f.write("""Some Text Some text after a newline. More text in a new line.""") Iterate of file using it as iterable: with open("f.txt","r") as r: for c in r: # returns each single line including \n (thats the way next() of file works print (c) # appends another \n due to default end='\n' print("-"*30) Output: Some Text Some text after a newline. More text in a new line. ------------------------------ Iterate over file.read(): with open("f.txt","r") as r: t = r.read() # returns a single string of the whole files content for c in t: # you iterate characterwise over a string! print (c) print("-"*30) Output: S o m e [... snipped ...] l i n e . ------------------------------ Iterate over file using readline(): with open("f.txt","r") as r: for c in r.readline(): # returns only the first line as string and iterates over this string print (c) # the other lines are omitted! print("-"*30) Output: S o m e T e x t ------------------------------ Iterate over file using readlines(): with open("f.txt","r") as r: for c in r.readlines(): # returns a list of strings print (c) # appends another \n due to default end='\n' print("-"*30) Output: Some Text Some text after a newline. More text in a new line. ---------------------------…
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52442788
answers question: http://stackoverflow.com/q/52442788
type: Answer

http://stackoverflow.com/comment/92018518
type: QuestionComment
has text: Interesting question. You surely have noted that this is not possible for every array. One possible approach could be picking one element at a time, but restricting it to the set elements that would not lead to a bad solution if they were chosen... however I am not sure whether that is easy to compute.
comment on: http://stackoverflow.com/q/52539338
score: 0
type: Comment

http://stackoverflow.com/comment/137691791
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/54032274
type: Comment
has text: 'but I needed to make my own implementation of this stft function for the 3 hour file I'm analysing, as it's far too big to keep in memory.' - for a similar task (matching jingles in long 44.1 kHz files) I simply loaded the first audio channel of the inputs into float32 numpy arrays and cross-correlated them via `scipy.signal.correlate(..., mode='full', method='fft')` which took 'just' 10.2 GiB of RAM (~ 12 s runtime) for an input file of 2 hours. Arguably, by today standards, this isn't excessive, i.e. since MS Teams/Chrome/Eclipse/VSCode/etc. likely use much more after startup ...

http://stackoverflow.com/comment/92089473
type: QuestionComment
has text: how to import from different folder ? , and i have calculation.py in several folder . and they have same variable and function. will it be a problem if i import all calculation.py to calculation_control.py ?
comment on: http://stackoverflow.com/q/52577047
score: 0
type: Comment

http://stackoverflow.com/comment/91828630
has text: you are a cheat'r ;)
comment on: http://stackoverflow.com/a/52442990
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92065310
score: 0
type: Comment
type: QuestionComment
has text: @rahlf23 I hope my goal for the algorithm is now clear.
comment on: http://stackoverflow.com/q/52563392

http://stackoverflow.com/comment/92043725
type: QuestionComment
score: 1
has text: Please describe what you mean by "four bit binary representation". Your code currently displays the [ASCII-Value](http://www.asciitable.com/) in binary representation. With only four digits, you can only cover 15 different values, which seems a little low when trying to represent letters.
type: Comment
comment on: http://stackoverflow.com/q/52552389

http://stackoverflow.com/comment/98655586
score: 0
type: AnswerComment
type: Comment
has text: I have made few minor edits. Lemme know how it goes. P.S. The code is tested, so there should be no major issues in making it work in a different pipeline.
comment on: http://stackoverflow.com/a/55856716

http://stackoverflow.com/comment/91861453
type: QuestionComment
has text: Kindly check the answer [here](https://stackoverflow.com/questions/4828885/how-to-direct-output-into-a-txt-file-in-python-in-windows) . it's clear and it shall help you.
comment on: http://stackoverflow.com/q/52459478
score: 0
type: Comment

http://stackoverflow.com/comment/111016152
comment on: http://stackoverflow.com/q/52539973
has text: Could you please share the whole code? This would be a life saver for me. Thanks!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52550463
tagged with: python
has answer: http://stackoverflow.com/a/52550510
answer count: 1
has body: I use Django. I also use standalone Jinja2 to build email body from django models. I have model with choice field and I would like to get its display value from the model instance. In django template, it is easy, for example: {{ form.get_foo_display }}. However, it does not work if is it outside of the django template. My code using jinja2 is: Trip participation:\t{{ item.get_event_trip_display }} where item is model instance and event_trip is choice field (the {{ item.event_trip }} works ok) However the get_event_trip_display is rendered as: Trip participation: &lt;bound method curry.&lt;locals&gt;._curried of &lt;Registration: John Doe&gt;&gt; Known solutions: Use {% if ... %} block to manually select the choice. Append the instance with new attributes in Python code: item.trip_parictipation_display = item.get_trip_participation_display() My question: Is there simpler way hot to call the function directly in jinja2? (I have a lot of fields like that)
score: 0
has comment: http://stackoverflow.com/comment/92039814
has title: Django template {{ item.get_FOO_display }} using only jinja2 without django
tagged with: jinja2
accepted answer: http://stackoverflow.com/a/52550510
type: AnsweredQuestion
type: Question
tagged with: django

http://stackoverflow.com/q/52561574
tagged with: pandas
has answer: http://stackoverflow.com/a/52561666
has body: I have a pandas dataframe df with a column, call it A, that contains multiple data types. I want to select all rows of df where A has a particular data type. For example, suppose that A has types int and str. I want to do something like df[type(df[A])==int] .
linked to: http://stackoverflow.com/q/46999146
has answer: http://stackoverflow.com/a/52561660
favorite count: 0
has title: Subset pandas dataframe by dtype
type: UnansweredQuestion
tagged with: python
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/52561707
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/52561724
duplicate of: http://stackoverflow.com/q/46999146
tagged with: dataframe
score: 4

http://stackoverflow.com/q/52434276
accepted answer: http://stackoverflow.com/a/52434304
downvote count: 6
tagged with: python
has comment: http://stackoverflow.com/comment/91812151
has body: I am using Python and reading values from properties file as shown below, print config.get('DeviceSection', 'Device1.name'); d1=config.get('DeviceSection', 'Device1.name') print d1 My JSON is { "device-id":"system", "open-config":{ "port":32767 } } Now, I want to set device-id with the value i was getting from config file. What I tried was, { "device-id":"+d1+", "open-config":{ "port":32767 } } But value of d1 is not substituting inside the string. Any idea what I am missing?
has comment: http://stackoverflow.com/comment/91812173
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52434304
type: Question
has title: Python String concatenation with in double quotes
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91812137
tagged with: string
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/91812119

http://stackoverflow.com/a/52481234
accepted answer of: http://stackoverflow.com/q/52481090
type: Answer
upvote count: 3
has body: Comprehension [{'id': i, 'age': {'value': v, 'timestamp': '2018-01-01'}} for i, v in zip(df.id, df.age)] [{'age': {'timestamp': '2018-01-01', 'value': 68}, 'id': 10002145}, {'age': {'timestamp': '2018-01-01', 'value': 44}, 'id': 10005414}, {'age': {'timestamp': '2018-01-01', 'value': 61}, 'id': 10007083}, {'age': {'timestamp': '2018-01-01', 'value': 60}, 'id': 10008103}]
score: 3
answers question: http://stackoverflow.com/q/52481090
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91896741
type: Comment
type: QuestionComment
has text: Can you povide the implementation of `import_module( ... )` and definition of `sub`?
score: 0
comment on: http://stackoverflow.com/q/52476244

http://stackoverflow.com/q/52454982
has answer: http://stackoverflow.com/a/55250370
upvote count: 17
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has title: Django: Transaction and select_for_update()
has body: In my Django application I have the following two models: class Event(models.Model): capacity = models.PositiveSmallIntegerField() def get_number_of_registered_tickets(): return EventRegistration.objects.filter(event__exact=self).aggregate(total=Coalesce(Sum('number_tickets'), 0))['total'] class EventRegistration(models.Model): time = models.DateTimeField(auto_now_add=True) event = models.ForeignKey(Event, on_delete=models.CASCADE) number_tickets = models.PositiveSmallIntegerField(validators=[MinValueValidator(1)]) The method get_number_of_registered_tickets() do I need at several places in my application (e.g. template rendering). So I thought it makes sense to put it into the model also because it's related to it and I often heard it's good to have "fat models and lightweight views". My problem now: In order to prevent that two people want to register for the event in parallel, I have to use locking. Example: Let's say there's one ticket left to register for. Now, to people are on my website and click "Register" simultaneously. Under unforunate circumstances, it could happen that both requests are valid and now I have more registrations than capacity. I'm relatively new to Django, but reading through the docs, I thought that select_for_update() should be the solution, am I right here (I use PostgreSQL, so that should be supported)? However, the docs also say that using select_for_update() is only valid within a transcation. Evaluating a queryset with select_for_update() in autocommit mode on backends which support SELECT ... FOR UPDATE is a TransactionManagementError error because the rows are not locked in that case. If allowed, this would facilitate data corruption and could easily be caused by calling code that expects to be run in a transaction outside of one. My idea was now to change my model method get_number_of_registered_tickets() and add select_for_update(): def get_number_of_registered_tickets(): return EventRegistration.objects.select_for_update().filt…
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52455168
score: 17

http://stackoverflow.com/comment/91917800
has text: Not the reply I was hoping for but either way thanks for the reply
score: 0
comment on: http://stackoverflow.com/q/52487043
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52557348
has answer: http://stackoverflow.com/a/52564183
tagged with: jobs
downvote count: 0
answer count: 1
tagged with: keyboard
favorite count: 0
tagged with: terminal
type: UnansweredQuestion
tagged with: python
tagged with: readline
score: 1
has title: returning to python3 with fg messes up arrow keys interpretation
upvote count: 1
has comment: http://stackoverflow.com/comment/92073814
type: Question
has body: When I'm in gnome-terminal (or Konsole) and run python3, arrow keys work as expected but when I CTRL+Z so I come back to terminal, then fg to bring-up python3 again, arrow keys are printed like ^[[A . How can I fix this?

http://stackoverflow.com/comment/91918953
comment on: http://stackoverflow.com/q/52488815
score: 0
type: Comment
type: QuestionComment
has text: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

http://stackoverflow.com/a/52885859
upvote count: 6
has comment: http://stackoverflow.com/comment/93191063
has comment: http://stackoverflow.com/comment/93928476
has body: pip uninstall googletrans googletrans-temp pip install googletrans-temp Worked for me in Win10 and Ubuntu 16 (Python 3.6) as of 2019.2.24 -- Refer to one of the replies in https://github.com/ssut/py-googletrans/issues/94. The old fix pip install git+https://github.com/BoseCorp/py-googletrans.git --upgrade does not work any more over here.
answers question: http://stackoverflow.com/q/52455774
downvote count: 0
has comment: http://stackoverflow.com/comment/93221345
score: 6
type: Answer

http://stackoverflow.com/comment/91909294
type: QuestionComment
comment on: http://stackoverflow.com/q/52482678
score: 0
has text: Sorry, no, image added really doesn't help much. What does being in bounds mean precisely? What should happen when the turtle goes out of those bounds and what's currently happening instead? You should also post enough code (but only the minimal amount needed) **in your question** to reproduce the problem. See [How to create a Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve).
type: Comment

http://stackoverflow.com/comment/92011595
type: Comment
comment on: http://stackoverflow.com/q/52536052
score: 1
has text: Can you provide some sample data, so that we can run the code
type: QuestionComment

http://stackoverflow.com/q/52442841
tagged with: python-2.7
answer count: 2
score: 2
downvote count: 0
has title: List method in python returns empty list when we pass magic mock object
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52443223
has comment: http://stackoverflow.com/comment/91832499
tagged with: python
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/52443422
type: Question
has answer: http://stackoverflow.com/a/52443422
has body: I have a python code which needs to be run in both Python 2 and 3. In python 2 dict.values() returns list but in python 3 it returns dict_val object. So to make it compatible I have put list(dict.values()). It works fine. But when I am doing a Unit test using python mock there is one error. I am mocking dict.values() and it gives output like this &lt;MagicMock name='mock().values()' id='1099587993168'&gt;, but when I use a list, it makes this empty list. Below is the example. function file: class abc(): def get_dict(self, key):#i want to mock this as its depends on other method also dic = {'key': {'smaplekey': 'samplevalue'}}# its sample - return dic['key'] def run_method(self, val): print val def a(self,key): print 'before list' print self.get_dict(key).values() print list(self.get_dict(key).values()) b = list(self.get_dict(key).values())[0] print 'after list' self.run_method(b) test file: import unittest from mock import Mock, patch, MagicMock, ANY import function_file class TestA(unittest.TestCase): @patch('function_file.abc.run_method') @patch('function_file.abc.get_dict',MagicMock(return_vlaue={'key': {}})) def test_a(self, mock_run_method): manager = function_file.abc() result = manager.a('key') mock_run_method.assert_called_once_with(ANY, create=True) if __name__ == '__main__': unittest.main() Here list method make magic mock object empty list so it is failing. And below is the python error before list &lt;MagicMock name='mock().values()' id='1099803145040'&gt; [] E ====================================================================== ERROR: test_a (__main__.TestA) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched return func(*args, **keywargs) File "test_manager.py", line 9, in test_a result = manager.a('key') File "/usr/lib/python2.7/site-packages/abcd/function_file.py", line 13, in a b = list(self.get_dict(key).values())[0] I…
has answer: http://stackoverflow.com/a/52443223

http://stackoverflow.com/q/52510764
type: AnsweredQuestion
score: 2
upvote count: 2
has title: I want to pass values are gotten in views.py to forms.py
type: Question
possible better answer: http://stackoverflow.com/a/52511518
has comment: http://stackoverflow.com/comment/91962058
has comment: http://stackoverflow.com/comment/91961916
accepted answer: http://stackoverflow.com/a/52511261
answer count: 2
has body: I want to pass values are gotten in views.py to forms.py. I wrote in views.py, def app(request): if request.method == "POST": form = InputForm(data=request.POST) if form.is_valid(): name = form.cleaned_data['name'] age = form.cleaned_data['age'] in forms.py class InputForm(forms.Form): name = forms.CharField(max_length=100) age = forms.CharField(max_length=100) def logic(self): #I want to use views.py’s name&amp;age’s value here I am new to Django, so how should I write codes to do my ideal thing?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91961473
has answer: http://stackoverflow.com/a/52511261
has answer: http://stackoverflow.com/a/52511518
has comment: http://stackoverflow.com/comment/91962029
linked to: http://stackoverflow.com/q/9723465
tagged with: django
tagged with: python

http://stackoverflow.com/a/52445270
upvote count: 3
has comment: http://stackoverflow.com/comment/91833483
type: Answer
has body: SQL Server will attempt to convert the nvarchar column to an integer to match the literal type of the ID, and as you've seen, that won't fly - instead you need to pass the ID as an nvarchar literal. One way to do is with single quotes and a preceding N: Data = pd.read_sql_query("SELECT * from Data where [ID] = N'" + id + "'" ,engine) But such string manipulation techniques make your code vulnerable to SQL Injection attacks. A better idea would be to pass the ID as a parameter: Data = pd.read_sql_query("SELECT * from Data where [ID] = %s", engine, params=(id,))
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91833453
answers question: http://stackoverflow.com/q/52445132

http://stackoverflow.com/comment/91985951
score: 0
type: Comment
type: AnswerComment
has text: In case it doesnt work (because range is not a list..), do list(range(len(data)))
comment on: http://stackoverflow.com/a/52522230

http://stackoverflow.com/comment/91940973
comment on: http://stackoverflow.com/a/52499929
type: AnswerComment
has text: @Qubix is it something like this , you can change the datetime64 key if you want
score: 0
type: Comment

http://stackoverflow.com/q/52512750
type: Question
has comment: http://stackoverflow.com/comment/91996537
has body: I am making a spider which will crawl the entire site on the first run and store the data in my database. But I will keep running this spider on weekly basis to get the updates of the crawled site in my database and I don't want scrapy to crawl the pages which are already present in my database how to achieve this I have made two plans - 1] Make a crawler to fetch the entire site and somehow store the first fetched URL in a csv file then keep following the next pages. Then make another crawler which will start fetching backwards that means it will take the input from the URL in csv and keep running till prev_page exits this way I will get the data, but the url in csv will be crawled twice. 2] Make a crawler which will check condition if the data is in the database then stop, is it possible? This will be the most productive way but I can't find the way out. Maybe making logs files might help in some way? Update The site is a blog which updates frequently and sorted as latest post on the top manner
has answer: http://stackoverflow.com/a/52550950
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91970613
has comment: http://stackoverflow.com/comment/91966216
has comment: http://stackoverflow.com/comment/92002874
has comment: http://stackoverflow.com/comment/91970245
linked to: http://stackoverflow.com/q/52501149
favorite count: 0
has title: How to stop scrapy from crawling when it reaches the starting point of previous run
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92017025
has comment: http://stackoverflow.com/comment/91966404
tagged with: python
has comment: http://stackoverflow.com/comment/91971216
has comment: http://stackoverflow.com/comment/91970456
score: 1
upvote count: 1
tagged with: scrapy

http://stackoverflow.com/a/52630247
score: 0
has body: I believe that code works on QPython because you are using the sl4a project.To get the same services on python,using kivy rather,you will need to use pyjnius This let's you access the android api then you take that result and use it however you want
type: Answer
answers question: http://stackoverflow.com/q/52509755

http://stackoverflow.com/comment/91903579
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52480667
has text: If you mean that decorating the custom command handler function, it cannot help me to log expressions. It would be nice if I wanted to log executed management commands, not expressions I type in the Django shell.

http://stackoverflow.com/q/52557224
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: django
has title: Django pyinstaller error Import error myapp
type: Question
upvote count: 2
favorite count: 0
has body: I developped myproject with Django 1.11.8 and all it's ok Now I trying to generate the "myproject.exe" file by pyinstaller 3.4 This is the structure: myproject\ manage.py myproject\ settings.py urls.py myapp\ models.py views.py urls.py [Settings.py] INSTALLED_APPS = [ 'django.contrib.admin', ... ... 'myapp', ] [myapp/views.py] from django.views.generic import ListView, TemplateView from myapp.models import ModelOne, ModelTwo .... [myapp/urls.py] from django.conf.urls import url from myapp import views from django.conf import settings ... I receive the error ImportError generate by the function: get_module_file_attribute(package) where I investigated that the package is "myapp" like the following: File "...\lib\site-packages\PyInstaller\utils\hooks__init__.py", line 340, in get_module_file_attribute raise ImportError ImportError
tagged with: importerror
tagged with: pyinstaller
tagged with: python
score: 2

http://stackoverflow.com/a/52461453
accepted answer of: http://stackoverflow.com/q/52460917
upvote count: 2
type: Answer
score: 2
has body: One possible reason could be that your test data is not pre-processed the same way as your train/val data. You need to make sure that your test image pixel values are normalized between 0-1 before you call model.predict() as your model is being trained on normalized images.
downvote count: 0
answers question: http://stackoverflow.com/q/52460917
type: AcceptedAnswer

http://stackoverflow.com/q/52552680
answer count: 0
upvote count: 1
downvote count: 1
has body: Here is a simple example of a qtableView where every cell have a different item. In the example here i used numbers, but ultimately i wish to display animated gifs for every cells. I wish to keep the MVC design and insert a custom widget proceduraly. 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 Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) data = [random.choice(range(10)) for i in range(20)] l = QtGui.QHBoxLayout(self) splitter = QtGui.QSplitter() l.addWidget(splitter) tvf = QtGui.QTableView() model = TableModel(data, 3, self) tvf.setModel(model) splitter.addWidget( tvf ) if __name__=="__main__": import sys a=QtGui.QApplication(sys.argv) w=Widget() w.show() sys.exit(a.exec_()) After reading a bit more and with the help of @eyllanesc, i understand that there is 2 ways of achieving this: delegates or itemWidget. It seem that delegates won't work for me since it's not possible to insert widget into cells that way. ItemWidget seems the way to go but this is not MVC compatible ? i do not wish to loop the function to insert into the table... is there a third way ?
type: Question
has comment: http://stackoverflow.com/comment/92072422
tagged with: pyqt4
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/92072759
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: how to add widgets in every a qtableView cell with a MVC design?
tagged with: qtableview
tagged with: model-view-controller

http://stackoverflow.com/q/52490145
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52490198
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52490198
type: Question
has title: Why FLAGS is storing a value like other variables
score: 1
has body: In the following code I am getting the error that None type object has no attribute x. When I run the following code by removing FLAGS it works fine. But I want to assign these values to the FLAGS because in my actual code I want to assign different values to the FLAGS. How can I fix this problem? FLAGS = None c1 =[1.5, 2.0, 2.5] for i in range(len(c1)): FLAGS.x = c1[i] print(FLAGS.x) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--x', type=float, default=2.0) FLAGS = parser.parse_args()

http://stackoverflow.com/a/52525294
type: Answer
has comment: http://stackoverflow.com/comment/91990759
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52525194
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52525194
downvote count: 0
has body: If I understand correctly, you could just create a helper dataframe of the rows you want duplicated, then increment the Week number on that helper dataframe, then concatenate to your original: helper = pd.concat([df.loc[df.Course == 'Prison']]*2) helper['Week'] += helper.reset_index().index+1 df = pd.concat((df,helper)).sort_values('ID') &gt;&gt;&gt; df ID Name Week Course Hours 0 1 John A 1922 Bike Tech 5.5 1 2 John B 1922 Auto Tech 3.2 2 3 John C 1922 Prison 3.5 2 3 John C 1923 Prison 3.5 2 3 John C 1924 Prison 3.5 3 4 John D 1922 Comp 6.5 4 5 John E 1922 Awareness 7.0 5 6 John F 1922 First Aid 7.2 6 7 John G 1922 BasketBall 2.5 7 8 John H 1922 Tech 5.4

http://stackoverflow.com/comment/91956228
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52507860
has text: @o11c, OK, so there's clearly a gap in my understanding. But I can see (maybe) what you mean, perhaps you need to have O(*n*) position access to keep O(1) deletion vs O(*n*) for lists.

http://stackoverflow.com/a/52514524
score: 0
accepted answer of: http://stackoverflow.com/q/52477809
type: AcceptedAnswer
has body: It turned out that a segment 'DTM+164:201702010000?+01:303' existed a second time further down in the file and that indeed that one is followed by a UTM segment. So the problem is with the protocol states themselves and the iterator was working correctly. So sorry that I bothered you with my wrong assumption. Thanks for wanting to help!
type: Answer
answers question: http://stackoverflow.com/q/52477809

http://stackoverflow.com/comment/126092070
type: AnswerComment
comment on: http://stackoverflow.com/a/52576723
type: Comment
has text: @LukeDavis great to hear that! You should also be able to use `Popen` as context manager. I've added example in my original answer.
score: 1

http://stackoverflow.com/q/52504263
answer count: 0
has body: I asked this question before and it is closed. Therefore I need to ask it again. I'm master student in computer engineering department and struggling with Labelpropagation and my problem is about Labelpropagation. I have below code and score is very low. I didn't understand where the problem is. I tried to use LabelPropagation with TfIdfVectorizer. But there is a problem about that code. The problem is low accuracy. Result is about %28 and it is very low. We have only four categories. I had been hoping the result would have high accuracy. Am I right? Can anybody help me? import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.semi_supervised import LabelPropagation ratiolabeled = 0.5 categories = [ 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space' ] data_train = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, remove=('headers', 'footers', 'quotes'), categories=categories) data_test = fetch_20newsgroups(subset='test', shuffle=True, random_state=42, remove=('headers', 'footers', 'quotes'), categories=categories) vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.8, stop_words='english') y_train, y_test = data_train.target, data_test.target X_train = vectorizer.fit_transform(data_train.data) X_test = vectorizer.transform(data_test.data) labeled_indices, unlabeled_indices = train_test_split(np.arange(len(y_train)), test_size=1-ratiolabeled, random_state=43, stratify = y_train) y_train[unlabeled_indices]=-1 lp_model = LabelPropagation(kernel='knn', n_neighbors=21, n_jobs=-1, max_iter=20) lp_model.fit(X_train.toarray(),y_train) print("Accuracy = ", lp_model.score(X_train.toarray(),y_train))
type: Question
score: 0
tagged with: tfidfvectorizer
has comment: http://stackoverflow.com/comment/91952706
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/92073934
has title: LabelPropagation with TfidfVectorizer low accuracy
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/92020143
score: 0
comment on: http://stackoverflow.com/q/52539542
type: QuestionComment
type: Comment
has text: What are you trying to accomplish with this loop? `for i in rest: dev.append(rest[i])` Are you trying append every item in `rest` to the end of `dev`? `rest` contains the results of your `resto` calculations which when `valor` is a float will be floats. `some_float % 2` is a float.

http://stackoverflow.com/comment/92106579
type: QuestionComment
score: 0
has text: why store empty documents ? this raised a lot `_id` error. Create an clean-up script ! You can't fix an ON-CREATE error on ON-USE step !
comment on: http://stackoverflow.com/q/52585431
type: Comment

http://stackoverflow.com/comment/91935737
comment on: http://stackoverflow.com/a/52496083
type: AnswerComment
has text: Yup Might be.. anywayz thank you so much for your time and help!
score: 1
type: Comment

http://stackoverflow.com/a/52572097
type: Answer
has body: Question: I need to verify an xml signature contained in the answer to a POST request. Do it, like the example in the Documentation SignXML: XML Signature in Python: SignXML uses the ElementTree API (also supported by lxml) to work with XML data. from signxml import XMLSigner, XMLVerifier from xml.etree import ElementTree cert = open("example.pem").read() key = open("example.key").read() xml = ElementTree.parse(file_name) #(data_to_sign) signed_xml = XMLSigner().sign(xml, key=key, cert=cert) result = XMLVerifier().verify(signed_xml) XMLVerifier().verify(...) Verify the XML signature supplied in the data and return the XML node signed by the signature, or raise an exception if the signature is not valid. class signxml.VerifyResult The results of a verification return the signed data, the signed xml and the signature xml Note: Necessarily read about See what is signed and Establish trust! Relevant: Python elementtree find function reads Signature as empty (None)
score: 0
answers question: http://stackoverflow.com/q/52571341

http://stackoverflow.com/q/52484161
has title: environment variables in jupyter notebook? (osx)
has comment: http://stackoverflow.com/comment/92884421
has body: i'm trying to put together a technical notebook for a python project that involves some YouTube scraping, so i want to set the developer key as a behind-the-scenes environment variable. i know how to do this with virtual environments for terminal scripts, but it's not working in jupyter notebook. i have an 'env_vars.sh' file in anaconda3/etc/conda/activate.d that reads as follows: #!/bin/sh export DEVELOPER_KEY='keytextgoeshere' and when i load jupyter, it doesn't show up in print(os.environ.keys()) ... same goes when i try !source activate for environments i know have other variables. adding text to ~/.bash_profile also didn't work. (i'm loading the right kernel, i swear!)
type: UnansweredQuestion
score: 2
tagged with: environment-variables
downvote count: 0
answer count: 0
tagged with: macos
favorite count: 0
type: Question
tagged with: python
tagged with: jupyter-notebook
upvote count: 2

http://stackoverflow.com/q/52577824
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52599288
score: 2
tagged with: django-views
tagged with: django-authentication
type: Question
has body: I need to implement a view in Django that requests digest auth instead of basic auth. The authentication should not be linked to the default User class but instead to a custom model. I tried with django-digest but it is outdated and not usable with recent versions of Django (ModuleNotFoundError: No module named 'django.utils.importlib'). I need a very simple digest auth solution for my Django application.
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: Implementing HTTP Digest Auth for Django view

http://stackoverflow.com/q/52483296
score: 9
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52502679
has title: When do I have to use TensorFlow's FileWriter.flush() method?
accepted answer: http://stackoverflow.com/a/52502679
has body: I am currently working at a slightly bigger TensorFlow project and tried to visualize certain variables of my network as usual, i.e. doing this workflow declare what variables i want to track via tf.summary.scalar('loss', loss) collect them via summary_op = tf.summary.merge_all() declare my writer as writer = tf.summary.FileWriter('PATH') and adding the graph evaluate the summary operation during my training iterations via s = sess.run(summary_op) and finally adding it to my writer via writer.add_summary(s, epoch) Usually this does the job for me. But this time, I only got the graph showing up and when I inspected the event-file, I found it to be empty. By coincidence, I found somebody suggesting to use writer.flush() after adding my summary as a 6th step. This resolved my problem. As a consequence, the logical follow-up question is: when and how do I have to use FileWriter.flush() to make tensorflow work correctly?
favorite count: 0
upvote count: 9
tagged with: tensorboard
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: tensorflow

http://stackoverflow.com/q/52578932
has title: Telegram bot does nothing after one reply
tagged with: python-telegram-bot
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I am new to python and trying to create a conversation bot on telegram that asks the user for their gender and age. However, my bot does not do anything after getting the age of the user. My functions for the gender and the age: def gender(bot, update): # Get gender from user user = update.message.from_user logger.info("Gender of %s: %s", user.first_name, update.message.text) update.message.reply_text( "&lt;TEXT&gt;", reply_markup=ReplyKeyboardRemove()) def age(bot, update): # Get age from user user = update.message.from_user logger.info("Age of %s: %s", user.first_name, update.message.text) update.message.reply_text( "&lt;TEXT&gt;" ) return ConversationHandler.END def skip_age(bot, update): # /skip command user = update.message.from_user logger.info("User %s did not specify age", user.first_name) update.message.reply_text( "&lt;TEXT&gt;" ) return ConversationHandler.END The command handler and message handler in the main function: conv_handler = ConversationHandler( entry_points=[CommandHandler('chat', chat)], states={ GENDER: [RegexHandler('^(Boy|Girl|Other)$', gender)], AGE: [MessageHandler(Filters.text, age), CommandHandler('skip', skip_age)] }, fallbacks=[CommandHandler('cancel', cancel)] ) dispatcher.add_handler(conv_handler) The log of the bot(Renamed the token in the log): 2018-09-30 21:20:33,977 - __main__ = INFO - Gender of Jan: Boy 2018-09-30 21:29:00,826 - telegram.vendor.ptb_urllib3.urllib3.connectionpool = WARNING - Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(&lt;telegram.vendor.ptb_urllib3.urllib3.connectionpool.HTTPSConnectionPool object at 0x7fafec6b5ef0&gt;, 'Connect timed out. (connect timeout=5.0)')': /bot&lt;TOKEN&gt;/getUpdates Link to py file for the whole code: https://github.com/TryingOutSomething/testing/blob/master/testing.py
tagged with: telegram-bot
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52580566
accepted answer: http://stackoverflow.com/a/52580566
favorite count: 0

http://stackoverflow.com/a/52601010
has comment: http://stackoverflow.com/comment/92221408
has comment: http://stackoverflow.com/comment/92205405
has body: BeautifulSoup is a library for parsing and formatting, not interacting with web pages. For the latter, if that page requires JavaScript to work, you're stuck using a headless browser. If it doesn't, you have at least two options: Watch the Network tab in your browser's developer tools and see if you can recreate the request for the page you want using requests or urllib2 Use mechanize, which is built specifically to work with forms on sites that don't depend on JavaScript mechanize is a little more work if there's no CSRF token or similar mechanism (though, again, it'll fail if JavaScript is required) and a little less work if there is.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92188031
accepted answer of: http://stackoverflow.com/q/52588660
answers question: http://stackoverflow.com/q/52588660
score: 0
type: Answer

http://stackoverflow.com/comment/91949488
comment on: http://stackoverflow.com/q/52498014
score: 0
type: Comment
has text: I don't think this has to do with `python-docx` per se, or at least it doesn't have to. `python-docx` can give you a `str` object, which you can then modify as you please and "write back" to `python-docx`. Your problem reduces to how to do a fuzzy search/replace on a `str` object, which you should be able to find more about on search, like this top Google hit: https://github.com/seatgeek/fuzzywuzzy
type: QuestionComment

http://stackoverflow.com/comment/92115448
type: Comment
has text: Well, you would have a master urls.py file (in your project), which would include the urls.py files from each app. https://docs.djangoproject.com/en/2.1/topics/http/urls/#including-other-urlconfs
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52581498

http://stackoverflow.com/comment/92076817
type: QuestionComment
has text: Thank you for making the title more understandable :)
score: 0
comment on: http://stackoverflow.com/q/52569448
type: Comment

http://stackoverflow.com/comment/92596429
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52834976
has text: That's interesting - my understanding was that `depends_on_past` just meant that it would depend on previous tasks in the run, not previous schedules. Any idea how to kickstart this back into working again? I've tried manually failing/deleting previous runs
score: 0

http://stackoverflow.com/comment/91975825
comment on: http://stackoverflow.com/q/52518096
score: 0
type: QuestionComment
type: Comment
has text: `len({example1,example2,example3,example4}) == 1`?

http://stackoverflow.com/comment/91852135
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52444996
type: Comment
has text: CPU consumption as in? You want number of CPU cycles? cProfile displays you amount of time spent per call per statement.

http://stackoverflow.com/comment/91942083
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52500778
has text: Please resend with correct indentation and send the traceback.

http://stackoverflow.com/a/52541331
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52539614
answers question: http://stackoverflow.com/q/52539614
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Rather than looping and testing if it's the right time over and over again, it's better to calculate the amount of time needed to wait, and sleep until then so the processor can go off and do other things. To do this we still use the datetime module and just a bit of simple math. from datetime import datetime as dt from time import sleep #Calculating sleep interval t = dt.now() #seconds in the hour sec = t.second + t.minute*60 #seconds since the last 5 min interval sec = sec % 300 #until the next 5 min interval sec = 300 - sec #30 sec before that sec = sec - 30 #if negative we're within 30 sec of 5 minute interval so goto next one if sec &lt; 0: sec = sec + 300 sleep(sec) while True: #loop forever #with a little re-arranging and boolean math, this can all be condensed to: t = dt.now() s = (t.second + 60*t.minute) % 300 sleep(270 - s + 300 * (s &gt;= 270)) #yourFunction() For very simple cases this should work. If at any point your program crashes, or if the computer re-boots, or a myriad of other reasons, It would be better to use something built in to the OS which will re-start the program automatically, and can handle other conditions such as setting sleep timers, or only executing if a particular user is logged in. On Windows this is task scheduler, on Linux this is typically cron, and OSX is launchd (at least according to developer.apple.com)

http://stackoverflow.com/a/52459884
has body: You made a simple mistake. In substitui, the line return x should not be in the for-loop. You should unindent the line: def substitui(A): n = len(A) x = n*[0] for i in range(n-1, -1, -1): s = sum([A[i][j]*x[j] for j in range(i+1,n)]) x[i] = (A[i][n] - s)/A[i][i] return x # like this
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52459357
answers question: http://stackoverflow.com/q/52459357
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/52432446
has body: It's impossible to perform the check without looping, but you could indeed use all to do this. use List::Util qw( all ); my $ok = all { all { $_-&gt;{err_msg} } @{ $_-&gt;{row} } } @$VAR1; or use List::Util qw( all ); my $ok = all { $_-&gt;{err_msg} } map { @{ $_-&gt;{row} } } @$VAR1; The first version is more efficient because it only looks at a group if all the previous groups check out ok, whereas the second version unconditionally does work for every group. This difference is unlikely to matter, though.
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/91808642
has comment: http://stackoverflow.com/comment/91810968
upvote count: 8
has comment: http://stackoverflow.com/comment/91812969
has comment: http://stackoverflow.com/comment/91816105
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52432130
has comment: http://stackoverflow.com/comment/91813791
type: Answer
answers question: http://stackoverflow.com/q/52432130

http://stackoverflow.com/comment/91901098
comment on: http://stackoverflow.com/q/52480040
score: 0
type: Comment
type: QuestionComment
has text: I'm not sure I understand the problem. How is "Python outputs strings with double quotes when you print them" related to "Postgres does not accept double quotes"? The way Python prepares data for stdout should have no bearing on data Postgres recieves, because Python doesn't send data to Postgres via stdout unless you're doing something very strange. Can you share the code where you actually run the statement?

http://stackoverflow.com/comment/91998868
type: QuestionComment
comment on: http://stackoverflow.com/q/52529785
score: 0
type: Comment
has text: Another one is to broke the y axis, [see](https://matplotlib.org/examples/pylab_examples/broken_axis.html)

http://stackoverflow.com/a/52523283
answers question: http://stackoverflow.com/q/52523244
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/91994579
score: 6
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52523244
has body: Use request.query_params From the doc request.query_params is a more correctly named synonym for request.GET. For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests example: class TagsAPIView(APIView): def get(self, request): search = request.query_params.get('search') if search: data = get_paginated_data( data=TagSerializer( Tag.objects.filter(name__contains=search).annotate(posts_count=Count('posts')).order_by( '-posts_count').exclude(posts__isnull=True), many=True).data, page=request.query_params.get('page'), limit=request.query_params.get('limit'), url=F"/social/tags/?search={search}" ) else: data = get_paginated_data( data=TagSerializer( Tag.objects.all().annotate(posts_count=Count('posts')).order_by('-posts_count').exclude( posts__isnull=True), many=True).data, page=request.query_params.get('page'), limit=request.query_params.get('limit'), url=F"/social/tags/?" ) return JsonResponse(data)

http://stackoverflow.com/a/52517579
downvote count: 0
has comment: http://stackoverflow.com/comment/92541127
has comment: http://stackoverflow.com/comment/92614206
score: 4
has comment: http://stackoverflow.com/comment/92590147
has body: Edit: what are the units of the time measurements? I believe that you compared them as they were all in the same unit. Probably the dtw.distance is, for example, in microseconds, while the other answers are in milliseconds, and you thought that dtw.distance performed slower, when it is actually the opposite. There are different methodologies to measure the distance between two points. It could be based on standard deviation or just euclidian distance. Here is a list of many of those distance. Some of them might be more computational intensive than others, and also have different meanings. Fast dtw, for example, uses as a third input the type of distance that you want, as described on their github distance3, path3 = fastdtw(s1, s2, dist = euclidean) Another reason for the speed difference is the underlying code. Some of them are in pure python, while others are in C, which can be easily 100x faster. A way to speed up your dtaidistance is to set a maximum distance threshold. The algorithm will stop the calculation if it realizes that the total distance will be above a certain value: distance2 = dtw.distance_fast(array.array('d',s1),array.array('d',s2), max_dist = your_threshold) It is also important to note that some might be optimized for longer or shorter arrays. Looking at the example below and running it in my computer, I find different results: from cdtw import pydtw from dtaidistance import dtw from fastdtw import fastdtw from scipy.spatial.distance import euclidean s1=np.array([1,2,3,4],dtype=np.double) s2=np.array([4,3,2,1],dtype=np.double) %timeit dtw.distance_fast(s1, s2) 4.1 µs ± 28.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit d2 = pydtw.dtw(s1,s2,pydtw.Settings(step = 'p0sym', window = 'palival', param = 2.0, norm = False, compute_path = True)).get_dist() 45.6 µs ± 3.39 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit d3,_=fastdtw(s1, s2, dist=euclidean) 901 µs ± 9.95 µs per loop (mean ± std. dev. of 7 runs, 1000 …
has comment: http://stackoverflow.com/comment/92757525
has comment: http://stackoverflow.com/comment/92676992
has comment: http://stackoverflow.com/comment/92590407
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52479046

http://stackoverflow.com/q/52459844
downvote count: 0
possible better answer: http://stackoverflow.com/a/52460422
favorite count: 0
tagged with: postgresql
tagged with: python
type: AnsweredQuestion
has body: I don't really know how to properly state this question in the title. Suppose I have a table Word like the following: | id | text | | --- | --- | | 0 | Hello | | 1 | Adam | | 2 | Hello | | 3 | Max | | 4 | foo | | 5 | bar | Is it possible to query this table based on text and receive the objects whose primary key (id) is exactly one off? So, if I do Word.objects.filter(text='Hello') I get a QuerySet containing the rows | id | text | | --- | --- | | 0 | Hello | | 2 | Hello | but I want the rows | id | text | | --- | --- | | 1 | Adam | | 3 | Max | I guess I could do word_ids = Word.objects.filter(text='Hello').values_list('id', flat=True) word_ids = [w_id + 1 for w_id in word_ids] # or use a numpy array for this Word.objects.filter(id__in=word_ids) but that doesn't seem overly efficient. Is there a straight SQL way to do this in one call? Preferably directly using Django's QuerySets? EDIT: The idea is that in fact I want to filter those words that are in the second QuerySet. Something like: Word.objects.filter(text__of__previous__word='Hello', text='Max')
has title: Filter SQL elements with adjacent ID
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/52460422
type: Question
has answer: http://stackoverflow.com/a/52459902
accepted answer: http://stackoverflow.com/a/52459902
score: 1
tagged with: django-models
answer count: 2
tagged with: sql

http://stackoverflow.com/a/52561866
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52560895
accepted answer of: http://stackoverflow.com/q/52560895
type: AcceptedAnswer
has body: Imports: from bs4 import BeautifulSoup as soup import requests as r import pandas as pd import re Get your page: url = 'http://www.crb.state.ri.us/verify_CRB.php?page=0&letter=' data = r.get(url) page_data = soup(data.text, 'html.parser') Choose your link: links = [link.text for link in page_data.table.tr.find_all('a') if re.search('licensedetail.php', str(link))] links -> 32922 # or links = [link for link in page_data.table.tr.find_all('a') if re.search('licensedetail.php', str(link))] links -> 32922 # or links = [link['href'] for link in page_data.table.tr.find_all('a') if re.search('licensedetail.php', str(link))] links -> licensedetail.php?link=32922&type=Resid # or links = [r'www.crb.state.ri.us/' + link['href'] for link in page_data.table.tr.find_all('a') if re.search('licensedetail.php', str(link))] links -> www.crb.state.ri.us/licensedetail.php?link=32922&type=Resid Finish: df = pd.DataFrame(links, columns=['LicenseURL']) df.to_csv('RI_License_urls.csv', index=False)
score: 1
type: Answer

http://stackoverflow.com/comment/92044554
type: QuestionComment
score: 3
type: Comment
comment on: http://stackoverflow.com/q/52552848
has text: `charge.get('metadata', {}).get('distinct_id', None)` or try-except

http://stackoverflow.com/q/52443804
favorite count: 0
tagged with: tensorflow-datasets
tagged with: tensor
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2
tagged with: tensorflow
type: Question
tagged with: tensorflow-serving
has body: I am trying to infer from a frozen graph(generated using freeze_graph.py) of tensorflow wideanddeep model. I use Dataset API to parse the test.csv file. Since feed dict only accepts numpy arrays and the contents of Dataset are tensors, I get batch next_element=iterator.get_next() and batch=sess.run(next_element) to get the numpy values and then feed into the placeholders using a feed dict. But this doesn't gives me good throughput when running on large datasets, since it is not efficient way to convert the tensors into numpy arrays and then feed into the placeholders. Is there an efficient way of doing this. def input_fn(data_file, num_epochs, shuffle, batch_size): """Generate an input function for the Estimator.""" assert tf.gfile.Exists(data_file), ( '%s not found. Please make sure you have run census_dataset.py and ' 'set the --data_dir argument to the correct path.' % data_file) def parse_csv(value): tf.logging.info('Parsing {}'.format(data_file)) cont_defaults = [ [0.0] for i in range(1,14) ] cate_defaults = [ [" "] for i in range(1,27) ] label_defaults = [ [0] ] column_headers = TRAIN_DATA_COLUMNS record_defaults = label_defaults + cont_defaults + cate_defaults columns = tf.decode_csv(value, record_defaults=record_defaults) all_columns = dict(zip(column_headers, columns)) labels = all_columns.pop(LABEL_COLUMN[0]) features = all_columns return features, labels # Extract lines from input files using the Dataset API. dataset = tf.data.TextLineDataset(data_file) if shuffle: dataset = dataset.shuffle(buffer_size=2000) dataset = dataset.map(parse_csv, num_parallel_calls=8) # We call repeat after shuffling, rather than before, to prevent separate # epochs from blending together. dataset = dataset.repeat(num_epochs) dataset = dataset.batch(batch_size) dataset = dataset.prefetch(56) return dataset with tf.Session(graph=graph) as sess: res_dataset = input_fn(predictioninputfile,1,False,batch_size) iterator = res_dataset.make_one_shot_iterator() next_element = iterator.g…
downvote count: 0
has title: infering from a frozen model in tensorflow using dataset API

http://stackoverflow.com/comment/91954517
score: 0
type: Comment
has text: Yea I understood that the problem is from the Softmax activation that I have used. But what would you perhaps recommend me to do as a solution to have outputs. Thanks.
comment on: http://stackoverflow.com/a/52477162
type: AnswerComment

http://stackoverflow.com/a/52533050
score: 0
type: AcceptedAnswer
has body: You mainly need to group these various return percentage classes. Assuming you have all this going in a dataframe, you can create a new column say Return_category and give 4 classes for your return levels. Then you need to count how much each of these classes has Then you can plot the pie chart.. df['Return_Category'] = np.where(df['Pct'] &lt;= -0.2, 'Very Negative', np.where(df['Pct'] &lt;=0, 'Marginally Negative', np.where(df['Pct'] &lt;= 0.2, 'Marginally Positive', 'Very Positive'))) counts = df['Return_Category'].value_counts() import matplotlib.pyplot as plt # Data to plot labels = 'Very Negative', 'Marginally Negative', 'Marginally Positive', 'Very Positive' sizes = counts colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] explode = (0.1, 0, 0, 0) # explode 1st slice # Plot plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140) plt.axis('equal') plt.show()
type: Answer
accepted answer of: http://stackoverflow.com/q/52528864
answers question: http://stackoverflow.com/q/52528864

http://stackoverflow.com/comment/92093252
type: QuestionComment
score: 0
has text: I am not sure it fully fixes my issue for a few reasons. I don't think it is exactly because the file is too large that I am having this problem because when I load different month's of comments, vastly different numbers of rows will load. For example, in 2014-07, 2100 rows load while in 2014-05 84000 rows load. Also, in his tutorial, sentdex does not use anything but JSON, so why would it work on his computer but not mine? Thank you for this tip though.
comment on: http://stackoverflow.com/q/52574413
type: Comment

http://stackoverflow.com/comment/92100558
has text: I still don't understand what the code is doing, but to eliminate that error you just need to put `global max` at the start of the function
comment on: http://stackoverflow.com/q/52582637
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/64170313
downvote count: 0
type: Answer
has body: In your case, import openpyxl import io # The bytes object (Something like b'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00...) file = part.get_payload(decode=True) xlsx = io.BytesIO(file) wb = openpyxl.load_workbook(xlsx) ws = wb['Sheet1'] for cells in ws.iter_rows(): print([cell.value for cell in cells])
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52514442

http://stackoverflow.com/q/52507938
tagged with: google-bigquery
has answer: http://stackoverflow.com/a/52508790
answer count: 1
has title: Big Query Dataflow Load to NULL partition
accepted answer: http://stackoverflow.com/a/52508790
tagged with: apache-beam
tagged with: python
type: AnsweredQuestion
score: 0
has body: Using the apache beam Python SDK, I've set up a dataflow that writes to the individual partitions in a date partitioned table on Big Query. According to this documentation every date partitioned table has special NULL and UNPARTITIONED partitions. According to those docs I can write to the UNPARTITIONED partition by just setting my date far in the past or future, but how can I write to the NULL partition? I'm trying to load data to a partition based off values in the data and sometimes the field is null. I'd rather write to the NULL partition than make up a date to use for nulls. For reference, I write to date partitions doing something like this: beam.io.Write(beam.io.BigQuerySink(table_id+'$20180925', project=project_id, dataset=dataset_id, schema=schema)) What do I need to replace $20180925 with to write to NULL?
type: Question
tagged with: google-cloud-dataflow

http://stackoverflow.com/comment/92046302
comment on: http://stackoverflow.com/a/52547174
type: AnswerComment
type: Comment
has text: There were NaNs in category_id column. I cleaned those rows. Now it's working.
score: 0

http://stackoverflow.com/comment/92069327
has text: https://github.com/ipython/ipython/issues/11337 is the issue that I encountered with v7. I could only create one line function definitions.
type: Comment
comment on: http://stackoverflow.com/a/52554137
score: 0
type: AnswerComment

http://stackoverflow.com/q/52502816
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52503922
score: 3
tagged with: anaconda
upvote count: 3
has body: Dears, I am using windows 10 and I am familiar with testing my python code in Spyder. however, when I am trying to write ïmport pyspark" command, Spyder showing "No module named 'pyspark'" Pyspark is installed in my PC and also I can do import pyspark in command prompt without any error. I found many blogs explaining how to do this in Ubuntu but I did not find how to solve it in windows.
type: Question
has comment: http://stackoverflow.com/comment/91947266
has comment: http://stackoverflow.com/comment/91947097
has comment: http://stackoverflow.com/comment/91946817
tagged with: pyspark
has comment: http://stackoverflow.com/comment/91946256
has title: Running pyspark in (Anaconda - Spyder) in windows OS
answer count: 2
tagged with: apache-spark
has answer: http://stackoverflow.com/a/57231144
has comment: http://stackoverflow.com/comment/91946377
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91947585
has comment: http://stackoverflow.com/comment/91947613

http://stackoverflow.com/comment/91947862
has text: @pygo but the point is there is actually a toolbox in Pandas specifically for what the OP is looking for. I linked it in my answer.
type: Comment
comment on: http://stackoverflow.com/q/52503363
score: 0
type: QuestionComment

http://stackoverflow.com/q/52545827
type: UnansweredQuestion
has body: I want to package and deploy a simple project on AWS Lambda, using Zappa, but without the Zappa requirements overhead. Given this simple scenario: lambda_handler.py def handle(event, context): print('Hello World') I have a deploy.sh script that does that: #!/usr/bin/env bash source venv/bin/activate zappa package -o lambda.zip aws lambda update-function-code --function-name lambda-example --zip-file fileb://./lambda.zip This works, BUT the final lambda.zip is way bigger then it needs to be: I know that for this specific case the Zappa is not needed, but in the real project I'm using some libraries that requires https://github.com/Miserlou/lambda-packages, and using Zappa is the simplest way to install them. How do I generate the python lambda package without this overhead?
tagged with: python
tagged with: zappa
downvote count: 0
has comment: http://stackoverflow.com/comment/92055910
upvote count: 8
type: Question
has title: Python AWS Lambda deploy - Zappa package without Zappa requirements
has answer: http://stackoverflow.com/a/56645905
has comment: http://stackoverflow.com/comment/92034758
answer count: 1
score: 8
tagged with: aws-lambda
favorite count: 0

http://stackoverflow.com/q/52489201
tagged with: while-loop
tagged with: python
has comment: http://stackoverflow.com/comment/91919498
has answer: http://stackoverflow.com/a/52489218
has comment: http://stackoverflow.com/comment/91919495
downvote count: 0
has answer: http://stackoverflow.com/a/52489278
has comment: http://stackoverflow.com/comment/91919558
type: UnansweredQuestion
has body: I am currently stuck on something I am trying to break out of a while loop that is like this while True if blah blah function() if blah blah: #break while loop I tried a lot of methods but I can't seem to get it working, can anyone teach me? EDIT: I fixed the example I typed above.
has comment: http://stackoverflow.com/comment/91919496
tagged with: loops
type: Question
has title: Break out of while loop within an if statement in an function
score: 1
answer count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/42318622
has comment: http://stackoverflow.com/comment/91919516
favorite count: 0

http://stackoverflow.com/comment/92423684
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52588653
has text: actually `numexpr` is only used to calculate `(10 < z) & (z < 50)`, `y[,,,].mean()` is done by pandas and this part seems to be responsible for the lion's share of the running time. Have no idea, why evaluating via `eval` is so much slower.
type: Comment

http://stackoverflow.com/comment/91856163
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52456905
has text: Which column do you want to sort? You can only sort 1 column at a time.

http://stackoverflow.com/comment/91944741
comment on: http://stackoverflow.com/q/52502061
type: Comment
score: 0
has text: For last example, `echo $?` succeeds, so on the next line `$?` is 0.
type: QuestionComment

http://stackoverflow.com/a/52483416
score: 0
has body: This is the case because you are only changing the temporary variable a. list = [1,2,3] for i in list: i+=1 list will still be [1,2,3] you have to edit the string based on its index in the list
type: Answer
answers question: http://stackoverflow.com/q/52483266

http://stackoverflow.com/comment/92072255
type: Comment
has text: and can you post the actual error message?
comment on: http://stackoverflow.com/q/52567368
score: 0
type: QuestionComment

http://stackoverflow.com/a/52472615
has body: With just for loop: from collections import Counter p = Counter({'a': 2, 'p': 1}) plist = [] for tup in p.items(): for n in range(tup[1]): plist.append(tup[0]) print(plist) output: ['a', 'a', 'p'] &gt;&gt;&gt;
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52459624
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/52460111
has answer: http://stackoverflow.com/a/52460202
type: AnsweredQuestion
has title: Why is SIGALARM killing the Python program on Linux?
type: Question
accepted answer: http://stackoverflow.com/a/52460202
score: 0
tagged with: linux
answer count: 1
tagged with: python
tagged with: alarm
has body: import signal import time import multiprocessing as mp def launch(): signal.alarm(5) while True: time.sleep(1) print "Alive" p = mp.Process(target=launch) p.start() p.join() This programs prints Alive four times on stdout and then dies. While I am not handling the SIGALARM signal explicitly inside the program, I just expect the alarm to get ignored. However, on Linux, the script dies after the alarm is triggered. I have not been able to find any documentation for Linux which states that it should be the default behavior for the alarm signal. Any idea what is causing this behavior?

http://stackoverflow.com/a/59227895
type: Answer
answers question: http://stackoverflow.com/q/52503203
score: 3
downvote count: 0
upvote count: 3
has body: An alternative way would be simply to set inverted limits on the x-axis, just like this: ax.set_xlim(14,0)

http://stackoverflow.com/comment/92085166
type: Comment
score: 1
has text: Welcome to SO. Please take the time to read [mcve], [ask] and the other links found on that page.
comment on: http://stackoverflow.com/q/52574557
type: QuestionComment

http://stackoverflow.com/comment/92045480
score: 0
type: QuestionComment
type: Comment
has text: please see my edit above
comment on: http://stackoverflow.com/q/52553208

http://stackoverflow.com/comment/91882183
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52469587
has text: R passes most arguments by value. (There are a few exceptions, but arrays aren't one of them. Mutable objects in R are typically built on environments, which are an exception to the pass by value rule.)
type: AnswerComment

http://stackoverflow.com/comment/91920113
has text: @EricKlaus Ho about mine?
comment on: http://stackoverflow.com/q/52489440
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/92019281
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52528889
has text: The import error. At the very top of my post
score: 0

http://stackoverflow.com/comment/91972123
type: Comment
comment on: http://stackoverflow.com/q/52506729
has text: @BryanOakley OP has provided image which clearly shows that the file name is correct and it exists.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92378396
type: Comment
comment on: http://stackoverflow.com/a/52724037
type: AnswerComment
score: 0
has text: i don't understand how you mean it. Use for where? if i'am to `yield` the pdata and send_from_directory what must the return statemnt be?

http://stackoverflow.com/comment/92083867
score: 0
type: AnswerComment
type: Comment
has text: Write your own replacements to those functions, they shouldn't be too hard to implement.
comment on: http://stackoverflow.com/a/52573699

http://stackoverflow.com/comment/91921615
type: Comment
has text: Hi I got it. I just convert it to int.
type: AnswerComment
comment on: http://stackoverflow.com/a/52479037
score: 0

http://stackoverflow.com/q/52520844
tagged with: python
has title: Multiple users authentication with one account in Python Django?
type: AnsweredQuestion
type: Question
has body: I want to make an app where ie 5 users can use one account, these users should have different permissions within this account, and one of them should have Admin permissions (create users connected to account, delete users). Which way should I move to?
score: 0
has answer: http://stackoverflow.com/a/52521199
answer count: 1
tagged with: account
accepted answer: http://stackoverflow.com/a/52521199
tagged with: django

http://stackoverflow.com/comment/91948714
score: 0
has text: I have not set the PYTHONPATH. I was hoping to avoid altering any environment settings directly to avoid issues when I transfer the file to other computers.
comment on: http://stackoverflow.com/q/52502551
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52553798
favorite count: 0
tagged with: python-3.x
has body: Has anyone succesfully implemented flask-saml using Windows as dev environment, Python 3.6 and Flask 1.0.2? I was given the link to the SAML METADATA XML file by our organisation and had it configured on my flask app. app.config.update({ 'SECRET_KEY': 'changethiskeylaterthisisoursecretkey', 'SAML_METADATA_URL': 'https://&lt;url&gt;/FederationMetadata.xml', }) flask_saml.FlaskSAML(app) According to the documentation this extension will setup the following routes: /saml/logout/: Log out from the application. This is where users go if they click on a “Logout” button. /saml/sso/: Log in through SAML. /saml/acs/: After /saml/sso/ has sent you to your IdP it sends you back to this path. Also your IdP might provide direct login without needing the /saml/sso/ route. When I go to one of the routes http://localhost:5000/saml/sso/ I get the error below saml2.sigver.SigverError saml2.sigver.SigverError: Cannot find ['xmlsec.exe', 'xmlsec1.exe'] I then went to this site https://github.com/mehcode/python-xmlsec/releases/tag/1.3.5 to get xmlsec and install it. However, I'm still getting the same issue. Here is a screenshot of how I installed xmlsec where does not seem to find the xmlsec.exe
has comment: http://stackoverflow.com/comment/92062964
tagged with: python
has comment: http://stackoverflow.com/comment/92112865
upvote count: 11
has title: Python flask saml throwing saml2.sigver.SigverError Error Message
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92089504
has comment: http://stackoverflow.com/comment/92090916
score: 11
has answer: http://stackoverflow.com/a/52668830
tagged with: saml
has comment: http://stackoverflow.com/comment/92057939
has comment: http://stackoverflow.com/comment/92063081
has answer: http://stackoverflow.com/a/63860598
type: Question
tagged with: xmlsec
answer count: 2
downvote count: 0
tagged with: flask

http://stackoverflow.com/q/52473040
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52476344
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/91887878
score: 1
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/91888349
downvote count: 1
type: Question
has body: I wanted to add the webcam image to my main GUI window and that image will send to the email id. If this is not Possible, I also want to save that image and that saved image will send to my email id and On the countdown to 3,2,1, smile it will click the image by webcam. Here, is my code: import sys from PyQt5 import QtCore from PyQt5 import QtWidgets, QtGui import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import cv2, time DURATION_INT = 5 class MyMainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.time_left_int = DURATION_INT self.widget_counter_int = 0 central_widget = QtWidgets.QWidget() self.setCentralWidget(central_widget) vbox = QtWidgets.QVBoxLayout() central_widget.setLayout(vbox) self.pages_qsw = QtWidgets.QStackedWidget() vbox.addWidget(self.pages_qsw) self.time_passed_qll = QtWidgets.QLabel() vbox.addWidget(self.time_passed_qll) self.pushButton = QtWidgets.QPushButton() self.pushButton.setText("Push to start") self.yesbutton = QtWidgets.QToolButton() self.yesbutton.setText("yes") self.Nobutton = QtWidgets.QToolButton() self.Nobutton.setText("No") self.imageframe = QtWidgets.QLabel() self.imageframe.setText("fghkfhh") vbox.addWidget(self.Nobutton) vbox.addWidget(self.yesbutton) vbox.addWidget(self.pushButton) vbox.addWidget(self.imageframe) self.pushButton.clicked.connect(self.timer_start) self.yesbutton.clicked.connect(self.capturing_image) self.update_gui() def gmail_alert(self): email_user = 'user email_id' email_send = 'receiver email_id' subject = 'Alert system' msg = MIMEMultipart() msg['From'] = email_user msg['To'] = email_send msg['Subject'] = subject msg.preamble = "test" body = 'Hi there, sending this email from Python!' msg.attach(MIMEText(body, 'plain')) filename = 'alert.png' attachment = open(filename, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.enc…
accepted answer: http://stackoverflow.com/a/52476344
has title: I wanted to add capturing image by using webcam to my PyQt gui window and webcam image will come on gui window
tagged with: pyqt
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91912997
upvote count: 2
tagged with: python

http://stackoverflow.com/a/52431827
has body: if float(x).is_integer(): # do stuff note, as the comments have said, x here is a string, so you're converting that string to a number first, then checking if it's an integer. you may also want to wrap this around a try block to catch strings that are not numbers, etc.
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/91807496
has comment: http://stackoverflow.com/comment/91807277
downvote count: 3
has comment: http://stackoverflow.com/comment/91807455
answers question: http://stackoverflow.com/q/52431785
has comment: http://stackoverflow.com/comment/91807412
upvote count: 0

rstudio
tags question: http://stackoverflow.com/q/52568135
tag name: rstudio
type: Tag

http://stackoverflow.com/q/52457014
accepted answer: http://stackoverflow.com/a/52457492
favorite count: 0
has answer: http://stackoverflow.com/a/52457044
has comment: http://stackoverflow.com/comment/91856324
tagged with: python
possible better answer: http://stackoverflow.com/a/52457044
type: AnsweredQuestion
score: 1
has title: Pandas group by with multiple columns and max value
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52457492
has comment: http://stackoverflow.com/comment/91857039
tagged with: dataframe
has body: I have some problems with group by with multiple columns and max value. A B C D E F G H x q e m k 2 1 y x q e n l 5 2 y x w e b j 7 3 y x w e v h 3 4 y This query is correct and returning what I want. SELECT A, B, C, D, E, MAX(F) FROM mytable group by A, B, C Results x q e n l 5 x w e b j 7 How it can be achieved in pandas? I try this: df.groupby(['A', 'B', 'C'], as_index=False)['F'].max() And this translates to this: SELECT A, B, C, MAX(F) FROM mytable group by A, B, C This also does not work df.groupby(['A', 'B', 'C'], as_index=False)['F','D','E'].max() How can I return also column D, E as it in sql query?
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/91856297
downvote count: 0

http://stackoverflow.com/comment/91869675
comment on: http://stackoverflow.com/a/52461755
score: 0
type: AnswerComment
type: Comment
has text: @TylerT the conventional name for the bot is `client` or `bot`, writing `self` isn’t exactly clear on what you’re referencing to. Plus, the OP tagged the rewrite version of discord, therefore your solution will not work.

http://stackoverflow.com/q/52533609
has title: Choosing best semantics for related variables in an untyped language like Python
type: Question
tagged with: naming-conventions
has body: Consider the following situation: you work with audio files and soon there are different contexts of what "an audio" actually is in same solution. This on one side is more obvious through typing, though while Python has classes and typing, but it is less explicit in the code like in Java. I think this occurs in any untyped language. My question is how to have less ambiguous variable names and whether there is something like an official and widely accepted guideline or even a standard like PEP/RFC for that or comparable. Examples for variables: A string type to designate the path/filename of the actual audio file A file handle for the above to do the I/O Then, in the package pydub, you deal with the type AudioSegment While in the package moviepy, you deal with the type AudioFileClip Using all the four together, requires in my eyes for a clever naming strategy, but maybe I just oversee something. Maybe this is a quite exocic example, but if you think of any other media types, this should provide a more broad view angle. Likewise, is a Document a handle, a path or an abstract object?
tagged with: typing
answer count: 1
tagged with: variables
type: UnansweredQuestion
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52533696

http://stackoverflow.com/comment/92041674
comment on: http://stackoverflow.com/q/52551158
score: 0
type: Comment
type: QuestionComment
has text: I get `Expected 'collections.Iterable', got 'None' instead` which makes sense to me. I have fixed the indentation and added a screenshot

http://stackoverflow.com/comment/91920490
comment on: http://stackoverflow.com/a/52489483
type: AnswerComment
score: 0
type: Comment
has text: I guess flower braces here are giving me error. I have to use openpyxl for some reason, and would there not be any other way to solve this issue ?Lmk if there is any other solution in openpyxl

http://stackoverflow.com/comment/91983933
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52522073
type: Comment
has text: i just read the ngram tokenizer. for the current use case the min length 3 would suffice. is there any specific/ generic way ? like in mongodb i used regex.

http://stackoverflow.com/q/52456060
has title: How to check if socket connection is working and buffering or is the request incorrect?
tagged with: python-3.x
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/91858578
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52459198
type: Question
has body: I have been trying to figure this out and can't seem to wrap my head around it. import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server = '192.168.1.7' port = 8000 buffer_size = 4096 request = '1|gkdgdfg49|sdfsdfsd*|sdsfsf*|'+server request = request.encode() s.connect((server,port)) s.send(request) x = s.recv(buffer_size) The documentation for the server side is: https://www.sharekhan.com/Upload/General/TradeTigerAPIForClient.pdf The log of api server shows: [I] "API Client Socket Connected with error Code=0"2018-09-22 16:07:23.555+05:30 [I] "Hurraay You have Connected."2018-09-22 16:07:23.555+05:30 [I] "Received Bytes Count = 49 Data Length = 1801944113 Thread State = Background, WaitSleepJoin , Queue Count = 0"2018-09-22 16:07:23.555+05:30 [I] "API Client Request Data Length 1801944113 bytes needs to read" 2018-09-22 16:08:21.984+05:30 [I] "Received Bytes Count = 49 Data Length = 1801944113 Thread State = Background, WaitSleepJoin , Queue Count = 0" 2018-09-22 16:08:21.984+05:30 [I] "API Client Request Data Length 1801944113 bytes needs to read"|Reserved = | Is the request correct? Is the data being transferred? If I rerun s.send(request) x = s.recv(buffer_size) Nothing happens. The interpreter is stuck at running the above two lines. I would appreciate any help. Very new to `sockets and the documentation is not very helpful.
has answer: http://stackoverflow.com/a/52459198
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91858471

http://stackoverflow.com/comment/92057674
type: QuestionComment
has text: Is this question solved?
score: 0
comment on: http://stackoverflow.com/q/52559302
type: Comment

http://stackoverflow.com/comment/91894449
score: 3
has text: It's not very clear what you're trying to do - can you [edit] into your post some example inputs and their corresponding outputs?
type: Comment
comment on: http://stackoverflow.com/q/52476527
type: QuestionComment

http://stackoverflow.com/comment/92080384
type: QuestionComment
has text: @sradha: the path should be `path('', views.home, name='home'),`, so an empty string as first element.
score: 1
comment on: http://stackoverflow.com/q/52571708
type: Comment

http://stackoverflow.com/q/52440213
has comment: http://stackoverflow.com/comment/91823104
has answer: http://stackoverflow.com/a/52440751
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/91823308
has comment: http://stackoverflow.com/comment/91823318
downvote count: 0
has answer: http://stackoverflow.com/a/52440837
accepted answer: http://stackoverflow.com/a/52440837
has title: Make List and Dictionaries dynamically in Python. I am trying to create the array in Python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91823209
linked to: http://stackoverflow.com/q/2468334
tagged with: python
possible better answer: http://stackoverflow.com/a/52440751
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91824546
upvote count: 2
has body: I am new in Python and getting the problem in creating the dynamically list and dictionaries. I want the result like: { 'page1': [{'email': [{'emailAddress':'abc@gmail.com'}],[{'emailAddress1':'abc@gmail.com1'}],... }],[{'url': [{'url':'abc.com','cordinates','10,10,100,45'}],[{'url':'abc.com','cordinates','10,10,100,45'}]... }] } { 'page1': [{'email': [{'emailAddress':'abc@gmail.com'}],[{'emailAddress1':'abc@gmail.com1'}],... }],[{'url': [{'url':'abc.com','cordinates','10,10,100,45'}],[{'url':'abc.com','cordinates','10,10,100,45'}]... }] } { 'page1': [{'email': [{'emailAddress':'abc@gmail.com'}],[{'emailAddress1':'abc@gmail.com1'}],... }],[{'url': [{'url':'abc.com','cordinates','10,10,100,45'}],[{'url':'abc.com','cordinates','10,10,100,45'}]... }] }..... I cannot give you the original data for review but I am going to create this type of the data using the code below: from pprint import pprint dict1 = {} dict2 = {} dict3 = {} newObj = {'name'} finalVar = [] finalVars = [] newVal = {} for i in range(10): temp = {'page'+str(i)} for k in range(10): newtemp = {'page'+str(i):{'email':[{ 'emailId':str(i), 'test':str(k) }]}} finalVar.append(newtemp) for i in range(10): temp = {'page'+str(i)} for k in range(10): newtemp = {'page'+str(i):{'email':[{ 'url':str(i), 'testing':str(k) }]}} finalVars.append(newtemp) pprint(finalVars) I am new in Python so, even I don't know that I am creating the valid list and array dictionary. So, please sorry if there is any thing wrong.
has comment: http://stackoverflow.com/comment/91823505
type: Question
has comment: http://stackoverflow.com/comment/91823605
has comment: http://stackoverflow.com/comment/91827571

http://stackoverflow.com/comment/91873634
comment on: http://stackoverflow.com/a/52465794
has text: Got it, Thanks!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91973605
has text: I'm not sure how you're expecting this to work. Those are URL patterns, not actual URLs, so will never be equal to the current URL.
score: 1
comment on: http://stackoverflow.com/q/52516918
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92115380
type: Comment
comment on: http://stackoverflow.com/q/52588535
type: QuestionComment
has text: The thing is I expected the same functionality in PyCharm and console, all other are hypotheses about potential use of the code.
score: 0

http://stackoverflow.com/comment/91918150
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52488395
has text: Oh you fast, I was somewhere else, vn
score: 0

http://stackoverflow.com/comment/91866508
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52462109
has text: @yoonghm `range(2, n)` does not create any lists.
type: Comment

http://stackoverflow.com/a/52493388
answers question: http://stackoverflow.com/q/52492579
has body: This is one approach. I am using a dictionary to separate the image from different domains then calculate the number of images required from each domain. Demo: import random inputData = ['1_A.png', '2_A.png', '3_A.png', '4_A.png', '5_A.png', '6_A.png', '7_A.png', '8_A.png', '9_A.png', '10_A.png', '1_B.png', '2_B.png', '3_B.png', '4_B.png', '5_B.png', '6_B.png', '7_B.png', '8_B.png', '9_B.png', '10_B.png', '1_C.png', '2_C.png', '3_C.png', '4_C.png', '5_C.png', '6_C.png', '7_C.png', '8_C.png', '9_C.png', '10_C.png'] d = {"A": [], "B":[], "C":[]} #for i in os.listdir("path"): for i in inputData: #Group images by domain. if "A" in i: d["A"].append(i) elif "B" in i: d["B"].append(i) else: d["C"].append(i) percentage = {"A": 30, "B": 30, "C": 60} res = [] for k, v in d.items(): res.extend([random.choice(v) for i in range(int((percentage[k] * len(v)) / 100.0))]) print(res) Output: ['7_A.png', '8_A.png', '9_A.png', '6_C.png', '8_C.png', '9_C.png', '7_C.png', '9_C.png', '7_C.png', '1_B.png', '6_B.png', '2_B.png']
score: 0
type: Answer

http://stackoverflow.com/comment/91981428
type: AnswerComment
type: Comment
has text: Thank you. You have solved my problem.
comment on: http://stackoverflow.com/a/52501740
score: 0

http://stackoverflow.com/a/52527862
has body: Do check out the following pages: Getting Started (The standard stuffs to kick off your script) https://selenium-python.readthedocs.io/getting-started.html Once you've init-ed your driver, you can locate the contents by the methods found here: https://selenium-python.readthedocs.io/navigating.html In your case, you probably need something like below; loop through the list and write the contents to file. td_list = driver.find_elements_by_tag_name('td')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52523688

http://stackoverflow.com/q/52517294
linked to: http://stackoverflow.com/q/17043860
possible better answer: http://stackoverflow.com/a/52517616
has comment: http://stackoverflow.com/comment/91974556
has answer: http://stackoverflow.com/a/52517605
has comment: http://stackoverflow.com/comment/91974116
has answer: http://stackoverflow.com/a/52517616
tagged with: pandas
favorite count: 0
score: -1
downvote count: 2
accepted answer: http://stackoverflow.com/a/52517605
tagged with: python
tagged with: dictionary
has title: Add two dictionaries into a json
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91974627
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
has comment: http://stackoverflow.com/comment/91974382
type: Question
has comment: http://stackoverflow.com/comment/91974700
answer count: 2
has comment: http://stackoverflow.com/comment/91974560
has body: I am trying to write two dictionaries into a JSON one after another in Python. I have made two dictionaries which look like --- dictionary_quant = {'dmin': [0.003163, 14.325], 'magNst': [0.0, 414.0], 'horizontalError': [0.12, 12.9], 'nst': [3.0, 96.0], 'depth': [-3.09, 581.37], 'latitude': [-43.3468, 67.1524], 'rms': [0.0, 1.49], 'depthError': [0.0, 32.0], 'magError': [0.0, 1.34], 'mag': [-0.57, 6.9], 'gap': [18.0, 342.0], 'longitude': [-179.8024, 179.3064]} dictionary_categorical = {'magType': ['ml', 'md', 'mb', 'mb_lg', 'mwr', 'Md', 'mwb', nan, 'mww'], 'net': ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismpkansas', 'hv', 'uu'], 'type': ['earthquake', 'explosion'], 'status': ['reviewed', 'automatic'], 'locationSource': ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismp', 'hv', 'uu', 'ott', 'guc'], 'magSource': ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismp', 'hv', 'uu', 'ott', 'guc']} I am trying to write a json which looks like -- data = [ { 'name' : 'dmin', 'type' : 'quant', 'minmax' : [0.003163, 14.325] }, { 'name' : 'magNSt', 'type' : 'quant', 'minmax' : [0.0, 414.0] }, {....}, {....}, { 'name' : 'magType', 'type' : 'categor', 'categories' : ['ml', 'md', 'mb', 'mb_lg', 'mwr', 'Md', 'mwb', nan, 'mww'] }, { 'name' : 'net', 'type' : 'categor', 'categories' : ['ci', 'nc', 'us', 'ak', 'mb', 'uw', 'nn', 'pr', 'se', 'nm', 'ismpkansas', 'hv', 'uu'] } ]

http://stackoverflow.com/q/52563711
upvote count: 1
possible better answer: http://stackoverflow.com/a/52563750
downvote count: 0
has title: Using Python3, need to insert a new string into a list and, if found, need to append suffix and increase counter by 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52563750
has comment: http://stackoverflow.com/comment/92065900
tagged with: python
has comment: http://stackoverflow.com/comment/92065928
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92065866
type: Question
accepted answer: http://stackoverflow.com/a/52564607
has body: I have a list of fruit names that I need to keep as unique string identifiers. Here's an example: fruit_names = ['banana_001','apple_001','banana_002'] There is also a function that acts on fruit_names and adds a new fruit to the list. If it finds the fruit on this list, it increments the ID after the underscore by 1. If it doesn't find the fruit at all, it starts the naming at 1: &gt;&gt;&gt;fruits.add(fruit_names,'apple') &gt;&gt;&gt;fruits.add(fruit_names,'orange') &gt;&gt;&gt;print(fruit_names) ['banana_001', 'apple_001', 'banana_002', 'apple_002', 'orange_001'] I have a hacky implementation I am not happy with for fruits.add() and was wondering if there's a super simple way of accomplishing the above that I may be missing.
answer count: 2
has answer: http://stackoverflow.com/a/52564607

http://stackoverflow.com/comment/92013960
comment on: http://stackoverflow.com/q/52537311
score: 0
has text: The error you get tells you you didn't set the name `doing_performance_analysis`. Have you tried defining that name to a boolean?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91822570
comment on: http://stackoverflow.com/q/52439639
type: QuestionComment
has text: i need only digit id, cause this id will be used for payments, for example replenish my account balance
score: 0
type: Comment

http://stackoverflow.com/comment/91849104
comment on: http://stackoverflow.com/q/52452950
has text: `"no file chosen"` is the default placeholder for file inputs. You need to click it to add a file (image in this case). There's nothing missing, your code is (should be) working
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52549032
has comment: http://stackoverflow.com/comment/92037218
answers question: http://stackoverflow.com/q/52548995
upvote count: 3
type: Answer
downvote count: 0
has body: I believe to need function max: dfs = [df1, df2, ..., dfn] df = max(dfs, key=len) Another solution, thanks @piRSquared: print (max(dfs, key=lambda d: d.size))
score: 3

http://stackoverflow.com/a/52558379
has comment: http://stackoverflow.com/comment/92056471
has body: re-import the notebook that sets up the redshift connectivity. Or find where it is set and copy that code. If you don't have privileges to modify the notebooks you are importing then I'd guess you don't have privileges to set roles on the cluster. If you use roles then you don't need aws keys.
score: 0
answers question: http://stackoverflow.com/q/52558185
type: Answer
has comment: http://stackoverflow.com/comment/92055390

http://stackoverflow.com/q/52563510
has comment: http://stackoverflow.com/comment/92067016
has body: input_String = str(input()) # Input is comma separated word cargo_status = str(input()) # String to look into input string list = input_String.split(",") i = 0 length = len(list) print(length) for x in list: if x == cargo_status: i=i+1 print(i) elif (not cargo_status in x) and (i==length): print(0) Input: In:Packed,InTransit,Packed,Shipped,Out-For-Delivery,Shipped,Delivered In:Packed Output: 1 3 Issue: Code is not printing 0 if the string is not found to compare the string otherwise I am getting desired output. Any help is much appreciated as I am very new in learning Python or a programming language.
answer count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52563528
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92070010
tagged with: python
score: 2
has title: How to find a specific string in a python list, if found print the positions else print 0
has answer: http://stackoverflow.com/a/52564450
has answer: http://stackoverflow.com/a/52565775
type: Question
has comment: http://stackoverflow.com/comment/92065532
has answer: http://stackoverflow.com/a/52563657
downvote count: 0
tagged with: string
favorite count: 0

http://stackoverflow.com/comment/91861363
comment on: http://stackoverflow.com/q/52459397
has text: It looks like you're only using the offset from the first group, so it just continues on calculating. You probably need to calculate for each group
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52468552
type: Question
answer count: 2
tagged with: optimization
has answer: http://stackoverflow.com/a/52487648
score: 0
has title: Django debug toolbar says I have a query that is duplicate 1367 times
tagged with: django-queryset
has answer: http://stackoverflow.com/a/52469305
type: UnansweredQuestion
has body: I have a short view but with a complex query (the model that uses comes from a database MySQL view). The problem is that when this view executes, template loads too slow. The Django debug tool shows that a query is duplicated 1367 times, but the duplicated query has nothing to do with the complex database view query. Is there any way to avoid duplicate query? Is this delay because of the second query? Below, is my template and view code. Sorry for not showing them too good, but it is my first post in StackOverflow. def simbouloi_list(request, eklid): paramorder = request.GET.get('orderoption', '') try: paramorder = int(paramorder) except: paramorder = 6 # default ταξινόμηση selected_ekloges = Eklogestbl.objects.filter(eklid=eklid) # επιλογή όλων των εκλ. αναμετρήσεων με visible=1 και κάνω φθίνουσα ταξινόμηση αν δεν δοθεί παράμετρος all_ekloges = Eklogestbl.objects.filter(visible=1).order_by('-eklid') #all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('surname', 'firstname', 'fathername') if paramorder==1 or paramorder==6: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('surname', 'firstname','fathername') elif paramorder == 2: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('sindiasmos', 'surname', 'firstname','fathername') elif paramorder == 3: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('sindiasmos', 'toposeklogis', 'surname', 'firstname','fathername') elif paramorder == 4: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by( 'toposeklogis','sindiasmos','surname', 'firstname','fathername') else: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('toposeklogis', 'surname','firstname', 'fathername') context = {'all_ekloges': all_ekloges, 'selected_ekloges': selected_ekloges, 'all_simbouloi': all_simbouloi, } return render(request, 'Elections/simbouloi_list.html' , context) Template: {% extends 'Elections/base.html' %} {% load staticfiles %} {% block content %} {% i…
tagged with: django
tagged with: python
tagged with: duplicates

http://stackoverflow.com/q/52537888
tagged with: python
type: AnsweredQuestion
tagged with: numpy-slicing
has answer: http://stackoverflow.com/a/52538369
downvote count: 1
has body: So I am searching for a simple solution for changing the content of a dataframe based on both a condition and a time range. See code below: import numpy as np import pandas as pd data = pd.DataFrame(data=np.random.rand(15,2), index = pd.DatetimeIndex(start = "2018-01-01 00:00", end = "2018-01-01 00:14", freq="1min"), columns = ["A", "B"]) data.loc[data["A"].between(0.2,0.3), :].loc[:"2018-01-01 00:02", "A"] = 4 # /Users/ap/anaconda/lib/python3.5/site-packages/pandas/core/indexing.py:189: SettingWithCopyWarning: # A value is trying to be set on a copy of a slice from a DataFrame # See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy # self._setitem_with_indexer(indexer, value) # __main__:1: SettingWithCopyWarning: # A value is trying to be set on a copy of a slice from a DataFrame # See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy print(data) # A B # 2018-01-01 00:00:00 0.146793 0.198634 # 2018-01-01 00:01:00 0.284354 0.422438 # 2018-01-01 00:02:00 0.359768 0.199127 # 2018-01-01 00:03:00 0.306145 0.538669 # 2018-01-01 00:04:00 0.839377 0.299983 # 2018-01-01 00:05:00 0.236554 0.127450 # 2018-01-01 00:06:00 0.262167 0.304692 # 2018-01-01 00:07:00 0.341273 0.099983 # 2018-01-01 00:08:00 0.721702 0.763717 # 2018-01-01 00:09:00 0.196948 0.541878 # 2018-01-01 00:10:00 0.673248 0.421809 # 2018-01-01 00:11:00 0.892244 0.070801 # 2018-01-01 00:12:00 0.354958 0.184147 # 2018-01-01 00:13:00 0.062060 0.840900 # 2018-01-01 00:14:00 0.139046 0.742875 # ==&gt; Nothing happened as indicated by the warning # non-elegant way to solve the issue: x = data.loc[data["A"].between(0.2,0.3), :] x.loc[:"2018-01-01 00:02", "A"] = 4 data.loc[x.index,:] = x print(data) # A B # 2018-01-01 00:00:00 0.146793 0.198634 # 2018-01-01 00:01:00 4.000000 0.422438 # 2018-01-01 00:02:00 0.359768 0.199127 # 2018-01-01 00:03:00 0.306145 0.538669 # 2018-01-01 00:04:00 0.…
type: Question
tagged with: indexing
tagged with: numpy
score: 0
has title: What is an elegant way to slice a pandas dataframe by a condition AND a date range at the same time?
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/92321529
favorite count: 0
has comment: http://stackoverflow.com/comment/92140149
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52538369

neural-network
tags question: http://stackoverflow.com/q/52538143
tags question: http://stackoverflow.com/q/52584256
tags question: http://stackoverflow.com/q/52460539
tags question: http://stackoverflow.com/q/52432258
tags question: http://stackoverflow.com/q/52486088
tags question: http://stackoverflow.com/q/52542842
tags question: http://stackoverflow.com/q/52538365
tags question: http://stackoverflow.com/q/52451067
tags question: http://stackoverflow.com/q/52433127
tags question: http://stackoverflow.com/q/52459748
tags question: http://stackoverflow.com/q/52580521
type: Tag
tags question: http://stackoverflow.com/q/52474744
tags question: http://stackoverflow.com/q/52584158
tags question: http://stackoverflow.com/q/52537408
tags question: http://stackoverflow.com/q/52571752
tags question: http://stackoverflow.com/q/52566823
tags question: http://stackoverflow.com/q/52534717
tags question: http://stackoverflow.com/q/52452475
tags question: http://stackoverflow.com/q/52498544
tags question: http://stackoverflow.com/q/52445046
tags question: http://stackoverflow.com/q/52452622
tags question: http://stackoverflow.com/q/52444510
tags question: http://stackoverflow.com/q/52525362
tags question: http://stackoverflow.com/q/52537021
tag name: neural-network
tags question: http://stackoverflow.com/q/52556337
tags question: http://stackoverflow.com/q/52526028

http://stackoverflow.com/q/52458508
has comment: http://stackoverflow.com/comment/91860092
favorite count: 0
possible better answer: http://stackoverflow.com/a/52469317
tagged with: python
has answer: http://stackoverflow.com/a/52469317
has title: Why would Pytorch (CUDA) be running slow on GPU
has answer: http://stackoverflow.com/a/56849357
has comment: http://stackoverflow.com/comment/91859176
type: AnsweredQuestion
tagged with: pytorch
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/91859201
has comment: http://stackoverflow.com/comment/91869380
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/91859284
accepted answer: http://stackoverflow.com/a/56849357
has comment: http://stackoverflow.com/comment/91861251
answer count: 2
score: 5
has body: I have been playing around with Pytorch on Linux for some time now and recently decided to try get more scripts to run with my GPU on my Windows desktop. Since trying this I have noticed a massive performance difference between my GPU execution time and my CPU execution time, on the same scripts, such that my GPU is significantly slow than CPU. To illustrate this I just a tutorial program found here (https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#pytorch-tensors) import torch import datetime print(torch.__version__) dtype = torch.double #device = torch.device("cpu") device = torch.device("cuda:0") # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output data x = torch.randn(N, D_in, device=device, dtype=dtype) y = torch.randn(N, D_out, device=device, dtype=dtype) # Randomly initialize weights w1 = torch.randn(D_in, H, device=device, dtype=dtype) w2 = torch.randn(H, D_out, device=device, dtype=dtype) start = datetime.datetime.now() learning_rate = 1e-6 for t in range(5000): # Forward pass: compute predicted y h = x.mm(w1) h_relu = h.clamp(min=0) y_pred = h_relu.mm(w2) # Compute and print loss loss = (y_pred - y).pow(2).sum().item() #print(t, loss) # Backprop to compute gradients of w1 and w2 with respect to loss grad_y_pred = 2.0 * (y_pred - y) grad_w2 = h_relu.t().mm(grad_y_pred) grad_h_relu = grad_y_pred.mm(w2.t()) grad_h = grad_h_relu.clone() grad_h[h &lt; 0] = 0 grad_w1 = x.t().mm(grad_h) # Update weights using gradient descent w1 -= learning_rate * grad_w1 w2 -= learning_rate * grad_w2 end = datetime.datetime.now() print(end-start) I increased the number of Epoch's from 500 to 5000 as I have read that the first CUDA call is very slow due to initialisation. However the performance issue still exists. With device = torch.device("cpu") the final time printed out is normal around 3-4 seconds, well device = torch.device("cuda:0") executes i…
downvote count: 0

http://stackoverflow.com/q/52539338
linked to: http://stackoverflow.com/q/62855575
has comment: http://stackoverflow.com/comment/92018552
type: Question
accepted answer: http://stackoverflow.com/a/52556609
has comment: http://stackoverflow.com/comment/92018614
score: 4
has title: How to shuffle an array of numbers without two consecutive elements repeating?
upvote count: 4
tagged with: numpy
tagged with: random
answer count: 3
possible better answer: http://stackoverflow.com/a/52540553
linked to: http://stackoverflow.com/q/25285792
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/52540553
favorite count: 0
has comment: http://stackoverflow.com/comment/92027135
has answer: http://stackoverflow.com/a/74943431
linked to: http://stackoverflow.com/q/36455104
has answer: http://stackoverflow.com/a/52556609
has body: I'm currently trying to get an array of numbers like this one randomly shuffled: label_array = np.repeat(np.arange(6), 12) The only constrain is that no consecutive elements of the shuffle must be the same number. For that I'm currently using this code: # Check if there are any occurrences of two consecutive # elements being of the same category (same number) num_occurrences = np.sum(np.diff(label_array) == 0) # While there are any occurrences of this... while num_occurrences != 0: # ...shuffle the array... np.random.shuffle(label_array) # ...create a flag for occurrences... flag = np.hstack(([False], np.diff(label_array) == 0)) flag_array = label_array[flag] # ...and shuffle them. np.random.shuffle(flag_array) # Then re-assign them to the original array... label_array[flag] = flag_array # ...and check the number of occurrences again. num_occurrences = np.sum(np.diff(label_array) == 0) Although this works for an array of this size, I don't know if it would work for much bigger arrays. And even so, it may take a lot of time. So, is there a better way of doing this?
tagged with: python
has comment: http://stackoverflow.com/comment/92018518
type: AnsweredQuestion

http://stackoverflow.com/a/52522794
type: Answer
answers question: http://stackoverflow.com/q/52522646
accepted answer of: http://stackoverflow.com/q/52522646
score: 3
downvote count: 0
has body: Using reindex with method nearest df2.reset_index().set_index('depth_2').reindex(df1.depth_1,method = 'nearest')['index'].unique() Out[265]: array([14], dtype=int64)
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/a/52575796
answers question: http://stackoverflow.com/q/52575710
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/92087332
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Python's sort functions can take a key, you can use a lambda function to define the key you want to sort over. In this case, i'd suggest sorting the indices and then applying the order to both v and w. For example: v = [60, 100 , 120] w = [20, 50, 30] order = sorted(range(len(v)), key=lambda i: v[i] / w[i], reverse=True) v_new = [v[i] for i in order] w_new = [w[i] for i in order]
has comment: http://stackoverflow.com/comment/92087309
accepted answer of: http://stackoverflow.com/q/52575710
has comment: http://stackoverflow.com/comment/92087502

http://stackoverflow.com/q/52479544
has answer: http://stackoverflow.com/a/52479585
type: AnsweredQuestion
tagged with: machine-learning
upvote count: 1
has body: I have been following tutorial on linear regression with scikitlearn.The code works perfectly and now i wanna predict new output by giving a new input.I have used student score and Study hour data set. Here's the code: import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression data=pd.read_csv("/home/crpsm/Pycharm/DataSet/student_scores.csv") data.plot(x="Hours",y="Scores",style="o") plt.title("Score-Hour") plt.xlabel('Hours ') plt.ylabel('Percentage ') x=data.iloc[:,:-1] y=data.iloc[:,1] x_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.55,random_state=5) regression_model=LinearRegression() regression_model.fit(x_train,y_train) print(regression_model.coef_) print(regression_model.intercept_) regression_model.predict(X_test)
downvote count: 1
has comment: http://stackoverflow.com/comment/91900951
type: Question
has comment: http://stackoverflow.com/comment/91900257
tagged with: linear-regression
accepted answer: http://stackoverflow.com/a/52479585
has title: How to predict new output from a linearRegression model build using sklean?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91900164
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91900626
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91901022

http://stackoverflow.com/comment/92087073
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52575813
type: QuestionComment
has text: `[digits]` will always be a list, and a list *never* `is None`.

flask
tags question: http://stackoverflow.com/q/52439234
tags question: http://stackoverflow.com/q/52573458
tags question: http://stackoverflow.com/q/52458393
tags question: http://stackoverflow.com/q/52456021
tags question: http://stackoverflow.com/q/52583000
tags question: http://stackoverflow.com/q/52587236
tags question: http://stackoverflow.com/q/52493420
tags question: http://stackoverflow.com/q/52531856
tags question: http://stackoverflow.com/q/52564254
tags question: http://stackoverflow.com/q/52562969
tags question: http://stackoverflow.com/q/52463734
tags question: http://stackoverflow.com/q/52488728
tags question: http://stackoverflow.com/q/52559079
tags question: http://stackoverflow.com/q/52587399
tags question: http://stackoverflow.com/q/52490719
tags question: http://stackoverflow.com/q/52560419
tags question: http://stackoverflow.com/q/52511145
tags question: http://stackoverflow.com/q/52460146
tags question: http://stackoverflow.com/q/52528615
tags question: http://stackoverflow.com/q/52581576
tags question: http://stackoverflow.com/q/52562319
tags question: http://stackoverflow.com/q/52568304
tags question: http://stackoverflow.com/q/52553798
tags question: http://stackoverflow.com/q/52533245
tags question: http://stackoverflow.com/q/52480212
tags question: http://stackoverflow.com/q/52575382
tags question: http://stackoverflow.com/q/52569791
tags question: http://stackoverflow.com/q/52517457
tags question: http://stackoverflow.com/q/52552390
tags question: http://stackoverflow.com/q/52543420
tags question: http://stackoverflow.com/q/52560881
tags question: http://stackoverflow.com/q/52534085
tags question: http://stackoverflow.com/q/52464632
tags question: http://stackoverflow.com/q/52448943
tags question: http://stackoverflow.com/q/52573025
tags question: http://stackoverflow.com/q/52532267
tags question: http://stackoverflow.com/q/52488647
tags question: http://stackoverflow.com/q/52445427
tags question: http://stackoverflow.com/q/52512606
tags question: http://stackoverflow.com/q/52536093
tags question: http://stackoverflow.com/q/52442522
tags question: http://stackoverflow.com/q/52560312
tags question: http://stackoverflow.com/q/52564356
tags question: http://stackoverflow.com/q/52451154
tags question: http://stackoverflow.com/q/52572134
tags question: http://stackoverflow.com/q/52495937
tags question: http://stackoverflow.com/q/52570253
tags question: http://stackoverflow.com/q/52465552
type: Tag
tags question: http://stackoverflow.com/q/52434566
tags question: http://stackoverflow.com/q/52496959
tags question: http://stackoverflow.com/q/52552467
tags question: http://stackoverflow.com/q/52516845
tags question: http://stackoverflow.com/q/52530536
tags question: http://stackoverflow.com/q/52502675
tags question: http://stackoverflow.com/q/52480066
tags question: http://stackoverflow.com/q/52578897
tags question: http://stackoverflow.com/q/52502442
tags question: http://stackoverflow.com/q/52538930
tags question: http://stackoverflow.com/q/52461808
tags question: http://stackoverflow.com/q/52433794
tags question: http://stackoverflow.com/q/52469712
tags question: http://stackoverflow.com/q/52530774
tags question: http://stackoverflow.com/q/52487824
tags question: http://stackoverflow.com/q/52483449
tags question: http://stackoverflow.com/q/52471838
tags question: http://stackoverflow.com/q/52543783
tags question: http://stackoverflow.com/q/52490348
tags question: http://stackoverflow.com/q/52495331
tags question: http://stackoverflow.com/q/52506075
tags question: http://stackoverflow.com/q/52574775
tags question: http://stackoverflow.com/q/52498379
tags question: http://stackoverflow.com/q/52448067
tags question: http://stackoverflow.com/q/52443855
tags question: http://stackoverflow.com/q/52542756
tags question: http://stackoverflow.com/q/52503214
tags question: http://stackoverflow.com/q/52431362
tags question: http://stackoverflow.com/q/52462986
tags question: http://stackoverflow.com/q/52540148
tags question: http://stackoverflow.com/q/52430671

http://stackoverflow.com/a/52581976
score: 4
answers question: http://stackoverflow.com/q/52581881
type: Answer
upvote count: 4
downvote count: 0
has body: I believe that there is no such method. So for your problem, you would want to find the difference between the length of the old &amp; new value of var 2 as such: var1 = 'AnAppleADayKeepsTheDoctorAway' var2 = '000Ig00000noranceIsBliss00000' old_length = len(var2) var2 = var2.strip('0') diff_length = old_length - len(var2) var1 = var1[diff_length:len(var1)-diff_length]

http://stackoverflow.com/comment/91809046
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52432533
has text: Exactly, so instead of the incremental step you just put `90` there.

http://stackoverflow.com/a/52492643
has body: Try to convert all columns to strings: df = df.astype(str).groupby('Full_name').agg(';'.join).reset_index()
has comment: http://stackoverflow.com/comment/91925928
type: AcceptedAnswer
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52492620
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52492620
upvote count: 2

http://stackoverflow.com/a/55513812
has comment: http://stackoverflow.com/comment/109250366
has body: I cannot comment on it's performance but you can do (Scipy 1.1.0); &gt;&gt;&gt; from scipy.sparse import csr_matrix &gt;&gt;&gt; a = csr_matrix([[0, 2, 0], [1, 0, 0]]) &gt;&gt;&gt; print(a) (0, 1) 2 (1, 0) 1 &gt;&gt;&gt; a[a.nonzero()] = a[a.nonzero()] + 1 &gt;&gt;&gt; print(a) (0, 1) 3 (1, 0) 2
downvote count: 0
has comment: http://stackoverflow.com/comment/109313133
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52564903
score: 4

http://stackoverflow.com/comment/91952807
score: 0
has text: You might want to take a look at https://pypi.org/project/python-Levenshtein/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52506099

http://stackoverflow.com/comment/91880902
score: 3
comment on: http://stackoverflow.com/q/52469467
type: QuestionComment
type: Comment
has text: You're not really asking anything here. What is the criteria of deciding which word should be output?

http://stackoverflow.com/q/52486840
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91917657
has comment: http://stackoverflow.com/comment/91916987
has title: Creating fast RGB look up tables in Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52489931
type: Question
upvote count: 2
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91917434
has comment: http://stackoverflow.com/comment/91956844
tagged with: opencv
tagged with: performance
has comment: http://stackoverflow.com/comment/91915310
has comment: http://stackoverflow.com/comment/91917536
tagged with: lookup-tables
tagged with: numpy
has comment: http://stackoverflow.com/comment/91916954
possible better answer: http://stackoverflow.com/a/52488855
has answer: http://stackoverflow.com/a/52489931
has answer: http://stackoverflow.com/a/52488855
downvote count: 0
has body: I have a function I will call 'rgb2something' that transforms RGB data [1x1x3] into a single value (a probability), looping over each pixel in the input RGB data turns out to be rather slow. I have tried the following approach to speed the conversion up. To generate the LUT (Look up table): import numpy as np levels = 256 levels2 = levels**2 lut = [0] * (levels ** 3) levels_range = range(0, levels) for r in levels_range: for g in levels_range: for b in levels_range: lut[r + (g * levels) + (b * levels2)] = rgb2something(r, g, b) And to convert RGB to the transformed probability image: result = np.take(lut, r_channel + (g_channel * 256) + (b_channel * 65536)) However both generating the LUT and calculating the result is still slow. In 2 dimensions it's rather fast, however in 3 dimensions (r, g and b) it's slow. How can I increase the performance of this? EDIT rgb2something(r, g, b) looks like this: def rgb2something(r, g, b): y = np.array(r, g, b) y_mean = np.mean(y, axis=0) y_centered = y - y_mean y_cov = y_centered.T.dot(y_centered) / len(y_centered) m = len(Consts.x) n = len(y) q = m + n pool_cov = (m / q * x_cov) + (n / q * y_cov) inv_pool_cov = np.linalg.inv(pool_cov) g = Consts.x_mean - y_mean mah = g.T.dot(inv_pool_cov).dot(g) ** 0.5 return mah EDIT 2: Full working code sample of what I'm trying to achieve, I am using OpenCV so any OpenCV approaches such as Apply LUT are welcome, as are C/C++ approaches: import matplotlib.pyplot as plt import numpy as np import cv2 class Model: x = np.array([ [6, 5, 2], [2, 5, 7], [6, 3, 1] ]) x_mean = np.mean(x, axis=0) x_centered = x - x_mean x_covariance = x_centered.T.dot(x_centered) / len(x_centered) m = len(x) n = 1 # Only ever comparing to a single pixel q = m + n pooled_covariance = (m / q * x_covariance) # + (n / q * y_cov) -&lt; Always 0 for a single point inverse_pooled_covariance = np.linalg.inv(pooled_covariance) def rgb2something(r, g, b): #Calculates Mahalanobis Distance between pixel and model X y = np.arra…
has comment: http://stackoverflow.com/comment/91916011
has comment: http://stackoverflow.com/comment/91917767
score: 2

http://stackoverflow.com/q/52440927
tagged with: pandas
has body: The purpose of this code is Scrape a 300 of tables via Pandas and Beautiful Soup Concatenate this tables into a single data frame The code works fine for the first step. But it is not working in the second. Here is the code: import pandas as pd from urllib.request import urlopen, Request from bs4 import BeautifulSoup header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 " "Safari/537.36", "X-Requested-With": "XMLHttpRequest"} url = open(r"C:\Users\Sayed\Desktop\script\links.txt").readlines() for site in url: req = Request(site, headers=header) page = urlopen(req) soup = BeautifulSoup(page, 'lxml') table = soup.find('table') df = pd.read_html(str(table), parse_dates={'DateTime': ['Release Date', 'Time']}, index_col=[0])[0] df = pd.concat(df, axis=1, join='outer').sort_index(ascending=False) print(df) Here is the error: Traceback (most recent call last): File "D:/Projects/Tutorial/try.py", line 18, in df = pd.concat(df, axis=1, join='outer').sort_index(ascending=False) File "C:\Users\Sayed\Anaconda3\lib\site-packages\pandas\core\reshape\concat.py", line 225, in concat copy=copy, sort=sort) File "C:\Users\Sayed\Anaconda3\lib\site-packages\pandas\core\reshape\concat.py", line 241, in init '"{name}"'.format(name=type(objs).__name__)) TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame
tagged with: python
favorite count: 0
upvote count: 1
has title: pandas merging 300 dataframes
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52441006
accepted answer: http://stackoverflow.com/a/52441006
score: 1
type: Question
answer count: 1
downvote count: 0
tagged with: beautifulsoup

http://stackoverflow.com/comment/91973931
score: 0
type: Comment
type: QuestionComment
has text: The approach here is working, right? It's just a little cumbersome. But that's expected for such detour. You wouldn't usually first plot something to get the data out, but rather the inverse, first get the data, then plot it.
comment on: http://stackoverflow.com/q/52517145

http://stackoverflow.com/comment/91843799
score: 0
comment on: http://stackoverflow.com/q/52449920
has text: I think it's also worth mentioning that you *can* use locals() or globals(), but in an Enterprise application with testing, linting or internationalization, it's not really a good practice to use this IMO. See https://stackoverflow.com/questions/1550479/python-is-using-vars-locals-a-good-practice for more discussion.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91889066
has text: @SamuelTan yeah it is possible but not necessary.
comment on: http://stackoverflow.com/a/52473676
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91917153
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52487941
has text: This produces a sawtooth pattern with vertical segments that may not be what OP is looking for. I think the solution is to suppress the line and add a marker symbol with `df.plot(style='o')`.

http://stackoverflow.com/a/52578372
answers question: http://stackoverflow.com/q/52577459
score: 0
type: Answer
has body: "Is there anyways to do the global thing without changing the name? I.e. I want to take my parameter make it a global variable retaining the same name (as opposed to here where value and n are named differently)" from: How to get the original variable name of variable passed to a function "You can't. It's evaluated before being passed to the function. All you can do is pass it as a string." What is doable is you can make your code always use a specific variable name, and within your function, declare it a global variable. That way you wouldnt even need to pass it as a parameter, but it would get affected every time you used the function; example: def test_function (): global N N = N + 1 print (N) N = 5 test_function() test_function() test_function() 6 7 8
has comment: http://stackoverflow.com/comment/92091936

http://stackoverflow.com/q/52452714
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/91848808
has comment: http://stackoverflow.com/comment/91849880
tagged with: numpy
has answer: http://stackoverflow.com/a/52452811
has title: read csv file with a few rows of information
upvote count: 0
answer count: 1
favorite count: 0
has body: I have a data csv file with first few rows are storing information. The format is like this: info1, aa info2, bb info3, cc col1, col2, col3 x1, y1, z1 x2, y2, z2 If I use numpy.genfromtxt(), it will show error due to different columns between first three lines, and the rest. I can use numpy.genfromtxt(skip_header=3) to read the data, and numpy.genfromtxt(skip_footer= ) to read the information. I wonder if there is a better way to do this?
tagged with: python
accepted answer: http://stackoverflow.com/a/52452811
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91848690
has comment: http://stackoverflow.com/comment/91849748

http://stackoverflow.com/comment/92062615
has text: In your print statement, you only print ch once. you want to print it i times. So replace `print(ch)` with `print(ch * i)`
type: AnswerComment
comment on: http://stackoverflow.com/a/52560599
score: 0
type: Comment

http://stackoverflow.com/q/52549102
score: 1
accepted answer: http://stackoverflow.com/a/52549374
possible better answer: http://stackoverflow.com/a/52549470
type: Question
tagged with: export-to-csv
answer count: 2
has answer: http://stackoverflow.com/a/52549470
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: Here is my content in my text file: and I only want to get this sha1 and description then parse it to a csv file using prefix and delimiter a trimed the strings then selected the sha1 between "\" and "->" then I want to get the description. +----------------------------------------------------+ | VSCAN32 Ver 2.00-1655 | | | | Copyright (c) 1990 - 2012 xxx xxx xxx Inc. | | | | Maintained by xxxxxxxxx QA for VSAPI Testing | +----------------------------------------------------+ Setting Process Priority to NORMAL: Success 1 Successfully setting POL Flag to 0 VSGetVirusPatternInformation is invoked Reading virus pattern from lpt$vpn.527 (2018/09/25) (1452700) Scanning samples_extracted\88330686ae94a9b97e1d4f5d4cbc010933f90f9a-&gt;(MS Office 2007 Word 4045-1) -&gt;Found Virus [TROJ_FRS.VSN11I18] Scanning samples_extracted\8d286d610f26f368e7a18d82a21dd68b68935d6d-&gt;(Microsoft RTF 6008-0) -&gt;Found Virus [Possible_SMCCVE20170199] Scanning samples_extracted\a10e5f964eea1036d8ec50810f1d87a794e2ae8c-&gt;(ASCII text 18-0) -&gt;Found Virus [Trojan.VBS.NYMAIM.AA] 18 files have been checked. Found 16 files containing viruses. (malloc count, malloc total, free total) = (0, 35, 35) So far this is my code: it still outputs many string but i only need the sha1 and description to be parsed in csv I used split so the sha1 can be selected between "\" and "->" it does put the sha1 but the description is not trimed, and the contents are still there import csv INPUTFILE = 'input.txt' OUTPUTFILE = 'output.csv' PREFIX = '\\' DELIMITER = '-&gt;' def read_text_file(inputfile): data = [] with open(inputfile, 'r') as f: lines = f.readlines() for line in lines: line = line.rstrip('\n') if not line == '': line = line.split(PREFIX, 1)[-1] parts = line.split(DELIMITER) data.append(parts) return data def write_csv_file(data, outputfile): with open(outputfile, 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) for row in data: csvwriter.writerow(r…
tagged with: text-files
has answer: http://stackoverflow.com/a/52549374
has comment: http://stackoverflow.com/comment/92037587
upvote count: 1
has title: How can I select a certain string in txt file and list it in csv file?
type: AnsweredQuestion

http://stackoverflow.com/comment/91995044
score: 0
comment on: http://stackoverflow.com/q/52526476
type: Comment
type: QuestionComment
has text: See the updates.

http://stackoverflow.com/comment/91891704
type: Comment
has text: Thank you. Its matching on the bases of index, if I change the position in of rows in any dataframe it gives wrong result. (eg. In df1 first row move to last, it will give missing as status)
comment on: http://stackoverflow.com/a/52448071
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92010599
type: AnswerComment
has text: Great I hope it should solve your problem. Can you accept as the answer?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52535554

http://stackoverflow.com/a/52502112
has body: There is a huge hidden problem to running tesseract in a webpage. pytesseract, the popular tesseract wrapper for Python, calls on subprocess and Popen to run tesseract from the command line, then parses the results and returns them to you. Spawning a subprocess from a web request (other than those directly managed by your webserver) will: Crash or stall most Python web frameworks Crash or stall WSGI processes Create tons of zombie processes Be a general pain to handle So, my advice is to not. Look for an OCR solution that runs in pure-Python or interfaces with Python through a statically compiled shared object. Which OCR solution does that... I have no clue.
has comment: http://stackoverflow.com/comment/91945534
has comment: http://stackoverflow.com/comment/92338091
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92076987
score: 1
has comment: http://stackoverflow.com/comment/91945783
has comment: http://stackoverflow.com/comment/91945333
answers question: http://stackoverflow.com/q/52502008
has comment: http://stackoverflow.com/comment/92128475
upvote count: 1

http://stackoverflow.com/q/52493544
downvote count: 2
has body: my code is: import base64 def encrypt(cleartext, key): new_message = cleartext,key,23 return new_message message = encrypt("heckin", 9) print (message) and I receive: ('heckin', 9, 23) How do I get rid of the ' ' and the parenthesis marks on the output? so it could just be: heckin 9 23 (completely new to python. i know its an overly easy solution for you guys)
type: Question
score: -2
answer count: 1
favorite count: 0
has title: why is message printing out the quotation marks in python? python super beginners code
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91927659
upvote count: 0
has answer: http://stackoverflow.com/a/52493577

http://stackoverflow.com/q/52551957
tagged with: python
upvote count: 6
has title: python plotly date axis as string not dates
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78220724
downvote count: 1
tagged with: plotly
type: Question
has answer: http://stackoverflow.com/a/52599209
score: 5
answer count: 3
has answer: http://stackoverflow.com/a/52554560
has body: I want to create a bar chart using python plotly, with on the x-axis dates as strings/categories. For some reason, plotly keeps transforming strings to dates. My x-axis is continuous "timeline" of dates, rather than categories as I would expect. My question: how can I construct a bar chart where my dates are handled as categories, rather than dates? Minimal example: d = {'date': ['2018-08-04', '2018-08-02','2018-08-03', '2018-08-11','2018-08-11'], 'score': [3, 4, 6, 2,8]} df = pd.DataFrame(data=d) data = [go.Bar( x=df['date'], y=df['score'] )] offline.iplot(data, filename='basic-bar') Example:
favorite count: 0

http://stackoverflow.com/a/52482503
has comment: http://stackoverflow.com/comment/91956138
upvote count: 7
has comment: http://stackoverflow.com/comment/91919067
has comment: http://stackoverflow.com/comment/91954816
has comment: http://stackoverflow.com/comment/91945167
has comment: http://stackoverflow.com/comment/91944838
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52452269
has comment: http://stackoverflow.com/comment/91918196
type: Answer
has body: Your main.py file and requirements.txt file should be in the same directory, and this should also be the same directory you're deploying your function from. Also, the google-cloud package is deprecated and shouldn't be used with other google-cloud-* packages. You should remove it from your requirements.txt file.
has comment: http://stackoverflow.com/comment/91955313
has comment: http://stackoverflow.com/comment/91914008
accepted answer of: http://stackoverflow.com/q/52452269
score: 7

http://stackoverflow.com/a/52503201
has body: The logic for checking if a Group exists, i.e. the line: if Group.objects.filter(group=group_name).exists() is not throwing the error here. It is likely that json_data is missing one of the keys you expect it to have, for example, 'group'. I'd recommend using the get method that dictionaries have. This provides default values when the specified key is not present in the dictionary. You should also have error handling for when the request body is not in valid JSON format. Here's an example: def device_update(request): try: json_data = json.loads(request.body) except json.JSONDecodeError: return HttpResponse('Request body must be in valid JSON format') email = json_data.get('email', '') imei = json_data.get('imei', '') sdk_version = json_data.get('sdk_version', '') date = json_data.get('updateDate', '') rule = json_data.get('ruleName', '') group_name = json_data.get('group', '') if Group.objects.filter(group=group_name).exists(): print("group does exists") else: print("group doesn't exists") return HttpResponse("Successful") I set the defaults to the empty string '', but you may want to change that.
type: Answer
answers question: http://stackoverflow.com/q/52502539
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/52502539
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/69720716
type: Answer
score: 0
has body: Auto logout. Add the below two values in settings.py file: 1.SESSION_COOKIE_AGE = TIME #//change expired session Example: SESSION_COOKIE_AGE = 240*60 #//four hours or your time SESSION_SAVE_EVERY_REQUEST = True ############################################################ And then add the below jquery code in your base.html file: function autorefresh() { // auto refresh page after 1 second setInterval('refreshPage()', 6*1000); } function refreshPage() { $.ajax({ url: window.location.pathname, success: function(data) { window.location = "." // $('#console').html(data); } }); }
answers question: http://stackoverflow.com/q/52496366

memory
tags question: http://stackoverflow.com/q/52526812
tag name: memory
tags question: http://stackoverflow.com/q/52456929
tags question: http://stackoverflow.com/q/52527152
type: Tag

http://stackoverflow.com/comment/91848626
has text: @EthanHill you also have to specify a narrowband model, like the error says.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52434042

http://stackoverflow.com/comment/91911754
type: Comment
type: QuestionComment
score: 0
has text: In the case of removing outliers in a dataframe in the case of data analysis, then resetting index is necessary ?
comment on: http://stackoverflow.com/q/52484958

http://stackoverflow.com/a/52500431
has comment: http://stackoverflow.com/comment/91941694
has comment: http://stackoverflow.com/comment/91941535
type: Answer
has comment: http://stackoverflow.com/comment/91941869
upvote count: 1
answers question: http://stackoverflow.com/q/52500359
has comment: http://stackoverflow.com/comment/91941906
has comment: http://stackoverflow.com/comment/91941402
score: 1
has comment: http://stackoverflow.com/comment/91941455
has body: Try this: with open("file.txt", "w") as output_file: for word in line: output_file.write(word) it will put all words in a line of the file if you want them in different lines: with open("file.txt", "w") as output_file: for word in line: output_file.write(word + '\n') and if you want them in one line with a space between them: with open("file.txt", "w") as output_file: output_file.write(line.join(' '))
downvote count: 0

http://stackoverflow.com/q/52562562
tagged with: psycopg2
has body: I have a class Person with id, fname, and lname. My program will have a large list of Person objects, which I would like to insert into my PostgreSQL database. I would like to do this through psycopg2.execute_values method, which requires __getitem__ to be defined for my class. __getitem__ is currently returning tuple(id, fname, lname), which results in pscopg2.execute_values trying to execute: insert into persons(id, fname, lname) values ((1, 'test1', 'test1'))... import psycopg2.extras class Person: def __init__(self, id, fname, lname): self.id = id self.fname = fname self.lname = lname def __len__(self): return 1 def __getitem__(self, item): return self.id, self.fname, self.lname dsn = "user=my_user host=localhost port=5432 dbname=my_db" query = "insert into persons(id, fname, lname) values %s" p1 = Person(1, 'test1', 'test1') p2 = Person(2, 'test2', 'test2') records = list() records.append(p1) records.append(p2) with psycopg2.connect(dsn=dsn) as conn: with conn.cursor() as cursor: psycopg2.extras.execute_values(cursor, query, records, template=None, page_size=1000) psycopg2.ProgrammingError: INSERT has more target columns than expressions LINE 1: insert into persons(id, fname, lname) values ((1, 'test1', 'test1'))... ^ HINT: The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses? Using a namedtuple works: from collections import namedtuple import psycopg2.extras Person = namedtuple('Person', ['id', 'fname', 'lname']) dsn = "user=my_user host=localhost port=5432 dbname=my_db" query = "insert into persons(id, fname, lname) values %s" p1 = Person(1, 'test1', 'test1') p2 = Person(2, 'test2', 'test2') records = list() records.append(p1) records.append(p2) with psycopg2.connect(dsn=dsn) as conn: with conn.cursor() as cursor: psycopg2.extras.execute_values(cursor, query, records, template=None, page_size=1000) However, I want to implement a different __eq__ and __hash__ implement…
type: AnsweredQuestion
type: Question
upvote count: 4
has title: psycopg2 execute_values with list of class objects
answer count: 1
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/52564059
accepted answer: http://stackoverflow.com/a/52564059
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/92080534
type: QuestionComment
has text: Look into the `os` module.
comment on: http://stackoverflow.com/q/52572007
score: 0
type: Comment

http://stackoverflow.com/comment/92103771
score: 0
has text: I'm not sure of the best way to do it, comparing idx to itself was the best way I could think of. So ideally, if idx = 0, it would build a list for row 1, if idx = 1, it would build a list for row 2, and so on. I compared idx to itself so no data from row 0 goes to row 1 or vice versa.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52584291

http://stackoverflow.com/q/52476666
has body: Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name 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) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Count class CatalogSerializer(serializers.ModelSerializer): total_pieces = serializers.SerializerMethodField() total_price = serializers.SerializerMethodField() company_name = serializers.CharField() class Meta: model = Catalog fields = ('name','no_of_pcs','per_piece_price','company_name','total_pieces','total_price') def get_total_pieces(self, obj): totalpieces = Catalog.objects.aggregate(total_pieces=Count('no_of_pcs')) return totalpieces["total_pieces"] def get_total_price(self, obj): totalprice = Catalog.objects.aggregate(total_price=Sum('per_piece_price')) return totalprice["total_price"] class UserSerializer(serializers.ModelSerializer): company_name = serializers.CharField() class Meta: model = User fields = '__all__' class CatalogData(serializers.ModelSerializer): class Meta: model = Catalog fields = ('name', 'no_of_pcs', 'per_piece_price') class CompanySerializer(serializers.ModelSerializer): catalog = CatalogData(many=True) user = UserSerializer(many=True) class Meta: model = Company fields = ('name', 'phone_number', 'catalog','user') here is my views.py from __future__ …
accepted answer: http://stackoverflow.com/a/52476723
tagged with: python
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52476723
type: Question
score: 0
has title: How to get all fields in django rest framework which is defined as related name in a diffent model with foreign key?
answer count: 1

http://stackoverflow.com/a/52514654
has body: If you want you own code to work, you can just add: counter = 0 After the while condition. The mistake in you code is the increment of count. What it does is for one loop, it counts all tails on your list and adds that to counter, then, like a snowball effect, the SAME tails were counted and added AGAIN for every succeeding loops. This correction is a bit inefficient though as you will always clear the value of count, then count again from the start. If your list reaches large index values, it may slow down your code. Good luck!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52514171

http://stackoverflow.com/a/52542519
type: Answer
accepted answer of: http://stackoverflow.com/q/52541490
score: 1
has comment: http://stackoverflow.com/comment/92029929
upvote count: 1
has body: You're trying to convert something which isn't an integer. I can reproduce the problem when I type in any alpha character. An easier way to see what is going on would be to make the input it's own variable and step through the debugger. Try something like this and see what get's printed before the assert. var = input('Enter a integer from 1 to 100: ') print(repr(var), type(var)) assert var.isalnum(), "var should be only numbers" promotion_percentage = int(var) print(promotion_percentage, type(promotion_percentage)) Notice that when I type in only numbers, your code works. Enter a integer from 1 to 100: 234 '234' &lt;class 'str'&gt; 234 &lt;class 'int'&gt; but when I give it a non-integer... Enter a integer from 1 to 100: abc 'abc' &lt;class 'str'&gt; Traceback (most recent call last): ValueError: invalid literal for int() with base 10: 'abc' To explain the error you are specifically getting, your input is an empty string. This happens when you hit enter without typing anything. In which case I would follow the advice from this post. var = input('Enter a integer from 1 to 100: ') print(repr(var), type(var)) assert var.isalnum(), "var should be only numbers" if not var: # ask them again? # exit script? # set a default value?
downvote count: 0
answers question: http://stackoverflow.com/q/52541490
type: AcceptedAnswer

pyperclip
tags question: http://stackoverflow.com/q/52486730
type: Tag
tag name: pyperclip

http://stackoverflow.com/comment/91845212
has text: What is your output of `import sys; print(sys.version_info)`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52448995

http://stackoverflow.com/comment/91870176
comment on: http://stackoverflow.com/q/52463972
score: 0
type: Comment
type: QuestionComment
has text: `g` is not very large, varying from 2 to 32 elements (is a regular finite difference stencil). But `N` can be slightly large. Like `100000`, anythow `N` that really dictates the size of matrix. And the size grows `N**2`.

http://stackoverflow.com/q/52516924
downvote count: 0
score: 1
favorite count: 0
has title: Split/explode cells into multiple rows based on conditions in pandas dataframe
type: Question
tagged with: explode
tagged with: python
has answer: http://stackoverflow.com/a/52551032
upvote count: 1
answer count: 1
tagged with: split
has comment: http://stackoverflow.com/comment/92012404
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52551032
has comment: http://stackoverflow.com/comment/92012672
tagged with: pandas
has body: The code for input dataframe is import pandas as pd df = pd.DataFrame([{'Column1': '((CC ) + (A11/ABC/ZZ) + (!AAA))','Column2': 'XYZ + XXX/YYY'}]) Input Dataframe:- +---------------------------------+---------------------------------+ | Column1 | Column2 + +---------------------------------+---------------------------------+ | ((CC ) + (A11/ABC/ZZ) + (!AAA)) | XYZ + XXX/YYY | +---------------------------------+---------------------------------+ Input list:- list = [AAA,BBB,CCC] Conditions:- '+' should remain as such (similar to AND condition) '/' means split the data into multiple cells (similar to OR condition) '!' means replace with other elements in the corresponding list (similar to NOT condition) Because of the ! sign, the row becomes +------------------------------------+---------------------------------+ | Column1 | Column2 + +------------------------------------+---------------------------------+ | ((CC ) + (A11/ABC/ZZ) + (BBB/CCC)) | XYZ + XXX/YYY | +------------------------------------+---------------------------------+ Please help me to split the singe row into multiple rows as shown below using Pandas +---------------------------------+---------------------------------+ | Column1 | Column2 + +---------------------------------+---------------------------------+ | CC + A11 + BBB | XYZ + XXX | +---------------------------------+---------------------------------+ | CC + ABC + BBB | XYZ + XXX | +---------------------------------+---------------------------------+ | CC + ZZ + BBB | XYZ + XXX | +---------------------------------+---------------------------------+ | CC + A11 + CCC | XYZ + XXX | +---------------------------------+---------------------------------+ | CC + ABC + CCC | XYZ + XXX | +---------------------------------+---------------------------------+ | CC + ZZ + CCC | XYZ + XXX | +---------------------------------+---------------------------------+ | CC + A11 + BBB | XYZ + YYY | +---------------------------------+---------------------------------+ | …
type: AnsweredQuestion

http://stackoverflow.com/comment/91901022
type: QuestionComment
type: Comment
has text: Let's say your new hour of study is in a variable called `new_hour`, then just use `y_new = regression_model.predict(new_hour)`. What's wrong with doing that?
score: 1
comment on: http://stackoverflow.com/q/52479544

http://stackoverflow.com/q/52489702
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Pandas Groupby using time frequency
type: Question
has answer: http://stackoverflow.com/a/52489723
has body: My question is regarding a groupby of pandas dataframe. A sample dataset would look like this: cust_id | date | category A0001 | 20/02/2016 | cat1 A0001 | 24/02/2016 | cat2 A0001 | 02/03/2016 | cat3 A0002 | 03/04/2015 | cat2 Now I want to groupby cust_id and then find events that occur within 30days of each other and compile the list of categories for those. What I have figured so far is to use pd.grouper in the following manner. df.groupby(['cust_id', pd.Grouper(key='date', freq='30D')])['category'].apply(list) But this isn't putting [cat1, cat2, cat3] in the same list for A0001. Any help on what I'm doing wrong or how I can go about doing what I need would be most appreciated. The results I want should look something like this: A0001 | [cat1, cat2, cat3] A0002 | [cat2] Thanks in Advance Edit: Following Wen's answer, I tried and it worked for this minimum example, my bad for providing a minimum example that wasn't representative. This can be recreated with this example for both 0.20.3 and 0.23.0 versions of pandas. cust_id date category 0 A0001 2015-02-02 cat5 1 A0002 2015-02-03 cat1 2 A0001 2016-02-20 cat1 3 A0001 2016-02-24 cat2 4 A0001 2016-03-02 cat3 5 A0003 2016-09-09 cat2 6 A0003 2016-08-21 cat5 The answer I get is: cust_id A0001 [cat5] A0001 [cat1, cat2] A0001 [cat3] A0002 [cat1] A0003 [cat5] Name: category, dtype: object My apologies for the initial confusion!
tagged with: data-science
score: 0

c++
tags question: http://stackoverflow.com/q/52461942
tags question: http://stackoverflow.com/q/52489854
tags question: http://stackoverflow.com/q/52578522
tags question: http://stackoverflow.com/q/52583498
tags question: http://stackoverflow.com/q/52495024
type: Tag
tags question: http://stackoverflow.com/q/52554798
tags question: http://stackoverflow.com/q/52570130
tags question: http://stackoverflow.com/q/52584465
tags question: http://stackoverflow.com/q/52445338
tags question: http://stackoverflow.com/q/52568315
tags question: http://stackoverflow.com/q/52478788
tags question: http://stackoverflow.com/q/52562833
tags question: http://stackoverflow.com/q/52441952
tags question: http://stackoverflow.com/q/52588634
tags question: http://stackoverflow.com/q/52459530
tags question: http://stackoverflow.com/q/52562028
tag name: c++
tags question: http://stackoverflow.com/q/52438568

http://stackoverflow.com/comment/91833602
score: 0
type: Comment
type: QuestionComment
has text: try python shell ! what error you get ?
comment on: http://stackoverflow.com/q/52445331

http://stackoverflow.com/a/52475680
type: Answer
accepted answer of: http://stackoverflow.com/q/52475679
has body: Works so far? :-) I don't think so. When I try to execute in python3, it just hangs at the subprocess statement. Where is line defined? You never increment number or count. You'll have to find out how to access the output of the subprocess in your while loop. I think that you're on a good track. I would do something like this: Read up on subprocess. Print line in that loop to see what your working with. Print count after the loop. You'll need another subprocess to run ps. Replace all of the functionality provided by echo, awk, cut, and grep with direct Python code. Read the man pages for awk, cut, and grep to understand what those commands are doing in the shell script. To find out how to do those things in Python, begin by looking at the Python String Methods documentation. Almost everything you need to do will be in String Methods and Subprocess. Good Luck!
answers question: http://stackoverflow.com/q/52475679
has comment: http://stackoverflow.com/comment/91892769
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/52548621
type: Answer
has comment: http://stackoverflow.com/comment/92036433
score: 1
answers question: http://stackoverflow.com/q/52548552
upvote count: 1
has body: If you've defined somewhere dictionary xpaths you should check whether it really looks like: xpaths = {'usernameTxtBox': '//input[@name="username"]', 'passwordTxtBox': '//input[@name="password"]', 'loginButton': '//button[@id="tdb1"]'} Update Note that you've defined Submit button with submitButton key while trying to get its value with loginButton key
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92036482
has comment: http://stackoverflow.com/comment/92036567
accepted answer of: http://stackoverflow.com/q/52548552

http://stackoverflow.com/q/52563291
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52572999
type: Question
tagged with: numpy
downvote count: 0
tagged with: histogram
tagged with: density-plot
answer count: 1
has comment: http://stackoverflow.com/comment/92149073
has body: Let's say the function is simply def linear(x,n): return n+x And that the universe of parameters to try are import numpy as np parameters = np.random.normal(0, 1, 1000) Which is the best way to plot all the universe of functions? The direct one is import matplotlib.pyplot as plt for n in parameters: plt.plot(x,linear(x,n)) However, when the parameres are many (like 1e5), this is not practicable. I think the proper way to do this may be along the lines of a 2D density plot or a 2D histogram but I am not sure how to apply those to my problem. A further complication: Each of the models tried above carries its own "goodness-fit-estimator value", a $\chi^2$, for example. After obtaining a plot showing the density of models as a color code, I would like to color code it by $\chi^2$ value. Again, I am asking for ideas or experience. Any suggestion is very welcome!
favorite count: 0
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42262563
tagged with: python
has title: How to make a density plot out of many individual functions?
score: 2

http://stackoverflow.com/comment/91894497
score: 1
has text: @EMKAY that won't work. Lexicographic ordering of numbers doesn't match the expected output. And your current code calls `sorted` on the string, not the contents of the directory.
comment on: http://stackoverflow.com/q/52476544
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52430682
type: Answer
downvote count: 0
has body: dictionaries are not order in python. if you need to order the dictionary . better to use OrderedDict from collections modules In [24]: from collections import OrderedDict ...: d = {'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}} ...: ...: ord_a = OrderedDict(sorted(ord_d.items(), key = lambda x: x[1]['frequency'])) ...: ...: In [25]: In [25]: print(ord_a) OrderedDict([('B', {'frequency': 2}), ('A', {'frequency': 4}), ('C', {'frequency': 7})])
score: 1
answers question: http://stackoverflow.com/q/52430465
upvote count: 1

http://stackoverflow.com/comment/92179776
type: AnswerComment
comment on: http://stackoverflow.com/a/52552759
type: Comment
score: 0
has text: Yes, you are right. The value 0.1 is the normed value e.g. the value for `dy/dx`. If you want to have the value 0.5, you have to multiply it by `dx` i.e. `ydata*np.diff(xdata)`. Or simply use keyword `normed=False` and normalize the `ydata` with the size of the data i.e. `ydata,xdata = np.histogram(data,bins=np.size(data),normed=True);ydata = ydata/np.size(data)`. Hope this helps.

http://stackoverflow.com/comment/91855850
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52456207
has text: You can't have `trans` as both the name of a function, and the name of a variable (used in that very last `for` loop). The times when your code did work are cases where that `for` loop was never executed, and therefore `trans` was never reassigned.
score: 1

http://stackoverflow.com/q/52455310
type: Question
score: 5
tagged with: python
has answer: http://stackoverflow.com/a/52455328
accepted answer: http://stackoverflow.com/a/52455371
has comment: http://stackoverflow.com/comment/91853091
has body: I have a list: mylist = [1,2,3] And I want to change the first element to the list, so a list inside a list. My first try: mylist + mylist[1:] gives me [1, 2, 3, 2, 3] # not what I want my second try mylist[0]=mylist gives me [[...], 2, 3] # is this an infinite list? Although I want [[1,2,3], 2, 3]
tagged with: list
possible better answer: http://stackoverflow.com/a/52455325
has answer: http://stackoverflow.com/a/52455325
has answer: http://stackoverflow.com/a/52455329
has comment: http://stackoverflow.com/comment/91853063
has title: Python: change the first element to the list itself
upvote count: 5
answer count: 5
has answer: http://stackoverflow.com/a/52455324
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91853076
favorite count: 0
has answer: http://stackoverflow.com/a/52455371

http://stackoverflow.com/comment/92104507
has text: there are keys like reference,date,postcode etc which need to be filled through excel sheet rather than through manually assigning through objects.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52552393

http://stackoverflow.com/q/52452283
answer count: 1
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
tagged with: tk-toolkit
has comment: http://stackoverflow.com/comment/91847969
has body: I'm using TkInter to show a GUI dialog under Python 2.7. I've defined the GUI in the main module, and I trying the split off the logic to a separate module that I import. import sys from Tkinter import * import ttk import dialoglogic : : class processorDialog: def _init__(self, top=None): : : self.ButtonProcess = Button(top) self.ButtonProcess.configure( state=DISABLED) self.ButtonProcess.configure( text='''Start Process''') And now in the dialoglogic module, I need to set the state of the button to NORMAL. I know I need to use xxxx.ButtonProcess.configure(state=NORMAL) But I've been unable to determine the secret sauce for "xxxx" to access the TkI button widget in the parent module from the child module. If the answer is out there, I'm confused as to how to Google it because I'm not coming up with any results (yet it seems like something everyone would need to do at some point ;-) ) Any pointers would be appreciated!
type: Question
has answer: http://stackoverflow.com/a/52453000
accepted answer: http://stackoverflow.com/a/52453000
tagged with: python-2.7
score: 0
has title: Python: how to set TkInter attribute from submodule?

http://stackoverflow.com/q/52548308
type: AnsweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52550791
score: 1
has title: Python launch program from Maya freeze
has body: I have a little question. Maybe it's not difficult but I don't find the answer. I find a way to launch from Maya substance painter with python command. My problem is that Maya stays freeze until I leave substance painter. I would like to use Maya while substance painter is open. the code: subprocess.call(['C:/Program Files/Allegorithmic/Substance Painter/substance painter.exe' ,'--mesh' , 'c:/temp/exported.fbx']) Thank in advance for your help.^^
downvote count: 0
answer count: 1
tagged with: maya
accepted answer: http://stackoverflow.com/a/52550791
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52458678
tagged with: python
has answer: http://stackoverflow.com/a/52458910
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52458719
has body: Here's my cube root calculator: cube = int(input('Input an integer: ')) for guess in range(abs(cube + 1)): if guess ** 3 &gt;= abs(cube): break if guess ** 3 != abs(cube): print(str(cube) + ' is not a perfect cube.') else: if cube &lt; 0: guess = - guess print('Cube root of ' + str(cube) + ' is ' + str(guess)) It returns following error on entering -1 as input: Traceback (most recent call last): File "C:/Users/ABC.py", line 5, in &lt;module&gt; if guess ** 3 != abs(cube): NameError: name 'guess' is not defined It prints expected answers for all negative integers expect -1 and I am unable to find reason for this behavior. It should print -1 as output and I don't see any reason for defining guesswhen it's being "defined" by range()function. Do you see what I am missing?
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52458715
has title: -1 returning error in cube root calculator
possible better answer: http://stackoverflow.com/a/52458719
accepted answer: http://stackoverflow.com/a/52458715
answer count: 3
favorite count: 0
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/91859595

http://stackoverflow.com/comment/91863980
type: AnswerComment
comment on: http://stackoverflow.com/a/52455168
type: Comment
score: 0
has text: @Aliquis: OK, so evaluate it. More commonly you would do the `select_for_update()` when you first fetch the `Event` (based on an `id` in the URL, or whatever), but this is the "fat models" version, since you mentioned that.

http://stackoverflow.com/a/78729909
has comment: http://stackoverflow.com/comment/138809522
type: Answer
answers question: http://stackoverflow.com/q/52481006
has body: Implementation of GPU is a very complex process. It's not just typing with'GPU' or with'cpu' and you see it's done. First you should mention what was your way of implementing gpu in details then it will reveal why and where things went wrong.
downvote count: 1
score: -1
upvote count: 0

http://stackoverflow.com/q/52571144
has answer: http://stackoverflow.com/a/77293561
tagged with: python
answer count: 4
has title: What is the Pythonic way to remove "Bearer " from the HTTP authorization header
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92079343
has comment: http://stackoverflow.com/comment/92079002
possible better answer: http://stackoverflow.com/a/52571314
downvote count: 3
has body: I have an Authorization header in a string like this: Bearer [myawesometoken] I don't want to tokenize using the space character because I want to require the string "Bearer" to be at the start of the string What is the pythonic way to return just the token from the string? Is there a regex matching function like PHP preg_match()? Would this be the pythonic way to do it?
type: Question
has comment: http://stackoverflow.com/comment/92079292
has answer: http://stackoverflow.com/a/52571440
has comment: http://stackoverflow.com/comment/92079211
accepted answer: http://stackoverflow.com/a/52571440
has comment: http://stackoverflow.com/comment/111517697
has answer: http://stackoverflow.com/a/52571305
score: 5
has answer: http://stackoverflow.com/a/52571314
tagged with: string
favorite count: 0
upvote count: 8

airflow
tags question: http://stackoverflow.com/q/52453414
tags question: http://stackoverflow.com/q/52554906
tags question: http://stackoverflow.com/q/52545295
tag name: airflow
tags question: http://stackoverflow.com/q/52450640
tags question: http://stackoverflow.com/q/52556361
tags question: http://stackoverflow.com/q/52558018
tags question: http://stackoverflow.com/q/52449483
tags question: http://stackoverflow.com/q/52452476
tags question: http://stackoverflow.com/q/52462548
type: Tag
tags question: http://stackoverflow.com/q/52506112

http://stackoverflow.com/comment/91859535
has text: `sentence = sentence.split()` is redundant. `for i in sentence.split():` is sufficient
comment on: http://stackoverflow.com/a/52458687
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/52562133
accepted answer: http://stackoverflow.com/a/52563566
answer count: 1
has title: Keras: How to shape inputs for CNN and LSTM layers?
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/92063082
has answer: http://stackoverflow.com/a/52563566
tagged with: python
upvote count: 4
type: AnsweredQuestion
tagged with: conv-neural-network
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/92064855
has comment: http://stackoverflow.com/comment/92063128
has body: I am building a model to predict geospatial-temporal datasets. My data has original dimensions (features, lat, lon, time), i.e. for each feature and at each lat/lon point there is a time series. I have created a CNN-LSTM model using Keras like so (I assume the below needs to be modified, this is just a first attempt): def define_model_cnn_lstm(features, lats, lons, times): """ Create and return a model with CN and LSTM layers. Input and output data is expected to have shape (lats, lons, times). :param lats: latitude dimension of input 3-D array :param lons: longitude dimension of input 3-D array :param times: time dimension of input 3-D array :return: CNN-LSTM model appropriate to the expected input array """ # define the CNN model layers, wrapping each CNN layer in a TimeDistributed layer model = Sequential() model.add(TimeDistributed(Conv2D(features, (3, 3), activation='relu', padding='same', input_shape=(lats, lons, times)))) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Flatten())) # add the LSTM layer, and a final Dense layer model.add(LSTM(units=times, activation='relu', stateful=True)) model.add(Dense(1)) model.compile(optimizer='adam', loss='mse') return model My assumption is that this model will take data with shape (features, lats, lons, times), so for example if my geospatial grid is 180 x 360 and there are 100 time steps at each point, and I have 4 features per observation/sample, then the shape will be (4, 180, 360, 100). I assume that I will want the model to take arrays with shape (features, lats, lons, times) as input and be able to predict labels arrays with shape (labels, lats, lons, times) as output. I am first using a single variable as my label, but it might be interesting later to be able to have multivariate output as well (i.e. labels > 1). How should I best shape my data for input, and/or how to structure the model layers in a way that's most appropriate for this application?
has comment: http://stackoverflow.com/comment/92063196
score: 4
tagged with: lstm
has comment: http://stackoverflow.com/comment/92063361
has comment: http://stackoverflow.com/comment/92065079

http://stackoverflow.com/comment/91936272
type: QuestionComment
has text: I'm going to read about hash salting as you mentioned thank you again!
comment on: http://stackoverflow.com/q/52481731
score: 0
type: Comment

pyspark
tags question: http://stackoverflow.com/q/52579424
tags question: http://stackoverflow.com/q/52491603
tags question: http://stackoverflow.com/q/52525361
tags question: http://stackoverflow.com/q/52543717
tags question: http://stackoverflow.com/q/52478515
tags question: http://stackoverflow.com/q/52538454
tags question: http://stackoverflow.com/q/52557734
tags question: http://stackoverflow.com/q/52527545
tags question: http://stackoverflow.com/q/52558185
tags question: http://stackoverflow.com/q/52478031
tags question: http://stackoverflow.com/q/52586199
type: Tag
tags question: http://stackoverflow.com/q/52531457
tags question: http://stackoverflow.com/q/52468609
tags question: http://stackoverflow.com/q/52499853
tags question: http://stackoverflow.com/q/52565482
tags question: http://stackoverflow.com/q/52535303
tags question: http://stackoverflow.com/q/52522057
tags question: http://stackoverflow.com/q/52542903
tags question: http://stackoverflow.com/q/52565986
tags question: http://stackoverflow.com/q/52488570
tags question: http://stackoverflow.com/q/52440622
tags question: http://stackoverflow.com/q/52447348
tags question: http://stackoverflow.com/q/52564332
tags question: http://stackoverflow.com/q/52452271
tags question: http://stackoverflow.com/q/52570949
tags question: http://stackoverflow.com/q/52502816
tags question: http://stackoverflow.com/q/52526913
tags question: http://stackoverflow.com/q/52545458
tag name: pyspark
tags question: http://stackoverflow.com/q/52452810
tags question: http://stackoverflow.com/q/52451132
tags question: http://stackoverflow.com/q/52504505

http://stackoverflow.com/comment/92091234
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52578002
has text: There is a standard type for this in the Python standard library: [`collections.Counter()`](https://docs.python.org/3/library/collections.html#collections.Counter): * The `Counter` class is similar to bags or multisets in other languages.*, so use `mySet = Counter(myStr)`.
type: Comment

http://stackoverflow.com/q/52455355
answer count: 1
has body: I have a data set of Tweets encoded to UTF-8. The data is loaded to pandas datagram. This consists Twitter emojis as well (Ex: \xf0\x9f\x8e\xb5 ). I want to replace these emojis with a space or empty character using regex in python. The below is how I tried. But my regex pattern is marked in red and I get a warning. How can I remove these Twitter emojis? &gt;&gt;&gt; preparedData.head(5).to_dict() {'id': {0: 1042616899408945154, 1: 1042592536769044487, 2: 1042587702040903680, 3: 1042587263643930626, 4: 1042586780292276230}, 'date': {0: '2018-09-20', 1: '2018-09-20', 2: '2018-09-20', 3: '2018-09-20', 4: '2018-09-20'}, 'time': {0: '03:30:14', 1: '01:53:25', 2: '01:34:13', 3: '01:32:28', 4: '01:30:33'}, 'text': {0: "b'\\xf0\\x9f\\x8c\\xb9 are red, violets are blue, if you want to buy us \\xf0\\x9f\\x92\\x90, here is a CLUE \\xf0\\x9f\\x98\\x89 Our #flowerpowered eye &amp;amp; cheek palette is AL\\xe2\\x80\\xa6 ", 1: "b'\\xf0\\x9f\\x8e\\xb5Is it too late now to say sorry\\xf0\\x9f\\x8e\\xb5 #tartetalk #memes ", 2: "b'@JillianJChase Oh no! Please email your order # to social@tarte.com &amp;amp; we can help \\xf0\\x9f\\x92\\x95'", 3: 'b"@Danikins__ It\'s best applied with our buffer brush! \\xf0\\x9f\\x92\\x9c\\xc2\\xa0', 4: "b'@AdelaineMorin DEAD \\xf0\\x9f\\xa4\\xa3\\xf0\\x9f\\xa4\\xa3\\xf0\\x9f\\xa4\\xa3'"}, 'hasMedia': {0: 0, 1: 1, 2: 0, 3: 0, 4: 0}, 'hasHashtag': {0: 1, 1: 1, 2: 0, 3: 0, 4: 0}, 'followers_count': {0: 801745, 1: 801745, 2: 801745, 3: 801745, 4: 801745}, 'retweet_count': {0: 17, 1: 94, 2: 0, 3: 0, 4: 0}, 'favourite_count': {0: 181, 1: 408, 2: 0, 3: 0, 4: 14}} How I tried preparedData['url removed'] = re.sub(r''/[\x{1F600}-\x{1F64F}]/u'', ' ', preparedData['text']) print(preparedData.head(5).to_dict()) Warning This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91853282
tagged with: regex
linked to: http://stackoverflow.com/q/49207552
type: UnansweredQuestion
has title: Replace UTF-8 encoded Twitter emojis in python
type: Question
has comment: http://stackoverflow.com/comment/91853517
linked to: http://stackoverflow.com/q/39536390
has comment: http://stackoverflow.com/comment/91853187
has comment: http://stackoverflow.com/comment/91853435
has answer: http://stackoverflow.com/a/52455628

http://stackoverflow.com/a/52485837
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52485698
has body: Looks to me like you need to give os.rename() the absolute path to the file os.rename(file, os.path.join(folder_name, date + file_extension))
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91999870
type: Comment
type: AnswerComment
has text: we have trying to print multiple responses not store multiple responses. As we know session attribute is only for storing values not display or UI purpose.
comment on: http://stackoverflow.com/a/52515540
score: 0

http://stackoverflow.com/q/52477644
has comment: http://stackoverflow.com/comment/91896494
tagged with: python
has title: How to check the condition on row level with np.where
upvote count: 2
has answer: http://stackoverflow.com/a/52480447
type: Question
has body: I have following dataframe in pandas: code diff pv 0 -34 100 1 34 100 2 16 100 3 -50 150 My desired dataframe would be: code diff pv flag 0 -344 100 excess 1 344 100 short 2 2 100 pass 3 -5 150 pass 4 -200 150 excess 5 200 150 short logic for flag column short = diff is positive &gt; pv excess = diff is negative &lt; -pv (pv is taken to be negative) pass = if the diff is within range of +- PV How can I achieve this in pandas?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91896600
has answer: http://stackoverflow.com/a/52477786
answer count: 3
tagged with: pandas
score: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52477786
possible better answer: http://stackoverflow.com/a/52478123
has answer: http://stackoverflow.com/a/52478123

http://stackoverflow.com/comment/91823579
score: 1
has text: What is that going to improve?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52440403

http://stackoverflow.com/q/52502164
has answer: http://stackoverflow.com/a/52502252
accepted answer: http://stackoverflow.com/a/52502252
type: Question
upvote count: 2
tagged with: concatenation
has body: I want to concatenate two matrices based on its matching string-values in a specific column. For example, I am trying to combine: 1 2 a 3 4 b 5 6 c 7 8 d and 13 14 c 15 16 d 9 10 a 11 12 b Such as: 1 2 9 10 a 3 4 11 12 b 5 6 13 14 c 7 8 15 16 d Observe that the matrices aren't sorted in the same way order, but that I wish for the result to be sorted similar to the first one. Thanks!
has answer: http://stackoverflow.com/a/52503023
tagged with: string
has answer: http://stackoverflow.com/a/52504912
answer count: 3
has comment: http://stackoverflow.com/comment/91944941
tagged with: python
has title: Concatenate two matrices based on matching list in Python?
favorite count: 0
downvote count: 0
score: 2
possible better answer: http://stackoverflow.com/a/52504912
type: AnsweredQuestion

http://stackoverflow.com/q/52573594
has body: I have a list of tuples, some of which are nested: [(name,(6,9.0,2.4),link),(name,(7.8,9.0,5),link)...] I would like to un-nest the inner tuple for each item in the list, but preserve the outer tuple: [(name,6,9.0,2.4,link),(name,7.8,9.0,5,link)...] This is different from the solution to the question posed here in which the solution sought to preserve the pairs.
type: Question
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/52573607
linked to: http://stackoverflow.com/q/47431752
answer count: 1
downvote count: 0
favorite count: 0
tagged with: tuples
tagged with: python
has title: Flatten Nested Tuples
tagged with: python-3.x
tagged with: list
upvote count: 3
has answer: http://stackoverflow.com/a/52573607

http://stackoverflow.com/comment/91860598
type: Comment
score: 1
has text: Other than preserving the sets before the union or re-testing after the union, no.
type: AnswerComment
comment on: http://stackoverflow.com/a/52459139

http://stackoverflow.com/a/52488462
accepted answer of: http://stackoverflow.com/q/52435394
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52435394
has comment: http://stackoverflow.com/comment/91918328
has comment: http://stackoverflow.com/comment/102641947
type: AcceptedAnswer
downvote count: 0
has body: Your custom activation is written as a function of a single floating point number but you want to apply it to a whole tensor. The best way to do that is to use tf.where. Something like def custom_activation_4(x): orig = x x = tf.where(orig &lt; -6, tf.zeros_like(x), x) x = tf.where(orig &gt;= -6 and orig &lt; -4, (0.0078*x + 0.049), x) x = tf.where(orig &gt;= -4 and orig &lt; 0, (0.1205*x + 0.5), x) x = tf.where(orig &gt;= 0 and orig &lt; 4, (0.1205*x + 0.5), x) x = tf.where(orig &gt;= 4 and orig &lt; 6, (0.0078*x + 0.951), x) return tf.where(orig &gt;= 6, 1, x)

http://stackoverflow.com/comment/92039505
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52546310
has text: See also: https://stackoverflow.com/a/21838329/2681632

http://stackoverflow.com/comment/91954603
score: 0
type: Comment
has text: I greatly appreciate it, and thanks for fixing it. Looking at the new output we lost the sample names and additional columns. So how do we preserve that information too?
comment on: http://stackoverflow.com/a/52506607
type: AnswerComment

http://stackoverflow.com/comment/91837388
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52436929
has text: thanks for the reply! Still having an issue though- Seems its not picking up `aria-label`. Heres the error I am getting on line 4 `KeyError: 'aria-label'` Thoughts?
type: Comment

http://stackoverflow.com/comment/92139053
type: QuestionComment
type: Comment
has text: Have you tried a different port for your app? Since (1) it’s working without jupyter and (2) jupyter relies heavily on zmq but Flask doesn’t, I assume this is some incompatibility between your app and Jupyter (not a networking or firewall problem). But it worked fine in Jupyter for me. What happens if you try to connect to port 5005 or probe it before you launch your app? Anything there? Not sure why zmq would try to use port 5005 after your app launches though. By the way, does your app ever say that it’s running successfully, or does it go pretty quickly to that error?
comment on: http://stackoverflow.com/q/52457582
score: 1

http://stackoverflow.com/q/52574715
downvote count: 0
tagged with: websocket
linked to: http://stackoverflow.com/q/32445705
favorite count: 0
linked to: http://stackoverflow.com/q/12479054
tagged with: python
has comment: http://stackoverflow.com/comment/92103571
has answer: http://stackoverflow.com/a/52574739
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92103680
score: 2
linked to: http://stackoverflow.com/q/6623113
tagged with: tornado
has answer: http://stackoverflow.com/a/63751944
type: Question
answer count: 2
has title: Python Tornado: Sending websocket messages from another class
has body: Have an app that is using (Python 3.6) Tkinter &amp; Tornado. Would like it send a websocket message when a button is pressed. The sendSocket is in my class that handles the interface. I am able to open my sockets ok, and can send data into the socket handler ok. Additionally, it serves up my html file ok from my RequestHandler. I can see that my code hits the sendSocketMessage line ok. However, I never get the print from within the SocketHandler.send_message def. There are no errors in the console. def sendSocketMessage(self, data = "whatever"): print("sending") #WebSocketeer.send_message(data) ioloop.IOLoop.current().add_callback(WebSocketeer.send_message, data) class WebSocketeer(websocket.WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): print("got message: " + message) def on_close(self): print("WebSocket closed") @classmethod def send_message(self, message): print("sending message: " + message) for session_id, session in self.session.server._sessions._items.iteritems(): session.conn.emit(event, message) Code based off of these SO responses Send a websocket message: How do I send a websocket message in Tornado at will? Send to all clients: Is it possible to send a message to all active WebSocket connections? Using either node.js or python tornado websockets

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/52545611
tags question: http://stackoverflow.com/q/52549001
type: Tag
tags question: http://stackoverflow.com/q/52495742
tags question: http://stackoverflow.com/q/52438263
tags question: http://stackoverflow.com/q/52541055
tags question: http://stackoverflow.com/q/52557099
tags question: http://stackoverflow.com/q/52562051
tags question: http://stackoverflow.com/q/52488082
tags question: http://stackoverflow.com/q/52502176
tags question: http://stackoverflow.com/q/52458641
tags question: http://stackoverflow.com/q/52548797
tags question: http://stackoverflow.com/q/52533473

http://stackoverflow.com/a/52564900
score: 0
has body: Try the following: return sum([number for number in range(a,b)]) As said in the commentaries, sum is a python built-in function which, given an array, it returns the result of the addtion of all elements in it
answers question: http://stackoverflow.com/q/52564828
type: Answer
has comment: http://stackoverflow.com/comment/92069001
has comment: http://stackoverflow.com/comment/92067920
has comment: http://stackoverflow.com/comment/92067966
has comment: http://stackoverflow.com/comment/92067985

http://stackoverflow.com/q/52579346
downvote count: 0
accepted answer: http://stackoverflow.com/a/52581210
tagged with: keras
favorite count: 0
linked to: http://stackoverflow.com/q/44896719
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/52581210
tagged with: tensorflow
has body: i have a Tensorflow graph (output_graph.pb) that I obtained by doing transfer learning on Inception V3 following this tutorial. Now I need to extract the weights of the individual layers to import them onto the model created with Keras. I know that it is not possible to directly convert the graph from tensorflow into a keras model (see here).
type: Question
has title: Extract the weights from a TensorFlow graph to use them in Keras
tagged with: deep-learning
answer count: 1

http://stackoverflow.com/a/52504526
has comment: http://stackoverflow.com/comment/91953646
type: AcceptedAnswer
has body: Based on the documentation, for the DATE_FORMAT, you do not need to put the %. So you would actually want to simply put DATE_FORMAT = 'm/d/Y'
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91958017
accepted answer of: http://stackoverflow.com/q/52504203
answers question: http://stackoverflow.com/q/52504203
downvote count: 0
score: 1

http://stackoverflow.com/q/52434128
favorite count: 0
type: Question
has title: Add column of repeating sequential values
upvote count: 2
has answer: http://stackoverflow.com/a/52434148
accepted answer: http://stackoverflow.com/a/52434148
tagged with: pandas
answer count: 1
tagged with: python
has body: I have a dataframe that contains stacked monthly values and looks like: Value Month 0 0.09187 Jan 1 0.72878 Feb 2 0.92052 Mar 3 -1.86845 Apr 4 -1.16489 May 5 -0.61433 Jun 6 0.68008 Jul 7 -1.50555 Aug 8 -0.18985 Sep 9 -1.11380 Oct 10 -0.63838 Nov 11 0.37527 Dec 12 0.234216 Jan I would like to add a column of years, using a known range, so that the df looks like: Value Month Year 0 0.09187 Jan 1950 1 0.72878 Feb 1950 2 0.92052 Mar 1950 3 -1.86845 Apr 1950 4 -1.16489 May 1950 5 -0.61433 Jun 1950 6 0.68008 Jul 1950 7 -1.50555 Aug 1950 8 -0.18985 Sep 1950 9 -1.11380 Oct 1950 10 -0.63838 Nov 1950 11 0.37527 Dec 1950 12 0.234216 Jan 1951 I tried initializing a years list to apply to the column as: years = list(range(1950, 2000) df['Year'] = years * 12 But this produced Value Month Year 0 0.09187 Jan 1950 1 0.72878 Feb 1951 2 0.92052 Mar 1952 And so on. I've been unable to come up with any other approach
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/a/52573006
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92096749
has comment: http://stackoverflow.com/comment/92088976
answers question: http://stackoverflow.com/q/52571812
has comment: http://stackoverflow.com/comment/92096839
type: Answer
has comment: http://stackoverflow.com/comment/92083565
downvote count: 0
has comment: http://stackoverflow.com/comment/92088379
has comment: http://stackoverflow.com/comment/92096793
has comment: http://stackoverflow.com/comment/92096830
has comment: http://stackoverflow.com/comment/92090421
score: 2
has body: I read your problem statement as follows: given 2 points A and B, and a center O, find the angle A to B as the angle, positive if anticlockwise, between the vectors A→O and A→B. If my premises are correct, then you can find the angle between A→B and a horizontal, rightward line passing in A, find the angle between A→O and a horizontal, rightward line passing in A, find the angle A to B as the difference of said angles, normalize the result range so that it's between -π and +π. What I've said can be visualized as follows or in code (assuming a Point class with attributes x and y) AhAB = math.atan2((B.y-A.y), (B.x-A.x)) # -π &lt; AhAB ≤ +π AhAO = math.atan2((O.y-A.y), (O.x-A.x)) # -π &lt; AhA) ≤ +π AB = AhAB - AhAO # -2π &lt; AB ≤ +2π AB = AB + ( 2*math.pi if AB &lt; math.pi else (-2*math.pi if AB&gt; math.pi else 0)) Addendum Here it is a small code example, the position of the points is just similar to what you can see in the picture In [18]: from math import atan2, pi In [21]: class Point(): ...: def __init__(self, x, y): ...: self.x, self.y = x, y ...: def __repr__(self): ...: return '(%s, %s)'%(self.x, self.y) In [22]: A = Point(0.0, 0.0) In [23]: B = Point(-2.0, 2.0) In [24]: O = Point(0.0, -3.0) In [25]: AhAB = atan2((B.y-A.y), (B.x-A.x)) ; print(3/4, AhAB/pi) 0.75 0.75 In [26]: AhAO = atan2((O.y-A.y), (O.x-A.x)) ; print(-1/2, AhAO/pi) -0.5 -0.5 In [27]: AB = AhAB - AhAO ; print(5/4, AB/pi) 1.25 1.25 In [28]: AB = AB + ( 2*pi if AB &lt; pi else (-2*pi if AB&gt; pi else 0)) ; print(AB/pi) -0.75 In [29]: The last line normalize your result AB to be in the correct range -π &lt; AB ≤ π, adding or subtracting 2π that doesn't change the meaning of the measured angle.
has comment: http://stackoverflow.com/comment/92102497
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52571812

http://stackoverflow.com/comment/91829874
type: QuestionComment
type: Comment
has text: What was your reasoning for adding the `break`?
comment on: http://stackoverflow.com/q/52443482
score: 0

http://stackoverflow.com/q/52490405
accepted answer: http://stackoverflow.com/a/52490503
type: Question
tagged with: networkx
tagged with: graph
tagged with: matplotlib
answer count: 1
downvote count: 0
has title: Edges don't show in a graph using Networkx - Python
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91921563
tagged with: python
has body: I am plotting a directed graph in python using networkx and matplotlib. However, not all edges are visible. The nodes are so close to each other that it doesn't show a path between two nodes. Code: import networkx as nx resultNodes = ['P0', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9'] resultEdges = [('P0', 'P4'), ('P0', 'P2'), ('P0', 'P1'), ('P1', 'P7'), ('P1', 'P8'), ('P1', 'P2'), ('P2', 'P3'), ('P4', 'P5'), ('P4', 'P6'), ('P5', 'P6'), ('P9', 'P2'), ('P9', 'P7'), ('P9', 'P1')] G=nx.DiGraph() G.add_nodes_from(resultNodes) G.add_edges_from(resultEdges) print("Nodes of graph: ") print(G.nodes()) print("Edges of graph: ") print(G.edges()) nx.draw(G,with_labels=True,font_size=15,node_color='yellowgreen',node_size=1000)
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/91921518
has answer: http://stackoverflow.com/a/52490503

http://stackoverflow.com/q/52474035
accepted answer: http://stackoverflow.com/a/52475538
tagged with: resampling
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
has title: Pandas Resampling For Loop Performance Issue
has answer: http://stackoverflow.com/a/52475538
tagged with: performance
has comment: http://stackoverflow.com/comment/91890342
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have the following DataFrame: df = pd.DataFrame({"id": [0]*5 + [1]*5, "time": ['2015-01-01', '2015-01-03', '2015-01-04', '2015-01-08', '2015-01-10', '2015-02-02', '2015-02-04', '2015-02-06', '2015-02-11', '2015-02-13'], 'hit': [0,3,8,2,5, 6,12,0,7,3]}) df.time = df.time.astype('datetime64[ns]') df = df'id', 'time', 'hit' df Output: id time hit 0 0 2015-01-01 0 1 0 2015-01-03 3 2 0 2015-01-04 8 3 0 2015-01-08 2 4 0 2015-01-10 5 5 1 2015-02-02 6 6 1 2015-02-04 12 7 1 2015-02-06 0 8 1 2015-02-11 7 9 1 2015-02-13 3 And a function to perform resampling: def subset(df): '''select first x rows''' return df.iloc[:14] def dailyCount(df, member_id, values, time): '''Transform a time-series df into 7 daily count per group''' # container for resulting dataframe ts = pd.DataFrame() for i in df.member_id.unique(): # prepare a series and upsample it within the same id chunk = pd.Series(df.loc[df.member_id == i, values]) #print(chunk) chunk = chunk.resample('1D').asfreq() # create dataframe and construct some additional columns chunk = pd.DataFrame(chunk, columns=[values]).reset_index().fillna(0) chunk[values] = chunk[values].astype(int) chunk[member_id] = i chunk['daily_count'] = chunk.groupby(member_id).cumcount() + 1 # accumulate id-wise dataframes 1 by 1 vertically ts = pd.concat([ts, chunk], axis=0, ignore_index=True) ts = ts.set_index([member_id, time]) ts = ts.reset_index(level=0).groupby(member_id).apply(subset).drop(member_id, axis=1).reset_index().drop(time, axis=1).set_index([member_id,'daily_count']).unstack().fillna(0) #ts = ts.reset_index().drop(columns=time).set_index([member_id,'daily_count']).unstack().fillna(0) ts.columns = pd.Index(['dailyCount_' + e[0] + '_' + str(e[1]) for e in ts.columns.tolist()]) ts = ts.astype(np.int32)#.reset_index() return ts Input: df.rename(columns={'id': 'member_id'}, inplace=True) df = df.set_index('time') dailyCount(df, 'member_id', 'hit', 'time') Output: dailyCount_hit_1 dailyCount_hit_2 dailyCount_hit_3 dailyCount_hit_4 daily…
score: 1
favorite count: 0

http://stackoverflow.com/a/52527697
answers question: http://stackoverflow.com/q/52527265
has body: simply: categories = [0.6, 0.7, 0.8, 0.9] cat = [categories[i]&lt;x and categories[i+1]&gt;=x for i in range(0, len(categories)-1)].index(True) + 1
score: 0
type: Answer

http://stackoverflow.com/q/52574989
tagged with: pandas
answer count: 1
has title: How to load the images with class labels from a single directory into Keras model using a dataframe containing filenames and labels?
favorite count: 0
accepted answer: http://stackoverflow.com/a/52578673
has body: I have two separate folders "train_images" and "val_images". I have all the images inside these two folders. I am doing a categorical classification using DenseNet121 model. I have two different y_df (dataframe) for training and validation. I know about flow_from_directory but for that I need to create different subforlders inside each "train_images" and "val_images" based on classes. I am willing to to know if I don't want to create those subforlders and don't use flow_from_directory, how do I pass those images into the model? I am using Keras with Tensorflow as the backend.
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
score: 1
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/52578673

http://stackoverflow.com/comment/91866079
has text: Why-ever not? Did you try it?
type: Comment
comment on: http://stackoverflow.com/a/52461906
score: 0
type: AnswerComment

http://stackoverflow.com/q/52532473
has comment: http://stackoverflow.com/comment/92004257
has comment: http://stackoverflow.com/comment/92004335
has comment: http://stackoverflow.com/comment/92004447
has answer: http://stackoverflow.com/a/52532552
answer count: 1
has comment: http://stackoverflow.com/comment/92004377
accepted answer: http://stackoverflow.com/a/52532552
has body: I am creating a game on python which requires names of songs to have a few characters removed from them. Here is an example of one: abbasong = ('Dancing Queen by ABBA') removed = abbasong.replace("d", "q", "") print removed However, when I run the program, the computer tells me I have a syntax error, and highlights removed. Does anyone know where I am going wrong? This is the error I am receving: Error image
has title: Variables not being recognised on python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/92004255
favorite count: 0
type: Question
downvote count: 2
tagged with: python
score: -2

http://stackoverflow.com/q/52453777
has answer: http://stackoverflow.com/a/52454002
possible better answer: http://stackoverflow.com/a/52454002
has body: I want to start a simply scrapy project. It is a python project from visual studio. The VS is running in administration mode. Unfortunately, parse(...) is never called, but should.. import scrapy from scrapy.crawler import CrawlerProcess import logging class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://blog.scrapinghub.com'] def parse(self, response): for title in response.css('.post-header&gt;h2'): yield {'title': title.css('a ::text').extract_first()} for next_page in response.css('div.prev-post &gt; a'): yield response.follow(next_page, self.parse) logging.error("this should be printed") process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(BlogSpider) process.start() print("ready") EDIT: my output: 2018-09-22 08:23:02 [scrapy.utils.log] INFO: Scrapy 1.5.1 started (bot: scrapybot) 2018-09-22 08:23:02 [scrapy.utils.log] INFO: Versions: lxml 4.2.5.0, libxml2 2.9.5, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, Twisted 18.7.0, Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)], pyOpenSSL 18.0.0 (OpenSSL 1.1.0i 14 Aug 2018), cryptography 2.3.1, Platform Windows-10-10.0.17134-SP0 2018-09-22 08:23:02 [scrapy.crawler] INFO: Overridden settings: {'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'} 2018-09-22 08:23:02 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] ready As note: Twisted is used from https://www.lfd.uci.edu/~gohlke/pythonlibs/.
accepted answer: http://stackoverflow.com/a/52456195
tagged with: python
has title: Scrapy: Simple Project
tagged with: scrapy
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52456195
score: 0
answer count: 2

http://stackoverflow.com/comment/91949392
comment on: http://stackoverflow.com/a/52481403
type: AnswerComment
has text: Please see my most recent code (updated). I had to add a while loop otherwise the circle(s) wouldn't continuously animate. Now I'm back where I started but with different code, one circle moving at a time. I think this is because the while loop keeps going and the program never reaches the next checkMouse, but the while loop is needed for continuous movement, causing the animation. How can I have more circles spawn and animate from the code I've left above? Thank you.
score: 0
type: Comment

http://stackoverflow.com/comment/129602511
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52517831
has text: How do you make it a certain percentage of the window height and width?

http://stackoverflow.com/a/52477162
type: Answer
has comment: http://stackoverflow.com/comment/91954517
answers question: http://stackoverflow.com/q/52475578
has body: It's because of softmax's properties -softmax function maximazes high values. Then, there's only one maximum for softmax function in most cases. Softmax: You can get two maximums for the softmax, if input of softmax contains two equal higest values. It is possible in a very rare case when the same values (logits) were produced by convolutional filters. Otherwise, there's only one maximum, then, one class predicted. Example from github: In a case of the last image, softmax produses two similar values. But you shouldn't expect that all the time. Check an output of Conv2D layer with linear activation, if you want to check this assumption. model = Sequential() model.add(Conv2D(32, kernel_size=(1, 2048), strides=(1, 1), activation='linear', input_shape=input_shape, kernel_regularizer=keras.regularizers.l1(L1regularization), kernel_constraint=keras.constraints.non_neg())) model.add(Activation('softmax')) is's the same architecture, but you get output of Conv2D.
score: 0
has comment: http://stackoverflow.com/comment/91955739

http://stackoverflow.com/comment/118137520
score: 0
type: Comment
comment on: http://stackoverflow.com/a/66818656
type: AnswerComment
has text: How is this different from @Monica’s answer?

http://stackoverflow.com/a/52560615
type: Answer
has body: You could use list comprehension: [[i,j] for i in list_1 for j in list_2] Output: [[1, 'one'], [1, 'two'], [1, 'three'], [1, 'four'], [2, 'one'], [2, 'two'], [2, 'three'], [2, 'four'], [3, 'one'], [3, 'two'], [3, 'three'], [3, 'four'], [4, 'one'], [4, 'two'], [4, 'three'], [4, 'four']] Or you could use itertools.product to get a list of tuples: import itertools list(itertools.product(list_1, list_2)) Output: [(1, 'one'), (1, 'two'), (1, 'three'), (1, 'four'), (2, 'one'), (2, 'two'), (2, 'three'), (2, 'four'), (3, 'one'), (3, 'two'), (3, 'three'), (3, 'four'), (4, 'one'), (4, 'two'), (4, 'three'), (4, 'four')]
answers question: http://stackoverflow.com/q/52560557
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52560557

http://stackoverflow.com/q/52583395
has comment: http://stackoverflow.com/comment/92102150
has comment: http://stackoverflow.com/comment/92127628
has title: Download a file to heroku process it and send as an attachment
has comment: http://stackoverflow.com/comment/92102093
has comment: http://stackoverflow.com/comment/92102078
has comment: http://stackoverflow.com/comment/92102292
type: Question
has comment: http://stackoverflow.com/comment/92121292
has comment: http://stackoverflow.com/comment/92102318
has comment: http://stackoverflow.com/comment/92101918
score: 0
has comment: http://stackoverflow.com/comment/92102157
has comment: http://stackoverflow.com/comment/92102372
has body: I'm trying to do the following: Download a pdf file from S3 to my heroku. Process the pdf. Email the pdf as an attachment. Is it possible? If yes, could you please give me a tip how? I'm running Django and pdf is about 1MB. This is my processing part: from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from reportlab.lib.colors import HexColor import os, sys import requests from io import BytesIO URL = "https://domainname.com/sample.pdf" response=requests.get(URL) p = BytesIO(response.content) p.seek(0, os.SEEK_END) def watermark_product(watermark_text, input_file_path, output_file_path): c = canvas.Canvas("watermark.pdf") c.setFont("Helvetica", 24) c.setFillGray(0.5,0.5) c.saveState() c.translate(500,100) c.rotate(45) c.drawCentredString(0, 300, watermark_text) c.restoreState() c.save() input_file = PdfFileReader(input_file_path) output_writer = PdfFileWriter() total_pages = input_file.getNumPages() for single_page in range(total_pages): page = input_file.getPage(single_page) watermark = PdfFileReader("watermark.pdf") page.mergePage(watermark.getPage(0)) output_writer.addPage(page) with open(output_file_path, "wb") as outputStream: output_writer.write(outputStream) os.remove("watermark.pdf") watermark_product('testtesatd', p, 'w1.pdf') EDIT: I've managed to keep the pdf file in memory.
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92102024
tagged with: heroku
has comment: http://stackoverflow.com/comment/92102010
tagged with: amazon-s3

http://stackoverflow.com/a/52476076
answers question: http://stackoverflow.com/q/52475010
has comment: http://stackoverflow.com/comment/91900680
has comment: http://stackoverflow.com/comment/91895484
has comment: http://stackoverflow.com/comment/91894320
has body: Your data: df = pd.DataFrame({'order':['A', 'B', 'C', 'D', 'E', 'F'],'quantity':[1,1,2,3,3,4]}) Solution: df = pd.DataFrame(np.concatenate(df.apply(lambda x: [x[0]] * x[1], 1).as_matrix()), columns=['order']) df['quantity'] = 1 df['group'] = sorted(range(0, len(df)/3, 1) * 4)[0:len(df)] Output: order quantity group 0 A 1 0 1 B 1 0 2 C 1 0 3 C 1 0 4 D 1 1 5 D 1 1 6 D 1 1 7 E 1 1 8 E 1 2 9 E 1 2 10 F 1 2 11 F 1 2 12 F 1 3 13 F 1 3 Then groupby and sum. df.groupby(['group', 'order']).sum() Output: quantity group order 0 A 1 B 1 C 2 1 D 3 E 1 2 E 2 F 2 3 F 2 You can use reset_index() after that, if you want. I hope it helps. Should I explain the solution? Does it work for you?
accepted answer of: http://stackoverflow.com/q/52475010
type: Answer
has comment: http://stackoverflow.com/comment/91900341
has comment: http://stackoverflow.com/comment/91900493
has comment: http://stackoverflow.com/comment/91896240
has comment: http://stackoverflow.com/comment/91903991
has comment: http://stackoverflow.com/comment/91902943
score: 2
has comment: http://stackoverflow.com/comment/91910785
downvote count: 0
has comment: http://stackoverflow.com/comment/91898637
has comment: http://stackoverflow.com/comment/91901416
has comment: http://stackoverflow.com/comment/91900391
upvote count: 2
has comment: http://stackoverflow.com/comment/91900996
has comment: http://stackoverflow.com/comment/91901265
type: AcceptedAnswer

http://stackoverflow.com/comment/91997451
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52529026
has text: The `()` are redundant as the `*` is higher precedence that the `+`

http://stackoverflow.com/q/52574371
has comment: http://stackoverflow.com/comment/92140655
has body: I'm writing a program for research/analysis using python in VS Code. The debugger crashes whenever it reaches an import matplotlib statement. Running the code normally without the debugger works fine. The most basic program I've tried to replicate this problem is import numpy as np import matplotlib print('Hello World!') This crashes the debugger at line 2. Breakpoint placed before this line work as normal. I haven't changed anything in the config file for the debugger. Any thoughts on what might be causing this issue or what to fix?
type: Question
has comment: http://stackoverflow.com/comment/92084870
tagged with: visual-studio-code
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92085045
answer count: 1
has comment: http://stackoverflow.com/comment/92133848
has comment: http://stackoverflow.com/comment/92084765
favorite count: 0
has comment: http://stackoverflow.com/comment/92085160
has title: Python code debugging fails when file contains import matplotlib statement (VS Code and Pycharm)
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92085751
tagged with: python
tagged with: vscode-debugger
has answer: http://stackoverflow.com/a/52610314
has comment: http://stackoverflow.com/comment/92084776

http://stackoverflow.com/q/52442106
score: 0
answer count: 1
has title: How to save form to database only if content meets certain criteria
accepted answer: http://stackoverflow.com/a/52442193
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-forms
has body: I am looking for a way to check data submitted from a form whether it meets certain criteria – not whether the data is valid, but whether, for example, a certain question is answered 'yes' or 'no', and only if the response is 'yes', should the data be saved to the database. If the submitted data does not meet the criteria, then it should not be saved to the database and a message should be displayed notifying the user. My code thus far: I have a model that stores participant information: class Participant(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() has_health_cover = models.CharField( choices=( ('0','No'), ('1','Yes) ), default='0', max_length=1 ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) date_registered = models.DateTimeField(default=timezone.now) The model is created using a Modelform: class ParticipantRegisterForm(forms.ModelForm): class Meta: model = Participant fields = [ 'first_name', 'last_name', 'date_of_birth', 'has_health_cover', ] Rendered using a generic CreateView object: class ParticipantRegisterView(LoginRequiredMixin, CreateView): model = Participant form_class = ParticipantRegisterForm template_name = 'participants/register.html' def form_valid(self, form): form.instance.provider = self.request.user return super().form_valid(form) I am not sure how to go about taking the POST request data, determining whether the variable has_health_cover was a 0 (No) or a 1 (Yes), and to only save the data to the Participant database should has_private_health == 0. If has_private_health == 1 then the data should not be saved, and a flash message should appear with a message notifying the user the 'Participant is ineligible'. I have flash messages already setup in the base .html template.
type: Question
has answer: http://stackoverflow.com/a/52442193

http://stackoverflow.com/comment/92077859
comment on: http://stackoverflow.com/q/52570452
type: QuestionComment
score: 0
has text: I don't get how your code relates to the question, but it sounds like you need to use a format string: `"{:03}_{}".format(23, "name")` evaluates to `"023_name"`
type: Comment

azure-data-factory
tags question: http://stackoverflow.com/q/52479935
tag name: azure-data-factory
type: Tag

http://stackoverflow.com/comment/92043881
has text: The get_id function belongs to an imported package and i need to use it in this specific way.
comment on: http://stackoverflow.com/q/52552440
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52575718
upvote count: 1
has body: You are trying to do something that is not supported. External processes can only emit, they are not recipients. If you need to emit and receive in the external process, then I recommend that you move the Socket.IO server entirely to this process.
downvote count: 0
answers question: http://stackoverflow.com/q/52571093
type: Answer
score: 1

http://stackoverflow.com/a/52437450
upvote count: 1
answers question: http://stackoverflow.com/q/52437272
has body: with collections.defaultdict you can remove the checks whether the key exist in the dictionary: from collections import defaultdict def nested_dict(): return defaultdict(nested_dict) def toNested(data): nd = nested_dict() for aa in data: nd[aa['company_id']][aa['year'].year][aa['month'].month][aa['gstin_code']] = aa['price_effective'] return nd import pprint pp = pprint.PrettyPrinter(indent=4) pp.pprint( toNested(data) )
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/92449778
type: Comment
has text: are you sure using apache as a reverse proxy works in my case? What I understood from the links you added is that it's adding headers to outgoing response from apache not incoming ones like I need.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52587884

http://stackoverflow.com/comment/92089307
comment on: http://stackoverflow.com/a/52576954
type: AnswerComment
score: 0
type: Comment
has text: Thank you so much, it's exactly what I need.

http://stackoverflow.com/a/52516590
type: AcceptedAnswer
has body: The process, started with Start-Process, closes, when an SSH channel that started it is closed. The "exec" channel (exec_command) closes immediately after the powershell process finishes, what is almost instantaneous. So I believe that your python process is actually started, but is taken down almost immediately. It should help, if you add -Wait switch to Start-Process. stdin, stdout, stderror = ssh_client.exec_command("powershell Start-Process python -ArgumentList \"C:\Users\myuser\python_script.py\",\"-param1\", \"param1\",\"-param2\",\"param2\" -Verb \"runAs\" -Wait") It "works" from an SSH terminal, because the terminal (SSH "shell" channel) stays open after powershell process finishes. But if you close the terminal before the python process finishes, it would terminate it too. Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52512645
score: 1
accepted answer of: http://stackoverflow.com/q/52512645
upvote count: 1

http://stackoverflow.com/q/52508124
has comment: http://stackoverflow.com/comment/91958819
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91956657
has title: Error when dealing with file paths in windows and Python
score: 0
has comment: http://stackoverflow.com/comment/91958715
has comment: http://stackoverflow.com/comment/91957754
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91956591
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/91958740
has comment: http://stackoverflow.com/comment/91956611
has body: I am trying to create a directory with a variable as the name, with a folder inside it (also a variable). Currently, this is what I have: ### sort and copy files to backup if event.event_type == 'created': #modFile = event.src_path[:-1] chainFolderOut = backupDir + event.src_path print(chainFolderOut) print(event.src_path) chainFolderIn = chainFolderOut + '/' + str(timestamp) print(chainFolderIn) os.mkdir(chainFolderOut) os.mkdir(chainFolderIn) This is the error I get when trying to run the program: /Users/Spencer/Desktop/backupTest/Users/Spencer/Desktop/TestWatchdog\New Text Document (4).txt /Users/Spencer/Desktop/TestWatchdog\New Text Document (4).txt /Users/Spencer/Desktop/backupTest/Users/Spencer/Desktop/TestWatchdog\New Text Document (4).txt/1537919413.7257273 Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\Spencer\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Spencer\AppData\Local\Programs\Python\Python37\lib\site-packages\watchdog\observers\api.py", line 199, in run self.dispatch_events(self.event_queue, self.timeout) File "C:\Users\Spencer\AppData\Local\Programs\Python\Python37\lib\site-packages\watchdog\observers\api.py", line 368, in dispatch_events handler.dispatch(event) File "C:\Users\Spencer\AppData\Local\Programs\Python\Python37\lib\site-packages\watchdog\events.py", line 322, in dispatch self.on_any_event(event) File "C:\Users\Spencer\Desktop\tesseractAlpha1.0\tesseractAlpha2.0.py", line 53, in on_any_event os.mkdir(chainFolderOut) FileNotFoundError: [WinError 3] The system cannot find the path specified: '/Users/Spencer/Desktop/backupTest/Users/Spencer/Desktop/TestWatchdog\\New Text Document (4).txt' What am I doing wrong here? event.src_path is the variable for full path of the file I want to deal with btw. I have no idea where that last slash is coming from before the file's name. Ultimately, I am creating a program that watches for file changes in …

http://stackoverflow.com/q/52543644
type: Question
answer count: 2
has body: Please read this question carefully, considering all aspects, before marking it as duplicate. I also had a stack account but seem to have forgotten on which email, thus a brand new one! I have a df with multiple columns and millions (literally) rows. Here's an example so I can be more specific about my question without revealing sensitive data: a b c d ... AAA BBB --- --- --- --- ... hf4r 192 --- --- --- --- ... h23g 103 --- --- --- --- ... 9fyd 7 --- --- --- --- ... hf4r 121 --- --- --- --- ... hf4r 32 --- --- --- --- ... h23g 12 ............... ............ I want to only keep those rows whose BBB value is larger than or equal to the 80th percentile of BBBs for their specific AAA; for all AAA. I work with pandas. I tried in-line fors and .querys and just regular calls, but I must be doing something wrong because each time my compiler doesn't like one thing or the other. Will appreciate any insights.
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/52543698
score: 0
type: UnansweredQuestion
has title: How to keep values over a percentile based on a condition on another column in pandas dataframe
tagged with: python
has answer: http://stackoverflow.com/a/52544214
tagged with: quantile
tagged with: dataframe

http://stackoverflow.com/a/52453506
type: Answer
downvote count: 0
score: 1
has body: pandas.Series.str.findall df.join( df.item.str.findall('(a|c)') .str.join('|') .str.get_dummies().add_prefix('contains_') ) id item contains_a contains_c 0 1 a,b,c 1 1 1 2 c,d,e 0 1 2 3 a,b 1 0
upvote count: 1
answers question: http://stackoverflow.com/q/52452996

on-the-fly
type: Tag
tag name: on-the-fly
tags question: http://stackoverflow.com/q/52550614

http://stackoverflow.com/comment/92059872
type: AnswerComment
comment on: http://stackoverflow.com/a/52560162
type: Comment
has text: SonarCube has no FP (functional programming) specific analysis. Custom checks can be added but I am searching a standalone tool.
score: 1

http://stackoverflow.com/comment/92050478
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52554798
has text: Yep, so the dnn initializations are all the same. Both are using the same model dat files.
score: 0

http://stackoverflow.com/comment/92032583
type: QuestionComment
score: 4
has text: Aside from newline handling, the big obvious thing is that Python 3 is doing Unicode decoding. That's pretty expensive.
comment on: http://stackoverflow.com/q/52545269
type: Comment

http://stackoverflow.com/comment/91988172
type: AnswerComment
comment on: http://stackoverflow.com/a/52524239
has text: this is almost comical that i just took it at face value that it wouldn't. i know better. even after doing that it's not working. It's just a blank sheet after running
score: 0
type: Comment

numpy-ndarray
tags question: http://stackoverflow.com/q/52443777
tags question: http://stackoverflow.com/q/52556903
tags question: http://stackoverflow.com/q/52582899
tags question: http://stackoverflow.com/q/52561715
tags question: http://stackoverflow.com/q/52465856
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/52539461
type: Tag
tags question: http://stackoverflow.com/q/52521358
tags question: http://stackoverflow.com/q/52449648

http://stackoverflow.com/q/52534717
score: 2
type: AnsweredQuestion
tagged with: autoencoder
upvote count: 2
tagged with: machine-learning
type: Question
has body: I am building a 5-layer autoencoder with Keras. I made the model that maps from input to output which was fine. I built another model that maps from input to the latent coded vector which worked fine. However, I then tried to make a decoding model that maps from the latent coded vector to the output which did not work. I know that first I should be making an input layer for the decoded model that makes that shape but I can't figure out how to get my coded layers data as an input for the decoded model and to let it map from the coded vector to the final layer. from keras.layers import Input, Dense from keras.models import Model from keras.datasets import mnist import numpy as np (x_train, _), (x_test, _) = mnist.load_data() # Prepare data and normalize x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = x_train.reshape(len(x_train), -1) x_test = x_test.reshape(len(x_test), -1) input_size = 784 hidden_size = 128 coded_size = 64 x = Input(shape=(input_size,)) hidden_1 = Dense(hidden_size, activation='relu')(x) coded =Dense(coded_size, activation='relu')(hidden_1) hidden_2 = Dense(hidden_size, activation='relu')(coded) r = Dense(input_size, activation='sigmoid')(hidden_2) autoencoder = Model(inputs=x, outputs=r) encoder = Model(inputs=x, outputs=coded) decoder_input = Input(shape=(coded_size,)) # should do this, but don't know how to connect it below decoder = Model(inputs=coded, output=r)
has comment: http://stackoverflow.com/comment/114680563
has title: reuse middle layer as input for another model in Keras
answer count: 1
downvote count: 0
tagged with: neural-network
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/52535460
accepted answer: http://stackoverflow.com/a/52535460
tagged with: python

http://stackoverflow.com/q/52566234
answer count: 2
tagged with: ros
has comment: http://stackoverflow.com/comment/92087105
downvote count: 0
possible better answer: http://stackoverflow.com/a/52571710
has comment: http://stackoverflow.com/comment/92077933
favorite count: 0
has comment: http://stackoverflow.com/comment/92082294
tagged with: python
tagged with: cmake
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92082621
score: 2
has comment: http://stackoverflow.com/comment/92082466
has title: Cmake not detecting boost-python when installing ROS
upvote count: 2
has comment: http://stackoverflow.com/comment/92070177
tagged with: boost
has answer: http://stackoverflow.com/a/52574402
type: Question
linked to: http://stackoverflow.com/q/13604090
linked to: http://stackoverflow.com/q/50919160
accepted answer: http://stackoverflow.com/a/52574402
has comment: http://stackoverflow.com/comment/92080677
has answer: http://stackoverflow.com/a/52571710
has body: I have been trying to install ROS on my Mac and have gotten around the errors with different libraries depending on different versions of boost. However, it seems that one library is not even detecting boost-python. Here is the error I get: CMake Error at /usr/local/share/cmake-3.12/Modules/FindBoost.cmake:2048 (message): Unable to find the requested Boost libraries. Boost version: 1.67.0 Boost include path: /usr/local/include Could not find the following static Boost libraries: boost_python Some (but not all) of the required Boost libraries were found. You may need to install these additional Boost libraries. Alternatively, set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost. Call Stack (most recent call first): CMakeLists.txt:8 (find_package) -- skipping nosetests(parser.py) in project 'camera_calibration_parsers' -- Configuring incomplete, errors occurred! See also "/Users/redacted/ros_catkin_ws/build_isolated/camera_calibration_parsers/CMakeFiles/CMakeOutput.log". &lt;== Failed to process package 'camera_calibration_parsers': Command '['/Users/redacted/ros_catkin_ws/install_isolated/env.sh', 'cmake', '/Users/redacted/ros_catkin_ws/src/image_common/camera_calibration_parsers', '-DCATKIN_DEVEL_PREFIX=/Users/redacted/ros_catkin_ws/devel_isolated/camera_calibration_parsers', '-DCMAKE_INSTALL_PREFIX=/Users/redacted/ros_catkin_ws/install_isolated', '-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_FIND_FRAMEWORK=LAST', '-DBoost_USE_STATIC_LIBS=ON', '-G', 'Unix Makefiles']' returned non-zero exit status 1 Reproduce this error by running: ==&gt; cd /Users/redacted/ros_catkin_ws/build_isolated/camera_calibration_parsers &amp;&amp; /Users/redacted/ros_catkin_ws/install_isolated/env.sh cmake /Users/redacted/ros_catkin_ws/src/image_common/camera_calibration_parsers -DCATKIN_DEVEL_PREFIX=/Users/redacted/ros_catkin_ws/devel_isolated/camera_calibration_parsers -DCMAKE_INSTALL_PREFIX=/Users/redacted/ros_catkin_ws/install_isolated -DCMAKE…
tagged with: boost-python

http://stackoverflow.com/q/52548299
has comment: http://stackoverflow.com/comment/92036381
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92036073
has comment: http://stackoverflow.com/comment/92036453
has answer: http://stackoverflow.com/a/52548365
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52548358
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/92036471
linked to: http://stackoverflow.com/q/8270092
linked to: http://stackoverflow.com/q/3739909
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52548363
has comment: http://stackoverflow.com/comment/92036454
has comment: http://stackoverflow.com/comment/92037448
tagged with: python-3.5
tagged with: python-3.6
score: 0
duplicate of: http://stackoverflow.com/q/3739909
has body: Basically, I'm trying to do a code in Python where a user inputs a sentence. However, I need my code to remove ALL whitespaces (e.g. tabs, space, index, etc.) and print it out. This is what I have so far: def output_without_whitespace(text): newText = text.split("") print('String with no whitespaces: '.join(newText)) I'm clear that I'm doing a lot wrong here and I'm missing plenty, but, I haven't been able to thoroughly go over splitting and joining strings yet, so it'd be great if someone explained it to me. This is the whole code that I have so far: text = input(str('Enter a sentence: ')) print(f'You entered: {text}') def get_num_of_characters(text): result = 0 for char in text: result += 1 return result print('Number of characters: ', get_num_of_characters(text)) def output_without_whitespace(text): newtext = "".join(text.split()) print(f'String without whitespaces: {newtext}') I FIGURED OUT MY PROBLEM! I realize that in this line of code. print(f'String without whitespaces: {newtext}') It's supposed to be. print('String without whitespaces: ', output_without_whitespace(text)) I realize that my problem as to why the sentence without whitespaces was not printing back out to me was, because I was not calling out my function!
tagged with: python-3.3
has title: How can I output a string excluding ALL whitespaces?
has answer: http://stackoverflow.com/a/52548342
favorite count: 0

http://stackoverflow.com/q/52480681
has comment: http://stackoverflow.com/comment/91918651
answer count: 3
tagged with: cx-oracle
downvote count: 0
favorite count: 0
has body: I'm trying to write a simple python script, that will connect to my oracle database as an externally identified user, then do some stuff. I can't get past the connection though. If I hard code the user/password in the connection string, then it connects just fine and prints out the DB version as expected, so the format of the connect string must be valid import cx_Oracle con = cx_Oracle.connect('&lt;user&gt;','&lt;password&gt;','&lt;service name&gt;') print (con.version) con.close() Now the os user is externally identified, as shown here: sqlplus / SQL*Plus: Release 11.2.0.4.0 Production on Mon Sep 24 14:28:01 2018 Copyright (c) 1982, 2013, Oracle. All rights reserved. Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP, Data Mining and Real Application Testing options SQL&gt; So from what I have seen when searching, I should be able to run this code to connect: import cx_Oracle con = cx_Oracle.connect('','','&lt;service name&gt;') print (con.version) con.close() But this gives me the error: Traceback (most recent call last): File "test.py", line 5, in &lt;module&gt; con = cx_Oracle.connect('','','&lt;service name&gt;') cx_Oracle.DatabaseError: ORA-01017: invalid username/password; logon denied Can anyone help me out here, this feels like it should be simple! Thanks
upvote count: 2
has comment: http://stackoverflow.com/comment/91924318
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52488618
tagged with: python
score: 2
type: Question
has answer: http://stackoverflow.com/a/52538145
has answer: http://stackoverflow.com/a/52526742
has title: Unable to connect as externally identified user using python3 and cx_Oracle on Linux

http://stackoverflow.com/a/52462847
has comment: http://stackoverflow.com/comment/91867850
answers question: http://stackoverflow.com/q/52462801
downvote count: 0
has comment: http://stackoverflow.com/comment/91877106
has comment: http://stackoverflow.com/comment/91875212
has comment: http://stackoverflow.com/comment/91867804
type: Answer
has comment: http://stackoverflow.com/comment/91867983
has comment: http://stackoverflow.com/comment/91867986
has comment: http://stackoverflow.com/comment/91867841
has comment: http://stackoverflow.com/comment/91867863
score: 1
has comment: http://stackoverflow.com/comment/91867887
has comment: http://stackoverflow.com/comment/91867833
upvote count: 1
has comment: http://stackoverflow.com/comment/91877035
has body: You can search for the month, day, and year by searching for letters with a possible ".": import re, datetime months = {b:a for a, b in enumerate(['Jan.', 'Feb.', 'March', 'April', 'May', 'June', 'July', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.'], 1)} def convert_date(d:str) -&gt; str: month, day, year = d.split() return datetime.datetime(int(year), months[month], int(day)) data = ['Date first available at Amazon.ca: Nov. 23 2017', 'Date first available at Amazon.ca: March 27 2017', 'Date first available at Amazon.ca: March 6 2018'] new_data = [re.findall('[a-zA-Z]+\.*\s\d+\s\d+$', i) for i in data] final_results = [convert_date(i[0]) for i in new_data if i] Output: [datetime.datetime(2017, 11, 23, 0, 0), datetime.datetime(2017, 3, 27, 0, 0), datetime.datetime(2018, 3, 6, 0, 0)] Timings: import time def timeit(f): _t1 = time.time() _ = f() print(f'{f.__name__}: completed in {time.time()-_t1}') @timeit def ajax1234(): new_data = [re.findall('[a-zA-Z]+\.*\s\d+\s\d+$', i) for i in data] @timeit def anthony(): t = [re.findall('(Jan.|Feb.|March|April|May|June|July|Aug.|Sept.|Oct.|Nov.|Dec.)[\d\s]+', i) for i in data] Output: ajax1234: completed in 4.982948303222656e-05 anthony: completed in 3.314018249511719e-05
has comment: http://stackoverflow.com/comment/91867844
has comment: http://stackoverflow.com/comment/91867853
has comment: http://stackoverflow.com/comment/91878674
has comment: http://stackoverflow.com/comment/91867992
has comment: http://stackoverflow.com/comment/91877552

http://stackoverflow.com/comment/91849430
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52453140
score: 0
has text: That worked, thanks!

http://stackoverflow.com/comment/91981306
type: QuestionComment
comment on: http://stackoverflow.com/q/52509254
score: 0
type: Comment
has text: @IonutTicus I've added a snippet of the GeoJSON file in the post above!

http://stackoverflow.com/comment/91848155
has text: @DYZ Ok, but when I run my solution (in the question), I get the same first 10 entries (did not check more) as I do with this answer, but your answer gives me a different first 10 entries in the output. EDIT: I didn't see your edit, now your solution is also great!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52452368

http://stackoverflow.com/comment/91896484
score: 1
type: QuestionComment
has text: The activate script (in the bin directory of the virtual env) which is used to activate the virtualenv might be a possible place to set the environment variables. All python scripts should inherit those, but from maintenance point of view it might not be a great option because if you set up a new virtualenv you would have to remember to modify the activate script again.
type: Comment
comment on: http://stackoverflow.com/q/52449602

http://stackoverflow.com/a/52483658
has comment: http://stackoverflow.com/comment/91942731
answers question: http://stackoverflow.com/q/52477809
score: 0
has body: I think it's possible there is a double apostrophe '' in your data file, near the 8942th apostrophe. In this case your code will continue to read the whole file reading all 210435 segments. But if you have the condition that tests the result of sg.next(), then that would be falsey on the 8942th iteration, and I'm guessing this is causing your program to abort. eg: while sg.next(): # some processing here If I'm completely wrong then I'd be interested in seeing the behaviour of this: - where len and iterations should equal. if __name__ == '__main__': fn = sys.argv[1] sg = SegmentGenerator(fn) print("Num segments:", len(sg.segments)) i = 0 value = 'x' while value: value = sg.next() i += 1 print(i, value) print("Num iterations:", i)
type: Answer

http://stackoverflow.com/q/52562028
has comment: http://stackoverflow.com/comment/92064078
tagged with: c++
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92064282
has body: I'm trying to compile a basic example copied and pasted directly from pybind11, with g++-8 on a Mac. This is the c++ code (example.cpp): #include &lt;pybind11/pybind11.h&gt; int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example plugin"; // optional module docstring m.def("add", &amp;add, "A function which adds two numbers"); } When I use the following command, it works: /usr/local/bin/g++-8 -O3 -Wall -shared -std=c++11 -fPIC -Wl,-undefined,dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix` However, when I add in -mcmodel=large, such as the following /usr/local/bin/g++-8 -Wall -shared -std=c++11 -mcmodel=large -fPIC -Wl,-undefined,dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix` It would give me a bunch of errors that look like: /var/folders/zk/zxm107qd503bgh5qxvdhv6cr0000gv/T//ccbv0Hje.s:75886:19: error: invalid variant 'PLTOFF' movabsq $__ZdlPv@PLTOFF, %rax I have Googled this error but I couldn't find a helpful thread. Also, I want to use g++ (not Xcode) since it's lightweight and popular in my community. I've tried different versions of g++ (6, 7, and 8) but I see the same error. I need to use mcmodel=large because the actual code that I deal with could require large memory allocations. Any help would be appreciated.
tagged with: g++
has comment: http://stackoverflow.com/comment/92063626
has comment: http://stackoverflow.com/comment/92063147
has comment: http://stackoverflow.com/comment/92064444
has title: Error during compilation when using pybind11
type: Question
has comment: http://stackoverflow.com/comment/92063395
tagged with: pybind11
score: 0
tagged with: python

http://stackoverflow.com/comment/91992970
score: 0
type: AnswerComment
type: Comment
has text: Or try to write "global message" at the beginning of each window, and use "message" variable instead of "self.message". Not sure either that they use a shared memory
comment on: http://stackoverflow.com/a/52502193

http://stackoverflow.com/a/54282902
has body: Move the table to the left as in left aligned next to the left margin? Set colWidths=['*']. That will force the table to use the full page width and will automatically align it to the left.
answers question: http://stackoverflow.com/q/52436651
score: 0
type: Answer

http://stackoverflow.com/a/52532173
upvote count: 1
answers question: http://stackoverflow.com/q/52531853
type: Answer
downvote count: 0
score: 1
has body: You may try the following: \w.*?\.\w+(?=\s) Explanation: \w.*?\. matches everything until the file extension dot . inclusive and .\w+ matches the file extension and (?=\s) positive look ahead asserts that white space exists ahead of file extension demo and explanation

http://stackoverflow.com/a/52542948
accepted answer of: http://stackoverflow.com/q/52542812
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: An mcve for creating a new list on each iteration of the outer loop then append to that list in the inner loop. x = [] for n in range(4): q = [] x.append(q) #other stuff for t in range(10): #other stuff q.append(t) &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(x) [[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, 8, 9]] &gt;&gt;&gt;
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52542812

http://stackoverflow.com/q/52472616
has comment: http://stackoverflow.com/comment/91887165
has answer: http://stackoverflow.com/a/52472784
downvote count: 1
type: Question
has title: Calculating no. of appearances of users in frequency of 30 days in Pandas
score: -1
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52472784
upvote count: 0
has comment: http://stackoverflow.com/comment/91887088
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91887127
tagged with: python
has comment: http://stackoverflow.com/comment/91886980
type: AnsweredQuestion
has body: I'm working with a dataframe with users appearing on my site. So I have a dataframe like this: dateTime userId 2018-08-02 17898 2018-08-10 17898 2018-08-25 17898 2018-08-31 17898 2018-08-02 17898 2018-09-06 17898 Here dateTime is basically the first day of appearance in that respective month. So I want to set a threshold of 30 days from their first day of appearance and count how many no. of days, the person has appeared. So my expected dataframe would be something like this: userId n_days_appeared total_days first_appearance 17898 4 30 2018-08-02 For every user I want something like this. So if the person has first appeared on say 5th of August then his 30 days will be 4th September, so I want to calculate how many no. of days has that person appeared in the next 30 days from his appearance.

http://stackoverflow.com/comment/91887318
comment on: http://stackoverflow.com/q/52472795
type: QuestionComment
type: Comment
score: 1
has text: you want to encode the values in z while loading the data? decode while doing operations?

http://stackoverflow.com/comment/91902296
type: AnswerComment
comment on: http://stackoverflow.com/a/52480243
has text: Yes, you can take the input there and in the next step compare it with the correct answer.
type: Comment
score: 0

http://stackoverflow.com/comment/91833980
type: QuestionComment
comment on: http://stackoverflow.com/q/52445182
has text: Can you post the error log?
score: 0
type: Comment

http://stackoverflow.com/comment/92043059
type: Comment
has text: Thank you. It works now! Also may I know how to know the correct threshold value?
comment on: http://stackoverflow.com/a/52551857
type: AnswerComment
score: 0

http://stackoverflow.com/q/52567121
linked to: http://stackoverflow.com/q/52089601
has body: I'm trying to develop an image captioning model. I'm referring to this Github repository. I have three methods, and they perform the following: Generates the image model Generates the caption model Concatenates the image and caption model together Since the code is long, I've created a Gist to show the methods. Here is a summary of my image model and caption model. But then I run the code, I am getting this error: TraceTraceback (most recent call last): File "trainer.py", line 99, in &lt;module&gt; model.fit([images, encoded_captions], one_hot_captions, batch_size = 1, epochs = 5) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 950, in fit batch_size=batch_size) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 671, in _standardize_user_data self._set_inputs(x) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 575, in _set_inputs assert len(inputs) == 1 AssertionError Since the error is coming from Keras library, I have no idea how to debug this. But something is wrong when I try to concatenate them together. I would like to know if I'm missing something here
type: Question
has comment: http://stackoverflow.com/comment/93737006
tagged with: keras-layer
tagged with: deep-learning
has answer: http://stackoverflow.com/a/52567474
accepted answer: http://stackoverflow.com/a/52567474
upvote count: 1
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: AssertionError while trying to concatenate two models and fit in Keras
score: 1
tagged with: machine-learning

http://stackoverflow.com/comment/92019070
type: QuestionComment
comment on: http://stackoverflow.com/q/52534085
has text: I simply see an empty page. In the browser source it does show the image. In console I see Failed to load resource: the server responded with a status of 404 (NOT FOUND)
score: 0
type: Comment

http://stackoverflow.com/a/52533048
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52532937
score: 4
type: AcceptedAnswer
has body: I guess you could introspect the mro manually, something to the effect of: In [8]: class Base(object): ...: def smart_word_reader(self): ...: for cls in type(self).mro(): ...: for word in getattr(cls, 'words', ()): ...: print(word) ...: ...: class A(Base): ...: words = ['foo', 'bar'] ...: ...: class B(A): ...: words = ['baz'] ...: In [9]: a = A() In [10]: a.smart_word_reader() foo bar In [11]: b = B() In [12]: b.smart_word_reader() baz foo bar Or perhaps in reversed order: In [13]: class Base(object): ...: def smart_word_reader(self): ...: for cls in reversed(type(self).mro()): ...: for word in getattr(cls, 'words', ()): ...: print(word) ...: ...: class A(Base): ...: words = ['foo', 'bar'] ...: ...: class B(A): ...: words = ['baz'] ...: In [14]: a = A() In [15]: a.smart_word_reader() foo bar In [16]: b = B() In [17]: b.smart_word_reader() foo bar baz Or a more complicated pattern: In [21]: class Base(object): ...: def smart_word_reader(self): ...: for cls in reversed(type(self).mro()): ...: for word in getattr(cls, 'words', ()): ...: print(word) ...: ...: class A(Base): ...: words = ['foo', 'bar'] ...: ...: class B(Base): ...: words = ['baz'] ...: ...: class C(A,B): ...: words = ['fizz','pop'] ...: In [22]: c = C() In [23]: c.smart_word_reader() baz foo bar fizz pop In [24]: C.mro() Out[24]: [__main__.C, __main__.A, __main__.B, __main__.Base, object]
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52532937

http://stackoverflow.com/q/52431119
accepted answer: http://stackoverflow.com/a/52432052
type: Question
possible better answer: http://stackoverflow.com/a/52431620
has title: Python: How to Keep Alphanumeric English,Latin Characters in the regex?
has comment: http://stackoverflow.com/comment/91807606
has answer: http://stackoverflow.com/a/52432052
upvote count: 3
answer count: 3
has comment: http://stackoverflow.com/comment/91806147
has answer: http://stackoverflow.com/a/52431889
has body: I want my regex to keep all alphanumeric English and Latin characters. re.sub('[^A-Za-z0-9-/().&amp;\' ]+', '',"L'Oréal") should persist with L'Oréal Currently, it gives me L'Oral Is there any Latin encoding that should be added?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52431620
has comment: http://stackoverflow.com/comment/91805898
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91807247
has comment: http://stackoverflow.com/comment/91806407
type: AnsweredQuestion
score: 3
downvote count: 0

http://stackoverflow.com/a/52555557
has body: You can easily define this function using the backend functions sum and binary_crossentropy (or use their equivalents in Tensorflow directly): def func(A, B): return K.sum(K.binary_crossentropy(A,B)) Note that K.binary_crossentropy() assumes that the given input values are probabilities; if that's not the case then pass from_logit=True as another argument to it. Further, if you would like to use this function in a Lambda layer, then you need to change it so that it accepts a list of tensors as input: def func(inp): return K.sum(K.binary_crossentropy(inp[0], inp[1]), [1,2]) # take the sum for each sample independently # ... out = Lambda(func)([A, B]) As you can see, [1,2] has been passed to K.sum() as its axis argument to take the sum over all the element of a single sample (and not over the whole batch).
answers question: http://stackoverflow.com/q/52552910
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52552910
type: Answer

http://stackoverflow.com/comment/91879415
type: AnswerComment
has text: looks promising, I just need to know a number of digits after fixed point (x), and then I can multiply Fractional part by 10^x. I think It could be the most efficient. I ned to measure perforamnce...
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52463854

http://stackoverflow.com/comment/92003194
score: 1
comment on: http://stackoverflow.com/q/52531942
has text: Well, `[] =` sets a specific key to a specific value. `update` takes another dict and sets all its keys and values. That's something of a difference… For single values, the result is the same though.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52522346
accepted answer: http://stackoverflow.com/a/52522429
type: Question
linked to: http://stackoverflow.com/q/18990977
has comment: http://stackoverflow.com/comment/91984290
has body: I want to generate a list of random numbers where the range and the length of the list can be varied later without modifying the function.So i thought of creating a function and the code i tried using python 3x is as follows: class Traffic_matrix: def All_traffic(self,first,last,length): all_t=[] for i in range(length): all_t.append (random.randint(first, last)) all_t = Traffic_matrix() print(all_t.All_traffic(23,56,6)) I know i have made a mistake somewhere and dont know what it is. Please help me out to sort this.
has comment: http://stackoverflow.com/comment/91984266
tagged with: class
tagged with: random
answer count: 2
has title: Writing a function inside a class to generate a list of SIX random numbers between a given range
tagged with: function
linked to: http://stackoverflow.com/q/136097
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52523601
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52522429
score: 1
possible better answer: http://stackoverflow.com/a/52523601
upvote count: 1

http://stackoverflow.com/q/52485861
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: Updating celery conf at runtime
type: UnansweredQuestion
tagged with: celery
type: Question
has body: I have a flask app running with celery as worker backend. I load my configuration variables via flask and give them to celery which works just fine. flask_app.config.from_object(config) celery.conf.update(flask_app.config) There is an option in my app to update a setting which also needs to be applied to celery at run-time, none of my tries seem to permanently save the config. Here is the documention from celery import current_app current_app.conf.update(new_settings) or from celery import current_app current_app.conf['SOME_SETTING'] = new_settings['SOME_SETTING'] In both tries 'SOME_SETTING' is correctly updated in the current_app during the update task but when making a new task the config is still it's original value and not the new one. I cannot find anything about this issue online, any help or indication in the right direction would be helpful.
has answer: http://stackoverflow.com/a/62967195
upvote count: 5
score: 5
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52579930
type: Answer
accepted answer of: http://stackoverflow.com/q/52579847
has body: You could use python's uuid library. Simple example (out of context): import uuid as uuidlib uuid = str(uuidlib.uuid4()) In your case: import uuid import random class Cell: def __init__(self, energy, strength, intelligence): self.energy = energy self.strength = strength self.intelligence = intelligence cells = {} k = 1 while k &lt; 100: key = str(uuid.uuid4()) print("Generating cell: " + key) cells[key] = Cell(random.randint(1, 100),random.randint(1, 100),random.randint(1, 100)) k += 1 #Generate cells
score: 2
has comment: http://stackoverflow.com/comment/92094968
answers question: http://stackoverflow.com/q/52579847
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52580729
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: You are printing the reference to the pay function. If you want to call the function, you need to have parenthesis (()): print(pay()) Note that hrs and rate are inputted inside the function, and finalPay is calculated inside it, so all three should be removed from the function definition.
answers question: http://stackoverflow.com/q/52580685

http://stackoverflow.com/q/52587236
has title: Can using a middle layer as an API bypass CORS?
accepted answer: http://stackoverflow.com/a/52587884
tagged with: flask
answer count: 2
tagged with: cors
tagged with: python
type: AnsweredQuestion
has body: I am developing an application using ReactJS, that communicates with another Enterprise application (Oracle Hyperion) using a rest API provided by Hyperion. The problem is that this API is not officially supported, and does not support CORS. I tried finding a solution to this problem with no success. While trying to solve another problem, I created a Python Flask application, and made all communication between the ReactJS app and Hyperion Rest API pass through it. Somehow, this made the CORS error that was happening disappear. I used the following import and function in the Flask app from flask_cors import CORS, cross_origin CORS(app) The ReactJS application now communicates with the Flask app only using Axios, and all requests are successful without the need for allow CORS plugins. The question is: I now need to know how this is possible, because I have an order to avoid using Python for different reasons. I want to know how the problem was solved in order to make sure it doesn't reappear when I rewrite this part using another language or eliminate it even. Does using an API in the middle solve the CORS issue or what?
score: 0
tagged with: httprequest
type: Question
has answer: http://stackoverflow.com/a/52587884
tagged with: reactjs
possible better answer: http://stackoverflow.com/a/64374386
has answer: http://stackoverflow.com/a/64374386

http://stackoverflow.com/q/52557058
has answer: http://stackoverflow.com/a/74187846
score: 2
type: AnsweredQuestion
type: Question
has body: Does anyone have a chronological list of operations performed by import spacy nlp = spacy.load('en_core_web_sm') doc = nlp(text) I can see the major components with nlp.pipe_names ['tagger', 'parser', 'ner'] and an alphabetical list of factory operations with nlp.factories {'merge_entities': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'merge_noun_chunks': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'ner': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'parser': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'sbd': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'sentencizer': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'similarity': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'tagger': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'tensorizer': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'textcat': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;, 'tokenizer': &lt;function spacy.language.Language.&lt;lambda&gt;&gt;} but I can't figure out when the lemmatizer is invoked. Lemmatization has to happen after tokenization and POS tagging, and it will run with the parser and ner disabled. The spaCy pipeline docs don't mention it at all. Thanks!
tagged with: lemmatization
possible better answer: http://stackoverflow.com/a/52560132
has answer: http://stackoverflow.com/a/52560132
accepted answer: http://stackoverflow.com/a/74187846
has title: spaCy nlp pipeline order of operations
answer count: 2
downvote count: 0
tagged with: nlp
favorite count: 0
tagged with: spacy
upvote count: 2
tagged with: python

http://stackoverflow.com/a/52520115
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52519848
has body: This list comprehension uses default values when one of the keys is not present (using dict.get()). I added variables so you can set the desired default values. default_name = '' default_address = '' default_open_now = False default_rating = 0.0 new_list = [ ( e.get('name', default_name), e.get('formatted_address', default_address), e.get('opening_hours', {}).get('open_now', default_open_now), e.get('rating', default_rating), ) for e in y]
answers question: http://stackoverflow.com/q/52519848
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52519002
answers question: http://stackoverflow.com/q/52516199
has comment: http://stackoverflow.com/comment/129184706
has body: For the dataframe DF, the following line of code will set the first row as the column names of the dataframe: DF.columns = DF.iloc[0]
score: 25
downvote count: 0
type: Answer
upvote count: 25

http://stackoverflow.com/a/52586877
score: 3
has comment: http://stackoverflow.com/comment/92340461
upvote count: 3
answers question: http://stackoverflow.com/q/52585298
downvote count: 0
type: Answer
has body: A simple solution would be this def add_group_by_columns(query, group_by_columns): return query.group_by(*group_by_columns) You can then use it like this q = db.session.query(Order.product_id, Order.seller_id, func.count(Order.id)).filter(Order.user_id==12) q1 = add_group_by_columns(q, [Order.product_category_id, Order.seller_id]) q1.all()
has comment: http://stackoverflow.com/comment/92127571

http://stackoverflow.com/q/52544571
has comment: http://stackoverflow.com/comment/92029051
tagged with: hash
accepted answer: http://stackoverflow.com/a/52545558
tagged with: python
has comment: http://stackoverflow.com/comment/92029066
has comment: http://stackoverflow.com/comment/92029534
has title: Java SHA256 generates different hash as in Python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52544959
tagged with: sha256
tagged with: java
has answer: http://stackoverflow.com/a/52545558
possible better answer: http://stackoverflow.com/a/52544959
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92029148
score: 0
has body: I am trying to generate OTP, but after I tried to rewrite code from python to java, I have got different outputs. I do not understand why, because some of outputs characters are same (when I change uname or ctr). PYTHON CODE: from Crypto.Hash import SHA256 def get_otp(uname, ctr): inp = uname+str(ctr) binp = inp.encode('ascii') hash=SHA256.new() hash.update(binp) dgst=bytearray(hash.digest()) out = '' for x in range(9): out += chr(ord('a')+int(dgst[x])%26) if x % 3 == 2 and x != 8: out += '-' return out print(get_otp('78951', 501585052583)) JAVA CODE: import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { public static void main(String[] args) throws NoSuchAlgorithmException { System.out.println(get_otp("78951", "501585052583")); } public static String get_otp(String uname, String otp) throws NoSuchAlgorithmException { String input = uname + otp; byte[] binInput = input.getBytes(StandardCharsets.US_ASCII); MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(binInput); String retVal = ""; for(int i = 0; i &lt; 9; ++i) { retVal += ((char)(((int)'a') + Math.floorMod((int)hash[i], 26))); if(i % 3 == 2 &amp;&amp; i != 8) retVal += '-'; } return retVal; } } Thank you for help.
tagged with: cryptography

http://stackoverflow.com/a/52570673
has body: You can use any array as input to linegress function.. this includes series in you dataframe: linregress(df['x-axis'], df['y-axis']) You can apply to each group when using pandas groupby grouped = df.groupby('Test Event') grouped.apply(lambda x: pd.Series(linregress(x['x-axis'], x['y-axis']))).rename(columns={ 0: 'slope', 1: 'intercept', 2: 'rvalue', 3: 'pvalue', 4: 'stderr'}).reset_index()
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92092378
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/92092305
answers question: http://stackoverflow.com/q/52570122
has comment: http://stackoverflow.com/comment/92100397

http://stackoverflow.com/q/52478788
has body: I am trying to execute a python interpreter from a python environment, called env_tensorflow, using pybind11 library. Even though, I include and link the cpp file to the pybind11 library which is included from that environment (env_tensorflow), the interpreter prints its binary path as: /usr/bin/python3 However, I expect the output to be: /home/user/miniconda3/envs/env_tensorflow/bin/python3 What am I doing wrong? How can I run the python interpreter from a specific environment? main.cpp #include "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/Python.h" #include "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/pybind11/pybind11.h" #include "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/pybind11/embed.h" namespace py = pybind11; int main() { py::scoped_interpreter guard{}; py::module sys = py::module::import("sys"); py::print(sys.attr("executable")); //prints: /usr/bin/python3 //expected print: /home/user/miniconda3/envs/env_tensorflow/bin/python3 return 0; } CMakeLists.txt cmake_minimum_required(VERSION 3.12) project(my_proj) set(CMAKE_CXX_STANDARD 11) add_library(my_python3.6m SHARED IMPORTED) set_target_properties(my_python3.6m PROPERTIES IMPORTED_LOCATION "/home/user/miniconda3/envs/env_tensorflow/lib/libpython3.6m.so" INTERFACE_INCLUDE_DIRECTORIES "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/" ) add_executable(my_proj main.cpp) target_link_libraries(my_proj my_python3.6m)
tagged with: python
tagged with: c++
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91901192
has answer: http://stackoverflow.com/a/52481680
accepted answer: http://stackoverflow.com/a/52481680
tagged with: pip
type: Question
tagged with: pybind11
has title: How to run the python interpreter from a virtualenv using pybind11?
has comment: http://stackoverflow.com/comment/91900471
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52439639
possible better answer: http://stackoverflow.com/a/52455423
linked to: http://stackoverflow.com/q/16008670
has answer: http://stackoverflow.com/a/66612465
tagged with: django
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91822626
score: 3
has comment: http://stackoverflow.com/comment/91822395
has comment: http://stackoverflow.com/comment/91822570
has answer: http://stackoverflow.com/a/66613880
has comment: http://stackoverflow.com/comment/91822357
type: Question
accepted answer: http://stackoverflow.com/a/52439710
has answer: http://stackoverflow.com/a/52455423
has comment: http://stackoverflow.com/comment/91822029
has comment: http://stackoverflow.com/comment/91822449
has answer: http://stackoverflow.com/a/52439710
downvote count: 1
linked to: http://stackoverflow.com/q/1210458
tagged with: python
has comment: http://stackoverflow.com/comment/91822610
upvote count: 4
answer count: 4
favorite count: 0
has title: How to generate unique 8 length number, for account ID for example (Python,Django)
has body: I need to generate unique account ID for each user.(only numeric) UUID can't solve this problem, pls help me!

http://stackoverflow.com/comment/92061768
has text: @JohnnyMopp what if I want to write the function for another shape such as `***** **** *** ** *` I have written `def print_upper_left_triangle(ch, height): width = height for i in range(height,0,-1): print(ch) ` but it gives me `5 of *` in height instead of `***** **** *** ** *`
comment on: http://stackoverflow.com/q/52560331
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52523514
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52524022
tagged with: git
type: Question
upvote count: 9
has title: Accessing User-Defined Packages in Google Cloud Function (ModuleNotFoundError: No module named...)
tagged with: google-cloud-platform
linked to: http://stackoverflow.com/q/52452269
linked to: http://stackoverflow.com/q/52432324
answer count: 1
has comment: http://stackoverflow.com/comment/91986628
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52524022
score: 9
has comment: http://stackoverflow.com/comment/91986658
tagged with: package
has body: I am deploying a Google Cloud function from a source repository. I can get the Google Function to deploy fine as long as I don't make any reference in my main.py to any of my user-defined functions in the repository (i.e. scripts/functions in either package or package2 below other than main.py). . ├── package | ├── __init__.py | ├── main.py | ├── requirements.txt | ├── script1.py | └── script2.py ├── package2 | ├── __init__.py | ├── script3.py | └── script4.py └── ... I have 2 recent Stack Overflow questions regarding this function deploy here and here. They have collectively guided me towards a solution where main.py and requirements.txt are within a package and I deploy the Google Cloud Function with that package as the source. The problem now though is that I need to be able to access functions/scripts in other packages/scripts. If I include a statement like from package.script1 import foo in main.py I get an error like the one below when I deploy the function: ERROR: (gcloud.functions.deploy) OperationError: code=3, 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/wo rker.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/wo rker.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 package.script1 import foo ModuleNotFoundError: No module named 'package' I am currently deploying this function with this google function deploy statement: gcloud functions deploy NAME --source https://source.developers.google.com/projects/PROJE…
tagged with: google-cloud-functions
tagged with: python

http://stackoverflow.com/q/52525062
type: Question
has answer: http://stackoverflow.com/a/52525171
has body: I would like to expand this dataframe on a depth range which has such a depth column: import numpy as np import pandas as pd depth = np.array([0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5]) df1 = pd.DataFrame({'depth': [0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2], '400.0': [13.909261, 7.758734, 3.513627, 2.095409, 1.628918, 0.782643, 0.278548, 0.160153, -0.155895, -0.152373, -0.147820, -0.023997, 0.010729, 0.006050, 0.002356], '401.0': [14.581624, 8.173803, 3.757856, 2.223524, 1.695623, 0.818065, 0.300235, 0.173674, -0.145402, -0.144456, -0.142969, -0.022471, 0.010802, 0.006181, 0.002641], '402.0': [15.253988, 8.588872, 4.002085, 2.351638, 1.762327, 0.853486, 0.321922, 0.187195, -0.134910, -0.136539, -0.138118, -0.020945, 0.010875, 0.006313, 0.002927], '403.0': [15.633908, 8.833914, 4.146499, 2.431543, 1.798185, 0.874350, 0.333470, 0.192128, -0.130119, -0.134795, -0.136049, -0.019307, 0.012037, 0.006674, 0.003002], '404.0': [15.991816, 9.066159, 4.283401, 2.507818, 1.831721, 0.894119, 0.344256, 0.196415, -0.125758, -0.133516 , -0.134189, -0.017659, -0.013281,0.007053, 0.003061], '405.0': [16.349725, 9.298403, 4.420303, 2.584094, 1.865257, 0.913887, 0.355041, 0.200702, -0.121396, -0.132237, -0.132330, -0.016012, 0.014525, 0.007433, 0.003120] }) So what I need in this case is three additional rows at the bottom with NaN values. Similarly I have a df2 with depth range from 1.1 to 2.5 and need to fill the upper 3 rows based on the extended depth range. How do I do it?
possible better answer: http://stackoverflow.com/a/52525094
has answer: http://stackoverflow.com/a/52525094
upvote count: 2
answer count: 3
tagged with: pandas
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52525113
accepted answer: http://stackoverflow.com/a/52525113
downvote count: 0
has title: Add n empty rows in a dataframe

http://stackoverflow.com/comment/92036101
score: 0
type: Comment
has text: Thanks! Actually the real use case is a bit complicated, while I just want to be lazy that don't want to find the original json file :D
type: AnswerComment
comment on: http://stackoverflow.com/a/52548432

http://stackoverflow.com/q/52460030
possible better answer: http://stackoverflow.com/a/52460140
score: 1
has answer: http://stackoverflow.com/a/52460140
type: Question
upvote count: 2
answer count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/91862120
favorite count: 0
has body: I'm a beginner in django middleware. I used to write a visitor system via middleware and still did't get a problem which can be solved with a middleware. Could you describe any typical tasks with django middleware? And tasks where the middleware must have to be
has comment: http://stackoverflow.com/comment/91862227
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91862321
has title: What problems can I solve with django middleware?
has answer: http://stackoverflow.com/a/52460133
accepted answer: http://stackoverflow.com/a/52460133
has answer: http://stackoverflow.com/a/52460176
type: AnsweredQuestion

http://stackoverflow.com/comment/91897102
comment on: http://stackoverflow.com/q/52477822
score: 0
has text: @ForceBru hhhh, yeah it is a tricky method. Thank you friend
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91898637
type: AnswerComment
comment on: http://stackoverflow.com/a/52476076
has text: @user10309160 it's really strange, I don't have errors. Try just `df['group'] = sorted(range(0, len(df)) * 4)[0:len(df)]`
type: Comment
score: 0

http://stackoverflow.com/comment/92070771
comment on: http://stackoverflow.com/q/52566588
score: 0
type: Comment
type: QuestionComment
has text: John Zwinck: I believe you have misunderstood the question, as I dont want the same outcomes the question you refer to.

http://stackoverflow.com/comment/91866139
score: 0
has text: @hpaulj I think that keras model.predict_classes(x) function expects an "array of array" argument of x
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52457661

http://stackoverflow.com/comment/92068753
comment on: http://stackoverflow.com/q/52565314
type: Comment
type: QuestionComment
has text: The 2nd case are from the h264 parser and indicates a corrupt stream or missing packets. ffmpeg logs to stderr although OpenCV is probably redirecting it.
score: 0

http://stackoverflow.com/comment/92093350
score: 1
has text: Hello @Swift! Thank you for your answer! I have additional user inputs, that's why I'm checking first if there are errors, so that I can gather them all together. And the process_data() method is not in there, but for the sake of simplicity I put it there. Thank you for the the link.
type: AnswerComment
comment on: http://stackoverflow.com/a/52579089
type: Comment

http://stackoverflow.com/q/52479017
type: Question
has answer: http://stackoverflow.com/a/52479326
has title: How to extract values using eval() in tensorflow and how many times we need to launch session
answer count: 1
downvote count: 0
score: 1
has body: In tensorflow we create graphs and then in order to pass the values to the graph we have to launch a session. In the following code I launch session once and then try to print filter by two different methods. But I am unable to get result with eval. Does I need to mention tf.Session again to extract value by eval? I also read that eval command uses default session. So according to my understanding I need to mention it once. filter = tf.random_normal(shape=[2,1,1], seed=123) sess=tf.Session() print(sess.run(filter)) print(filter.eval())
favorite count: 0
accepted answer: http://stackoverflow.com/a/52479326
tagged with: python
type: AnsweredQuestion
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/91861935
type: Comment
comment on: http://stackoverflow.com/a/52456400
has text: i have no error, despite that location is booked, the item got saved and that is it...i will update the function in my question.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52494318
has comment: http://stackoverflow.com/comment/91932165
has comment: http://stackoverflow.com/comment/91932352
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52494900
type: Question
tagged with: python
tagged with: jupyter
has body: I am on mac with homebrew mysql, making a django app. I also use jupyter. I don't know which of these things is the root cause of the issue. I used to get this error message coming up every now and again, and I know how to fix it: just type brew services restart mysql and wait a bit. The problem is that it's now happening with increasing frequency, several times an hour. Is there a known fix for this, when working on a local machine? I thought, since I'm ctrl-c ing programs frequently, that might be exhausting the connection pool so I increased the connection pool size using SET GLOBAL max_connections = 5000;, but that has not helped.
score: 0
has comment: http://stackoverflow.com/comment/91929277
tagged with: mysql
tagged with: django
answer count: 1
has title: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")

http://stackoverflow.com/comment/91924064
has text: labels is a list of tkinter label widgets, it is unlikely that they are ints. The labels are behaving as expected.
type: Comment
comment on: http://stackoverflow.com/a/52490633
score: 0
type: AnswerComment

http://stackoverflow.com/a/52528048
has comment: http://stackoverflow.com/comment/91996872
has body: Using [] will return the pd.Series a['date'][2] Out[257]: '20180924' a.iloc[0]['date'] Out[258]: '20180924' a.loc[2,'date'] Out[259]: '20180924'
has comment: http://stackoverflow.com/comment/91996845
has comment: http://stackoverflow.com/comment/91997007
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52527978
has comment: http://stackoverflow.com/comment/91996982
upvote count: 1
type: Answer

http://stackoverflow.com/a/52535124
has body: You can sort the elements first. Then for each of the largest elements find its index in the original list. Your should look like this: original_list = [...] sorted_list = original_list.sort() 1st_largest_index = original_list.index(sorted_list[-1]) 2nd_largest_index = original_list.index(sorted_list[-2])
upvote count: 1
answers question: http://stackoverflow.com/q/52534972
score: -3
type: Answer
downvote count: 4

http://stackoverflow.com/q/52510915
has body: My original data - pd.DataFrame([ {'col1': 1, 'col2': 11, 'col3': ['A', 'B'] }, {'col1': 2, 'col2': 22, 'col3': ['P', 'Q', 'R'] }, ]) which gives me - col1 col2 col3 0 1 11 ['A', 'B'] 1 2 22 ['P', 'Q', 'R'] I'd like to expand the rows depending on contents of the array in col3 i.e. I'd like to get a dataframe like this one - col1 col2 col3 0 1 11 'A' 1 1 11 'B' 2 2 22 'P' 3 2 22 'Q' 4 2 22 'R' What's a good way accomplishing this? I found a similar question here however it doesn't include col3 in the output. I also have another similar question here however since it has strings in the column. The same solution wouldn't work here because split() wouldn't work for list.
type: Question
duplicate of: http://stackoverflow.com/q/42012152
upvote count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/12680754
tagged with: python
linked to: http://stackoverflow.com/q/42012152
has title: Expanding the rows of a data frame based on its column containing lists
answer count: 0
linked to: http://stackoverflow.com/q/52352226
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/52547477
downvote count: 0
has answer: http://stackoverflow.com/a/52549053
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92034459
score: 1
has body: is there a way that i can concatenate a string list and 2 number list such that the concatenated list would take them one after the order while joining them. Input: a = [john, bob, ted, Paul] b = [22, 34, 56, 12] c = [13, 98, 78, 60] Expected Ouput: [john, 22, 13, bob, 34, 98, ted, 56, 78, Paul, 12, 60]
upvote count: 1
type: Question
has title: can i join three list in python (string list and two number list)
has answer: http://stackoverflow.com/a/52548492
linked to: http://stackoverflow.com/q/7946798
has answer: http://stackoverflow.com/a/52547511
answer count: 3
has comment: http://stackoverflow.com/comment/92034586

http://stackoverflow.com/comment/91807551
has text: @JonClements now with that OP gets busted for sure
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52431950
type: Comment

http://stackoverflow.com/q/52555385
accepted answer: http://stackoverflow.com/a/52557430
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52557430
tagged with: freedesktop.org
upvote count: 1
tagged with: python
tagged with: dictionary
has title: Python properly and effectively obtaining DBUS object path (e.g. /org/bluez/dev_XX_XX_XX_XX_XX_XX/playerY)
type: AnsweredQuestion
score: 1
type: Question
downvote count: 0
tagged with: bluez
tagged with: dbus
has body: I would like to get the device path for bluez-based A2DP bluetooth player that I am creating. I am stuck implementing Play/Pause/Next/Previous commands efficiently, because the dbus availability and player path changes depending on the media player you choose. Furthermore, bluez sometimes decides to send a lot of useless information (for me) such as playlist details that makes the payload bigger for my application to handle. So the goal here is to obtain /org/bluez/dev_XX_XX_XX_XX_XX_XX/playerY when a function is called. def update_player(): manager = dbus.Interface(self.bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") objects = manager.GetManagedObjects() player_path = getFromDict(objects,[self.devicepath,"org.bluez.MediaControl1", "Player"]) When I try to change the media player, or bluez sends some logs (so 5% of the time in general), dbus org.freedesktop.DBus.ObjectManager receives a lot of information which makes manager.GetManagedObjects() get stuck for 10~20 seconds. Is there a way of determining bluez object path without having to receive the entire org.freedesktop.DBus.ObjectManager objects; or Is there a way to just limit the amount of message sent by bluez. I really would like to get the object path efficiently. Any help is greately appreciated. EDIT: Although I did not test it in the embedded system that had the problem with ObjectManager being populated, thanks to Partiban's great suggestion, I was able to use InterfacesAdded and some regex in order to match the path I needed. self.bus.add_signal_receiver(self.objectPathHandler, bus_name="org.bluez", dbus_interface="org.freedesktop.DBus.ObjectManager", signal_name="InterfacesAdded", path_keyword="path") def objectPathHandler(self, interface, changed, path): iface = interface[interface.rfind(".") + 1:] #print("InterfacesAdded: {}; changed: {}; path {}".format(iface, changed, path)) self.playerpath = re.findall('/org/bluez/hci[0-9]/dev_[\dA-F]{2}_[\dA-F]{2}_[\dA-F]{2}_[\dA-F]{2}_[\d…

http://stackoverflow.com/a/52484197
downvote count: 0
has comment: http://stackoverflow.com/comment/91910022
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52484043
has body: This is possible but tedious with regular Python. If you are willing to use a 3rd party library, you can use Pandas to perform a GroupBy aggregation: import pandas as pd d = {'d1': {'goober': True, 'horse': 42}, 'd2': {'goober': True, 'horse': 42}, 'd3': {'goober': False, 'horse': 71}} df = pd.DataFrame(d).T.reset_index().groupby('goober')\ .agg(lambda x: set(x)).reset_index() print(df) # goober index horse # 0 False {d3} {71} # 1 True {d1, d2} {42} res = [{'dict': {'goober': row.goober, 'horse': next(iter(row.horse))}, 'keys': list(row.index)} for row in df.itertuples(index=False)] Result: [{'dict': {'goober': False, 'horse': 71}, 'keys': ['d3']}, {'dict': {'goober': True, 'horse': 42}, 'keys': ['d1', 'd2']}] Note I haven't applied any logic to derive 'group1' and 'group2' outer dictionary keys. It's not clear how these are derived. If they are arbitrary identifiers, you can use enumerate in a subsequent step: res2 = {f'group{idx}': d for idx, d in enumerate(res, 1)} Result: {'group1': {'dict': {'goober': False, 'horse': 71}, 'keys': ['d3']}, 'group2': {'dict': {'goober': True, 'horse': 42}, 'keys': ['d1', 'd2']}}
has comment: http://stackoverflow.com/comment/91910114
score: 2
has comment: http://stackoverflow.com/comment/91910133

http://stackoverflow.com/comment/92012799
type: Comment
comment on: http://stackoverflow.com/a/52533588
has text: @blhsing np, it's not worth many upvotes in the first place because it's not wise _not_ to initialize the variable in `__init__`. Stupid homework requirements...
type: AnswerComment
score: 0

http://stackoverflow.com/q/52446496
accepted answer: http://stackoverflow.com/a/52447515
type: AnsweredQuestion
score: 2
downvote count: 0
type: Question
has title: Why are there two unique copies of Python 3.7.0 installed on Windows in vastly different locations?
upvote count: 2
answer count: 2
tagged with: python-3.7
has body: I have Python 3.7.0 installed on Windows. I only followed the Installer one time, but I have two different executables of python installed in two different locations. C:\Windows\py.exe with a white icon, 887 KB (908,952 bytes); and C:\Users\myuser\AppData\Local\Programs\Python\Python37\python.exe with a black icon, 97.6 KB (99,992 bytes) The Python Installer specifies the second path, as shown in the Installation guide, but Git Bash, Cygwin, and MSYS+MingW all report the first one as valid and not the second one: $ which python which: python: unknown command $ which py /c/WINDOWS/py.exe And PowerShell shows that both of them are Python 3.7.0, despite their different file sizes: PS C:\Users\myuser\AppData\Local\Programs\Python\Python37&gt; ./python.exe -V Python 3.7.0 PS C:\Users\myuser\AppData\Local\Programs\Python\Python37&gt; py -V Python 3.7.0 The first path does not have a "Scripts" sub-folder, but the second one does, however the System Environment variables point to a "Scripts" folder at the path that has no "Scripts" folder: PATH variable: %PYTHON_HOME%\ %PYTHON_HOME%\Scripts\ PYTHON_HOME variable: C:\Windows\ So where does the "py.exe" store libraries? Why do both of them correctly run python scripts and have the same outputs? And why is there an install at C:\Windows\ anyway? I had to physically add the second one to the PATH variable to be able to use pip from a terminal without typing py -m pip, and I do not want to type the long version.
has answer: http://stackoverflow.com/a/52447004
favorite count: 0
tagged with: path-variables
tagged with: python-3.x
tagged with: windows
possible better answer: http://stackoverflow.com/a/52447004
has answer: http://stackoverflow.com/a/52447515
tagged with: python

http://stackoverflow.com/comment/91944887
score: 0
type: Comment
has text: Excellent, this is exactly what I was looking for. I didn't realise you could pass it in as a tuple!
type: AnswerComment
comment on: http://stackoverflow.com/a/52501841

http://stackoverflow.com/comment/91929442
comment on: http://stackoverflow.com/q/52494395
has text: Yeah! It works, Thank you very much!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92044815
comment on: http://stackoverflow.com/q/52552994
score: 0
type: Comment
has text: @MartijnPieters, yes exactly! I completely missed the `concatenate`, that's it!
type: QuestionComment

http://stackoverflow.com/comment/91850001
has text: What version of Python are you using? Are you using a variant like Anaconda or Jython?
comment on: http://stackoverflow.com/q/52453442
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52526102
score: 4
accepted answer of: http://stackoverflow.com/q/52526046
answers question: http://stackoverflow.com/q/52526046
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Perform the check when you're retrieving the environment variables in the first place: def needenv(name): val = os.environ.get(name) if val is None: sys.exit('{} is required.'.format(name)) return val a = needenv('a') b = needenv('b') ...
type: Answer
has comment: http://stackoverflow.com/comment/91992046

http://stackoverflow.com/comment/91938834
type: Comment
comment on: http://stackoverflow.com/q/52499124
type: QuestionComment
score: 0
has text: You might be needing a main function to call `update_userinfo` if it is not being called in some other way

http://stackoverflow.com/comment/91831915
has text: @Bazingaa I am extremely sorry, I made a mistake, I meant cells, not lines. My sincere apologies. I have modified the question. It won't happen again
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52444456

http://stackoverflow.com/comment/105377614
has text: If they are not keyboard events, is there a way in pynput to at least receive the events for those buttons?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52577777

http://stackoverflow.com/q/52455337
has answer: http://stackoverflow.com/a/52455515
has body: I have installed OpenCV and make a python virtual environment adding a simbolink link to OpenCV library in /usr/local/lib/python3.6/sites-packages/cv2.so This is working fine (in Spyder I only change the default interpreter by the interpreter in the virtual environment and the library is loaded). But when I do the same thing in PyCharm, it seems like the simbolink link is broken because PyCharm can't acces to /usr/local... path (Screenshot). Thanks for your time.
tagged with: pycharm
type: Question
tagged with: opencv
score: 0
answer count: 1
has title: Import library from /usr/local to PyCharm
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52502117
has comment: http://stackoverflow.com/comment/91982927
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52495623
has comment: http://stackoverflow.com/comment/91969444
answers question: http://stackoverflow.com/q/52495623
type: AcceptedAnswer
upvote count: 3
type: Answer
has body: You should install all the dependencies in a single command: $ pip install -t lib/ google-cloud-bigquery google-cloud-pubsub This will install both packages along side each other: $ ls lib/google/cloud __pycache__ _testing.py environment_vars.py obsolete.py pubsub_v1 _helpers.py bigquery exceptions.py operation.py _http.py client.py iam.py pubsub.py Installing the dependencies from a requirements file should have the same effect: $ cat requirements.txt google-cloud-bigquery google-cloud-pubsub $ pip install -t lib/ -r requirements.txt Make sure to start with an empty lib/ folder, and with the latest version of pip: pip install -U pip

http://stackoverflow.com/comment/91921624
type: Comment
type: QuestionComment
has text: Provide examples of your various components of the update request. Also, highlight the line on which the error is issued.
comment on: http://stackoverflow.com/q/52488617
score: 0

http://stackoverflow.com/q/52447224
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/91837404
has comment: http://stackoverflow.com/comment/91837303
score: 2
has answer: http://stackoverflow.com/a/52447341
has comment: http://stackoverflow.com/comment/91837294
upvote count: 2
type: Question
has body: I'm unable to install packages with pip3 (pip 9.0.1, fresh Ubuntu 18.04.1 LTS) when I specify --extra-index-url inside requirements.txt. Here is the requirements.txt: --extra-index-url https://some.domain attrs==17.4.0 And here is the output: $ sudo pip3 install -r requirements.txt Collecting attrs==17.4.0 (from -r req.txt (line 2)) Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 342, in run requirement_set.prepare_files(finder) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file require_hashes File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "/usr/lib/python3/dist-packages/pip/index.py", line 568, in _get_pages page = self._get_page(location) File "/usr/lib/python3/dist-packages/pip/index.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/lib/python3/dist-packages/pip/index.py", line 795, in get_page resp.raise_for_status() File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status raise HTTPError(http_error_msg, response=self) pip._vendor.requests.exceptions.HTTPError: 403 Client Error: SSL is required for url: http://pypi.python.org/simple/attrs/ An interesting fact might be that: $ sudo pip3 install attrs==17.4.0 works just fine.
tagged with: python-3.6
has title: pip3 client error SSL is required for url
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52464613
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52459285
has comment: http://stackoverflow.com/comment/91961235
has comment: http://stackoverflow.com/comment/91922860
score: 2
has comment: http://stackoverflow.com/comment/91961838
has comment: http://stackoverflow.com/comment/92092322
downvote count: 0
has body: Let's look at three solutions and provide performance comparisons at the end. One approach that tries to stay close to pandas would be the following: def f1(df): # Group together the elements of df.Sum that might have to be added pos_groups = (df.Sum &lt;= 0).cumsum() pos_groups[df.Sum &lt;= 0] = -1 # Create the new column and populate it with what is in df.Sum df['new_sum'] = df.Sum # Find the indices of the new column that need to be calculated as a sum indices = df[df.Quantity &gt; 0].index for i in indices: # Find the relevant group of positive integers to be summed, ensuring # that we only consider those that come /before/ the one to be calculated group = pos_groups[:i+1] == pos_groups[i] # Zero out all the elements that will be part of the sum df.new_sum[:i+1][group] = 0 # Calculate the actual sum and store that df.new_sum[i] = df.Sum[:i+1][group].sum() f1(df) One place where there's possibly room for improvement would be in pos_groups[:i+1] == pos_groups[i] which checks all i+1 elements when, depending on what your data looks like, it could probably get away with checking a fraction of those. However, chances are this is still more efficient in practice. If not, you may want to iterate by hand to find the groups: def f2(sums, quantities): new_sums = np.copy(sums) indices = np.where(quantities &gt; 0)[0] for i in indices: a = i while sums[a] &gt; 0: s = new_sums[a] new_sums[a] = 0 new_sums[i] += s a -= 1 return new_sums df['new_sum'] = f2(df.Sum.values, df.Quantity.values) Finally, depending once again on what your data looks like, there is a decent chance that the latter approach can be improved using Numba: from numba import jit f3 = jit(f2) df['new_sum'] = f3(df.Sum.values, df.Quantity.values) For the data provided in the question (which might very well be too small to provide a proper picture) the performance tests looks as follows: In [13]: %timeit f1(df) 5.32 ms ± 77.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [14]: %timeit df['new_sum'…

http://stackoverflow.com/q/52580176
score: -1
has comment: http://stackoverflow.com/comment/92096177
tagged with: argparse
answer count: 1
has comment: http://stackoverflow.com/comment/92095646
has answer: http://stackoverflow.com/a/52611474
has comment: http://stackoverflow.com/comment/92095597
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/92095504
has body: I'm using argparse to generate CLI. There are two positional arguments which are all of type str and can occur several time (i.e., nargs='+'). What my current code looks like is : parser.add_argument('-a', type=str, nargs='+', required=True, help='argument a') parser.add_argument('-b', type=str, nargs='+', required=True, help='argument b') However, this is not a good solution as both of a and b are "optional arguments" in the help document. I want to make a and b both positional. Is there any way to do so in argparse? Such as: python main.py a=["a_1", "a_2"] b=["b_1", "b_2"]
has comment: http://stackoverflow.com/comment/92095721
upvote count: 1
type: Question
has title: Multiple arguments with the same type

http://stackoverflow.com/a/52459274
has comment: http://stackoverflow.com/comment/91860774
has body: Here is an exapmle of how to do this, I would suggest not returning the coded message as a list but you should turn the message into a list to get the individual characters, return it as a string but leave spaces to separate the code or you will have one long number you cant interpret back, then when you decode a message you can enter it as 84 105 102 102 97 110 121 and then split this and decode the individual ints def encode(s): s = [str((ord(i))) for i in list(s)] return ' '.join(s) def decode(s): s = [(chr(int(i))) for i in s.split()] return ''.join(s) print(encode('Tiffany')) print(decode('84 105 102 102 97 110 121')) ~/python/stack/sept/twenty_2$ python3.7 alice.py 84 105 102 102 97 110 121 Tiffany
has comment: http://stackoverflow.com/comment/91860889
has comment: http://stackoverflow.com/comment/91860807
answers question: http://stackoverflow.com/q/52459081
score: 0
type: Answer

http://stackoverflow.com/a/52484144
has comment: http://stackoverflow.com/comment/91909895
type: Answer
answers question: http://stackoverflow.com/q/52484111
has body: This is more like a isin problem Activity['active']=Activity'date','_p_user'.apply(tuple,1).isin(dft.apply(tuple,1))
score: 0

http://stackoverflow.com/q/52518096
has answer: http://stackoverflow.com/a/52531469
has comment: http://stackoverflow.com/comment/91975738
answer count: 3
has answer: http://stackoverflow.com/a/52518351
downvote count: 0
has body: I'm trying to check 4 separate variables for the exact same strings using separate variables with similar names. An example is below. The print functions are also an example, they're not my final goal. from random import randint example1 = randint(1,3) example2 = randint(1,3) example3 = randint(1,3) example4 = randint(1,3) if example1 == 1: print ("A") elif example1 == 2: print ("C") else: print ("M") Can anyone suggest how I could repeat this area for all of the variables? if example1 == 1: print ("A") elif example1 == 2: print ("C") else: print ("M")
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91975773
possible better answer: http://stackoverflow.com/a/52518153
has title: Checking separate variables with a while loop
has comment: http://stackoverflow.com/comment/91976849
has answer: http://stackoverflow.com/a/52518153
tagged with: python
has comment: http://stackoverflow.com/comment/91975825
accepted answer: http://stackoverflow.com/a/52518351
score: 1
upvote count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/52564537
accepted answer of: http://stackoverflow.com/q/52562117
answers question: http://stackoverflow.com/q/52562117
type: AcceptedAnswer
downvote count: 0
has body: Here is an optimized version using blas. blas has special routines for linear algebra on symmetric or Hermitian matrices. These use specialized, packed storage, keeping only the upper or lower triangle and leaving out the (redundant) mirrored entries. That way blas saves not only ~half the storage but also ~half the flops. I've put quite a few comments to make it readable. import numpy as np import itertools from scipy.linalg.blas import zhpr, dspr2, zhpmv def acc_vect(pos, mas): n = mas.size d2 = pos@(-2*pos.T) diag = -0.5 * np.einsum('ii-&gt;i', d2) d2 += diag + diag[:, None] np.einsum('ii-&gt;i', d2)[...] = 1 return np.nansum((pos[:, None, :] - pos) * (mas[:, None] * d2**-1.5)[..., None], axis=0) def acc_blas(pos, mas): n = mas.size # trick: use complex Hermitian to get the packed anti-symmetric # outer difference in the imaginary part of the zhpr answer # don't want to sum over dimensions yet, therefore must do them one-by-one trck = np.zeros((3, n * (n + 1) // 2), complex) for a, p in zip(trck, pos.T - 1j): zhpr(n, -2, p, a, 1, 0, 0, 1) # does a -&gt; a + alpha x x^H # parameters: n -- matrix dimension # alpha -- real scalar # x -- complex vector # ap -- packed Hermitian n x n matrix a # i.e. an n(n+1)/2 vector # incx -- x stride # offx -- x offset # lower -- is storage of ap lower or upper # overwrite_ap -- whether to change a inplace # as a by-product we get pos pos^T: ppT = trck.real.sum(0) + 6 # now compute matrix of squared distances ... # ... using (A-B)^2 = A^2 + B^2 - 2AB # ... that and the outer sum X (+) X.T equals X ones^T + ones X^T dspr2(n, -0.5, ppT[np.r_[0, 2:n+1].cumsum()], np.ones((n,)), ppT, 1, 0, 1, 0, 0, 1) # does a -&gt; a + alpha x y^T + alpha y x^T in packed symmetric storage # scale anti-symmetric differences by distance^-3 np.divide(trck.imag, ppT*np.sqrt(ppT), where=ppT.astype(bool), out=trck.imag) # it remains to scale by mass and sum # this can be done by matrix multiplication with the vector of masses ... # ... unfortunately because…
type: Answer
has comment: http://stackoverflow.com/comment/92104392
has comment: http://stackoverflow.com/comment/92103672
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/92104626
has comment: http://stackoverflow.com/comment/92104436

http://stackoverflow.com/q/52504092
accepted answer: http://stackoverflow.com/a/52504418
upvote count: 4
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52504209
favorite count: 0
tagged with: python-3.x
tagged with: package
possible better answer: http://stackoverflow.com/a/52504209
tagged with: windows
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/52504418
type: AnsweredQuestion
has title: Windows: Get all modules/packages used by a python project
has body: I have an application and now I would like to know what packages/modules are necessary if someone else wants to install it. How can I get all the python modules/packages that are needed for a specific project? Important Note: This question was already answered for Linux. They suggested pipreqs, which seems like a great solution, however it does not to support Windows. My Python version is 3.6.4. I am working on windows 10.
linked to: http://stackoverflow.com/q/35796968
type: Question
score: 4

http://stackoverflow.com/comment/91962142
has text: @eyllanesc I'm using a Raspberry Pi 3, which has a 64-bit CPU, but a 32-bit operating system.
type: Comment
comment on: http://stackoverflow.com/q/52511042
score: 0
type: QuestionComment

http://stackoverflow.com/a/52484193
accepted answer of: http://stackoverflow.com/q/52484136
type: Answer
has body: You are iterating over the elements of the list, not its indices; that is, i is what you think arr[i] should be. As you actually need the indices, you could iterate over them explicitly: for i in range(len(arr)): although a more Pythonic idiom is to use the enumerate function instead, which gives you an element of the list and its index at the same time. for i, x in enumerate(arr): if x not in '+-*/': arr2[i] = x else: arr1[i] = x
answers question: http://stackoverflow.com/q/52484136
score: 2
has comment: http://stackoverflow.com/comment/91910151
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91910325
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91910507

http://stackoverflow.com/q/52522590
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/51549588
has comment: http://stackoverflow.com/comment/91984933
has answer: http://stackoverflow.com/a/52543001
downvote count: 0
has title: Tensorflow Keras LSTM not training - affected by number_of_epochs, optimizer adam
tagged with: keras
has comment: http://stackoverflow.com/comment/91984893
tagged with: lstm
has comment: http://stackoverflow.com/comment/92031497
answer count: 1
has comment: http://stackoverflow.com/comment/92002231
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/52543001
has comment: http://stackoverflow.com/comment/92053399
tagged with: machine-learning
has body: I have 2 code snippets. One of them trains a model while the other one doesn't. I don't want to raise an issue on Github without getting to the bottom of this and it wasted a day of mine waiting for the incorrect model to train. This is the model, which is correct. Running tensorflow 1.10.1. model = Sequential() # I truncate the string at 20 characters, alphabet listset is a sorted list of the set of [A-Za-z0-9-_] which has len = 64 model.add(LSTM(512, return_sequences=True, input_shape=(20, len(alphabet_listset)), dropout=0.2, stateful=False)) model.add(LSTM(512, return_sequences=False, dropout=0.2, stateful=False)) model.add(Dense(2, activation="softmax")) model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy']) # adam here is at learning rate 1e-3 model.summary() To create X_train and Y_train I use test_train_split. The way I convert the string to one hot vector(even though there is a fuction for one hot vector for lstm now, if you add that it would really help) is def string_vectorizer(strng, alphabet, max_str_len=20): vector = [[0 if char != letter else 1 for char in alphabet] for letter in strng[0:max_str_len]] while len(vector) != max_str_len: vector = [*vector, [0 for char in alphabet]] return np.array(vector) The parts I mention as correct are indeed correct as this is not the first time I am training this model and have validated it. I need to update my models every month and when I was testing my architecture by running multiple models I came across this anomaly. Here is the incorrect code model.fit(X_train, to_categorical(Y_train, 2), epochs=1000, validation_data=(X_test, to_categorical(Y_test, 2)), verbose=2, shuffle=True) loss, accuracy = model.evaluate(X_test, to_categorical(Y_test, 2)) Output of this incorrect snippet is the same as the correct snippet log, just that the accuracy remains at 0.5454 for 12 epochs and the loss does not reduce. My sample data is at a split of 50k correct to 60k incorrect labels. So if the mode…
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/92025714
has comment: http://stackoverflow.com/comment/91985576
has comment: http://stackoverflow.com/comment/92002463

http://stackoverflow.com/a/52537355
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52537299
score: 1
has body: Use scipy.signal.argrelextrema: from scipy.signal import argrelextrema a = df.iat[argrelextrema(df[1].values, np.greater)[0][-1], 0] print (a) g
downvote count: 0

http://stackoverflow.com/comment/91995521
type: Comment
type: QuestionComment
has text: Your first mistake is not adding a language tag to the question
score: 0
comment on: http://stackoverflow.com/q/52462747

http://stackoverflow.com/q/52459977
has answer: http://stackoverflow.com/a/52460868
favorite count: 0
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/52460793
upvote count: 3
has answer: http://stackoverflow.com/a/52460039
has body: My dataframe : df Object quantity A 3 B 4 C 10 D 11 My desired result: df Object quantity A 3 B 4 C 4 C 4 C 2 D 4 D 4 D 3 My Goal here is to split the value stored in the column2 "quantity" so that it should be 4 or less than 4. Which method I can use to solve this problem? any suggestion would be appreciated.
downvote count: 1
type: Question
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52460039
has title: How to split the values inside the Dataframe using python
answer count: 3
has answer: http://stackoverflow.com/a/52460793

http://stackoverflow.com/comment/92373170
has text: This is fantastically detailed, thank you so much! I will read over it properly when I have 5 minutes to digest it all :)
type: Comment
comment on: http://stackoverflow.com/a/52703508
type: AnswerComment
score: 0

http://stackoverflow.com/a/52560730
has comment: http://stackoverflow.com/comment/92060338
type: Answer
has comment: http://stackoverflow.com/comment/92060717
has body: I would use the itertools module. &gt;&gt;&gt; from itertools import islice, imap, repeat &gt;&gt;&gt; from random import randint &gt;&gt;&gt; diceType = 5 &gt;&gt;&gt; list(islice(imap(random.randint, repeat(1), repeat(diceType)), 5)) [5, 5, 4, 5, 4] repeat creates infinite sequences of 1s and diceTypes. imap creates an infinite sequence of the result of calling randint(1, diceType) (each call pulls the next value of repeat(1) and repeat(diceType) as an argument. islice makes a finite iterator that takes only the first 5 elements of the infinite sequence, and list actually takes the values from the finite iterator. Along the same lines, without using itertools, is the following (using Python 2's version of map for simplicity): map(lambda f: f(1, diceType), [randint]*5) This creates a list with 5 separate references to randint, then maps a function that calls its arguments on 1 and diceType over that list. (Actually, the itertools version can be simplified using that same approach: list(islice(map(lambda f: f(1, diceType), repeat(randint)), 5)) )
answers question: http://stackoverflow.com/q/52560505
score: 0

http://stackoverflow.com/a/52570621
accepted answer of: http://stackoverflow.com/q/52562063
has body: My comment may be difficult to understand, so here is an example: class Gameclass(Widget): def on_touch_move(self, touch): if touch.x &lt; self.width / 3: self.player1.center_y = touch.y if touch.x &gt; self.width - self.width / 3: self.player2.center_y = touch.y def callback(self, btn_instance): self.player1.center_y = 22 self.player2.center_y = 250 btn1 = Button(text='click me') gc = Gameclass() btn1.bind(on_press=gc.callback) Note that you probably create an instance of Gameclass somewhere else in your code, and that instance should be used.
type: Answer
answers question: http://stackoverflow.com/q/52562063
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91963676
type: Comment
comment on: http://stackoverflow.com/a/52497738
has text: It didn't solve the issue! numpy appears in conda list, but does not work when imported in a python file.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52546154
downvote count: 2
has comment: http://stackoverflow.com/comment/92032797
tagged with: python
has answer: http://stackoverflow.com/a/52547162
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92032218
has comment: http://stackoverflow.com/comment/92032132
has answer: http://stackoverflow.com/a/52546437
has comment: http://stackoverflow.com/comment/92032282
has title: Code takes a lot of time to run for large numbers
has comment: http://stackoverflow.com/comment/92032187
has body: Given the number of squares in a board (e.g. scrabble or chess board), N and dimensions AxB, this code tries to determine all possible dimensional combinations that can give N number of squares in the board. Example: N = 8 There are four possible dimensional combinations to obtain exactly 8 squares in the board. So, the code outputs board dimensions 1x8 2x3, 3x2 and 8x1. The 8x1 boards have eight 1x1 squares; the 3x2 boards have six 1x1 squares and two 2x2 squares. Here is my solution: def dims(num_sqrs): dim_list=[] for i in range(1,num_sqrs+1): temp = [] for x in range(1,num_sqrs+1): res = 0 a = i b = x while (a != 0) and (b !=0): res = res + (a*b) a = a -1 b = b-1 if res == num_sqrs: dim_list.append((i,x)) print(dim_list) dims(8) However, this code takes too much time to run for large values of N. Any suggestion to optimize the efficiency of the code will be much appreciated.
type: Question
has comment: http://stackoverflow.com/comment/92032271
possible better answer: http://stackoverflow.com/a/52546437
tagged with: algorithm
has comment: http://stackoverflow.com/comment/92032151
has comment: http://stackoverflow.com/comment/92032255
accepted answer: http://stackoverflow.com/a/52547162
has comment: http://stackoverflow.com/comment/92032111
has comment: http://stackoverflow.com/comment/92033003
has answer: http://stackoverflow.com/a/52560797
score: 0
has comment: http://stackoverflow.com/comment/92032545
has comment: http://stackoverflow.com/comment/92032182
answer count: 4
has comment: http://stackoverflow.com/comment/92032341
favorite count: 0
has answer: http://stackoverflow.com/a/52561180
has comment: http://stackoverflow.com/comment/92032258
upvote count: 2

http://stackoverflow.com/a/52528494
score: 0
type: AcceptedAnswer
type: Answer
has body: if you had imported the file instead of running it directly, a .pyc file would have been created containing the compiled bytecode which you could easily transform back into the regular python code (minus the comments.) However, you did run the script directly, so there is no .pyc file. If you deleted the file in a GUI file browser, the file might have been sent into a "trash bin" where you might be able to recover it from. Assuming you deleted the file using the "rm" command in the terminal, however, the data might still be on the disk provided it hasn't been overwritten ("deleting" files normally just marks the data to be overwritten on the disk) If you're lucky, you might be able to recover it. The process isn't exactly simple, though, and there's no guarantee that the file hasn't already been overwritten since the disk is pretty much in constant use when you're using the system. More info on that here: https://help.ubuntu.com/community/DataRecovery There's also a handy utility called lsof which you can use to recover a 'deleted' file if there's still an open file handle for it: https://support.hpe.com/hpsc/doc/public/display?docId=emr_na-c00833030 Also, in the future, I recommend using "rm -i" instead of just rm with no options as that will at least prompt you to confirm if you're sure you want to delete something first. You can also make an alias for this in your shell so that regular rm just points to 'rm -i'
answers question: http://stackoverflow.com/q/52528278
accepted answer of: http://stackoverflow.com/q/52528278

http://stackoverflow.com/a/56837041
type: Answer
answers question: http://stackoverflow.com/q/52562753
downvote count: 0
score: 1
upvote count: 1
has body: Not sure why but using root.resizable(False, False) to stop the window size being changed means a new window is created rather than a tab.

http://stackoverflow.com/comment/99787676
type: Comment
type: AnswerComment
has text: Thanks buddy. btw, could you please use f-strings?
comment on: http://stackoverflow.com/a/56591102
score: 0

http://stackoverflow.com/comment/92078318
has text: Sure :D This is just a university assignment.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52570225

http://stackoverflow.com/a/52464592
upvote count: 14
answers question: http://stackoverflow.com/q/52464451
has comment: http://stackoverflow.com/comment/91871185
has comment: http://stackoverflow.com/comment/91879387
type: Answer
downvote count: 0
has body: In addition to U9-Forward's answer, one using filter and mean: from statistics import mean list1 = [50, 83, 26, 65, 92, 29, 77, 64] average = mean(filter((50).__le__, list1)) print('%.2f' % average)
score: 14
has comment: http://stackoverflow.com/comment/91871148

http://stackoverflow.com/a/52529659
answers question: http://stackoverflow.com/q/52529537
score: 0
type: Answer
has body: You reinitialize the variable cash with 20 before every game. To fix the game, just move that code out of the loop. The initialization of win and loss can also be moved out of the loop since they do not change. Same for the from random import randint statement, it is considered a good practice to put all import statements at the top of the file. from random import randint #Setting up RNG loop = "y" win = 3 loss = 2 cash = 20 while loop == "y" or loop == "yes": dice = (randint(1,10)) dice2 = (randint(1,10)) roll = (dice + dice2) if roll == 3 or roll == 7 or roll == 11 or roll == 17: cash += win else: cash -= loss #Starting game print("""Welcome to, Gambling for School! You have $20 and must earn as much money as possible If you roll a 3, 7, 11, or 17, you will win $3 but any other number takes $2 You have a 20% of winning """) x = input("Press ENTER to start.") #Results if roll == 11 or roll == 8 or roll == 18: print("You rolled an " + str(roll) + "!") else: print("You rolled a " + str(roll) + "!") print("") print("Cash - $" + str(cash)) loop = input("Continue? (Y/N) ").lower()

http://stackoverflow.com/q/52513327
has comment: http://stackoverflow.com/comment/91966436
has body: I am trying to send variables to Zingharts to set background colors. This is the format I need to create to set the backgrounds. "styles":[ { "background-color":"pink", }, { "background-color":"red", }, { "background-color":"green", }, ] I created the string with python and then print it out in the chart: 'marker' : { "styles": var-background, }, This is the result I get. You will see I get the extra ' at the start and end. This prevents the code from working. 'styles': ' [{"background-color":"#C2D3EC" }, {"background-color":"#52702A" }, {"background-color":"#C2D3EC" }, {"background-color":"#82B6FF" }, {"background-color":"#52702A" } ] ' How can I print the var-background string without the beginning and ending single quote marks? Thank you.
has comment: http://stackoverflow.com/comment/91966374
has comment: http://stackoverflow.com/comment/91966420
tagged with: http://stackoverflow.com/tag/json
type: Question
possible better answer: http://stackoverflow.com/a/52515587
answer count: 2
tagged with: string
favorite count: 0
tagged with: python
tagged with: dictionary
has title: Removing the single quotes when printing string?
has answer: http://stackoverflow.com/a/52515587
upvote count: 0
score: -4
has answer: http://stackoverflow.com/a/52513396
accepted answer: http://stackoverflow.com/a/52513396
downvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/92036919
type: Comment
type: QuestionComment
has text: Thank you for guiding me in the right direction .Your suggestion is correct . I will implement it tomorrow.Following your recommendation I found these examples very useful: https://marshmallow.readthedocs.io/en/3.0/examples.html
comment on: http://stackoverflow.com/q/52547705
score: 0

2captcha
tags question: http://stackoverflow.com/q/52446075
tag name: 2captcha
type: Tag

http://stackoverflow.com/q/52490250
favorite count: 0
has answer: http://stackoverflow.com/a/52490294
answer count: 5
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52491537
has answer: http://stackoverflow.com/a/52490525
has answer: http://stackoverflow.com/a/52491741
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52491292
has body: I have a dictionary currently setup as {'name': 'firm', 'name':'firm', etc}, Where keys are analyst names and values are analyst firms. I am trying to create a new dictionary where the new values are the old k,v pairs and the associated key is simply the index (1, 2, 3, 4, etc). Current code is below: num_analysts = len(analysts.keys()) for k,v in analysts.items(): analysts_dict = dict.fromkeys(range(num_analysts), [k,v]) Current result Each numeric key is getting given the same value (old k,v pair). What is wrong with my expression?
tagged with: data-structures
score: 0
has title: Creating a dict containing a sub-dict as the new value with the index as the key
has comment: http://stackoverflow.com/comment/91921281

http://stackoverflow.com/comment/92100755
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52544283
has text: Yes, this works! Thanks so much. Want to write it as the answer so I can give you credit?
score: 0

http://stackoverflow.com/a/57881778
has comment: http://stackoverflow.com/comment/103026735
downvote count: 1
has body: I had the same issue. Fixed it by using "integratedTerminal". PS: My system is Windows 7. { "name": "Debug", "type": "python", "request": "launch", "program": "${workspaceFolder}/main.Py", "console": "integratedTerminal" }
upvote count: 7
type: Answer
score: 6
answers question: http://stackoverflow.com/q/52462599

http://stackoverflow.com/q/52501887
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: LogoutView() received an invalid keyword 'name'. as_view only accepts arguments that are already attributes of the class?
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/71261095
type: Question
downvote count: 0
has body: Hi I am trying to name my url and I get the following error: error: LogoutView() received an invalid keyword 'name'. as_view only accepts arguments that are already attributes of the class. url: url(r'^logout/$', auth_views.LogoutView.as_view(template_name='accounts/logout.html', name='logout')), working on a project and stuck atm. TIA
has comment: http://stackoverflow.com/comment/91944821
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52440881
accepted answer: http://stackoverflow.com/a/52441149
has title: How to get list items next to each other in stead of beneath each other using python/selenium
has answer: http://stackoverflow.com/a/52441149
has body: below is the code I'm using with open ('Argentinie1Form.txt', 'w', encoding='utf-8') as r: driver = webdriver.Chrome("C:/Users/gdebr/Desktop/chromedriver.exe") driver.get("https://int.soccerway.com/national/argentina/primera-division/20182019/regular-season/r47779/") wait = WebDriverWait(driver, 10) elm = wait.until(EC.presence_of_element_located((By.XPATH,"""//*[@id="page_competition_1_block_competition_tables_7_1_4"]"""))) elm.click() time.sleep(2) with open ('Argentinie1Form.txt', 'a', encoding='utf-8') as r: teams_list = driver.find_elements_by_xpath("//table[contains(@id, 'page_competition_1_block_competition_tables_7_block_competition_form_table_1_table')]/tbody/tr/td[3]/a[1]") for items in teams_list: r.write(items.get_attribute('title')+'\n') MatchesPlayed_list = driver.find_elements_by_xpath("//table[contains(@id, 'page_competition_1_block_competition_tables_7_block_competition_form_table_1_table')]/tbody/tr/td[4]") for matches in MatchesPlayed_list: r.write(matches.text+'\n') The output I get is: But in fact I want somethink like this: Racing Club,5 and below this the next team and it's number What am I dooing wrong here?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: selenium
type: Question

http://stackoverflow.com/comment/91997705
type: Comment
comment on: http://stackoverflow.com/a/52529179
has text: @JohnWahlberg see comments you can use list comprehension or good old for loop
type: AnswerComment
score: 0

http://stackoverflow.com/comment/125320174
has text: There's some settings about buffering that can be adjusted. There's a related discussion on the Jupyter Discourse Community Forum [here](https://discourse.jupyter.org/t/how-to-show-the-result-of-shell-instantly/8947?u=fomightez).
score: 1
comment on: http://stackoverflow.com/q/52545512
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52452596
has title: Factorial question without function stuck
has answer: http://stackoverflow.com/a/52452786
favorite count: 0
accepted answer: http://stackoverflow.com/a/52452786
tagged with: python
score: -2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52452796
downvote count: 3
has comment: http://stackoverflow.com/comment/91848733
has answer: http://stackoverflow.com/a/52452796
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91848740
has comment: http://stackoverflow.com/comment/91848519
linked to: http://stackoverflow.com/q/5136447
has body: So I have a question that goes find the factorial of 25! and I am not allowed to use the math.facorial function. So far I did }} input() }}}}25 and I was wondering is there anyway I can manipulate that to give me the factorial. Any help is appreciated.
answer count: 2

http://stackoverflow.com/q/52459104
score: 0
answer count: 3
tagged with: upsert
has answer: http://stackoverflow.com/a/52462024
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52460199
has answer: http://stackoverflow.com/a/52469222
tagged with: web-scraping
tagged with: scrapy
type: Question
tagged with: mongodb
has title: How can I trigger a Mongodb import once a Scrapy Spider has completed?
has body: I am using Scrapy, the Python library, to scrape websites and generate json output files at regular intervals. For efficiency, I want to do bulk upserts of these json files into Mongodb after each spider is completed. I believe I can do the upsert like so: mongoimport -c &lt;collection&gt; -d &lt;db&gt; --mode merge --file test.json However, I am wondering what is the best way to to trigger this import once the spider has complete? And how? I was hopeful I could use the close_spider method described here: https://doc.scrapy.org/en/latest/topics/item-pipeline.html#writing-your-own-item-pipeline However, after playing around with it I discovered that the json file is only created, and not written to when inside this method. It would be nice if there was some way for me to listen for a new file in a certain directory and then execute the import statement above. Perhaps, this can all be done in a bash script?s

http://stackoverflow.com/comment/91879969
type: AnswerComment
score: 0
type: Comment
has text: What do you mean by return static files? I just want images to be displayed in the browser. Do i need a function for that? I'am using Apache production server not the embedded development server and i cant even http://superhost.gr/static/img/digital.gif for example. The path is correct i just do NOT understand why the file is NOT being displayed in the browser. If the url cannot be views in the browser HOW Bottle will be bale to display it? Please tell em what you want me to try!
comment on: http://stackoverflow.com/a/52468934

http://stackoverflow.com/a/52568784
has comment: http://stackoverflow.com/comment/92074632
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52568734
downvote count: 0
has body: There are several issues with your code: You need to return a value from your fruit function You need to give the fruit function a different name from the list You need to actually call the fruit function at some point Avoid using str as a variable name, as this is a built-in function in Python. The sortby function works fine, however. fruit = [["Apples", 30], ["Bananas", 100], ["Pears", 0], ["Peaches", 20]] def sortby(par): return par[1] def sort_fruit(): rate = [] fruit.sort(key=sortby, reverse=True) for success in fruit: rate.append(success[0]) rate.append(success[1]) return rate print(sort_fruit())
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92077166
accepted answer of: http://stackoverflow.com/q/52568734

http://stackoverflow.com/a/52466018
has comment: http://stackoverflow.com/comment/92041209
type: Answer
has comment: http://stackoverflow.com/comment/91873765
has body: This can happen when you are either having 1. Insifficient data/opportunity to arrive a convergence 2. Model is largely underfitting, and each run is a variation
score: 0
has comment: http://stackoverflow.com/comment/91874283
has comment: http://stackoverflow.com/comment/91873923
answers question: http://stackoverflow.com/q/52465957

http://stackoverflow.com/q/52538759
has comment: http://stackoverflow.com/comment/92078480
has comment: http://stackoverflow.com/comment/92038591
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52571234
score: 1
has comment: http://stackoverflow.com/comment/92018362
type: Question
upvote count: 2
tagged with: ctypes
has comment: http://stackoverflow.com/comment/92047161
answer count: 1
favorite count: 0
downvote count: 1
tagged with: python
has body: Hi just need some guidance with python as I am still a noob, I converted the following snippet of C source code to python. C snippet: Typedef struct packet_s { union { uint16_t fcf; struct { uint16_t type:3; uint16_t security:1; uint16_t framePending:1; uint16_t ack:1; uint16_t ipan:1; uint16_t reserved:3; uint16_t destAddrMode:2; uint16_t version:2; uint16_t srcAddrMode:2; } fcf_s; }; uint8_t seq; uint16_t pan; locoAddress_t destAddress; locoAddress_t sourceAddress; uint8_t payload[128]; } __attribute__((packed)) packet_t; python: class fcf_s(Structure): _fields_ = [ ("type", c_uint, 3), ("security", c_uint, 1), ("framePending", c_uint, 1), ("ack", c_uint, 1), ("ipan", c_uint, 1), ("reserved", c_uint, 3), ("destAddrMode", c_uint, 2), ("version", c_uint, 2), ("srcAddrMode", c_uint, 2) ] class fcf_union(Union): _fields_ = [ ("fcf", c_uint), ("fcf_s", fcf_s) ] class packet_s(Structure): _fields_ = [ ("fcf_union", fcf_union), ("seq", c_uint), ("pan", c_uint), ("destAddress", c_uint64 * 8), ("sourceAddress", c_uint64 * 8), ("payload", c_uint * 128) ] edit 1: The Function used to convert to bytes def writeValueToBytes(data, val, n): """ This function writes the value specified and convert it into bytes to write in the array Args: data: The array you want to write the value into. val: The value you want to write in the array. n: The size of the array. Return: The modified array of bytes. """ for i in range(0, n): data[i] = int(((val &gt;&gt; (i * 8)) &amp; C.MASK_LS_BYTE)) return data once the packet_s structure has been populated with the correct data, I need to pass it to function with splits it into bytes to be written via spi to the DWM1000 UWB radio. The type error I get is " TypeError: packet_s is not iterable", how do I fix this ? Thanks in advance.
has title: making a ctypes structure iterable
has comment: http://stackoverflow.com/comment/92036402
accepted answer: http://stackoverflow.com/a/52571234

http://stackoverflow.com/comment/92082378
has text: Yes this works too! I love how simple and straightforward this is! Still learning how to simplify code as I am a beginner. Thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52572953
type: Comment

http://stackoverflow.com/q/52544907
tagged with: python
has comment: http://stackoverflow.com/comment/92030267
has body: I'm trying to program a board game called Djambi, most of its pieces can move like the queen from chess. I created a list to save all valid destinations of a piece, which can be in 8 different directions, so I used 8 for loops, but the code of each loop is almost identical: This is the loop for possible movements to the right: count = 0 for j in range(y+1,9): if P == 3 and count == 2: break if re.search(r'[■]',board[x][j]): pos = str(x)+str(j) destinations.append(pos) elif re.search(r'\d', board[x][j]): if re.search(r'' + chip[0], board[x][j]) or P == 1 or P == 0: break else: pos = str(x)+str(j) destinations.append(pos) break elif re.search(r'[░]',board[x][j]): if P == 0: pos = str(x)+str(j) destinations.append(pos) break else: break else: if P == 2: pos = str(x)+str(j) destinations.append(pos) else: continue count += 1 The loop for movements to the left can be simplified with the one above, but the problem is for the loops for movements up count = 0 for i in range(x+1,9): if P == 3 and count == 2: break if re.search(r'[■]',board[i][y]): pos = str(i)+str(y) destinations.append(pos) elif re.search(r'[\d]',board[i][y]): if re.search(r'' + chip[0], board[i][y]) or P == 1 or P == 0: break else: pos = str(i)+str(y) destinations.append(pos) break elif re.search(r'[░]',board[i][y]): if P == 0: pos = str(i)+str(y) destinations.append(pos) break else: break else: if P == 2: pos = str(i)+str(y) destinations.append(pos) else: continue count += 1 and down, because the order of variables that change is different, also for diagonal movements: count = 0 for i,j in zip( range(x+1,9) , range(y+1,9) ): if P == 3 and count == 2: break if re.search(r'[■]',board[i][j]): pos = str(i)+str(j) destinations.append(pos) elif re.search(r'[\d]',board[i][j]): if re.search(r'' + chip[0], board[i][j]) or P == 1 or P == 0: break else: pos = str(i)+str(j) destinations.append(pos) break elif re.search(r'[░]',board[i][j]): if P == 0: pos = str(i)+str(j) destinations.append(pos) break else: break else:…
tagged with: python-3.x
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/92030436
type: UnansweredQuestion
score: 1
has title: How to avoid repeating chunks of code that are almost identical?
has comment: http://stackoverflow.com/comment/92029798
has comment: http://stackoverflow.com/comment/92029773
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/92029803
has comment: http://stackoverflow.com/comment/92029925
has comment: http://stackoverflow.com/comment/92030445
favorite count: 0
has comment: http://stackoverflow.com/comment/92030148
has comment: http://stackoverflow.com/comment/92030354

http://stackoverflow.com/q/52447266
has answer: http://stackoverflow.com/a/52447641
tagged with: javascript
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52447664
tagged with: jquery
tagged with: flask
tagged with: ajax
tagged with: python
has body: I'm trying to run some python code which is served via Flask and I want that python code to return a value to javascript so that I can use it there. In this case, I have a button in HTML, When I hit it, I want a python code (served via Flask) to run and it should return "Hello" which I can use it in HTML like displaying it or storing it another variable. Here are my codes: ajax.html country display Display here {{ temp }} flaskajax.py from flask import Flask app = Flask(__name__) @app.route("/hello", methods=['GET', 'POST']) def Hello(): message = "Hello" return render_template("ajax.html", temp=message) if __name__ == '__main__': app.run(debug=True) webserver.py import SimpleHTTPServer import SocketServer PORT = 8888 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever() What I'm doing is, I'm running webserver.py and I'm navigating to http://localhost:8888/ajax.html and when I press display button I'm seeing this error Error Message I don't even know If I'm doing it in the right way or not, I don't understand the GET and POST methods also. If anyone understood what I'm actually trying to do and if they can explain to me what really is happening behind the hood, I will be grateful. Please comment if you need any additional information.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52447641
has answer: http://stackoverflow.com/a/52447664
type: Question
has title: Run python code which is served via flask in javascript when a button is clicked

systemd
tags question: http://stackoverflow.com/q/52495742
tag name: systemd
type: Tag
tags question: http://stackoverflow.com/q/52520642

http://stackoverflow.com/comment/91916519
score: 1
has text: [This is the issue](https://github.com/matplotlib/matplotlib/issues/12239) and [this is the fix](https://github.com/matplotlib/matplotlib/pull/12241). I suppose you can apply it manually, i.e. making spines invisible before calling `tight_layout`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52487395

http://stackoverflow.com/comment/92066352
score: 1
has text: I think you can, why not? Though you will need to duplicate processess, variables and detections, also nesting loops within loops within loops (which slows down the program sometimes). Though at the end, the bulk of your code will make it hard to debug, and/or to read. Learning how to use classes will make it soooo easy to do this without as much lines of code.
type: Comment
comment on: http://stackoverflow.com/q/52562504
type: QuestionComment

http://stackoverflow.com/comment/92069347
comment on: http://stackoverflow.com/a/52565713
score: 0
type: AnswerComment
has text: df['ColB (New datetime)'] = df['ColA (Localized datetime)'].apply(lambda x: x.replace(tzinfo=None)) works. Thanks everyone for your time :)
type: Comment

http://stackoverflow.com/comment/91855756
score: 0
comment on: http://stackoverflow.com/q/52455597
type: Comment
type: QuestionComment
has text: Good. Now what would be helpful is if this question included that code that didn't work, because in principle that is of course the correct strategy.

http://stackoverflow.com/comment/91931486
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52495474
has text: Possible duplicate of [Django Filters - or?](https://stackoverflow.com/questions/739776/django-filters-or)

http://stackoverflow.com/a/52575577
has body: There's no need to use a dict to hold the base digits, we can just put them into a string: alph = '0123456789abcdefghijlmnopqrstuvwxyz!' We can get the correct digits by doing the division with remainder in a loop. If the input number is zero, the loop won't produce any digits, so we handle that as a special case. This code will work with a base_digits string of any length, but I'll just use a short string to keep the output short. This code works correctly on Python 2 and Python 3. from __future__ import print_function def int_to_base(n, base_digits): if n == 0: return base_digits[0] base = len(base_digits) digits = [] # Build a list of digits in reverse order while n: n, r = divmod(n, base) digits.append(base_digits[r]) # Reverse the digits and join them into a string return ''.join(digits[::-1]) base_digits = '0ab' for i in range(28): print(i, int_to_base(i, base_digits)) output 0 0 1 a 2 b 3 a0 4 aa 5 ab 6 b0 7 ba 8 bb 9 a00 10 a0a 11 a0b 12 aa0 13 aaa 14 aab 15 ab0 16 aba 17 abb 18 b00 19 b0a 20 b0b 21 ba0 22 baa 23 bab 24 bb0 25 bba 26 bbb 27 a000 Another way to do this is to create a generator that counts using the base digits. You can loop over the generator in a for loop, or fetch its next value using the next function. def base_counter(base_digits): """ An infinite iterator that counts using base_digits as its digits """ base = len(base_digits) digits = [0] while True: yield ''.join([base_digits[d] for d in reversed(digits)]) digits[0] += 1 pos = 0 while digits[pos] == base: digits[pos] = 0 pos += 1 if pos == len(digits): digits.append(1) else: digits[pos] += 1 base_digits = '0ab' counter = base_counter(base_digits) for i, v in enumerate(counter): print(i, v) if i == 27: break print('next', next(counter)) This produces the same output as the previous version, and then it prints next a00a
has comment: http://stackoverflow.com/comment/92086930
has comment: http://stackoverflow.com/comment/92088086
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92096640
has comment: http://stackoverflow.com/comment/92087739
has comment: http://stackoverflow.com/comment/92086801
accepted answer of: http://stackoverflow.com/q/52508757
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52508757
score: 2
has comment: http://stackoverflow.com/comment/92086907

http://stackoverflow.com/comment/91870972
score: 0
has text: I used this: https://stackoverflow.com/questions/33404752/removing-emojis-from-a-string-in-python/33417311#comment54637275_33417311
comment on: http://stackoverflow.com/q/52464119
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91954869
comment on: http://stackoverflow.com/a/52507159
score: 0
type: AnswerComment
type: Comment
has text: `apply` + a custom function is not recommended with Pandas where vectorised operations are available.

http://stackoverflow.com/comment/92093484
has text: What shall the function print for `a = 1; b = a; function(a)`?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52579189

http://stackoverflow.com/a/52586353
downvote count: 0
has body: Another way, just for fun :) would be limiting the range of j with current value of i: &gt;&gt;&gt; for i in range(1, -1, -1): for j in range(i, 10+i): print (j, end=" ") print() 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 OR &gt;&gt;&gt; for i in range(2): for j in range(1-i, 11-i): print (j, end=" ") print()
upvote count: 2
answers question: http://stackoverflow.com/q/52585210
type: Answer
score: 2

http://stackoverflow.com/q/52496980
possible better answer: http://stackoverflow.com/a/52527069
has comment: http://stackoverflow.com/comment/91934271
has answer: http://stackoverflow.com/a/52527069
favorite count: 0
accepted answer: http://stackoverflow.com/a/52497025
has title: How to Register different type user with profile in django?
has body: I am new to django and I started a new project. shortly, I want to register different type of users (Teacher, Student, Stuff) with their profile picture. I made a one to one field from user to profile and below is my code and I get the following error. if you have any suggestion for my registration purpose, I want to register a different type of user with a profile picture. models.py from django.db import models from django.contrib.auth.models import User,AbstractUser from django.conf import settings from django.dispatch import receiver from django.db.models.signals import post_save class User(AbstractUser): USER_TYPE_CHOICES = ( (1,'Student'), (2,'Teacher'), (3,'Stuff') ) profile = models.OneToOneField(on_delete=models.CASCADE, related_name='user') user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='profile') photo = models.ImageField(upload_to='users/%Y/%m/%d/') def __str__(self): return 'Profile {}'.format(self.user.username) its the form from django import forms from django.contrib.auth.models import User from .models import Profile class UserCreationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, label='Password') password2 = forms.CharField(widget=forms.PasswordInput, label='Repeat Password') class Meta: model = User fields = ('username', 'first_name', 'last_name') def clean_password(self): cd = self.cleaned_data if cd['password']!=cd['password2']: raise forms.ValidationError('password no match') return cd['password2'] class ProfileCreationForm(forms.ModelForm): class Meta: model = Profile fields = ('photo',) its my view module from django.shortcuts import render from .forms import ProfileCreationForm, UserCreationForm from .models import Profile from django.http import HttpResponse def sign_up(request): if request.method == 'POST': user_form = UserCreationForm(instance=request.user,data=req…
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: django
type: Question
tagged with: django-registration
has answer: http://stackoverflow.com/a/52497025
answer count: 2
downvote count: 0

http://stackoverflow.com/q/52478317
has comment: http://stackoverflow.com/comment/91914169
has comment: http://stackoverflow.com/comment/91897887
has answer: http://stackoverflow.com/a/52481645
tagged with: pandas
has comment: http://stackoverflow.com/comment/91903436
tagged with: python
linked to: http://stackoverflow.com/q/7837722
has comment: http://stackoverflow.com/comment/91911467
has body: I have a dataframe in the following structure as of now. I saw this post here, in which the second answer says that using numpy array for looping huge dataframe is the best. This is my requirement: Loop through unique dates Within unique dates in the dataframe, loop through unique session. Once I'm inside unique session within unique dates, I need to do some operations Currently I'm using for loop, but its unbearably slow. Can anyone suggest how to use numpy arrays to meet my requirements? as suggested in this post here? EDIT: I'm elaborating my requirement here: 1. Loop through unique dates Which would give me the following dataframe: 2. Within unique dates, loop through unique sessionId's. Which would give me something like this: 3. Once within unique sessionId within unique date, Find the timestamp difference between last element and first element This time difference is added to a list for each unique session. 4. Outside the 2nd loop, I will take the average of the list that is created in the above step. 5. The value we get in step 4 is added to another list The aim is to find the average time difference between the last and first message of each session per day
type: Question
accepted answer: http://stackoverflow.com/a/52481645
has comment: http://stackoverflow.com/comment/91900693
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91898230
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91897875
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/91900756
has title: Use numpy arrays to speed up iteration in pandas dataframe
has comment: http://stackoverflow.com/comment/91898354
answer count: 1

http://stackoverflow.com/a/52519208
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52511653
answers question: http://stackoverflow.com/q/52511653
type: AcceptedAnswer
downvote count: 0
has body: This may not be the answer you are expecting for since I don't know anything about guitars and guitar chords. Please take a look. const SVG_NS = 'http://www.w3.org/2000/svg'; let json = [ { "id": "404", "name": "Cb", "intervals": "", "positions": [ { "id": "1226", "position": "x,2,4,4,4,2", "fingerings": "13331;12341", "picture": "", "chord_id": "404", "instrument_id": "1" }, { "id": "1231", "position": "7,9,9,8,7,7", "fingerings": "134211", "picture": "", "chord_id": "404", "instrument_id": "1" }, { "id": "1251", "position": "7,6,4,4,4,7", "fingerings": "321114", "picture": "", "chord_id": "404", "instrument_id": "1" } ] } ] for(let j = 0; j &lt; json[0].positions.length; j++){ let position = json[0].positions[j].position.replace("x","").split(","); let min = Math.min.apply(null, position); let displacement = min &lt; 1 ? 1 : min; let svg = drawSVGElement("svg", {viewBox:"0 0 70 60"}, wrap); drawGrid(); for(let i = 0; i &lt; position.length; i++ ){ if(parseInt(position[i]) &gt; 0){ let cp = {// circle position x : 10 + parseInt(i) * 10, y : 15 + (position[i] - displacement)*10 } drawSVGElement("circle",{cx:cp.x,cy:cp.y,r:4}, svg) } } function drawGrid(){ let d = ""; for(let i = 1; i &lt; 6; i++){ d+=`M10,${i*10}H60` } for(let i = 1; i &lt; 7; i++){ d+=`M${i*10},10V50` } let path = drawSVGElement("path",{"d": d}, svg); } function drawSVGElement(tag, o, parent) { var svgElement = document.createElementNS(SVG_NS, tag); for (let name in o) { if (o.hasOwnProperty(name)) { svgElement.setAttributeNS(null, name, o[name]); } } parent.appendChild(svgElement); return svgElement; } } svg{border:1px solid; max-height:100vh;} path{fill:none;stroke:red;stroke-linecap: round} &lt;div id="wrap"&gt;&lt;/div&gt;
has comment: http://stackoverflow.com/comment/91978179
type: Answer

http://stackoverflow.com/comment/91916934
comment on: http://stackoverflow.com/a/52480245
has text: OK. So I have a very important update on this... the placement BELOW the fetchone() and fetchall() is CORRECT! I have spent the last hour trying to retreive my @@IDENTITY value and was unable to do that because of the commit being placed before the fetch()
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92076619
score: 0
type: Comment
type: QuestionComment
has text: @CoolestNerdIII I updated the question. Any ideas how to solve this?
comment on: http://stackoverflow.com/q/52569690

http://stackoverflow.com/comment/92063218
type: Comment
has text: @JacobClark No, the comments are volatile, they can be deleted and your question will not be useful, post a answer and mark it as correct or invite the person who helped you to do it, otherwise use `@` to notify another user of a message .
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52561762

http://stackoverflow.com/q/52579847
has title: Dynamically generating dictionary entries with unique names
favorite count: 0
possible better answer: http://stackoverflow.com/a/52579963
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92094825
upvote count: 1
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52579930
has body: I'm trying to dynamically generate cells. Each cell has a name, defined as a key of a dictionary. The value is an instance of a class, containing three parameters (strength, intelligence, energy). import random class Cell: def __init__(self, energy, strength, intelligence): self.energy = energy self.strength = strength self.intelligence = intelligence cells = {} k = 1 while k &lt; 100: key = "a" + str(k) print("Generating cell: " + key) cells[key] = Cell(random.randint(1, 100),random.randint(1, 100),random.randint(1, 100)) k += 1 #Generate cells My problem is with names. This code was good enough for the first generation of cells, but when I need to make more, the new cells can override old ones due a name conflict. Is there a way to generate random, but unique cell names to avoid such conflict? I tried to create new names starting with 'a' and the lowest number which doesn't already exist. However, cells die throughout my program. My approach would simply fill in the gaps, which would make it hard to determine which generation the cell is from.
has answer: http://stackoverflow.com/a/52579963
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92094795
has answer: http://stackoverflow.com/a/52579930
downvote count: 0
tagged with: python

http://stackoverflow.com/a/52579697
score: 1
has comment: http://stackoverflow.com/comment/92422738
upvote count: 1
answers question: http://stackoverflow.com/q/52579601
downvote count: 0
has body: As far as I am aware, there is no native functionality for this. For example, the maximum length of all values within a series is not stored anywhere. However, you can implement your logic more efficiently via a list comprehension and f-strings: data_types = [(col, arr[col].dtype if arr[col].dtype != 'O' else \ f'U{df[col].astype(str).str.len().max()}') for col in arr.dtype.names]
type: Answer

http://stackoverflow.com/q/52558519
has comment: http://stackoverflow.com/comment/92064618
score: 22
tagged with: bluez
has comment: http://stackoverflow.com/comment/92130164
has comment: http://stackoverflow.com/comment/92128070
has comment: http://stackoverflow.com/comment/92128080
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92128199
has comment: http://stackoverflow.com/comment/92128214
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92129866
has comment: http://stackoverflow.com/comment/92129930
tagged with: python
has comment: http://stackoverflow.com/comment/92129675
has body: I'm trying to get a bluetoothe device working in Python on Bluez5. Currently I have the following: #set up a bluez profile to advertise device capabilities from a loaded service record def init_bluez_profile(self): print("Configuring Bluez Profile") #setup profile options service_record=self.read_sdp_service_record() opts = { "ServiceRecord":service_record, "Role":"server", "RequireAuthentication":False, "RequireAuthorization":False, "Name":BTKbDevice.MY_DEV_NAME, "AutoConnect":True } #retrieve a proxy for the bluez profile interface bus = dbus.SystemBus() self.manager = dbus.Interface(bus.get_object("org.bluez","/org/bluez"), "org.bluez.ProfileManager1") self.profile = BTKbBluezProfile(bus, BTKbDevice.PROFILE_DBUS_PATH) self.manager.RegisterProfile(BTKbDevice.PROFILE_DBUS_PATH, BTKbDevice.UUID, opts) print("Profile registered ") This code executes properly and the profile code is the standard one from teh bluez test cases: class BTKbBluezProfile(dbus.service.Object): fd = -1 @dbus.service.method("org.bluez.Profile1", in_signature="", out_signature="") def Release(self): print("Release") mainloop.quit() @dbus.service.method("org.bluez.Profile1", in_signature="", out_signature="") def Cancel(self): print("Cancel") @dbus.service.method("org.bluez.Profile1", in_signature="oha{sv}", out_signature="") def NewConnection(self, path, fd, properties): self.fd = fd.take() print("NewConnection(%s, %d)" % (path, self.fd)) for key in properties.keys(): print ('key ' + key + ' value ' + properties[key]) if key == "Version" or key == "Features": print(" %s = 0x%04x" % (key, properties[key])) else: print(" %s = %s" % (key, properties[key])) @dbus.service.method("org.bluez.Profile1", in_signature="o", out_signature="") def RequestDisconnection(self, path): print("RequestDisconnection(%s)" % (path)) if (self.fd &gt; 0): os.close(self.fd) self.fd = -1 def __init__(self, bus, path): dbus.service.Object.__init__(self, bus, path) However when I get connections/disconnections nothing work…
has answer: http://stackoverflow.com/a/62881439
has comment: http://stackoverflow.com/comment/92057535
has comment: http://stackoverflow.com/comment/92128105
has comment: http://stackoverflow.com/comment/92128233
has comment: http://stackoverflow.com/comment/92128771
type: Question
upvote count: 22
has title: Bluez Profile Registration
has comment: http://stackoverflow.com/comment/92129313
has comment: http://stackoverflow.com/comment/92130075

http://stackoverflow.com/comment/92075737
has text: @Erik thank you for this. I have managed to get it to come up one by one, however, it just doesn't stop. Any idea?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52562511

http://stackoverflow.com/a/52472295
has body: One way to make it work is to have the Button create the timer. Start by adding a start_timer() method to the ContScreen class: class ContScreen(Screen): def start_timer(self, *args): timer = Timer1(size_hint=(0.2, 0.2)) self.add_widget(timer) timer.start() For this to work, make three other changes: Change your main.kv file to make a root widget (eliminate the &lt;&gt; surrounding ContScreen). Change the on_press for the button in the .kv file by replacing t1.start() with root.start_timer(). Eliminate the t1 = Timer1() statement from your build method in the XGApp class. Another approach would be to create the Timer1 in the .kv file, and just start it running when the Button is pressed. To do this, change your .kv file to include a Timer: ContScreen: DigitalClock: pos_hint: {'center_x': 0.1, 'center_y': 0.9} size_hint: (0.075, 0.075) StackLayout orientation: "tb-rl" spacing: 15 Button: text: "1" size_hint: None, .16 width: 225 on_press: self.background_color = (1.7, 0, 1.7, 1) timer.start() Timer1: id: timer text: '0.0' size_hint: (0.2, 0.2) Move your backbone = Builder.load_file("main.kv") to after the definition of the Timer1 class. And change the ContScreen class back to: class ContScreen(Screen): pass
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52460513
has comment: http://stackoverflow.com/comment/91886597
has comment: http://stackoverflow.com/comment/91886481

http://stackoverflow.com/comment/91982929
type: Comment
comment on: http://stackoverflow.com/q/52521068
has text: It does appear correct when viewed in an editor. I will hex dump the python script and look at how it is representing that character.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52477549
downvote count: 0
upvote count: 2
has body: The question was caused by Windows 10 Exploit Protection. I went to Windows Defender -> App &amp; Browser Control -> Exploit Protection -> Program Settings and added a custom rule (by path) and turn off all protections for python. It's not recommanded because it will increase the risk of your computer being attacked but it did work on my computer. I will be happy to accept better solutions.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52453925
score: 2
answers question: http://stackoverflow.com/q/52453925

http://stackoverflow.com/q/52511722
score: 1
type: Question
has body: This is my problem, suppose I have a vector like this: import numpy as np idxx = np.array([0. , 0.07665982, 0.24366872, 0.49555099, 0.74743326, 1.07871321, 1.58247775, 2.24503765, 2.58179329, 3.16221766, 3.74811773, 4.1615332 , 4.58042437, 5.33059548]) I am interested in filtering out only those values which are approximately multiples of 0.25, 0.5 and 1.0. Let's start with 0.25 to demonstrate what I am looking the filter to return: np.array([0.24366872, 0.49555099, 0.74743326, 1.07871321, 1.58247775, 2.24503765, 2.58179329, 3.74811773, 4.58042437, 5.33059548]) Here only values that are approximately some multiple of 0.25 remain. In practise, I will also need to keep the first entry 0.0, but have removed it for this demonstration. If I am using 0.5 then my result would look like this: np.array([0.49555099, 1.07871321, 1.58247775, 2.58179329, 4.58042437]) My initial attempts was: import math for i in idxx: g = 0.25 k = i % g if math.isclose(k, g, rel_tol=0.5): print('This is reasonably close: ', i, '\n\t for modulus k == ', k, '\n') Still requires me to do an awful lot of tuning (and I still cannot manage to filter out what I want), so I wondering if anyone has a better way of doing this properly? In essence, I want to select those irregular points (e.g. 0.24366872), onto a "regularly" spaced grid (e.g. with 0.25 spacing), but where each point on the regularly spaced grid has some tolerance of e.g. +/- 0.05, in order to accommodate irregularities in the real data. Thus allowing me to find those points which sit within this tolerance, at those regularly spaced points.
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52512081
accepted answer: http://stackoverflow.com/a/52512192
answer count: 2
downvote count: 0
favorite count: 0
has title: Selecting approximately regular samples from an irregularly spaced vector
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52512192
has answer: http://stackoverflow.com/a/52512081

http://stackoverflow.com/a/52565804
score: 0
has body: Cast it to datetime import pandas as pd import numpy as np data = ('2016-09-19 00:29:13-05:00,' '2016-09-19 04:16:04-02:00,' '2016-09-19 06:57:54+01:00').split(',') pd.DataFrame(data).astype(np.datetime64)
answers question: http://stackoverflow.com/q/52565673
has comment: http://stackoverflow.com/comment/92069334
type: Answer
has comment: http://stackoverflow.com/comment/92069456

http://stackoverflow.com/q/52443136
answer count: 1
has answer: http://stackoverflow.com/a/52443163
score: 0
type: UnansweredQuestion
has body: Could someone please explain why I get TypeError: '_io.TextIOWrapper' object is not callable with the input statement inside the Maze function in the code below? I tested it outside of the function and it works fine. None of the answers in SO about this error seem to address my problem. # This program traverses a maze using a stack. from sq import Stack # import a Stack type from sq.py MAZE_SIZE = 10 # define the size of the maze def PrintMaze(maze): # an auxilliary function that prints a maze for row in range(MAZE_SIZE): print(maze[row], end='') print() def InBounds(xxx_todo_changeme): # an auxillary function that determines if (x,y) is on the maze (x,y) = xxx_todo_changeme return (0 &lt;= x &lt; MAZE_SIZE) and (0 &lt;= y &lt; MAZE_SIZE) def Maze(maze, start): # traverse 'maze' from starting coordinates 'start' s = Stack() # create a new Stack named s s.push(start); # push the start coordinates onto s while not s.isEmpty(): # loop while s is not empty (x, y) = s.pop() # pop a coordinate off s into the tuple (x,y) input("press Enter to continue ") if InBounds((x,y)): # if (x,y) is on the maze then if maze[x][y] == 'G': # if (x,y) is the goal then s.empty() # empty the stack because we're done elif maze[x][y] == ' ': # else if (x,y) is an undiscovered coordinate maze[x] = maze[x][:y] + 'D' + maze[x][y+1:] # mark (x,y) discovered with 'D' PrintMaze(maze); # print the maze to show progress so far s.push((x+1, y)) # push right neighbor onto stack s s.push((x-1, y)) # push left neighbor onto stack s s.push((x, y-1)) # push upper neighbor onto stack s s.push((x, y+1)) # push lower neighbor onto stack s # The following can be used to create a maze and traverse it: import sys input("press Enter to continue ") input = open('maze.dat', 'r') # open the file 'maze.dat' for reading maze = input.readlines(); # read the file into maze Maze(maze, (0,0)) # traverse the maze starting at (0,0)
tagged with: typeerror
has title: Python Input TypeError: '_io.TextIOWrapper' object is not callable
type: Question
tagged with: input
tagged with: python

http://stackoverflow.com/comment/91866937
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52461979
has text: Did you check it?
type: AnswerComment

http://stackoverflow.com/a/52554493
upvote count: 7
has comment: http://stackoverflow.com/comment/92048950
answers question: http://stackoverflow.com/q/52550922
has body: The problem is how to express the predicate "A user identified by ID has only one tool with the name NAME". This would of course be easy to express with a simple table such as: db.Table('user_toolname', db.Column('user', db.Integer, db.ForeignKey('user.id'), primary_key=True), db.Column('toolname', db.String, primary_key=True)) It is also very clear that this alone is not nearly enough to uphold integrity, as there is no connection between the fact about user's toolnames and the actual tools. Your database could state that a user both has a hammer and doesn't have a hammer. It would be nice to enforce this in your user_tool_assoc_table or something equivalent, but since Tool.name is not a part of the primary key of Tool, you cannot reference it. On the other hand since you do want to allow multiple tools with the same name to co-exist, the subset { id, name } is in fact the proper key for Tool: class Tool(db.Model): __tablename__ = 'tool' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, primary_key=True) The id now acts as a "discriminator" of sorts between the tools having the same name. Note that id need not be globally unique in this model, but locally to name. It's handy to have it auto increment still, but the default setting of autoincrement='auto' only treats a single-column integer primary key as having auto incrementing behavior by default, so it must be explicitly set. It is now possible to define user_tool_assoc_table in terms of tool_name as well, with the additional constraint that a user can only have a single tool with a given name: user_tool_assoc_table = db.Table( 'user_tool', db.Column('user', db.Integer, db.ForeignKey('user.id')), db.Column('tool', db.Integer), db.Column('name', db.String), db.ForeignKeyConstraint(['tool', 'name'], ['tool.id', 'tool.name']), db.UniqueConstraint('user', 'name')) With this model and the following setup: john = User(name='John') mark = User(name='Mark') db.session.add_all([…
has comment: http://stackoverflow.com/comment/92070786
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92050298
has comment: http://stackoverflow.com/comment/92050056
has comment: http://stackoverflow.com/comment/92048915
type: Answer
accepted answer of: http://stackoverflow.com/q/52550922
score: 7

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/52453190
type: Tag

http://stackoverflow.com/q/52489613
possible better answer: http://stackoverflow.com/a/63215874
has body: You are given queries. Each query is of the form two integers described below: Insert x in your data structure. Delete one occurrence of y from your data structure, if present. Check if any integer is present whose frequency is exactly. If yes, print 1 else 0. Example input : queries = [(1,1),(2,2),(3,2),(1,1),(1,1),(2,1),(3,2)] The problem is pretty self-explanatory and I think I have a decent solution: loop through the queries and increment and decrement the frequencies of each number accordingly in a dict ... simultaneously in a separate dict keep track of how many times each key of the other dict appears when checking if any integer is present whose frequency is exactly y for QUERY 3 you would check if the count of y in the second dict exists... I am passing most test cases but failing some.. can anyone explain flaws in my thinking. def freqQuery(queries): frequency = {} results = [] frequencyValues = {} for query in queries: q = query[0] val = query[1] if q == 1: frequency[val] = frequency.get(val, 0) + 1 freq = frequency[val] frequencyValues[freq] = frequencyValues.get(freq, 0) + 1 frequencyValues[freq-1] = frequencyValues.get(freq-1, 1) - 1 elif q == 2: if val in frequency.keys(): frequency[val] += - 1 if frequency[val] &lt; 0: frequency[val] = 0 freq = frequency[val] frequencyValues[freq + 1] = frequencyValues.get(freq + 1, 1) - 1 frequencyValues[freq] = frequencyValues.get(freq, 1) + 1 elif q == 3: if val in frequencyValues.keys(): if frequencyValues[val] &gt; 0: results.append(1) else: results.append(0) else: results.append(0) return results
has answer: http://stackoverflow.com/a/63215874
favorite count: 0
has title: Hackerrank Frequency Queries
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52491274
accepted answer: http://stackoverflow.com/a/52491274
score: 4

http://stackoverflow.com/q/52580807
type: Question
has answer: http://stackoverflow.com/a/52583174
answer count: 1
score: 0
has title: Performance Django/Python calling modules
tagged with: python
accepted answer: http://stackoverflow.com/a/52583174
has body: To the experts on Django/Python: Is there a significative difference in performance between calling, as an example: from foo.views import foo, foo2, #... and son on than: from foo import views path('foo', views.foo, name="my_view"), path('foo2', views.foo2, name="my_view") # ... and so on Having in mind of course that you have tons of views or other classes, methods, etc.
tagged with: django
type: AnsweredQuestion
tagged with: performance

http://stackoverflow.com/comment/121585260
has text: Cool answer, but this has precision problems. For n=7 it would give 33.007272246494836 instead of 33. If rounded to nearest integer, it will start giving wrong results already at n <= 100
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52488140
type: Comment

http://stackoverflow.com/a/52581308
has body: As I can see from your sample, entire XML file is related to the same company. To me it sounds that you need to add this a new row, not join it as a table. In my understanding you want to have some list of metrics for each company. If so you probably can just stick with key-value storage. If python is your primary tool, use dictionary, and then save it as a JSON file. In your for loop just fill a blank dictionary with data from XML like this: report = { "apple": { 'metricSet1': {"m11": 5, "m12": 2, "m13": 3}, 'metricSet2': {"m21": 4, "m22": 5, "m23": 6} }, "google": { 'metricSet1': {"m11": 1, "m12": 13, "m13": 3}, 'metricSet2': {"m21": 9, "m22": 0, "m23": 11} }, "facebook": { 'metricSet1': {"m11": 1, "m12": 9, "m13": 9}, 'metricSet2': {"m21": 7, "m22": 2, "m23": 4} } } when you need to query it or fill some table with data do something like this: for k in report.keys(): row = [ k, report[k]["metricSet1"]["m12"], report[k]["metricSet2"]["m22"], report[k]["metricSet2"]["m23"] ] print(row) If data structure is not changing (say all these XML are the same) it would make sence to store it in SQL database, creating a table for each metric set. If XML structure may vary then just keep it as json file, or probably in some Key-Value based database, like mongo
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52546519
type: Answer
answers question: http://stackoverflow.com/q/52546519
score: 1
upvote count: 1

http://stackoverflow.com/comment/91948559
type: Comment
type: QuestionComment
has text: You can speed it up by reversing the inner loop: Iterate from `len(arr)-1` downwards to `i+1`. The time complexity will stay the same though.
comment on: http://stackoverflow.com/q/52503842
score: 0

interpolation
tags question: http://stackoverflow.com/q/52515077
tags question: http://stackoverflow.com/q/52474045
tag name: interpolation
tags question: http://stackoverflow.com/q/52451102
type: Tag
tags question: http://stackoverflow.com/q/52562494
tags question: http://stackoverflow.com/q/52545069
tags question: http://stackoverflow.com/q/52543930

http://stackoverflow.com/a/52658564
score: 3
downvote count: 0
has body: These are partially subjective questions. But I'll have a go at answering some of them to the best of my current knowledge and the information available in the question posed. How Filter class will look like? That could depend for instance on the storage mechanism. Is it stored in-memory as a bunch of Python objects or is it first taken out of an SQL database or perhaps a NoSQL database. If it's taken from an SQL database you can take advantage of the filtering mechanism of SQL. It's after all a (Structured) Query Language. In that case your Filter class would be like a translator of field values to a bunch of SQL operators/conditions. If it's a bunch of Python objects without some database mechanism to use for querying your data then you might need to think of your own query/filter methods. A Filter class might be using a Condition class and an Operator class. Maybe you have an Operator class as an abstract class and have 'glue' operators to glue conditions together (AND/OR). And another kind of operators to compare a property of a domain object with a value. For the latter, even if you are not designing a 'filter language' for it, you could get some inspiration from an API querying format, specified here for Flask-Restless: https://flask-restless.readthedocs.io/en/stable/searchformat.html#query-format Surely if you are designing a query interface to e.g. a REST API, Flask-Restless's query-format could give you some inspiration of how to tackle the querying. Is returning List of domain objects correct or should I return list of dict? Returning a list of domain objects has the advantage of being able to use inheritance. That's at least one possible advantage. A rough sketch of certain classes: from abc import ABCMeta, abstractmethod from typing import List class DomainObjectOperatorGlue(metaclass=ABCMeta): @abstractmethod def operate(self, haystack: List['DomainObject'], criteria: List['DomainObject']) -&gt; List['DomainObject']: pass class DomainObjectFieldGlueOper…
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/92307208
has comment: http://stackoverflow.com/comment/92308946
has comment: http://stackoverflow.com/comment/92307240
answers question: http://stackoverflow.com/q/52574433
has comment: http://stackoverflow.com/comment/92308643
has comment: http://stackoverflow.com/comment/92468603
type: Answer
accepted answer of: http://stackoverflow.com/q/52574433

http://stackoverflow.com/q/52490692
has title: Selenium Firefox driver raise exception OSError: [Errno 8] Exec format error
tagged with: geckodriver
tagged with: python
favorite count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: selenium
type: Question
score: 3
has body: def setUp(self): display = Xvfb() display.start() fp = webdriver.FirefoxProfile() fp.set_preference("browser.download.folderList",2) fp.set_preference("browser.download.manager.showWhenStarting",False) fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv") self.browser= webdriver.Firefox(firefox_profile=fp) On webdriver.firefox it raises an exception even I tried with geckodriver path self.browser=webdriver.Firefox(executable_path='/usr/bin/geckodriver',firefox_profile=fp) But still it raises an exception Traceback (most recent call last): File "fbCampaign.py", line 23, in setUp self.browser= webdriver.Firefox(executable_path='/usr/bin/geckodriver',firefox_profile=fp) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 157, in __init__ self.service.start() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/usr/lib/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child raise child_exception OSError: [Errno 8] Exec format error
tagged with: webdriver
tagged with: firefox
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52491810

http://stackoverflow.com/q/52460327
has answer: http://stackoverflow.com/a/52462006
has title: Efficient Intersection of pandas dataframe with remote mongodb?
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52462006
tagged with: python
type: AnsweredQuestion
tagged with: pymongo
has body: I have a python pandas dataframe on my local machine, and have access to a remote mongodb server that has additional data that I can query via pymongo. If my local dataframe is large, say 40k rows with 3 columns in each row, what's the most efficient way to check for the intersection of my local dataframe's features and a remote collection containing millions of documents? I'm looking for general advice here. I thought I could just take a distinct list of values from each of the 3 features, and use each of these in an $or find statement, but if I have 90k distinct values for one of the 3 features it seems like a bad idea. So any opinion would be very welcome. I don't have access to insert my local dataframe into the remote server, I only have select/find access. thanks very much!
type: Question
tagged with: mongodb

atom-editor
tags question: http://stackoverflow.com/q/52466092
tags question: http://stackoverflow.com/q/52455664
tags question: http://stackoverflow.com/q/52584622
tags question: http://stackoverflow.com/q/52468477
type: Tag
tag name: atom-editor
tags question: http://stackoverflow.com/q/52458721
tags question: http://stackoverflow.com/q/52582762
tags question: http://stackoverflow.com/q/52567471

http://stackoverflow.com/comment/91973618
type: Comment
comment on: http://stackoverflow.com/q/52466353
type: QuestionComment
score: 0
has text: As far as I can tell, you're using an ID locator correctly in which case @cruisepandey has the best answer for you: the button id is dynamic so it changes and isnt constantly 'rallybutton-1121' thus the NoSuchElement Exception. I would recomend using Class as the selector, it tends to be more stable. Another thing thats relatively stable is the actual text of the button. I don't believe its a built in command (pretty sure links have a by-text function automatically) but I'm sure you could easily make something to find/match button text unless there are multiple buttons with the same text.

http://stackoverflow.com/q/52496387
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91935971
tagged with: opencv
has title: opencv shape detection in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91936787
has body: 1st I know this post is duplicate.but that threads are not helpful to me. I want detect shape and convert text in that shape to text file. This is my image . I want to get that ER table to text file like this. customer-cid,cfName,cLName,... I tried this tutorial detect shape but I couldn't detect any shapes. It detect shapes as shown in image below any help is appreciated
has comment: http://stackoverflow.com/comment/91936382
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91938933
tagged with: python
score: 0

http://stackoverflow.com/comment/91889869
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52474017
has text: Thank you for your answer, I will test it out!
type: AnswerComment

http://stackoverflow.com/q/52481557
accepted answer: http://stackoverflow.com/a/52481956
has answer: http://stackoverflow.com/a/52481829
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: How can one create a python dictionary (key : value) from select objects in a JSON file with multiple JSON lines
has body: I have a file with multiple JSON lines as shown below. {"status str":null,"id":563221, "filter":"low","text" : "Grass is green"} {"status str":null,"id":612835, "filter":"high","text" : "Textual blue"} My desired output should show only the ID number and the "Grass is green" as a [key : value] pair as in dictionaries in Python : 563221 : "Grass is green" 612835 : "Textual blue" I am currently using ObjectPath to query. Using the tuples, I can output all the data but I can't select sections of the data. Below is the code that I am using. read_data = [] with open(fileName, 'r') as file_to_read: for line in filetoread: json_tree = objectpath.Tree(read_data) dict = {tuple(json_tree.execute('$.id')) : tuple(json_tree.execute('$.text'))} line = next(filetoread) return dict
type: Question
possible better answer: http://stackoverflow.com/a/52481743
upvote count: 1
has answer: http://stackoverflow.com/a/52481743
favorite count: 0
tagged with: objectpath
answer count: 3
has answer: http://stackoverflow.com/a/52481956

http://stackoverflow.com/comment/91981193
score: 0
type: Comment
type: QuestionComment
has text: @BryanOakley That was surprisingly easy. Thank you. I simply used `shutil.rmtree(root)` in place of the `print` statement and the folder was removed. Thank you.
comment on: http://stackoverflow.com/q/52520604

http://stackoverflow.com/comment/92029655
has text: beside the docs, you can inspect any bokeh model using the method properties_with_values() (e.g. legend.properties_with_values() )
comment on: http://stackoverflow.com/q/52542140
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52496970
type: Question
has title: How to solve the delimiter error while using to_csv function in pandas
has comment: http://stackoverflow.com/comment/91934324
has body: This is a followup question on how to write a single row cell by cell and fill it in csv file import pandas as pd delim = "@@@" # just for abrevation tmp = pd.read_csv("mycsv.csv",sep='@@@') tmp.loc[0,:] = "None" tmp.to_csv("mycsv.csv",sep=delim,index=False) I am getting follow error . Please suggest some correct solution self.writer = csv.writer(f, **writer_kwargs) TypeError: "delimiter" must be a 1-character string Exception ignored in: &lt;module 'threading' from Traceback (most recent call last): line 1296, in _shutdown _main_thread._delete() File /share/python-3.6.1/linux_x86_64/lib/python3.6/threading.py", line 1015, in _delete del _active[get_ident()] KeyError: 140613724829696
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52497080
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/52494495

http://stackoverflow.com/comment/91967748
score: 3
comment on: http://stackoverflow.com/q/52513365
type: Comment
type: QuestionComment
has text: You have 15! = 1 307 674 368 000 solutions

http://stackoverflow.com/comment/91957839
has text: `divmod(i,36)[0] < 36` is always true, so you'll never enter the second `elif`, that's the problem of your code.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52508757

pca
tag name: pca
tags question: http://stackoverflow.com/q/52574826
tags question: http://stackoverflow.com/q/52457024
type: Tag
tags question: http://stackoverflow.com/q/52449331

http://stackoverflow.com/comment/91943756
score: 4
type: Comment
type: QuestionComment
has text: It's easy -> it gets many answers -> the "hotness formula" think (_no comment on the formula_) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from [so]. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
comment on: http://stackoverflow.com/q/52493328

http://stackoverflow.com/q/52556111
type: Question
has comment: http://stackoverflow.com/comment/92051469
has title: Is there a general animation function in tkinter?
has answer: http://stackoverflow.com/a/52556319
has comment: http://stackoverflow.com/comment/92051077
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92051120
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has body: Do you know a function in tkinter to change a general parameter of a widget over time (or for loop)? Like the move function changes its coordinates automatically.Is there something similar with which I could change the extent=x parameter of an arc over a for loop? Or should I write it for myself? Update: After your answer Bryan Oakley, I came up with this: def rotate_arc_function(): for d in range(90, 359): arc.configure(extent=d) root.update() time.sleep(.05) But the arc object I get with arc = canvas.create_arc(20,20,100,100, extent=90, fill="green") doesn't seem to have the configure function, because I get: AttributeError: 'int' object has no attribute 'configure'
has comment: http://stackoverflow.com/comment/92051527
accepted answer: http://stackoverflow.com/a/52556319

http://stackoverflow.com/q/52576047
has answer: http://stackoverflow.com/a/52576070
answer count: 1
tagged with: regex
score: 1
favorite count: 0
has title: Recursively replace certain lines using regex in Python
tagged with: python
accepted answer: http://stackoverflow.com/a/52576070
type: AnsweredQuestion
upvote count: 1
tagged with: loops
type: Question
has body: I have a text file and want to recursively replace all lines containing some regex pattern, then save the result into a new text file. The input text file has the following contents: NAME1 184,743 184,439 14,305 NAME2 84,343 64,437 36,335 NAME3 154,543 174,439 38,385 I want to fill down all empty lines (including lines with only tabs and/or spaces) with the non-empty line above it. The final output should look like this: NAME1 184,743 184,439 14,305 NAME1 184,743 184,439 14,305 NAME1 184,743 184,439 14,305 NAME1 184,743 184,439 14,305 NAME2 84,343 64,437 36,335 NAME2 84,343 64,437 36,335 NAME2 84,343 64,437 36,335 NAME2 84,343 64,437 36,335 NAME2 84,343 64,437 36,335 NAME3 154,543 174,439 38,385 NAME3 154,543 174,439 38,385 NAME3 154,543 174,439 38,385 NAME3 154,543 174,439 38,385 I tried this code but I can't figure how to make it work as I am new to Python. The regular expression works in Notepad++ but not in IDLE: import re fhand = open("/home/user1/Documents/inputtext.txt") fout = open("/home/user1/Documents/outputtext.txt","w") for line in fhand: re.sub("^(\S+.*)$(\n)^([\t ]+|)$","\1\2\1",line) fout.write(line) fout.close()
downvote count: 0

http://stackoverflow.com/comment/91959683
has text: @LuisEduardoBoikoFerreira how does that affect executing a python script in bash? If your python script is named `foo`, has a proper shebang, and is executable, you could run it with `./foo` inCygwin/Msys/WSL bash without worrying about PATHEXT.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52509565

python-3.3
tags question: http://stackoverflow.com/q/52548299
tag name: python-3.3
type: Tag

http://stackoverflow.com/comment/91881560
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52469293
has text: Can you be more specific on what "problem" you're getting?
type: Comment

web-scraping
tags question: http://stackoverflow.com/q/52582671
tags question: http://stackoverflow.com/q/52458349
tags question: http://stackoverflow.com/q/52536056
tags question: http://stackoverflow.com/q/52518372
tags question: http://stackoverflow.com/q/52452041
tags question: http://stackoverflow.com/q/52517882
tags question: http://stackoverflow.com/q/52520975
tags question: http://stackoverflow.com/q/52578565
tags question: http://stackoverflow.com/q/52585948
tags question: http://stackoverflow.com/q/52548821
tags question: http://stackoverflow.com/q/52548963
tags question: http://stackoverflow.com/q/52481880
tags question: http://stackoverflow.com/q/52570401
tags question: http://stackoverflow.com/q/52532637
tags question: http://stackoverflow.com/q/52587674
tags question: http://stackoverflow.com/q/52521456
tags question: http://stackoverflow.com/q/52468619
tags question: http://stackoverflow.com/q/52558105
tags question: http://stackoverflow.com/q/52536842
tags question: http://stackoverflow.com/q/52462801
tags question: http://stackoverflow.com/q/52547535
tags question: http://stackoverflow.com/q/52511169
tags question: http://stackoverflow.com/q/52582830
tags question: http://stackoverflow.com/q/52578946
tags question: http://stackoverflow.com/q/52584207
tags question: http://stackoverflow.com/q/52571362
tags question: http://stackoverflow.com/q/52458279
tags question: http://stackoverflow.com/q/52468995
tags question: http://stackoverflow.com/q/52564677
tags question: http://stackoverflow.com/q/52457900
tags question: http://stackoverflow.com/q/52580875
tags question: http://stackoverflow.com/q/52526729
tags question: http://stackoverflow.com/q/52513329
tags question: http://stackoverflow.com/q/52576618
tags question: http://stackoverflow.com/q/52442597
tags question: http://stackoverflow.com/q/52463349
tags question: http://stackoverflow.com/q/52459104
tags question: http://stackoverflow.com/q/52458442
tags question: http://stackoverflow.com/q/52544562
tags question: http://stackoverflow.com/q/52587552
tags question: http://stackoverflow.com/q/52451631
tags question: http://stackoverflow.com/q/52568025
tags question: http://stackoverflow.com/q/52528418
tags question: http://stackoverflow.com/q/52431098
tags question: http://stackoverflow.com/q/52522884
tags question: http://stackoverflow.com/q/52486992
tags question: http://stackoverflow.com/q/52525924
tag name: web-scraping
tags question: http://stackoverflow.com/q/52501149
tags question: http://stackoverflow.com/q/52451429
tags question: http://stackoverflow.com/q/52436525
tags question: http://stackoverflow.com/q/52584273
tags question: http://stackoverflow.com/q/52496078
tags question: http://stackoverflow.com/q/52448236
tags question: http://stackoverflow.com/q/52530092
type: Tag
tags question: http://stackoverflow.com/q/52436604
tags question: http://stackoverflow.com/q/52571344
tags question: http://stackoverflow.com/q/52453169
tags question: http://stackoverflow.com/q/52508044
tags question: http://stackoverflow.com/q/52563545
tags question: http://stackoverflow.com/q/52560205
tags question: http://stackoverflow.com/q/52572003
tags question: http://stackoverflow.com/q/52483034
tags question: http://stackoverflow.com/q/52437091
tags question: http://stackoverflow.com/q/52514267
tags question: http://stackoverflow.com/q/52525989
tags question: http://stackoverflow.com/q/52516934

http://stackoverflow.com/q/52462507
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91951158
has comment: http://stackoverflow.com/comment/91952917
has comment: http://stackoverflow.com/comment/91952726
tagged with: python
has comment: http://stackoverflow.com/comment/91952960
answer count: 0
tagged with: python-imaging-library
type: Question
has comment: http://stackoverflow.com/comment/91953090
has title: Python PIL doubling images
has body: I am trying to draw over 2 images, and I am getting this weird error. For most of the time the image drawing goes well. -or- These are the two symbols as they normally would be. However here is what is being outputted randomly Most of the time this code works without a hitch but sometimes it does this: So here is my code. This first one chooses ONE overlay image(not two) if 'Instant' in s.duration: durpic = Image.open('Dur-I.png') elif 'round' in s.duration: durpic = Image.open('Dur-R.png') dnum = write_roman(int(re.search(r'\d+', s.duration).group())) draw = ImageDraw.Draw(durpic) w, h = draw.textsize(dnum) draw.text((0, 0), dnum, (0, 0, 0), font=font) elif 'min' in s.duration: if 'Concentration' in s.duration: durpic = Image.open('Dur-CM.png') else: durpic = Image.open('Dur-M.png') dnum = write_roman(int(re.search(r'\d+', s.duration).group())) draw = ImageDraw.Draw(durpic) w, h = draw.textsize(dnum) draw.text((0, 0), dnum, (0, 0, 0), font=font) elif 'hour' in s.duration: if 'Concentration' in s.duration: durpic = Image.open('Dur-CH.png') else: durpic = Image.open('Dur-H.png') dnum = write_roman(int(re.search(r'\d+', s.duration).group())) draw = ImageDraw.Draw(durpic) w, h = draw.textsize(dnum) draw.text((0, 0), dnum, (0, 0, 0), font=font) elif 'day' in s.duration: if 'Concentration' in s.duration: durpic = Image.open('Dur-CD.png') else: durpic = Image.open('Dur-D.png') dnum = write_roman(int(re.search(r'\d+', s.duration).group())) draw = ImageDraw.Draw(durpic) w, h = draw.textsize(dnum) draw.text((0, 0), dnum, (0, 0, 0), font=font) elif 'Until' in s.duration: durpic = Image.open('Dur-R.png') Placing the image over the base image image_copy = scho.image image_copy.paste(durpic, scho.point3, durpic) imgpath = 'output/' + s.name + '.png' image_copy.save(imgpath) So any advice on what is causing this error? I could paste more code if needed or more output examples.
score: 0
tagged with: python-3.x

http://stackoverflow.com/comment/92110812
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52587761
has text: What URL are you querying?
score: 0

http://stackoverflow.com/comment/91888245
comment on: http://stackoverflow.com/a/52472297
type: AnswerComment
has text: Take a look at https://osxuninstaller.com/uninstall-guides/properly-uninstall-python-mac/ Note this is a guide for Python 3.6 so you may need to adjust for that.
score: 0
type: Comment

http://stackoverflow.com/q/52585752
upvote count: 2
accepted answer: http://stackoverflow.com/a/52586422
has comment: http://stackoverflow.com/comment/92106901
has body: The following code is giving TypeError. from sklearn.model_selection import KFold kf = KFold(n_splits=5,shuffle=False).split(range(25)) print('{} {:^61} {}'.format('Iteration','Training set observations','Testing set observations')) for iteration, data in enumerate(kf, start=3): print('{:^9} {} {:^25}'.format(iteration, data[0], data[1])) TypeError: unsupported format string passed to numpy.ndarray.format The code gives correct output when we use str(data[1]) Why is this explicit string conversion required ?
answer count: 1
downvote count: 1
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52586422
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/92106881
has comment: http://stackoverflow.com/comment/92106332
tagged with: python
has title: Why explicit string conversion is required in .format method in python is required?

http://stackoverflow.com/comment/92303028
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52451039
score: 0
has text: Distance function is the square root of the sum of squared differences along each dimension of x and y. `distance = math.sqrt((y[0] - x[0])**2 + (y[1] - x[1])**2)`

http://stackoverflow.com/a/52467149
has body: Multiprocessing module has already a solution for parallel task processing: multiprocessing.Pool from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': with Pool(processes=4) as pool: # start 4 worker processes print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]" You can achieve the same using multiprocessing.Queue. I believe that's how pool.map() is implemented internally. So, what's the difference between multiprocessing.Queue and multiprocessing.Pipe? Queue is just a Pipe plus some locking mechanism. Therefore multiple worker processes can share just a single Queue (or rather 2 - one for commands, one for results), but with Pipe each process would need it's own Pipe (or a pair of, or a duplex one), exactly how you are doing it now. The only disadvantage of Queue is performance - because all processes share one queue mutex it doesn't scale well for many processes. To be sure it can handle tens of thousands items/s I would choose Pipe, but for classic parallel task processing use case I think Queue or just Pool.map() could be OK because they are much easier to use. (Managing processes can be tricky and asyncio doesn't make it easier either.) Hope that helps, I'm aware that I've answered a bit different question than you've asked :)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52467049
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91841427
type: AnswerComment
comment on: http://stackoverflow.com/a/52449135
type: Comment
has text: sum(map(int, row)) better imo. No need to feed a list to sum.
score: 0

http://stackoverflow.com/comment/92087142
type: AnswerComment
has text: Hi @wndtanaka, welcome to SO! Please note that according to the error the OP is showing this doesn't look to be the source of the problem.
comment on: http://stackoverflow.com/a/52575797
type: Comment
score: 0

http://stackoverflow.com/comment/91818112
type: Comment
type: QuestionComment
has text: Can you show us what you've tried so far?
comment on: http://stackoverflow.com/q/52437577
score: 3

row
tags question: http://stackoverflow.com/q/52449246
type: Tag
tags question: http://stackoverflow.com/q/52586286
tag name: row

http://stackoverflow.com/comment/92055587
type: QuestionComment
comment on: http://stackoverflow.com/q/52555841
score: 0
has text: https://en.wikipedia.org/wiki/One_in_ten_rule
type: Comment

http://stackoverflow.com/q/52452233
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52452296
favorite count: 0
has title: some problems with obtaining the value of functions within a dictionary
has comment: http://stackoverflow.com/comment/91847822
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91850907
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52452296
has body: So, I'm just starting out in Python, but I'm attempting to implement functions within dictionaries (kind of like function pointers in C), but I'm stuck on how to receive the returned value from the function without an error. Here's a snippit from my code: def main(): numberOfDice = 5 dice = rollDice(numberOfDice) #rolls dice thrice, returns a list of 5 integers scoreBoard(dice) #displays Yahtzee scoreboard value = choice(dice) #value = the category choice[1-13] whichCategory(value) def whichCategory(category): board = { 6: numberOfSixes, # I have 1-13 filled, but just for example 12: yahtzee # this is just to save space. } board[category]() def numberOfSixes(theDice): count = theDice.count(6) points = count * 6 return points def yahtzee(theDice): yahtzee = 0 ones, twos, threes, fours, fives, sixes = countDice(theDice) # countDice() determines the amount that each number is present in the # list and then returns those six variables. if any(x==5 for x in(ones, twos, threes, fours, fives, sixes)): yahtzee = 50 return yahtzee After rolling three times and I finalize my dice (the list of integers), I select my value from choice that goes with whichCategory(), and then it does the correct calculations, spits out the correct return value from those functions, but then I'll get an error like this(for inputting in two sixes(12 pts)): Traceback (most recent call last): File "C:\python\Lib\idlelib\Yahtzee.py", line 407, in &lt;module&gt; main() # My call to main() File "C:\python\Lib\idlelib\Yahtzee.py", line 18, in main whichCategory(value) File "C:\python\Lib\idlelib\Yahtzee.py", line 90, in whichCategory board[category]() TypeError: yahtzee() missing 1 required positional argument: 'theDice It's funny because it says the error is with yahtzee(), not the sixes, and I believe it's because it's somehow getting 12 as an answer and it's calling the 12th keyword in the dictionary. or I'll get an error like: Traceback (most recent call last): File "C:\python\Lib\idlelib\Yahtzee.py…

http://stackoverflow.com/q/52532504
tagged with: colorama
upvote count: 3
answer count: 2
has title: display the user input text in color in the windows cmd
favorite count: 0
possible better answer: http://stackoverflow.com/a/52533983
linked to: http://stackoverflow.com/q/52102240
has answer: http://stackoverflow.com/a/52533983
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: formatting
has body: I have yet another question regarding my little console program for the windows cmd. I use colorama to color my text in the terminal which makes it look like this: Then I found out how to color the text in an input()-method using a little "hack" with a print without linebreak, like this: from colorama import init init(autoreset=True) YELLOW = "\x1b[1;33;40m" print(f"\n{YELLOW}Turnier spielen? [T]: ", end='') tournament = input() this leads to the yellow line in the picture above. But I still look for a way to color the very characters the user inputs - so here I would like to format the user input "sdffdgf..." in color as well. has anyone a solution for me or will it just not be possible with the limited windows cmd?
type: Question
has answer: http://stackoverflow.com/a/52720659
accepted answer: http://stackoverflow.com/a/52720659
score: 3

http://stackoverflow.com/comment/91925166
type: Comment
comment on: http://stackoverflow.com/a/52489556
has text: This is perfect! I thought from the documentation that SizeGrips resize the main window, but this works as expected.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52522755
tagged with: uwsgi
has answer: http://stackoverflow.com/a/65455864
tagged with: tensorflow
type: Question
score: 4
tagged with: docker
has body: I'm trying to deploy a face detection service using MTCNN in tensorflow + flask + uWSGI. I based my deployment on this docker and added this custom uwsgi.ini: [uwsgi] module = main callable = app enable-threads = true cheaper = 2 processes = 16 threads = 16 http-timeout = 60 but when I try to do face detection using this docker image I just built, I always get 504 Gateway Time-out. Actually when I dug deeper, I noticed that the code runs fine to this session.run line: for op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data in iteritems(data_dict[op_name]): try: var = tf.get_variable(param_name) session.run(var.assign(data)) except ValueError: if not ignore_missing: raise At first, I thought it was a problem related to threading under uwsgi worker, so I added increased number of processes and threads but without any success. When I run the same code with flask debugger, it runs just fine and processes the image in less than a second. So it is not a problem with code but a problem with config or combination of these tools.
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/96283565
type: UnansweredQuestion
tagged with: python
upvote count: 4
downvote count: 0
has title: unable to utilize tensorflow model under uwsgi + nginx deployment
has answer: http://stackoverflow.com/a/57839525
has answer: http://stackoverflow.com/a/56935325
has comment: http://stackoverflow.com/comment/96306784

http://stackoverflow.com/a/52577177
answers question: http://stackoverflow.com/q/52576986
type: Answer
has body: As timgeb mentions, there are better ways to do this. But as pkpnd mentions, the reason your code sometimes fails is that some of the path states do not have corresponding keys, so they need to be skipped. I've made a few other minor changes, like using more modern set syntax, and not using next as a variable name because that's a built-in function. I also use the set.difference method rather than the - operand form so I don't need to convert the path list to a set. graph = { 'state1': {'state3', 'state2', 'state4'}, 'state2': {'state5'}, 'state5': {'state11', 'state10'}, 'state10': {'state20'}, 'state20': {'state34', 'state35'}, 'state11': {'state22', 'state21', 'state23'}, 'state21': {'state37', 'state36'}, 'state22': {'state39', 'state38'}, 'state23': {'state40', 'state41'}, 'state3': {'state8', 'state7', 'state6'}, 'state6': {'state13', 'state12'}, 'state12': {'state24'}, 'state24': {'state43', 'state42'}, 'state13': {'state25'}, 'state25': {'state45', 'state44'}, 'state7': {'state14', 'state15'}, 'state14': {'state26'}, 'state26': {'state46'}, 'state15': {'state27'}, 'state8': {'state17', 'state16'}, 'state16': {'state28'}, 'state17': {'state29'}, 'state4': {'state9'}, 'state9': {'state19', 'state18'}, 'state18': {'state30', 'state32', 'state31'}, 'state19': {'state33'}, } #Depth First Algorithm def dfs_paths(graph, start, goal): stack = [(start, [start])] while stack: vertex, path = stack.pop() if vertex not in graph: continue for nxt in graph[vertex].difference(path): if nxt == goal: yield path + [nxt] else: stack.append((nxt, path + [nxt])) for a in dfs_paths(graph, 'state1', 'state46'): print(a) output ['state1', 'state3', 'state7', 'state14', 'state26', 'state46']
score: 2
has comment: http://stackoverflow.com/comment/92089851
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52576986
has comment: http://stackoverflow.com/comment/92089924
type: AcceptedAnswer
downvote count: 0

generator
tags question: http://stackoverflow.com/q/52431995
tags question: http://stackoverflow.com/q/52458135
tags question: http://stackoverflow.com/q/52573393
tags question: http://stackoverflow.com/q/52527810
type: Tag
tags question: http://stackoverflow.com/q/52539947
tags question: http://stackoverflow.com/q/52438356
tags question: http://stackoverflow.com/q/52487164
tags question: http://stackoverflow.com/q/52546783
tag name: generator
tags question: http://stackoverflow.com/q/52472632

http://stackoverflow.com/q/52560390
tagged with: python
upvote count: 0
type: UnansweredQuestion
has title: Solving large system of non linear equations
tagged with: equation-solving
has comment: http://stackoverflow.com/comment/92059417
has body: I'm trying to solve a system of 30 non linear equations (unknown variables sit inside exponential functions). I have exactly 30 variables and 30 unknowns. I'm trying to use scipy.optimize.fsolve but it is essentially not doing anything. I'll post my attempt below. Below, yu,yd,and Vckm are known matrices with elements ranging from 1e-6 to 1, and the function qyuk(ca,cb,lam)depends on Exp[(1 - ca - cb)lam]. My system is complicated because this exponential has to reproduce small numbers (~1e-6) so my solution is extremely sensitive. def f(c): cq1,cq2,cq3,cu1,cu2,cu3,cd1,cd2,cd3,ce1,ce2,ce3,lu1,lu2,lu3,lu4,lu5,lu6,lu7,lu8,lu9,du1,du2,du3,du4,du5,du6,du7,du8,du9 = c Gu = [[qyuk(cq1,cu1,lam),qyuk(cq1,cu2,lam),qyuk(cq1,cu3,lam)], [qyuk(cq2,cu1,lam),qyuk(cq2,cu2,lam),qyuk(cq2,cu3,lam)], [qyuk(cq3,cu1,lam),qyuk(cq3,cu2,lam),qyuk(cq3,cu3,lam)]] Gd = [[qyuk(cq1,cd1,lam),qyuk(cq1,cd2,lam),qyuk(cq1,cd3,lam)], [qyuk(cq2,cd1,lam),qyuk(cq2,cd2,lam),qyuk(cq2,cd3,lam)], [qyuk(cq3,cd1,lam),qyuk(cq3,cd2,lam),qyuk(cq3,cd3,lam)]] Gu_squared = np.matmul(Gu,np.transpose(Gu)) Gd_squared = np.matmul(Gd,np.transpose(Gd)) Ul = [[lu1,lu2,lu3],[lu4,lu5,lu6],[lu7,lu8,lu9]] Dl = [[du1,du2,du3],[du4,du5,du6],[du7,du8,du9]] rul = np.matmul(np.transpose(Ul),np.matmul(yu,np.matmul(yu,Ul))) rdl = np.matmul(np.transpose(Dl),np.matmul(yd,np.matmul(yd,Dl))) rvckm = np.matmul(np.transpose(Ul),Dl) return ( Gu_squared[0][0] - rul[0][0],Gu_squared[0][1] - rul[0][1],Gu_squared[0][2] - rul[0][2], Gu_squared[1][0] - rul[1][0],Gu_squared[1][1] - rul[1][1],Gu_squared[1][2] - rul[1][2], Gu_squared[2][0] - rul[2][0],Gu_squared[2][1] - rul[2][1],Gu_squared[2][2] - rul[2][2], Gd_squared[0][0] - rdl[0][0],Gd_squared[0][1] - rdl[0][1],Gd_squared[0][2] - rdl[0][2], Gd_squared[1][0] - rdl[1][0],Gd_squared[1][1] - rdl[1][1],Gd_squared[1][2] - rdl[1][2], Gd_squared[2][0] - rdl[2][0],Gd_squared[2][1] - rdl[2][1],Gd_squared[2][2] - rdl[2][2], qyuk(ce1,ce1,lam) - ye[0][0],qyuk(ce2,ce2,lam) - ye[1][1],qyuk(ce3,ce3,lam) - ye[2…
score: -1
has answer: http://stackoverflow.com/a/52808446
tagged with: non-linear-regression
type: Question
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/52451105
accepted answer: http://stackoverflow.com/a/52461647
upvote count: 3
has title: Python - converting UTC millisecond timestamp to local time
type: Question
linked to: http://stackoverflow.com/q/4770297
has comment: http://stackoverflow.com/comment/91845643
downvote count: 0
score: 3
tagged with: datetime
answer count: 1
has answer: http://stackoverflow.com/a/52461647
has comment: http://stackoverflow.com/comment/91845685
favorite count: 0
has comment: http://stackoverflow.com/comment/91845551
tagged with: timezone
tagged with: python
has body: I have a Unix epoch timestamp in milliseconds and need to get date string in local time. This is my code: date = datetime.utcfromtimestamp(timestamp / 1000).strftime('%d-%m-%Y') hour = datetime.utcfromtimestamp(timestamp / 1000).strftime('%H') month = datetime.utcfromtimestamp(timestamp / 1000).strftime('%m') monthName = calendar.month_name[int(month)] weekDay = calendar.day_name[(datetime.strptime(date, '%d-%m-%Y')).weekday()] The original timestamp and the resulting date, hour and all other values generated from the above functions are in UTC. How can I change my code to get it in local time?
type: AnsweredQuestion

http://stackoverflow.com/q/52576681
type: Question
has comment: http://stackoverflow.com/comment/92090040
duplicate of: http://stackoverflow.com/q/47855725
has comment: http://stackoverflow.com/comment/92122121
upvote count: 1
has comment: http://stackoverflow.com/comment/92121694
has comment: http://stackoverflow.com/comment/92121742
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has body: I'd like users to be able to define which keys they'd like to use during a pygame session. I include a short example below where I'd like to change the current working event_handler() function so that it can utilise a user-defined key to quit during the loop: A more advanced python user might also be able to advise me as to how the user could choose a function key or the up/down/left/right arrows of the keyboard too? import pygame from pygame.locals import * pygame.init() size = display_width, display_height = 200,100 DS = pygame.display.set_mode((400,200)) userQuitKey = "K_"+"q" print(userQuitKey) def event_handler(): for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_q): #if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == userQuitKey): pygame.quit() quit() for r in range(210,255): for g in range(210,255): for b in range(210,255): event_handler() DS.fill((r,g,b)) pygame.display.update() print("Loops have ended!") pygame.quit() quit()
has title: User-defined keys within a Pygame
has comment: http://stackoverflow.com/comment/92090240
has comment: http://stackoverflow.com/comment/92090398
answer count: 0
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/47855725
favorite count: 0

http://stackoverflow.com/comment/91904097
comment on: http://stackoverflow.com/a/52481211
has text: Can you explain what operator "<" do when it's inside of array brackets ?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52568708
score: 0
has body: You may want to look at these two links. The Pypi link was last updated in 2006, however, so be careful with use: https://pypi.org/project/pyhjb/ https://docs.spring.io/spring-python/1.2.x/sphinx/html/jms.html
answers question: http://stackoverflow.com/q/52568689
type: Answer

http://stackoverflow.com/comment/92046108
comment on: http://stackoverflow.com/q/52511845
type: Comment
type: QuestionComment
has text: Try using read_json https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html
score: 0

http://stackoverflow.com/q/52440507
type: Question
has comment: http://stackoverflow.com/comment/91824123
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91823916
has title: How to replace some specific characters in django template?
tagged with: python
has comment: http://stackoverflow.com/comment/91823767
favorite count: 0
tagged with: python-3.x
tagged with: django-templates
answer count: 0
type: UnansweredQuestion
has body: Some values from database get fetched and passed to the template like this :['2'] In controller : book = Book.objects.get(id=id) return render(request, 'file.html', {'book': book}) In template: {{book.pages}} output : ['140'] Book model : class Book(models.Model): title = models.CharField(max_length=300, unique=False, default='', null=True) cover_url = models.CharField(max_length=2000) pages = models.CharField(max_length=6, unique=False, default='', null=True) How to delete brackets and ' before delivering the result?
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/91823748

http://stackoverflow.com/q/52433414
has comment: http://stackoverflow.com/comment/91810595
has comment: http://stackoverflow.com/comment/91838065
has comment: http://stackoverflow.com/comment/91844355
has comment: http://stackoverflow.com/comment/91819686
has comment: http://stackoverflow.com/comment/91811640
upvote count: 1
has comment: http://stackoverflow.com/comment/91837808
answer count: 1
has comment: http://stackoverflow.com/comment/91834614
favorite count: 0
has title: I get the following error: ModuleNotFoundError: No module named
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52452070
tagged with: python
has comment: http://stackoverflow.com/comment/91811320
downvote count: 0
has comment: http://stackoverflow.com/comment/91811774
score: 1
has body: The error that I get after the command "python manage.py runserver": from LoginAPI.LoginApp.views import register_view, login_view, logout_view ModuleNotFoundError: No module named 'LoginAPI.LoginApp' My urls.py: from django.conf.urls import url from django.contrib import admin from LoginAPI.LoginApp.views import register_view, login_view, logout_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/', register_view, name='register'), url(r'^login/', login_view, name='login'), url(r'^logout/', logout_view, name='logout'), ] Django version: 2.1.1 I am not very experienced in python yet and would love to here your feedback, I have searched for solutions but couldn't seem to find any. Maybe that I missed something small but can't seem to find the problem. EDIT: The file hierarchy is as displayed: You have the folder: "LoginAPI" which contains the two folders: "LoginAPI" and "LoginApp" The folder "LoginAPI" contains the file "urls.py" The folder "LoginApp" contains a file "views.py"
tagged with: django
type: Question

http://stackoverflow.com/comment/119204049
score: 1
comment on: http://stackoverflow.com/a/52456197
has text: This solution did not work for me. Only installing google_trans_new solved my problem.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52516689
tagged with: python
has comment: http://stackoverflow.com/comment/91973740
has comment: http://stackoverflow.com/comment/91974034
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91973011
downvote count: 0
type: Question
tagged with: opencv
score: 3
has comment: http://stackoverflow.com/comment/91974104
accepted answer: http://stackoverflow.com/a/52517332
upvote count: 3
linked to: http://stackoverflow.com/q/11699298
has comment: http://stackoverflow.com/comment/91973156
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52517332
has body: Similiar to OpenCV 2.4 VideoCapture not working on Windows The result is a window with a grey image for about 2 seconds before closing and displaying "End of video import cv2 import imutils vidPath = "filename.mp4" video = cv2.VideoCapture(vidPath) index = 0; while True: print (index) index += 1 ret, frame = video.read() if ret == False: print("End of video") break frame = imutils.resize(frame, width = 500) cv2.imshow("Video", frame) video.release() cv2.destroyAllWindows() 'ret' always returns false after the index print gets to about 900, with nothing useful displaying on the window at all. The video in question is roughly 2 minutes long. Windows 10, Python version 3.5, OpenCV version 3.4.3 (contrib) installed via pip install opencv-contrib-python I have checked cv2.getBuildInformation(), FFMpeg is YES (prebuilt Binaries) I have copied opencv_ffmpeg313.dll to the path for python (user/AppData/Local/Programs/Python/Python35-32/Scripts) and (user/AppData/Local/Programs/Python/Python35-32) I also made copies of them called opencv_ffmpeg313_64.dll just in case I have also tried several different videos, multiple .mp4's, .avi's etc. I have exhausted every fix I have found for this problem and still come up sort.
has title: Python OpenCV-contrib v3.4.3 VideoCapture.read() returns false
has comment: http://stackoverflow.com/comment/91973820

http://stackoverflow.com/a/52559754
upvote count: 3
has comment: http://stackoverflow.com/comment/92058878
has comment: http://stackoverflow.com/comment/92058245
type: Answer
has comment: http://stackoverflow.com/comment/92058836
has comment: http://stackoverflow.com/comment/92058234
downvote count: 0
has comment: http://stackoverflow.com/comment/92058343
has comment: http://stackoverflow.com/comment/92058306
score: 3
answers question: http://stackoverflow.com/q/52559709
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52559709
has body: Applying isin on a GroupBy object doesn't make sense. You can use Boolean indexing on the index of your GroupBy object: Fruits = pdextract[pdextract.index.isin(sector.Fruits)] You can also filter on a series before your GroupBy operation: pdextract = pdmart.loc[pdmart['item'].isin(sector.Fruits)]\ .groupby('item')['price'].sum()

http://stackoverflow.com/q/52530200
tagged with: python
tagged with: command-line
upvote count: 2
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91999693
has comment: http://stackoverflow.com/comment/92001727
downvote count: 1
has answer: http://stackoverflow.com/a/52530581
type: Question
tagged with: tiff
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/91999595
has comment: http://stackoverflow.com/comment/91999927
has title: Why isn't my code working in command line?
has comment: http://stackoverflow.com/comment/91999720
tagged with: gdal
has comment: http://stackoverflow.com/comment/91999978
has comment: http://stackoverflow.com/comment/91999826
has comment: http://stackoverflow.com/comment/92001038
answer count: 1
favorite count: 0
has body: I am using Python3.6 and I need to run my code in command line. The code works when I run it in PyCharm but when I use command line I get this error: File "path", line 43, in &lt;module&gt; rb = ds.GetRasterBand(1) AttributeError: 'NoneType' object has no attribute 'GetRasterBand' It seems that I have a problem with these lines: ds = gdal.Open('tif_file.tif', gdal.GA_ReadOnly) rb = ds.GetRasterBand(1) img_array = rb.ReadAsArray() Does anyone know what I might have done wrong? EDIT Some magic just happened. I tried to run my code this morning and everything seems fine. I guess what my computer needed was a restart or something. Thanks to you all for help.

http://stackoverflow.com/comment/99922518
type: Comment
has text: I think [this](https://python-forum.io/Thread-Recursion-concept?pid=59503#pid59503) is a good visualization of what happened.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52578602

http://stackoverflow.com/a/52587964
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has body: It looks like you are creating a figure with multiple subplots, but only plotting on the first one. You are also using a combination of the object oriented API (axes.scatter) and the pyplot state-machine (plt.legend). So, when you call plt.legend it is looking for labels in one of your empty subplots and giving you the warning you are seeing. One solution would be to create a legend for the subplots you are plotting to using axes[0].legend(): for i in range(len(list(data_all_bands.values())[0])): y_multi = [v[i] for v in data_all_bands.values()] plt_multi = axes[0].scatter(x_multi, y_multi, label="channel" , color = colors[i])#, color=colors[i]) axes[0].legend()
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52587741
accepted answer of: http://stackoverflow.com/q/52587741

http://stackoverflow.com/comment/91813215
type: QuestionComment
score: 2
has text: If you make a list from an object with a `len`, Python can use that value to guess at the size of the list it will end up making, so it doesn't have to constantly resize the list, which is expensive.
comment on: http://stackoverflow.com/q/52434815
type: Comment

http://stackoverflow.com/a/52475184
type: Answer
has comment: http://stackoverflow.com/comment/134746697
score: 2
upvote count: 2
has body: I solved the problem by using the following solution (https://github.com/rtfd/sphinx_rtd_theme/pull/672/commits/4b9053cb9e805211f227399d66d82361b3e2bf56). Credit goes to GitHub user @tk0miya. First, navigate to the Python installation folder and locate the layout.html inside ./Lib/site-packages/sphinx_rtd_theme/layout.html. Then replace line 191 - 204 containing {%- for scriptfile in script_files %} {%- endfor %} by the following code {% if sphinx_version >= "1.8.0" %} {%- for scriptfile in script_files %} {{ js_tag(scriptfile) }} {%- endfor %} {% else %} {%- for scriptfile in script_files %} {%- endfor %} {% endif %} Then run make clean and make html inside your documentation folder for the console. It is important that the console commands are executed inside your documentation folder.
answers question: http://stackoverflow.com/q/52474177
downvote count: 0

http://stackoverflow.com/q/52542273
has comment: http://stackoverflow.com/comment/92024508
has comment: http://stackoverflow.com/comment/92024868
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92024963
has comment: http://stackoverflow.com/comment/92024952
has comment: http://stackoverflow.com/comment/92024443
type: UnansweredQuestion
has title: django type object 'PoliceDefenceJobs' has no attribute 'objects'
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92024465
has body: Here is my models.py class PoliceDefenceJobs(models.Model): police_defence_id = models.AutoField(primary_key=True) start_date = models.CharField(max_length=60) last_date = models.CharField(max_length=60) post_name = models.CharField(max_length=255) education = models.CharField(max_length=255) more_info = models.TextField() requirement_board = models.CharField(max_length=255) type = models.IntegerField() job_id = models.IntegerField(default=None,blank=True,null=True) join_id = models.IntegerField(default=None,blank=True,null=True) def __str__(self): return "Police Defence Jobs" here is my views.py class PoliceDefenceJobs: def police_defence_jobs(request): PoliceDefenceJobs.objects.all().delete() return JsonResponse({"code":200}) Here i am getting type object 'PoliceDefenceJobs' has no attribute 'objects' error..
has comment: http://stackoverflow.com/comment/92024471
type: Question
has answer: http://stackoverflow.com/a/52543549
has comment: http://stackoverflow.com/comment/92024536

http://stackoverflow.com/q/52440529
tagged with: python
has body: I understand that: "When axis=0, columns which only contained missing values at fit are discarded upon transform." So the first time I use the Imputer all NaN values are replaced by the mean and the columns only contained missing values are replaced. My code: df.shape (1430,488) #1. delete all columns containing 0 df=df.loc[:, (df != 0).any(axis=0)] df.shape (1430,370) #2. replace all Nan Values with mean from sklearn.preprocessing import Imputer imr = Imputer(missing_values='NaN', strategy='mean', axis=0) imr = imr.fit(df) imputed_data = imr.transform(df.values) imputed_data.shape (1430,321) #3. replace all 0 Values with mean from sklearn.preprocessing import Imputer imr = Imputer(missing_values=0, strategy='mean', axis=0) imr = imr.fit(df) imputed_data = imr.transform(df.values) imputed_data.shape (1430,167) So in the first step i am deleting all columns containing 0 and then in step 2 the imputer is deleting all columns with only NaN. But why is there a reduction of dimension when it comes to step 3 to 167 columns? I already deleted all columns with only 0 in step 1? Another question is how can i transform the new numpy array back to pandas without losing the header? Thank you, R
score: 0
tagged with: dimension
type: UnansweredQuestion
has title: Scikit-learn Imputer reducing dimensions when using it twice
answer count: 0
tagged with: scikit-learn
type: Question
has comment: http://stackoverflow.com/comment/91830809
has comment: http://stackoverflow.com/comment/91828066

http://stackoverflow.com/a/52451469
upvote count: 5
has comment: http://stackoverflow.com/comment/109684316
accepted answer of: http://stackoverflow.com/q/52450659
type: AcceptedAnswer
downvote count: 0
has body: I remember having similar issues getting sqlalchemy setup. I've attached my engine statement syntax. I don't remember the details, but I do remember the driver selection being a real pain point. I believe I had to download the ODBC 13 driver separately, but can confirm pd.read_sql() and df.to_sql are working like a charm now. driver = 'ODBC+DRIVER+13+for+SQL+Server' engine_stmt = ("mssql+pyodbc://%s:%s@%s/%s?driver=%s" % (username, password, server, database, driver ) engine = sqlalchemy.create_engine(engine_stmt)
has comment: http://stackoverflow.com/comment/109683903
type: Answer
answers question: http://stackoverflow.com/q/52450659
score: 5

http://stackoverflow.com/a/52558507
has comment: http://stackoverflow.com/comment/92094848
has comment: http://stackoverflow.com/comment/92230535
has comment: http://stackoverflow.com/comment/92157547
type: Answer
has comment: http://stackoverflow.com/comment/92175870
answers question: http://stackoverflow.com/q/52556750
score: 1
upvote count: 1
has body: Assuming you know the name of the function in question: Use the 'Find in Path' function. Edit > Find > Find in Path or Right Click folder in project > Find in Path Then search for a definition of the function you're looking for. You can see my example I have the same function name in two different modules.
downvote count: 0

http://stackoverflow.com/q/52521654
has title: Kivy - combining KV with python logic
type: Question
has comment: http://stackoverflow.com/comment/91983372
has comment: http://stackoverflow.com/comment/91983529
score: 0
has comment: http://stackoverflow.com/comment/91983190
tagged with: kivy
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm struggling since yesterday with my kivy application and I'm in the dead end. I'm a newbie programmer and I decided that I want to create app in Kivy, with logic in Python. App will collect status of the devices connected to the network through REST API. Rest api works well, and I have all the infos that I needed. Also, my graphical side of the project is done. Now I want to connect those two things into one. Here's the problem. from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition from kivy.config import Config from os import listdir from kivy.uix.label import Label from kivy.properties import ObjectProperty from rest import sniffer # Window config Config.set('graphics', 'width', '800') Config.set('graphics', 'height', '500') Config.set('graphics', 'resizable', False) Config.write() # Variables mir_list = [] mir_dict = {'MiR_S161': '10.173.175.117', 'MiR_S162': '10.173.175.121', 'MiR_S319': '10.173.175.120', 'MiR_S325': '10.173.175.119', 'MiR_S326': '10.173.175.116', 'MiR_S327': '10.173.175.118' } # Kivy kv_path = './kv/' for kv in listdir(kv_path): Builder.load_file(kv_path+kv) # Declare screens class MainScreen(Screen): pass class MiRScreen161(Screen): pass class MiRScreen162(Screen): pass class MiRScreen319(Screen): pass class MiRScreen325(Screen): pass class MiRScreen326(Screen): pass class MiRScreen327(Screen): pass # Create the screen manager sm = ScreenManager(transition = SlideTransition()) sm.add_widget(MainScreen(name='main')) sm.add_widget(MiRScreen161(name='MiR_S161')) sm.add_widget(MiRScreen162(name='MiR_S162')) sm.add_widget(MiRScreen319(name='MiR_S319')) sm.add_widget(MiRScreen325(name='MiR_S325')) sm.add_widget(MiRScreen326(name='MiR_S326')) sm.add_widget(MiRScreen327(name='MiR_S327')) class MainApp(App): def build(self): self.title = 'MiR Sniffer' return sm if __name__ == '__main__': MainApp().run() That's my main code - it refers to the other .py script with the REST han…
has comment: http://stackoverflow.com/comment/91984204
has comment: http://stackoverflow.com/comment/91982982

http://stackoverflow.com/comment/91839546
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52447748
type: Comment
has text: You don't need enumerate. just `for date, new_df in df.groupby():`, then `new_df` is your `DataFrame`

http://stackoverflow.com/q/52581386
score: 1
has title: Getting True or False value for elements in a list from a dictionary
has body: Suppose we for example have these variables: my_list = ["door_open", "AND", "dog_gone"], my_dict ={"door_open" : "false", "dog_gone" : "true", "dog_asleep" : "true"}) (Note, the list and dictionary could be longer or shorter and it should still work) . And we want to be able to run it through this function: def and_function(arg1, arg2): if arg1=="true" and arg2=="true": return "true" else: return "false" How do we write a function that first will check if the elements in the list are "true" or "false", and then run it through the "and_function". This is somewhat what it should look like: def interpret(my_list, my_dict): #DO SOMETHING SO WE GET THE "true" OR "false" VALUE FOR ELEMENTS . . . if "AND" in my_list: return and_function(ture_or_false, false_or_true) "false"
type: Question
has comment: http://stackoverflow.com/comment/92097961
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92097892
has comment: http://stackoverflow.com/comment/92097944
favorite count: 0
has answer: http://stackoverflow.com/a/52581702
tagged with: python
tagged with: dictionary
tagged with: list
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/92097981
has comment: http://stackoverflow.com/comment/92098002
has comment: http://stackoverflow.com/comment/92098025

http://stackoverflow.com/comment/92053222
comment on: http://stackoverflow.com/q/52546519
type: Comment
type: QuestionComment
has text: In your code example, I don't see what are you joining those table on (no "on" parameter"). You might do some unexpected many to many join, say if you join on company, and same company appear in both tables 3 times you'll get 9 rows in the output. I would also check how that script works on smaller arrays. Say if on 1000 files it runs for a minute but for 2000 it runs way much longer (like 20 minutes), there might be an issue with memory handling
score: 0

http://stackoverflow.com/a/52481932
answers question: http://stackoverflow.com/q/52481651
upvote count: 1
score: 1
downvote count: 0
has body: df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]), columns=['a', 'b']) Now you can use the quantile function in pandas. Make sure you using the numbers between 0 and 1. Here an example below: df.a.quantile(0.5) 3.25 You can apply the function to the whole dataframe
type: Answer

http://stackoverflow.com/q/52578329
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/92092392
has comment: http://stackoverflow.com/comment/92092309
has comment: http://stackoverflow.com/comment/92092218
has comment: http://stackoverflow.com/comment/92092311
has comment: http://stackoverflow.com/comment/92092366
answer count: 1
has comment: http://stackoverflow.com/comment/92092347
tagged with: calculator
has comment: http://stackoverflow.com/comment/92092369
has comment: http://stackoverflow.com/comment/92091948
favorite count: 0
has comment: http://stackoverflow.com/comment/92092066
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92091822
has comment: http://stackoverflow.com/comment/92092318
score: -1
has comment: http://stackoverflow.com/comment/92091926
has answer: http://stackoverflow.com/a/52578747
has comment: http://stackoverflow.com/comment/92092570
downvote count: 2
has body: I am asked to create a function: maximum_home_loan(PMT, i, n) that calculates the maximum home loan that my customer can afford, if they: Can afford to pay an amount, PMT at the end of every YEAR (with the 1st payment made at exactly one year from now) at an interest of i% per year compounded annually, and pay off the home over a term of n year. This is how I did it but I think the amount don't add up. def maximum_home_loan(PMT, i, n): For i in range(n): PMT = PMT*(1 + i)**n PV = PMT + i PV = PV + PMT PV = round(PV, 2) return float(PV) print(maximum_home_loan(15000*12, 0.1045/100, 25)) Output: 369523.89 And the output should actually be: 1578934.73 What is it that am doing wrong?
upvote count: 1
has title: Home loan affordability Calculator

http://stackoverflow.com/q/52529785
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91998982
has comment: http://stackoverflow.com/comment/91998983
has title: Plotting data with matplot and python to graph
type: Question
has body: I'm currently trying to plot 7 days with varying small to large numbers. The first set of data may look like this dates = ['2018-09-20', '2018-09-21', '2018-09-22', '2018-09-23', '2018-09-24', '2018-09-25', '2018-09-26', '2018-09-27'] values = [107.660514, 107.550403, 107.435041, 107.435003, 107.574965, 107.449961, 107.650052, 107.649974] vs another set of data may have the same dates, but the values may be much small incremental changes dates = ['2018-09-20', '2018-09-21', '2018-09-22', '2018-09-23', '2018-09-24', '2018-09-25', '2018-09-26', '2018-09-27'] values = [0.849215, 0.849655, 0.849655, 0.851095, 0.850885, 0.850135, 0.851203, 0.851865] When I use this import matplotlib import matplotlib.pyplot as plt import numpy as np plt.plot_date(x=dates, y=values, fmt="r--") plt.ylabel(c) plt.grid(True) plt.savefig('static/%s.png' % c) The resulting image for the 1st set of values comes out as a dashed lined connecting the days to the dots. But the 2nd set of data makes a image of 7 parallel lines stacked on top of each other. Should I be plotting this differently?
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/91998853
has answer: http://stackoverflow.com/a/52530421
answer count: 1
has comment: http://stackoverflow.com/comment/91998851
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91998868
has comment: http://stackoverflow.com/comment/92000178
accepted answer: http://stackoverflow.com/a/52530421

http://stackoverflow.com/comment/91867303
comment on: http://stackoverflow.com/q/52462497
has text: Your code would work only for max >= 5, since you are comparing fib and self.max which would not work for index < 5.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91915020
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52486822
score: 0
has text: @Jean-FrançoisFabre, better :)

http://stackoverflow.com/a/52540164
score: 0
has body: To answer your question you need the following: Knowledge how to read txt files Knowledge about regex And here is a possible answer: with open(examplefile) as f: t = f.read() m = re.search(r"Cluster : (.+?)\n", t) if m: print(m.group(1)) This will print TEST2
type: Answer
answers question: http://stackoverflow.com/q/52539930

http://stackoverflow.com/q/52451007
has title: I can't find ConvexHull in scipy.spatial
has answer: http://stackoverflow.com/a/52452556
accepted answer: http://stackoverflow.com/a/52452556
has comment: http://stackoverflow.com/comment/91848819
has body: Edit: As far as I can tell it's an issue with the build, I haven't figured out exactly what yet, but I've narrowed it down to that. For anyone reading this, try the suggestion in the marked answer first. I'm trying to use the ConvexHull function from the scipy library to compute the convex hull for some points, but scipy.spatial.ConvexHull doesn't seem to exist. The documentation has this as an example: from scipy.spatial import ConvexHull points = np.random.rand(30, 2) # 30 random points in 2-D hull = ConvexHull(points) I tried to use this example in my project but couldn't get it to work.. I typed in the appropriate import line but ConvexHull was not found, PyCharm underlined the ConvexHull reference in red, and a mouse-hover shows a 'not found' message. I've found various mentions on SO about different methods that might be required for importing and using parts of scipy, which I've tried and none of them seem to work, including the import line in the docs example. I'm running Python 3.6 inside a clean PyCharm venv that I've just created. The pip install of scipy worked fine and scipy is appearing when I try to import it, as is spatial... but ConvexHull doesn't seem to exist. I'm using scipy 1.1.0, and I've tried using the import that a deleted answer provided... from scipy.spatial.qhull import ConvexHull... but this didn't work. Alternately, if this won't work then I am willing to use a different library if possible.
tagged with: python
has comment: http://stackoverflow.com/comment/91848784
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91845640
tagged with: convex-hull
tagged with: scipy
type: Question
answer count: 1
score: 0

http://stackoverflow.com/comment/91811058
score: 1
has text: Please post the *complete* exception traceback, and rename your `typing` module to something else - you don't want it to clash with the [`typing` module](https://docs.python.org/3/library/typing.html) in the standard library.
comment on: http://stackoverflow.com/q/52433611
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91984905
type: AnswerComment
comment on: http://stackoverflow.com/a/52522073
type: Comment
has text: @LasitPant did you use the `*` for wildcards? Essentially was your query for `"*Lasit Pant*"` or just for `"Lasit Pant"`?
score: 0

http://stackoverflow.com/comment/91896382
type: QuestionComment
has text: Possible duplicate of [How to run a simple python script on heroku without flask/django?](https://stackoverflow.com/questions/35438949/how-to-run-a-simple-python-script-on-heroku-without-flask-django)
comment on: http://stackoverflow.com/q/52477103
score: 0
type: Comment

http://stackoverflow.com/q/52525355
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
has comment: http://stackoverflow.com/comment/91991358
linked to: http://stackoverflow.com/q/19505676
answer count: 0
linked to: http://stackoverflow.com/q/19616205
type: Question
has comment: http://stackoverflow.com/comment/91990808
has body: Suppose I have a dataframe created from the following list: import pandas as pd from openpyxl import Workbook from pandas import ExcelWriter import openpyxl #Using openpyxl engine wb = Workbook() sheet = wb.active data = [ [0, 0, 1], [3, 0, 4], ['=EVALUATE(Something ends up being 1)', 0, 4], [4, 0, 1]] df = pd.DataFrame(data, columns=["value", "min", "max"]) Now I want to format(color the cell) the first(value) column based on the min and max column; green if within range, and red if not. In this example it should be [Green,Green,Green,Red]. I've tried a few examples at: https://pandas.pydata.org/pandas-docs/stable/style.html, however, the formatting is static. Problems: If I were to change the value in the excel sheet to fit/unfit the condition, the style remains the same. If 1. cannot be addressed, excel formulas are interpreted as non numbers, so how do I get them to evaluate within the code?
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/91990768
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91990891
has comment: http://stackoverflow.com/comment/91990872
has comment: http://stackoverflow.com/comment/91991095
has title: Pandas Dynamic Conditional Formatting
has comment: http://stackoverflow.com/comment/91992912

http://stackoverflow.com/comment/91851406
type: Comment
comment on: http://stackoverflow.com/q/52454310
type: QuestionComment
score: 1
has text: @asmgx which means you don't have it installed. It requires installation.

http://stackoverflow.com/q/52582418
type: Question
tagged with: dynamic-tables
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52589454
type: UnansweredQuestion
tagged with: python
has body: I am trying to fetch a specific table from a webpage using BeautifulSoup4 and Selenium the table is present there but it is not fetching using this code. I tried this from bs4 import BeautifulSoup from selenium import webdriver import time driver = webdriver.Chrome() url = 'https://de.sharkscope.com/#Find-Tournament/networks/PokerStars/tournaments/2412466083' driver.get(url) res = driver.execute_script("return document.documentElement.outerHTML") time.sleep(5) driver.quit() soup = BeautifulSoup(res, 'lxml') targetTable = soup.findAll('table', {'id': 'tournamentgrid-1538318460041'}) print(targetTable) screenshot table With ID and the Result DisplayResult Platform and tools Microsoft Windows 10 x64 Using Chromium Webdriver ( installed version 32bit) Edited. I already Tried table = driver.get_element_by_id('tournamentgrid-1538318460041') &amp; table = driver.get_element_by_xpath('//*[@id="tournamentgrid-1538398792982"]')
tagged with: selenium-webdriver
has title: Using Selenium and BeautifulSoup Specific table is not returning by providing table ID Python3.7 ( returns Empty Array)
tagged with: selenium
upvote count: 1

http://stackoverflow.com/q/52507368
has title: How can I use tf.cond?
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91961792
tagged with: deep-learning
upvote count: 1
favorite count: 0
tagged with: python
has body: I'm trying to get the result from model using condition statement. There are 3 tensors all has the same shape: mu, sigma, alpha. Among them, if alpha[:, -1] has a probability of zero, I want to get the 0 value. Specifically, if alpha[:, -1] is bigger than 0.5, and other value when alpha[:, -1] is smaller than 0.5. This is my code. def get_mdn_result(self, params): # ouput of each step -&gt; params : 2d mu = params[:, :self.num_mixture] sigma = params[:, self.num_mixture:self.num_mixture * 2] alpha = params[:, self.num_mixture * 2:self.num_mixture * 3] mu = tf.reduce_sum(mu * alpha, 1, keepdims=True) sigma = tf.reduce_sum(sigma**2 * alpha**2, 1, keepdims=True) mu = tf.cond(alpha[:, -1] &lt; 0.5, lambda: tf.reduce_sum(mu * alpha, 1, keepdims=True), lambda: 0) return mu, sigma but I've got an error message like below. Shape must be rank 0 but is rank 1 for 'while/cond/Switch' (op: 'Switch') with input shapes: [?], [?]. How I can fix it? mu, alpha are like this mu [[1, 2, 3], [2, 3, 4]] alpha [[0.1, 0.3, 0.6],[0.5, 0.2, 0.3]]

http://stackoverflow.com/q/52434480
tagged with: machine-learning
has body: Hello I am following a video on Udemy. We are trying to apply a random forest classifier. Before we do so, we convert one of the columns in a data frame into a string. The 'Cabin' column represents values such as "4C" but in order to reduce the number of unique values, we want to use simply the first number to map onto a new column 'Cabin_mapped'. data['Cabin_mapped'] = data['Cabin'].astype(str).str[0] # this transforms the letters into numbers cabin_dict = {k:i for i, k in enumerate( data['Cabin_mapped'].unique(),0)} data.loc[:,'Cabin_mapped'] = data.loc[:,'Cabin_mapped'].map(cabin_dict) data'Cabin_mapped', 'Cabin'.head() This part below is simply splitting the data into training and test set. The parameters don't really matter for figuring out the problem. X_train_less_cat, X_test_less_cat, y_train, y_test = \ train_test_split(data[use_cols].fillna(0), data.Survived, test_size = 0.3, random_state=0) I get an error here after the fit, saying I could not convert the string into a float. rf = RandomForestClassifier(n_estimators=200, random_state=39) rf.fit(X_train_less_cat, y_train) It seems like I need to convert one of the inputs back into float to use the random forest algorithms. This is despite the error not showing up in the tutorial video. If anyone could help me out, that'd be great.
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/52434887
has comment: http://stackoverflow.com/comment/91812817
has comment: http://stackoverflow.com/comment/91813177
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91812891
type: UnansweredQuestion
tagged with: python
has title: ValueError: could not convert string to float: 'n'
tagged with: sklearn-pandas
upvote count: 3
score: 1
has comment: http://stackoverflow.com/comment/91812618
downvote count: 2

http://stackoverflow.com/q/52432991
downvote count: 2
tagged with: document
answer count: 1
has title: Copying specific content from one word doc to another
tagged with: automation
upvote count: 0
has body: I'm trying to automate copying specific content from one word document(table) to other document(tables(s)), Please see below image to understand what I'm trying to do. Please suggest on how to make it work. I'm pretty comfortable with using python, if that's possible or any another tool. Thanks in advance.
type: UnansweredQuestion
tagged with: copying
tagged with: ms-word
favorite count: 0
has answer: http://stackoverflow.com/a/52443753
type: Question
tagged with: python
score: -2

http://stackoverflow.com/q/52469467
has comment: http://stackoverflow.com/comment/91880920
has comment: http://stackoverflow.com/comment/91880902
has answer: http://stackoverflow.com/a/52469544
tagged with: python-3.x
downvote count: 2
possible better answer: http://stackoverflow.com/a/52469544
type: AnsweredQuestion
tagged with: list
score: -2
accepted answer: http://stackoverflow.com/a/52469522
has answer: http://stackoverflow.com/a/52469618
has body: I got a list of words. Let's say: words = ['a', 'b', 'c', 'd', 'a', 'g', 'h', 'v'] values = ['donkey', 'monkey', 'whale', 'dog'] Note: real lists are much longer Depending on each element in the list words it should output a certain value. For example, a should print donkey, b should print whale etcetera. The values are very long(30 elements). Also they are handwritten. They aren't read from something else. The wordsare. This means I can choose for a dictionary or something else if this is better. What's the best way to handle this?
has comment: http://stackoverflow.com/comment/91880976
type: Question
has comment: http://stackoverflow.com/comment/91880873
upvote count: 0
has title: Match element in list with possible values
has comment: http://stackoverflow.com/comment/91880901
favorite count: 0
has comment: http://stackoverflow.com/comment/91880939
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91880896
has answer: http://stackoverflow.com/a/52469522

http://stackoverflow.com/q/52541136
has body: Hy, I tried this code found in many links with some minor differences between them main.py #-*-coding:utf8;-*- #qpy:2 #!/usr/bin/python # -*- coding: utf-8 -*- import androidhelper droid = androidhelper.Android() scan = droid.scanBarcode().result result = [(scan['extras']['SCAN_RESULT'])] droid.dialogCreateAlert('u'.join(result)) droid.dialogShow() with QPython and it works well. I had installed "Barcode Scanner+" as app for scan barcode as it is based on ZXing library (https://play.google.com/store/apps/details?id=com.srowen.bs.android). Then I tried to create an APK with buildozer and installed on mobile it crashed immediately after start app. buildozer.spec [app] # (str) Title of your application title = appFMS # (str) Package name package.name = FMpkgS # (str) Package domain (needed for android/ios packaging) package.domain = aaaaa.com # (str) Source code where the main.py live source.dir = . # (list) Source files to include (let empty to include all the files) source.include_exts = py,png,jpg,kv,atlas,ini # (list) List of inclusions using pattern matching #source.include_patterns = assets/*,images/*.png # (list) Source files to exclude (let empty to not exclude anything) #source.exclude_exts = spec # (list) List of directory to exclude (let empty to not exclude anything) #source.exclude_dirs = tests, bin # (list) List of exclusions using pattern matching #source.exclude_patterns = license,images/*/*.jpg # (str) Application versioning (method 1) version = 1.0.1 # (str) Application versioning (method 2) # version.regex = __version__ = ['"](.*)['"] # version.filename = %(source.dir)s/main.py # (list) Application requirements # comma seperated e.g. requirements = sqlite3,kivy #requirements = kivy==master,paho-mqtt # (str) Custom source folders for requirements # Sets custom source for any requirements with recipes # requirements.source.kivy = ../../kivy # (list) Garden requirements #garden_requirements = xcamera # (str) Presplash of the application #presplash.filen…
tagged with: android
tagged with: apk
tagged with: python
tagged with: qpython
type: UnansweredQuestion
type: Question
has title: Python code work with qpython but apk crash on mobile
answer count: 1
has answer: http://stackoverflow.com/a/52810783
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/92103258
type: QuestionComment
has text: _my python code only passes 3 out of 5 tests cases_ Do you know what the 5 test cases are, and do you know which two are failing? Does your program produce correct output for the test case given in the instructions? (input `[3,1,4,1,5,9]` returns `94311`).
comment on: http://stackoverflow.com/q/52584048
score: 0
type: Comment

http://stackoverflow.com/q/52466638
has body: I have CUDA 9.0 and CUDNN 7.1 installed on Ubuntu 18.04(Linux mint 19). Tensorflow-gpu works fine on GPU(GTX 1080ti). Now i am trying to build dlib with CUDA support: sudo python3 setup.py install --yes USE_AVX_INSTRUCTIONS --yes DLIB_USE_CUDA --clean Got the error: user@user-pc:~/Downloads/dlib$ sudo python3 setup.py install --yes USE_AVX_INSTRUCTIONS --yes DLIB_USE_CUDA --clean running install running bdist_egg running egg_info writing dlib.egg-info/PKG-INFO writing dependency_links to dlib.egg-info/dependency_links.txt writing top-level names to dlib.egg-info/top_level.txt package init file 'dlib/__init__.py' not found (or not a regular file) reading manifest file 'dlib.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'dlib.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib running build_py running build_ext Building extension for Python 3.6.5 (default, Apr 1 2018, 05:46:30) Invoking CMake setup: 'cmake /home/me/Downloads/dlib/tools/python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/home/me/Downloads/dlib/build/lib.linux-x86_64-3.6 -DPYTHON_EXECUTABLE=/usr/bin/python3 -DUSE_AVX_INSTRUCTIONS=yes -DDLIB_USE_CUDA=yes -DCMAKE_BUILD_TYPE=Release' -- The C compiler identification is GNU 4.8.5 -- The CXX compiler identification is GNU 7.3.0 -- Check for working C compiler: /usr/bin/cc -- Check for working C compiler: /usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Found PythonInterp: /usr/bin/python3 (found version "3.6.5") -- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython3.6m.so -- Performing Test HAS_CPP14_FLAG -- Perfor…
downvote count: 1
tagged with: dlib
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91876807
upvote count: 0
tagged with: ubuntu
tagged with: gpu
answer count: 1
has answer: http://stackoverflow.com/a/52470013
favorite count: 0
score: -1
tagged with: nvidia
has title: Install dlib with cuda support ubuntu 18.04
has comment: http://stackoverflow.com/comment/91877507
has comment: http://stackoverflow.com/comment/91881969
accepted answer: http://stackoverflow.com/a/52470013
has comment: http://stackoverflow.com/comment/91875424
tagged with: python

http://stackoverflow.com/a/52485506
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52485217
downvote count: 0
has body: An alternative way, less generalized way x = df.set_index('amount')'feature_2020', 'feature_2030', 'feature_2040' r1 = x.lt(20).mul(x.index, axis=0).sum() r2 = (x.ge(20) &amp; x.lt(40)).mul(x.index, axis=0).sum() r3 = x.ge(40).mul(x.index, axis=0).sum() df_f = pd.concat([r1,r2,r3], 1).T feature_2020 feature_2030 feature_2040 0 500 0 0 1 1000 500 500 2 0 1000 1000

http://stackoverflow.com/comment/91813646
type: QuestionComment
comment on: http://stackoverflow.com/q/52433957
type: Comment
has text: @JohnY A good idea but when I bring the .csv into ArcMap it just turns the "smart quotes" into a regular "straight quotes".
score: 0

http://stackoverflow.com/q/52485191
tagged with: javascript
tagged with: jquery
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52486332
has comment: http://stackoverflow.com/comment/91913374
tagged with: django
tagged with: python
has title: Django post data from Javascript function
type: AnsweredQuestion
tagged with: django-views
has comment: http://stackoverflow.com/comment/91913804
has body: I'm trying to send a string to a post view via checkbox being checked and unchecked. The part I am having trouble with is on the post view being able to get read the data. I have the name being generated during the templating of the HTML to tell me the id of the item. Then the javascript is supposed to pass the name of the checkbox to the post view and then just print out the post value. Error The error I'm getting is that it returned a "None" so I'm thinking I'm not getting the name right. In the data field of the javascript, I also tried "data:{data:$header}" and I got the same result. Javascript $("input[type='checkbox']").change(function() { // console.log($header = $(this)[0].name) $header = $(this)[0].name $.post({ url: "", data: $header, headers: { 'X-CSRFToken': csrftoken } }) }); Django view.py class CurrentCodeView(LoginRequiredMixin,DetailView): template_name = 'codes/currentCodes.html' def get(self, request, *args, **kwargs): //doing alot of stuff def post(self,request,*args, **kwargs): print(request.POST.get('data'))
type: Question
has answer: http://stackoverflow.com/a/52486332

http://stackoverflow.com/comment/91889210
comment on: http://stackoverflow.com/a/52455781
type: Comment
has text: Its a Handycam not webcam how can we connect Handycam
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91989274
has text: The start and end values are results of calculations with numpy arrays. Also, the number of elements given by start[k]:end[k] differs for each k
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52524761

http://stackoverflow.com/comment/131741376
comment on: http://stackoverflow.com/a/72808431
has text: I've been trying to figure out how to get around that limit by actually paying for the service. So far been unable :-( :shaking head:
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52521545
has comment: http://stackoverflow.com/comment/91982630
type: UnansweredQuestion
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/91983319
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91983348
type: Question
has comment: http://stackoverflow.com/comment/91983107
has title: How can I get a square wave by using python pandas or matplotlib？
score: 0
has body: I’m trying to use python to deal with data to get a SPC or CPK chart. I want to draw a line like ‘UCL’ as below. But now, I can only draw a line like P-bar. How can I get it in an easy way？ my code： df.plot(x=‘StartDateTime’,y=[‘UCL’,’LCL’,’P-bar’,’P’]) plt.show() And I get this:
tagged with: pandas
has answer: http://stackoverflow.com/a/52522294
answer count: 1

http://stackoverflow.com/comment/91847354
type: AnswerComment
comment on: http://stackoverflow.com/a/52451920
has text: Ok. I just ran some tests. You can get runs longer than 2 at the end of the list.
type: Comment
score: 0

http://stackoverflow.com/comment/92099601
type: AnswerComment
comment on: http://stackoverflow.com/a/52581659
score: 0
type: Comment
has text: Ok, I think this is starting to make sense now. How do I have it stop reading lines once it has read a certain number of rows?

http://stackoverflow.com/q/52464269
answer count: 2
tagged with: pandas
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
possible better answer: http://stackoverflow.com/a/52464497
tagged with: python
has answer: http://stackoverflow.com/a/52464497
has body: I have found many answers relating to Errno 22 but nothing pandas specific and nothing where it is only on overwrite not on write (initial write succeeds). So ive managed to recreate the bug with the following python script: import pandas as pd print('path:') path = input() data = pd.DataFrame(data=[1,2,3], columns=['index']) data.to_csv(path, encoding='utf-8', index=False) data = data.append(pd.DataFrame(data=[4,5,6], columns=['index'])) data.to_csv(path, encoding='utf-8', index=False) so the first call to to_csv writes the following file index 1 2 3 but the second call to to_csv causes the error: OSError: [Errno 22] Invalid argument: '[path omitted]/python/bug' Any help is much appreciated :)
accepted answer: http://stackoverflow.com/a/52464560
type: AnsweredQuestion
downvote count: 0
has title: Python Pandas unable to overwrite a csv file "OSError: [Errno 22] Invalid argument"
score: 1
type: Question
has answer: http://stackoverflow.com/a/52464560

http://stackoverflow.com/comment/92081693
type: AnswerComment
comment on: http://stackoverflow.com/a/52572471
score: 0
type: Comment
has text: One more thing, the code runs just perfect but there is one error on the last line.

http://stackoverflow.com/comment/91958069
type: Comment
has text: Thank you. That makes a lot of sense. I can calculate mean and std of an actual set of numbers. Not sure how this is done with images or tensors. Do you perhaps have a peace of code or link (just as an example) where you've actually done that ?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52490369

http://stackoverflow.com/comment/91863354
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52460662
has text: Can you suggest a way of reversing this process?

http://stackoverflow.com/comment/92560190
has text: May be some user access issue or something? Try to get inside the code of DotExporter and see what is happening
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52493775
score: 0

http://stackoverflow.com/a/52445426
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52444490
accepted answer of: http://stackoverflow.com/q/52444490
type: Answer
score: 2
downvote count: 0
has body: You can repeat elements, then concatenate. from keras.layers import Input, Lambda, Concatenate from keras.models import Model import keras.backend as K rows = 2 cols = 2 features = 2 row = Input((1, cols, features)) col = Input((rows, 1, features)) row_repeated = Lambda(lambda x: K.repeat_elements(x, rows, axis=1))(row) col_repeated = Lambda(lambda x: K.repeat_elements(x, cols, axis=2))(col) out = Concatenate()([row_repeated, col_repeated]) model = Model(inputs=[row,col], outputs=out) model.summary() Experiment: import numpy as np x = np.array([1,2,3,4]).reshape((1, 1, 2, 2)) y = np.array([5,6,7,8]).reshape((1, 2, 1, 2)) model.predict([x, y]) #array([[[[1., 2., 5., 6.], # [3., 4., 5., 6.]], # # [[1., 2., 7., 8.], # [3., 4., 7., 8.]]]], dtype=float32)
upvote count: 2

http://stackoverflow.com/q/52480804
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91905536
has title: Stretching an image with lastly available pixels(background)
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91911806
has comment: http://stackoverflow.com/comment/91955370
type: UnansweredQuestion
has body: I've an image of shape (768,576,3) and I want to Resize it into (1100,1100,3). But not in a usual way. The above image has to be padded three sides(top, right left) with their near by pixel values like the below image. It is like stretching the image from three sides. How to achieve this programmatically using opencv, numpy or any other way?
tagged with: python
has comment: http://stackoverflow.com/comment/91975531
tagged with: opencv
has answer: http://stackoverflow.com/a/52485288
has comment: http://stackoverflow.com/comment/91911839
tagged with: scipy

http://stackoverflow.com/comment/91830174
has text: What does "The root environment has this libraries, but I don't know if I could import from there." mean? If those packages are installed, what problem is there using them?
score: 0
comment on: http://stackoverflow.com/q/52443042
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91858961
type: Comment
type: QuestionComment
has text: There is a python package called `urlparse` which can help you split up a URL into multiple separate pieces. And then yes using the `datetime` python package can probably help you iterate through every day. Then you can save that to a CSV file pretty easily. Stackoverflow isn't really meant for broad design questions, so I would suggest trying your best at getting something working, and then make a question here if you get stuck on something specific or an error happens that you can't fix.
comment on: http://stackoverflow.com/q/52458349
score: 0

http://stackoverflow.com/q/52518283
score: 3
has answer: http://stackoverflow.com/a/52518610
possible better answer: http://stackoverflow.com/a/52518565
linked to: http://stackoverflow.com/q/22591174
has title: In Python Pandas, how to search if column elements contains the first 2 digits
has answer: http://stackoverflow.com/a/52518450
accepted answer: http://stackoverflow.com/a/52518507
has body: I am fairly new to Python and currently I am trying to build a function that searches for the first 2 digits of the elements in a column and if true, return the result with a new header such as region For example, Adres AreaCode Region 0 SArea 123191 A 1 BArea 122929 A 2 AArea 132222 B I want the function to search for just the first 2 digits of the AreaCode which would give me the result of along with a new header of Region which classifies the Region based on the first 2 digits of the AreaCode. So in this case 12 would give me A and 13 would give me B I already tried this df.loc[df.AreaCode == 123191, 'Region'] = 'A' and this worked for the entire AreaCode but I have no idea how to modify it so that I would be able to search based on the first 2 digits. and I tried this df.loc[df.AreaCode.str.contains == 12, 'Region' ] = 'A' but it gives me the error: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas How do I fix this and thanks a lot for helping!
tagged with: pandas
downvote count: 0
favorite count: 0
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/52518670
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52518507
upvote count: 3
has answer: http://stackoverflow.com/a/52518565
type: Question

http://stackoverflow.com/comment/92099502
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52582189
has text: @Ehsan: yes, you obtain the second element, and can treat it as an indpendent one (well it is an independent one :)
score: 1

http://stackoverflow.com/a/52559048
score: 1
upvote count: 1
has body: This seems like a case for crosstab (it's a built-in function :D) import pandas as pd df = pd.DataFrame([['M', 0], ['M', 1], ['M', 1], ['F', 0], ['F', 0], ['F', 1]], columns=['Gender', 'Showed']) pd.crosstab(df.Gender, df.Showed) Output: Showed 0 1 Gender F 2 1 M 1 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52558614

http://stackoverflow.com/q/52552341
has answer: http://stackoverflow.com/a/52552530
has answer: http://stackoverflow.com/a/52553150
tagged with: python
answer count: 4
has title: Python Dataframe: change values of a specified column of a Dataframe
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/52552379
type: Question
accepted answer: http://stackoverflow.com/a/52552379
score: 0
has answer: http://stackoverflow.com/a/52552417
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52552530
has body: I have the following Dataframe object df: A B C 0 0.0 5.0 0.0 1 0.0 6.0 0.0 2 0.0 9.0 0.0 3 0.0 0.0 0.0 4 0.0 2.0 0.0 5 0.0 5.0 0.0 6 6.0 0.0 0.0 7 0.0 0.0 0.0 8 0.0 1.0 0.0 I want to change the values of column 'B': If the value is smaller than 3, than the value should be replaced with 'False'. Otherwise the value should be replaced with 'True'. I tried: df['B'] = df['B'].apply(lambda x: [False if y &lt; 3 else True for y in x]) In this case I get the TypeError: 'float' object is not iterable. When I use it for the whole Dataframe it works though: df = df.apply(lambda x: [False if y &lt; 3 else True for y in x]) Any help will be appreciated.

http://stackoverflow.com/q/52566790
downvote count: 0
tagged with: django-rest-framework
tagged with: postman
has body: I had an issue of understanding the django rest framework doc about many to many relationship and upload files like image, here my code. models.py class Team(models.Model): admin = models.ForeignKey(User, null=True, blank=True, related_name='admin', on_delete=models.CASCADE) name = models.CharField(blank=True, max_length=100) longitude = models.FloatField(blank=True, null=True, max_length=20) latitude = models.FloatField(blank=True, null=True, max_length=20) score = models.IntegerField(blank=True, null=True, default=0) country = models.ForeignKey(Country, blank=True, on_delete=models.DO_NOTHING) city = models.ForeignKey(City, blank=True, on_delete=models.DO_NOTHING) players = models.ManyToManyField(User, blank=True, related_name='players') created = models.DateField(auto_now_add=True) class TeamImage(models.Model): Team = models.ForeignKey(to=Team, null=True, blank=True, on_delete=models.CASCADE) img = models.ImageField(upload_to='team_img/', null=True, blank=True) serializer.py class TeamCreateSerializer(ModelSerializer): # admin = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), # many=False, default=serializers.CurrentUserDefault()) players = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), many=True) country = serializers.PrimaryKeyRelatedField(queryset=Country.objects.all()) city = serializers.PrimaryKeyRelatedField(queryset=City.objects.all()) score = serializers.IntegerField(read_only=True) images = TaskImageSerializer(source='teamimage_set', many=True, read_only=False) # images = TaskImageSerializer(many=True, read_only=True) class Meta: model = Team fields = [ # 'admin', 'name', 'longitude', 'latitude', 'score', 'country', 'city', 'players', 'created', 'images', ] def create(self, validated_data): images_data = self.context.get('view').request.FILES team = Team.objects.create(name=validated_data.get('name', 'no-title'), latitude=validated_data.get('latitude'), longitude=validated_data.get('longitude'), # score=validated_data.ge…
favorite count: 0
tagged with: python-3.x
has title: many to many relationship in django rest frame work
type: UnansweredQuestion
tagged with: django
upvote count: 1
linked to: http://stackoverflow.com/q/28078092
tagged with: python
answer count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92072116

http://stackoverflow.com/q/52547785
has comment: http://stackoverflow.com/comment/92034955
has comment: http://stackoverflow.com/comment/92035430
has title: Python Code for Counting Items Under Specific Criteria?
has answer: http://stackoverflow.com/a/52547923
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52547864
tagged with: python
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has body: I have the following data: Switch1 int1 int2 int3 int4 Switch2 int1 int2 int3 int4 int5 int6 int7 int8 Switch3 int1 int2 int3 int4 int5 int6 int7 Please help with Python 3 code to count all the items under each of the Switches (Switch1, 2, 3). I do have the list of the Switches in a separate file if that makes it easier.
type: Question
has comment: http://stackoverflow.com/comment/92035061
tagged with: counting
has answer: http://stackoverflow.com/a/52547877
score: 0
answer count: 3

http://stackoverflow.com/comment/91868248
type: QuestionComment
comment on: http://stackoverflow.com/q/52463007
has text: @vash_the_stampede On the contrary, it is perfectly clear what `name` and `value` are, but if someone wants to get an answer, they must ask an explicit question. That's how SO works.
type: Comment
score: 0

http://stackoverflow.com/a/74573424
type: Answer
has body: Considering the start of the Fibonacci series with 1 rather than 0. def fib(no_of_elements): elements, start = [], 1 while start &lt;= no_of_elements: if start in [1, 2]: elements.append(1) elif start &gt;= 3: elements.append(elements[start-2]+elements[start-3]) start += 1 return elements, sum(elements) print(fib(8)) Output: ([1, 1, 2, 3, 5, 8, 13, 21], 54)
score: 0
answers question: http://stackoverflow.com/q/52487490

http://stackoverflow.com/a/52504369
upvote count: 1
has comment: http://stackoverflow.com/comment/92123050
downvote count: 1
has comment: http://stackoverflow.com/comment/92075184
has comment: http://stackoverflow.com/comment/91949293
has body: A oneliner would be: ''.join(int(y[0])*y[1] for y in (x.split('(') for x in Input.split(')')[:-1])) It works like this. We take the input, and split on the close paren In [1]: Input ='3(a)2(b)' In [2]: a = Input.split(')')[:-1] In [3]: a Out[3]: ['3(a', '2(b'] This gives us the integer, character pairs we're looking for, but we need to get rid of the open paren, so for each x in a, we split on the open paren to get a two-element list where the first element is the int (as a string still) and the character. You'll see this in b In [4]: b = [x.split('(') for x in a] In [5]: b Out[5]: [['3', 'a'], ['2', 'b']] So for each element in b, we need to cast the first element as an integer with int() and multiply by the character. In [6]: c = [int(y[0])*y[1] for y in b] In [7]: c Out[7]: ['aaa', 'bb'] Now we join on the empty string to combine them into one string with In [8]: ''.join(c) Out[8]: 'aaabb'
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91953840
has comment: http://stackoverflow.com/comment/91951236
type: Answer
answers question: http://stackoverflow.com/q/52504299
score: 0
accepted answer of: http://stackoverflow.com/q/52504299

http://stackoverflow.com/comment/91838502
type: QuestionComment
has text: Anaconda navigator gives you a GUI for what you can otherwise do in the command line of your choice. So in principle you can also use the GUI to install whichever package you need. The important part is to always use the python from the distribution you want to work with - it doesn't help if you installed some package with anaconda but then start the homebrew python.
comment on: http://stackoverflow.com/q/52441950
score: 0
type: Comment

http://stackoverflow.com/a/52489247
accepted answer of: http://stackoverflow.com/q/52489188
score: 0
answers question: http://stackoverflow.com/q/52489188
has body: soup.find() fetches you an entire HTML Tag object from the HTML source. You should use .text param or .contents array of the Tag object to get the text you need. strip() part will consequently remove the \n\t tags from the string. One more tip: I would use soup.find() for this part of the code. find_all() can return an array of objects matching the search condition. As you are searching for an id, you should be expecting to get a single element as a response, thus find() is a more appropriate function. i = "https://www.fbo.gov/index.php?s=opportunity&amp;mode=form&amp;id=50e3e1ec75e2aaa7c4fca7761e4c46a2&amp;tab=core&amp;_cview=1" response = requests.get(i) textfield = response.text soup = BeautifulSoup(textfield, 'lxml') tags = soup.find(attrs={'id':'dnf_class_values_procurement_notice__classification_code__widget'}).text.strip() tags
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/91808192
score: 0
has text: edit: moved to answer
comment on: http://stackoverflow.com/q/52432042
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52497333
upvote count: 6
tagged with: recursion
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52497376
has answer: http://stackoverflow.com/a/52497376
has comment: http://stackoverflow.com/comment/91934958
downvote count: 1
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/52497665
has answer: http://stackoverflow.com/a/52497512
has answer: http://stackoverflow.com/a/52497448
linked to: http://stackoverflow.com/q/17778372
has comment: http://stackoverflow.com/comment/91935178
has comment: http://stackoverflow.com/comment/91935282
has comment: http://stackoverflow.com/comment/91935286
has body: I had an exercise and tried to use parts of code I found here on another person's question, but I found that I needed a part of code that I have no idea why I do. The full code I was using for my function is this: def rreverse(s): if s == "": return s else: return rreverse(s[1:]) + s[0] But I only used the else as a statement, and I didn't get the result I was hoping for. def recur_reverse(x): if x != "": return recur_reverse(x[1:]) + x[0] I got TypeError saying "unsupported operand type(s) for +: 'NoneType' and 'str'." What is the logic behind this first example working fine and the second one throwing an error when the difference is this if statement? and why is my version incorrect? Thank you!
has answer: http://stackoverflow.com/a/52497383
has comment: http://stackoverflow.com/comment/91935226
has comment: http://stackoverflow.com/comment/91935136
favorite count: 0
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/52497665
has title: Why do I need both condition branches for the rreverse function?
has comment: http://stackoverflow.com/comment/91935516
tagged with: python

http://stackoverflow.com/a/52478397
upvote count: 2
score: 2
has body: Since your function defines a as a local variable, it is considered a local variable everywhere in the function. Your first print statement then references the variable before it's initially assigned. Global variables can be confusing (and reasoning about what functions make changes to what globals is extra complicated) and best practice (in most languages) is to simply not use them. A better formulation of your sample might be def test(a): print(a) a = 13 print(a) if __name__ == '__main__': test(17)
answers question: http://stackoverflow.com/q/52478309
downvote count: 0
type: Answer

http://stackoverflow.com/a/52573113
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52548689
has body: You are trying to plot the decision surface, right ? You get this error because you first fit the classifier clf using: clf.fit(iris.data, iris.target) Now, iris.data contains 4 features/variables: print(iris.data.shape) (150, 4) Next, you are trying to predict using data that contain only 2 varaibles/features: Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) print(np.c_[xx.ravel(), yy.ravel()].shape) (61600, 2) How to solve this To solve this use 2 features initially. Example: import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets iris = datasets.load_iris() X = iris.data[:, :2] Y = iris.target h = .02 # step size in the mesh # we create an instance of SVM and fit out data. clf = svm.SVC(kernel='linear') clf.fit(X, Y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k') plt.title('3-Class classification using Support Vector Machine') plt.axis('tight') plt.show()
upvote count: 2
answers question: http://stackoverflow.com/q/52548689
type: AcceptedAnswer

http://stackoverflow.com/a/52579152
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92093664
has comment: http://stackoverflow.com/comment/92093611
has body: Following is one way using a list of pre-assigned colors of your choice and plotting the values of each key in a different color. This way you don't need to define any empty lists x_multi and y_multi. fig = plt.figure() ax = fig.add_subplot(111) colors = ['blue', 'yellow', 'green'] i = 0 for k, v in data_all_bands.items(): x_multi = list(itertools.repeat(int(k[-3:]), len(v))) plt_multi = ax.scatter(x_multi, v, color=colors[i]) i += 1 Way 2 since it is unclear what order of colors you want x_multi = [int(k[-3:]) for k in data_all_bands.keys()] colors = ['blue', 'yellow', 'green', 'red'] for i in range(len(list(data_all_bands.values())[0])): y_multi = [v[i] for v in data_all_bands.values()] plt_multi = ax.scatter(x_multi, y_multi, color=colors[i])
has comment: http://stackoverflow.com/comment/92093703
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92093511
has comment: http://stackoverflow.com/comment/92093680
accepted answer of: http://stackoverflow.com/q/52579114
has comment: http://stackoverflow.com/comment/92093422
has comment: http://stackoverflow.com/comment/92093468
answers question: http://stackoverflow.com/q/52579114
has comment: http://stackoverflow.com/comment/92093630
has comment: http://stackoverflow.com/comment/92093744

http://stackoverflow.com/q/52503628
has comment: http://stackoverflow.com/comment/91947922
type: Question
has comment: http://stackoverflow.com/comment/91967737
score: 0
has comment: http://stackoverflow.com/comment/92058231
has body: I was trying to create a map using OSM and the following code was working fine until I used the add_child method. import folium map=folium.Map(location=[38.58,-99.09],zoom_start=6, tiles= "Mapbox Bright") fg= folium.FeatureGroup(name="My Map") fg.add_child(folium.Marker(location=[38,-99], popup="Hi, I'm a marker", icon=folium.Icon(color='green'))) map.add_child(fg) map.save("Map0.html") Thanks, in advance!!
has comment: http://stackoverflow.com/comment/91951741
type: UnansweredQuestion
tagged with: python
tagged with: folium
has title: Why does add_child method does not work in my geo-mapping code using folium library?
answer count: 0
has comment: http://stackoverflow.com/comment/91949308
tagged with: addchild
linked to: http://stackoverflow.com/q/52063335

http://stackoverflow.com/a/52500118
score: 1
answers question: http://stackoverflow.com/q/52499991
downvote count: 0
has body: You can use string formatting to forget about worrying about integers You still loop over with the number as your parameter and keep the base name the same: base = 'Station' for i in range(1, 21): name = '{}_{}.txt'.format(base, i) print(name) # or do whatever with 'name'
type: Answer
upvote count: 1

http://stackoverflow.com/a/52444735
answers question: http://stackoverflow.com/q/52444657
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52444657
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: This syntax is called list comprehension. It constructs a list by evaluating expression after the opening square bracket for each element of the embedded for loop that meets criteria of the if.

http://stackoverflow.com/q/52501191
has body: I have this loop that generates a combination of numbers and solves to see if they equal a solution. After running a profiler I find that the sum and the comparison to the solution take the longest amount of time. Is this just due to the number of calls to each of them or would there be a way to make this faster? Profiler output: [Name, Call Count, Time(ms), Own Time(ms)] [listcomp, 23114767, 5888, 5888] 25% of total time. [builtin.sums, 23164699, 3097, 3097] 12% of total time Right now I can't think of a way to reduce the search range so trying to save time elsewhere :) Thanks for the help. rangedict = {'f1': range(1850, 1910), 'f2': range(2401, 2482), 'f3': range(5150, 5850)} coefficient = [-3, 1, 1] possiblesolution = 1930 for combination in itertools.product(*rangedict.values()): if solutionfound: break else: currentsolution = sum([x*y for x, y in zip(coefficient, combination)]) if currentsolution == possiblesolution: solutionfound = True dosomething()
has comment: http://stackoverflow.com/comment/91943583
has comment: http://stackoverflow.com/comment/91943435
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52501903
has comment: http://stackoverflow.com/comment/91943424
tagged with: sum
tagged with: comparison
tagged with: list-comprehension
has title: Speeding up iterating over a range and comparing a value
type: Question
has comment: http://stackoverflow.com/comment/91943336
answer count: 2
has comment: http://stackoverflow.com/comment/91943143
has answer: http://stackoverflow.com/a/52501510
accepted answer: http://stackoverflow.com/a/52501510
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52501903
has comment: http://stackoverflow.com/comment/91948645
tagged with: python
has comment: http://stackoverflow.com/comment/91946883
tagged with: python-3.x
score: 1
upvote count: 1

http://stackoverflow.com/comment/92045734
score: 0
type: Comment
type: QuestionComment
has text: Isn't there a masked version of minimum? Either np.ma.minimum or a method?
comment on: http://stackoverflow.com/q/52552951

http://stackoverflow.com/comment/92093375
has text: What I meant is even if you limit it with the method you suggested, when you resize the window, the widget will collapse when you return to the original size. That's the problem I have right now. I did you solution but the problem still present, the only way to solve this is to not allow resize but that's not a fix.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52571217

http://stackoverflow.com/comment/91923113
type: QuestionComment
has text: But if you want to multiply the same matrix N times, would it also work? @PaulPanzer
comment on: http://stackoverflow.com/q/52490184
score: 0
type: Comment

http://stackoverflow.com/a/52581719
has comment: http://stackoverflow.com/comment/92101690
accepted answer of: http://stackoverflow.com/q/52570678
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92101488
score: 1
has comment: http://stackoverflow.com/comment/92101273
has comment: http://stackoverflow.com/comment/92101057
downvote count: 0
has comment: http://stackoverflow.com/comment/92101316
answers question: http://stackoverflow.com/q/52570678
has body: To use both an image and text you must set the compound option. From the canonical documentation: Specifies if the widget should display text and bitmaps/images at the same time, and if so, where the bitmap/image should be placed relative to the text. Must be one of the values none, bottom, top, left, right, or center. For example, the (default) value none specifies that the bitmap or image should (if defined) be displayed instead of the text, the value left specifies that the bitmap or image should be displayed to the left of the text, and the value center specifies that the bitmap or image should be displayed on top of the text. Example: The following example uses this image: The program renders like this when using compound="center": import tkinter as tk image_data = ''' [binary] ''' root = tk.Tk() image = tk.PhotoImage(data=image_data) label = tk.Button(root, image=image, text="Hello, world", compound="center") label.pack(padx=20, pady=20) root.mainloop()
type: AcceptedAnswer

http://stackoverflow.com/comment/91904152
score: 0
type: AnswerComment
has text: @jezrael In any case, I think your answer is the correct one, I just have to double check everything again, thanx for the help.
type: Comment
comment on: http://stackoverflow.com/a/52480389

http://stackoverflow.com/q/52449658
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91900380
answer count: 0
has body: I have a perplexing problem. I have a job that runs and creates an EXCEL file. It appends the date on the end of the file as part of the name. The problem is that the date that is getting appended is not TODAY, but TOMORROW's date. the job is run at 2:00 am daily (CRON). This was "handed" to me because the person who created the program was terminated as part of a company layoff. I know some PYTHON, but I cannot seem to determine why this is happening. Any assistance is greatly appreciated. import datetime today = datetime.datetime.now() #grab data and header names and format data into namedtuples self._entryData = ReaderManager(config.config['path'] + 'data/processing/concur_entries_' + today.strftime('%Y_%m_%d') + '.xlsx').read() self._Entry = namedtuple('Entry', map(lambda s: s[:1].lower() + s[1:], [re.sub(r'[^\w]', '', header) for header in self._entryData[0]])) self._entryData = map(lambda x: self._Entry(*x), self._entryData[1:])
has comment: http://stackoverflow.com/comment/91842487
has comment: http://stackoverflow.com/comment/91842358
has comment: http://stackoverflow.com/comment/91842422
type: Question
has comment: http://stackoverflow.com/comment/91900513
has title: today.strftime('%Y_%m_%d') - not returning current date

http://stackoverflow.com/q/52503141
answer count: 1
has answer: http://stackoverflow.com/a/52503234
has comment: http://stackoverflow.com/comment/91946852
tagged with: series
tagged with: datetime
tagged with: python
has title: How to convert messy column object data using datetime
duplicate of: http://stackoverflow.com/q/41177992
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52503234
type: Question
linked to: http://stackoverflow.com/q/41177992
score: 0
has body: Column name: Timestamp Column dtype: Object Example data: 2017-12-01T00:02:39 import pandas as pd from datetime import datetime df['Timestamp'] = pd.to_datetime(df['Timestamp'], format='%Y/%m/%d %H:%M:%S') ValueError: time data Timestamp doesn't match format specified I'm having problems converting the data within the Timestamp column into a datetime object which I can then manipulate / index by etc. I feel like the 'T' between the date and the time may be causing the issue. Is there a way to add an 'ignore' within datetime format so as to account for the 'T'? Thanks for any help!
tagged with: pandas

http://stackoverflow.com/a/52507868
score: -1
has comment: http://stackoverflow.com/comment/91956491
has body: use the double underscore to traverse the foreign key tree list_display = ('id', 'item', 'item__description', 'item__brand', 'active', 'description')
has comment: http://stackoverflow.com/comment/91972480
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52507723
has comment: http://stackoverflow.com/comment/91956479
upvote count: 0
has comment: http://stackoverflow.com/comment/91956244
has comment: http://stackoverflow.com/comment/91956416

http://stackoverflow.com/q/52510375
linked to: http://stackoverflow.com/q/15870493
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/55157266
type: Question
has body: Based off of https://stackoverflow.com/a/17981327/9614384: import dbus bus = dbus.SessionBus() screensaver = bus.get_object('org.gnome.ScreenSaver', '/') print(bool(screensaver.GetActive())) I'm trying to access the screensaver since this has changed in Ubuntu 18.04, but this code gives me the following error: dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: No such interface '(null)' on object at path /
answer count: 2
possible better answer: http://stackoverflow.com/a/52511189
downvote count: 0
has answer: http://stackoverflow.com/a/52511189
tagged with: ubuntu
favorite count: 0
has title: Screensaver status on Linux via python-dbus using Python3
tagged with: dbus
tagged with: linux
has answer: http://stackoverflow.com/a/55157266
tagged with: python
tagged with: screensaver
upvote count: 2

http://stackoverflow.com/comment/91986125
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52523259
has text: the top while loop was my attempt to get the prompt to run continuously after the user was able to display the results of one valid number. I realize this was defeated by "break" but that was my intention.
type: Comment

http://stackoverflow.com/a/52562911
has comment: http://stackoverflow.com/comment/92064650
downvote count: 0
score: 9
answers question: http://stackoverflow.com/q/52562882
has body: You can use a defaultdict to hold lists, and then just append the values to them. This approach easily extends to an arbitrary number of dictionaries. from collections import defaultdict dd = defaultdict(list) dics = [dic1, dic2] for dic in dics: for key, val in dic.iteritems(): # .items() in Python 3. dd[key].append(val) &gt;&gt;&gt; dict(dd) {'first': [1, 9], 'fourth': [3], 'second': [4, 5], 'third': [8]} All of the keys with a single value are still held within a list, which is probably the best way to go. You could, however, change anything of length one into the actual value, e.g. for key, val in dd.iteritems(): # .items() in Python 3. if len(val) == 1 dd[key] = val[0]
upvote count: 9
has comment: http://stackoverflow.com/comment/92064395
type: Answer

http://stackoverflow.com/q/52569506
has comment: http://stackoverflow.com/comment/92079219
answer count: 1
has comment: http://stackoverflow.com/comment/92075873
has title: How can I make it so the user only has 2 tries to enter valid input?
score: 0
tagged with: reset
tagged with: python
has answer: http://stackoverflow.com/a/52597322
type: UnansweredQuestion
tagged with: loops
type: Question
has body: print('Hello, welcome to your grade calculator.') GradeCount = 0 totalGrades = 0.0 moreStudent = 'y' while moreStudent == 'y' or moreStudent == 'Y': grade = float(input('Enter a grade or a -1 to end: ')) while grade != -1: if grade &gt; 100 or grade &lt; 0: print('Invalid input. Please enter a value between 1 and 100.') grade = float(input('Enter the next grade or -1 to end: ')) continue totalGrades = totalGrades + grade GradeCount = GradeCount + 1 if 90 &lt;= grade &lt;=100: print('You got an A. Thats awesome.') print('Number of grades entered: ',GradeCount) print('Class total: ',totalGrades) elif 80 &lt;= grade &lt; 90: print('You got a B. Good job.') print('Number of grades entered: ',GradeCount) print('Class total: ',totalGrades) elif 70 &lt;= grade &lt; 80: print('You got a C. Thats fine I guess.') print('Number of grades entered: ',GradeCount) print('Class total: ',totalGrades) elif 60 &lt;= grade &lt; 70: print ('You got a D. Not very good.') print('Number of grades entered: ',GradeCount) print('Class total: ',totalGrades) elif grade &lt; 60: print ('You got an F. You fail.') print('Number of grades entered: ',GradeCount) print('Class total: ',totalGrades) grade = float(input('Enter the next grade or -1 to end: ')) moreStudent = input('Are you a new student and ready to enter your grades? y or n: ') print ('Number of grades entered:', GradeCount) print ('Class total:',totalGrades) print ('Class grade average:', format(totalGrades / GradeCount, '.2f')) How can I make it so the user only has 2 tries before the program issues an error message then clears the screen and starts over? Also how can I make it clear the screen every time there is a new user?

http://stackoverflow.com/a/52550208
score: 1
has comment: http://stackoverflow.com/comment/92039374
upvote count: 1
has body: Your question is something like this : You have an array Keywords=["Donut", "Pizza", "Burger"] and you want this in a loop SELECT * FROM items WHERE name LIKE '%Pizza%' OR name LIKE '%Donut%' OR name LIKE '%Burger%';
answers question: http://stackoverflow.com/q/52548751
type: Answer
downvote count: 0

http://stackoverflow.com/q/52514207
tagged with: regex
has comment: http://stackoverflow.com/comment/91968179
score: 2
type: AnsweredQuestion
has title: Understanding how else path in conditional regex python works
has answer: http://stackoverflow.com/a/52514355
tagged with: conditional-statements
linked to: http://stackoverflow.com/q/52494341
type: Question
accepted answer: http://stackoverflow.com/a/52514355
has body: I tried to understand the simple regex: ([+]{1})(?(1)\d{3}|\d{2}). My (very probably wrong) understanding of the regex above is: If there is a single "+" then it should be followed directly by three digits, else (if there is no plus) it should look for two digits. My two test sentences are: 1: "This is a +333 test." 2: "This is a 22 test." See: https://regex101.com/r/oJepMi/1/ The regex finds in 1: "+333", but does not find "22" in sentence 2:. https://docs.python.org/3/library/re.html mentions: (?(id/name)yes-pattern|no-pattern): "Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t." It seems a quiet easy tasks, but I struggle to understand. Can someone please explain how the else path concept works for python? Best regards and many thanks Giovanni
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/91957171
type: QuestionComment
has text: When I execute the command in the VisualStudioCode ide, it goes really well
type: Comment
comment on: http://stackoverflow.com/q/52508350
score: 0

http://stackoverflow.com/comment/91935023
type: Comment
comment on: http://stackoverflow.com/q/52497195
has text: i did that when opened the file i just found 99 ! i need it to save in the file from 1 to 99 what should i do?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91849895
has text: Have you tried .reshape()? Also does the dimension hold any value? It would unwise to slice data that's needed. Not a practice I've seen before.
score: 1
comment on: http://stackoverflow.com/q/52453285
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91980383
type: Comment
type: QuestionComment
has text: Add `>> /tmp/start.sh.log` to both lines in your `start.sh` and check the output. To catch error output do: [how-can-i-redirect-and-append-both-stdout-and-stderr-to-a-file-with-bash](https://stackoverflow.com/questions/876239/how-can-i-redirect-and-append-both-stdout-and-stderr-to-a-file-with-bash)
score: 0
comment on: http://stackoverflow.com/q/52516109

http://stackoverflow.com/q/52475811
has body: Recently, I have found Shannon's book and saw an interesting chapter: http://math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf What I would like to do is to create a function in python such that given a text and given an order, create an other text of length N with k-order approximation of the stochastic properties of a text: def create_text(text, N, n) However, I do not know the algorithm to implement such a function. I suppose that I should count the frequences of the letters, but how do I correlate some letters with others according to a given order? MY ATTEMPT: Counting frequences of one letter it is easy. I started counting frequencies of two letters (I think they are called bigrams). Well, I implemented a recursive function, which seems to work with small tetxs, but with bigger ones it just exceeds the recursion depth. When I tried to change the limit of the recursion depth, then it just hanged. However, with small texts it almost works: # Input: text, letter, (recursive argument), dictionary for bigrams def find_next (txt, x, index_txt, dic): total = txt.count(x) current = txt.find(x, index_txt) if current == -1: return print (current, txt[current+1]) # Set dictionary keys = dic.keys() index_dic = x+txt[current+1] if index_dic in keys: dic[index_dic] += 1/total else: dic[index_dic] = 1/total find_next(txt, x, current+1, dic) This function counts the frequency of appearance of letter x+another one. However, when the text ends in x, the function fails becuase of the out of range. I see that it is in line txt[current+1] the error, but I cannot figure out how to loop back. I mean, when I reach the last letter, go back to the first and end. Example: f = "this is amazing" If I lauch find_next (f, 'g', 0, {}) the function fails at the end, because I don't know how to connect g to the first letter t. I suppose this can be solved. But then, when I calculate the frequencies of unique letters (a, b, c, ...) and then bigrams (ae, ar, at, bg, bj, ...), wh…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52476745
type: Question
answer count: 1
favorite count: 0
tagged with: statistics
score: 0
tagged with: frequency
has comment: http://stackoverflow.com/comment/91893373
has answer: http://stackoverflow.com/a/52476745
tagged with: python
has comment: http://stackoverflow.com/comment/91913087
tagged with: python-3.x
tagged with: information-theory
upvote count: 1
downvote count: 1
has title: INFORMATION THEORY: trying to create new texts using stochastic properties of other texts PYTHON

http://stackoverflow.com/q/52570192
has comment: http://stackoverflow.com/comment/92078765
upvote count: 12
has comment: http://stackoverflow.com/comment/92078800
has comment: http://stackoverflow.com/comment/92077215
favorite count: 0
has answer: http://stackoverflow.com/a/52570258
answer count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/52570258
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92078810
has title: Why does a large for loop with 10 billion iterations take a much longer time to run in Python than in C?
has comment: http://stackoverflow.com/comment/92078865
has comment: http://stackoverflow.com/comment/92077218
has answer: http://stackoverflow.com/a/52570221
downvote count: 2
possible better answer: http://stackoverflow.com/a/52572800
has answer: http://stackoverflow.com/a/52572800
linked to: http://stackoverflow.com/q/13683563
type: AnsweredQuestion
has body: I am currently comparing two loop calculation in Python3 and C. For Python, I have: # Python3 t1 = time.process_time() a = 100234555 b = 22333335 c = 341500 for i in range(1, 10000000001): a = a - (b % 2) b = b - (c % 2) print("Sum is", a+b) t2 = time.process_time() print(t2-t1, "Seconds") Then in C, I do the same thing: #include &lt;stdio.h&gt; int main() { long long a = 100234555; long long b = 22333335; long long c = 341500; for(long long i = 1; i &lt;= 10000000000; i++){ a = a - (b % 2); b = b - (c % 2); } printf("Sum is %lld\n", a+b); return 0; } I timed both the code in Python and in C. The timing for Python is around 3500 seconds while the timing in C (including compilation and execution) only takes around 0.3 seconds. I am wondering how there is such a big difference in timing. The execution was done on a server with 100 GB Ram and enough processing power.
score: 10
tagged with: http://stackoverflow.com/tag/c
type: Question

http://stackoverflow.com/comment/92041957
type: QuestionComment
has text: Share the sample content from the file worldserieswinners.txt
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52551459

http://stackoverflow.com/comment/91951457
comment on: http://stackoverflow.com/q/52505247
type: Comment
type: QuestionComment
score: 1
has text: @krishna serialize it as a list of objects, or use a different format, like json-lines.

http://stackoverflow.com/comment/91950505
comment on: http://stackoverflow.com/q/52505021
type: Comment
type: QuestionComment
score: 1
has text: Have you tried? To me it looks like (after testing).

http://stackoverflow.com/q/52452086
tagged with: deep-learning
has body: Building a model with exponential decay and started to train the model. However, received the error Tensor("ExponentialDecay:0", shape=(), dtype=float32) must be from the same graph as Tensor("dnn/.../embedding_weights/...", ...) Looks like the root cause is that, during the training process, tf tries to create another graph instead of the one used when creating the tensor "ExponentialDecay". But how should this happen? learning_rate = tf.train.exponential_decay(learning_rate=0.1, global_step=tf.train.get_or_create_global_step(), decay_steps=100, decay_rate=0.96) optimizer = tf.train.AdagradOptimizer(learning_rate=learning_rate) estimator = tf.estimator.DNNClassifier( feature_columns=..., hidden_units=..., n_classes=..., model_dir=..., optimizer=optimizer) tf.estimator.train_and_evaluate( estimator=estimator, train_spec=..., eval_spec=...)
tagged with: python
tagged with: dotnetnuke
favorite count: 0
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
upvote count: 2
has title: ExponentialDecay is in a different graph with embedding weight

http://stackoverflow.com/comment/92085708
has text: Maybe there is an option to strip the curly braces via the regex as well and also dump the empty results. If you know how you are welcome to edit my answer with more accurate result
comment on: http://stackoverflow.com/a/52575027
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/67098578
answers question: http://stackoverflow.com/q/52462599
score: 1
upvote count: 1
downvote count: 0
has body: Add cmd to your environment variables That helped me to solve the problem. You need to add the following path to your system variables path. %SystemRoot%\system32 Good luck, I hope it solved your problem.
type: Answer

http://stackoverflow.com/comment/91992589
type: Comment
score: 0
type: AnswerComment
has text: Good advice, but the price calculation code will only work if the user inputs exactly match the dictionary keys.
comment on: http://stackoverflow.com/a/52525970

http://stackoverflow.com/a/52561804
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52560061
has body: Comment:I get back a 400 (bad request) with that accepted answer.. {"status":"FAILURE", "error":[{"code":"5004", "name":"General Error","severity":"3","message":"Error Occurred During the operation", "details":{"5004":"General Error null"}}]} {'Connection': 'keep-alive', 'X-Powered-By': 'Undertow/1', 'Server': 'WildFly/9', 'Content-Length': '172', 'Content-Type': 'application/json;charset=UTF-8', 'X-Application-Context': 'application:9090', 'Date': 'Fri, 28 Sep 2018 17:57:57 GMT'} Please edit your Question and add your Python and requests Version! Tried the following, using a Text file instead of Image: import requests url = 'http://httpbin.org/anything' files = {'file': ('helloworld.txt', open('../test/helloworld.txt', 'rb'), 'text/text')} data = dict(name='barca', country='spain') r = requests.post(url, files=files, data=data) # Print my requests.post header, files and data. r_dict = r.json() for key in r_dict: print('{}:{}'.format(key, r_dict[key])) Response from http://httpbin.org/anything: &lt;Response [200]&gt; My requests.post header, files and data, send back from host. method:POST files:{'file': 'Hello World'} url:http://httpbin.org/anything form:{'name': 'barca', 'country': 'spain'} origin:xx.xx.xx.xx args:{} headers:{'Content-Length': '369', 'Accept': '*/*', 'Content-Type': 'multipart/form-data; boundary=bc3c1927f542430f8166e8f3f27f3c72', 'Host': 'httpbin.org', 'Connection': 'close', 'User-Agent': 'python-requests/2.11.1', 'Accept-Encoding': 'gzip, deflate'} json:None data: Tested with Python:3.4.2 - requests:2.11.1

http://stackoverflow.com/q/52489397
type: AnsweredQuestion
type: Question
has body: I want to merge two csv file vertically. One file contain only strings (first column, first three rows). Second file contain strings and numbers. I can print them out. But have problem to save them row by row to a csv file. Also have problem to keep the data type. (number to number, string to string). The following is the code I used : Method 1: import csv file1 = ("/Users/yingdu/GitHub/20180807/String_.csv") file2 = ("/Users/yingdu/GitHub/20180807/CovertFile_SampleData4.csv") combined_file = ("/Users/yingdu/GitHub/20180807/combined_file.csv") spreadsheet_filenames = [file1,file2] for filename in spreadsheet_filenames: with open(filename, 'r') as csvfile: output = csv.reader(csvfile) for row in output: print row The following is my print results: ['SoftGenetics GeneMarker Trace Data Export'] ['Raw Data'] ['PAT_Ladder_1.fsa'] ['Blue', 'Green', 'Yellow', 'Red', 'Orange'] ['82.45', '97.65', '229.05', '85.25', '44.85'] ['151.08', '167.48', '454.48', '136.68', '59.28'] ['144.45', '161.25', '440.25', '133.65', '60.45'] ['49.5', '65.9', '105.5', '69.1', '44.5'] ['73.25', '109.45', '326.65', '70.85', '26.85'] ['66.58', '97.18', '322.58', '65.38', '24.78'] ['56.95', '77.35', '138.35', '91.95', '61.75'] ['66.45', '79.65', '351.05', '69.25', '35.25'] The following is the code I used to write csv file that save all data to a new csv file. I found that csv file was not created correctly. import csv file1 = ("/Users/yingdu/GitHub/20180807/String_.csv") file2 = ("/Users/yingdu/GitHub/20180807/CovertFile_SampleData4.csv") combined_file = ("/Users/yingdu/GitHub/20180807/combined_file.csv") spreadsheet_filenames = [file1,file2] for filename in spreadsheet_filenames: with open(filename, 'r') as csvfile: output = csv.reader(csvfile) with open(Combined_File, mode='w') as Combined_File: for row in output: print row csv_writer = csv.writer(Combined_File, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(row) Method 2: By using "dataframe.concat". I consider file…
has answer: http://stackoverflow.com/a/52489567
tagged with: python
tagged with: merge
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52489673
has answer: http://stackoverflow.com/a/52489673
accepted answer: http://stackoverflow.com/a/52489567
has title: How to merge two csv file vertically and keep the data formate (number to number, string to string)
tagged with: dataframe
tagged with: export-to-csv

byte
tags question: http://stackoverflow.com/q/52533853
tag name: byte
tags question: http://stackoverflow.com/q/52586790
tags question: http://stackoverflow.com/q/52491640
tags question: http://stackoverflow.com/q/52513772
tags question: http://stackoverflow.com/q/52535980
tags question: http://stackoverflow.com/q/52468714
type: Tag

http://stackoverflow.com/comment/91809315
score: 0
comment on: http://stackoverflow.com/q/52432549
type: Comment
type: QuestionComment
has text: If your image is binary (uint8) and you want to invert it why not just applying a `cv2.bitwise_not(im)` ?

http://stackoverflow.com/comment/92064890
has text: @PeterWood ... what do you mean?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52562511

http://stackoverflow.com/comment/92021383
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52540682
score: 1
has text: maybe it's a dumb question, but have you installed the required packages on ubuntu?

http://stackoverflow.com/comment/91864497
comment on: http://stackoverflow.com/q/52458641
score: 0
type: Comment
has text: Karl - The proc works completely fine when I execute in MS SQL Server, and yes if I narrow down that proc to fewer lines then its running completely fine when called from python. But this doesn't solve my purpose as narrowing down the proc removes essential functionality. Dan - I have added SET NOCOUNT ON already but still I face the same issue
type: QuestionComment

http://stackoverflow.com/comment/91927388
comment on: http://stackoverflow.com/q/52492085
score: 0
type: Comment
type: QuestionComment
has text: have you installed tabula properly.? check with doing `import tabula`. If it throws any error it is not properly installed

http://stackoverflow.com/q/52457024
tagged with: pca
has comment: http://stackoverflow.com/comment/91857135
answer count: 0
downvote count: 0
has title: "Result not set" error while using PCA from scikit-learn
type: Question
has comment: http://stackoverflow.com/comment/91856504
has comment: http://stackoverflow.com/comment/91856832
has comment: http://stackoverflow.com/comment/91856695
upvote count: 2
has body: I have Numpy array with the shape (774743, 135), and when I run pca.fit() with this data, I get Result not set error during the SVD process. What should I fix to remove this error? Here’s the code: scaler = sklearn.preprocessing.StandardScaler() data = scaler.fit_transform(df) pca = sklearn.decomposition.PCA() pca.fit(data) #Error here And the error: ~/anaconda2/envs/py3/lib/python3.6/site-packages/daal/algorithms/svd.py in compute(self) 613 614 def compute(self): --&gt; 615 return _svd.Batch_Float64DefaultDense_compute(self) 616 __swig_destroy__ = _svd.delete_Batch_Float64DefaultDense 617 __del__ = lambda self: None SystemError: Result not set
has comment: http://stackoverflow.com/comment/91856712
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91856908
tagged with: python
score: 2

wifi
tag name: wifi
tags question: http://stackoverflow.com/q/52457112
type: Tag

http://stackoverflow.com/comment/91948692
comment on: http://stackoverflow.com/a/52504053
type: AnswerComment
has text: Aside from the fact that this does not use opencv, nice.
score: 0
type: Comment

http://stackoverflow.com/comment/92039452
comment on: http://stackoverflow.com/q/52550304
has text: This isn't really about sorting.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/122265471
type: AnswerComment
has text: @KevinChristopherHenry, also referring back to the author's situation and your suggested solution, I am still convinced that this will not solve the race condition, since there's no read lock, if 2 threads are evaluating the line of code at the if condition, and there's one ticket left, both threads will pass and move inside the body of the if condition, which is not the intended behavior, the correct way to solve this is for one thread to wait till the other thread has finished the whole transaction, and then it can start evaluating the line at the if condition
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52455168

http://stackoverflow.com/comment/91873209
type: Comment
comment on: http://stackoverflow.com/a/52465749
has text: The main issue i am having is finding the start and end indices
type: AnswerComment
score: 0

http://stackoverflow.com/q/52430892
has comment: http://stackoverflow.com/comment/91805677
tagged with: pandas
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/52431033
has body: I have a Panda's dataframe that is filled as follows: ref_date tag 1/29/2010 1 2/26/2010 3 3/31/2010 4 4/30/2010 4 5/31/2010 1 6/30/2010 3 8/31/2010 1 9/30/2010 4 12/31/2010 2 Note how there are missing months (i.e. 7, 10, 11) in the data. I want to fill in the missing data through a forward filling method so that it looks like this: ref_date tag 1/29/2010 1 2/26/2010 3 3/31/2010 4 4/30/2010 4 5/31/2010 1 6/30/2010 3 7/30/2010 3 8/31/2010 1 9/30/2010 4 10/29/2010 4 11/30/2010 4 12/31/2010 2 The tag of the missing date will have the tag of the previous. All dates represent the last business day of the month. This is what I tried to do: idx = pd.date_range(start='1/29/2010', end='12/31/2010', freq='BM') df.ref_date.index = pd.to_datetime(df.ref_date.index) df = df.reindex(index=[idx], columns=[ref_date], method='ffill') It's giving me the error: TypeError: Cannot compare type 'Timestamp' with type 'int' where pd is pandas and df is the dataframe. I'm new to Pandas Dataframe, so any help would be appreciated!
downvote count: 0
favorite count: 0
type: Question
answer count: 2
tagged with: python
upvote count: 3
has title: Forward filling missing dates into Python Pandas Dataframe
has answer: http://stackoverflow.com/a/52431033
has answer: http://stackoverflow.com/a/52431393
possible better answer: http://stackoverflow.com/a/52431393
tagged with: dataframe

http://stackoverflow.com/comment/91985486
type: Comment
comment on: http://stackoverflow.com/a/52507957
has text: Ah, I see. Just to make sure I am understanding you correctly, when you delete a key, it's actually set to `null` in the entries vector. This is unlike the POC implementation [here](http://code.activestate.com/recipes/578375/), where the value is simply popped from the vector (the list `self.entries` in `__delitem__`)? I assume the motivation is not to incur an O(N) penalty for deletions?
type: AnswerComment
score: 0

http://stackoverflow.com/q/52437232
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/52443085
score: 0
has title: widget in sub-window update with real-time data in tkinter python
tagged with: ttk
tagged with: python-2.7
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52443085
tagged with: tkinter
has body: I've tried using the after/time.sleep to update the treeview, but it is not working with the mainloop. My questions are: How can I update the treeview widget with real-time data? And is there a way that I can change all treeview children simultaneously? (I don't want to delete all children and insert again) Script 1: class mainwindow(tk.Tk): #Initalize main window def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) #use to shift frames .... if __name__ == "__main__": ... app = mainwindow() app.geometry("1920x1080") app.mainloop() Script 2: class Page_one(tk.Frame): def __init__(self, parent, controller): mainframe=tk.Frame.__init__(self, parent) self.controller = controller #treeview widget attached to page_one tree1=Treeviews(...) tree1.place(x=880,y=25) #Question1: How can I update the treeview widget with real-time data? #Question2: is there a way that I can change all treeview children simuteniously? (I dont want to delete all children and insert again) My question is: may someone show me a structure that I could use for updating widgets in my second script.
type: Question
tagged with: treeview

http://stackoverflow.com/q/52459530
score: 3
answer count: 1
downvote count: 0
has body: I'm using pybind11 to provide a Python interface to my C++ library. My library contains enums for which I've provided convenience functions to allow iterating through the enum values and conversion to string; as an example template &lt;typename Enum&gt; struct iter_enum { struct iterator { using value_type = Enum; using difference_type = ptrdiff_t; using reference = const Enum&amp;; using pointer = const Enum*; using iterator_category = std::input_iterator_tag; iterator(Enum value) : cur(value) {} reference operator * () { return cur; } pointer operator -&gt; () { return &amp;cur; } bool operator == (const iterator&amp; other) { return cur == other.cur; } bool operator != (const iterator&amp;other) { return!(*this == other); } iterator&amp; operator ++ () { if (cur != Enum::Unknown) cur = static_cast&lt;Enum&gt;(static_cast&lt;std::underlying_type_t&lt;Enum&gt;&gt;(cur) + 1); return *this; } iterator operator ++ (int) { iterator other = *this; ++(*this); return other; } private: Enum cur; }; iterator begin() { return iterator(static_cast&lt;Enum&gt;(0)); } iterator end() { return iterator(Enum::Unknown); } }; enum class Colour : char { Black = 0, Blue, Red, Yellow, Unknown }; const char* to_string(Colour colour) { switch (colour) { case Colour::Black: return "Black"; case Colour::Blue: return "Blue"; case Colour::Red: return "Red"; case Colour::Yellow: return "Yellow"; default: return "Unknown"; } } int main() { for (auto colour : iter_enum&lt;Colour&gt;()) std::cout &lt;&lt; to_string(colour) &lt;&lt; '\n'; } When porting such code using pybind11 I am currently defining the iterator as a static member function, pybind11::enum_&lt;Colour&gt;(m, "Colour") .value("Black", Colour::Black) // add other values and __str__ .def_static("iter", []() { iter_enum&lt;Colour&gt; i; return pybind11::make_iterator(i.begin(), i.end(); }); however I would like to be able to on the Python side write something along the lines of for c in Colour: print("Colour") as I would for an enum …
favorite count: 0
tagged with: python
tagged with: c++
upvote count: 3
type: UnansweredQuestion
has title: pybind11 emulate python Enum behaviour
has answer: http://stackoverflow.com/a/66679059
type: Question
tagged with: enums
tagged with: pybind11

http://stackoverflow.com/q/52445676
answer count: 1
has title: Python Regular Expression - Replace String Based Repeated Patterns
tagged with: pattern-matching
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: I want to transform the string L^2 M T^-1 to L^2.M.T^-1. The dot replaces the space (\s) only if it is between two word characters. For example, if the string is 'lbf / s' no replacement will be applied. str1= 'L^2 M T^-1' pattern = re.compile(r'(\w+\s\w+)+') def pattern_match2(m): me = m.group(0).replace(' ', '.') return me pattern.sub(pattern_match2, str1) # this produces L2.MT-1 How can i replace the string with dot (.) by repeated patterns?
has answer: http://stackoverflow.com/a/52445762
accepted answer: http://stackoverflow.com/a/52445762
type: Question
score: 0

http://stackoverflow.com/comment/92058842
comment on: http://stackoverflow.com/q/52560055
has text: Last thing: there are no nested loops in your code - why did you put them in the question title?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92085071
type: AnswerComment
has text: Using `[]` as a default value for parameter `_c` makes subsequent calls to `combinations` incorrect. Try calling `combinations` again with a different input after calling it to see what I mean.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52574285

http://stackoverflow.com/comment/91844315
type: Comment
score: 2
has text: At least this answers my question "Does the amplitude have any singnificance in data space?" with "no".
type: AnswerComment
comment on: http://stackoverflow.com/a/52449999

http://stackoverflow.com/comment/91933018
comment on: http://stackoverflow.com/q/52490607
score: 2
has text: Looks like a weird TF bug. You could submit an issue [here](https://github.com/tensorflow/tensorflow/issues).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92073693
score: 0
type: Comment
has text: @Neb, so I'm a novice at timing my functions. I'm using time.time() with very large lists generated from a loop to test how fast everything is, according to this my filter false method is half as fast as yours however if I only search half the list as suggested do you think they will be on par? Also are my functions "good" in the python sense or are they hard to read? Thanks much!
type: AnswerComment
comment on: http://stackoverflow.com/a/52566934

http://stackoverflow.com/q/52446677
score: -4
has answer: http://stackoverflow.com/a/52922562
has body: I would like to convert a python code with command line argument into windows executable using pyInstaller. I run my python program as follows python myPython 1
type: Question
downvote count: 4
upvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/41570359
tagged with: pyinstaller
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/92754322
has title: Converting Python program with command line argument into executable using PyInstaller
type: UnansweredQuestion

http://stackoverflow.com/comment/92011107
has text: @Mangu, you should post this as an answer.
comment on: http://stackoverflow.com/q/52535386
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52534183
downvote count: 0
upvote count: 2
has body: Expanding on what piy26 mentioned regarding exposing a remote docker port, I think pudb is very apt for the task. I wrote a github repository with a simple example and step by step instructions you can clone and try out https://github.com/isaacbernat/docker-pudb There is more info on this other answer: Running pudb inside docker container
type: Answer
has comment: http://stackoverflow.com/comment/92024280
answers question: http://stackoverflow.com/q/52532802
has comment: http://stackoverflow.com/comment/92042722
score: 2
has comment: http://stackoverflow.com/comment/92251352

http://stackoverflow.com/q/52443488
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91829818
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91830037
upvote count: 1
tagged with: python
has body: I'm trying to catch exception in sub process. My code (see below) works fine if number of workers == number of tasks. But if workers more than tasks as in an example, 2 process that was not started yet will thow same exception but I can't catch it neither in MainProcess nor in sub processes. from multiprocessing import Pool, current_process import time from exceptions import GracefulExit import signal def terminate_handler(signum, frame): print(dir(frame)) if current_process().name == 'MainProcess': # we will not raise error if process # is main because we need to finish all the jobs return raise GracefulExit() def test_func(val): i = 0 try: while True: time.sleep(0.1) i += 1 if i &gt;= 10: return i except GracefulExit: pass return i if __name__ == "__main__": signal.signal( signal.SIGINT, terminate_handler) try: with Pool(5) as p: r = p.map(test_func, [1, 2, 3]) except GracefulExit: pass print(r)
has title: Catch exception in Pool worker that is not started yet
answer count: 1
has answer: http://stackoverflow.com/a/52445092
tagged with: multiprocessing

http://stackoverflow.com/a/52453492
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52453169
type: Answer
has body: You need to check WebSocket (WS) tab:
upvote count: 1
has comment: http://stackoverflow.com/comment/91850793
answers question: http://stackoverflow.com/q/52453169
score: 1

http://stackoverflow.com/q/52565507
has answer: http://stackoverflow.com/a/52565534
tagged with: python
type: AnsweredQuestion
type: Question
has title: can't assign a value to a variable in a @classmethod
answer count: 1
has body: I have a bit of background in Java and used static variables and methods a lot. I am new to python and learning about using @classmethod as a static method. Here is code, import redis class GetClients: r = None @classmethod def connect_r(cls, host, port, db): r = redis.StrictRedis(host=host, port=port, db=db) @classmethod def get_clients(cls, clients_key): return r.smembers(clients_key) My code first create a variable r and then inside a classmethod it assigns it to a redis connection, r = redis.StrictRedis(host=host, port=port, db=db) In the next method get_clients, I am using the value of r to invoke a function on it., but I keep getting the following error NameError: name 'r' is not defined here is how i am using the class, clients = GetClients() clients.connect_r("localhost", 6379, 0) allc = clients.get_clients("clients") can someone please explain why I cannot access r in the 2nd method?
tagged with: class
score: 0
accepted answer: http://stackoverflow.com/a/52565534
tagged with: class-method
linked to: http://stackoverflow.com/q/48880314

http://stackoverflow.com/a/52559858
score: 1
downvote count: 0
type: Answer
has body: You can expand into multiple columns and select the first: df['column1'] = df['column1'].str.split('/', n=1, expand=True)[0].astype(int) print(df['column1']) 0 411 1 589 2 90 Name: 0, dtype: int32
upvote count: 1
answers question: http://stackoverflow.com/q/52559683

http://stackoverflow.com/q/52469491
tagged with: multiprocessing-manager
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/11515944
has comment: http://stackoverflow.com/comment/91883122
tagged with: parallel-processing
answer count: 0
score: 0
has title: multiprocessing.process in python for parallel processes consuming values from shared queue
upvote count: 1
has comment: http://stackoverflow.com/comment/91880895
downvote count: 1
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/91892000
has comment: http://stackoverflow.com/comment/91880951
has comment: http://stackoverflow.com/comment/91883319
has comment: http://stackoverflow.com/comment/91893883
has body: I am trying to utilize python multiprocessing pool to take values from a shared queue and consume in worker processes. import multiprocessing def myTask(queue): while not queue.empty(): value = queue.get() print "Process {} Popped {} from the shared Queue".format(multiprocessing.current_process().pid, value) queue.task_done() def main(): m = multiprocessing.Manager() sharedQueue = m.Queue() sharedQueue.put(2) sharedQueue.put(3) sharedQueue.put(4) sharedQueue.put(5) sharedQueue.put(6) pool = multiprocessing.Pool(processes=3) pool.apply_async(myTask, args=(sharedQueue,)) pool.close() pool.join() if __name__ == '__main__': main() From the output I am getting, I see that only a single process was started that took all values out from queue. How can I spawn multiple processes in parallel that keep on getting values from queue. I do have a max limit on number of processes that may be greater than the queue size. Kindly guide me in this regard. Thanks. PS: This is just an example. The actual task does migration of data from one form to another, and does some heavy lifting operations on data. Update: I did following modifications, and they seem to work, except for the fact that pool.join() blocks main process from exiting even when all child processes exit. pool = multiprocessing.Pool(processes=4) while not sharedQueue.empty(): pool.apply_async(myTask, args=(sharedQueue,)) pool.close() #pool.join() def myTask(queue): value = queue.get() print "Process {} Popped {} from the shared Queue".format(multiprocessing.current_process().pid, value) queue.task_done()
has comment: http://stackoverflow.com/comment/91881722
favorite count: 0

http://stackoverflow.com/a/52498796
has body: m=int(input("enter matrix row size")) n=int(input("enter matrix column size")) Mat1 = [] Mat2 = [] Mat3 = [] for i in range(m): Mat1.append([0]*n) print (Mat1) for j in range(m): Mat2.append([0]*n) print (Mat2) for k in range(m): Mat3.append([0]*n) print (Mat3) for i in range(m): for j in range(n): print ('enter in Matrix 1 row: ',i+1,' column: ',j+1) Mat1[i][j] = int(input()) for k in range(m): for l in range(n): print ('enter in MAtrix 2 row: ',k+1,' column: ',l+1) Mat2[k][l] = int(input()) for p in range (m): for q in range (n): Mat3[p][q]=Mat1[p][q]+Mat2[p][q] #print(Mat1[p][q]+Mat2[p][q])`z print (Mat1) print (Mat2) print (Mat3)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52467934

http://stackoverflow.com/a/52472459
answers question: http://stackoverflow.com/q/52472419
has body: Summary: Because a function like that, has an argument for the item, btw it's equivalent to lambda x: .. maybe you're more familiar with that, so you're sorting values by that function basically direct helper in sort is equivalent to lambda x: helper(x) maybe more familiar, Btw it's not a tuple it's a set because it contains curly-braces and doesn't contain colons So to answer your questions one by one: 1) Where is the actual value of x parameter in the helper(x) being passed? It applies that method to each function and as you know from above, equivalent to lambda x: helper(x). 2) I understand that Python compares 0-to-0 index first, then 1-to-1 index, etc. in the tuple; but not quite sure how the returned tuple being used in comparison in this case. Well, because you're returning the value in the helper function so that's how it's gonna sort by.
score: 0
type: Answer

http://stackoverflow.com/a/52577286
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/92089808
has body: Your logic overcomplicates the problem. You can access the method of a class instance directly: print(kingsguard.pronoun()['them']) # 'he' a_noun = Player.pronoun() will not work as desired because the class needs to know which instance pronoun belongs to. Otherwise, it will not be able to access self.gender.
answers question: http://stackoverflow.com/q/52577249
type: Answer
accepted answer of: http://stackoverflow.com/q/52577249

http://stackoverflow.com/comment/91982948
type: QuestionComment
has text: @ w-m I am running it from the command line by calling convertbook.py and it executes without error
score: 0
comment on: http://stackoverflow.com/q/52521594
type: Comment

http://stackoverflow.com/comment/92024655
comment on: http://stackoverflow.com/q/52542344
has text: can you give us a sample of the dataframes you're using?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52479094
has comment: http://stackoverflow.com/comment/91903171
has comment: http://stackoverflow.com/comment/91902044
has comment: http://stackoverflow.com/comment/91905785
score: 0
has body: The source you generate is not a vector. In order to be one, it should have its fourth coordinate equal to zero. You could generate valid ones with: source = np.append(np.random.randint(1, 20, size=3), 0).reshape(4, 1) Note that your code can't be tested as you pasted it in your question: for example, vec = vec.reshape(3, 1) in get_transformation uses vec that hasn't been defined anywhere before...
has comment: http://stackoverflow.com/comment/91899412
answers question: http://stackoverflow.com/q/52478416
type: Answer

http://stackoverflow.com/comment/92049927
comment on: http://stackoverflow.com/q/52554798
has text: @Scheff I converted to double just to check. All the numbers are still the same.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52508728
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/12201577
tagged with: python
tagged with: roi
has answer: http://stackoverflow.com/a/52536820
tagged with: valueerror
has comment: http://stackoverflow.com/comment/91996122
has title: Image analysis with Roipoly. Getting ValueError
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92012948
accepted answer: http://stackoverflow.com/a/52536820
tagged with: image-processing
tagged with: image
has body: I have been trying to use RoiPoly to draw a ROI and find the mean pixel grey value inside a ROI in the image. However, I keep getting the following error: Traceback (most recent call last): File "example.py", line 22, in &lt;module&gt; ROI1.displayMean(img) File "/home/ruven/Downloads/Rupesh images/roipoly.py", line 74, in displayMean mask = self.getMask(currentImage) File "/home/ruven/Downloads/Rupesh images/roipoly.py", line 48, in getMask ny, nx = np.shape(currentImage) ValueError: too many values to unpack This is my code: import pylab as pl from roipoly import roipoly import matplotlib.pyplot as plt import matplotlib.image as mpimg # create image img=mpimg.imread('5.jpg') # show the image pl.imshow(img, interpolation='nearest', cmap="Greys") pl.colorbar() pl.title("left click: line segment right click: close region") # let user draw first ROI ROI1 = roipoly(roicolor='r') #let user draw first ROI # show the image with the first ROI pl.imshow(img, interpolation='nearest', cmap="Greys") pl.colorbar() ROI1.displayROI() ROI1.displayMean(img) ''' # show the image with both ROIs and their mean values pl.imshow(img, interpolation='nearest', cmap="Greys") pl.colorbar() ROI1.displayMean(img) pl.title('The ROI') pl.show() ''' # show ROI masks pl.imshow(ROI1.getMask(img), interpolation='nearest', cmap="Greys") pl.title('ROI masks of ROI') pl.show() And this is the image:enter image description here This is the ROI: I am also open to other methods of using an ROI to find the mean pixel grey value
has comment: http://stackoverflow.com/comment/91983890
type: Question

http://stackoverflow.com/q/52577968
type: UnansweredQuestion
tagged with: python
has title: Python method: How to accept a single object or a collection as parameter?
has body: I'm wondering why I cannot find any solution to this by googling: I want to write a python function which can accept either a single object or any collection of the same type. My idea is to wrap a list around the parameter if it is a single instance, like so: def postprocess(results): """ An arbitrary function that takes a list or single object and behaves smart depending on that. """ if not is_collection(results): # &lt;-- How to implement this?? results = [results] for result in results: # do processing magic print(result) # to be called like one of those: postprocess(result1) # single object postprocess([result1, result2]) # a list postprocess((result1, result2)) # a tuple What is the best/most pythonic way to implement is_collection()? (Might it bring problems, if result is an iterable type itself? I could do if type(results) is not list:, but I explicitly want to allow any kind of iterable collection not only list.
duplicate of: http://stackoverflow.com/q/998938
answer count: 0
has comment: http://stackoverflow.com/comment/92091097
type: Question
has comment: http://stackoverflow.com/comment/92091098
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92091243
has comment: http://stackoverflow.com/comment/92091238
favorite count: 0

http://stackoverflow.com/comment/91917877
score: 0
type: QuestionComment
has text: The [mcve] is literally right there in the question.
type: Comment
comment on: http://stackoverflow.com/q/52471756

http://stackoverflow.com/comment/126263601
type: AnswerComment
comment on: http://stackoverflow.com/a/54518924
has text: simple great solution
type: Comment
score: 0

http://stackoverflow.com/a/61124973
score: 0
answers question: http://stackoverflow.com/q/52434701
type: Answer
has body: congig.gin import use_gin my_other_func.a = -2.9 my_other_func.b = 9.3 # Comments! my_other_func.c = 'Oh, Dear.' test.py import gin gin.parse_config_file('config.gin') import use_gin print(use_gin.my_other_func()) use_gin.py import gin @gin.configurable def my_other_func(a, b, c): return a, b, c

http://stackoverflow.com/q/52531262
tagged with: floating-point
has answer: http://stackoverflow.com/a/60026172
has answer: http://stackoverflow.com/a/52531330
has answer: http://stackoverflow.com/a/52531474
has body: I had written the following function in which values of x,y were passed: def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" Now when I called check(1.00000000000000001, 1.0000000000000002) it was printing: &lt;type 'float'&gt; &lt;type 'float'&gt; 1.0 1.0 Now from the print statements of variables x &amp; y, it was hard for me to debug why x != y (though both were printing same values). Though I resolved it by printing x - y which gave me the difference but is there any way to modify print statement so that to know why x!=y in this particular use case without using any external print libraries and subtraction solution.
upvote count: 15
has comment: http://stackoverflow.com/comment/106140168
downvote count: 0
type: UnansweredQuestion
has title: How to print full precision of floating numbers
tagged with: python-2.7
tagged with: python
has comment: http://stackoverflow.com/comment/92001884
answer count: 4
favorite count: 0
score: 15
type: Question
has answer: http://stackoverflow.com/a/61922605
linked to: http://stackoverflow.com/q/8568233
has comment: http://stackoverflow.com/comment/121083285
linked to: http://stackoverflow.com/q/25898733
has comment: http://stackoverflow.com/comment/106140020

http://stackoverflow.com/comment/92058116
score: 1
has text: Have you considered the case of the $ is not valid in Python? They must have equivalents implemented. Please look harder before asking question.
comment on: http://stackoverflow.com/q/52559576
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52503465
tagged with: python
answer count: 0
score: 0
type: Question
has title: Command to make files download instead of being displayed
has comment: http://stackoverflow.com/comment/91947655
has comment: http://stackoverflow.com/comment/91947955
has comment: http://stackoverflow.com/comment/92078436
has comment: http://stackoverflow.com/comment/92077867
linked to: http://stackoverflow.com/q/7243750
has body: I use the following &lt;meta&gt; tag to download a file but some files like pdf are being viewed instead of getting download. &lt;meta http-equiv="REFRESH" content="5;{{ filepath }}"&gt; How can I alter this statement to make ALL the files download? And if I was to use a python/bottle framework command to have the same functionality what that command would be e.g. static_file()
has comment: http://stackoverflow.com/comment/91947719
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/52580625
has answer: http://stackoverflow.com/a/52580813
tagged with: network-programming
accepted answer: http://stackoverflow.com/a/52580813
score: 0
has body: I am implementing this example for using select in a simple echo server. Everything works fine, the client sends the message, receives the echo and disconnects. This is the code I used for the client: import socket ECHOER_PORT = 10000 if __name__ == '__main__': sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockfd.connect(('localhost', ECHOER_PORT)) msg = input('Message: ').encode() sockfd.send(msg) response = sockfd.recv(len(msg)) print('Response: {}'.format(response)) sockfd.close() The issue is with the server (full gist code is here), after sending the echo, select is called again one more time and the current client (which received the echo and disconnected) is returned from select as both readable and writable. I understand why it's returned as readable, since according to the article: A readable socket without data available is from a client that has disconnected, and the stream is ready to be closed. But my question is why does return as writable also?
answer count: 1
tagged with: sockets
tagged with: python
type: AnsweredQuestion
tagged with: select
has title: Why is `select()` returning a client as writable when the client has disconnected?
type: Question

http://stackoverflow.com/a/52572300
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/52553925
has body: The short answer is that converting the Dataset to a DataFrame before dropping NaNs is exactly the right solution. One of the key differences between a pandas DataFrame with a MultiIndex and an xarray Dataset is that some index elements (time/lat/lon combinations) can be dropped in a MultiIndex without dropping all instances of the time, lat, or lon with a NaN. On the other hand, the DataArray models each dimension (time, lat, and lon) as orthogonal, meaning NaNs cannot be dropped without dropping an entire slice of the array. This is a core feature of the xarray data model. As an example, here is a small dataset that matches the structure of your data: In [1]: import pandas as pd, numpy as np, xarray as xr In [2]: ds = xr.Dataset({ ...: var: xr.DataArray( ...: np.random.random((4, 3, 6)), ...: dims=['time', 'lat', 'lon'], ...: coords=[ ...: pd.date_range('2010-01-01', periods=4, freq='Q'), ...: np.arange(-60, 90, 60), ...: np.arange(-180, 180, 60)]) ...: for var in ['tmp', 'pre']}) ...: We can create a fake land mask which will NaN out specific lat/lon combos for each time period In [3]: land_mask = (np.random.random((1, 3, 6)) &gt; 0.3) In [4]: ds = ds.where(land_mask) In [5]: ds.tmp Out[5]: &lt;xarray.DataArray 'tmp' (time: 4, lat: 3, lon: 6)&gt; array([[[0.020626, 0.937496, nan, 0.052608, 0.266924, 0.361297], [0.299442, 0.524904, 0.447275, 0.277471, nan, 0.595671], [0.541777, 0.279131, nan, 0.282487, nan, nan]], [[0.473278, 0.302622, nan, 0.664146, 0.401243, 0.949998], [0.225176, 0.601039, 0.543229, 0.144694, nan, 0.196285], [0.059406, 0.37001 , nan, 0.867737, nan, nan]], [[0.571011, 0.864374, nan, 0.123406, 0.663951, 0.684302], [0.867234, 0.823417, 0.351692, 0.46665 , nan, 0.215644], [0.425196, 0.777346, nan, 0.332028, nan, nan]], [[0.916069, 0.54719 , nan, 0.11225 , 0.560431, 0.22632 ], [0.605043, 0.991989, 0.880175, 0.3623 , nan, 0.629986], [0.222462, 0.698494, nan, 0.56983 , nan, nan]]]) Coordinates: * time (time) datetime64[ns] 2010-03-31 2010-06-30 2010-09…
upvote count: 7
type: Answer

http://stackoverflow.com/a/52468293
has body: This would do you can compare the key's value to the min of the values worst = [i for i in car_dict if car_dict[i] == min(car_dict.values())]
type: Answer
has comment: http://stackoverflow.com/comment/91878369
has comment: http://stackoverflow.com/comment/91878845
has comment: http://stackoverflow.com/comment/91878360
answers question: http://stackoverflow.com/q/52468270
has comment: http://stackoverflow.com/comment/91878569
score: 0
has comment: http://stackoverflow.com/comment/91878818
has comment: http://stackoverflow.com/comment/91878498

http://stackoverflow.com/comment/91939312
has text: @Mornor was you able to train the model.? what is y_train.shape .?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52499274
type: Comment

http://stackoverflow.com/q/52541183
type: Question
has comment: http://stackoverflow.com/comment/92022308
has answer: http://stackoverflow.com/a/52588066
has body: I am working on a python program using Enthought Canopy (for data acquisition). However I have an issue using tkinter when working in the python 3.5 environment. I can not get the values of my radio buttons using the var.get() function. (both defining it as tk.IntVar() when using integers or as tk.StringVar() like in my example code) Also the main loop does not stop when pressing the exit button, the tkinter window closes but the program keeps running. When switching to the python 2.7 environment I don't have these problems. Below is a stripped down version of the code. Thanks in advance for the help import tkinter as tk class GUI: def __init__ (self, master): self.master = master #Defining the root window #Create container frame = tk.Frame(master) #Defining the labels fontName = 'Helvetica 10' self.waveform = tk.StringVar() self.sawtoothRadio = tk.Radiobutton(frame, text='Sawtooth', variable=self.waveform, value="sawtooth") self.triangleRadio = tk.Radiobutton(frame, text='Triangle', variable=self.waveform, value="triangle") self.triangleRadio.select() self.startButton = tk.Button(frame, text="Start", font = fontName, command=self.calibrate) #Structuring the GUI self.sawtoothRadio.grid(row=9, column=0) self.triangleRadio.grid(row=9, column=1) self.startButton.grid(row=10, column=1) frame.pack(side=tk.LEFT) def draw_graph(self, right_frame): #Plotting the graph if self.waveform.get() == "sawtooth": sawtooth = True else: sawtooth = False def calibrate(self): #Plotting the graph if self.waveform.get() == "sawtooth": sawtooth = True else: sawtooth = False root = tk.Tk() newWindow = GUI(root) root.mainloop()
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52588066
tagged with: python
has title: tkinter radiobutton and mainloop not working properly in python3, using Enthought's Canopy
type: AnsweredQuestion
tagged with: tkinter
tagged with: mainloop
has comment: http://stackoverflow.com/comment/92022516

http://stackoverflow.com/comment/92071289
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52566302
has text: please share actual codes, and error messages..

http://stackoverflow.com/a/52486991
has comment: http://stackoverflow.com/comment/91917251
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91915634
has body: You are falling into quote hell due to multiple levels of special char handling, by the multiple shells you're running one inside the other. You can reduce your doom, by avoiding using shell=True so it is one less shell to escape for: p = subprocess.run([ 'sshpass', '-p', 'redhat' 'ssh', '-o', 'ConnectTimeout=6', '-o', 'NumberOfPasswordPrompts=2', '-o', 'StrictHostKeyChecking=no', '-tt', 'ricky@192.168.0.50' """sudo -S zless /var/log/messages* | grep '^Sep 9' | awk ' \$3 &gt; "09:30" &amp;&amp; \$3 &lt; "23:50" '""" ], input='redhat\n', stdout=subprocess.PIPE) out4 = p.stdout
has comment: http://stackoverflow.com/comment/91917243
has comment: http://stackoverflow.com/comment/91917709
type: Answer
has comment: http://stackoverflow.com/comment/91926705
has comment: http://stackoverflow.com/comment/91916390
has comment: http://stackoverflow.com/comment/91915962
has comment: http://stackoverflow.com/comment/91915579
has comment: http://stackoverflow.com/comment/91915421
has comment: http://stackoverflow.com/comment/91917570
has comment: http://stackoverflow.com/comment/91916221
accepted answer of: http://stackoverflow.com/q/52486851
score: 0
answers question: http://stackoverflow.com/q/52486851

http://stackoverflow.com/q/52506814
score: 0
has answer: http://stackoverflow.com/a/52506938
tagged with: python
has comment: http://stackoverflow.com/comment/91954416
has comment: http://stackoverflow.com/comment/91954346
type: UnansweredQuestion
has title: Sort a mongodb query by Int32 field
has body: I have a Mongodb query that is being used in pagination. The pagination works so long as I don't use any sorting or orderby. Can anyone tell me what is the problem with this query? votes is an Int32 column. x = [person for person in mongo.db.users.find({'user': name}).sort("votes", -1)]
has answer: http://stackoverflow.com/a/52510345
has comment: http://stackoverflow.com/comment/91957068
type: Question
tagged with: mongodb
answer count: 2

http://stackoverflow.com/q/52572297
downvote count: 0
score: 1
tagged with: youtube-data-api
tagged with: youtube-api
linked to: http://stackoverflow.com/q/69937867
type: Question
has title: How do I download YouTube subtitles via Python Shell?
has answer: http://stackoverflow.com/a/69291421
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I've been trying to work out how to download YouTube captions via the API but the official instructions are tailored towards command line code whereas I'm trying to do this in Python Shell. Currently I've been following this page to no avail - https://developers.google.com/youtube/v3/docs/captions/list What seems to trip me up is the Storage and args related pieces of code which even after much googling doesn't make any sense to me. See the storage code below: storage = Storage("%s-oauth2.json" % sys.argv[0]) #nowhere on the page does it refer to this oauth2.json file credentials = storage.get() if credentials is None or credentials.invalid: credentials = run_flow(flow, storage, args) #if credentials is none why would storage still be needed as an argument? In the second half of the page, it's all adding arguments to args.parser which seems to be command line stuff that I don't want to use as I'm working from Python Shell. I've also been reading the official page on getting authorization OAuth 2.0 for YouTube API so I can rewrite this code myself but I can't get past this part: https://developers.google.com/api-client-library/python/auth/web-app Step 5: Exchange authorization code for refresh and access tokens After the web server receives the authorization code, it can exchange the authorization code for an access token. On your callback page, use the google-authlibrary to verify the authorization server response. Then, use the flow.fetch_tokenmethod to exchange the authorization code in that response for an access token: state = flask.session['state'] this is error I'm getting from the above code statement: RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. Essentially from lots of digging regarding the Oauth 2.0 process, I think I am unable to get the flow.fetch_token to swap my autho…

http://stackoverflow.com/a/52481271
upvote count: 1
has comment: http://stackoverflow.com/comment/134362110
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52477795
has body: I've done enough experimentation with some command line tools of my own devising to convince me that the problem is the way Python works in this piped context. It doesn't process the data until it gets EOF (because the data fed isn't big enough to fill buffers). So, despite the best efforts of raw_input and attempts to set line buffering before Python is executed, it isn't reading data as soon as lines are available. My test pipeline has 6 processes in a row: timecmd -m -- cat -u | tstamp -f3 | tee /dev/tty | timecmd -m -- pycalc.py | tstamp -f3 | tee $(isodate -c).log The timecmd command reports the start time of the command, runs the command, and reports the exit time (-m for millisecond times). The tstamp -f3 prefixes each line of output with a timestamp (-f3 for millisecond times). Using cat -u does unbuffered output; it reports the lines as they're available; the tee /dev/tty shows the timestamped output on the terminal and feeds it to pycalc.py; the output is again timestamped, and then piped to tee for logging (the combination with isodate -c generates a log file name such as 20180924.072626.log). When I use this, I see clearly that pycalc.py doesn't do a thing until I indicate EOF to the cat -u. $ timecmd -m -- cat -u | tstamp -f3 | tee /dev/tty | timecmd -m -- pycalc.py | > tstamp -f3 | tee $(isodate -c).log 2018-09-24 07:29:06.419 [PID 44960] cat -u 2018-09-24 07:29:06.419 [PID 44961] pycalc.py dude 2018-09-24 07:29:09.274: dude how 2018-09-24 07:29:10.819: how are 2018-09-24 07:29:12.349: are you 2018-09-24 07:29:16.540: you 2018-09-24 07:29:26.205 [PID 44960; status 0x0000] - 19.786s 2018-09-24 07:29:26.209 [PID 44961; status 0x0000] - 19.789s 2018-09-24 07:29:26.208: MjAxOC0wOS0yNCAwNzoyOTowOS4yNzQ6IGR1ZGU= 2018-09-24 07:29:26.209: 2018-09-24 07:29:26.209: MjAxOC0wOS0yNCAwNzoyOToxMC44MTk6IGhvdw== 2018-09-24 07:29:26.209: 2018-09-24 07:29:26.209: MjAxOC0wOS0yNCAwNzoyOToxMi4zNDk6IGFyZQ== 2018-09-24 07:29:26.209: 2018-09-24 07:29:26.209: MjAxOC0wOS0yNCAwNz…
answers question: http://stackoverflow.com/q/52477795
type: Answer
score: 1

http://stackoverflow.com/q/52513752
has body: I would like to get help regarding Crontab on Centos 7. I Need to create the scheduler to run python script (which have 2-5 addition import in the same folder) by using Crontabs Currently, my crontab looks like this I have PATH = /srv/git/XXX 30 * * * * cd $PATH/XXX/XXXX python $PATH/XXX/XXXX/upload.py I have tried to use a path to the python folder and so on, nothing works. Then I found that the best way is to use .sh files. WHAT I NEED: Currently, I'm looking to for the best way to run crontab scheduler, for python script(which have an extra import in the same folder) with PROD and DEV variables for future testings. Any better way instead of .sh files? and is .sh is the best way, what if the clean way to write them?
tagged with: centos7
upvote count: 1
has answer: http://stackoverflow.com/a/52513825
type: Question
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52513825
answer count: 1
downvote count: 0
tagged with: scheduler
favorite count: 0
has title: Crontab (Centos7) with Python Files
tagged with: cron
tagged with: python

http://stackoverflow.com/comment/91937940
type: Comment
has text: I have checked by printing the filenames and they are all correct and they do exists as `os.path.exist` is shown. Latin names appear correctly while for e.g. a greek filanem appears in the browser when i try to print it as `ÎÎ¹Î¿Î³ÏÎ±ÏÎ¹ÎºÏ - ÎÎ¯ÎºÎ¿Ï.docx`
comment on: http://stackoverflow.com/a/52498288
type: AnswerComment
score: 0

http://stackoverflow.com/a/52433085
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52433049
score: 2
downvote count: 0
has body: Use loc and duplicated with the argument keep='last': df.loc[df.duplicated(subset='col1',keep='last'), 'col2'] = 0 &gt;&gt;&gt; df col1 col2 0 a 0 1 a 0 2 a 30 3 b 0 4 b 20 5 c 10 6 d 0 7 d 0 8 d 30

http://stackoverflow.com/q/52461091
has comment: http://stackoverflow.com/comment/91864298
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91864338
answer count: 0
score: 1
has title: KeyError at /skye/ u'\u201c'
type: Question
downvote count: 0
tagged with: database
has body: This happens When I post a post with so much content on my blog. I am using postgresql database. I want to know how to tackle the problem. This my post_detail.html {% extends "base.html" %} {% load urlify %} {% load crispy_forms_tags %} {% block head_title %} {{ instance.title }} | {{ block.super }} {% endblock head_title %} {% block post_detail_link %} {{ instance.title }} {% endblock %} {% block content %} {% if instance.image %} {% endif %} {{ title }} {% if instance.draft %}Draft {% endif %}{{ instance.publish }} {% if instance.user.get_full_name %} Author: {{ instance.user.get_full_name }} {% endif %} <!-- {% if instance.|time:"i" <= "01" %} < 1 minute {% else %}{{ instance.read_time|time:"i" }} minutes {% endif %} --> Please enable JavaScript to view the comments powered by Disqus. <!--div> Comments {% if request.user.is_authenticated %} {% csrf_token %} {% else %} You must login to comment {% endif %} {% for comment in comments %} {{ comment.content }} via {{ comment.user }} | ago | {% if comment.children.count > 0 %}{{ comment.children.count }} Comment{% if comment.children.count > 1 %}s{% endif %} | {% endif %} Reply | Thread {% for child_comment in comment.children %} {{ child_comment.content }} via {{ child_comment.user }} | ago {% endfor %} {% if request.user.is_authenticated %} {% csrf_token %} {% else %} You must login to comment {% endif %} {% endfor %} </div--> <!--div> </div--> {% endblock content %} How can I solve this? my models.py from __future__ import unicode_literals from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save from django.utils import timezone from django.utils.safestring import mark_safe from django.utils.text import slugify …
tagged with: postgresql
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/52463012
type: Answer
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52462931
has body: Give this a shot: from django.db.models import Sum Countries.objects.aggregate(total_population=Sum('Population')) More info on aggregation here
score: 4
answers question: http://stackoverflow.com/q/52462931

http://stackoverflow.com/q/52538464
answer count: 1
has answer: http://stackoverflow.com/a/52538748
has comment: http://stackoverflow.com/comment/92016348
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92017479
accepted answer: http://stackoverflow.com/a/52538748
type: Question
score: 0
has title: Python Error Import Class another directory
has body: I have structure project python MyProject +Classes -stage_competition.py main.py Executing Python (main.py) - Show error "ModuleNotFoundError("No module named 'Classes'",)" I tried import direct, but is not working too, always showing same error from Classes.stage_competition import Stage_competition item = Stage_competition("field1", "field2", "field3" , "field4") Create class Stage_competition class Stage_competition(object): """description of class""" def __init__(self, type_competition, datalake, competition ,hour): self.type_competition = type_competition self.datalake = datalake self.competition = competition self.hour = hour def settype_competition(self, type_competition): self.type_competition = type_competition def setdatalake(self, datalake): self.datalake = datalake def getcompetition(self): return self.competition def gethour(self): return self.hour

http://stackoverflow.com/q/52441692
has answer: http://stackoverflow.com/a/52443133
score: 0
tagged with: json-rpc
answer count: 1
has comment: http://stackoverflow.com/comment/91826213
type: UnansweredQuestion
tagged with: python
has title: Json-rpc 2.0 - How to extract data
tagged with: http://stackoverflow.com/tag/json
has body: I am trying to extract data from an in-house project(http:\192.168.1.15:8082). It uses json-rpc 2.0. At first, I tried using beautilsoup to retrieve the information since it was being displayed on the screen, but that does not work, all I get is a bunch o function code. I am not familiar with json-rpc. Any help is welcome. The REPONSE data printed on the website look like this: RESPONSE: {"jsonrpc":"2.0","result":[{"uri":"Geometry","time":1537525006,"geo":{"type":"characteristic","id":125,"information2":{"type":"Point","Weight":[15.362154,196.623546]} How do I retrieve this information? Thank you all, Nick,
type: Question

http://stackoverflow.com/q/52530800
tagged with: tensorflow
has title: How to use SHAP KernelExplainer with Tensorflow DNNClassifier
type: Question
score: 0
answer count: 1
has body: Encounter a question while working on TF canned model with SHAP, for instant DNNClassifier. What parameter could I use in model since canned DNNClassifier doesn't support predict_proba? explainer = shap.KernelExplainer(model, data, link) model : function or iml.Model User supplied function that takes a matrix of samples (# samples x # features) and computes the output of the model for those samples. The output can be a vector (# samples) or a matrix (# samples x # model outputs). classifier = tf.estimator.DNNClassifier(hidden_units=[1024, 512, 256], feature_columns=feature_columns, model_dir='/tmp/stack/All', n_classes=2, optimizer='Adagrad', config=tf.estimator.RunConfig().replace(save_summary_steps=2) ) predictions = classifier.predict(input_fn=lambda: eval_input_fn(test_x, labels=None, batch_size=400), predict_keys="probability") explainer = shap.KernelExplainer(predictions, test_x) In short, what it expects in shap.KernelExplainer model parameter? A right thing to replace "predictions" in above.
has answer: http://stackoverflow.com/a/52550596
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/91864459
type: Comment
has text: I really wouldn't try and run the web server via jupyter. It's built for data analysis, there could be all sorts of quirks. The fact that it uses ipython could lead to memory issues too.
type: QuestionComment
comment on: http://stackoverflow.com/q/52457582
score: 1

http://stackoverflow.com/q/52481492
has answer: http://stackoverflow.com/a/52481555
has comment: http://stackoverflow.com/comment/91904476
has answer: http://stackoverflow.com/a/52481672
type: Question
has title: How to remove the first and last portion of a string in Python?
has comment: http://stackoverflow.com/comment/91904456
score: 0
has answer: http://stackoverflow.com/a/52481663
possible better answer: http://stackoverflow.com/a/52481738
has answer: http://stackoverflow.com/a/52481738
tagged with: python
accepted answer: http://stackoverflow.com/a/52481555
answer count: 4
type: AnsweredQuestion
has body: How can i cut from such a string (json) everything before and including the first [ and everything behind and including the last ] with Python? { "Customers": [ { "cID": "w2-502952", "soldToId": "34124" }, ... ... ], "status": { "success": true, "message": "Customers: 560", "ErrorCode": "" } } I want to have at least only { "cID" : "w2-502952", "soldToId" : "34124", } ... ...

http://stackoverflow.com/a/53018744
has comment: http://stackoverflow.com/comment/102506587
has body: After doing multiple tests...yes you do need a parameter server
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52458563
answers question: http://stackoverflow.com/q/52458563

multi-index
tags question: http://stackoverflow.com/q/52451146
tags question: http://stackoverflow.com/q/52435825
type: Tag
tags question: http://stackoverflow.com/q/52482768
tags question: http://stackoverflow.com/q/52497554
tags question: http://stackoverflow.com/q/52440134
tags question: http://stackoverflow.com/q/52457288
tags question: http://stackoverflow.com/q/52447748
tag name: multi-index
tags question: http://stackoverflow.com/q/52470344
tags question: http://stackoverflow.com/q/52566616
tags question: http://stackoverflow.com/q/52488252
tags question: http://stackoverflow.com/q/52504709
tags question: http://stackoverflow.com/q/52566588

http://stackoverflow.com/q/52533429
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52533563
downvote count: 0
has comment: http://stackoverflow.com/comment/92007616
favorite count: 0
has comment: http://stackoverflow.com/comment/92006047
has answer: http://stackoverflow.com/a/52533563
has comment: http://stackoverflow.com/comment/92006419
tagged with: python
possible better answer: http://stackoverflow.com/a/52533498
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92006473
upvote count: 3
has body: How do I remove non-alphabet from the values in the dataframe? I only managed to convert all to lower case def doubleAwardList(self): dfwinList = pd.DataFrame() dfloseList = pd.DataFrame() dfwonandLost = pd.DataFrame() #self.dfWIN... and self.dfLOSE... is just the function used to call the files chosen by user groupby_name= self.dfWIN.groupby("name") groupby_nameList= self.dfLOSE.groupby("name _List") list4 = [] list5 = [] notAwarded = "na" for x, group in groupby_name: if x != notAwarded: list4.append(str.lower(str(x))) dfwinList= pd.DataFrame(list4) for x, group in groupby_nameList: list5.append(str.lower(str(x))) dfloseList = pd.DataFrame(list5) data sample: Basically I mainly need to remove the full stops and hyphens as I will require to compare it to another file but the naming isn't very consistent so i had to remove the non-alphanumeric for much more accurate result creative-3 smart tech pte. ltd. nutritive asia asia's first desired result: creative 3 smart tech pte ltd nutritive asia asia s first
type: Question
score: 3
has title: Removing non-alphanumeric symbols in dataframe
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92006548
has answer: http://stackoverflow.com/a/52533498
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92006488

http://stackoverflow.com/a/52490085
has body: You're examining way more pairs of strings than you need to. You only need to examine consecutive pairs of strings, not all pairs. The information you get by comparing strings 0 and 3 is implied by the 0-1, 1-2, and 2-3 comparisons, and the topological sort can handle it for you. The topological sort should run faster with less extraneous edges in the input, too.
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52489854
answers question: http://stackoverflow.com/q/52489854
type: AcceptedAnswer
upvote count: 3
type: Answer

http://stackoverflow.com/a/52512129
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52511424
has comment: http://stackoverflow.com/comment/91964313
type: AcceptedAnswer
has body: For the sake of the answer let's have your code in a form that others can reproduce the issue: from sklearn import svm from sklearn.model_selection import cross_val_score np.random.seed(42) X = np.random.rand(2000, 2) y = np.random.randint(0,2,2000) C = np.array([1, 10, 100, 1000]) gamma = np.array([1e-3, 1e-4]) avg_rbf_f1 = [] for a in C: for b in gamma: rbf_model = svm.SVC(kernel='rbf',C=a, gamma=b) rbf_scores = cross_val_score(rbf_model, X, y, cv=10, scoring='f1_macro') avg_rbf_f1.append(np.mean(rbf_scores)) best_gamma = gamma[np.argmax(avg_rbf_f1)] best_C = C[np.argmax(avg_rbf_f1)] print('The gamma with the highest accuracy is {}'.format(best_gamma)) print('The C with the highest accuracy is {}'.format(best_C)) And the error itself: IndexError Traceback (most recent call last) &lt;ipython-input-30-84d1adf5e2d9&gt; in &lt;module&gt;() 17 avg_rbf_f1.append(np.mean(rbf_scores)) 18 ---&gt; 19 best_gamma = gamma[np.argmax(avg_rbf_f1)] 20 best_C = C[np.argmax(avg_rbf_f1)] 21 IndexError: index 6 is out of bounds for axis 0 with size 2 Hyperparameter gamma has 2 possible values, while avg_rbf_f1 is a list of 8. In the way you have currently implemented the grid search, there's no way you can get back your best params. Here's how you can modify your code so that it works: from sklearn import svm from sklearn.model_selection import cross_val_score np.random.rand(42) X = np.random.rand(2000, 2) y = np.random.randint(0,2,2000) C = np.array([1, 10, 100, 1000]) gamma = np.array([1e-3, 1e-4]) avg_rbf_f1 = [] search = [] for a in C: for b in gamma: search.append((a,b)) rbf_model = svm.SVC(kernel='rbf',C=a, gamma=b) rbf_scores = cross_val_score(rbf_model, X, y, cv=10, scoring='f1_macro') avg_rbf_f1.append(np.mean(rbf_scores)) best_C, best_gamma = search[np.argmax(avg_rbf_f1)] print('The gamma with the highest accuracy is {}'.format(best_gamma)) print('The C with the highest accuracy is {}'.format(best_C)) It's far from optimal. I simply added search list that collects combinatio…
answers question: http://stackoverflow.com/q/52511424
type: Answer
score: 1

http://stackoverflow.com/comment/92019783
comment on: http://stackoverflow.com/a/52539943
has text: while-loop is bad. `for i in range(len(rest)):dev.append(rest[i])` is better but non-idiomatic. `for i in rest:dev.append(i)` is idiomatic Python. But there's a better way: `dev.extend(rest)`.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/92073841
type: AnswerComment
comment on: http://stackoverflow.com/a/52566934
type: Comment
has text: I'm using time.time() as well. How are you getting time? I mean, where did you positioned the lines of code to get the timing? In my code they are just before and just after the function call. On 10mln elements, both mine and yours get around 0.52s
score: 0

http://stackoverflow.com/comment/91923815
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52491589
has text: Not like del or pop because I don't wont to remove the whole element. just the stuff within them that is equal to /n
type: Comment

http://stackoverflow.com/q/52539871
has title: Write to javascript console from abstracted class in jupyter notebook
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/92020895
answer count: 0
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: javascript
has comment: http://stackoverflow.com/comment/92020309
score: 0
has body: I'm working on a project in Jupyter Notebook that uses a custom class that I'm importing into the notebook. Within this class there's a function that I would like to be able to write to the javascript console. It's impractical for this application to just use python's print(). Using the %%javascript magic won't work because the logging needs to take place within a python function. Is it even possible to write to the javascript console from an imported class? If so, how can I go about it?
tagged with: jupyter

http://stackoverflow.com/a/52470857
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52470712
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52470712
has body: One way from value_counts df.iloc[:,1:].apply(pd.Series.value_counts).fillna(0).T Out[184]: No Yes Attend_x 4.0 0.0 Attend_y 2.0 2.0 Attend_z 2.0 2.0 Or using crosstab after melt m = df.iloc[:,1:].melt() pd.crosstab(m.variable, m.value) value No Yes variable Attend_x 4 0 Attend_y 2 2 Attend_z 2 2
type: Answer

http://stackoverflow.com/q/52531864
has answer: http://stackoverflow.com/a/69382520
has comment: http://stackoverflow.com/comment/92003027
type: Question
tagged with: shellsort
upvote count: 0
has comment: http://stackoverflow.com/comment/92003201
tagged with: sorting
answer count: 3
has title: Why the time complexity for shell sort is nlogn in my data?
tagged with: time-complexity
favorite count: 0
has answer: http://stackoverflow.com/a/52531961
has answer: http://stackoverflow.com/a/52532283
type: UnansweredQuestion
has body: environment: python3.6, Anaconda 5.1, Jupyter notebook, numba. I used a random array generated by Python to measure the time complexity of shell sort, but found that its time complexity is more in line with NlogN. I understand that the time complexity of shell sort is O(n^2), I am confused. Shell sort code: def shell_sort(list): n = len(list) gap = n // 2 while gap &gt; 0: for i in range(gap, n): temp = list[i] j = i while j &gt;= gap and list[j - gap] &gt; temp: list[j] = list[j - gap] j -= gap list[j] = temp gap = gap // 2 return list shell sort time complexity analysis
tagged with: python
downvote count: 1
tagged with: algorithm
score: -1

http://stackoverflow.com/q/52543181
tagged with: python
tagged with: regex
has title: Python - Removing strings that follow a wildcard pattern
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/92026295
has answer: http://stackoverflow.com/a/52543251
has body: Initial Data (String datatype) Los Gatos 50K Las Palmas Canary Islands 25K Roland Garros Seoul 25K Rome Desired Result Los Gatos Las Palmas Canary Islands Roland Garros Seoul Rome I am looking for a way to remove any string pattern that is 2 digits and then a K. But it needs to be able to handle any 2 values before the K. I haven't seen any answers that use a wildcard for the part of the replace. It should be something like this (I know this is not valid) - data.replace("**K", '') Side note - This string will be a column in a dataframe so if there is an easy solution that works with that would be ideal. If not I can iterate through each row and transform it that way.
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92028993
tagged with: wildcard
tagged with: parsing
favorite count: 0
accepted answer: http://stackoverflow.com/a/52543251

http://stackoverflow.com/q/52487716
tagged with: arrays
tagged with: multidimensional-array
has title: Store contents of several files in an array Python
type: Question
tagged with: python
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91916727
has body: I have a directory with a lot of files, structured as n rows x 2 columns. What I'd like to do is to store the contents of these files in a way that the shape of the final array is (nfiles, nrows, 2). Something similar to array = numpy.array([[[1,1], [1,1], [1,1]], [1,1], [1,1], [1,1]]]) but how to do it for several files? I've tried fnames = glob.glob(/path/to/directory/"*.txt") final_array = [numpy.genfromtxt(fname) for fname in fnames] but the final shape is (nfiles,), and numpy.reshapedidn't work. With import pandas as pd df_list = [pd.read_csv(filename, header=None, sep=" ") for filename in fnames] comb = pd.concat(df_list, ignore_index=True, sort=False) I can create an array with all file contents (presumably in order) in 2 columns. Is there any way to divide this in parts to reshape (nrows is the same for every file)? Note that I don't want separate arrays for each file, but a single array Thank you all for the help
has answer: http://stackoverflow.com/a/52487898
type: UnansweredQuestion

http://stackoverflow.com/a/52446727
has body: Both will iterate over a generator, without loading the whole file into memory, but the iter() version is demonstrating the use of the second argument of iter(), "sentinel". From the docs: if the value returned is equal to sentinel, StopIteration will be raised So this code will read from the file, until a line equals '' and then stop. This is a strange example, as all lines in the file will have a newline on the end, so this will only trigger at the end of the file anyway (if at all).
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52446415
has comment: http://stackoverflow.com/comment/91836465
score: 4
has comment: http://stackoverflow.com/comment/91836353
type: Answer

http://stackoverflow.com/comment/109412772
comment on: http://stackoverflow.com/a/52615705
has text: @user4815162342 That is true, but i guess it assumes that the problems are known ahead of time and we also know how to deal with them. I was thinking "fail fast" and just stick the job back on the end of the queue and keep going.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52579058
accepted answer of: http://stackoverflow.com/q/52578713
type: AcceptedAnswer
score: 0
type: Answer
has body: This seems to be a CORS issue. When a web page loaded from server A is sending a request (via XMLHttpRequest) to server B, then we are facing a Cross-Origin Resource Sharing (CORS) scenario. This kind of request has to meet certain requirements (as described at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). Long story short, server B (here example.com) has to provide an extra header in its response: Access-Control-Allow-Origin: http://server-a-domain.com The following is OK, too. By the way, that's what your example server regres.in returns. Access-Control-Allow-Origin: * If you are using Flask, then look into Flask-CORS that seems to provide a generic solution: https://flask-cors.readthedocs.io/en/latest/
answers question: http://stackoverflow.com/q/52578713

http://stackoverflow.com/q/52568213
downvote count: 2
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52568314
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/52568314
type: Question
has body: Last question about this topic. I didn't add the output as its not the issue rather then passing of the output. Basically the final output of each function is a list. I am running into a problem. So this is the code I have def mean(studentp_file): li = [] for line in studentp_file: nameless = line[1:14] for l in range(len(nameless)): answer = sum(nameless)/len(nameless) li.append(answer) li.insert(0,"Needie Seagoon") li.insert(2,"Eccles") li.insert(4,"Bluebottle") li.insert(6,"Henry Crun") li.insert(8,"Minnie Bannister") li.insert(10,"Hercules Grytpype-Thynne") li.insert(12,"Count Jim Moriarty") li.insert(14, "Major Dennis Bloodnok") mean_li = li return mean_li passing_file = normalise("DB.csv.", "units.csv") mean(passing_file) """ This function will print out the final mean average percentile for each student over their computer science degree. """ def final(mean_li): ~ wanted to see if the code worked.~ print(mean_li) mean_list = mean(studentp_file) final(mean_list) The problem I am having is passing the variable mean_li into the new function final(). I get the error mean_list = mean(student_file) is not defined? I was able to pass output of another function into the previous function but for some reason I can't do it here. Any help would be great.
score: -2
has comment: http://stackoverflow.com/comment/92073404
has comment: http://stackoverflow.com/comment/92073550
has title: Output of a function used as an input for another

http://stackoverflow.com/q/52522959
downvote count: 0
has title: Support both encrypted and non encrypted configuration with aumbry
score: 8
favorite count: 0
possible better answer: http://stackoverflow.com/a/52689432
upvote count: 8
has answer: http://stackoverflow.com/a/52689432
tagged with: aumbry
tagged with: python
tagged with: python-cryptography
type: AnsweredQuestion
has body: We have a python application that loads a config.yml with aumbry. For production purpose we need to encrypt this configuration with fernet, which aumbry can load seamlessly. We want to be able to load both unencrypted and encrypted in a transparent way, for example load unencrypted if found, and if not (production) load encrypted. So far we have implemented this. Encryption import cryptography.Fernet as fn from os.path import split, splitext def _encrypt_file(path, key): with open(path, 'rb') as infile: file_data = infile.read() nc_data= fn(key).encrypt(file_data) infile.close() base_path, filename = split(path) name, _ = splitext(filename) nc_name = "{}.{}".format(name, 'nc') with open(join(base_path, nc_name), 'wb') as outfile: outfile.write(nc_data) outfile.close() Aumbry configuration from aumbry.errors import LoadError def _get_configuration(): return aumbry.load( aumbry.FILE, AppConfig, options={ 'CONFIG_FILE_PATH': "config.yml" } ) def _get_encrypted_configuration(): return aumbry.load( aumbry.FERNET, AppConfig, options={ 'CONFIG_FILE_PATH': "config.nc", 'CONFIG_FILE_FERNET_KEY': 'bZhF6nN4A6fhVBPtru2dG1_6d7i0d_B2FxmsybjtE-g=' } ) def load_config(): """General method to load configuration""" try: return _get_configuration() except LoadError: try: return _get_encrypted_configuration() except LoadError: return None Is there a more elegant way to achieve this behavior?
type: Question
tagged with: configuration
has answer: http://stackoverflow.com/a/52684351
answer count: 2
accepted answer: http://stackoverflow.com/a/52684351

http://stackoverflow.com/comment/92208340
has text: @LiamHanninen, GIL stands for Global Interpreter Lock, which means only one thread can control the python interpreter at a time. So using `Thread` is guaranteed thread safe, in this case you do not need to pickle `websockect` like in multiprocessing . While, `asyncio` is not guaranteed thread safe (though there is thread-safe method in `asyncio` library).
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52608090

http://stackoverflow.com/q/52494395
possible better answer: http://stackoverflow.com/a/52494554
has body: I try to use the @ in the class method. like this class Dataset: @parse_func def get_next_batch(self): return self.generator.__next__() and the parse function like this: def parse_func(load_batch): def wrapper(**para): batch_files_path, batch_masks_path, batch_label = load_batch(**para) batch_images = [] batch_masks = [] for (file_path, mask_path) in zip(batch_files_path, batch_masks_path): image = cv2.imread(file_path) mask = cv2.imread(mask_path) batch_images.append(image) batch_masks.append(mask) return np.asarray(batch_images, np.float32), np.asarray(batch_masks, np.uint8), batch_label return wrapper However, when I call dataset.get_next_batch(), it will raise a exception as followed. Traceback (most recent call last): TypeError: wrapper() takes exactly 0 arguments (1 given) Do you know why raise this error and any solution? Thank you very much!
accepted answer: http://stackoverflow.com/a/52494669
has comment: http://stackoverflow.com/comment/91929442
has answer: http://stackoverflow.com/a/52494554
score: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91929295
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52494669
has title: Python, How to use the @ in class method
has comment: http://stackoverflow.com/comment/91929440
tagged with: python

http://stackoverflow.com/a/52545427
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92031164
answers question: http://stackoverflow.com/q/52435788
has body: I have also seen this 4.15.0-33-generic is where it first showed up. 4.15.0-32-generic does not have the problem and its not specifically, the ethernet driver since I tried a usb ethernet also to make sure.

http://stackoverflow.com/q/52470310
score: 2
has title: TypeError: expected a character buffer object using .translate
has answer: http://stackoverflow.com/a/52470346
upvote count: 2
tagged with: translate
type: Question
has body: I'm getting the error: TypeError: expected a character buffer object In the line where it says words=user_input_txt.translate(translate_table).lower().split(). I checked the type for the argument user_input_txt and its Type Unicode. I'm not sure what I'm doing wrong and don't quite understand previous postings. If someone could advise on how to fix I would greatly appreciate! def contains_bad_words(user_input_txt): """ remove punctuation from text and make it case-insensitive""" translate_table = dict((ord(char), None) for char in string.punctuation) words = user_input_txt.translate(translate_table).lower().split() for bad_word in blacklist: for word in words: if word == bad_word: return True return False EDIT: I've revised my solution per the recommendation received from Daniel. However, I'm now getting the error: TypeError: maketrans() takes exactly 2 arguments (1 given). Could someone please advise what I'm doing wrong? I read that string.maketrans could take one argument as long as it's a dict. But translate_table is a dictionary no? Please help!! def contains_bad_words(user_input_txt): """ remove punctuation from text and make it case-insensitive""" translate_table = dict((ord(char), None) for char in string.punctuation) translate_table_new = string.maketrans(translate_table) words = user_input_txt.translate(translate_table_new).lower().split() for bad_word in blacklist: for word in words: if word == bad_word: return True return False SECOND EDIT: So i fixed the problem by converting the unicode string to a string, and changing the number of arguments to maketrans. However, I'm still very puzzled why my solution above doesn't work. I read somewhere that it can take 1 argument provided it must be a dictionary, which is clearly what I did. Could someone help explain why the above doesn't work but the below does: def contains_bad_words(user_input_txt): """ remove punctuation from text and make it case-insensitive""" user_typ = user_input_txt.encode() translate_tab…
has comment: http://stackoverflow.com/comment/91888716
has comment: http://stackoverflow.com/comment/91885970
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52471953
answer count: 2
has comment: http://stackoverflow.com/comment/91888593
has comment: http://stackoverflow.com/comment/91885944
downvote count: 0
has comment: http://stackoverflow.com/comment/91888300
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/91888217
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/52463362
score: 1
upvote count: 1
has body: Yes, Python 3.5 introduces type hinting and Pycharm utilizes that. Use def func_name(param: type) -&gt; return_type: Like def func_a(a: list): Note that all type hints are completely optional and ignored by the interpreter. However, Pycharm can potentially help you detect type errors if you use it as a habit.
has comment: http://stackoverflow.com/comment/91868822
has comment: http://stackoverflow.com/comment/91868789
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52463351
answers question: http://stackoverflow.com/q/52463351
type: Answer

http://stackoverflow.com/q/52526137
tagged with: word-cloud
type: Question
has body: I am trying to create a clickable word cloud for which I am starting to apply logic with button. I am able to split the words of text file using regular expressions and create button for each word. But each button's position is shown in a column view. like in the image below: Does tkinter have any function to randomize this location and alter the buttons manually that can give me a look of a clikable word cloud. Here's my working solution: # import the 'tkinter' module import tkinter # import regular expression import re # create a new window window = tkinter.Tk() # set the window title window.title("Commands") # set the window icon window.wm_icon bitmap('Icon.ico') # initially, the button hasn't been pressed presses = 0 # a function that changes the text of the label to a location of the word clicked def locate(): global presses # add code to find the location of the word --------------- # update the label text with the new value of 'presses' ----------- lbl.configure(text=presses) # create a label to display a message lbl = tkinter.Label(window, text=presses) lbl.pack() # looping through the number f words # create a new button, assign a specific text to each button and provide an argument called 'command' # which in this case calls a function called 'callback' with open ('sample.txt','r') as f: f_contents = f.read() # Removing URLs f_contents = re.sub(r'http\S+',"",f_contents) # Removing all the punctuations f_contents = re.sub(r'[^\w\s]', '', f_contents) for word in f_contents.split(): btn = tkinter.Button(window, text=word, command=locate) btn.pack() # draw the window, and start the 'application' window.mainloop() Thanks in advance.
tagged with: python
possible better answer: http://stackoverflow.com/a/52526305
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52526584
has title: How to Randomize the button location in python using tkinter?
tagged with: tkinter
has answer: http://stackoverflow.com/a/52526305
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52526584
type: AnsweredQuestion
tagged with: tkinter-canvas

http://stackoverflow.com/a/52541019
type: Answer
has comment: http://stackoverflow.com/comment/92040287
answers question: http://stackoverflow.com/q/52540185
has comment: http://stackoverflow.com/comment/92040221
has comment: http://stackoverflow.com/comment/92040346
score: 0
has body: You can create a fab script like below and then iterate over the host list you want to run the commands because you can passwd username and password in the script itself so to avoid password invocation: # testCheck.py #!/usr/bin/python2.7 import sys from fabric.api import * env.skip_bad_hosts=True env.command_timeout=160 env.user = 'user_name' env.shell = "/bin/sh -c" env.warn_only = True env.password = 'user_password' def readhost(): env.hosts = [line.strip() for line in sys.stdin.readlines()] def hosts(): with settings(warn_only=True): output=sudo("ls -l /myfolder",shell=False) # cat hostfile.txt| | /usr/local/bin/fab readhost -f testCheck.py hosts -P -z 5 OR supplying password at command line # cat hostfile.txt | /usr/local/bin/fab readhost -f testCheck.py --password=your_pass hosts -P -z 5 --&gt; argument "-P" refers to parallel execution method --&gt; argument "-z" refres to the number of concurrent processes to use in parallel mode exapmle hostfile.txt: server1 server2 server3 server4 Hope this will help.

http://stackoverflow.com/comment/92049131
type: AnswerComment
has text: Thank you again. I put a print after the 'for' and I obtained the good items. but for the 'if' loop it didn't printed the values of the files on the GUI, I obtained just the print command of my 'else'. I think there is maybe a problem with the 'if'. It seems that s and v can't match with the item that we obtain with get().
type: Comment
comment on: http://stackoverflow.com/a/52554395
score: 0

http://stackoverflow.com/comment/92011763
score: 0
type: AnswerComment
has text: Is it going to be easier to color those boxplots using seaborn? Thats the only reason why I have been struggling so much.
type: Comment
comment on: http://stackoverflow.com/a/52536219

http://stackoverflow.com/comment/92242228
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52583498
has text: The segfault happens on the code I provided? Can you either [edit] your question to add the backtrace, or perhaps put it on some service like pastebin and give me a link? I tested it on Windows, so I'm curious what could be the issue.

http://stackoverflow.com/a/52502601
score: 1
downvote count: 0
type: Answer
has body: According to your algorithm, you're just checking the first character of the string. And not the entire string. This block of code has erroneus logic: for k in unique_chars: if unique_chars[k] &gt; 1: return False else: return True You don't need that else condition inside the for loop. Try this instead: def unique_chars_in_string(input_string): unique_chars = {} if input_string == "": return True for letter in input_string: if letter in unique_chars: unique_chars[letter]+=1 else: unique_chars[letter]=1 for k in unique_chars: if unique_chars[k] &gt; 1: return False return True print(unique_chars_in_string('Programming')) So, if any character has more than 1 count, your code will return false else it will return true. Also, check Jean-François Fabre's answer to this problem, it is a short and sweet Pythonic implementation. Happy Coding! :)
answers question: http://stackoverflow.com/q/52502508
upvote count: 1

http://stackoverflow.com/comment/91923483
comment on: http://stackoverflow.com/q/52490184
type: QuestionComment
type: Comment
score: 0
has text: Yes, to verify, compare `M@M@M@M@M` to `functools.reduce(operator.matmul, 5*[M])`.

http://stackoverflow.com/q/52521053
type: Question
has comment: http://stackoverflow.com/comment/91981805
has body: In java you can use interfaces to restrict access to class methods ex: public interface InterFace { public int method1(); } public class Example implements InterFace{ public int method1(){...} public int method2(){...} } which means that any method which takes an InterFace as input wouldn't be able to access method2 (except with casting) Is there a way to get this sort of behavior in python (by for example encapsulation) In other words is there a pythonic way to restrict what methods can be used on an object when passed to another function PS class A: def j(self): return 7 def l(self): return 5 class interfaceforA: def __init__(self,obj) self.obj = obj def l(self): self.obj.l() I know you can use something like this, but this isn't practical for large amount of classes. So I'm looking for something more general.
has comment: http://stackoverflow.com/comment/91981876
score: 0
has comment: http://stackoverflow.com/comment/91983228
has comment: http://stackoverflow.com/comment/91981708
favorite count: 0
has comment: http://stackoverflow.com/comment/91981859
has title: Java like interface for restricted access in Python
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52574557
has answer: http://stackoverflow.com/a/52574767
downvote count: 2
has body: So I have this list here: [('CITS1001,95', 'CITS1401,100', 'CITS1402,97', 'CITS2002,99', 'CITS2211,94', 'CITS2401,95', 'CITS3001,93', 'CITS3002,93', 'CITS3003,91', 'CITS3200,87', 'CITS3401,98', 'CITS3402,93', 'CITS3403,88')] How do you make it so it looks like this? [('CITS1001,95'), ('CITS1401,100'), ('CITS1402,97'), ('CITS2002,99'), ('CITS2211,94'), ('CITS2401,95'), ('CITS3001,93'), ('CITS3002,93'), ('CITS3003,91'), ('CITS3200,87'), ('CITS3401,98'), ('CITS3402,93'), ('CITS3403,88')] I think you have to loop it but I can't get it to bracket like above. In general how do you tuple correctly for the above output. The problem I am having is the string values and the integer values I believe. I keep getting [('C'), ('I'), ('T') ETC.. because they are string. So for just an example. Say I have list [John, 20, Jeff 30] How do I output it to [('John', 20),('Jeff', 30)] Any help would be nice, thanks. :)
has comment: http://stackoverflow.com/comment/92085166
favorite count: 0
tagged with: python-3.x
has title: Strings and integer values in tuples
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52574643
answer count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/92085130
type: Question
has answer: http://stackoverflow.com/a/52574719
has comment: http://stackoverflow.com/comment/92085159
score: -2
has answer: http://stackoverflow.com/a/52582707

http://stackoverflow.com/q/52584039
tagged with: python
tagged with: regex
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52584074
has title: How to combine two urls as Regex pattern
score: 1
upvote count: 1
type: Question
has body: I used pattern = re.compile(r'(\/\/smtgvs\.weathernews\.jp\/s\/topics\/img\/\d+\/\w+\.[jpng]*)') to find all urls, now I found there are some urls \/\/smtgvs\.cdn\.weathernews\.jp\/s\/topics\/img\/\d+\/\w+\.[jpng]*)') How can I combine these two patterns? I tried pattern = re.compile(r'(\/\/smtgvs\[.cdn]*\.weathernews\.jp\/s\/topics\/img\/\d+\/\w+\.[jpng]*)') That seems like not correct...
has answer: http://stackoverflow.com/a/52584074
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pattern-matching
has comment: http://stackoverflow.com/comment/92103027

http://stackoverflow.com/a/52615705
has comment: http://stackoverflow.com/comment/136929703
has comment: http://stackoverflow.com/comment/95646656
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/129361227
has comment: http://stackoverflow.com/comment/95645915
has comment: http://stackoverflow.com/comment/107203623
has body: How can I modify the program above so that the producer(s) is its own coroutine that can be scheduled concurrently with the consumers/workers? The example can be generalized without changing its essential logic: Move the insertion loop to a separate producer coroutine. Start the consumers in the background, letting them process the items as they are produced. With the consumers running, start the producers and wait for them to finish producing items, as with await producer() or await gather(*producers), etc. Once all producers are done, wait for consumers to process the remaining items with await queue.join(). Cancel the consumers, all of which are now idly waiting for the queue to deliver the next item, which will never arrive as we know the producers are done. Here is an example implementing the above: import asyncio, random async def rnd_sleep(t): # sleep for T seconds on average await asyncio.sleep(t * random.random() * 2) async def producer(queue): while True: # produce a token and send it to a consumer token = random.random() if token < .05: break print(f'produced {token}') await queue.put(token) await rnd_sleep(.1) async def consumer(queue): while True: token = await queue.get() # process the token received from a producer await rnd_sleep(.3) queue.task_done() print(f'consumed {token}') async def main(): queue = asyncio.Queue() # fire up the both producers and consumers producers = [asyncio.create_task(producer(queue)) for _ in range(3)] consumers = [asyncio.create_task(consumer(queue)) for _ in range(10)] # with both producers and consumers running, wait for # the producers to finish await asyncio.gather(*producers) print('---- done producing') # wait for the remaining tasks to be processed await queue.join() # cancel the consumers, which are now idle for c in consumers: c.cancel() asyncio.run(main()) Note that in real-life producers and consumers, especially those that involve network access, you probably want to catch IO-related exceptions that occur durin…
has comment: http://stackoverflow.com/comment/109412772
has comment: http://stackoverflow.com/comment/138747409
type: Answer
score: 141
has comment: http://stackoverflow.com/comment/95667708
accepted answer of: http://stackoverflow.com/q/52582685
upvote count: 141
has comment: http://stackoverflow.com/comment/92175009
has comment: http://stackoverflow.com/comment/107198526
answers question: http://stackoverflow.com/q/52582685
has comment: http://stackoverflow.com/comment/109419525
has comment: http://stackoverflow.com/comment/129364846
has comment: http://stackoverflow.com/comment/109411863
has comment: http://stackoverflow.com/comment/109412072
has comment: http://stackoverflow.com/comment/92169595

http://stackoverflow.com/q/52481342
has answer: http://stackoverflow.com/a/52481912
has comment: http://stackoverflow.com/comment/91904833
type: Question
has body: I have extracted a pdf into a dataframe and would like to merge the rows if column B is the same speaker : From : Index Column B Column C 1 'I am going' Speaker A 2 'to the zoo' Speaker A 3 'I am going' Speaker B 4 'home ' Speaker B 5 'I am going' Speaker A 6 'to the park' Speaker A To : Index Column B Column C 1 'I am going to the zoo ' Speaker A 2 'I am going home' Speaker B 3 'I am going to the park' Speaker A I tried using groupby but the order is important in the context of a pdf which is a speech.
has title: Merging rows in a dataframe depending on another column
tagged with: dataframe
answer count: 2
tagged with: pandas-groupby
downvote count: 0
accepted answer: http://stackoverflow.com/a/52481912
score: 1
tagged with: string
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52481534
type: AnsweredQuestion
tagged with: join
upvote count: 1
possible better answer: http://stackoverflow.com/a/52481534

http://stackoverflow.com/comment/91845292
type: Comment
has text: @Bazingaa obviously price has not been declared inside the funtion
type: AnswerComment
comment on: http://stackoverflow.com/a/52450954
score: 0

http://stackoverflow.com/comment/91942013
type: Comment
type: QuestionComment
score: 0
has text: BTW, `words[len(words)-1]` is the same as `words[-1]`.
comment on: http://stackoverflow.com/q/52500359

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/52504017
tags question: http://stackoverflow.com/q/52481206
tags question: http://stackoverflow.com/q/52508716
tags question: http://stackoverflow.com/q/52476935
tags question: http://stackoverflow.com/q/52544562
tags question: http://stackoverflow.com/q/52446737
tags question: http://stackoverflow.com/q/52534085
tags question: http://stackoverflow.com/q/52564227
tags question: http://stackoverflow.com/q/52488647
tags question: http://stackoverflow.com/q/52572469
tags question: http://stackoverflow.com/q/52580875
tags question: http://stackoverflow.com/q/52451179
tags question: http://stackoverflow.com/q/52554477
tags question: http://stackoverflow.com/q/52570253
type: Tag
tags question: http://stackoverflow.com/q/52434566
tags question: http://stackoverflow.com/q/52458442
tags question: http://stackoverflow.com/q/52515212
tags question: http://stackoverflow.com/q/52520638
tags question: http://stackoverflow.com/q/52556450
tags question: http://stackoverflow.com/q/52502442
tags question: http://stackoverflow.com/q/52466206
tags question: http://stackoverflow.com/q/52503895
tags question: http://stackoverflow.com/q/52430558
tags question: http://stackoverflow.com/q/52570549
tags question: http://stackoverflow.com/q/52526442
tags question: http://stackoverflow.com/q/52502008
tags question: http://stackoverflow.com/q/52445743
tags question: http://stackoverflow.com/q/52503112
tags question: http://stackoverflow.com/q/52456292
tags question: http://stackoverflow.com/q/52550953
tags question: http://stackoverflow.com/q/52560228
tags question: http://stackoverflow.com/q/52443855
tags question: http://stackoverflow.com/q/52548474
tags question: http://stackoverflow.com/q/52452041
tags question: http://stackoverflow.com/q/52531068
tags question: http://stackoverflow.com/q/52454797
tags question: http://stackoverflow.com/q/52519836
tags question: http://stackoverflow.com/q/52488443
tags question: http://stackoverflow.com/q/52508044
tags question: http://stackoverflow.com/q/52490457
tags question: http://stackoverflow.com/q/52494488
tags question: http://stackoverflow.com/q/52442721
tags question: http://stackoverflow.com/q/52481096
tags question: http://stackoverflow.com/q/52525989
tags question: http://stackoverflow.com/q/52461091
tag name: html
tags question: http://stackoverflow.com/q/52477086
tags question: http://stackoverflow.com/q/52452687
tags question: http://stackoverflow.com/q/52578946
tags question: http://stackoverflow.com/q/52503465
tags question: http://stackoverflow.com/q/52457922
tags question: http://stackoverflow.com/q/52583543
tags question: http://stackoverflow.com/q/52493520

http://stackoverflow.com/comment/91921448
comment on: http://stackoverflow.com/q/52483397
type: Comment
score: 0
type: QuestionComment
has text: is request.File also null ??

http://stackoverflow.com/a/52484678
upvote count: 1
answers question: http://stackoverflow.com/q/52484609
has body: The problem is with the print statement. It is indented on the same level as the if block and thus, the if block ends on line containing the print statement. Thus, the else on the next line is incorrect. To achieve what you are trying, you should do something like this: n = int(input("number= ")) if 0 &lt;= n &lt; 5: a = "small" elif 5 &lt;= n &lt; 10: a = "medium" elif 10 &lt;= n &lt;= 20: a = "large" else: print("not between 0 and 20") print("The number is", a)
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/72808788
type: Answer
has body: I don't understand why it works with a int argument but not with a list. No, it doesn't: Traceback (most recent call last): File "method.py", line 10, in <module> Draw.platforms(locations) File "method.py", line 8, in platforms print(self.locations) AttributeError: 'int' object has no attribute 'locations' The reason why it doesn't work in either case is because you never constructed any instance of your class---you just called on a ("public") method belonging to the class. So when platforms() tries to use self.locations, it doesn't exist. You could either instantiate the object first: locations = [0, 1] drawer = Draw(locations) drawer.platforms() Or, if you don't care about keeping the Draw instance around: locations = [0, 1] Draw(locations).platforms() Or you change the method so that it accepts an argument instead: class Draw: def platforms(value): print(value) But now it's basically a static method, and you're only using the class as a namespace.
answers question: http://stackoverflow.com/q/52528985
score: 0

http://stackoverflow.com/a/52453080
has body: May be you can use dictionary instead and use key to get the corresponding value as following: a={21:-0.4, 22:-0.3, 23:-0.2} print("beta coefficient is ",a[age]) Update: If entered value or key does not exist in the dictionary, it will raise KeyError. In that case .get can be used with default value of None (or other value) to return when key is not found: print("beta coefficient is ",a.get(age, None))
type: Answer
answers question: http://stackoverflow.com/q/52453064
upvote count: 4
has comment: http://stackoverflow.com/comment/91849807
has comment: http://stackoverflow.com/comment/91849540
score: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91849342

http://stackoverflow.com/a/52522463
has comment: http://stackoverflow.com/comment/91994739
has comment: http://stackoverflow.com/comment/91989329
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52504781
has comment: http://stackoverflow.com/comment/91984928
has body: No, static_file is for returning a static file; templates are for returning dynamic content. They do not interoperate. You use static_file from within your code (route handler), not from within a template. E.g. (from the documentation), @route('/static/&lt;filepath:path&gt;') def server_static(filepath): return static_file(filepath, root='/path/to/your/static/files')
has comment: http://stackoverflow.com/comment/92001377
has comment: http://stackoverflow.com/comment/91989140
score: 2
has comment: http://stackoverflow.com/comment/91988586
has comment: http://stackoverflow.com/comment/91988060
downvote count: 0

http://stackoverflow.com/comment/92096630
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52562888
has text: @myrtlecat Update: I let it train for over a hundred thousand iterations and it still only outputs EOS (and occasional periods). The training loss also does not decrease after the first iteration (it remains at around 47)

http://stackoverflow.com/comment/92072760
has text: I edited my question to clear the air a bit, sorry for the ambiguity
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52567204

http://stackoverflow.com/comment/92106682
score: 0
has text: Facebook turns off your webhook, if your app fails to respond quickly enough for a while. Try removing it from your app settings, set it up again, and see if that changes things.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52576650

http://stackoverflow.com/comment/92073935
type: Comment
has text: @TrippCannella That is what I don't want. It returns both in black background like cmd. I am using Jupyter Notebook btw. I want the data frames to be returned in proper table format.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52568474

http://stackoverflow.com/comment/91951596
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52485502
has text: `issigned` adding a issigned attribute to `ctypes.c_ types` could also be an interesting idea
score: 0

http://stackoverflow.com/q/52475119
favorite count: 0
tagged with: classification
tagged with: regression
upvote count: 1
tagged with: python
has body: How do I create multiple regression models (statsmodel) in subsets of a pandas data frame using a for loop or conditon? I have a datframe which has one variable state that has 51 unique values. I have to make a model for each state. For some reason I am limited to regression(statsmodel) lets say with variable V1 to be predicted by variables X1 , X2, X3 State is 1:51 and will be used as condition to split that dataframe How can I automate this task using a for loop ?
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52476903
type: Question
answer count: 2
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/52476614
has answer: http://stackoverflow.com/a/52476614
has title: How do I create multiple regression models (statsmodel) in subsets of a pandas data frame using a for loop or conditon?
tagged with: pandas
has comment: http://stackoverflow.com/comment/91891843
downvote count: 0
accepted answer: http://stackoverflow.com/a/52476903
has comment: http://stackoverflow.com/comment/91893812

http://stackoverflow.com/q/52452475
favorite count: 0
has title: Dataset for predicting gender
type: UnansweredQuestion
tagged with: facebook
tagged with: machine-learning
tagged with: python
score: -5
has answer: http://stackoverflow.com/a/52452779
type: Question
upvote count: 0
tagged with: neural-network
has comment: http://stackoverflow.com/comment/91848724
downvote count: 5
has body: Can anyone guide me towards any dataset which consists of questions/survey based on psychology which when answered in full extent can tell you the gender if the person taking the test? I need it to create a tool through which we can detect the patterns of fake profiles on the social platforms. I know a few groups which are gender-specific (e.g. for mothers, for women private talk) but the opposite gender tries to trash it getting into the group pretending to be female. I know it sounds silly for now, but anyone who wants to join these group can go through the questionnaire and the AI can detect it's gender. Thank you in advance.
tagged with: supervised-learning
has comment: http://stackoverflow.com/comment/91851500
answer count: 1

http://stackoverflow.com/comment/92057253
type: Comment
has text: Is it possible to do this with the sequential API ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52559327

http://stackoverflow.com/a/52574927
type: Answer
has body: use the following regex: import re s = "{q0,q1,q2,q3},{a,b},q0,{q1,q3}" m = re.findall(r"\{([A-Za-z0-9_,]+)\}|,([A-Za-z0-9_]+),", s) if m: print(m)
has comment: http://stackoverflow.com/comment/92085748
upvote count: 1
has comment: http://stackoverflow.com/comment/92085648
answers question: http://stackoverflow.com/q/52574877
has comment: http://stackoverflow.com/comment/92085674
downvote count: 0
score: 1

http://stackoverflow.com/q/52580632
has comment: http://stackoverflow.com/comment/92096751
has body: Can someone please explain what is wrong with my formula, I'm not getting the desired output. I'm supposed to get 1635153.79 as my answer given the parameters below for my test value = maximum_home_loan(15000*12, 0.1045, 35). Build a function maximum_home_loan_with_age(PMT, i, start_age) that calculates the maximum home loan that your customer can afford Assume that start_age is an int value, and start_age &lt; 65 ' def maximum_home_loan(PMT, i, n): n=0 total_present_value = 0 while n &lt;66 : total_present_value = PMT * ((1+i)**n - 1) / i /(1+i)**n PV = round(total_present_value, 2) return PV '
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92096574
favorite count: 0
has comment: http://stackoverflow.com/comment/92133502
has answer: http://stackoverflow.com/a/52596450
has comment: http://stackoverflow.com/comment/92099062
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92131012
has comment: http://stackoverflow.com/comment/92124588
type: UnansweredQuestion
has title: Home Loan Affordability Calculator?
type: Question
score: -5
downvote count: 5

http://stackoverflow.com/comment/91977698
score: 1
type: QuestionComment
has text: So are those `a1`, `a2`, etc references actually floating point numbers?
type: Comment
comment on: http://stackoverflow.com/q/52518946

http://stackoverflow.com/q/52568678
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52597717
tagged with: string
has answer: http://stackoverflow.com/a/52568791
tagged with: python
has title: Python - Wildcard character generating vowels
has answer: http://stackoverflow.com/a/52569415
type: UnansweredQuestion
type: Question
tagged with: recursion
has body: Folks, Teaching myself python through open course ware and I have hit a wall on an assignment. Basically, the user types in a word with an * in place for a vowel. Example: 'd*g' for dig, dog, or dug. The program I wrote will replace * to a value from object: vowels='aeiou' and then look through a list of words and see if there is a match. Example: d*g -> *dag: no match, deg: no match, dig: match; end search. for char_vow in VOWELS: wildcard_word=word.replace('*',char_vow) print(wildcard_word) if wildcard_word in word_list: word=wildcard_word break This worked perfectly when there was one '*', but my program can't handle two or more. For instance if the user put in d**th for death, the code would only check daath, deeth, diith, dooth, duuth and then give back a false. So then I thought recursion might be the answer and wrote out: def wildcard_replacement(word): wildcard_word="" if word.find('*')==-1: return word else: for char_vow in VOWELS: wildcard_word=word.replace('*',char_vow,1) print(wildcard_word) if wildcard_word in word_list: word=wildcard_word break elif wildcard_word.find('*')!=-1: return wildcard_replacement(wildcard_word) return wildcard_replacement(wildcard_word) print(wildcard_replacement(word)) This program searched for: daath, daeth, daith, daoth, dauth then stopped. Which in hindsight makes sense. There is no longer an *. But I want the first vowel to now flip over from an a to and e and then continue the replacement loop for the second wildcard. I am stuck... Any suggestions?
tagged with: replace

http://stackoverflow.com/comment/91886210
has text: BTW, I guess this is a Python2 project right? As there is no `cmp` in Python3.
type: Comment
comment on: http://stackoverflow.com/q/52472091
score: 0
type: QuestionComment

ubuntu-server
type: Tag
tag name: ubuntu-server
tags question: http://stackoverflow.com/q/52580658

http://stackoverflow.com/a/64145911
answers question: http://stackoverflow.com/q/52442789
score: 0
has body: In https://stackoverflow.com/a/64145818/11262633, I have described 3 changes you can make to reduce memory utilization in TensorFlow v2.
type: Answer

http://stackoverflow.com/comment/91965227
type: QuestionComment
comment on: http://stackoverflow.com/q/52503969
score: 0
has text: Maybe websocket.recv() is trying to build your message. There is a concept called continuation frames in WebSocket that you can use to get messages in chunks to speed up your application: https://tools.ietf.org/html/rfc6455 Not sure how it is handled in python
type: Comment

http://stackoverflow.com/comment/92131428
has text: Seems like it. Though comparing to directly to the emoji didn't seem to work. I had to test against the find function like I did above
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52584889

http://stackoverflow.com/comment/91891213
has text: Have you checked the documentation? The [`tempfile.gettempdir()` function docs](https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir) spell this out for you.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52474813

jinja2
tags question: http://stackoverflow.com/q/52550766
tags question: http://stackoverflow.com/q/52553470
tags question: http://stackoverflow.com/q/52502405
tags question: http://stackoverflow.com/q/52493420
tags question: http://stackoverflow.com/q/52488728
tags question: http://stackoverflow.com/q/52573041
tags question: http://stackoverflow.com/q/52434588
tags question: http://stackoverflow.com/q/52464632
tags question: http://stackoverflow.com/q/52553445
type: Tag
tags question: http://stackoverflow.com/q/52502675
tags question: http://stackoverflow.com/q/52449492
tag name: jinja2
tags question: http://stackoverflow.com/q/52550463
tags question: http://stackoverflow.com/q/52496330
tags question: http://stackoverflow.com/q/52584099
tags question: http://stackoverflow.com/q/52450640
tags question: http://stackoverflow.com/q/52444751

http://stackoverflow.com/q/52460740
score: 1
has comment: http://stackoverflow.com/comment/91863967
tagged with: dataframe
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52461761
linked to: http://stackoverflow.com/q/5595425
tagged with: floating-accuracy
favorite count: 0
has comment: http://stackoverflow.com/comment/91863679
has body: I have a CSV file such as this one (example.csv). STRING_COL,INT_1,INT_2,FLOAT,INT_3 Hello,9,65151651,3234.54848,7832 This is a string,2,5484651,34.234,-999 Another,2,62189548,51.51658,-999 Test,2,2131514,5.2156,-999 Ham,9,6546548,2.15,-999 String,9,3216546,2.15468,-999 Every cell has a different number of decimals. They can be strings as well or integers (Int64, Int8, ...). Then I also have a similar CSV, but with some values changed. I want to check de differences between both files. Therefore I have written a code similar to this one to compare the values cell by cell: import pandas as pd df = pd.read_csv( 'example.csv', delimiter=',', comment='#', skip_blank_lines=True, verbose=False, engine='python', dtype=str ) df = df.apply(lambda x: pd.to_numeric(x, errors='ignore', downcast='integer')) df_2 = pd.read_csv( 'example_2.csv', delimiter=',', comment='#', skip_blank_lines=True, # file with small changes verbose=False, engine='python', dtype=str ) df_2 = df_2.apply(lambda x: pd.to_numeric(x, errors='ignore', downcast='integer')) for i in list(df.index): for column in list(df.columns): old = df.loc[i, column] new = df_2.loc[i, column] if old != new: print('DIFFERENT VALUE &gt;&gt; INDEX: {} | OLD: {} | NEW: {}'.format(i, old, new)) If you run this example with the small CSV file I am pretty sure it is going to work well. But with a huge CSV file some weird things are happening. I do not understand why sometimes many values are truncated to this ones: 1.6440000000000001 &gt;&gt; original value 1.644 7.7189999999999985 &gt;&gt; original value 7.7189 Then if I compare them it finds that they are different and this is not true because the value is the same. What is happening? Is there a way to fix this? Is there a better way to compare values with DataFrames? NOTE: Maybe I am doing anything wrong in other part of my original code, but I think I have written the most important and relevant. NOTE 2: I take into account that the != operator does not work well with NaN val…
tagged with: pandas
has comment: http://stackoverflow.com/comment/91865620
tagged with: python
linked to: http://stackoverflow.com/q/34611858
linked to: http://stackoverflow.com/q/33549193
tagged with: python-3.x
has title: How to compare two CSV files using DataFrames and retrieve the different cells? Why am I getting so many decimals figures in the float cells?
duplicate of: http://stackoverflow.com/q/33549193
upvote count: 1
has answer: http://stackoverflow.com/a/52461761
type: AnsweredQuestion

http://stackoverflow.com/comment/92278887
comment on: http://stackoverflow.com/a/52561946
type: Comment
has text: @TomAudre - it is probably because the original function worked through the lists passed to `search_queue` backwards (just because I did not put much thought into preserving order with this function). That said, I edited the answer to work through the list queues forwards which I think should get you the order you are looking for (but I am not 100% sure).
score: 0
type: AnswerComment

http://stackoverflow.com/q/52582723
type: Question
downvote count: 0
answer count: 1
has body: I want to replace all categories in a pandas dataframe with 'Others', if value count for that category is less than 10. I am trying something like this. df['variable'].where(df['variable'].apply(lambda x: x.map(x.value_counts()))&lt;=10, "other") But I get the following error: AttributeError: 'str' object has no attribute 'map'
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52582765
upvote count: 6
favorite count: 0
score: 6
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92100499
has title: replace column value with constant if value_count for that category is less than 10 python
has answer: http://stackoverflow.com/a/52582765

http://stackoverflow.com/comment/91976163
comment on: http://stackoverflow.com/a/52518161
score: 0
type: AnswerComment
has text: I'm not sure i have understood when to use one over another. And what if it has no slash at all.
type: Comment

http://stackoverflow.com/comment/91962667
type: QuestionComment
comment on: http://stackoverflow.com/q/52504185
has text: The problem lies in these lines: - f = open('userData.csv','r',newline =" '') for i in f: if userLName == f[0,3] and passLWord == f[0,4]: print('Log In Successfull') else: print('Incorrect Username or Password') main()
score: 0
type: Comment

http://stackoverflow.com/q/52570225
has comment: http://stackoverflow.com/comment/92077238
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92077246
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52570318
has body: I was given an assignment in university to write a program that will create user's password using their name and surname( ex: name = 'John', surname = 'Smith' => password will be 'JSomhinth', but I get “IndexError: string index out of range” mistake. name = input("Enter your name: ") surname = input("Enter your surname: ") print("Your credentials are %s %s." %(name, surname)) length = int((len(name) + len(surname))/2) password = [] x = 0 y = 0 if len(name)&gt;len(surname): for i in range(0, length): for n in range(0, len(name)): password.append(name[x]) x += 1 break for m in range(0, len(surname)): password.append(surname[y]) y += 1 break print(''.join(password))
has comment: http://stackoverflow.com/comment/92078318
upvote count: 1
has comment: http://stackoverflow.com/comment/92077360
type: Question
has title: String index out of range error in program that generates password in Python
score: 1
possible better answer: http://stackoverflow.com/a/52570326
has comment: http://stackoverflow.com/comment/92078062
has answer: http://stackoverflow.com/a/52570326
has comment: http://stackoverflow.com/comment/92077200
answer count: 2
has answer: http://stackoverflow.com/a/52570318

http://stackoverflow.com/q/52565668
upvote count: 0
has comment: http://stackoverflow.com/comment/92068968
tagged with: nested
has comment: http://stackoverflow.com/comment/92069159
favorite count: 0
has answer: http://stackoverflow.com/a/52566391
tagged with: python
tagged with: dictionary
has title: Fetching value in nested dictionary
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52566429
score: -5
has comment: http://stackoverflow.com/comment/92069073
downvote count: 5
has comment: http://stackoverflow.com/comment/92068995
has body: How can I fetch the world 'hello' from the following dictionary structure in Python? d = { 'k1': [1, 2, 3, { 'tricky': ['oh', 'man', 'inception', { 'target': [1, 2, 3, 'hello'] }] }] }
answer count: 2

http://stackoverflow.com/comment/91959835
type: Comment
comment on: http://stackoverflow.com/a/52500924
score: 1
type: AnswerComment
has text: Thanks Mike! This is exactly what I had ended up doing, but left the question open in case anyone had a better workaround.

http://stackoverflow.com/a/52576960
score: 7
answers question: http://stackoverflow.com/q/52576498
upvote count: 7
has body: From the docs: OpenCV has distanceTransform() and distanceTransformWithLabels() functions which work sort of similarly, but there are some differences from this Matlab function. From the Matlab docs for bwdist: D = bwdist(BW) computes the Euclidean distance transform of the binary image BW. For each pixel in BW, the distance transform assigns a number that is the distance between that pixel and the nearest nonzero pixel of BW. Compare this to the OpenCV docs for distanceTransformWithLabels(): Calculates the distance to the closest zero pixel for each pixel of the source image. So Matlab gives the distance to the nearest non-zero pixel, while OpenCV gives the distance to the nearest zero pixel. So you'll need to invert the image for OpenCV. Additionally, the optional output for Matlab with the labels gives the linear index corresponding to that closest pixel: [D,idx] = bwdist(BW) also computes the closest-pixel map in the form of an index array, idx. Each element of idx contains the linear index of the nearest nonzero pixel of BW. The closest-pixel map is also called the feature map, feature transform, or nearest-neighbor transform. With OpenCV, the label that gets output is not a coordinate of the image, nor an index. Instead it's just a numerical label, similar to a connected component label, that is not related to the pixel location/index at all. This variant of the function does not only compute the minimum distance for each pixel (x,y) but also identifies the nearest connected component consisting of zero pixels (labelType==DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==DIST_LABEL_PIXEL). This means that you'll have to use this labeled image to mask your input and find the pixel that corresponds to that label (as far as I know, this is the best way to do it, at least). Solution: So just to wrap our heads around how to get where we want, let's take a look at where this function gets us (with an inverted image as input as stated before): In [138]: img Out…
downvote count: 0
has comment: http://stackoverflow.com/comment/92090920
has comment: http://stackoverflow.com/comment/92090679
type: Answer

http://stackoverflow.com/q/52581359
type: Question
score: 1
tagged with: python-3.6
has body: I'm having the following problem when outputting the items that are in a list that are not in second list. Here is the code: def getInitialList(): # Define initial list with the use of requests and BS, will return a set getInHtml = requests.get("http://127.0.0.1") parseInHtml = BeautifulSoup(getInHtml.content, "html.parser") processInHtml = parseInHtml.find_all("div", class_="inner-article") firstList = [] for items in processInHtml: firstList.append(items) return firstList def getSecList(): #Define second list with the use of requests and BS, will return a set getHtml = requests.get("http://127.0.0.1") parseHtml = BeautifulSoup(getHtml.content, "html.parser") processHtml = parseHtml.find_all("div", class_="inner-article") secList = [] for items in processHtml: secList.append(items) return secList def catch_new_item(): initList = getInitialList() while True: if initList == getSecList(): print("No new items") else: print("New items found") break secList = getSecList() return set(secList) - set(initList) This last function (catch_new_items()), should return what is in the secList thats not in the initList, but when I run it it returns an empty set. The address 127.0.0.1 its a local web server that im running to determine the difference between this 2 items. All i do is edit the html and add one more element to it. Let me know what you think?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52581565
tagged with: python
tagged with: python-3.x
downvote count: 0
has title: Difference between 2 list
type: UnansweredQuestion
tagged with: python-requests

http://stackoverflow.com/comment/91829707
type: Comment
comment on: http://stackoverflow.com/a/52443366
has text: Sounds like a problem with your installation (most likely of Jupyter or some browser issue). Generally the output should be identical, but overwriting the line instead of writing it one by one.
type: AnswerComment
score: 0

python-2.7
tags question: http://stackoverflow.com/q/52437978
tags question: http://stackoverflow.com/q/52516709
tags question: http://stackoverflow.com/q/52487313
tags question: http://stackoverflow.com/q/52449997
tags question: http://stackoverflow.com/q/52559614
tags question: http://stackoverflow.com/q/52456633
tags question: http://stackoverflow.com/q/52437746
tags question: http://stackoverflow.com/q/52452283
tags question: http://stackoverflow.com/q/52533429
tags question: http://stackoverflow.com/q/52470351
tags question: http://stackoverflow.com/q/52452677
tags question: http://stackoverflow.com/q/52463761
tags question: http://stackoverflow.com/q/52488615
tags question: http://stackoverflow.com/q/52471611
tags question: http://stackoverflow.com/q/52568689
tags question: http://stackoverflow.com/q/52570005
tags question: http://stackoverflow.com/q/52569579
tags question: http://stackoverflow.com/q/52471626
tags question: http://stackoverflow.com/q/52485586
tags question: http://stackoverflow.com/q/52505349
tags question: http://stackoverflow.com/q/52495137
tags question: http://stackoverflow.com/q/52500777
tags question: http://stackoverflow.com/q/52461007
tags question: http://stackoverflow.com/q/52482720
tags question: http://stackoverflow.com/q/52473588
tags question: http://stackoverflow.com/q/52460976
tags question: http://stackoverflow.com/q/52508696
tags question: http://stackoverflow.com/q/52449000
tags question: http://stackoverflow.com/q/52557685
tags question: http://stackoverflow.com/q/52499752
tags question: http://stackoverflow.com/q/52461230
tags question: http://stackoverflow.com/q/52452810
tags question: http://stackoverflow.com/q/52469045
tags question: http://stackoverflow.com/q/52434152
tags question: http://stackoverflow.com/q/52435128
tags question: http://stackoverflow.com/q/52533665
tags question: http://stackoverflow.com/q/52442837
tags question: http://stackoverflow.com/q/52471216
tags question: http://stackoverflow.com/q/52534395
tags question: http://stackoverflow.com/q/52487612
tags question: http://stackoverflow.com/q/52493202
tags question: http://stackoverflow.com/q/52562394
tags question: http://stackoverflow.com/q/52431278
tags question: http://stackoverflow.com/q/52513846
tags question: http://stackoverflow.com/q/52521963
tags question: http://stackoverflow.com/q/52462472
tags question: http://stackoverflow.com/q/52513200
tags question: http://stackoverflow.com/q/52552616
tags question: http://stackoverflow.com/q/52465014
tags question: http://stackoverflow.com/q/52561107
tags question: http://stackoverflow.com/q/52537238
tags question: http://stackoverflow.com/q/52535478
tags question: http://stackoverflow.com/q/52510965
tags question: http://stackoverflow.com/q/52509190
tags question: http://stackoverflow.com/q/52460092
tags question: http://stackoverflow.com/q/52508642
tags question: http://stackoverflow.com/q/52473281
tags question: http://stackoverflow.com/q/52435912
tags question: http://stackoverflow.com/q/52457633
tags question: http://stackoverflow.com/q/52569148
tags question: http://stackoverflow.com/q/52441950
tags question: http://stackoverflow.com/q/52497031
tags question: http://stackoverflow.com/q/52533615
tags question: http://stackoverflow.com/q/52430427
tags question: http://stackoverflow.com/q/52569597
tags question: http://stackoverflow.com/q/52545836
tags question: http://stackoverflow.com/q/52432059
tags question: http://stackoverflow.com/q/52521317
tags question: http://stackoverflow.com/q/52572654
tags question: http://stackoverflow.com/q/52431265
tags question: http://stackoverflow.com/q/52489246
tags question: http://stackoverflow.com/q/52567243
tags question: http://stackoverflow.com/q/52499563
tags question: http://stackoverflow.com/q/52503870
tags question: http://stackoverflow.com/q/52552994
tags question: http://stackoverflow.com/q/52521288
tags question: http://stackoverflow.com/q/52532618
tags question: http://stackoverflow.com/q/52478939
tags question: http://stackoverflow.com/q/52470310
tags question: http://stackoverflow.com/q/52440213

jupyter-notebook
tags question: http://stackoverflow.com/q/52454372
tags question: http://stackoverflow.com/q/52443042
tags question: http://stackoverflow.com/q/52568474
tags question: http://stackoverflow.com/q/52584855
tags question: http://stackoverflow.com/q/52582390
tags question: http://stackoverflow.com/q/52470555
tags question: http://stackoverflow.com/q/52536387
tags question: http://stackoverflow.com/q/52458725
tags question: http://stackoverflow.com/q/52522845
tags question: http://stackoverflow.com/q/52551575
tags question: http://stackoverflow.com/q/52443200
tags question: http://stackoverflow.com/q/52484161
tags question: http://stackoverflow.com/q/52539871
tags question: http://stackoverflow.com/q/52540775
type: Tag
tags question: http://stackoverflow.com/q/52566756
tags question: http://stackoverflow.com/q/52487490
tags question: http://stackoverflow.com/q/52547769
tags question: http://stackoverflow.com/q/52564114
tags question: http://stackoverflow.com/q/52572751
tags question: http://stackoverflow.com/q/52486697
tags question: http://stackoverflow.com/q/52452222
tags question: http://stackoverflow.com/q/52502187
tags question: http://stackoverflow.com/q/52582187
tags question: http://stackoverflow.com/q/52457582
tags question: http://stackoverflow.com/q/52453840
tags question: http://stackoverflow.com/q/52444456
tags question: http://stackoverflow.com/q/52485276
tags question: http://stackoverflow.com/q/52461441
tags question: http://stackoverflow.com/q/52462183
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/52512650
tags question: http://stackoverflow.com/q/52525361
tags question: http://stackoverflow.com/q/52435726
tags question: http://stackoverflow.com/q/52435697
tags question: http://stackoverflow.com/q/52545512
tags question: http://stackoverflow.com/q/52461751
tags question: http://stackoverflow.com/q/52511169
tags question: http://stackoverflow.com/q/52449810
tags question: http://stackoverflow.com/q/52477839
tags question: http://stackoverflow.com/q/52501459
tags question: http://stackoverflow.com/q/52576808
tags question: http://stackoverflow.com/q/52558607

http://stackoverflow.com/comment/92056127
type: QuestionComment
has text: Not sure why `leftover` column is `0` everywhere...
score: 0
comment on: http://stackoverflow.com/q/52555508
type: Comment

http://stackoverflow.com/a/52575216
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: instead of printing the tuples directly you can use join suppose secret = ('ew', 'A', 2.0, 'B', 1.5, 1, 0 ) print(' ** '.join(map(str,secret))) result is like ew ** A ** 2.0 ** B ** 1.5 ** 1 ** 0 you can use anything in place '**' to join it can be anything even empty string like ''.
answers question: http://stackoverflow.com/q/52575168

http://stackoverflow.com/q/52468877
downvote count: 0
favorite count: 0
answer count: 3
has title: Assign predefined numbers to values of column rows in a dataframe
has body: lets say i have a dataframe C D agree Average agree agree strongly agree disagree disagree agree what i want to do is to assign numbers to C column values like this ? C D 1 3 1 1 2 0 0 1 i can use map for single column but if there are more than one column how do i change values to numbers without writing individually for every column (i know i could use for loops but the problem is that how would i apply it in here) anyone know how to do this? i tried to use a for loop def assignNumbers(df): for i in df: dftest= df[i].map({'Average':3, 'Agree':1, 'Disagree':0, 'Strongly Agree':2}) return dftest
tagged with: python
accepted answer: http://stackoverflow.com/a/52468954
score: 2
possible better answer: http://stackoverflow.com/a/52469016
upvote count: 2
has answer: http://stackoverflow.com/a/52469016
tagged with: loops
type: AnsweredQuestion
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/52468954
has answer: http://stackoverflow.com/a/52469137
tagged with: for-loop
tagged with: pandas

http://stackoverflow.com/q/52565345
type: Question
has title: How I can get f1 score, precision and recall, on a multiclass-multioutput problem?
has comment: http://stackoverflow.com/comment/92068747
has body: I am working on a NLP multiclass-multiouput classification problem. Here is the output prediction and the shape is (6546, 36), it's a 36 class classification problem. I tried to use classification_report to get the scores and error shows multiclass-multioutput is not supported. I am wondering anyone can help with this type of problem. I just trying to get a sense how the model work and to improve the model from there. If there is any better score can evaluate this type of problem, please let me know as well. Thank you guys in advance.
has comment: http://stackoverflow.com/comment/92069286
tagged with: python
answer count: 0
tagged with: classification
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52519568
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/92005917
has comment: http://stackoverflow.com/comment/91986497
score: 2
has comment: http://stackoverflow.com/comment/91988184
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91988753
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/91986683
accepted answer: http://stackoverflow.com/a/52534633
tagged with: python-3.6
upvote count: 2
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/91981188
tagged with: windows
answer count: 1
has comment: http://stackoverflow.com/comment/91980124
has answer: http://stackoverflow.com/a/52534633
has title: Pygame. Windows 10. Creates additional windows after loop.run_in_executor using ProcessPoolExecutor
has comment: http://stackoverflow.com/comment/91986225
has comment: http://stackoverflow.com/comment/92006787
favorite count: 0
has body: Environment where issues is reproduced: OS: Windows 10 (Host) CPU: 8 Python: 3.6.6 pygame version: 1.9.4 "builder": cx_Freeze version 5.1.1 Environment where issues is NOT reproduced: OS: Ubuntu 14.04 (guest, virtualbox) CPU: 4 Python: 3.6.6 pygame version: 1.9.4 "builder": cx_Freeze version 5.1.1 Script import asyncio import pygame import multiprocessing from concurrent.futures import ProcessPoolExecutor from concurrent.futures import ThreadPoolExecutor def init(): pygame.init() screen = pygame.display.set_mode((900, 700), pygame.RESIZABLE) clock = pygame.time.Clock() return screen, clock def fast_cpu_blocked(): print("blocked is run") i = 1 while 1: i += 1 if i &gt; 100000000: print("blocked is finished") return i executor_threads = ThreadPoolExecutor(multiprocessing.cpu_count()) executor_processes = ProcessPoolExecutor(multiprocessing.cpu_count()) async def start(): loop = asyncio.get_event_loop() cpu_run = False screen, clock = init() while 1: await loop.run_in_executor(None, clock.tick, 60) screen.fill((0, 0, 0)) txt_surface = pygame.font.Font(None, 18).render( "FPS: {}".format(int(clock.get_fps())), True, pygame.Color('grey')) screen.blit(txt_surface, (0, 0)) pygame.display.flip() if not cpu_run: print("RUN CPU TASK") cpu_run = True loop.run_in_executor(executor_processes, fast_cpu_blocked) print("FINISH CPU TASK") if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(start()) Issue: When loop.run_in_executor(executor_processes, fast_cpu_blocked) is executed it produces multiple windows of application(just black window, without any rendered context). It doesn't happen when use executor_threads instead of executor_processes. But anyway I need executor_processes, so it is just a fact. Logs in Windows: pygame 1.9.4 Hello from the pygame community. https://www.pygame.org/contribute.html RUN CPU TASK FINISH CPU TASK pygame 1.9.4 Hello from the pygame community. https://www.pygame.org/contribute.html blocked is run pygame 1.9.4 Hello fro…

http://stackoverflow.com/comment/91854639
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52454250
score: 0
has text: If you have grabbed as false, then it will not go to line "imutils.resize(frame, width=500)". what is value of args.get("video")? is it true?

http://stackoverflow.com/q/52476494
type: Question
has title: How to increase the error limit in flake8 and pylint VS Code?
has answer: http://stackoverflow.com/a/52476867
score: 0
tagged with: visual-studio-code
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: As mentioned above I would like to know how I can increase the no of errors shown in flake8 and pylint. I have installed both and they work fine when I am working with small files. I am currently working with a very large file (>18k lines) and there is no error highlighting done at the bottom part of the file, I believe the current limit is set to 100 and would like to increase it. If this isn't possible is there any way I can just do linting for my part of the code? I am just adding a function in this large file and would like to monitor the same.
tagged with: vscode-debugger

http://stackoverflow.com/comment/91975158
has text: Perfect! I had to change range(5) to range(20) and remove the fillvalue as it was filling with 0's but that's exactly what i needed, thank you again so much, if i could upvote more i would!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52513947
type: Comment

http://stackoverflow.com/a/52516772
has body: a pseudo code idea would be to do the following: scan multi-dim array horizontally and then vertically until you find True value (for second array it is (0,4)) output that as a start coord since you have been scanning as determined above your first move will be to go right. repeat until you come back: move one block in the direction you are facing. you are now at coord x,y check values of ul=(x-1, y-1), ur=(x-1, y), ll=(x, y-1), lr=(x,y) # if any of above is out of bounds, set it as False if ul is the only True: if previous move right: next move is up else: next move is left output previous move move by one ..similarly for other single True cells.. elif ul and ur only True or ul and ll only True or ll and lr only True or ur and lr only True: repeat previous move elif ul and lr only True: if previous move left: next move down elif previous move right: next move up elif preivous move down: next move left: else: next move right output previous move move one elif ul, ur, ll only Trues: if previous move left: next move down else: next move right output previous move, move by one ...similarly for other 3 True combos... for the second array it will do the following: finds True val at 0,4 start at 0,4 only lower-right cell is True, so moves right to 0,5 (previous move is None, so no output) now only lower-left cell is True, so moves down to 1,5 (previous move right 1 is output) now both left cells are True, so repeat move (moves down to 2,5) ..repeat until hit 4,5.. only upper-left cell is True, so move left (output down 4) both upper cells are true, repeat move (move left to 3,4) both upper cells are true, repeat move (move left to 2,4) upper right cell only true, so move up (output right -3) ..keep going until back at 0,4.. Try visualising all the possible coord neighbouring cell combos and that will give you a visual idea of the possible flows. Also note that with this method it should be impossible to be traversing a coord which has all 4 neighbours as False.
answers question: http://stackoverflow.com/q/52516043
score: 0
type: Answer

http://stackoverflow.com/q/52518066
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52520850
has title: Return Empty Dataframe using cursor.fetchall()
has comment: http://stackoverflow.com/comment/91980333
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52520850
has body: I have a SQL Query which may return Empty or Non Empty records. I need to execute this query in Python: import os import pandas as pd import pymysql from pandas import ExcelWriter from sqlalchemy import create_engine connection = pymysql.connect(host='localhost', user='root', password='root', db='device_db', cursorclass=pymysql.cursors.DictCursor) cur3=connection.cursor() cur3.execute('SELECT outgoing_db.Customer_No, sum(SUM_IC_CALLS) AS SumOfSUM_IC_CALLS, sum(SUM_AIC_DURATION_C1) AS SumOfSUM_AIC_DURATION_C1, sum(SUM_AIC_AMOUNT_C1) AS SumOfSUM_AIC_AMOUNT_C1, outgoing_db.Rate, outgoing_db.Customer_Name FROM outgoing_db WHERE (((outgoing_db.User_ID) != ("IND")) AND ((outgoing_db.Incoming_ID)="Airtel") AND ((outgoing_db.Customer_Type)="Check") AND ((outgoing_db.Current_Operation)="NO") AND ((outgoing_db.Active)="NO")) GROUP BY outgoing_db.Customer_No, outgoing_db.Rate, outgoing_db.Customer_Name HAVING (((outgoing_db.Customer_No) In (33165,33197)));') mydf3=pd.DataFrame(cur3.fetchall()) print(mydf3) It is giving me an exception: Traceback (most recent call last): File "C:\wamp64\www\DevicePortal\Query.py", line 16, in &lt;module&gt; mydf3=pd.DataFrame(cur3.fetchall()) File "C:\Users\Sonal\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\frame.py", line 404, in __init__ raise ValueError('DataFrame constructor not properly called!') ValueError: DataFrame constructor not properly called! When I am doing cur3.fetchone() It is giving me an output: Empty DataFrame Columns: [] Index: [] But the data may be added in future (around 1 Million). Is there a solution to return empty dataframe using cur3.fetchall()
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/92045241
has text: @PanagiotisIoannidis, do you want to extract any particular column data?
comment on: http://stackoverflow.com/q/52552258
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92075816
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52569202
has text: Why wouldn't the settings just go in the settings.py?
score: 0

http://stackoverflow.com/comment/91866682
comment on: http://stackoverflow.com/q/52462209
score: 1
type: Comment
type: QuestionComment
has text: There are plenty of languages that don't even have all the concepts you listed. No mutable objects, or no immutable objects, or none of those data structures, or multiple different implementations of those data structures... your perspective seems to be very shaped by Python.

http://stackoverflow.com/q/52466682
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has body: I am trying to set the value of a pandas column based on another columns value. The new value should be set by iterating through a list, that has the same length like the unique values of col1 Example: d = {'col1': [1, 2,2,2,3,3,4], 'col2': [1,1,1,1,1,1,1]} df = pd.DataFrame(data=d) items_to_add=[5,2,11,9] #list has length of unique values in `column1` Now i want to add for example 5 to column2 if column1is 1 and 2 to all column2 rows where column1 is 2 .... So i should get: col1 col2 1 5 2 2 2 2 2 2 3 11 3 11 4 9 This code throws me an syntax error but i do not know why items_to_add=[5,2,11,9] for i in range(len(items_to_add)): df['col2'][df.col1[i]] = items_to_add[i] What am I doing wrong? How can i fix it?
possible better answer: http://stackoverflow.com/a/52466749
score: 0
has answer: http://stackoverflow.com/a/52466774
has answer: http://stackoverflow.com/a/52466749
tagged with: loops
type: Question
accepted answer: http://stackoverflow.com/a/52466774
answer count: 3
has comment: http://stackoverflow.com/comment/91875088
has answer: http://stackoverflow.com/a/52466874
has title: Pandas set column value based on other columns value with list item by iteration
linked to: http://stackoverflow.com/q/28896769

http://stackoverflow.com/comment/92112110
score: 0
comment on: http://stackoverflow.com/q/52583932
type: Comment
type: QuestionComment
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.

http://stackoverflow.com/comment/91957776
type: QuestionComment
score: 2
has text: See how this is working? Your job as a system designer and programmer is to properly stage these computations, parameterize the items that can change with different specifications, and to generalize repetitive steps into iteration loops. Handing you code is simply too broad for Stack Overflow; this warrants a tutorial in problem analysis and execution.
comment on: http://stackoverflow.com/q/52508293
type: Comment

http://stackoverflow.com/q/52437416
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/52481429
downvote count: 0
tagged with: genetic-algorithm
has title: Automatically calculated bits in SimpleGADriver of OpenMDAO with integer value
type: Question
has answer: http://stackoverflow.com/a/52481429
has body: The link below about a SimpleGADriver document in OpenMDAO describes "Default is an empty dict, where every unspecified variable is assumed to be an integer, and the number of bits is calculated automatically" In the example in the document, "xI" value is calculated in the optimization process as an integer value with the range from -5 to 10. However, When I change the range from -6 to 11 (Not the length of 2^(n)), "xI" value is calculated as a real value. Although the "xI" value is unspecified variable, it seems the bits of the value is not calculated automatically as mentioned in the document. link of the document [The example in the document] from openmdao.api import Problem, Group, IndepVarComp, SimpleGADriver from openmdao.test_suite.components.branin import Branin prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('xC', 7.5)) model.add_subsystem('p2', IndepVarComp('xI', 0.0)) model.add_subsystem('comp', Branin()) model.connect('p2.xI', 'comp.x0') model.connect('p1.xC', 'comp.x1') model.add_design_var('p2.xI', lower=-5.0, upper=10.0) model.add_design_var('p1.xC', lower=0.0, upper=15.0) model.add_objective('comp.f') prob.driver = SimpleGADriver() prob.driver.options['bits'] = {'p1.xC': 8} prob.setup() prob.run_driver() Is there any solution for the "xI" integer value even if its range is changed?
tagged with: optimization
tagged with: openmdao
upvote count: 3
answer count: 1
tagged with: integer
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52469412
has comment: http://stackoverflow.com/comment/91880856
has body: Doing a remainder operation gives an error in z3py code Following is my code x = Real("x") solve( x%2 == 3 ) The Code gives the following Error : z3.z3types.Z3Exception: Z3 integer expression expected whereas when I am doing division operation it is working perfectly solve( x/2 == 3 ) (It gives an answer of 6) Is remainder operation not supported in z3? If it is how can achieve it?
score: -1
has comment: http://stackoverflow.com/comment/91881799
accepted answer: http://stackoverflow.com/a/52469997
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91880875
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91881344
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52469997
has comment: http://stackoverflow.com/comment/91880916
has comment: http://stackoverflow.com/comment/91881137
tagged with: python
has comment: http://stackoverflow.com/comment/91881243
tagged with: z3
has title: Error when using remainder operation in z3py
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91881254
downvote count: 1
tagged with: z3py
type: Question
has comment: http://stackoverflow.com/comment/91881045

http://stackoverflow.com/q/52564595
has body: I was running this code through python tutor, and was just confused as to how the keys and values get switched around. I also was confused as to what value myDict[d[key]] would correspond to as I'm not sure what the d in [d[key]] actually does. def dict_invert(d): ''' d: dict Returns an inverted dictionary according to the instructions above ''' myDict = {} for key in d.keys(): if d[key] in myDict: myDict[d[key]].append(key) else: myDict[d[key]] = [key] for val in myDict.values(): val.sort() return myDict print(dict_invert({8: 6, 2: 6, 4: 6, 6: 6}))
has answer: http://stackoverflow.com/a/52564635
has comment: http://stackoverflow.com/comment/92067341
type: Question
has answer: http://stackoverflow.com/a/52564728
has comment: http://stackoverflow.com/comment/92067364
has title: How values and keys get assigned in a dictionary using python
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/92067342
has answer: http://stackoverflow.com/a/52564684
has answer: http://stackoverflow.com/a/52564649
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/92067536

http://stackoverflow.com/q/52527320
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92003436
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91994314
favorite count: 0
type: Question
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/92004305
has answer: http://stackoverflow.com/a/52532509
answer count: 2
has comment: http://stackoverflow.com/comment/91994341
has title: Python: Catching a logging.exception() call
has answer: http://stackoverflow.com/a/52531699
has body: I am trying to catch an exception that is not raised, just logged. Is there any way to do this? def exampleFunction(): try: x = 1 / 0 except Exception: logging.exception('divide by 0 error here.') try: exampleFunction() except &lt;condition based on if logging.exception was called&gt; print('there was a divide by 0 error when I called exampleFunction()')
has comment: http://stackoverflow.com/comment/91994306

http://stackoverflow.com/a/52507469
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91955661
type: Answer
answers question: http://stackoverflow.com/q/52507352
accepted answer of: http://stackoverflow.com/q/52507352
score: 1
has body: tf.load_op_library calls the C function TF_LoadLibrary. According to the documentation for that function: Load the library specified by library_filename and register the ops and kernels present in that library. Pass "library_filename" to a platform-specific mechanism for dynamically loading a library. The rules for determining the exact location of the library are platform-specific and are not documented here. On success, place OK in status and return the newly created library handle. The caller owns the library handle. On failure, place an error status in status and return NULL. I think that the "platform-specific mechanism for dynamically loading a library" for your platform might not check the current directory, so you have to specify ./ in front of the filename to explicitly use the current directory.
upvote count: 1

http://stackoverflow.com/comment/92063395
type: Comment
type: QuestionComment
has text: @FlorianWeimer I might and want to prepare for the worst.
comment on: http://stackoverflow.com/q/52562028
score: 0

http://stackoverflow.com/a/52460968
upvote count: 3
has body: If you don't want to modify the array in place, you can make use of the np.ma library, and create a masked array: np.ma.masked_array(output, ~np.isfinite(output)).filled(0) array([[1. , 0.5 , 1. , 1. , 0. , 1. ], [1. , 1. , 0.5 , 1. , 0.46524064, 1. ], [1. , 1. , 1. , 0. , 1. , 1. ]])
downvote count: 0
answers question: http://stackoverflow.com/q/52458409
type: Answer
score: 3

http://stackoverflow.com/a/52537580
type: AcceptedAnswer
has body: This worked for me: img_buffer = numpy.asarray(bytearray(wand_img.make_blob(format='png')), dtype='uint8') bytesio = io.BytesIO(img_buffer) pil_img = PIL.Image.open(bytesio)
type: Answer
accepted answer of: http://stackoverflow.com/q/52536843
answers question: http://stackoverflow.com/q/52536843
upvote count: 5
downvote count: 0
score: 5

http://stackoverflow.com/comment/92104024
type: Comment
comment on: http://stackoverflow.com/q/52584499
type: QuestionComment
has text: Got it re: using struct, but to make sure I have a concrete answer to my original question: the "extra" character at the end of the hex is simply python trying to make it "easier" for me to understand what it is by automatically interpreting the hex for me? If so, please answer with that, and I'll make it the accepted answer...
score: 0

http://stackoverflow.com/a/52511370
has body: You can remove the time part of a datetime object using the .replace() method: self.date = self.date.replace(hour=0, minute=0, second=0, microsecond=0) This will result in: datetime.datetime(2018, 9, 26, 0, 0)
answers question: http://stackoverflow.com/q/52510834
score: 0
type: Answer

http://stackoverflow.com/a/52471238
has comment: http://stackoverflow.com/comment/91885027
score: 3
downvote count: 0
has body: You will have to specify what class you would like to import into the attribute __all__ of your __init__.py file. See below the example: from car import * __all__ = ["Car"]
has comment: http://stackoverflow.com/comment/91884376
has comment: http://stackoverflow.com/comment/92726250
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/52471227

http://stackoverflow.com/q/52573183
has body: For example my list is lst=['hello','world','this','is','hello','world','world','hello'] subString=['hello','world'] The result I'm looking for is in this case is 2 since the list ['hello','world'] occurs twice with that same order. I tried doing list(filter(lambda x : x in substring,lst)) but that returns all of hello and world
has answer: http://stackoverflow.com/a/52573252
downvote count: 1
type: Question
score: -1
accepted answer: http://stackoverflow.com/a/52573252
has title: How to count occurrences of a list of string inside of a list in python?
upvote count: 0
linked to: http://stackoverflow.com/q/6822725
favorite count: 0
has comment: http://stackoverflow.com/comment/92083530
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92082771
has answer: http://stackoverflow.com/a/52573281
possible better answer: http://stackoverflow.com/a/52573238
has answer: http://stackoverflow.com/a/52573263
tagged with: python
has answer: http://stackoverflow.com/a/52573238
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/91982262
has text: the purpose is to call a javascript function basically my pagination elements click load data of next page and i want to load the elements through next button just tell me how to call a javascript function because my href has a javascript function and i don't know how to call it.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52519345

http://stackoverflow.com/a/52563054
downvote count: 4
has comment: http://stackoverflow.com/comment/92064594
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/92064638
upvote count: 1
has body: you can use dict like this: &gt;&gt;&gt; def func_t(): ... return "I am T" ... &gt;&gt;&gt; def func_e(): ... return "I am E" ... &gt;&gt;&gt; def func_x(): ... return "I am X" ... &gt;&gt;&gt; my_dict = {'t':func_t(), 'e':func_e(), 'x':func_x()} &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; my_dict.get('x') 'I am X'
answers question: http://stackoverflow.com/q/52562941
has comment: http://stackoverflow.com/comment/92065010

http://stackoverflow.com/comment/92032618
comment on: http://stackoverflow.com/q/52546411
type: Comment
type: QuestionComment
score: 2
has text: In Python, you *cannot* enlarge a list by assigning to nonexistent indexes - you have to use the `.append()` or `.extend()` methods.

http://stackoverflow.com/a/52487916
type: Answer
answers question: http://stackoverflow.com/q/52487490
score: 0
has body: First of all, the line sum = sum + res makes no sense because you never defined sum in the first place. So, your function should look like def fibo(n): if n&lt;2: return 1 else: return fibo(n-1) + fibo(n-2) Second, you can get the sum by simply sum_ = 0 for i in range(0, n): sum_ += fibo(i) Or maybe sum_ = sum(fibo(i) for i in range(0, n)) Notice that the latter would only work if you have not overridden the built-in function named sum

http://stackoverflow.com/q/52523710
has answer: http://stackoverflow.com/a/78477893
linked to: http://stackoverflow.com/q/6390393
type: Question
linked to: http://stackoverflow.com/q/44863375
upvote count: 12
tagged with: matplotlib
score: 12
linked to: http://stackoverflow.com/q/20337664
has body: I'm looking for a way to prevent labels from overlapping. While searching through Stackoverflow I couldn't even find any suggestion on how to control x-axis spacing. matplotlib.pyplot.xticks(x, xticks, rotation=90) matplotlib.pyplot.plot(x, y) matplotlib.pyplot.bar(x, y, alpha=0.2) matplotlib.pyplot.title( f"średnia cena produktu {self.identifier}, według kontrahentów") matplotlib.pyplot.xlabel("kontrahent") matplotlib.pyplot.ylabel("cena") matplotlib.pyplot.tight_layout() matplotlib.pyplot.savefig(os.path.join( "products", self.identifier, "wykres.png")) matplotlib.pyplot.close()
answer count: 3
has answer: http://stackoverflow.com/a/52524120
has title: Increase spacing between points on x-axis
downvote count: 0
tagged with: xticks
possible better answer: http://stackoverflow.com/a/65602635
favorite count: 0
has answer: http://stackoverflow.com/a/65602635
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52524120

http://stackoverflow.com/q/52554766
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52555090
has comment: http://stackoverflow.com/comment/92048306
has title: What is the code of read() function in python?
downvote count: 2
has comment: http://stackoverflow.com/comment/92049026
upvote count: 1
has body: I opened a file and used the read() function as : file = open(r'C:\Users\admin\Desktop\bigmountain.txt') print(file.read()) I want to know how the read() function works in python. I got the code of other built-in functions but not read() over here. I also imported inspect module and used it's "getsource" function but to no use: import inspect print(inspect.getsource(read())) It says read not defined. Please tell me how should I get the code of read() to know how it works.
has comment: http://stackoverflow.com/comment/92048396
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92048083
score: -1
type: Question
has comment: http://stackoverflow.com/comment/92048772
has answer: http://stackoverflow.com/a/52555090
answer count: 1

http://stackoverflow.com/q/52580546
has body: I get an error with this code, I tried many things but it still keeps saying: traceback (most recent call last): File, line 7 TypeError: can't convert complex to float This is the code: import math a = float(input()) x = complex((a**1/3)*math.exp(0)*1j) y = complex((a**1/3)*math.exp(((2*math.pi)/3)*1j)) z = complex((a**1/3)*math.exp(((4*math.pi)/3)*1j)) print(complex(x).real) print(complex(x).imag) print(complex(y).real) print(complex(y).imag) print(complex(z).real) print(complex(z).imag)
has title: Can't convert complex to float
score: -1
type: Question
upvote count: 2
duplicate of: http://stackoverflow.com/q/8498310
answer count: 1
has answer: http://stackoverflow.com/a/52580619
accepted answer: http://stackoverflow.com/a/52580619
downvote count: 3
has comment: http://stackoverflow.com/comment/92096244
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/35423928
linked to: http://stackoverflow.com/q/8498310
type: AnsweredQuestion

http://stackoverflow.com/q/52569418
has title: Python - How to fix table row height and increase the size of the table based on the number of lines using PLT.TABLE?
has comment: http://stackoverflow.com/comment/92569064
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/92557299
has comment: http://stackoverflow.com/comment/92077201
tagged with: signal-processing
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92606444
has comment: http://stackoverflow.com/comment/92600673
has body: I need to plot a table beside a graph, and the number of lines it is not fixed, I mean, sometimes I will have 2 lines and sometimes I will have 5 or more lines. Saying that, I need to plot a table that "fits" the number of lines for each situation. My question is: How to fix table row height and also increase the size of the table based on the number of lines? i.e for each new row, the height of the table increases. Follow to image that FFT with one peak - table with 2 lines FFT with four peaks - table with 5 lines Follow my code below: import numpy as np import scipy import matplotlib.pyplot as plt from pylab import * import peakutils a =0.5 #a =input("entre com o limite: ") # Number of samplepoints N = 600 # sample spacing T = 1.0 / 800.0 x = np.linspace(0.0, N*T, N) y1 = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)+ 0.7*np.sin(30.0 * 2.0*np.pi*x)+ 0.5*np.sin(10.0 * 2.0*np.pi*x) #yf1 = scipy.fftpack.fft(y1) yf1 = np.fft.fft(y1) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) v1 = 2.0/N * np.abs(yf1[:N//2]) # Find peaks indexes = peakutils.indexes(v1, thres = a , min_dist=1,thres_abs= True) columns = ('Freq (Hz)','Amplitude') table_vals = np.column_stack((xf[indexes],v1[indexes])) table_vals = np.around(table_vals,decimals=2) print table_vals plt.figure(1) plt.plot(xf,v1) plt.scatter(xf[indexes],v1[indexes],color ='r') plt.table(cellText= table_vals, colLabels=columns, rowLoc = 'right',colLoc='right', colWidths = [0.3,0.3],bbox=[1.05,0.5,0.5,0.5],cellLoc = 'right') plt.subplots_adjust(right=0.65) #plt.subplots_adjust(bottom=0.3) plt.xlabel('Freq(Hz)') plt.ylabel('Amplitude') plt.grid() plt.show()
tagged with: python
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92566816
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/92558402

http://stackoverflow.com/a/52576065
has body: Use any: if any((len(self.e.get().strip())==0,len(self.e2.get().strip())==0,len(self.e2.get().strip())==0)): do stuff to say that user did not input all fields else: do stuff to say that user inputted all fields So full code: from tkinter import Tk, Label, Entry, Button, W from tkinter import messagebox class MyForm: def thanx(self): if any((len(self.e.get().strip())==0,len(self.e2.get().strip())==0,len(self.e2.get().strip())==0)): messagebox.showerror("Error", "Please enter affordable infos") self.boo = False else: messagebox.showinfo("Submition done", "Thank you") self.boo = True def callback(self): #print("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get())) if self.boo: f = open("PrivatData.txt", "w+") f.write("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get())) def __init__(self): self.root = Tk() self.root.title("Your privat details") Label(self.root, text="Your Name").grid(row = 0, padx = 12, pady=5) Label(self.root, text="Password").grid(row=1, padx=12, pady=5) Label(self.root, text="Email").grid(row=2, padx=12, pady=5) self.e = Entry(self.root) self.e2 = Entry(self.root) self.e3= Entry(self.root) self.e.grid(row=0,column=1,columnspan=2) self.e2.grid(row=1, column=1, columnspan=2) self.e3.grid(row=2, column=1, columnspan=2) self.e.focus_set() self.show= Button(self.root, text="Submit", command=lambda:[self.thanx(),self.callback()]) self.quit = Button(self.root,text="Quit", command = self.root.quit) self.show.grid(row=3, column=1, pady=4) self.quit.grid(row=3, column=2, sticky = W, pady=4) self.root.geometry("230x140") self.root.configure(background= "#65499c") self.root.mainloop() if __name__ == "__main__": app= MyForm()
has comment: http://stackoverflow.com/comment/92087660
has comment: http://stackoverflow.com/comment/92087708
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92087684
accepted answer of: http://stackoverflow.com/q/52576000
answers question: http://stackoverflow.com/q/52576000
type: Answer
has comment: http://stackoverflow.com/comment/92087729

python-curses
tags question: http://stackoverflow.com/q/52468889
tag name: python-curses
type: Tag

http://stackoverflow.com/a/52458429
has body: Home myhostname Hostname 52.62.207.113 ... c = Connection('52.62.207.113') I'm not a fabric user, but I guess you're expecting fabric to make use of the entry from your ssh_config file here? I can see two likely problems: You have Home myhostname. The correct keyword here is Host, not Home: Host myhostname Hostname 52.62.207.113 If you want fabric to use the Host section for myhostname, you probably have to tell it to connect to myhostname: c = Connection('myhostname') You're telling it to connect to an IP address, and it probably wouldn't relate that to the host section The actual error that you're getting, "No authentication methods available", is probably because fabric didn't apply the Host section from ssh_config, and it doesn't know of any key files that it should use for the session.
type: Answer
answers question: http://stackoverflow.com/q/52457960
has comment: http://stackoverflow.com/comment/91873060
score: 0

http://stackoverflow.com/comment/91890634
has text: NoAlertPresentException:
comment on: http://stackoverflow.com/a/52473667
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52493092
answer count: 3
tagged with: for-loop
downvote count: 0
has answer: http://stackoverflow.com/a/52493208
has body: In my code there is a for loop which iterates over pandas timestamps. I need to get the index in the for loop. Normally, I would do for idx, day in dates: However, if I try to do that I get the error "'Timestamp' object is not iterable". How can I get the index of the for loop? My code looks like this: import pandas as pd import numpy as np base = pd.Timestamp('2018-02-05 00:00:00+0000') dt_start = base total_days = 50 dates = np.array([base + pd.DateOffset(i) for i in xrange(total_days)]) for day in dates:
accepted answer: http://stackoverflow.com/a/52493195
tagged with: pandas
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
has title: Get index of for loop when iterating over pandas timestamps
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52493121
has answer: http://stackoverflow.com/a/52493121
has answer: http://stackoverflow.com/a/52493195

http://stackoverflow.com/q/52471547
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91885169
upvote count: 1
tagged with: python
downvote count: 1
has title: numpy subtract two arrays: output
has comment: http://stackoverflow.com/comment/91885151
has body: So I want to subtract two numpy arrays a and b: a=[[ 1. 0.85979163 0. 0.11766047 0.19353699] [ 0.8589698 1. 0.24111901 0. 0. ] [ 0. 0.24554123 1. 0.09234979 0.07125199] [ 0.31269982 0.22558714 0.29298401 1. 0.475543 ] [ 0.18880995 0. 0.06580817 0.32276821 1. ]] b=[[1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1]] When I use the following command: y=numpy.subtract(b,a) I get an output array: y= [[ -2.22044605e-16 1.40208370e-01 1.00000000e+00 8.82339528e-01 8.06463005e-01] [ 1.41030195e-01 0.00000000e+00 7.58880995e-01 1.00000000e+00 1.00000000e+00] [ 1.00000000e+00 7.54458767e-01 -2.22044605e-16 9.07650211e-01 9.28748013e-01] [ 6.87300178e-01 7.74412855e-01 7.07015986e-01 0.00000000e+00 5.24457002e-01] [ 8.11190053e-01 1.00000000e+00 9.34191829e-01 6.77231787e-01 0.00000000e+00]] And it's really confusing me as to how it's outputting these values. When I tried to troubleshoot and do: y=b[0,0]-a[0,0] I got y=0.. which makes sense because i would be subtracting 1-1. But in the output array I'm getting a value of -2.22044605e-16 instead. Do you have any idea as to why this might be happening and what I can do to fix it?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52471598
has comment: http://stackoverflow.com/comment/91885070
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/25181642

http://stackoverflow.com/a/52544798
answers question: http://stackoverflow.com/q/52544716
type: Answer
downvote count: 0
has body: I cant test this code right now, but it should be fairly close # get sorted entries s = sorted(d.items(), key=lambda e: e[1], reverse=True) # since Python 3.6, dictionaries are sorted by entry # if you're using an older Python, check out collections.OrderedDict d = {k: v for (k,v) in s}
score: 1
upvote count: 1

http://stackoverflow.com/comment/91897251
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52468744
has text: You said it’s sorted based on column. Index in my answer is that column.

http://stackoverflow.com/a/52567088
answers question: http://stackoverflow.com/q/52566866
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I've always found the matplotlib locators and formatters to be uneasy to use for many practical purposes, so if the links given by Mad Physicist do not suit you, you can just set them manually: n, m = data.shape ax.set_xticks(np.linspace(0, n-1, n)) ax.set_xticklabels(["%.1f" % i for i in np.linspace(0, 100, n)]) to format the xaxis from 0 to 100 with ticks on the middle of the squares, or n, m = data.shape ax.set_xticks(np.linspace(-0.5, n-0.5, n+1)) ax.set_xticklabels(["%.1f" % i for i in np.linspace(0, 100, n+1)]) for ticks on the left/right sides of the squares. Note that the "%.1f" is used to format the string to a float with 1 zero after the comma (see e.g. here); you can use "%d" if you want integers.
accepted answer of: http://stackoverflow.com/q/52566866
score: 1

http://stackoverflow.com/q/52579551
has answer: http://stackoverflow.com/a/52579602
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/52579630
has body: I have a pandas dataframe df that looks like userid trip_id segmentid actual prediction 1 13 40 3 3 1 6 2 1 1 1 44 3 2 3 2 70 19 1 1 2 12 5 0 0 I need to create a summary dataframe dfsummary grouped on column userid, having three columns userid, correct_classified, incorrect_classified. If actual and prediction values are same then it is correct classified, otherwise incorrect classified. I can count the correct_classfied on whole dataframe as correct_classified = submission[(submission['Actual'] == submission['prediction'])] incorrect_classified = submission[(submission['Actual'] != submission['prediction'])] but don’t getting an idea to create summary table grouped on user id, that should look like this userid correct_classified incorrect_classified 1 2 1 2 2 0
has answer: http://stackoverflow.com/a/52579630
answer count: 2
has title: Creating summary table on groupby dataframe based on condition
upvote count: 1
accepted answer: http://stackoverflow.com/a/52579602
tagged with: counter
tagged with: dataframe
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/91993333
type: Comment
score: 0
type: AnswerComment
has text: please also try changing mirror, https://github.com/pypa/pip/issues/4205#issuecomment-382154209
comment on: http://stackoverflow.com/a/52488986

http://stackoverflow.com/comment/91911812
has text: Thanks @Joost . I've updated the question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52480212
score: 0

http://stackoverflow.com/comment/102376573
type: Comment
has text: I have been looking for this explanation for three days. Thank you.
comment on: http://stackoverflow.com/a/52913854
score: 0
type: AnswerComment

http://stackoverflow.com/q/52519848
downvote count: 0
has body: I have a list y of keys from a dictionary that is derived from a call to the Google Places API. I would like to build a list of tuples for each point of interest: lst = [] for i in range(len(y)): lst.append((y[i]['name'], y[i]['formatted_address'], y[i]['opening_hours']['open_now'], y[i]['rating'])) This works if the field is in the list and I receive a list of results that look like the one below, which is exactly what I want: ("Friedman's", '1187 Amsterdam Ave, New York, NY 10027, USA', True, 4.2) However, the script throws an error if a desired field is not in the list y. How can I build a list of tuples that checks whether the desired field is in y before building the tuple? Here's what I've tried: for i in range(len(y)): t = () if y[i]['name']: t = t + lst.append(y[i]['name']) if y[i]['formatted_address']: t = t + lst.append(y[i]['formatted_address']) if y[i]['opening_hours']['open_now']: t = t + lst.append(y[i]['opening_hours']['open_now']) if y[i]['rating']: t = t + lst.append(y[i]['rating']) lst.append(t) However, this doesn't work and seems very inelegant. Any suggestions?
has comment: http://stackoverflow.com/comment/91979620
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91979314
has comment: http://stackoverflow.com/comment/91979553
possible better answer: http://stackoverflow.com/a/52519955
has answer: http://stackoverflow.com/a/52520041
type: Question
has title: Build a List of Tuples from a Dict
upvote count: 2
has answer: http://stackoverflow.com/a/52520124
accepted answer: http://stackoverflow.com/a/52520115
favorite count: 0
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/52520115
has comment: http://stackoverflow.com/comment/91979411
has answer: http://stackoverflow.com/a/52519955
tagged with: python
has answer: http://stackoverflow.com/a/52520021
score: 2

vscode-debugger
type: Tag
tags question: http://stackoverflow.com/q/52574371
tags question: http://stackoverflow.com/q/52476494
tags question: http://stackoverflow.com/q/52462326
tag name: vscode-debugger

http://stackoverflow.com/comment/91993103
has text: [This](https://stackoverflow.com/questions/45390553/calling-super-class-method-in-multiple-inheritance) is technically a duplicate, but I like neither the question nor the answer very much. I think we can do better than that.
type: QuestionComment
comment on: http://stackoverflow.com/q/52526451
type: Comment
score: 1

http://stackoverflow.com/comment/91838912
score: 2
has text: `df.plot(kind='bar', stacked=True)`
type: Comment
comment on: http://stackoverflow.com/q/52447199
type: QuestionComment

http://stackoverflow.com/q/52462764
downvote count: 0
favorite count: 0
has body: I have a list containing three separate lists: James = ['Alvin Kamara','Alex Collins','Michael Thomas', 'Adam Thielen','Evan Engram','Lamar Miller'] Ben = ['Todd Gurley II','Royce Freeman','Larry Fitzgerald', 'Cooper Kupp','Benjamin Watson','Robby Anderson'] Chris = ['Dion Lewis','Rex Burkhead','Julio Jones', 'Keenan Allen','Zach Ertz','Demaryius Thomas'] I want to remove the text ' II', which if you look in the "Ben" list, would change 'Toddy Gurley II' to 'Todd Gurley'. My current attempt is this: master_list = [James,Ben,Chris] for owner in master_list: owner = [word.replace(' II','') for word in owner] print(master_list[1]) But the output I get is: ['Todd Gurley II', 'Royce Freeman', 'Larry Fitzgerald', 'Cooper Kupp', 'Benjamin Watson', 'Robby Anderson']
has answer: http://stackoverflow.com/a/52462944
possible better answer: http://stackoverflow.com/a/52462794
has title: replacing string in list of lists python
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/52462833
tagged with: list
score: 1
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: replace
has answer: http://stackoverflow.com/a/52462839
has answer: http://stackoverflow.com/a/52462833
has answer: http://stackoverflow.com/a/52462794

http://stackoverflow.com/q/52473084
has answer: http://stackoverflow.com/a/52473195
answer count: 3
downvote count: 1
linked to: http://stackoverflow.com/q/12453580
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/52473195
has answer: http://stackoverflow.com/a/52473155
accepted answer: http://stackoverflow.com/a/52473155
has body: I have a problem wrapping my head around trying to convert strings into lists and producing the desired output. So far I have this code: def func(): characters = '?/&gt;&lt;,.:;"[]{}=+()*&amp;^%$#@!' # keeping ' and - new_lst = [] user = input("String: ") for i in user: if (i not in characters): #new_lst = user.split(' ') new_lst += i # I know this is the problem but I just don't know where to go from here print(new_lst) For example: Keep. hyphen- and apostrophe's only. Current output: 'K', 'e', 'e', 'p', ' ', 'h', 'y', 'p', 'h', 'e', 'n', '-', ' ', 'a', 'n', 'd', ' ', 'a', 'p', 'o', 's', 't', 'r', 'o', 'p', 'h', 'e', "'", 's', ' ', 'o', 'n', 'l', 'y'] Desired output: ['Keep', 'hyphen-', 'and', "apostrophe's", 'only'] Thanks for any help!
has title: Python 3.x function:Converting string to list and printing output which excludes certain characters
type: Question
score: -1
has comment: http://stackoverflow.com/comment/91888131
has answer: http://stackoverflow.com/a/52473194

http://stackoverflow.com/comment/91825365
type: Comment
type: QuestionComment
score: 0
has text: Do you have any resources that state this clearly @VineethSai? If so, please post it and I'll accept it as an answer.
comment on: http://stackoverflow.com/q/52441280

http://stackoverflow.com/q/52433986
answer count: 1
favorite count: 0
has body: I have written a program in Python 3.6 that makes use of IBM Watson's Speech to Text library. When the program searches a folder and reads through each .wav file individually, it's supposed to check the file's frequency and flag my IBM Watson integration differently. Then, it takes the response and maps it to a list. Through stub testing, the main, problematic code in question is here: speech_to_text.set_detailed_response(True) # Narrowband if rate &lt; 16000: x = json.loads( json.dumps(speech_to_text.recognize(audio_file, content_type='audio/basic', timestamps=True, max_alternatives=0).get_result(), indent=2), object_hook=lambda d: namedtuple('X', d.keys())(*d.values()) ) # Broadband else: x = json.loads( json.dumps(speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=True, max_alternatives=0).get_result(), indent=2), object_hook=lambda d: namedtuple('X', d.keys())(*d.values()) ) This program is completely functional when I supply it with a file over 16 kbps. However, anything less than that, and I get this error: File "echo_cli.py", line 64, in &lt;module&gt; json.dumps(speech_to_text.recognize(audio_file, content_type='audio/basic', timestamps=True, max_alternatives=0).get_result(), File "C:\Python37\lib\site-packages\watson_developer_cloud\speech_to_text_v1.py", line 373, in recognize accept_json=True) File "C:\Python37\lib\site-packages\watson_developer_cloud\watson_service.py", line 479, in request info=error_info, httpResponse=response) watson_developer_cloud.watson_service.WatsonApiException: Error: This 8000hz audio input requires a narrow band model. See https://&lt;STT_API_ENDPOINT&gt;/v1/models for a list of available models., Code: 400 , Information: {'code_description': 'Bad Request'} , X-dp-watson-tran-id: stream01-167902601 , X-global-transaction-id: f257b1145ba417780a01fd89 As a note, the files I'm using are over a network drive. However, I get the same error when I copy them to my local drive, so I'm thinking that this is an un…
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52434042
tagged with: python
has title: IBM Watson Speech to Text Audio/Basic not accepting narrowband .WAV
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: speech-to-text
tagged with: ibm-watson
type: Question
tagged with: wav
upvote count: 2
accepted answer: http://stackoverflow.com/a/52434042

http://stackoverflow.com/comment/91956597
has text: I personally like/prefer groupby because that's an SQL idiom I like to use when thinking of how to solve problems,... but sometimes people prefer the simpler stuff. ;-)
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52508094

http://stackoverflow.com/q/52452950
linked to: http://stackoverflow.com/q/1696877
has body: I'm trying to create the edit of posts for a blog. When i create the form with the instance all the fields display but the image part appears like "No file chosen" Here is my model class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() image = models.ImageField(blank=True, null=True) publication_date = models.DateField(default=datetime.date.today) expiring_date = models.DateField() Here is my form class PostForm(forms.models.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.publication_date = datetime.date.today() class Meta: model = Post exclude = ['publication_date'] widgets = { 'title': forms.fields.TextInput(attrs={ 'class': 'form-control' }), 'content': forms.Textarea(attrs={ 'class': 'form-control' }), 'image': forms.fields.FileInput(attrs={ 'class': 'form-control' }), 'expiring_date': forms.fields.DateInput(attrs={ 'input_type': 'date', 'class': 'form-control' }), } This is my view def edit(request, post_id): post = get_object_or_404(Post, pk=post_id) form = PostForm(instance=post) return render(request, 'posts/edit.html', {'form': form}) And here is my template {% block content %} {{ form }} {% csrf_token %} {% endblock %} What is missing? Edit; Maybe is imposible because of security reasons?: How to set a value to a file input in HTML?
has comment: http://stackoverflow.com/comment/91849171
downvote count: 0
has comment: http://stackoverflow.com/comment/91849142
has comment: http://stackoverflow.com/comment/91849204
has answer: http://stackoverflow.com/a/73961651
score: 1
has comment: http://stackoverflow.com/comment/91850887
has comment: http://stackoverflow.com/comment/91849133
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91849104
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/65205064
has title: ModelForm django shows no file chosen when editing
tagged with: django-forms
has comment: http://stackoverflow.com/comment/91851461
type: Question
answer count: 2

http://stackoverflow.com/a/52560938
has comment: http://stackoverflow.com/comment/92060511
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52560895
score: 1
has body: Change soup_data = page_data.find('table') to soup_data = page_data.find_all('table'). find only finds the first matching object, whereas find_all finds all the matching objects. See here for more information. from bs4 import BeautifulSoup as soup import requests as r import pandas as pd url = 'http://www.crb.state.ri.us/verify_CRB.php?page=0&amp;letter=' data = r.get(url) page_data = soup(data.text, 'html.parser') soup_data = page_data.find_all('table') df = pd.DataFrame() for each in soup_data: lic_link = each.find('a').text df=df.append(pd.DataFrame({'LicenseURL': lic_link}, index=[0])) df.to_csv('RI_License_urls.csv', index=False)
upvote count: 1
has comment: http://stackoverflow.com/comment/92060594

http://stackoverflow.com/comment/91828474
type: QuestionComment
comment on: http://stackoverflow.com/q/52442837
score: 1
has text: We would appreciate a slightly more specific question from you: What have you tried? What does not work? Where is the error and how is its exact text? Where is your code? Please refer to [how to ask](https://stackoverflow.com/help/how-to-ask) and provide a [minimal verifyable complete example](https://stackoverflow.com/help/mcve) to improve your question
type: Comment

http://stackoverflow.com/comment/92028867
type: Comment
has text: See https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly . The rows of your `temp_matrix` are all the same `temp_row` list.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52544456

http://stackoverflow.com/q/52478039
has answer: http://stackoverflow.com/a/52649556
tagged with: python
accepted answer: http://stackoverflow.com/a/52649556
tagged with: python-packaging
score: 1
linked to: http://stackoverflow.com/q/11147667
upvote count: 1
has body: I'm trying to generate a list of requirements from a local uninstalled wheel. Simply getting the list that was fed as the packages parameter into setup.py's setuptools.setup-call would be optimal. The output that a pip freeze would generate if the wheel were installed could work, too. Slightly more context I want to build a docker image that is going to be used in a CI chain. In order to cut down on pipeline time, it should come front-loaded with all runtime dependencies. But at the point where the image is built, the python package is not built yet, and building the package outside of the chain merely for obtaining a requirements.txt is cumbersome and error-prone. Things I tried Hacking it into the Dockerfile: python -c $'\ import setuptools\n\ setuptools.setup = lambda *args, **kwargs: None\n\ exec(compile(open("setup.py").read(), "setup.py", "exec"))\n\ for requirement in requirements: print(requirement)\n' &gt; python_packages.txt # `requirements` is the name of variable that holds the package list This doesn't work very well because docker does weird things with its build context. Having any code in setup.py that accesses local files (such as, for example, fetching the current version number from a VERSION file) breaks this hack. Fixing the docker-build context so that this code works would solve my problem, but I'd prefer a proper solution that doesn't implicitly rely on how stuff looks in setup.py. Using pip/pipreqs/pipenv/pipdeptree: All of these tools work on top of local environments, and can't handle an uninstalled wheel. This answer comes quite close using pip, but 1) only works if the package is uploaded at pyPI (which my target package isn't) and 2) does a hefty dry-build to get the package list.
type: Question
type: AnsweredQuestion
tagged with: docker
tagged with: continuous-integration
has title: Generate requirements.txt from uninstalled wheel
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52502421
answers question: http://stackoverflow.com/q/52495742
has body: Replace sudo apt-get install spyder3 with sudo pip install spyder3 If you hade other error please show me and also show me command in terminal
type: Answer
score: 0

http://stackoverflow.com/q/52526960
type: Question
answer count: 1
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52527115
accepted answer: http://stackoverflow.com/a/52527115
has title: Getting the date from customText from a json string
type: AnsweredQuestion
tagged with: arcpy
has body: I'm trying to loop through this json string "layoutOptions": { "titleText": "Route Number", "authorText": "West LA Yard", "copyrightText": "", "customTextElements": [{ "Date": "9/11/2018, 7:37:35 AM" } ], "scaleBarOptions": { "metricUnit": "esriKilometers", "metricLabel": "km", "nonMetricUnit": "esriMiles", "nonMetricLabel": "mi" }, "legendOptions": { "operationalLayers": [{ "id": "ParcelRouteEditingTest_1458" }, { "id": "ParcelRouteEditingTest_1259" } ] } } I keep running to this error list indices must be integers, not str layoutOpsDict = layoutData["layoutOptions"] dateList = [dateEle["customTextElements"]["Date"] for dateEle in layoutOpsDict] Error: Traceback (most recent call last): File "&lt;pyshell#44&gt;", line 1, in &lt;module&gt; dateList = [dateEle["customTextElements"]["Date"] for dateEle in layoutOpsDict] TypeError: string indices must be integers, not str What is the best method to grab the date in customTextElements other than keep setting more variables to keep track of?

http://stackoverflow.com/comment/137711437
comment on: http://stackoverflow.com/a/52536584
type: AnswerComment
has text: How about the new class name 'Y', how do you use it?
score: 0
type: Comment

http://stackoverflow.com/a/52478814
has comment: http://stackoverflow.com/comment/91906507
type: Answer
has comment: http://stackoverflow.com/comment/91899030
has comment: http://stackoverflow.com/comment/91903945
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91903322
has comment: http://stackoverflow.com/comment/91904170
type: AcceptedAnswer
downvote count: 0
has body: You are implementing the get_redirect_url method. Whatever that method returns us treated as a URL to redirect the browser to. The JsonResponse function returns an object with the response data. But since this is get_redirect_url, Django thinks that it is a string with the URL. Instead, implement the post method and manually return a HttpResponseRedirect if it is a normal request, and the JsonResponse if it is a AJAX request. Another thing: You are using the LoginRequiredMixin mix-in. No need to check for user.is_authenticated in the View. class PostLikeToggle(LoginRequiredMixin, RedirectView): def post(self, *args, **kwargs): slug = self.kwargs.get('slug') obj = get_object_or_404(Post, slug=slug) user = self.request.user context = {"post": obj} if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) if self.request.is_ajax(): html = render_to_string("posts/like_section.html", context, request=self.request) return JsonResponse({"form": html}) url = obj.get_absolute_url() return HttpResponseRedirect(url)
has comment: http://stackoverflow.com/comment/91904343
accepted answer of: http://stackoverflow.com/q/52456154
answers question: http://stackoverflow.com/q/52456154

http://stackoverflow.com/q/52586005
tagged with: selenium-webdriver
answer count: 0
tagged with: selenium
type: Question
has title: AttributeError: 'module' object has no attribute 'PoolManager'
has body: Code from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.google.com") print drive.title I have tried using Firefox and Chrome webdriver, but I'm getting same error as below for both of them. AttributeError: 'module' object has no attribute 'PoolManager' self.driver = webdriver.Firefox() File "C:\Python27\lib\site-packages\selenium-3.14.1-py2.7.egg\selenium\webdriver\firefox\webdriver.py", line 169, in __init__ remote_server_addr=self.service.service_url) File "C:\Python27\lib\site-packages\selenium-3.14.1-py2.7.egg\selenium\webdriver\firefox\remote_connection.py", line 23, in __init__ RemoteConnection.__init__(self, remote_server_addr, keep_alive) File "C:\Python27\lib\site-packages\selenium-3.14.1-py2.7.egg\selenium\webdriver\remote\remote_connection.py", line 140, in __init__ self._conn = urllib3.PoolManager(timeout=self._timeout) AttributeError: 'module' object has no attribute 'PoolManager' Any help will be appreciated TIA
has comment: http://stackoverflow.com/comment/92107344
score: 0
has comment: http://stackoverflow.com/comment/92107216
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91874846
score: 1
comment on: http://stackoverflow.com/q/52466372
has text: @DominiqueM okay, than you pass `strawberries` as the `fruit` parameter and `10` to `quantity`. What is `inventory` being used for? why the loop?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52880584
score: 0
has body: It looks like you're running experiments in create_model() and then throwing the model away. If you return the models this may solve your problem. Try: out={'loss':-acc,'score':score,'status':STATUS_OK, 'model': network}
answers question: http://stackoverflow.com/q/52461011
type: Answer

http://stackoverflow.com/q/52433957
has answer: http://stackoverflow.com/a/52434034
has comment: http://stackoverflow.com/comment/91812012
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91812372
has title: Make CSV escape Double Quotation Marks
has comment: http://stackoverflow.com/comment/91812519
has answer: http://stackoverflow.com/a/52434633
has body: I need to prepare a .csv file so that a double quotation marks gets ignored by the program processing it (ArcMap). Arc was blending the contents of all following cells on that line into any previous one containing double quotation marks. For example: ...and no further rows would get processed at all. How does one make a CSV escape Double Quotation Marks for successful processing in ArcMap (10.2)?
has comment: http://stackoverflow.com/comment/91811955
type: Question
tagged with: python-2.7
score: 0
tagged with: arcmap
has comment: http://stackoverflow.com/comment/91814485
upvote count: 1
has comment: http://stackoverflow.com/comment/91811698
downvote count: 1
has comment: http://stackoverflow.com/comment/91811746
has comment: http://stackoverflow.com/comment/91813646
favorite count: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/53550195
tagged with: python
has comment: http://stackoverflow.com/comment/91812057

http://stackoverflow.com/a/52538697
type: Answer
has comment: http://stackoverflow.com/comment/92017689
score: 3
has comment: http://stackoverflow.com/comment/92020943
has comment: http://stackoverflow.com/comment/92018215
has body: I'm not aware of any progress report functionality back from .str.extract. Changing it into an .apply to use .progress_apply might come with bad performance penalties. It's neither pretty nor a one-liner, but if the work being done is row-independent (no grouping), you can always just split the df up into chunks, do the work independently on the chunks, and merge them back together at the end. You can then track the progress by chunk with tqdm. Something like this: # 1000 sections as an example, may need to adapt to your problem chunks = np.array_split(df, 1000) processed = [] for chunk in tqdm(chunks): processed.append(chunk.str.extract(r"Name: (.*), Value: (.*)")) out = pd.concat(processed)
downvote count: 0
answers question: http://stackoverflow.com/q/52538308
accepted answer of: http://stackoverflow.com/q/52538308
has comment: http://stackoverflow.com/comment/92020580
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92017287
upvote count: 3

http://stackoverflow.com/comment/91917938
comment on: http://stackoverflow.com/a/52488198
type: AnswerComment
score: 0
type: Comment
has text: @roganjosh, what do you mean by "completes"? Typically, a directory's creation is completed as soon as it's fully reflected by the VFS layer, visible to other applications, etc; that doesn't mean the changes were flushed to disk and going to survive reboot. Watch the linked presentation -- I don't have the time to recount everything in it, and if I tried, I'd probably get half the details wrong.

http://stackoverflow.com/a/52438791
has comment: http://stackoverflow.com/comment/91821460
type: Answer
upvote count: 16
accepted answer of: http://stackoverflow.com/q/52438263
score: 16
answers question: http://stackoverflow.com/q/52438263
has comment: http://stackoverflow.com/comment/91821869
has body: You just encounterd the problem with local optimization: it strongly depends on the start (initial) values you pass in. If you supply [2, 1] it will find the correct minima. Common solutions are: use your optimization in a loop with random starting points inside your boundaries import numpy as np from numpy import *; from scipy.optimize import *; from math import * def f(X): x=X[0]; y=X[1] return x**4-3.5*x**3-2*x**2+12*x+y**2-2*y bnds = ((1,3), (0, 2)) for i in range(100): x_init = np.random.uniform(low=bnds[0][0], high=bnds[0][1]) y_init = np.random.uniform(low=bnds[1][0], high=bnds[1][1]) min_test = minimize(f,[x_init, y_init], bounds = bnds) print(min_test.x, min_test.fun) use an algorithm that can break free of local minima, I can recommend scipy's basinhopping() use a global optimization algorithm and use it's result as initial value for a local algorithm. Recommendations are NLopt's DIRECT or the MADS algorithms (e.g. NOMAD). There is also another one in scipy, shgo, that I have no tried yet.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91967192
has text: if type(value) != str and isinstance(value, get_keys.Iterable): AttributeError: 'function' object has no attribute 'Iterable',Got this error
type: AnswerComment
comment on: http://stackoverflow.com/a/52513211
score: 0
type: Comment

praw
tags question: http://stackoverflow.com/q/52436259
type: Tag
tags question: http://stackoverflow.com/q/52520949
tag name: praw

http://stackoverflow.com/q/52449475
favorite count: 0
has body: I found a Python script that I'm trying to convert to Lua. I believe I have it just about converted, but the code isn't quite working properly, so I need assistance as I do not know Python at all, and can only guess at the intentions. This is merely a color converter to convert RGB color to xterm 256. The table is quite huge, so I've truncated it for ease of reading. Python code: import sys, re CLUT = [ # color look-up table # 8-bit, RGB hex # Primary 3-bit (8 colors). Unique representation! ('00', '000000'), ('01', '800000'), ('02', '008000'), ('03', '808000'), ('04', '000080'), ('05', '800080'), ('06', '008080'), ('07', 'c0c0c0'), ] def _str2hex(hexstr): return int(hexstr, 16) def _strip_hash(rgb): # Strip leading `#` if exists. if rgb.startswith('#'): rgb = rgb.lstrip('#') return rgb def _create_dicts(): short2rgb_dict = dict(CLUT) rgb2short_dict = {} for k, v in short2rgb_dict.items(): rgb2short_dict[v] = k return rgb2short_dict, short2rgb_dict def short2rgb(short): return SHORT2RGB_DICT[short] def print_all(): """ Print all 256 xterm color codes. """ for short, rgb in CLUT: sys.stdout.write('\033[48;5;%sm%s:%s' % (short, short, rgb)) sys.stdout.write("\033[0m ") sys.stdout.write('\033[38;5;%sm%s:%s' % (short, short, rgb)) sys.stdout.write("\033[0m\n") print "Printed all codes." print "You can translate a hex or 0-255 code by providing an argument." def rgb2short(rgb): """ Find the closest xterm-256 approximation to the given RGB value. @param rgb: Hex code representing an RGB value, eg, 'abcdef' @returns: String between 0 and 255, compatible with xterm. &gt;&gt;&gt; rgb2short('123456') ('23', '005f5f') &gt;&gt;&gt; rgb2short('ffffff') ('231', 'ffffff') &gt;&gt;&gt; rgb2short('0DADD6') # vimeo logo ('38', '00afd7') """ rgb = _strip_hash(rgb) incs = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff) # Break 6-char RGB code into 3 integer vals. parts = [ int(h, 16) for h in re.split(r'(..)(..)(..)', rgb)[1:4] ] res = [] for part in parts: i = 0 while i &lt; len(incs)-1: s, b = …
has title: Code conversion from Python to Lua almost completed
tagged with: python
tagged with: code-translation
tagged with: lua
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52450565
score: 1
upvote count: 1
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52450565
downvote count: 0

http://stackoverflow.com/q/52460044
favorite count: 0
has comment: http://stackoverflow.com/comment/91862239
has title: Split DataFrame into chunks
has answer: http://stackoverflow.com/a/52465147
has answer: http://stackoverflow.com/a/52460172
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52465147
type: AnsweredQuestion
score: 1
type: Question
linked to: http://stackoverflow.com/q/37486502
accepted answer: http://stackoverflow.com/a/52460172
answer count: 2
downvote count: 0
tagged with: dataframe
has body: I have a DataFrame that contains an name, a year, a tag and a bunch of other variables. So it might look like this df = pd.DataFrame({ "name": 4*["A"] + 5*["B"], "year": [1999,2000,2001,2002,2010,2011,2012,2013,2014], "tag": [0,1,0,0,1,0,0,1,0], "x1": np.random.normal(size=9), "x2": np.random.uniform(size=9) }) print df name tag x1 x2 year 0 A 0 -1.352707 0.932559 1999 1 A 1 -1.359828 0.724635 2000 2 A 0 1.289980 0.477135 2001 3 A 0 -0.409960 0.863443 2002 4 B 1 -1.469220 0.324349 2010 5 B 0 0.372617 0.871734 2011 6 B 0 -0.047398 0.307596 2012 7 B 1 1.240108 0.667082 2013 8 B 0 0.558432 0.284363 2014 I am looking for a way to either group or split the DataFrame into chunks, where each chunk should contain one row with tag==1 and all rows where tag==0, row[year+1] and row[year-1] exist, rowyear+-1,"tag"==1 and rowyear+-1,"name"==rowyear,"name". Simpy put, I want chunks of size 3 where the middle row is tagged and is surrounded by two untagged rows of the same company. So in the example above the only two chunks that pass these conditions are name tag x1 x2 year 0 A 0 -1.352707 0.932559 1999 1 A 1 -1.359828 0.724635 2000 2 A 0 1.289980 0.477135 2001 and 7 B 0 -0.047398 0.307596 2012 8 B 1 1.240108 0.667082 2013 9 B 0 0.558432 0.284363 2014 I have thought about grouping by multiple columns but the problem is that the rows I need to group don't have anything in common but the name. I have also thought about manually introducing (in a for loop) another column that gives each chunk a new ID which I could then group by. I am however very unhappy with that approach as it does not seem either efficient nor elegant. I'd appreciate any ideas.
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/91862282

http://stackoverflow.com/a/52529443
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52529353
has body: This worked for me. d = {'key':['apples','oranges','banana'],'key2':['mangoes','pineapple','apple']} for key in d: val = d[key] print(key,val[1])

http://stackoverflow.com/a/52521085
has body: With the help from an amazing BT support engineer, we were finally able to figure out a solution to our problem. The explanation: When BT returns search results, they gather all associated data and return a large (serialized) response object to the client. In our case some of the subscriptions had a large number of associated transactions, which makes the process of fetching, serializing and returning them to the client slow. When making a request, the BT gateway returns pages in groups of 50 with a default timeout of 60 seconds. Any group with several large response objects will likely time out and produce a 504 error. The solution: To avoid this delay, instead of using the items method, we can use the id method from the ResourceCollections class and return just the ids of the objects. With the individual subscription id, we can fetch the individual subscription and only the attributes we need, like so: subscriptions = gateway.subscription.search( braintree.SubscriptionSearch.status.in_list( braintree.Subscription.Status.Active ) ) subscription_ids = subscriptions.ids def find_customer_id(id): subscription = gateway.subscription.find(id) payment_method = gateway.payment_method.find(subscription.payment_method_token) return (payment_method.customer_id, subscription.price) Hope this will help someone else!
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52503289
answers question: http://stackoverflow.com/q/52503289
score: 1
upvote count: 1

http://stackoverflow.com/comment/92016213
type: Comment
type: QuestionComment
has text: @AndrewSvetlov done
comment on: http://stackoverflow.com/q/52532075
score: 0

http://stackoverflow.com/comment/91828486
comment on: http://stackoverflow.com/q/52442837
has text: `2*(n+1)+1` is the first element and then you just add 2 to the next element until you have total `n` elements. Would be straightforward using a range/arange/for loop. Try it out
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91917350
comment on: http://stackoverflow.com/a/52485716
has text: Didn't know that. Thank you very much. Hope this will help others.
score: 0
type: AnswerComment
type: Comment

bokeh
tags question: http://stackoverflow.com/q/52588443
type: Tag
tags question: http://stackoverflow.com/q/52451654
tags question: http://stackoverflow.com/q/52527718
tags question: http://stackoverflow.com/q/52489650
tags question: http://stackoverflow.com/q/52539639
tags question: http://stackoverflow.com/q/52488701
tags question: http://stackoverflow.com/q/52540568
tags question: http://stackoverflow.com/q/52461910
tags question: http://stackoverflow.com/q/52548670
tags question: http://stackoverflow.com/q/52556002
tags question: http://stackoverflow.com/q/52437891
tags question: http://stackoverflow.com/q/52542140
tag name: bokeh
tags question: http://stackoverflow.com/q/52433129

http://stackoverflow.com/q/52587144
favorite count: 0
has title: DRF: Nested serializers with depth > 1
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
has body: I'm looking into "nested-nested" serializers, where there's a nested serializer nested in another one. It's a cooking service where a recipe has multiple directions, each having multiple ingredients. I set that up with foreign keys. Here are my models: class Category(models.Model): """Model representing a recipe category""" name = models.CharField(max_length=200, help_text="Enter a recipe category (e.g Baking)") def __str__(self): """String for representing the Model object.""" return self.name class Ingredient(models.Model): """Model representing an ingredient in a direction""" name = models.CharField(max_length=250, help_text="The ingredient's name") quantity = models.CharField(max_length=200, help_text="How much of this ingredient.") direction = models.ForeignKey("Direction", help_text="This ingredient's direction", on_delete=models.CASCADE, related_name='ingredients') def __str__(self): """String for representing this recipe ingredient""" return f'{self.quantity} {self.ingredient}' class Direction(models.Model): """Model representing a step in a recipe""" title=models.CharField(max_length=200) text=models.TextField(blank=True, help_text="Describe this step.") recipe=models.ForeignKey("Recipe", help_text="This direction's recipe", on_delete=models.CASCADE, related_name='directions') def __str__(self): """String for representing the Direction""" return self.title class Recipe(models.Model): """Model representing a recipe.""" title = models.CharField(max_length=200) notes = models.TextField(max_length=1000, help_text="Enter notes, reviews, ...") photos = models.ImageField(null=True, blank=True) category = models.ForeignKey(Category, help_text="This recipe's category", on_delete=models.CASCADE, related_name='recipes') def __str__(self): """String for representing the Model object.""" return self.title def get_absolute_url(self): """Returns the url to access a detail record for this recipe.""" I read the docs and thought I could just use a nested serializer in anothe…
type: Question
downvote count: 0
tagged with: django-rest-framework

http://stackoverflow.com/q/52551147
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52551934
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/38088652
has body: I want to group by age and name and assign different poeple in a same category. Initial Data: name age salary abc 24 1000 def 27 2000 ghi 25 3000 jkl 24 1000 mno 25 3000 Final Data: name age salary group abc 24 1000 1 def 27 2000 2 ghi 25 3000 3 jkl 24 1000 1 mno 25 3000 3
has answer: http://stackoverflow.com/a/52551487
tagged with: dataframe
has title: How to groupby two columns and assign a category(number) in a new column?
score: 0
tagged with: pandas
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52461883
accepted answer: http://stackoverflow.com/a/52461943
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
has title: Rearranging headers in linregress python
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52461943
has body: I am using Linregress in Python to get slope, intercept, etc The output is a csv file. However, the data output does not have headers in columns. The data output is as: slope=5.562, intercept=223.5 etc An image is attached herewith with what I see in Jupyter notebook(left image) vs what I need to have the data as (right image). t is rearranging the data so that the headers are not seen horizontally but vertically. Will be great if I can get help on this. Thanks for reading!!
upvote count: 1
tagged with: scipy
type: Question

http://stackoverflow.com/comment/91969539
type: AnswerComment
score: 0
type: Comment
has text: @NabilGhodbane thanks for the answer! Your method works generally, just not for my particular usecase as somethingelse.py is intended to reside in different drives and different locations. Not sure why you were downvoted, it's a good solution.
comment on: http://stackoverflow.com/a/52502784

http://stackoverflow.com/comment/91830728
type: Comment
comment on: http://stackoverflow.com/q/52443783
has text: added a non-regex approach to the dupes answers.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91903355
comment on: http://stackoverflow.com/q/52480212
has text: I don't think you need to, since JSON is just strings. As long as you don't do the js equivalent of `eval(string)`, you'll be fine.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/52459951
type: Answer
has body: In a word, no. No meaningful hash function can be applied in reverse. What hash functions do is that they try to create a "signature" of the original message. The signature must be small enough, and is usually used for verification or as an index into some storage. To this end, the output domain must be significantly smaller than the input domain, or in other words, multiple inputs could correspond to the same output. In your case, strings "000" and "000000000" will have the same hash value, and you will have no way of distinguishing one from the other given just the hash.
answers question: http://stackoverflow.com/q/52459179
score: 0

http://stackoverflow.com/comment/91939187
has text: Ideally I'd be interested in reshaping the subplots post-hoc, as described above, rather than digging in the internals of plot_prob_atlas which won't generalize to another problem. But here are some details on my particular issue: nilearn.plotting does accept an axes so I had tried initializing a subplot to the appropriate size and plotting each slice one by one by passing the appropriate ax. This approach hangs, but even if it did work there is no color correspondence between slices (region 1 may be blue in one slice and red in another) because of the multiple calls. Thanks for the help!
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52480756

http://stackoverflow.com/a/52527837
type: Answer
answers question: http://stackoverflow.com/q/52527750
has body: You can apply the same thing you do to the hard-coded 1 in __str__ to accountType in __init__: self.accountType = AccountType(accountType) Even though you can now get rid of self.d and use self.accountType, I would recommend not using the integer value in the initialization to begin with: test = BankAccount("Max", AccountType.SAVINGS) This is much clearer than using a magic number. The update to __init__ will accept both the enums and their values.
has comment: http://stackoverflow.com/comment/91995671
score: 0

http://stackoverflow.com/a/52438618
has body: FIRST QUESTION: I am pretty sure that .readline() is faster than .read(). Plus, the fastest way based my test is to do lopping like: with open(file, 'r') as f: for line in f: ... SECOND QUESTION: I am not quite sure abut this. you may consider to use yield. There is a code snippet you may refer: def myreadlines(f, newline): buf = "" while True: while newline in buf: pos = buf.index(newline) yield buf[:pos] buf = buf[pos + len(newline):] chunk = f.read(4096) if not chunk: # the end of file yield buf break buf += chunk with open("input.txt") as f: for line in myreadlines(f, "{|}"): print (line)
type: Answer
answers question: http://stackoverflow.com/q/52438356
score: 0

http://stackoverflow.com/comment/120429570
comment on: http://stackoverflow.com/q/52458506
has text: What I plan to do (and haven't yet) is to create my own local PyPI repository mirror on my laptop. the idea is to have all the packages I normally used cached locally, then as I create and delete virtual environments, they can draw from my local repository rather than requiring internet connectivity.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52463709
score: 0
has body: I am newly learning matplotlib. I have plotted some data in a surface plot. But without colors it looks monotonous. I have referred this matplotlib example document and used the same code for plotting. I am getting the above mentioned error in this line surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) I have tried upgrading the matplotlib module and still getting the same error. Could anyone help me in fixing this. Thank you in advance.
favorite count: 0
tagged with: python-3.x
has title: AttributeError: module 'matplotlib' has no attribute 'coolwarm'
has comment: http://stackoverflow.com/comment/91869388
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: matplotlib
upvote count: 1
downvote count: 1
type: Question
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/91873455
has comment: http://stackoverflow.com/comment/91869400

http://stackoverflow.com/comment/91858898
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52458265
has text: I am wondering looking at the down vote of this question. May i know the reason for that.
score: 0

http://stackoverflow.com/q/52504886
has answer: http://stackoverflow.com/a/52505736
answer count: 1
has comment: http://stackoverflow.com/comment/91951836
score: 0
tagged with: python
has title: Django Class-based View and URL configuration
has body: I am trying to learn Django and I am stuck with Class-based views and URLconf. From what I understand I should see my test.html at localhost/app1/test1/test/test.html, but I get an error page not found. I am not sure what I am doing wrong. #~/project_folder/mysite/ulrs.py urlpatterns = [ path('admin/', admin.site.urls), path('app1/test1/', include("app1.urls")), ] #~/project_folder/app1/urls.py urlpatterns = [ path('test/', TemplateView.as_view(template_name="test.html"), name="home"), ] #~/project_folder/static/templates test.html #~/project_folder/mysite/settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'static/templates'), ], 'APP_DIRS': True, ... } STATIC_URL = os.path.join(BASE_DIR, 'static/')
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/91952053
type: Question

http://stackoverflow.com/comment/91975747
type: QuestionComment
type: Comment
has text: @timgeb sir...can u please tell me if there is any way to fix this error
comment on: http://stackoverflow.com/q/52518048
score: 0

http://stackoverflow.com/q/52472975
has body: I'm learning pyqt5, and specifically how to use it with the QT Designer. I'm sort of following the turorial HERE. However in this tutorial they are converting the XML interface to Python code with pyuic5, while I'm trying to import it dynamically with uic.loadUi("myui.ui"). In the tutorial we define a slot with the signals and slot editor named " browseSlot". When I try to run/compile, at the line dlg = uic.loadUi("myui.ui") I get the error: AttributeError: 'QMainWindow' object has no attribute 'browseSlot' I think what's going on is that QT Designer connects a signal to the slot 'browseSlot' but because a 'browseSlot' method isn't defined in the myui.ui, the error is thrown, because there is no way for the interpreter to know I'm referring to a method that is outside the UI interface file. (In this case, in the module that loads the interface). As far as I can tell QT Designer only lets me connect signals to slots, not define a whole new one. I think that way this is handled in other frameworks is that there will be an abstract method that needs over riding. So what can I do in this situation to make it work? from PyQt5 import QtCore, QtGui, QtWidgets, uic from PyQt5.QtCore import QObject, pyqtSlot import sys app = QtWidgets.QApplication([]) dlg = uic.loadUi("myui.ui") @pyqtSlot def returnPressedSlot(): pass @pyqtSlot def writeDocSlot(): pass @pyQt def browseSlot(): pass dlg.show() sys.exit(app.exec())
answer count: 2
tagged with: pyqt
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52476717
tagged with: python
has title: pyqt5, Receiving AttributeError: 'QMainWindow' object has no attribute 'browseSlot'
type: AnsweredQuestion
tagged with: pyqt5
upvote count: 1
accepted answer: http://stackoverflow.com/a/52476717
possible better answer: http://stackoverflow.com/a/58058788
type: Question
has answer: http://stackoverflow.com/a/58058788

http://stackoverflow.com/a/52505064
upvote count: 10
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52505021
has body: Yes, those are the same. Python's augmented assignment is not an expression, it is a statement, and doesn't play in expression precedence rules. += is not an operator, and instead it's part of the augmented assignment statement syntax. So everything to the right of the += is an expression, but += itself is not, so the assignment will always be handled last. And because (augmented) assignment is not an expression, it can't produce a value to use in a surrounding expression either. There is no (a += b) / 2, that'd be a syntax error, and certainly no if (a += b / 2): or other such shenanigans. See the reference documentation on Augmented assignment statements, which states the grammar is: augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression) augtarget ::= identifier | attributeref | subscription | slicing augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**=" | "&gt;&gt;=" | "&lt;&lt;=" | "&amp;=" | "^=" | "|=" So the augop is part of the statement syntax, and only the part following is an expression (specifically, either a expression_list or yield_expression grammar rule). Furthermore, the explanation shows: An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once. So the augtarget part is handled first, the expression list (or yield expression) is handled second, and then the augmented assignment applies the operator and assigns back the result. Furthermore, the expressions reference documentation does include a precedence table, but that table doesn't include assignments (augmented or otherwise), simply because assignments are not expressions but statements.
score: 10
answers question: http://stackoverflow.com/q/52505021
downvote count: 0

http://stackoverflow.com/comment/91849041
type: Comment
type: QuestionComment
score: 0
has text: I don't understand the purpose of the `more` here, you are going through the contents only (your not appending any more to contents). Oh, maybe I see, you want to break if `more is False`?
comment on: http://stackoverflow.com/q/52452491

http://stackoverflow.com/a/52585946
upvote count: 2
has body: Add column VAR_TEXT_ to loc for Series: x = df1.loc[df1['VAR_NAME_'] == 'employmentType', 'VAR_TEXT_'] print(x) 21 Employed Name: VAR_TEXT_, dtype: object And then use next with optional argument, if there are no elements to extract: a = next(iter(x), 'no matched value') print (a) Employed x=df1.loc[df1['VAR_NAME_'] == 'aaa', 'VAR_TEXT_'] print(x) Series([], Name: VAR_NAME_, dtype: object) a = next(iter(x), 'no matched value') print (a) no matched value
downvote count: 0
answers question: http://stackoverflow.com/q/52585881
type: Answer
score: 2

http://stackoverflow.com/comment/91835239
type: Comment
has text: If I well understood you wand to distinguish the points of the two contours ? why not simply do : cv2.drawContours(im, cnt, -1, (255, 0, 0), 1) cv2.drawContours(im, cnt_new, -1, (0, 0, 255), 1) rather than: cv2.drawContours(im, cnt, -1, (255, 0, 0), 1) cv2.drawContours(im, cnt_new, -1, (0, 0, 255), 1)
comment on: http://stackoverflow.com/a/52432922
score: 0
type: AnswerComment

http://stackoverflow.com/a/52512686
type: Answer
answers question: http://stackoverflow.com/q/52504347
score: 32
has comment: http://stackoverflow.com/comment/91965099
has comment: http://stackoverflow.com/comment/91966011
downvote count: 0
upvote count: 32
has comment: http://stackoverflow.com/comment/91991512
has body: Using an alias to mark the meaning of a value can be misleading and dangerous. If only a subset of values are valid, a NewType should be used instead. Recall that the use of a type alias declares two types to be equivalent to one another. Doing Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures. Simple aliasing works both ways: the alias URL = str means any URL is a str and also means any str is a URL – which is usually not correct: A URL is a special kind of str and not any can take its place. An alias URL = str is a too strong statement of equality, as it cannot express this distinction. In fact, any inspection that does not look at the source code does not see the distinction: In [1]: URL = str In [2]: def foo(bar: URL): ...: pass ...: In [3]: foo? Signature: foo(bar: str) Consider that you alias Celsius = float in one module, and Fahrenheit = float in another. This signals that it is valid to use Celsius as Fahrenheit, which is wrong. Unless your types do cary separative meaning, you should just take a url: str. The name signifies the meaning, the type the valid values. That means that your type should be suitable to separate valid and invalid values! Use aliases to shorten your hints, but use NewType to refine them. Vector = List[float] # alias shortens URL = NewType("URL", str) # new type separates

http://stackoverflow.com/a/52497212
score: -1
has comment: http://stackoverflow.com/comment/91934869
has comment: http://stackoverflow.com/comment/91934812
downvote count: 2
has comment: http://stackoverflow.com/comment/91935397
type: Answer
has comment: http://stackoverflow.com/comment/91935177
has comment: http://stackoverflow.com/comment/91935330
upvote count: 1
has body: def examplefunc(x,y,**kwargs): print(kwargs['extraarg']) if ('extraarg' in kwargs)==True print(kwargs['extraarg']) print("This is not printed") if 'extraarg' in kwargs: print("This is printed") if __name__ == "__main__": examplefunc(3,2,extraarg=True) output: True True This is not printed This is printed
answers question: http://stackoverflow.com/q/52497159
has comment: http://stackoverflow.com/comment/91936713

http://stackoverflow.com/comment/92081482
type: AnswerComment
has text: when I did that nothing changed. I will try and label the axis now myself. When we calculate the absolute error and we calculating it and each step size from 0 to 20 at Xo and comparing it to cosXo
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52571295

http://stackoverflow.com/comment/92204499
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52612403
has text: I have added some examples to my answer on how to benchmark things.
score: 0

http://stackoverflow.com/comment/91894886
has text: This might also be a candidate for [Code Review](https://codereview.stackexchange.com/).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52476527
score: 3

http://stackoverflow.com/comment/91857436
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52457302
has text: k I'm going to try now
type: AnswerComment

http://stackoverflow.com/q/52544331
tagged with: http://stackoverflow.com/tag/csv
has body: I am looking for a python 3 example, I need to open a csv file, look at a certain column in the CSV file, create a new column from those values in a new csv file, and change some values in the new column based on a match from a list. Any help is greatly appreciated. Thanks
tagged with: python
score: 0
has title: Python Array Column Match in a CSV File
has comment: http://stackoverflow.com/comment/92028661
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92028584
answer count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/91880863
score: 0
comment on: http://stackoverflow.com/q/52466496
type: Comment
type: QuestionComment
has text: Check the browser version and chromedriver version compatibility. Chromedriver devs like to indicate incompatibility by crashing the whole world instead of an error message... [Here](http://chromedriver.chromium.org/downloads) you can find which chromedriver supports which chrome browser. (As a side note I'm surprised that there is a chromedriver binary for rpi/arm)

http://stackoverflow.com/comment/91932257
has text: thanks @BryceH but I cant just upload to S3. We're doing some custom stuff with files before uploading them, so we really need to proxy them through our app.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52470229

http://stackoverflow.com/q/52563371
tagged with: model-fitting
score: 0
has comment: http://stackoverflow.com/comment/92067239
upvote count: 1
downvote count: 1
has title: Parameter extraction from a spectrum
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: regression
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/92066704
type: Question
has comment: http://stackoverflow.com/comment/92071844
has body: Let's say for a plant leaf I have a spectrum from 400-1000nm with parameters like temperature, moisture, sunlight, soil. Now I have multiple samples with different leaves with respective parameter values and a spectrum for each. Once I have this database, now I would like to extrapolate the values of temperature, moisture, sunlight and soil for an unknown leaf spectra by comparing with the database. What would be the right way to find the parameter values? Thanks!
has comment: http://stackoverflow.com/comment/92075979
has comment: http://stackoverflow.com/comment/92080394
tagged with: statistics

http://stackoverflow.com/q/52473960
type: AnsweredQuestion
upvote count: 3
tagged with: django
accepted answer: http://stackoverflow.com/a/52474026
type: Question
score: 3
has body: Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name 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) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Avg,Max,Min,Count,F,Q class CatalogSerializer(serializers.HyperlinkedModelSerializer): dynamic_data = serializers.SerializerMethodField() class Meta: model = Catalog fields = '__all__' def get_dynamic_data(self, obj): totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs')) totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price')) print(totalpieces["total_pieces"],totalprice["total_price"]) return totalpieces["total_pieces"],totalprice["total_price"] class UserSerializer(serializers.ModelSerializer): # name = serializers.StringRelatedField() company_name = serializers.CharField() class Meta: model = User fields = '__all__' class CatalogData(serializers.ModelSerializer): class Meta: model = Catalog fields = ('name', 'no_of_pcs', 'per_piece_price') class CompanySerializer(serializers.ModelSerializer): # catalog_details = serializers.SerializerMethodField() # name = serializers.StringRelatedField() catalog = CatalogData(many=True) user = UserSerializer(many=True) class Meta: model = Company fields = ('name', 'phone_number', 'catalog','user…
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52474026
tagged with: python
has title: How to get aggregation in django rest framework inside same api

http://stackoverflow.com/a/52556300
has comment: http://stackoverflow.com/comment/92054899
has comment: http://stackoverflow.com/comment/92053333
type: Answer
has body: Apache airflow will do the job Each DAG may or may not have a schedule, which informs how DAG Runs are created. schedule_interval is defined as a DAG arguments, and receives preferably a cron expression as a str, or a datetime.timedelta object. Alternatively, you can also use one of these cron “preset”
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/52556233
upvote count: 0

http://stackoverflow.com/a/58103736
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52451154
type: Answer
upvote count: 2
has body: I had the same issue. I found out that all works fine using python run.py instead of flask run.

http://stackoverflow.com/comment/91991951
type: Comment
type: QuestionComment
has text: Hello Juan Carlos. It is difficult to understand what you are asking. You could be asking how to draw the form shown in your image; you could be asking how to write code that is executed when the button is clicked; you could be asking how to write code that queries an SQL database; or you could be asking how to write code that will store the results of the SQL query in an Excel file. Your readers don't want to waste your time (or their own time) telling you how to do things you already know how to do. Please edit your post to focus on one question - see [ask] and [mcve] for more guidance.
score: 0
comment on: http://stackoverflow.com/q/52500524

http://stackoverflow.com/q/52539729
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92019328
has comment: http://stackoverflow.com/comment/92019241
favorite count: 0
tagged with: python
has body: I tested the following unicode: In [34]: snowman = "\u2603" In [35]: snowman Out[35]: '☃' encode snowman In [36]: ds = snowman.encode("utf-8") In [37]: ds Out[37]: b'\xe2\x98\x83' However, when I checked it with ord() In [38]: ord('☃') Out[38]: 9731 It's different with b'\xe2\x98\x83' How could I understand it?
upvote count: 6
has comment: http://stackoverflow.com/comment/92019788
type: AnsweredQuestion
score: 6
has title: '☃'.encode("utf-8") is different from ord('☃')
has comment: http://stackoverflow.com/comment/92019490
type: Question
has answer: http://stackoverflow.com/a/52540054
accepted answer: http://stackoverflow.com/a/52540054

http://stackoverflow.com/q/52502689
has comment: http://stackoverflow.com/comment/91946127
type: Question
score: 3
has answer: http://stackoverflow.com/a/52502784
has body: During the course of my python program, I have generated the following string "D:\something_else.py" Lets say there are other resources in D: that something_else.py requires. How would I go about running something_else.py from my code, which let's say is being run from C:\Users\Someone\Desktop? Right now I'm using the following: from subprocess import call call(["python",pythloc]) This gives me an error as it's able to find only something_else.py and is unable to find the other resources that something_else.py needs which are in the same folder as something_else.py
has title: How do I run a python file in a different directory from another python file?
has comment: http://stackoverflow.com/comment/91969434
has comment: http://stackoverflow.com/comment/91949476
tagged with: python-import
has comment: http://stackoverflow.com/comment/91946045
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52502815
has comment: http://stackoverflow.com/comment/91969440
has comment: http://stackoverflow.com/comment/91969421
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91946675
upvote count: 3
type: UnansweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/91969429

http://stackoverflow.com/comment/92081504
type: QuestionComment
comment on: http://stackoverflow.com/q/52560967
has text: Thanks for the suggestion! It still runs out of order even with this change. Canopy's code editor is just idiosyncratic, I guess.
score: 0
type: Comment

http://stackoverflow.com/q/52572612
has comment: http://stackoverflow.com/comment/92081651
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92082449
tagged with: python
tagged with: regex
type: AnsweredQuestion
has title: Why is this Python Regex Expression not working?
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92082061
type: Question
has comment: http://stackoverflow.com/comment/92081655
has answer: http://stackoverflow.com/a/52573446
accepted answer: http://stackoverflow.com/a/52573446
has body: I'm new to regex expressions, and python. But created a script that uses multiple regex expressions. Two of which, work when run through Regexpal.com. But when I run the script. They do not work. Script works fine, when I run my other regex expressions. Here are the two that are not working. Can someone explain why they do not work, and give me the correct expressions? I tested these three different ones, none work. I have a line with Patient: Höler, Adam* 10.07.1920 ID-Nr: 1118111111 And I want to extract Patient: Höler, Adam. Patient:\s.*\* Patient:.*?([*]) Patient:.*\* I have another line with VCI-exsp = 20mm; And I'm trying to extract VCI-exsp=20mm (get rid of the ';'). This is the regex expression I made, but it also works on regexpal.com (and on Atom), but not when I run the script. VCI-exsp =[^;]* Here is the scripts I have, regexText is a text file full of my regex expressions. And Realthingnotaphony is the text file with the text I'm trying to extract data from. If the problem is that I'm not including r, how would I inject it into the expressions? regexarr = [] with open("regexText.txt") as fw: for line in fw: regexarr.append(re.compile(line)) matchs = [] count = 1 with open('Realthingnotaphony.txt') as f: for line in f: for regexp in regexarr: test = re.search(regexp, line) if test != None: matchs.append(test) print(test.group(0))
score: 0

linear-algebra
tags question: http://stackoverflow.com/q/52574594
tags question: http://stackoverflow.com/q/52467168
type: Tag
tags question: http://stackoverflow.com/q/52443302
tags question: http://stackoverflow.com/q/52471817
tags question: http://stackoverflow.com/q/52439564
tags question: http://stackoverflow.com/q/52585356
tag name: linear-algebra

http://stackoverflow.com/a/52741693
answers question: http://stackoverflow.com/q/52580318
score: 0
type: Answer
has body: Here is what works for me after I fixed stuff from your code. I used sympy factorial. from sympy import * x = symbols('x') def taylor(f,x,x0, n): t = 0 for i in range(0,n): t = t + ((diff(f,x,i).subs(x,x0))/(factorial(i))) * (x ** i) return t pprint(taylor(sin(x),x,Rational(1,32),4)) and the answer I get is 3 2 x ⋅cos(1/32) x ⋅sin(1/32) - ──────────── - ──────────── + x⋅cos(1/32) + sin(1/32) 6 2

http://stackoverflow.com/comment/91889275
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52473766
type: QuestionComment
has text: @jezrael check it now

http://stackoverflow.com/a/52528139
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52526476
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52526476
upvote count: 1
type: Answer
has body: If you're processing columns into a dict of names with accumulated values, consider a defaultdict. Given import itertools as it import collections as ct pred = lambda x : 5 &lt; x &lt; 16 # Sample data (bad + good) values = list(range(-10, -5)) + list(range(6, 11)) names = ["Nick"] * 5 + ["James"] * 5 Code def make_dict(names, values): """Return a defaultdict of names and listed values.""" data = ct.defaultdict(list) for name, value in zip(names, values): data[name].append(value) return data def process_dict(data, pred): """Return a list of strings; pass if values satisfy the predicate.""" result = [] for name, counts in data.items(): if all(pred(v) for v in counts): result.append(f"{name} passed.\n") else: result.append(f"{name} failed.\n") return result Demo d = make_dict(names, values) d # defaultdict(list, {'Nick': [-10, -9, -8, -7, -6], 'James': [6, 7, 8, 9, 10]}) process_dict(d, pred) # ['Nick failed.\n', 'James passed.\n'] Details we use a sample data of names and values make_dict() returns a dictionary of name-values pairs. defaultdict makes an empty list if a key is missing, so we can safely append values without a KeyError; this obviates chunking. process_dict() validates passing data using a predicate. A predicate is a function that returns True or False based on a condition, e.g. 5 &lt; x &lt; 16.

http://stackoverflow.com/q/52543717
downvote count: 0
favorite count: 0
has body: I am trying to build a spark schema the want to explicity supply while creating the dataframe I can generate the json schema using below from pyspark.sql.types import StructType # Save schema from the original DataFrame into json: schema_json = df.schema.json() which gives me {"fields":[{"metadata":{},"name":"cloud_events_version","nullable":true,"type":"string"},{"metadata":{},"name":"data","nullable":true,"type":{"fields":[{"metadata":{},"name":"email","nullable":true,"type":"string"},{"metadata":{},"name":"member_role","nullable":true,"type":"string"},{"metadata":{},"name":"reg_source_product","nullable":true,"type":"string"},{"metadata":{},"name":"school_type","nullable":true,"type":"string"},{"metadata":{},"name":"year_in_college","nullable":true,"type":"long"}],"type":"struct"}},{"metadata":{},"name":"event_time","nullable":true,"type":"string"},{"metadata":{},"name":"event_type","nullable":true,"type":"string"},{"metadata":{},"name":"event_type_version","nullable":true,"type":"string"},{"metadata":{},"name":"event_validated_ts","nullable":true,"type":"string"},{"metadata":{},"name":"event_validation_status","nullable":true,"type":"string"},{"metadata":{},"name":"extensions","nullable":true,"type":{"fields":[{"metadata":{},"name":"client_common","nullable":true,"type":{"fields":[{"metadata":{},"name":"adobe_mcid","nullable":true,"type":"string"},{"metadata":{},"name":"adobe_sdid","nullable":true,"type":"string"},{"metadata":{},"name":"auth_state","nullable":true,"type":"string"},{"metadata":{},"name":"uuid","nullable":true,"type":"string"},{"metadata":{},"name":"client_experiments","nullable":true,"type":"string"},{"metadata":{},"name":"client_ip_address","nullable":true,"type":"string"},{"metadata":{},"name":"device_id","nullable":true,"type":"string"},{"metadata":{},"name":"page_name","nullable":true,"type":"string"},{"metadata":{},"name":"referral_url","nullable":true,"type":"string"},{"metadata":{},"name":"url","nullable":true,"type":"string"},{"metadata":…
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54994857
score: 2
has title: Build spark schema from json schema
has answer: http://stackoverflow.com/a/52545723
type: Question
has answer: http://stackoverflow.com/a/52549047
tagged with: pyspark
tagged with: apache-spark
answer count: 3

http://stackoverflow.com/comment/91848343
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52452447
has text: i see. i will dabble further. thank you for your inputs sirs. :) /ogs

http://stackoverflow.com/a/52562412
type: AcceptedAnswer
downvote count: 0
has body: So it appears the problem was my virtualenvironment kept wanting to install pip packages to the global directory and not its own. What fixed it was deleting the old virtualenv and initializing a new one with the command: virtualenv &lt;&lt;name of env&gt;&gt; --python=python2.7 I'm not entirely sure why this worked. I would love any clarification in the comments.
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52541033
answers question: http://stackoverflow.com/q/52541033

http://stackoverflow.com/a/52564100
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52563922
upvote count: 1
has body: One way you could achieve this would be by frequently polling the currently opened windows titles this recipe. Make a function that attempts to find a window object with the expected title and returns True if it finds one, False otherwise. Now you can have a while True: loop that calls that function, checks if it returns a True (which should happen when that folder is opened, if it's opened using the Windows Explorer with the option to show the folder name in the title bar), and waits a few seconds before trying again. Maybe you can have additional checks on the hwnd object to make sure it's an explorer process and not something else, I don't know. I don't know much about the windll function, maybe there's a way to avoid polling and be notified by some kind of event when the status of the windows change, which would make the code more efficient and a bit more resilient. Full working example after correcting a few things (tested on Windows 7 with the "Display the full path in the title bar" Folder Option turned on): import ctypes import time EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW IsWindowVisible = ctypes.windll.user32.IsWindowVisible class FoundWindow(Exception): pass def titleExists(title): status = [] def foreach_window(hwnd, lParam): if IsWindowVisible(hwnd): length = GetWindowTextLength(hwnd) buff = ctypes.create_unicode_buffer(length + 1) GetWindowText(hwnd, buff, length + 1) if buff.value == title: status.append(True) return True EnumWindows(EnumWindowsProc(foreach_window), 0) return len(status) &gt; 0 while True: if titleExists(u"C:\Windows"): print('The "C:\Windows" directory was opened!') exit(0) time.sleep(1) I'm bad at python so I had to resort to ugly tricks to keep track of what happened inside the EnumWindowsProc calls, t…

http://stackoverflow.com/comment/98536867
type: AnswerComment
comment on: http://stackoverflow.com/a/52549728
type: Comment
has text: cool, there are very interesting comments above. I migrated my code from python 2.7 to python 3.7. I get the same error with an OrderedDict. Shouldn't I do `deepcopy` instead of `copy`?
score: 0

http://stackoverflow.com/comment/92205119
type: Comment
has text: Purr, can you help me with this post by chance? https://stackoverflow.com/questions/52635962/python-statsmodels-linear-regression
comment on: http://stackoverflow.com/a/52563013
type: AnswerComment
score: 0

http://stackoverflow.com/a/52435190
type: Answer
answers question: http://stackoverflow.com/q/52434990
score: 3
accepted answer of: http://stackoverflow.com/q/52434990
upvote count: 3
has body: Your desired result is impossible since np.arrays can only have one data type (which would usually be one of the numerical types, e.g. float, int,...)... unless you choose the generic type dtype=object, but then you loose all the numpy goodness (i.e. all the optimization working on numerical values). So why do you want to do this? If this is really what you want then try this: array = np.array(['1', '2', '3', 'string']) def safe_float(x): try: x = float(x) except: pass return x array = np.array(list(map(safe_float, array)), dtype=object) print(array) array([1.0, 2.0, 3.0, 'string'], dtype=object)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91809444
comment on: http://stackoverflow.com/a/52432408
type: AnswerComment
has text: I did upvote because it is helpful, but I do think my answer is more elegant :P
type: Comment
score: 1

http://stackoverflow.com/comment/91824472
has text: Sounds like you need to get over thinking that Python variables are just like C/C++'s. Also, Python doesn't have pointers, so saying "`b` points to `a`" doesn't really make sense.
score: 0
comment on: http://stackoverflow.com/q/52440701
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52574968
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/92085797
answers question: http://stackoverflow.com/q/52572679
accepted answer of: http://stackoverflow.com/q/52572679
score: 0
has body: Your code is correct! After you commit the profile, you can get the valid id. profile = Profile(name='some_profile') -&gt; print(profile.name) some_profile -&gt; print(profile.id) None # commit session.add(profile) session.commit() # print saved profile -&gt; print(profile.name) some_profile -&gt; print(profile.id) ff36e5ff-16b5-4536-bc86-8ec02a53cfc8

http://stackoverflow.com/a/52580493
has body: You can use a comprehension with chain.from_iterable and a ternary statement: from itertools import chain L = list('abca') # ['a', 'b', 'c', 'a'] rep_key, rep_val = ('a', ['a_1', 'b_1', 'c_1']) res = list(chain.from_iterable([i] if i != rep_key else rep_val for i in L)) ['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52580426
type: Answer
answers question: http://stackoverflow.com/q/52580426
upvote count: 3

http://stackoverflow.com/comment/92420374
type: QuestionComment
comment on: http://stackoverflow.com/q/52562941
score: 0
has text: @PM2Ring Sorry replying late. Thanks for your reply, and yes both of your suggestions are quicker ways of doing what I want to achieve. Thanks
type: Comment

http://stackoverflow.com/q/52523757
possible better answer: http://stackoverflow.com/a/52533084
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/52533084
has answer: http://stackoverflow.com/a/71472035
tagged with: pagination
has comment: http://stackoverflow.com/comment/91987135
has comment: http://stackoverflow.com/comment/91988287
accepted answer: http://stackoverflow.com/a/52533322
tagged with: api
has comment: http://stackoverflow.com/comment/91989614
downvote count: 0
has comment: http://stackoverflow.com/comment/91994662
favorite count: 0
has answer: http://stackoverflow.com/a/73464291
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: i want to get these transactions: https://www.omniexplorer.info/address/1FoWyxwPXuj4C6abqwhjDWdz6D4PZgYRjA The first page is no problem with: import requests headers = { 'Content-Type': 'application/x-www-form-urlencoded', } data = [('addr', '1FoWyxwPXuj4C6abqwhjDWdz6D4PZgYRjA')] response = requests.post('https://api.omniexplorer.info/v1/address/addr/details/', headers=headers, data=data) response = response.json() print(response["transactions"]) But how can i call page 2 for example? I tried with params "params = {'page': 2}" but that doesnt work Would appreciate any help! regards
has answer: http://stackoverflow.com/a/52533322
score: 1
has comment: http://stackoverflow.com/comment/91987324
has title: Requests - POST pagination?
upvote count: 1

http://stackoverflow.com/q/52580892
tagged with: debugging
has body: Often when I need to debug the value of a variable at runtime I use print(). But when there are many variables, I need to identify the name of the variable along with the value. This way, with several variables, print becomes more laborious: print ("x=", x, "y=", y, "x+y*2=", x+y*2) The ideal would be a simple command, such as: debug (x, y, x + y * 2) ... which would automatically add variables as in the print above. The idea would be just to have a simple and quick command to facilitate debugging since during this process it would not be nice to lose focus by building a series of commands just to debug. I already use Pycharm which has an excellent debugging. The problem is that to follow the evolution of values at runtime, I have to use print() because the Pycharm debugger shows the values only during a breakpoint. Hence my question, if I had a facilitator, something simple? Is there any simple command to do this?
has comment: http://stackoverflow.com/comment/92101596
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92098840
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52595175
upvote count: 1
tagged with: python
has title: Debug command showing name and value of variable?
score: 1
type: Question

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/52456976
tags question: http://stackoverflow.com/q/52452190
tags question: http://stackoverflow.com/q/52533006
tags question: http://stackoverflow.com/q/52551172
tags question: http://stackoverflow.com/q/52435807
type: Tag
tags question: http://stackoverflow.com/q/52559882

http://stackoverflow.com/a/52487774
has comment: http://stackoverflow.com/comment/91918325
has comment: http://stackoverflow.com/comment/91917029
has comment: http://stackoverflow.com/comment/91916979
has comment: http://stackoverflow.com/comment/91917001
type: Answer
has body: Let's try a generator-based solution using itertools.cycle and islice: from itertools import cycle, islice def split_list(lst, n): it = cycle(lst) for i in range(len(lst) // n + len(lst) % n): yield list(islice(it, n)) Call the function like this: &gt;&gt;&gt; a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] &gt;&gt;&gt; list(split_list(a_list, 3)) [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]] I personally prefer a generator here because the chunks are yielded one at a time, efficiently. If you want everything at once, you call list() on the result (like I've done).
has comment: http://stackoverflow.com/comment/91917634
has comment: http://stackoverflow.com/comment/91917603
score: 3
has comment: http://stackoverflow.com/comment/91918369
upvote count: 3
answers question: http://stackoverflow.com/q/52487712
downvote count: 0

3d
tags question: http://stackoverflow.com/q/52550460
type: Tag
tags question: http://stackoverflow.com/q/52468325
tags question: http://stackoverflow.com/q/52474045
tag name: 3d
tags question: http://stackoverflow.com/q/52495077
tags question: http://stackoverflow.com/q/52572197
tags question: http://stackoverflow.com/q/52463599

http://stackoverflow.com/comment/92058529
comment on: http://stackoverflow.com/q/52559922
has text: @FlorianWeimer I edited my post and added my attempt
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91886353
has text: If there's no explicit name in the language definition, then it might have none and you just call it "colon".
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52472200
type: QuestionComment

http://stackoverflow.com/comment/92069936
score: 0
has text: I will have a look, but I've read in other topics that is was mainly efficient for medium chunk size of update, but for large scale (thousands) it was not really good. Is it still the case ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52565838

http://stackoverflow.com/comment/91942503
comment on: http://stackoverflow.com/q/52493972
type: QuestionComment
has text: Thanks @Markus, that does makes sense. Feeling a bit silly for not seeing this.
score: 0
type: Comment

http://stackoverflow.com/comment/92031761
has text: Is the icon's path the value of the string, or is there only a number of fixed icons?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52545316

http://stackoverflow.com/q/52581426
tagged with: list
has answer: http://stackoverflow.com/a/52581471
has answer: http://stackoverflow.com/a/52581504
accepted answer: http://stackoverflow.com/a/52581504
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/92098048
tagged with: arrays
has title: How is user input converted into a list with Python?
downvote count: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52581471
has comment: http://stackoverflow.com/comment/92098000
favorite count: 0
has body: d_num = [] d_num.append(input("Enter a figure to verify if is a Disarium number: ")) With the above code, an input of 135 and print(d_num), would return '135' opposed to '1, 3, 5'. A quick-fix would be, prompt the user to include whitespace or other characters between digits and use the split command. However, that poses a problem because the output calculation is based upon the index of the digit. For example: input: 135 output: true, 135 == Disarium number as 1^1 + 3^2 + 5^3 = 135 Is there an easier way to convert user input, despite type, into a list?
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/53360609
upvote count: 7
answers question: http://stackoverflow.com/q/52545269
score: 7
has body: Because in Python 2, the standard open() call creates a far simpler file object than the Python 3 open() call does. The Python 3 open call is the same thing as io.open(), and the same framework is available on Python 2. To make this a fair comparison, you'd have to add the following line to the top of your test: from io import open With that change, the timings on Python 2 go from 5.5 seconds, to 37 seconds. Compared to that figure, the 11 seconds Python 3 takes on my system to run the test really is much, much faster. So what is happening here? The io library offers much more functionality than the old Python 2 file object: File objects returned by open() consist of up to 3 layers of composed functionality, allowing you to control buffering and text handling. Support for non-blocking I/O streams A consistent interface across a wide range of streams Much more control over the universal newline translation feature. Full Unicode support. That extra functionality comes at a performance price. But your Python 2 test reads byte strings, newlines are always translated to \n, and the file object the code is working with is pretty close to the OS-supplied file primitive, with all the downsides. In Python 3, you usually want to process data from files as text, so opening a file in text mode gives you a file object that decodes the binary data to Unicode str objects. So how can you make things go 'faster' on Python 3? That depends on your specific use case, but you have some options: For text-mode files, disable universal newline handling, especially when handling a file that uses line endings that differ from the platform standard. Set the newline parameter to the expected newline character sequence, like \n. Binary mode only supports \n as line separator. Process the file as binary data, and don't decode to str. Alternatively, decode to Latin-1, a straight one-on-one mapping from byte to codepoint. This is an option when your data is ASCII-only too, where Latin-1 omits an e…
accepted answer of: http://stackoverflow.com/q/52545269
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91892113
type: Comment
comment on: http://stackoverflow.com/a/52474388
score: 0
type: AnswerComment
has text: @alienflow Is the picture above sorted correctly for you? How do you want the letters sorted?

http://stackoverflow.com/q/52446737
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I am trying to pull data from this url https://99airdrops.com/page/1/. The code I have written is below. import requests from bs4 import BeautifulSoup url_str = 'https://99airdrops.com/page/1/' page = requests.get(url_str, headers={'User-Agent': 'Mozilla Firefox'}) # soup = BeautifulSoup(page.text, 'lxml') soup = BeautifulSoup(page.text, 'html.parser') # print(soup.prettify()) print(len(soup.findAll('div'))) print(soup.find('div', class_='title')) My issue is the line print(len(soup.findAll('div'))) is only returning 23, and the line print(soup.find('div', class_='title')) prints None. The find command isn't finding the div element with class_='title' even though there are multiple instances, and the div element is nested deeply in the html page but this has never caused me issues before. I've tried using the lxml and html.parser, but neither is returning all the div elements. I also tried writing the html to a file, reading it in, and then running BeautifulSoup with it but I got the same results. Could someone tell me what the issue is here? I also tried the suggestions here Beautiful Soup - `findAll` not capturing all tags in SVG (`ElementTree` does) to update my lxml package but I run into the same issue still. I also tried the solutions here BeautifulSoup doesn&#39;t find correctly parsed elements with no luck.
has comment: http://stackoverflow.com/comment/91838691
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91838640
type: Question
linked to: http://stackoverflow.com/q/26896558
accepted answer: http://stackoverflow.com/a/52448352
linked to: http://stackoverflow.com/q/28016981
linked to: http://stackoverflow.com/q/17608572
has title: Python BeautifulSoup findAll not returning all the elements?
has answer: http://stackoverflow.com/a/52448352
score: 0
answer count: 1
tagged with: beautifulsoup

http://stackoverflow.com/comment/91867461
has text: How do you determine "lowest grades"? Do you take the average of two grades per student?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52462148

http://stackoverflow.com/q/52468045
tagged with: dictionary
tagged with: python-3.x
has title: I have a list in values of a dictionary and I want the first index of the list. How to iterate through it?
has answer: http://stackoverflow.com/a/52472048
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91878177
has comment: http://stackoverflow.com/comment/91877903
has answer: http://stackoverflow.com/a/52472346
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91877898
has body: My dict looks like this. {'a':0,'is_target':False,'properties':[{'id':19,'title':{'x':0,'y':1,'z':2}},{'id':20,'title':{'x':0,'y':1,'z':2}}]} I want to group all the id's. So Far I have tried using maps,also tried creating a new dict from the items and iterating over it. but I couldn't group.
upvote count: 1
has answer: http://stackoverflow.com/a/52468177
downvote count: 1
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91877942
tagged with: python

http://stackoverflow.com/comment/91886492
comment on: http://stackoverflow.com/q/52472302
score: 0
type: Comment
type: QuestionComment
has text: Do you want to not match strings with duplicates, or you just want to filter duplicates from your results? If the latter, use a `set`.

http://stackoverflow.com/comment/92067472
has text: I wonder that if you want export it into a file and load it next time into python? Or you just want to export it into a file and load it with some graphic software?
type: QuestionComment
comment on: http://stackoverflow.com/q/52564644
score: 0
type: Comment

tkinter
tags question: http://stackoverflow.com/q/52583911
tags question: http://stackoverflow.com/q/52440314
tags question: http://stackoverflow.com/q/52541183
tags question: http://stackoverflow.com/q/52517851
tags question: http://stackoverflow.com/q/52437097
tags question: http://stackoverflow.com/q/52470363
tags question: http://stackoverflow.com/q/52501512
tags question: http://stackoverflow.com/q/52582292
tags question: http://stackoverflow.com/q/52540227
tags question: http://stackoverflow.com/q/52537135
tags question: http://stackoverflow.com/q/52472105
tags question: http://stackoverflow.com/q/52556111
tags question: http://stackoverflow.com/q/52541283
tags question: http://stackoverflow.com/q/52545995
tags question: http://stackoverflow.com/q/52558118
tags question: http://stackoverflow.com/q/52557905
tag name: tkinter
tags question: http://stackoverflow.com/q/52571846
tags question: http://stackoverflow.com/q/52453471
tags question: http://stackoverflow.com/q/52568016
tags question: http://stackoverflow.com/q/52580084
tags question: http://stackoverflow.com/q/52434544
tags question: http://stackoverflow.com/q/52457733
tags question: http://stackoverflow.com/q/52506729
tags question: http://stackoverflow.com/q/52487043
tags question: http://stackoverflow.com/q/52484359
tags question: http://stackoverflow.com/q/52460846
tags question: http://stackoverflow.com/q/52553600
tags question: http://stackoverflow.com/q/52584273
tags question: http://stackoverflow.com/q/52452857
tags question: http://stackoverflow.com/q/52476783
tags question: http://stackoverflow.com/q/52460584
tags question: http://stackoverflow.com/q/52431102
tags question: http://stackoverflow.com/q/52534755
tags question: http://stackoverflow.com/q/52535324
tags question: http://stackoverflow.com/q/52521419
tags question: http://stackoverflow.com/q/52471380
tags question: http://stackoverflow.com/q/52526374
tags question: http://stackoverflow.com/q/52546212
tags question: http://stackoverflow.com/q/52488650
tags question: http://stackoverflow.com/q/52579782
tags question: http://stackoverflow.com/q/52553102
tags question: http://stackoverflow.com/q/52547801
tags question: http://stackoverflow.com/q/52466432
tags question: http://stackoverflow.com/q/52571560
tags question: http://stackoverflow.com/q/52535407
tags question: http://stackoverflow.com/q/52498137
tags question: http://stackoverflow.com/q/52526137
tags question: http://stackoverflow.com/q/52546520
tags question: http://stackoverflow.com/q/52464307
tags question: http://stackoverflow.com/q/52544108
tags question: http://stackoverflow.com/q/52452283
tags question: http://stackoverflow.com/q/52437232
tags question: http://stackoverflow.com/q/52430388
tags question: http://stackoverflow.com/q/52572956
tags question: http://stackoverflow.com/q/52459277
tags question: http://stackoverflow.com/q/52477052
tags question: http://stackoverflow.com/q/52529403
tags question: http://stackoverflow.com/q/52455477
tags question: http://stackoverflow.com/q/52556781
tags question: http://stackoverflow.com/q/52582051
tags question: http://stackoverflow.com/q/52439711
tags question: http://stackoverflow.com/q/52571873
tags question: http://stackoverflow.com/q/52433611
tags question: http://stackoverflow.com/q/52571426
tags question: http://stackoverflow.com/q/52455616
tags question: http://stackoverflow.com/q/52504286
tags question: http://stackoverflow.com/q/52576000
tags question: http://stackoverflow.com/q/52580315
tags question: http://stackoverflow.com/q/52581748
tags question: http://stackoverflow.com/q/52488223
tags question: http://stackoverflow.com/q/52540413
tags question: http://stackoverflow.com/q/52456088
tags question: http://stackoverflow.com/q/52562753
tags question: http://stackoverflow.com/q/52562511
tags question: http://stackoverflow.com/q/52469772
tags question: http://stackoverflow.com/q/52459511
tags question: http://stackoverflow.com/q/52460939
tags question: http://stackoverflow.com/q/52486467
tags question: http://stackoverflow.com/q/52481616

http://stackoverflow.com/q/52430334
accepted answer: http://stackoverflow.com/a/52430456
linked to: http://stackoverflow.com/q/52444993
score: 0
answer count: 1
tagged with: user-interface
has title: Kivy - UI Issues
has answer: http://stackoverflow.com/a/52430456
has body: Trying to create a simple Kivy GUI with two screens: a title screen and a control screen with a number of buttons. The main problem is navigating the GUI and letting the builder function properly. I just get a black screen at the moment on run. import kivy kivy.require('1.10.0') from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.app import App from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.floatlayout import FloatLayout from kivy.uix.stacklayout import StackLayout class IntroScreen(Screen): pass class ContScreen(Screen): pass class ScreenManagement(ScreenManager): pass backbone = Builder.load_file("main.kv") class MasterApp(App): def build (self): return backbone boApp = MasterApp() if __name__ == "__main__": boApp.run() with the main .kv ScreenManagement: transition: FadeTransition &lt;IntroScreen&gt;: name: "main" intro.kv &lt;ContScreen&gt;: name: "cont" stacklayout.kv and the example screen (intro.kv) &lt;IntroScreen&gt;: FloatLayout orientation: 'vertical' padding: [10,50,10,50] spacing: 50 Label: text: 'WELCOME' font_size: 50 pos_hint={'x':0, 'y':0} Image: source=('mylogo.png') pos_hint: {'x':0,'y':0} Button: text: 'Initialize' font_size: 35 on_release: app.root.current = "cont" Still learning Kivy so I know I'm doing something wrong. Would appreciate help figuring this out. EDIT: NAVIGATION SOLVED FOLLOW UP: &lt;IntroScreen&gt;: FloatLayout orientation: 'vertical' padding: [10,50,10,50] spacing: 50 Label: text: 'WELCOME' font_size: 50 pos_hint: {'x':0, 'y':0} Image: source: 'mylogo.png' pos_hint: {'x':0,'y':0} Button: text: 'Initialize' font_size: 35 on_release: root.manager.current = "cont" Image not showing at all on the screen, just full button.
tagged with: python
tagged with: kivy
type: AnsweredQuestion
tagged with: kivy-language
type: Question

http://stackoverflow.com/q/52542392
has answer: http://stackoverflow.com/a/52543095
answer count: 1
has body: I'm new to Python and am trying my hand at Python3.7. I'm running this on Windows 10 in a PyCharm environment I have a json file that contains a bunch of network data from one of my appliances. Its imaginatively called 'network.json' I am trying to return the 'host names from the json object. The particular hostnames im trying to return are in the 'probes' section I have tried referencing it as print([instances][probes]) but that does not return what I'm looking for. I have tried looking at examples on here and other sites but I just cant get my brain around it. Any help would be much appreciated. My code is below. import json with open('network.json') as f: data = json.load(f) print('Appliance OS Code is ', data["applianceOSCode"]) print('Version is: ', data["version"]) for hostname in data.items(): print(hostname) The output of the code is as follows Appliance OS Code is x Version is: 3.0.8 (oc6d6f) ('time', '2018-09-26 09:34') ('installed', '2018-08-13') ('version', '3.0.8 (oc6d6f)') ('modelsUpdated', '2018-08-30 10:12:41') ('modelPackageVersion', '3.0.8.1~20180726095847~gc6d747') ('hostname', 'at-40-99-29') ('inoculation', True) ('applianceOSCode', 'x') ('diskSpaceUsed_ssd', 77) ('diskSpaceUsed_var', 77) ('type', 'unifiedView') ('load', 29) ('cpu', 39) ('memoryUsed', 49) ('instances', {'at-40-99-29': {'id': 1, 'version': '3.0.8 (oc6d6f)', 'label': 'Master 1', 'hostname': 'at-40-99-29', 'time': '2018-09-26 09:34', 'applianceOSCode': 'x', 'diskSpaceUsed_ssd': 77, 'diskSpaceUsed_var': 77, 'type': 'master', 'diskUtilization': 3, 'load': 31, 'cpu': 34, 'memoryUsed': 49, 'darkflowQueue': 280, 'networkInterfacesReceived_eth0': 4211426005033, 'networkInterfacesReceived_eth1': 1143, 'networkInterfacesReceived_eth2': 72400, 'networkInterfacesReceived_eth3': 24110, 'networkInterfacesReceived_eth6': 1258046541112778, 'networkInterfacesTransmitted_eth0': 326798655431, 'bandwidthCurrent': 2909592901, 'bandwidthCurrentString': '2.91 Gbps', 'bandwidthAverage': 2473968000, 'band…
downvote count: 0
has comment: http://stackoverflow.com/comment/92024738
favorite count: 0
has title: I'm not understanding how to iterate through a json file
has comment: http://stackoverflow.com/comment/92025168
tagged with: python-3.x
tagged with: python
tagged with: parsing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92025246
accepted answer: http://stackoverflow.com/a/52543095
linked to: http://stackoverflow.com/q/21028979
upvote count: 1
has comment: http://stackoverflow.com/comment/92029680
type: Question
linked to: http://stackoverflow.com/q/48193502
score: 1
has comment: http://stackoverflow.com/comment/92025062
tagged with: http://stackoverflow.com/tag/json
duplicate of: http://stackoverflow.com/q/48193502

http://stackoverflow.com/comment/92366796
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52720758
has text: I had the same problem previously, but I have done is reading the changelog on their site. Then I found inside the changelog that is replaced by -f! Now, I have everything in fabric, which is imo much better than fabric1
score: 0

http://stackoverflow.com/comment/91921609
score: 0
comment on: http://stackoverflow.com/a/52487593
type: AnswerComment
has text: Fantastic answer, by the way.
type: Comment

http://stackoverflow.com/comment/91976135
has text: Please share the (relevant) models.
comment on: http://stackoverflow.com/q/52518294
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52439001
has comment: http://stackoverflow.com/comment/91820995
score: -1
type: Question
has answer: http://stackoverflow.com/a/52439090
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91820946
favorite count: 0
has comment: http://stackoverflow.com/comment/91820864
tagged with: python
has comment: http://stackoverflow.com/comment/91820926
type: UnansweredQuestion
tagged with: fiona
has body: I want to install fiona module with PhotoScan and I get a bug: command : ./python.exe -m pip install fiona (when I'm located in my python folder, of Photoscan) error : PS C:\Program Files\Agisoft\PhotoScan Pro\python&gt; ./python.exe -m pip install fiona Collecting fiona Using cached https://files.pythonhosted.org/packages/82/52/fe30f9f529edf52080e7f5a2ffe377aefd84d0aceeb2e96022b5a78b3faf/Fiona-1.7.13.tar.gz Collecting cligj&gt;=0.4 (from fiona) Using cached https://files.pythonhosted.org/packages/fc/05/e8384e1f7c8689cd1b91818a24cc860077c73368fb285ba53fbd8556ec98/cligj-0.4.0-py3-none-any.whl Collecting click-plugins (from fiona) Using cached https://files.pythonhosted.org/packages/95/dd/fef84cf1678418f241ef542c0288bdf215bdd3e35f1fe03dc5223a2e80ba/click_plugins-1.0.4-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): six&gt;=1.7 in c:\program files\agisoft\photoscan pro\python\lib\site-packages (from fiona) Collecting munch (from fiona) Collecting click&gt;=4.0 (from cligj&gt;=0.4-&gt;fiona) Using cached https://files.pythonhosted.org/packages/34/c1/8806f99713ddb993c5366c362b2f908f18269f8d792aff1abfd700775a77/click-6.7-py2.py3-none-any.whl Building wheels for collected packages: fiona Running setup.py bdist_wheel for fiona ... error Complete output from command "C:\Program Files\Agisoft\PhotoScan Pro\python\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\HP-EB-~1\\AppData\\Local\\Temp\\pip-build-hy53yycg\\fiona\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\HP-EB-~1\AppData\Local\Temp\tmpzzfrfqe4pip-wheel- --python-tag cp35: C:\Program Files\Agisoft\PhotoScan Pro\python\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'requires_python' warnings.warn(msg) C:\Program Files\Agisoft\PhotoScan Pro\python\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'metadata_version' warnings.warn(msg) C:\P…
has title: fiona - install package to photoscan
downvote count: 1

http://stackoverflow.com/comment/91997985
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52527774
score: 0
has text: Yes - tried executing that command in the pipeline and error persists.

http://stackoverflow.com/q/52495331
has body: I have a small flask todo app, and trying to deploy it in heroku, but getting errors and I am unable to solve it, source code is here, this is working perfectly, error screenshot can be seen here => http://prntscr.com/kyfwmy Here is my app.py: from flask import Flask, render_template, request, jsonify, url_for, redirect from flask_cors import CORS from flask_pymongo import PyMongo, pymongo import sys, time from bson.json_util import dumps, ObjectId app = Flask(__name__) app.config['MONGO_DBNAME']='todo' app.config['MONGO_URI']='mongodb://todo_task:todo_task*123*@ds111082.mlab.com:11082/todo' mongo = PyMongo(app) cors = CORS(app, resources={r'/ajax/*': {"origins": '*'}}) @app.route('/') def index(): _tasks = mongo.db.tasks.find().sort('created_at', pymongo.DESCENDING) return render_template('index.html', tasks=_tasks) @app.route('/add_task', methods=['POST']) def add_task(): if request.method == 'POST': tasks = mongo.db.tasks data = { 'task': request.form['task'], 'status': 'view', 'created_at': time.strftime('%d-%m-%Y %H:%M:%S'), 'updated_at': time.strftime('%d-%m-%Y %H:%M:%S') } tasks.insert(data) return redirect(url_for('index')) @app.route('/destroy_task') def task_destroy(): if request.method == 'GET': id = request.args.get('id') tasks = mongo.db.tasks result = tasks.find_one({'_id': ObjectId(id)}) tasks.remove(result) return redirect(url_for('index')) @app.route('/ajax/task_update', methods=['POST']) def task_update(): id = request.form['id'] tasks = mongo.db.tasks result = tasks.find_one({'_id': ObjectId(id)}) if result['status'] == 'completed': result['status'] = 'view' res = {"status": 'view'} else: result['status'] = 'completed' res = {"status": 'completed'} result['updated_at'] = time.strftime('%d-%m-%Y %H:%M:%S') tasks.save(result) return jsonify({'status': res}) @app.route('/actives') def actives(): tasks = mongo.db.tasks _tasks = tasks.find({'status': 'view'}).sort('created_at', pymongo.DESCENDING) return render_template('index.html', tasks=_tasks) @app…
tagged with: python
tagged with: deployment
has comment: http://stackoverflow.com/comment/91931338
type: AnsweredQuestion
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/91931497
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52495659
tagged with: heroku
score: -1
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52495659
tagged with: flask
has title: python (flask) deployment issue on heroku
favorite count: 0

http://stackoverflow.com/comment/91973243
type: Comment
has text: NP. Though I'm not using your solution in this case, it might help someone in future and there's one more alternative we learnt :-)
comment on: http://stackoverflow.com/a/52516388
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91852900
has text: By the way, `export MYVAR = MYVAL` is invalid in shell, there are no spaces allowed around an `=`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52454896

http://stackoverflow.com/q/52564254
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/52564284
has answer: http://stackoverflow.com/a/52564284
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92070624
has answer: http://stackoverflow.com/a/52570300
tagged with: flask
has title: NameError: name 'User' is not defined (when flask shell)
accepted answer: http://stackoverflow.com/a/52570300
tagged with: python
has comment: http://stackoverflow.com/comment/92066952
favorite count: 0
has comment: http://stackoverflow.com/comment/92069069
upvote count: 2
has body: This is my microblog.py file, environment, centos7. from app import app,db from app.models import User,Post @app.shell_context_processor def make_shell_context(): return {'db':db,'User':User,'Post':Post} when I input flask shell, and want to add User: Python 3.6.5 (default, Apr 10 2018, 17:08:37) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux App: app [production] Instance: /root/code/microblog/instance &gt;&gt;&gt; User Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; NameError: name 'User' is not defined &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/92067258

http://stackoverflow.com/comment/91895377
comment on: http://stackoverflow.com/q/52476959
has text: @ManojKengudelu I am sure that i do not have any indentation error. My question is not about the error. It is about how to perform the action.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91951563
type: Comment
type: QuestionComment
has text: What about weekends? Do those count as days?
comment on: http://stackoverflow.com/q/52505501
score: 0

http://stackoverflow.com/q/52487164
linked to: http://stackoverflow.com/q/3766711
has comment: http://stackoverflow.com/comment/91915751
has answer: http://stackoverflow.com/a/52487300
has comment: http://stackoverflow.com/comment/91915735
upvote count: 1
answer count: 1
favorite count: 0
has body: What is the best way to skip entries in a generator expression that are created using a function and another generator? In essence, I am looking for an expression that looks like this: some_iter = (some_function(_x, _y, **kwargs) or continue for _x, _y in some_generator(*x)) (but the continue statement obviously doesn't work in this context) Functionally, it should act like this: def some_iter(*x): for _x, _y in some_generator(*x): x = some_function(_x, _y, **kwargs) if x: yield x
has comment: http://stackoverflow.com/comment/91916904
type: UnansweredQuestion
tagged with: python
tagged with: generator
has comment: http://stackoverflow.com/comment/91916320
has title: Skip entry in generator expression
tagged with: generator-expression
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91915610
tagged with: expression

http://stackoverflow.com/comment/92075321
type: QuestionComment
comment on: http://stackoverflow.com/q/52569134
has text: Use `.timedelta(seconds=i * 2)`
type: Comment
score: 1

pygame
tags question: http://stackoverflow.com/q/52541534
tags question: http://stackoverflow.com/q/52452237
tags question: http://stackoverflow.com/q/52551073
tags question: http://stackoverflow.com/q/52514929
tags question: http://stackoverflow.com/q/52576681
tags question: http://stackoverflow.com/q/52456284
tags question: http://stackoverflow.com/q/52563927
tags question: http://stackoverflow.com/q/52461148
tags question: http://stackoverflow.com/q/52499190
tags question: http://stackoverflow.com/q/52465795
tags question: http://stackoverflow.com/q/52456427
tags question: http://stackoverflow.com/q/52446792
tags question: http://stackoverflow.com/q/52553011
tags question: http://stackoverflow.com/q/52436416
tag name: pygame
tags question: http://stackoverflow.com/q/52564391
tags question: http://stackoverflow.com/q/52480093
tags question: http://stackoverflow.com/q/52487883
tags question: http://stackoverflow.com/q/52504266
tags question: http://stackoverflow.com/q/52564275
tags question: http://stackoverflow.com/q/52517452
tags question: http://stackoverflow.com/q/52469687
tags question: http://stackoverflow.com/q/52575892
tags question: http://stackoverflow.com/q/52434247
tags question: http://stackoverflow.com/q/52519568
tags question: http://stackoverflow.com/q/52457595
tags question: http://stackoverflow.com/q/52588601
tags question: http://stackoverflow.com/q/52490469
tags question: http://stackoverflow.com/q/52451476
tags question: http://stackoverflow.com/q/52562504
tags question: http://stackoverflow.com/q/52535162
tags question: http://stackoverflow.com/q/52470930
type: Tag

http://stackoverflow.com/comment/95519696
score: 0
has text: I also implemented it using Tensorflow (https://github.com/GalaxyDream/DRNN-Tensorflow), got bad performance as well. I asked Baoxin for the code, but he said he could not provide it due to a contract with a company.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52529763

http://stackoverflow.com/q/52562511
linked to: http://stackoverflow.com/q/9776718
has comment: http://stackoverflow.com/comment/92066038
has title: Add items to a listbox after 5 seconds in Python
type: Question
has comment: http://stackoverflow.com/comment/92075737
tagged with: listbox
has comment: http://stackoverflow.com/comment/92064890
has comment: http://stackoverflow.com/comment/92063581
has answer: http://stackoverflow.com/a/52757714
score: 0
has comment: http://stackoverflow.com/comment/92097018
answer count: 2
has answer: http://stackoverflow.com/a/52757075
type: UnansweredQuestion
tagged with: python
has body: I have written a simple program which creates maths multiplication problems. I wrote it as a CLI, however moved over to a GUI as some teachers were saying that the CLI was too small for pupils to see. Everything works bar one thing. Once the 'start' button has been clicked I would like to update the listbox on the left with a new question after 5 seconds. In the CLI version I simply added sleep(5) which paused the program and then resumed, however the GUI halts the whole program and waits, then spits out all the questions. If I remove the for loop the teacher can click the button 15 times, but this seems wasteful. Here's my code: from tkinter import * from tkinter import messagebox from time import sleep from random import randint questionList=[] def main(): for i in range (15): num1= randint(0,12) num2 = randint(1,12) question = ("Question",(i+1),")",num1,"X",num2) listbox.insert(END, question) #sleep(5) tempArray = [] tempArray.append(num1) tempArray.append(num2) questionList.append(tempArray) def answers (): for i in range (len(questionList)): ans = (questionList[i][0]*questionList[i][1]) listbox1.insert(END,ans) root = Tk() root.geometry("445x590+460+70") root.title("Maths Machine") label = Label(root, text="Maths Machine", font = ("Arial",16)).grid(row = 0, columnspan = 2) startButton = Button(root, text = "Start", width = 15, command = main).grid(row = 1, column = 1,padx = 10, pady = 10) label = Label(root, text = "Questions", font = ("Arial",12)).grid(row = 2, column = 0) label = Label(root, text = "Answers", font = ("Arial",12)).grid(row = 2, column = 1) listbox = Listbox(root, width = 25, height = 15,font = ("Arial",16)) listbox.grid(row = 3, column = 0) listbox1 = Listbox(root, width = 10, height = 15,font = ("Arial",16)) listbox1.grid(row = 3, column = 1) answerButton = Button(root, text ="Show answers", width = 15, command = answers).grid(row = 4, column = 1, padx =10, pady =10) mainloop()
tagged with: tkinter

http://stackoverflow.com/comment/92104502
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52584838
has text: @a_python_user Exactly, that's what I wanna do
score: 0

http://stackoverflow.com/comment/91916008
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52475347
has text: Choose carefully between `reflect` and `symmetric`

http://stackoverflow.com/comment/91928044
score: 0
type: QuestionComment
has text: If you need to retain the order in which keys were *added to the dictionary,* then yes, you need OrderedDict. If you need to order the keys by some function, keep using a standard dict and use `sorted(d.keys(), key=lambda k: d[k])` to get the keys sorted based on their values (or whatever other criterion you need).
type: Comment
comment on: http://stackoverflow.com/q/52492913

http://stackoverflow.com/a/52500340
answers question: http://stackoverflow.com/q/52500199
type: Answer
has comment: http://stackoverflow.com/comment/91942102
upvote count: 2
score: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52500199
has body: You only wish to update one column for each row. Therefore, with advanced indexing you must explicitly provide those row identifiers: A = np.zeros((4, 10)) A[np.arange(A.shape[0]), [2, 7, 0, 3]] = 1 Result: array([[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.]]) Using a colon for the row indexer will tell NumPy to update all rows for the specified columns: A[:, [2, 7, 0, 3]] = 1 array([[ 1., 0., 1., 1., 0., 0., 0., 1., 0., 0.], [ 1., 0., 1., 1., 0., 0., 0., 1., 0., 0.], [ 1., 0., 1., 1., 0., 0., 0., 1., 0., 0.], [ 1., 0., 1., 1., 0., 0., 0., 1., 0., 0.]])
type: AcceptedAnswer

http://stackoverflow.com/a/52513340
upvote count: 5
has comment: http://stackoverflow.com/comment/91972674
type: Answer
answers question: http://stackoverflow.com/q/52507860
has comment: http://stackoverflow.com/comment/91972841
score: 3
has body: As per @TimPeters' answer, there are structural reasons why you cannot access dictionary items by position in O(1) time. It's worth considering the alternatives if you are looking for O(1) lookup by key or position. There are 3rd party libraries such as NumPy / Pandas which offer such functionality, efficient especially for numeric arrays where pointers are not required. With Pandas, you can construct a "dictionary-like" series with unique labels offering O(1) lookup by "label" or position. What you sacrifice is performance when deleting a label, which incurs O(n) cost, much like list. import pandas as pd s = pd.Series(list(range(n))) # O(n) item deletion del s[i] s.drop(i) s.pop(i) # O(1) lookup by label s.loc[i] s.at[i] s.get(i) s[i] # O(1) lookup by position s.iloc[i] s.iat[i] pd.Series is by no means a drop-in replacement for dict. For example, duplicate keys are not prevented and will cause issues if the series is used primarily as a mapping. However, where data is stored in a contiguous memory block, as in the example above, you may see significant performance improvements. See also: What are the advantages of NumPy over regular Python lists?. What is the performance impact of non-unique indexes in pandas? Pandas DataFrame search is linear time or constant time?
downvote count: 2

http://stackoverflow.com/comment/91933639
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52496390
score: 7
has text: What about simply `value_str.isdigit()`?

http://stackoverflow.com/q/52502896
has answer: http://stackoverflow.com/a/52608250
has comment: http://stackoverflow.com/comment/92050345
type: Question
has comment: http://stackoverflow.com/comment/92011323
has comment: http://stackoverflow.com/comment/91964553
has comment: http://stackoverflow.com/comment/91951942
downvote count: 0
favorite count: 0
has title: How can I fit a good Lorentzian on python using scipy.optimize.curve_fit?
answer count: 1
tagged with: curve-fitting
has body: I'm trying to fit a Lorentzian function with more than one absorption peak (Mössbauer spectra), but the curve_fit function it not working properly, fitting just few peaks. How can I fit it? Figure: Trying to adjusting multi-Lorentzian Below I show my code. Please, help me. import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def mymodel_hema(x,a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4,a5,b5,c5,a6,b6,c6): f = 160000 - (c1*a1)/(c1+(x-b1)**2) - (c2*a2)/(c2+(x-b2)**2) - (c3*a3)/(c3+(x-b3)**2) - (c4*a4)/(c4+(x-b4)**2) - (c5*a5)/(c5+(x-b5)**2) - (c6*a6)/(c6+(x-b6)**2) return f def main(): abre = np.loadtxt('HEMAT_1.dat') x = np.zeros(len(abre)) y = np.zeros(len(abre)) for i in range(len(abre)): x[i] = abre[i,0] y[i] = abre[i,1] popt,pcov = curve_fit(mymodel_hema, x, y,maxfev=1000000000) My data --> https://drive.google.com/file/d/1LvCKNdv0oBza_TDwuyNwd29PgQv22VPA/view?usp=sharing
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/q/52458290
score: -4
upvote count: 1
type: Question
has title: Without using any number write a code in python to print number from 61 to 70
downvote count: 5
answer count: 1
has comment: http://stackoverflow.com/comment/91858697
favorite count: 0
has comment: http://stackoverflow.com/comment/91858721
has comment: http://stackoverflow.com/comment/91858709
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52458320
has body: How can i print numbers from 61 to 70 in python without using any number in my code . Also I don't know the ascii character corresponding to 61 and 70 .

http://stackoverflow.com/comment/91935878
has text: @Yog - ooops, not tested - need `df['RollNumber'] = [f'ABC{x:010}AB' for x in range(20, len(df) + 20)] `
type: Comment
comment on: http://stackoverflow.com/a/52473889
score: 1
type: AnswerComment

http://stackoverflow.com/comment/92066022
comment on: http://stackoverflow.com/a/52563718
type: AnswerComment
has text: @Unni, Pandas is probably *not* the right structure for you. The name Pandas is derived from [panel data](https://en.wikipedia.org/wiki/Panel_data). As such, it's designed for structured data stored in *arrays*. Each row in this array is indexed and can't be arbitrarily long. `list`, possibly combined with `dict` may be more appropriate.
type: Comment
score: 2

http://stackoverflow.com/comment/91825456
type: AnswerComment
score: 0
has text: I get this error Location based index Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array])
type: Comment
comment on: http://stackoverflow.com/a/52441054

http://stackoverflow.com/q/52507605
score: 0
has body: I want to plot a seaborn catplot with multiple columns and use the parameter hue to differentiate some observations. Let's say I have import pandas as pd import seaborn as sns import random as r import numpy as np name_list=['pepe','Fabrice','jim','Michael'] country_list=['spain','France','uk','Uruguay'] favourite_color=['green','blue','red','white'] df=pd.DataFrame({'name':[r.choice(name_list) for n in range(100)], 'country':[r.choice(country_list) for n in range(100)], 'fav_color':[r.choice(favourite_color) for n in range(100)], 'score':np.random.rand(100),}) If I run sns.catplot(y='score',hue='fav_color',col='country',data=df) I get a TypeError: 'NoneType' object is not iterable. If I specify legend=False, I do not get any error but all points seem of the same color. I tried also to specify the palette with the same result. Is this a bug or am I doing something wrong?
answer count: 1
has answer: http://stackoverflow.com/a/57238151
tagged with: python-3.x
tagged with: seaborn
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91956559
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/91955868
has title: hue parameter in seaborn.catplot

http://stackoverflow.com/a/52518595
answers question: http://stackoverflow.com/q/52500368
has body: Yet another way to do it: df = pd.read_csv('filename',sep='\s+', names=['key1','key2','key3']) for col in df.columns: df[col] = df[col].str.split(':').str[1].astype(float)
score: 0
type: Answer

http://stackoverflow.com/a/65109346
has body: Update 06.12.20: A new 'official' alpha version of googletrans with a fix was released Install the alpha version like this: pip install googletrans==3.1.0a0 Translation example: translator = Translator() translation = translator.translate("Der Himmel ist blau und ich mag Bananen", dest='en') print(translation.text) #output: 'The sky is blue and I like bananas' In case it does not work, try to specify the service url like this: from googletrans import Translator translator = Translator(service_urls=['translate.googleapis.com']) translator.translate("Der Himmel ist blau und ich mag Bananen", dest='en') See the discussion here for details and updates: https://github.com/ssut/py-googletrans/pull/237 Update 10.12.20: Another fix was released As pointed out by @DesiKeki and @Ahmed Breem, there is another fix which seems to work for several people: pip install googletrans==4.0.0-rc1 Github discussion here: https://github.com/ssut/py-googletrans/issues/234#issuecomment-742460612 In case the fixes above don't work for you If the above doesn't work for you, google_trans_new seems to be a good alternative that works for some people. It's unclear why the fix above works for some and doesn't for others. See details on installation and usage here: https://github.com/lushan88a/google_trans_new #pip install google_trans_new from google_trans_new import google_translator translator = google_translator() translate_text = translator.translate('สวัสดีจีน',lang_tgt='en') print(translate_text) #output: Hello china
has comment: http://stackoverflow.com/comment/115241111
has comment: http://stackoverflow.com/comment/134088901
type: Answer
has comment: http://stackoverflow.com/comment/115217475
has comment: http://stackoverflow.com/comment/115260965
has comment: http://stackoverflow.com/comment/115274947
has comment: http://stackoverflow.com/comment/115394660
score: 256
has comment: http://stackoverflow.com/comment/118268047
has comment: http://stackoverflow.com/comment/115190280
has comment: http://stackoverflow.com/comment/115234196
has comment: http://stackoverflow.com/comment/115261161
upvote count: 257
answers question: http://stackoverflow.com/q/52455774
downvote count: 1
has comment: http://stackoverflow.com/comment/115284259

http://stackoverflow.com/comment/92013487
score: 0
type: QuestionComment
has text: @Sayse I believe list comprehension is a more "pythonic" way of doing things and will give cleaner more maintainable code.
type: Comment
comment on: http://stackoverflow.com/q/52536997

http://stackoverflow.com/comment/91923752
comment on: http://stackoverflow.com/a/52491492
has text: @Jan - it is default value, it is not important also in `drop_duplicates`
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91959176
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52462910
has text: I've tried that. distutils doesn't seem to respect those variables. It explicitly needs those flags to use the intel compilers.
score: 0

http://stackoverflow.com/comment/92042581
has text: Excellent. It was so simple.
type: AnswerComment
comment on: http://stackoverflow.com/a/52550510
type: Comment
score: 0

http://stackoverflow.com/comment/135396850
type: Comment
has text: Worked like a Charm !! I tried nearly all versions of GoogleTrans before I tried this. Thanks !
score: 0
comment on: http://stackoverflow.com/a/72808431
type: AnswerComment

http://stackoverflow.com/q/52459935
tagged with: discord
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59527627
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91869641
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91862050
tagged with: discord.py
answer count: 2
has title: Discord Bot Responding to Phrase (Discord.py Rewrite)
has body: Right now, I am trying to code an event for a Discord Bot (Using the Discord.py Rewrite package) that would send an image upon certain phrase being sent in the chat. Based upon the error messages I been having, it looks like it is not passing the Message argument, as it is likely I am missing something somewhere. The Listener seems like it is working as it should be (It triggers the moment someone says something in chat). Here is the error message I am receiving for reference: Ignoring exception in message Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site->packages\discord\client.py", line 221, in _run_event await coro(*args, **kwargs) TypeError: dealwithit() missing 1 required >positional argument: 'message' Here is the code snippet for reference @bot.event async def dealwithit(ctx,message): msg = message.content msg = msg.lower() msg = "".join(msg.split()) if ctx.user.id != message.author.id: if msg == "dealwithit": dealwithit= discord.File('swag.jpg', filename='swag.jpg') await client.send_message(content=None,file=dealwithit) bot.add_listener(dealwithit,'on_message') Any assistance on what I might be missing that is not passing the arguments over, or have set up incorrectly would be appreciated.
has answer: http://stackoverflow.com/a/52461866
has comment: http://stackoverflow.com/comment/91862837
score: 0

http://stackoverflow.com/comment/91982059
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52520274
type: Comment
has text: For the actual use-case see https://gitlab.kwant-project.org/qt/adaptive/merge_requests/70/diffs

http://stackoverflow.com/comment/91913848
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52485201
has text: Also incrementing the value n_commenters will not allow me to pull out unique commenters for the file. It will increment whenever it sees the commenter field. What if the same user comments twice or multiple time? That user will be counted twice or how many ever times they commented. This will skew the numbers significantly. Is there a way to count them by their id and then increment that number?

http://stackoverflow.com/comment/92074857
has text: You might want to consider looking at the `pyparsing` module which is a library for building parsers with little code if this isn't just a learning exercise or a trivial task.
comment on: http://stackoverflow.com/q/52568816
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91962288
type: AnswerComment
comment on: http://stackoverflow.com/a/52509549
has text: dude, it you try to make simple sudo program to draw the rectangle on any image then draw rectangle function will work. Try to post whole code if possible then it would be easy to debug
type: Comment
score: 0

http://stackoverflow.com/a/52570318
type: AcceptedAnswer
downvote count: 0
has body: You could use itertools.zip_longest with fillvalue handling the unequal length case. Using a list-comprehension: from itertools import zip_longest name = 'John' surname = 'Smith' print(''.join([x + y for x, y in zip_longest(name, surname, fillvalue='')])) # JSomhinth Or using map: print(''.join(map(''.join, zip_longest(name, surname, fillvalue='')))) # JSomhinth
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52570225
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52570225

http://stackoverflow.com/comment/91939448
type: Comment
has text: @Cleb there are several ways of making equation search - my site uses unbounded Differential Evolution for initial parameter estimates - and I was attempting to illustrate the "split-and-fit" technique with data overlap as a method to solve the problem, rather than a final solution. Plus, the plotted fit looks cool.
comment on: http://stackoverflow.com/a/52489856
type: AnswerComment
score: 0

http://stackoverflow.com/q/52462757
score: 1
has answer: http://stackoverflow.com/a/52462937
favorite count: 0
tagged with: python
tagged with: python-3.x
has title: Python dictionaries matrix "representation"
has body: I have a dictionary dict in Python. Imagine this simple example. Dict: bin1:{apple,apple,cherry,cherry,cherry,banana,banana,avocado} bin2:{cucumber,cucumber,cucumber,cucumber,apple} bin3:{cherry,cherry,banana,banana} I want to calculate and store this (in any representation, I just can't come up with data structure): Rows represent all keys, columns represent all available distinct fruits in all dictionary values Numbers mean this: for each key, we calculate number of times fruit appears for that key divided by number of times other particular fruit appears the most for that key. Ex: for bin1: cherry appears the most (3), so apples would be 2/3 (apples appear 2 times divided by cherry appears 3 times) and so on. Maybe we can create something like dictionary inside dictionary: bin1:{apple:2/3,banana:2/3,cherry:1,cucumber:0,avocado:1/3} bin2:{apple:1/4,banana:0,cherry:0,cucumber:1,avocado:0} bin3:{apple:0,banana:1,cherry:1,cucumber:0,avocado:0}
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91867741
upvote count: 1
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/q/52511653
tagged with: reactjs
answer count: 2
has comment: http://stackoverflow.com/comment/91963170
downvote count: 0
has answer: http://stackoverflow.com/a/52519208
has comment: http://stackoverflow.com/comment/91963248
has answer: http://stackoverflow.com/a/52512042
favorite count: 0
has comment: http://stackoverflow.com/comment/91963275
has title: Drawing guitar chords dynamically
possible better answer: http://stackoverflow.com/a/52512042
tagged with: python
tagged with: drawing
type: AnsweredQuestion
has body: So my goal is to draw guitar chords like this using a json file, the number of chords I should create is 924 so there's no way I can do it mannually. What I have is an array of numbers comma separated (look into position) I am definitely not using fingerings (that's the finger you should use, basically it's a number on top of the circles) [ { "id": "404", "name": "Cb", "intervals": "", "positions": [ { "id": "1226", "position": "x,2,4,4,4,2", "fingerings": "13331;12341", "picture": "", "chord_id": "404", "instrument_id": "1" }, { "id": "1231", "position": "7,9,9,8,7,7", "fingerings": "134211", "picture": "", "chord_id": "404", "instrument_id": "1" }, { "id": "1251", "position": "7,6,4,4,4,7", "fingerings": "321114", "picture": "", "chord_id": "404", "instrument_id": "1" }, ... This is challenging because each chords have several position and some of them are on fret 5 or more so I should indicate which fret we're drawing rather than draw a whole guitar every time. Second issue is I don't know where exactly I should start and how to handle that correctly, I would love to implement everything in React or Python and then generate a bunch of imgs and use them in my app, this is what I'm comfortable with. I was also thinking about js and css but really how can I write a code that put a circle on that specific place based on a number. I'm not looking for code, just some links where I can start my research, now I am kinda stuck, please let me know if you need more infos.
score: 3
tagged with: http://stackoverflow.com/tag/svg
upvote count: 3
accepted answer: http://stackoverflow.com/a/52519208
type: Question
tagged with: javascript

machine-learning
tags question: http://stackoverflow.com/q/52477891
tags question: http://stackoverflow.com/q/52585975
tags question: http://stackoverflow.com/q/52587574
tags question: http://stackoverflow.com/q/52478445
tags question: http://stackoverflow.com/q/52571493
tags question: http://stackoverflow.com/q/52440940
tags question: http://stackoverflow.com/q/52579293
tags question: http://stackoverflow.com/q/52458426
tags question: http://stackoverflow.com/q/52551909
tags question: http://stackoverflow.com/q/52510737
tags question: http://stackoverflow.com/q/52481006
tags question: http://stackoverflow.com/q/52539110
tags question: http://stackoverflow.com/q/52550176
tags question: http://stackoverflow.com/q/52458508
tags question: http://stackoverflow.com/q/52510531
tags question: http://stackoverflow.com/q/52436030
tags question: http://stackoverflow.com/q/52455536
tags question: http://stackoverflow.com/q/52567129
tags question: http://stackoverflow.com/q/52455829
tags question: http://stackoverflow.com/q/52432258
tags question: http://stackoverflow.com/q/52463538
tags question: http://stackoverflow.com/q/52539910
tags question: http://stackoverflow.com/q/52521475
tags question: http://stackoverflow.com/q/52464094
tags question: http://stackoverflow.com/q/52496804
tags question: http://stackoverflow.com/q/52587022
tags question: http://stackoverflow.com/q/52513495
tags question: http://stackoverflow.com/q/52539986
tags question: http://stackoverflow.com/q/52558382
tags question: http://stackoverflow.com/q/52499536
tags question: http://stackoverflow.com/q/52441919
tags question: http://stackoverflow.com/q/52522171
tags question: http://stackoverflow.com/q/52495852
tags question: http://stackoverflow.com/q/52534569
tags question: http://stackoverflow.com/q/52560683
tags question: http://stackoverflow.com/q/52527333
tags question: http://stackoverflow.com/q/52567121
tags question: http://stackoverflow.com/q/52564903
tags question: http://stackoverflow.com/q/52547380
tag name: machine-learning
tags question: http://stackoverflow.com/q/52572485
tags question: http://stackoverflow.com/q/52476784
tags question: http://stackoverflow.com/q/52572433
tags question: http://stackoverflow.com/q/52507815
tags question: http://stackoverflow.com/q/52586526
tags question: http://stackoverflow.com/q/52543817
tags question: http://stackoverflow.com/q/52513777
tags question: http://stackoverflow.com/q/52489821
tags question: http://stackoverflow.com/q/52453079
type: Tag
tags question: http://stackoverflow.com/q/52573507
tags question: http://stackoverflow.com/q/52498640
tags question: http://stackoverflow.com/q/52433145
tags question: http://stackoverflow.com/q/52558917
tags question: http://stackoverflow.com/q/52484410
tags question: http://stackoverflow.com/q/52537408
tags question: http://stackoverflow.com/q/52571752
tags question: http://stackoverflow.com/q/52511424
tags question: http://stackoverflow.com/q/52434480
tags question: http://stackoverflow.com/q/52563371
tags question: http://stackoverflow.com/q/52566823
tags question: http://stackoverflow.com/q/52534717
tags question: http://stackoverflow.com/q/52452475
tags question: http://stackoverflow.com/q/52453990
tags question: http://stackoverflow.com/q/52528611
tags question: http://stackoverflow.com/q/52464543
tags question: http://stackoverflow.com/q/52525990
tags question: http://stackoverflow.com/q/52580023
tags question: http://stackoverflow.com/q/52471464
tags question: http://stackoverflow.com/q/52467159
tags question: http://stackoverflow.com/q/52566385
tags question: http://stackoverflow.com/q/52444175
tags question: http://stackoverflow.com/q/52577250
tags question: http://stackoverflow.com/q/52450705
tags question: http://stackoverflow.com/q/52542976
tags question: http://stackoverflow.com/q/52433384
tags question: http://stackoverflow.com/q/52483935
tags question: http://stackoverflow.com/q/52579346
tags question: http://stackoverflow.com/q/52452622
tags question: http://stackoverflow.com/q/52546651

http://stackoverflow.com/comment/91821707
type: Comment
comment on: http://stackoverflow.com/q/52439346
score: 1
has text: Also, is this a batch or streaming environment? Because approaching this as a streaming problem may make it conceptually easier.
type: QuestionComment

http://stackoverflow.com/a/52519109
downvote count: 0
score: 1
has body: Alternative solution pets = {"Tom" : Cat("Tom"), "Rex" : Dog("Rex")} print(pets.keys()) print(json.dumps(pets)) In the end, there's no way to say "is there a cat or dog in the dictionary" without looping over all the values
answers question: http://stackoverflow.com/q/52517662
upvote count: 1
type: Answer

http://stackoverflow.com/q/52560716
tagged with: schedule
linked to: http://stackoverflow.com/q/373335
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92060149
tagged with: python
tagged with: module
has body: Is it only me? I cant figure out, how to run job for example every minute on friday with Schedule module import schedule import time def job(x): print("{} Amigo".format(x)) schedule.every(1).minutes.friday.do(job,'Hello') while True: schedule.run_pending() time.sleep(1) This code doesnt throw any error nor expected result. It just do nothing. Am I the only one who needs this kind of scheduling? Because I didnt see any example on this, nothing is in the documentation or in git repository as an example. Could you please advice me, how to do this time logic with this library? Thanks in advnce
answer count: 0
type: Question
has title: Python schedule module, is it only me?
tagged with: jobs
score: 0
has comment: http://stackoverflow.com/comment/92060176
tagged with: cron

http://stackoverflow.com/comment/92077226
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52570221
has text: I guess there is also a goid amount of compiler optimization involved.
score: 1

http://stackoverflow.com/comment/92149828
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52607858
type: AnswerComment
has text: Thank you for your answer(upvote). However, please keep in mind that this small parameters grid (`n_estimators = [150, 175, 200]`) is only for start so I will do a way more extensive grid search and in this sense I think that it is better to do it with `GridSearchCV`. And hence if I want to use `GridSearchCV` with my separate validation set then I will have to use probably `PredefinedSplit` (https://stackoverflow.com/questions/31948879/using-explict-predefined-validation-set-for-grid-search-with-sklearn).

http://stackoverflow.com/q/52521109
tagged with: forms
has comment: http://stackoverflow.com/comment/91982523
has body: I'm trying to send a dynamic amount of selections of checkboxes on obj.html to the /items function. I'm getting the error "Select a valid choice. 1234 is not one of the available choices." But you'll notice that I print the queryset of choices from #views.py, it outputs that 1234 is contained in the flat queryset, with quotes around it. print(form.fields['choices'].queryset) # Console output ['1234', '1243',...] Why is 1234 not one of the available choices? I've tried putting quotes around the value attribute in the input form but it doesn't work. The items function stops because the data is not valid. How can I solve this? # forms.py class ItemForm(forms.Form): choices = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, queryset = Sampledata.objects.none()) # views.py def obj(request, object_id,): data = Sampledata.objects.filter(id=object_id) form = ItemForm() form.fields['choices'].queryset = list(data.values_list('value', flat=True)) print(form.fields['choices'].queryset) return render(request, 'obj.html', {'data':data,'form':form}) def items(request): if request.method == 'POST': form = ItemForm(request.POST) # check whether it's valid: if form.is_valid(): ... # obj.html &lt;form action="/items" method="post"&gt; # Many of these spread out throughout the page {% for obj in data %} &lt;input type="checkbox" name="choices" value="{{obj.value}}"&gt; {% endfor %} &lt;input type="submit" value="Submit"&gt; Updated but still get the same error: def items(request, object_id): if request.method == 'POST': # create a form instance and populate it with data from the request: form = ItemForm(request.POST) data = Sampledata.objects.filter(id=object_id) form.fields['choices'].queryset = (data.values_list('value', flat=True)) # check whether it's valid: if form.is_valid():
tagged with: python
has comment: http://stackoverflow.com/comment/91981823
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/91982275
has comment: http://stackoverflow.com/comment/91981956
tagged with: django
tagged with: django-forms
has title: Django ModelMultipleChoice validation error
type: Question
tagged with: django-models

http://stackoverflow.com/comment/92189250
comment on: http://stackoverflow.com/q/52581584
score: 0
has text: Oh yeah, its working now. Could you post it as an answer so i may accept it ? Thanks.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92004746
type: QuestionComment
comment on: http://stackoverflow.com/q/52532580
score: 0
has text: @Divakar I edited my question - hope it is clearer now.
type: Comment

http://stackoverflow.com/comment/92056342
type: Comment
comment on: http://stackoverflow.com/a/52539943
score: 0
type: AnswerComment
has text: That would work, but as @StevenRumbalski pointed out, dev.extend(rest) will be a better option.

http://stackoverflow.com/comment/91870158
type: QuestionComment
has text: @RafaelC actually the code is for my office use and hence I can't put the actual data here. But yes when I did Df.head(5) I got to find that the error with which KeyError was coming, is not present. The command missed few columns and placed "..." In their place. Although Dr.columns gave me all the columns.
comment on: http://stackoverflow.com/q/52457633
score: 0
type: Comment

http://stackoverflow.com/comment/91996474
type: QuestionComment
has text: have you tried- while(mTotal > 0):
score: 3
comment on: http://stackoverflow.com/q/52528493
type: Comment

http://stackoverflow.com/a/52484062
type: Answer
has body: Using pandas &gt;&gt;&gt; d = pd.read_csv('file.csv', sep=';', header=None).set_index(0).agg(np.array,1).to_dict() {'E1': array([4, 6, 7, 1, 3, 6]), 'E2': array([5, 4, 3, 5, 0, 0]), 'E3': array([2, 3, 3, 0, 0, 0])} Using pure python: with open('file.csv', 'r') as f: d = {} for line in f: l = line.strip().split(';') d[l[0]] = np.array(list(map(int, l[1:]))) {'E1': array([4, 6, 7, 1, 3, 6]), 'E2': array([5, 4, 3, 5, 0, 0]), 'E3': array([2, 3, 3, 0, 0, 0])}
answers question: http://stackoverflow.com/q/52483977
score: 0
accepted answer of: http://stackoverflow.com/q/52483977
type: AcceptedAnswer

http://stackoverflow.com/comment/92072616
type: AnswerComment
comment on: http://stackoverflow.com/a/52554612
has text: if I am doing company.first() it will only filter the groups and ledgers of the first company...What if the user select the second company which the user have created
score: 0
type: Comment

http://stackoverflow.com/comment/91811373
has text: You can't pass fixtures as test parameters in `unittest` test classes, only in test functions. Check out [Using autouse fixtures and accessing other fixtures](https://docs.pytest.org/en/latest/unittest.html#using-autouse-fixtures-and-accessing-other-fixtures) for an example of applying fixtures in `unittest` test classes via autousing, it happens to be the `tmpdir` usage.
type: QuestionComment
comment on: http://stackoverflow.com/q/52433546
score: 0
type: Comment

http://stackoverflow.com/comment/102281664
comment on: http://stackoverflow.com/a/57932294
score: 0
type: AnswerComment
type: Comment
has text: When your answer is too short, you can send it as a comment.

http://stackoverflow.com/comment/91836946
score: 0
type: Comment
has text: By the way, neither `*` nor `*u*` are valid regex patterns. You may be thinking of globbing.
type: QuestionComment
comment on: http://stackoverflow.com/q/52446975

http://stackoverflow.com/a/52514094
answers question: http://stackoverflow.com/q/52513904
score: 1
upvote count: 1
has body: d1 = {"a":1} d2 = {"b":2} import json array = [json.dumps(d) for d in [d1,d2]] Then write array to file
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92086375
type: QuestionComment
comment on: http://stackoverflow.com/q/52575131
has text: maybe you can look in the js code what type of encryption used, and use the method of encryption yourself.
score: 0
type: Comment

http://stackoverflow.com/a/52457003
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52456966
has body: You can use the following nested loop: s = {} for t, c in D.items(): for i in t: s[i] = s.get(i, 0) + c s would become: {'a': 4, 'b': 6, 'c': 6}
downvote count: 0

http://stackoverflow.com/a/52557279
type: Answer
accepted answer of: http://stackoverflow.com/q/52556616
score: 0
answers question: http://stackoverflow.com/q/52556616
type: AcceptedAnswer
has body: this may be help import json import hmac import hashlib import time from websocket import create_connection key = "" secret = "" class Bitfinex(object): def __init__(self, secret, key): self.secret = secret self.key = key self.url = 'wss://api.bitfinex.com/ws/2' self.nonce = str(int(time.time() * 1000000)) self.signature = hmac.new(str.encode(self.secret), bytes('AUTH' + self.nonce, 'utf8'), hashlib.sha384).hexdigest() self.payload = {'apiKey': self.key, 'event': 'auth', 'authPayload': 'AUTH' + self.nonce, 'authNonce': self.nonce, 'authSig': self.signature} self.ws = create_connection(url) def get_chanid(self, symbol): self.ws.send(json.dumps(self.payload)) get_chanid = { 'event': "subscribe", 'channel': "ticker", 'symbol': "t" + symbol, } self.ws.send(json.dumps(get_chanid)) while True: data = self.ws.recv() print(data) bit = Bitfinex(secret, key) bit.get_chanid('BTCUSD')

http://stackoverflow.com/a/52432220
type: AcceptedAnswer
has body: TL;DR socket.AF_INET = The type of socket address socket.SOCK_STREAM = The type of socket Explanation Whenever you provide socket.AF_INET to your server you instruct it to listen to an IPv4 address, and to your client to connect to an IPv4 address. This will work. Same for IPv6. However mixing them up doesn't. That would be the same me waiting for you to talk to me on StackOverflow while you send me messages by email. We are not looking at the same spot, so we won't be able to communicate. Same for socket.SOCK_STREAM (and the other values). The difference lies in the fact that this tells python's socket how we are going to communicate. socket.SOCK_STREAM will be TCP, while socket.SOCK_DGRAM will be UDP. Let's come back to our "real world" example and let's imagine we agreed on communicating by email. I could expect either one email from you (explaining me everything you have to tell) or several (with a part of what you have to say in each email). That's the same as TCP vs UDP. References Well, I guess you have read both: python's socket module python's socket How to Potentially: SO: What is Address Family? Wikipedia: IPv4 Also, I guess: Difference Between Socket Types (and the references therein) Wikipedia: Network socket - Types Super long explanation but mostly testing So. If after all that you don't understand. Let's try: # server.py import socket s = socket.socket() s.bind(('localhost', 5050)) s.listen(5) while True: (clientsocket, address) = s.accept() print 'client connected' And: # client.py import socket s = socket.socket(socket.AF_INET) s.connect(('127.0.0.1', 5050)) print "Yeah! I'm connected :)" So far, everything as in the how to. We launch our server: $ python server.py And then we launch our client: $ python client.py Yeah! I'm connected :) Everything works fine. That's good. Now, lets change our client: # client.py import socket s = socket.socket(socket.AF_INET6) s.connect(('127.0.0.1', 5050)) print "Yeah! I'm connected :)" And relaunch our new client…
type: Answer
accepted answer of: http://stackoverflow.com/q/52431424
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91861597
answers question: http://stackoverflow.com/q/52431424
downvote count: 0

http://stackoverflow.com/q/52461441
has body: I have already looked through and tried all the solutions on Stackoverflow, however they still don't work for me. I've installed pydot, graphviz, and pydotplus already, and I still get this error while trying to generate a model: 'ImportError Traceback (most recent call last) &lt;ipython-input-80-1ebf31238a67&gt; in &lt;module&gt;() 99 # summarize defined model 100 print(model.summary()) --&gt; 101 plot_model(model, to_file='model.png', show_shapes=True) ~\Anaconda3\lib\site-packages\keras\utils\vis_utils.py in plot_model(model, to_file, show_shapes, show_layer_names, rankdir) 130 'LR' creates a horizontal plot. 131 """ --&gt; 132 dot = model_to_dot(model, show_shapes, show_layer_names, rankdir) 133 _, extension = os.path.splitext(to_file) 134 if not extension: ~\Anaconda3\lib\site-packages\keras\utils\vis_utils.py in model_to_dot(model, show_shapes, show_layer_names, rankdir) 53 from ..models import Sequential 54 ---&gt; 55 _check_pydot() 56 dot = pydot.Dot() 57 dot.set('rankdir', rankdir) ~\Anaconda3\lib\site-packages\keras\utils\vis_utils.py in _check_pydot() 18 if pydot is None: 19 raise ImportError( ---&gt; 20 'Failed to import `pydot`. ' 21 'Please install `pydot`. ' 22 'For example with `pip install pydot`.') ImportError: Failed to import `pydot`. Please install `pydot`. For example with `pip install pydot`. Here is my Code, the model summary prints, but not the model itself: model = define_model(khm_vocab_size, eng_vocab_size, khm_length, eng_length, 256) model.compile(optimizer='adam', loss='categorical_crossentropy') # summarize defined model print(model.summary()) plot_model(model, to_file='model.png', show_shapes=True) # fit model filename = 'model.h5' checkpoint = ModelCheckpoint(filename, monitor='val_loss', verbose=1, save_best_only=True, mode='min') model.fit(trainX, trainY, epochs=30, batch_size=64, validation_data=(testX, testY), callbacks=[checkpoint], verbose=2)
tagged with: anaconda
score: 0
tagged with: keras
has title: Pydot won't output models in Anaconda-Jup NoteBook
has comment: http://stackoverflow.com/comment/91867836
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91869222
tagged with: python
tagged with: jupyter-notebook
answer count: 0
tagged with: pydot
has comment: http://stackoverflow.com/comment/91874919
type: Question

http://stackoverflow.com/a/52541032
downvote count: 1
has comment: http://stackoverflow.com/comment/92024453
has comment: http://stackoverflow.com/comment/92022296
has body: You need to convert the values to the right type before sending them to the database. user_i = '' rate_i = request.form.get("rate", type=int) user_i = session['user'] time_i = datetime.now() id_i = int(all2[0]) db.execute("INSERT INTO review_table (id, review, rate , user , time_t) VALUES (?, ?, ? , ? , ?)" , (id_i, review_i, rate_i , user_i , time_i ))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52540555
upvote count: 1

http://stackoverflow.com/q/52513973
tagged with: tensorflow
has body: I have updated the example program in the keras cifar10_resnet to work on the cifar 100 instead of cifar 10 data set. I am able to run the code only for the first epoch. When i try to save the model the programs breaks with the below error - 'KeyError: 'Cannot set attribute. Group with name "keras_version" exists.' I have python 3.5.2, tensorflow gpu version 1.10.1 in my laptop.
type: Question
has title: Cannot set attribute. Group with name "keras_version" exists
upvote count: 3
tagged with: deep-learning
answer count: 3
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/52613471
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52661678
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52608138

http://stackoverflow.com/a/52459984
has comment: http://stackoverflow.com/comment/91889173
has comment: http://stackoverflow.com/comment/91869061
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91910896
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52459478
answers question: http://stackoverflow.com/q/52459478
score: 2
has body: When you changed sys.stdout, you lost the ability to write to the console. This code does exactly what you told it to do. If I look at for_posterity.txt, it says inside fun 1 inside fun 2 inside fun 1 inside fun 2 ... If you want a logging function which does both, you have to actually do both. def output(message): with open("for_posterity.txt", "a") as logfile: print (message) logfile.write(message + "\n") def fun1(): time.sleep(1) output("inside fun 1") def fun2(): time.sleep(1) output("inside fun 2") However, when you get more advanced, you will want to use the logging module, which you can configure to write to as many or as few places as you want, and it can decide based on what's happening. https://docs.python.org/3/library/logging.html

http://stackoverflow.com/q/52556781
answer count: 1
score: 0
tagged with: tkinter
has title: Python - Can I use a lambda function to generate a repetitive GUI with tkinter? (labels/text/buttons)
tagged with: python
has body: I have a very repetitive GUI to implement - think tens of label/text/button fields, for a data entry form. The sizes of each repeated section can be the same - in fact, everything can be the same except the text in the label and the variable that the data from the text field is assigned to upon completion. I've worked with an engineer who used lambda functions to generate sub-functions in a very complex way which I almost followed, but not quite 100%. I was hoping, since this is a similar, mostly repetitive task, that there was some way to use a formulaic function to repeat the GUI creation work for me, rather than to have to type out each and every GUI item. Is it possible to have repetitive GUI elements generated by a function, and if so, is that a lambda function? Or is there a different (or better) way to accomplish the same "not repeating myself"?
tagged with: lambda
has answer: http://stackoverflow.com/a/52557551
accepted answer: http://stackoverflow.com/a/52557551
type: AnsweredQuestion
tagged with: tk-toolkit
has comment: http://stackoverflow.com/comment/92059235
has comment: http://stackoverflow.com/comment/92052140
has comment: http://stackoverflow.com/comment/92052145
type: Question
has comment: http://stackoverflow.com/comment/92059237
tagged with: user-interface

http://stackoverflow.com/a/52548432
has comment: http://stackoverflow.com/comment/92064954
type: Answer
has comment: http://stackoverflow.com/comment/92064979
answers question: http://stackoverflow.com/q/52548218
has comment: http://stackoverflow.com/comment/92036108
has comment: http://stackoverflow.com/comment/92036101
score: 0
has body: If you're in control of the input, don't do it this way. If the gal or guy on the input end is the client/boss, curse the code gods under your breath and write a helper function like this: # returns a list of plaintext lines and a json string. def split_text_and_json(filename): textlines = [] jsonlines = [] bracketcount = 0 with open(filename) as f: for line in f.readlines(): bracketcount += line.count('{') if bracketcount: jsonlines.append(line) else: textlines.append(line) bracketcount-=line.count('}') return (textlines, ''.join(jsonlines)) plaintextpart, jsonpart = split_text_and_json('file.txt') You could do this inline if the JSON was always guaranteed to be the last part of the file. Now for the bad stuff: You need to handle files that include the { } characters outside of the json. This script will throw errors in that case when you try to load the json.

http://stackoverflow.com/comment/91924444
has text: Possible duplicate of [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date)
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52491900

http://stackoverflow.com/comment/91952026
type: Comment
has text: Is dot in your command PATH? Can you run it directly in the command prompt? I assume tree.dot is being created in the current directory.
score: 0
comment on: http://stackoverflow.com/q/52505606
type: QuestionComment

http://stackoverflow.com/q/52446975
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/91837016
upvote count: 0
has body: How would I test if a string June tests True for any of the regex patterns in a given list, ignoring case sensitivity as well. I'm using python to do this. ['Ju*','October'] = True ['june','November'] = True ['*u*','October'] = True ['Junee','October'] = False ['October']` = False ['*'] = True
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52448474
has comment: http://stackoverflow.com/comment/91837308
has comment: http://stackoverflow.com/comment/91836919
tagged with: python
has comment: http://stackoverflow.com/comment/91839050
has comment: http://stackoverflow.com/comment/91837050
score: -3
accepted answer: http://stackoverflow.com/a/52448474
has comment: http://stackoverflow.com/comment/91836946
has title: Check if string matches regex list of patterns in Python
type: Question

http://stackoverflow.com/comment/131793770
type: AnswerComment
has text: @FelixBertoni What is the difference?
comment on: http://stackoverflow.com/a/60026172
type: Comment
score: 1

http://stackoverflow.com/comment/91870646
comment on: http://stackoverflow.com/a/52464384
type: Comment
score: 1
has text: How does the last one reverse?
type: AnswerComment

http://stackoverflow.com/comment/92279099
has text: Thanks for the update. I think there's something odd with my environment. On OS X (python 3.7) I get consistent order in the elements. On my Debian 8 server (python 3.4.2) I'm still getting random order. Thanks again for taking another look.
comment on: http://stackoverflow.com/a/52561946
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92081313
has text: What you want and what you have written in the code is a bit confusing. Try to explain what you want more clearly
comment on: http://stackoverflow.com/q/52572412
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52561874
accepted answer: http://stackoverflow.com/a/52562060
tagged with: continuous
possible better answer: http://stackoverflow.com/a/52562225
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52562225
downvote count: 0
has title: Counting continuous nan values in panda Time series
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/2154249
has answer: http://stackoverflow.com/a/52562060
tagged with: python
has answer: http://stackoverflow.com/a/52561935
type: AnsweredQuestion
score: 1
has body: I actually work on time series in Python 3 and Pandas and I want to make a synthesis of periods of contiguous missing values but I'm only able to find the indexes of nan values ... Sample data : Valeurs 2018-01-01 00:00:00 1.0 2018-01-01 04:00:00 NaN 2018-01-01 08:00:00 2.0 2018-01-01 12:00:00 NaN 2018-01-01 16:00:00 NaN 2018-01-01 20:00:00 5.0 2018-01-02 00:00:00 6.0 2018-01-02 04:00:00 7.0 2018-01-02 08:00:00 8.0 2018-01-02 12:00:00 9.0 2018-01-02 16:00:00 5.0 2018-01-02 20:00:00 NaN 2018-01-03 00:00:00 NaN 2018-01-03 04:00:00 NaN 2018-01-03 08:00:00 1.0 2018-01-03 12:00:00 2.0 2018-01-03 16:00:00 NaN Expected results : Start_Date number of contiguous missing values 2018-01-01 04:00:00 1 2018-01-01 12:00:00 2 2018-01-02 20:00:00 3 2018-01-03 16:00:00 1 How can i manage to obtain this type of results with pandas (shift(), cumsum(), groupby() ???)? Thank you for your advice! Sylvain
upvote count: 1
type: Question
tagged with: time-series

http://stackoverflow.com/q/52551398
tagged with: python-3.x
linked to: http://stackoverflow.com/q/21142231
has title: Slicing a list into sublists based on condition
has answer: http://stackoverflow.com/a/52551537
accepted answer: http://stackoverflow.com/a/52551537
has body: I want to slice this list of numbers: num_list = [97, 122, 99, 98, 111, 112, 113, 100, 102] into multiple sublists. The condition for slicing is that the numbers in each sublist should be in increasing order. So the final result will look like this: list_1 = [97, 122] list_2 = [99] list_3 = [98, 111, 112, 113] list_4 = [100, 102] Can anyone help me to solve this problem please? Thanks a lot
tagged with: python
score: 14
type: AnsweredQuestion
tagged with: list
upvote count: 14
has answer: http://stackoverflow.com/a/52551664
type: Question
has answer: http://stackoverflow.com/a/52552301
duplicate of: http://stackoverflow.com/q/21142231
downvote count: 0
possible better answer: http://stackoverflow.com/a/52551664
answer count: 4
has answer: http://stackoverflow.com/a/52551746
favorite count: 0

file
type: Tag
tags question: http://stackoverflow.com/q/52502689
tags question: http://stackoverflow.com/q/52516680
tags question: http://stackoverflow.com/q/52488122
tags question: http://stackoverflow.com/q/52541568
tags question: http://stackoverflow.com/q/52572007
tags question: http://stackoverflow.com/q/52496374
tags question: http://stackoverflow.com/q/52498677
tags question: http://stackoverflow.com/q/52495625
tags question: http://stackoverflow.com/q/52545269
tags question: http://stackoverflow.com/q/52485698
tag name: file
tags question: http://stackoverflow.com/q/52545749
tags question: http://stackoverflow.com/q/52471197
tags question: http://stackoverflow.com/q/52431602
tags question: http://stackoverflow.com/q/52583932
tags question: http://stackoverflow.com/q/52568711
tags question: http://stackoverflow.com/q/52445319
tags question: http://stackoverflow.com/q/52505483
tags question: http://stackoverflow.com/q/52498776
tags question: http://stackoverflow.com/q/52474813
tags question: http://stackoverflow.com/q/52503249
tags question: http://stackoverflow.com/q/52467516
tags question: http://stackoverflow.com/q/52520031
tags question: http://stackoverflow.com/q/52500359
tags question: http://stackoverflow.com/q/52513271
tags question: http://stackoverflow.com/q/52516127
tags question: http://stackoverflow.com/q/52440321
tags question: http://stackoverflow.com/q/52573600
tags question: http://stackoverflow.com/q/52547143
tags question: http://stackoverflow.com/q/52526524

http://stackoverflow.com/a/78580647
answers question: http://stackoverflow.com/q/52459123
type: Answer
upvote count: 2
has body: The previously accepted answer in not valid anymore, since Pyglet does not even have a «canvas» module these days. Try this instead: viewport = pyglet.display.get_display().get_default_screen() left = viewport.width // 2 - WINDOW_WIDTH // 2 top = viewport.height // 2 - WINDOW_HEIGHT // 2 self.set_location(left, top)
score: 2
downvote count: 0

http://stackoverflow.com/q/52500449
tagged with: tox
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/52501062
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/70020257
tagged with: python
has body: I have python application which I would like to test. This application is importing a lot of packages for example: import time import sys . . . import mypackage Where mypackage is my own package. When I start application everything works fine. However, as soon as I try to run tox to test it I will get the following error: Collecting mypackage Could not find a version that satisfies the requirement mypackage (from versions: ) No matching distribution found for mypackage I understand that tox can't install mypackage dependency since it is not in pip. Do you know how to run tox on such application or how to install own packages with tox ? Content of my tox.ini file: [tox] envlist = py36 [testenv] deps = pytest coverage time sys mypackage commands = python setup.py develop coverage erase coverage run -m pytest myapp/tests/ coverage report --omit='.tox/*'
type: UnansweredQuestion
type: Question
has title: Use own package in tox+pytest
tagged with: pytest
has answer: http://stackoverflow.com/a/73080181
linked to: http://stackoverflow.com/q/15031694
upvote count: 4

http://stackoverflow.com/comment/91929982
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52494633
score: 0
has text: According to Python 3.7 documentation, your code should work. https://docs.python.org/3/library/datetime.html I guess your problem has a different reason.

http://stackoverflow.com/a/52450993
has comment: http://stackoverflow.com/comment/91952020
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91864143
has body: I think the issue is that your receiving slot doesn't match any of the available .activated signals. self.activated.connect(self.setdatastrength) @QtCore.pyqtSlot() def setdatastrength(self): index = self.currentIndex() it = self.compressive_strength[index] print(it) self.concreteproperty.display_condata(it) The QComboBox.activated signal emits either an int of the index, or a str of the selected value. See documentation. You've attached it to setdatastrength which accepts doesn't accept any parameters (aside from self, from the object) — this means it doesn't match the signature of either available signal, and won't be called. If you update the definition to add the index value, and accept a single int it should work. self.activated.connect(self.setdatastrength) @QtCore.pyqtSlot(int) # add the target type for this slot. def setdatastrength(self, index): it = self.compressive_strength[index] print(it) self.concreteproperty.display_condata(it) After the update — the above looks now to be fixed, although you don't need the additional index = self.currentIndex() in setdatastrength it's not doing any harm. Looking at your code, I think the label is being updated. The issue actually is that you can't see the label at all. Looking at the init for ConcreteProperty class ConcreteProperty(QtWidgets.QWidget): def __init__(self, parent=None): super(ConcreteProperty, self).__init__(parent) self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False)) self.concretestrength_lay = QtWidgets.QHBoxLayout() fctd = "\nfcd\n\nfctd\n\nEc" con_strength = QtWidgets.QLabel(fctd) self.con_strength_value = QtWidgets.QLabel(" ") self.concretestrength_lay.addWidget(con_strength) self.concretestrength_lay.addWidget(self.con_strength_value, alignment=QtCore.Qt.AlignLeft) The reason the changes are not appearing is that you create two ConcreteProperty objects, one in ConcreteStrengthInfo and one in ConcreteStrengthComboBox. Updates to the combo box trigger an update of the Concrete…
has comment: http://stackoverflow.com/comment/91845692
type: Answer
has comment: http://stackoverflow.com/comment/91882629
has comment: http://stackoverflow.com/comment/91938792
has comment: http://stackoverflow.com/comment/91851313
has comment: http://stackoverflow.com/comment/91915830
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52450713
answers question: http://stackoverflow.com/q/52450713
has comment: http://stackoverflow.com/comment/91853803
has comment: http://stackoverflow.com/comment/91856153
has comment: http://stackoverflow.com/comment/91864354

http://stackoverflow.com/a/53620034
type: Answer
answers question: http://stackoverflow.com/q/52569791
has body: from flask_pymongo import Pymongo import json import pandas as pd user = pd.DataFrame(user) mongo.db.users.insert_one({'email':json.loads(user[0].to_json(orient='index')), 'password':json.loads(user[1].to_json(orient='index'))}) This will throw up errors if your objects are already json. If they aren't though, it'll turn them into json and load them all in one go.
score: 0

http://stackoverflow.com/q/52468487
tagged with: pandas
downvote count: 0
favorite count: 0
has title: Pandas doesnt recognize categorical -- access original codes when convert_categorical=True
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I have a stata .dta file. If I open it in stata, I can see several columns with value labels. I can go into browse, click on one of them, and see the original code behind the label. If I read this .dta file into python via pd.read_stata(..., convert_categoricals=True), I can get the data types via df.dtypes. For some of the columns, categories have been created. However, for one column of interest, instead a series with dtype Object has been created, which contains the labels as string. How exactly does the process of category creation in pd.read_stata work? How can I access the original data codes behind the labels when reading in with convert_categorical=True What do I do in the case where columns are converted into dtype Object -- do I have to read in the data frame a second time with convert_categoricals=False and merge? That really sounds non-pythonic.
type: Question

http://stackoverflow.com/comment/92075668
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52568718
has text: Just did. Thanks
score: 0

http://stackoverflow.com/a/52523460
accepted answer of: http://stackoverflow.com/q/52519892
has comment: http://stackoverflow.com/comment/91992012
has body: I guess you could literally just do something like this. from pynput.keyboard import Key, Controller, Listener import time def on_press(key): print('{0} pressed'.format( key)) def on_release(key): print('{0} release'.format( key)) if key == Key.esc: # Stop listener return False # Collect events until released with Listener( on_press=on_press, on_release=on_release) as listener: listener.join() keyboard = Controller ()# You should only need to define this once while(True):# This will repeat the indented code below forever time.sleep(0.1) for char in "vcmine start": keyboard.press(char) keyboard.release(char) time.sleep(0.03) keyboard.press(Key.enter) keyboard.release(Key.enter) # However the only way you can stop it is by closing the program This is pretty much just copied and pasted from https://pythonhosted.org/pynput/keyboard.html under the section Monitoring the Keyboard. First run the code, then place the cursor where you want the text to be typed, then by hitting the esc key on the keyboard the rest of the code will now run and will type what you want where you want it. Also note that if you run the code and then put the cursor in another text field while this is running it will start to type there instead. for and while loops can be confusing at first but definitely read up on them because they are used a lot in coding and are very useful. While Python is my favorite language it has a bit more variety with respect to how loops can be defined which might be kind of confusing at first. Use google ALOT to find tutorials and YouTube videos on the subject (there's tons of great info out there).
type: Answer
has comment: http://stackoverflow.com/comment/91992659
answers question: http://stackoverflow.com/q/52519892
has comment: http://stackoverflow.com/comment/91990168
has comment: http://stackoverflow.com/comment/92003352
has comment: http://stackoverflow.com/comment/91991240
has comment: http://stackoverflow.com/comment/92027144
has comment: http://stackoverflow.com/comment/91999899
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91930725
type: AnswerComment
comment on: http://stackoverflow.com/a/52495046
score: 0
type: Comment
has text: Wow, not yet documented code. But thanks, I think I am getting now closer to what I really want...

http://stackoverflow.com/a/52471311
score: 0
accepted answer of: http://stackoverflow.com/q/52471194
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52471194
has body: As the documentation for find says, it stops at the first node it finds. You need to iterate over the parent node to find all of them, and check the value. Here is an example. from xml.etree import ElementTree with open("data.xml", "rb") as fo: root = ElementTree.parse(fo) for plantnode in root.findall("PLANT"): if plantnode.find("COMMON").text == "Columbine": pricenode = plantnode.find("PRICE") print(pricenode.text) pricenode.text = '3.50' print(pricenode.text)

http://stackoverflow.com/comment/92020703
comment on: http://stackoverflow.com/a/52527604
score: 0
type: AnswerComment
has text: As far as I know it is supported, but I can't find a document to confirm this.
type: Comment

http://stackoverflow.com/comment/92053447
score: 2
type: AnswerComment
has text: [`is` is not equivalent to `===`!](https://stackoverflow.com/q/306313/476) `a = 12345; a is 12345 # false`
comment on: http://stackoverflow.com/a/52557440
type: Comment

http://stackoverflow.com/q/52451429
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52453795
has comment: http://stackoverflow.com/comment/91847234
has title: Scrape HTML off AppBuilder page
downvote count: 3
tagged with: web-scraping
type: Question
tagged with: ecmascript-6
upvote count: 0
tagged with: javascript
accepted answer: http://stackoverflow.com/a/52453795
has comment: http://stackoverflow.com/comment/91849953
answer count: 1
has body: I found this website with some interesting data I wish to analyze. But the page is really slow and build around .docx files. But it has a preview of each document in HTML http://www.produktresume.dk/AppBuilder/search?page=0 My current idea for a strategy is: Wait for the page to load (haven't tried this before) Dig into the div class="widget_inside" Grab all the href in &lt;a class="preview_link" Iterate over all the collected links and parse the HTML into some .json/.csv for later analysis I'm pretty new when it comes to scraping, and had previously some luck with BeautifulSoup in Python - with a page that don't have a loading. But I have been using nodejs lately, so would prefer to be able to do it in JS with some npm package. Anybody who can help me out finding the right tools for the job and some pointers/comments on the best strategy? Bonus info By decoding one of the filter links to the left this comes up: http://www.produktresume.dk/AppBuilder/search?expand_all=true&amp;page=0&amp;refinements_token={}&amp;selected_tokens[]={"s":[{"id":"folder-refinement","xPath":"$folders","separator":"\u003e","logic":"OR","s":[{"n":"Human","k":"Human"}]}]} Don't know if that would be of any use?
favorite count: 0
score: -3
tagged with: python

http://stackoverflow.com/q/52558760
has answer: http://stackoverflow.com/a/52560355
score: 0
tagged with: python
type: UnansweredQuestion
has body: Currently my django admin site's setup looks like Topic submit_date: 2018/09/25 submit_user: blah Topic-category1 sub-topic field1 field2 --------------------------------- bleh bleh1 bleh2 mlem mlem1 mlem2 Topic-category2 something something1 something2 --------------------------------------- asd asd1 asd2 asd2 asd2-1 asd2-2 I want to add a note section in between Topic-category1 and the table, so it looks like Topic-category1 &lt;this is where the note goes, functions like description&gt; sub-topic field1 field2 --------------------------------- bleh bleh1 bleh2 mlem mlem1 mlem2 Is there a way for django admin to do it? I'm not using any of the custom form. Only using ModelAdmin and modify variables here and there
tagged with: django
type: Question
tagged with: django-admin
has title: Adding note in Django Admin site's TubularInline
answer count: 1

http://stackoverflow.com/comment/92101539
comment on: http://stackoverflow.com/q/52583246
has text: Notice `max` isn't defined if a certain conditional is not executed. And if you don't define `max`, since you're shadowing a built-in Python function name, Python will attempt to use the builtin `max` function in the expression `str1 = ''.join(str(e) for e in max)`, which obviously won't work. Firstly, make sure variables aren't just defined in conditionals. Always define variables outside of conditionals. Secondly, don't shadow builtin variable names. Use some other name rather than `max`.
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/a/52450865
has comment: http://stackoverflow.com/comment/91845899
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52450778
has body: You can continue with loop if 2 arrays are equal. For instance, if: k1 = [0,0,0,0,0]; k2 = [0,0,0,0,0]; then you can check whether k1 == k2. If it is true, just use continue for your loop. Like this: if ( k1 == k2 ) == True: continue just before you call mannwhitneyu(k1, k2)
score: 2
answers question: http://stackoverflow.com/q/52450778
downvote count: 0

http://stackoverflow.com/a/52535205
answers question: http://stackoverflow.com/q/52534907
type: Answer
has comment: http://stackoverflow.com/comment/92011814
upvote count: 2
score: 2
has body: If you want to apply an operation to a rectangular box you can pass in the region by index. So first dilate the whole image: dilated_img = cv2.dilate(img, np.ones((5, 5), np.uint8)) Then overwrite the region requiring higher dilation: dilated_img[10:50, 30:40] = cv2.dilate(img[10:50, 30:40], np.ones((20, 20), np.uint8))
has comment: http://stackoverflow.com/comment/92011653
downvote count: 0

http://stackoverflow.com/comment/92100427
has text: how do I change it so it returns the largest prime number???
comment on: http://stackoverflow.com/q/52582652
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91814634
type: AnswerComment
has text: Oh snap, I can imagine how tedious it can be! Thanks for the advice. I will be keeping that in mind for future assignments! This one was given to me without context or clear instructions. :D
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52435479

http://stackoverflow.com/comment/91920607
has text: If you definitely need to access both databases from one service, Django does support configuration for [multiple databases](https://docs.djangoproject.com/en/2.1/topics/db/multi-db/); is this not appropriate for your use case? Though it does seem to me that as you're using microservices it might be more appropriate to get whatever user data you need from an endpoint on the auth service rather than subverting the architecture by going straight to the DB.
comment on: http://stackoverflow.com/q/52475303
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/52541312
type: Answer
upvote count: 4
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52534211
downvote count: 0
has comment: http://stackoverflow.com/comment/113265751
accepted answer of: http://stackoverflow.com/q/52534211
has body: You'll probably want to use protocols here. In short, you define a custom protocol in your codebase containing signatures for methods any "connection" object must have. Then, you're free to return any arbitrary object so long as it contains those methods with the specified methods. Final note: I know that mypy supports protocols, but I'm not sure if other type checkers do. There's an open PEP to formally introduce protocols to the Python typing ecosystem -- presumably other type checkers will add support for protocols once that PEP is accepted, if they haven't already.

http://stackoverflow.com/comment/92058344
comment on: http://stackoverflow.com/a/52559801
has text: @RickyKim: The program allows other choices. See the code: `if user_choice == "rock" or user_choice == "r":`.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/129170330
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52557037
has text: Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/)). By SE policy, any vandalism will be reverted.

http://stackoverflow.com/comment/129242090
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52468783
has text: I resolved it by increasing the size of the neural network.
score: 1

http://stackoverflow.com/q/52529031
has answer: http://stackoverflow.com/a/52530120
accepted answer: http://stackoverflow.com/a/52530120
type: Question
has comment: http://stackoverflow.com/comment/91997596
has comment: http://stackoverflow.com/comment/91997570
has body: I have this string str = "Hello (m)y name (?) is (donal)d (!) " and expect the following output: "Hello my name (?) is donald (!) " I tried it with r = re.sub(r'([()+])', '', str) But this removes all parentheses. What am I missing?
has title: Remove only parentheses from string not characters between them but ignore certain parentheses
has comment: http://stackoverflow.com/comment/91997657
downvote count: 3
has comment: http://stackoverflow.com/comment/91997611
answer count: 1
favorite count: 0
tagged with: python-3.x
score: -3
has comment: http://stackoverflow.com/comment/91997560
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91997506
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/91933083
comment on: http://stackoverflow.com/q/52495623
type: Comment
type: QuestionComment
has text: Have you tried adding both libraries to a `requirements.txt` file and then run `pip install -t lib/ -r requirements.txt`?
score: 0

http://stackoverflow.com/comment/91945727
has text: @IMCoins Hm yes I modified my question quite a bit. But I was doing this pandas conversion only when doing `h2o.init()` and not with the second way which I show above.
comment on: http://stackoverflow.com/a/52502277
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52544130
answers question: http://stackoverflow.com/q/52495773
type: Answer
score: 0
type: AcceptedAnswer
has body: for passnum in range(len(alist)-1,0,-1): Per the range function documentation: len(alist) - 1 is the length of the list (8) minus one (7). It represents some "starting" number. 0 represents the "stopping" number. -1 represents the "step" number. These come together in range(len(alist) - 1, 0, -1) to say "count from 7 to 0, backwards - one negative step at a time". for i in range(passnum): When range() is only passed one argument (a number), it counts from 0 to that number. The documentation gives this example: list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] So the code counts from 7 down to 0 - and every time it performs a single count, it immediately counts from 0 to that number.
accepted answer of: http://stackoverflow.com/q/52495773

http://stackoverflow.com/comment/91848225
comment on: http://stackoverflow.com/a/52452432
type: AnswerComment
score: 0
type: Comment
has text: I am assuming that the initial sort does not preserve order, which is important...

http://stackoverflow.com/comment/91837695
comment on: http://stackoverflow.com/q/52447364
score: 0
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga Why not?

http://stackoverflow.com/comment/136370839
type: AnswerComment
comment on: http://stackoverflow.com/a/74936772
type: Comment
has text: Thanks for this answer. My understanding from this is -- basically, if Python thread is not running Python byte-code but C code (the 3 cases mentioned above), then GIL is released.
score: 1

http://stackoverflow.com/q/52578848
has body: I have a pandas dataframe which contains some sar output that I would like to plot in matplotlib. Sample data is below. &gt;&gt;&gt; cpu_data.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 70 entries, 0 to 207 Data columns (total 8 columns): 00:00:01 70 non-null datetime64[ns] CPU 70 non-null object %user 70 non-null float64 %nice 70 non-null float64 %system 70 non-null float64 %iowait 70 non-null float64 %steal 70 non-null float64 %idle 70 non-null float64 dtypes: float64(6), object(2) memory usage: 4.4+ KB &gt;&gt;&gt; cpu_data 00:00:01 CPU %user %nice %system %iowait %steal %idle 0 00:10:01 all 0.30 0.00 0.30 0.06 0.0 99.34 3 00:20:01 all 0.09 0.00 0.13 0.00 0.0 99.78 6 00:30:01 all 0.07 0.00 0.11 0.00 0.0 99.81 9 00:40:01 all 0.08 0.00 0.11 0.00 0.0 99.80 12 00:50:01 all 0.08 0.00 0.13 0.00 0.0 99.79 15 01:00:04 all 0.09 0.00 0.13 0.00 0.0 99.77 18 01:10:01 all 0.27 0.00 0.28 0.00 0.0 99.46 21 01:20:01 all 0.09 0.00 0.11 0.00 0.0 99.79 24 01:30:04 all 0.12 0.00 0.13 0.01 0.0 99.74 27 01:40:01 all 0.08 0.00 0.11 0.01 0.0 99.80 30 01:50:01 all 0.09 0.00 0.13 0.01 0.0 99.77 I want to plot using the timestamps as the x-axis. I have written the following code. import pandas as pd import os import matplotlib.pyplot as plt import matplotlib.dates as md import dateutil import matplotlib.dates as mdates cpu_data[cpu_data.columns[0]] = [dateutil.parser.parse(s) for s in cpu_data[cpu_data.columns[0]]] plt.subplots_adjust(bottom=0.2) plt.xticks( rotation=25 ) ax=plt.gca() ax.xaxis_date() xfmt = md.DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(xfmt) cpu_data.plot(ax=ax) plt.show() But I get the following error ValueError: view limit minimum -5.1000000000000005 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units This doesn't make any sense because I manually converted all of the time stamp strings to datetime objects cpu_data[cpu_data.columns[0]] = [dateutil.par…
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92095595
tagged with: python
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/92093880
type: Question
score: 5
has title: ValueError: view limit minimum -5.1000000000000005 is less than 1 and is an invalid Matplotlib date value
has comment: http://stackoverflow.com/comment/92093058
upvote count: 5
tagged with: matplotlib
has answer: http://stackoverflow.com/a/54560210
tagged with: pandas
has comment: http://stackoverflow.com/comment/92093189
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91924733
type: QuestionComment
has text: You should read about mutable vs immutable objects in Python
score: 1
comment on: http://stackoverflow.com/q/52491747
type: Comment

http://stackoverflow.com/comment/91934411
type: AnswerComment
type: Comment
has text: Awee You are awesome. It took all my morning and afternoon for finding a solution for it. Thank you so much.
comment on: http://stackoverflow.com/a/52496952
score: 0

http://stackoverflow.com/q/52537294
upvote count: 2
tagged with: screen-scraping
accepted answer: http://stackoverflow.com/a/52538317
type: Question
possible better answer: http://stackoverflow.com/a/52537676
has answer: http://stackoverflow.com/a/52538317
answer count: 2
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52537676
tagged with: python
has comment: http://stackoverflow.com/comment/92014050
has title: Scraping with Python BeautifulSoup two prices
score: 2
type: AnsweredQuestion
has body: i'm currently working on scraping this website: https://listado.mercadolibre.com.ve/oficinas-suministros-papeleria-papel-en-aragua/resma-carta-alpes i've been successful until i apply the "text" attribute to the decimal price variable. this is the code i've been using: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://listado.mercadolibre.com.ve/oficinas-suministros-papeleria-papel-en-aragua/resma-carta-alpes' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") containers = page_soup.findAll("div", {"class": "item__info-container"}) for container in containers: title_container = container.a.text.strip() price_container_fraction = container.find("span" ,{"class":"price__fraction"}).text price_container_decimal = container.find("span" ,{"class":"price__decimals"}) print(title_container) print(price_container_fraction) print(price_container_decimal) this is the html ad block: Resma Tamaño Carta Marca Alpes Caja Bs. 4 50 2 vendidos This is the result: i need to gather the 2 elements of the price and then add them but no luck. any help?

http://stackoverflow.com/q/52474999
has comment: http://stackoverflow.com/comment/92038264
has comment: http://stackoverflow.com/comment/92007055
tagged with: selenium
has comment: http://stackoverflow.com/comment/92047903
type: AnsweredQuestion
score: 26
has comment: http://stackoverflow.com/comment/91998169
accepted answer: http://stackoverflow.com/a/52537137
type: Question
has comment: http://stackoverflow.com/comment/92008314
has comment: http://stackoverflow.com/comment/92012795
tagged with: firefox
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52537137
has comment: http://stackoverflow.com/comment/92174436
favorite count: 0
has body: I am running very complex python-selenium tests on non-public webpages. In most cases these tests run fine, but sometimes one of these tests fail during the initialization of the webdriver itself. Hint: This error happens when trying to initialize a webdriver, i.e. when doing something like this: # Start of the tests mydriver = webdriver.Firefox(firefox_profile=profile, log_path=logfile) # ERROR HAPPENS HERE # Doing other stuff here .... # Doing tests here .... # Doing shutdown here mydriver.quit() Here is a full example of such an error: ___________ ERROR at setup of TestSuite.test_synaptic_events_fitting ___________ &gt; lambda: ihook(item=item, **kwds), when=when, ) /usr/local/lib/python2.7/dist-packages/flaky/flaky_pytest_plugin.py:273: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ conftest.py:157: in basedriver mydriver = firefox.get_driver(*args) bsp_usecase_tests/tools/firefox.py:44: in get_driver driver = webdriver.Firefox(firefox_profile=profile, log_path=logfile) #### INITIALIZING OF WEBDRIVER HERE /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py:158: in __init__ keep_alive=True) /usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py:154: in __init__ self.start_session(desired_capabilities, browser_profile) /usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py:243: in start_session response = self.execute(Command.NEW_SESSION, parameters) /usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py:311: in execute self.error_handler.check_response(response) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = &lt;selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x7efd3b702f90&gt; response = {'status': 500, 'value': '{"value":{"error":"unknown error","message":"connection refused","stacktrace":"stack backtra...s::imp::thread::{{impl}}::new::thread_start\n at /checkout/src/libstd/sys/uni…
tagged with: geckodriver
has comment: http://stackoverflow.com/comment/92033782
tagged with: python
upvote count: 27
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/91999386
has title: How to fix python-selenium error "connection refused" when initializing a selenium webdriver?
has comment: http://stackoverflow.com/comment/91967358

http://stackoverflow.com/comment/91890322
has text: Okay, but this doesn't sort the bars of the histogram. I mean, I obtain the same result..
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52474243

http://stackoverflow.com/comment/91942042
type: QuestionComment
comment on: http://stackoverflow.com/q/52495502
score: 0
has text: the math target is checking all k-algebra functions (I have only 1 condition to decrease their number-it is meeting n times (minimal) each number)
type: Comment

acl
tags question: http://stackoverflow.com/q/52529763
type: Tag
tag name: acl

http://stackoverflow.com/a/52527671
type: Answer
has comment: http://stackoverflow.com/comment/91994980
answers question: http://stackoverflow.com/q/52527435
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52527435
type: AcceptedAnswer
downvote count: 0
has body: You can use regex to get the job done: Input: import re text = '1:CH,AG,ME,GS,AP,CH,HE,AC,AC,AG,CA,HE,AT,AT,AC,AT,OG,NE,AG,AC,CS,OD\n&amp;:TA,EB,PA,AC,BR,TH,PO,AC,2I,AC,TH,PE,TH,AZ,AZ,ZE,CS,OD,CH,EO,ZE,OG\n&amp;:TH,ZE,ZE,HE,HE,HP,HP,OG,HP,ZE\n2:ZE,FD,FD,AG,EO,OG,AG,NE,RU,GS,HP,ZE,ZE,HM,HM,PC,PC,AS,AS,TY,TY,AG\n&amp;:AG,GS,NO,EU,ZF,HE,AT,AT,OD,OD,EB,OD,GS,TR,OD,AC,TR,GS,OD,TR,OD,AT,GS\n&amp;:CA,GS,NE,GS,AG,PS,HL,AG,NE,ID,AJ,AX,DI,OD,ME,AT,GS,MU,HO,PB,LT,9Z,PT,9Y\n&amp;:9W,9X,AR,9V,9U,9T,AX,9S,9R,AT,AJ,DI,ST,EA,AG,ME,NE,MU,9Q,9P,9O,9N,9M,9L\n&amp;:9K,ID,MG,OD,FY,AU,AU,HR,HR,9J,TL,9I,9H,9G,9F,AC,BR,AC,9E,9D,9C,9B,99\n' text = re.sub(r'\n&amp;*(\d*:)*',',', text[2:]).rstrip(',') Output: 'CH,AG,ME,GS,AP,CH,HE,AC,AC,AG,CA,HE,AT,AT,AC,AT,OG,NE,AG,AC,CS,OD,TA,EB,PA,AC,BR,TH,PO,AC,2I,AC,TH,PE,TH,AZ,AZ,ZE,CS,OD,CH,EO,ZE,OG,TH,ZE,ZE,HE,HE,HP,HP,OG,HP,ZE,ZE,FD,FD,AG,EO,OG,AG,NE,RU,GS,HP,ZE,ZE,HM,HM,PC,PC,AS,AS,TY,TY,AG,AG,GS,NO,EU,ZF,HE,AT,AT,OD,OD,EB,OD,GS,TR,OD,AC,TR,GS,OD,TR,OD,AT,GS,CA,GS,NE,GS,AG,PS,HL,AG,NE,ID,AJ,AX,DI,OD,ME,AT,GS,MU,HO,PB,LT,9Z,PT,9Y,9W,9X,AR,9V,9U,9T,AX,9S,9R,AT,AJ,DI,ST,EA,AG,ME,NE,MU,9Q,9P,9O,9N,9M,9L,9K,ID,MG,OD,FY,AU,AU,HR,HR,9J,TL,9I,9H,9G,9F,AC,BR,AC,9E,9D,9C,9B,99'

http://stackoverflow.com/a/52535841
has body: It happens because of your network is not perfectly match to the loaded one. You can use selective checkpoint loader something like that: reader = tf.train.NewCheckpointReader(os.path.join(checkpoint_dir, ckpt_name)) restore_dict = dict() for v in tf.trainable_variables(): tensor_name = v.name.split(':')[0] if reader.has_tensor(tensor_name): print('has tensor ', tensor_name) restore_dict[tensor_name] = v restore_dict['my_new_var_scope/my_new_var'] = self.get_my_new_var_variable() Where get_my_new_var_variable() is something like that: def get_my_new_var_variable(self): with tf.variable_scope("my_new_var_scope",reuse=tf.AUTO_REUSE): my_new_var = tf.get_variable("my_new_var", dtype=tf.int32,initializer=tf.constant([23, 42])) return my_new_var Loading the weights: self.saver = tf.train.Saver(restore_dict) self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name)) Edited: Note that in order to avoid override the loaded variables you can use this method: def initialize_uninitialized(sess): global_vars = tf.global_variables() is_not_initialized = sess.run([tf.is_variable_initialized(var) for var in global_vars]) not_initialized_vars = [v for (v, f) in zip(global_vars, is_not_initialized) if not f] if len(not_initialized_vars): sess.run(tf.variables_initializer(not_initialized_vars)) Or simply calling tf.global_variables_initializer() before loading the variables should work here.
has comment: http://stackoverflow.com/comment/92073221
type: Answer
has comment: http://stackoverflow.com/comment/92037067
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92017326
has comment: http://stackoverflow.com/comment/92071432
accepted answer of: http://stackoverflow.com/q/52532150
answers question: http://stackoverflow.com/q/52532150
has comment: http://stackoverflow.com/comment/92020089
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/91961758
type: Comment
comment on: http://stackoverflow.com/a/52510778
type: AnswerComment
has text: @PL200 - Can you add some data samples? Because not sure if understand.
score: 0

http://stackoverflow.com/q/52475075
favorite count: 0
has comment: http://stackoverflow.com/comment/91891841
tagged with: exception
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91891674
has title: Why python introspection doesn't know exceptions in a function?
linked to: http://stackoverflow.com/q/32560116
score: -5
has comment: http://stackoverflow.com/comment/91891673
has comment: http://stackoverflow.com/comment/91891896
has comment: http://stackoverflow.com/comment/91891950
has comment: http://stackoverflow.com/comment/91891845
has answer: http://stackoverflow.com/a/52475239
type: Question
has comment: http://stackoverflow.com/comment/91891756
downvote count: 5
has body: When I handle some code exception code, I wander why python didn't include what exception will the function raise in its introspect system.For example,when I have to use a function refer to many other function that will raise different exceptions,I have to consider all that happen in my business logic. Like this: def a(): raise Exception('exception1') def b(): a() raise Exception('exception2') def c(): b() raise Exception('exception3') def business(): try: c() except Exception as e: pass I have to keep digging in the function calls between them that I can know what maybe raise in this code block.And introspect system does not have information of exception. And as I know, Java will explicitly annotated 'Throw' in function definition,and IDE and programmer can easily know what kinds of exception should I handle. It will be better if I can know all the exception with object itself,for example: all_exception = obj.__exceptions__() So,my question is,why python not include exception introspect in function object. Who can explain python's design?
upvote count: 0
has comment: http://stackoverflow.com/comment/91891679
answer count: 1

http://stackoverflow.com/a/52535499
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/92013105
accepted answer of: http://stackoverflow.com/q/52534892
has body: Re-shaping is using when you want to retain all of the data but in a different shape. I believe that you are trying to drop 125 of the 128 channels. To do this you can just use indexing to get the first 3 channels: img_reshaped = img['embedmap'][:, :, :3] Also you are passing img['embedmap'], not the reshaped img_reshaped into cv2.imshow(). Although I would recommend looking at them 1 by 1 in grey scale. for i in range(128): cv2.imshow("segmented_map", img['embedmap'][:, :, i]) cv2.waitKey(0)
score: 2
answers question: http://stackoverflow.com/q/52534892

http://stackoverflow.com/q/52485477
tagged with: javascript
tagged with: hashlib
has answer: http://stackoverflow.com/a/52485716
score: 3
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: node.js
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52485716
upvote count: 3
type: Question
has title: Equivalent MD5 from CryptoJS and Python Hashlib
has body: I try to bring some code from JS to Python. I'm stuck with that code in JS : const crypto = require('crypto') var txtToHash = "Hello¤World¤"; var md5sum = crypto.createHash('md5'); md5sum.update(new Buffer(txtToHash, 'binary')); md5val = md5sum.digest('hex'); // equivalent to // crypto.createHash('md5').update(urlPart, 'binary').digest('hex')); Returns : 3a091f847ee21c7c1927c19e0f29a28b And, in Python 3.7 I have this code : import hashlib txtToHash = "Hello¤World¤" md5val = hashlib.md5(txtToHash.encode()).hexdigest() Returns : f0aef2e2e25ddf71473aa148b191dd70 Why are they different please ? I can't find an answer on Google or SO.

oop
tags question: http://stackoverflow.com/q/52572485
tags question: http://stackoverflow.com/q/52538757
tags question: http://stackoverflow.com/q/52542510
tags question: http://stackoverflow.com/q/52587006
tags question: http://stackoverflow.com/q/52434414
tags question: http://stackoverflow.com/q/52466815
tags question: http://stackoverflow.com/q/52459138
tags question: http://stackoverflow.com/q/52504849
tags question: http://stackoverflow.com/q/52527232
tag name: oop
tags question: http://stackoverflow.com/q/52521921
tags question: http://stackoverflow.com/q/52468080
tags question: http://stackoverflow.com/q/52523102
tags question: http://stackoverflow.com/q/52577249
tags question: http://stackoverflow.com/q/52456088
tags question: http://stackoverflow.com/q/52501454
tags question: http://stackoverflow.com/q/52508794
tags question: http://stackoverflow.com/q/52574772
tags question: http://stackoverflow.com/q/52455322
tags question: http://stackoverflow.com/q/52462209
tags question: http://stackoverflow.com/q/52452597
tags question: http://stackoverflow.com/q/52579725
tags question: http://stackoverflow.com/q/52561425
tags question: http://stackoverflow.com/q/52436502
tags question: http://stackoverflow.com/q/52559922
tags question: http://stackoverflow.com/q/52445629
type: Tag
tags question: http://stackoverflow.com/q/52480434

http://stackoverflow.com/a/52599532
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52581992
has body: You can set conditions using a while loop that will only accept a string that meets the requirements of having a len of 5 and is.digit() num1 = input('Enter a number with a length of 5: ') while len(num1) != 5 and num1 != num1.isdigit(): num1 = input('Please enter a number with a length of 5: ') num1 = int(num1)

http://stackoverflow.com/q/52579531
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/52584027
has body: All the dependencies are installed in a docker container, but when I run the example with GPU=True it returns "Status: Unbounded" and with GPU=False it works ok. The scs-python GPU tests return "Status: Unbounded". Also, nvidia-smi displays GPU usage. What might be the issue? Dockerfile: https://gist.github.com/Cerebrock/eef5d33ece1782d3efdf0b35d29fb48e Example: https://gist.github.com/Cerebrock/885023ec2faf1d1c6bf9b1a4df12df36 OS: Ubuntu 16.04 on Azure, image NVIDIA GPU Cloud image, NVIDIA Tesla P100
has title: How to install CVXPY / SCS to use with GPU?
tagged with: docker
downvote count: 0
answer count: 1
tagged with: nvidia
favorite count: 0
accepted answer: http://stackoverflow.com/a/52584027
tagged with: azure
tagged with: cvxpy
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52448773
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91840571
tagged with: python
has comment: http://stackoverflow.com/comment/91840634
has body: Let's say I want to integrate x**2 from 0 to 1. I do it using the scipy.integrate.quad: from scipy import integrate def f(x): return x**2 I = integrate.quad(f, 0, 1)[0] print(I) Questions: Is there any way to know how many times the user-defined function f gets called by the quad? I want to do it as I am interested to know how many have been utilized by quad to evaluate the integral.
has answer: http://stackoverflow.com/a/52448858
has answer: http://stackoverflow.com/a/52448849
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/52448853
score: 7
linked to: http://stackoverflow.com/q/21716940
has comment: http://stackoverflow.com/comment/91840568
answer count: 6
has answer: http://stackoverflow.com/a/52448830
has comment: http://stackoverflow.com/comment/91840622
has comment: http://stackoverflow.com/comment/111272217
has comment: http://stackoverflow.com/comment/91840576
has title: The number of times a function gets called
downvote count: 0
has answer: http://stackoverflow.com/a/52448864
has answer: http://stackoverflow.com/a/66574089
favorite count: 0

http://stackoverflow.com/comment/91831157
comment on: http://stackoverflow.com/a/52444212
type: AnswerComment
score: 0
type: Comment
has text: Appreciate the response! I added the 'with open ('newTest.csv)...' code seen in the edit of the OP to your answer, replacing the '... your code ...' however after submitting the form the file still doesn't appear. I'm positive your solution as others posted here work, so perhaps the issue is that I haven't actually got flask setup correctly?

http://stackoverflow.com/comment/91945130
score: 0
has text: What do you mean by "producted five times then be multiplied by 5000 range from 0.0 to 1.0"?
type: Comment
comment on: http://stackoverflow.com/a/52502185
type: AnswerComment

http://stackoverflow.com/comment/92343802
has text: Just an fyi - I added a new question using the same code - about logging: https://stackoverflow.com/questions/52708756/how-to-use-pythons-built-in-logging-with-asyncio-permission-error
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52608090

http://stackoverflow.com/comment/91837645
has text: globals()[user_input] = [] wher user input is your user input, buuuuuuuuuuuuuuuuuuuuuut be careful
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52447364

http://stackoverflow.com/q/52555027
has comment: http://stackoverflow.com/comment/92048822
has title: Python GTTS Error : AttributeError: 'NoneType' object has no attribute 'group'
tagged with: text-to-speech
tagged with: google-text-to-speech
has comment: http://stackoverflow.com/comment/92048645
has answer: http://stackoverflow.com/a/54959254
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52555218
type: Question
has answer: http://stackoverflow.com/a/53538724
upvote count: 3
has answer: http://stackoverflow.com/a/52555228
accepted answer: http://stackoverflow.com/a/52555228
tagged with: python
possible better answer: http://stackoverflow.com/a/52555218
has answer: http://stackoverflow.com/a/55186469
favorite count: 0
has body: I have a project where I was doing text to speech conversion. My audio file is being stored as a mp3. But now, when I check the Gtts api is throwing error. I tried searching but couldn't find a workable solution for the bug. My code is as follows: def synth(sent,language='en',slow = False): """ Synthesize text into audio """ os.system('clear') print("Speaker Output:" + sent) gt_ob = gTTS(text=sent, lang=language, slow=slow) file_name = hashlib.md5(sent.encode('utf-8')).hexdigest() print("File Name " + file_name) gt_ob.save("media/audio.mp3") print("Till here") os.system("ffmpeg -nostats -loglevel 0 -y -i media/audio.mp3 -ar 16000 media/"+ file_name + ".wav") if __name__ == "__main__": synth("good morning","en") And the Error message that I am getting is : File "file_name.py", line 30, in &lt;module&gt; synth("good morning","en") File "file_name.py", line 25, in synth gt_ob.save("media/audio.mp3") File "/home/arqam/anaconda3/lib/python3.6/site-packages/gtts/tts.py", line 247, in save self.write_to_fp(f) File "/home/arqam/anaconda3/lib/python3.6/site-packages/gtts/tts.py", line 187, in write_to_fp part_tk = self.token.calculate_token(part) File "/home/arqam/anaconda3/lib/python3.6/site-packages/gtts_token/gtts_token.py", line 28, in calculate_token seed = self._get_token_key() File "/home/arqam/anaconda3/lib/python3.6/site-packages/gtts_token/gtts_token.py", line 62, in _get_token_key a = re.search("a\\\\x3d(-?\d+);", tkk_expr).group(1) AttributeError: 'NoneType' object has no attribute 'group' So how can we resolve this bug that has popped up?
answer count: 5

http://stackoverflow.com/a/52485522
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/52485276
upvote count: 0
has comment: http://stackoverflow.com/comment/91912599
has body: Replace ‘ character to ' . Here is new code: import sqlalchemy from sqlalchemy import create_engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://root:password@localhost:3306/dbname')
type: Answer
has comment: http://stackoverflow.com/comment/91913578

http://stackoverflow.com/a/52541372
score: 0
type: AcceptedAnswer
type: Answer
has body: A clean way to approach this problem is to read each line from the file and split the line by white space and store it into an array. You can then index the array for the specific values you're interested in. I would suggest using a dictionary to store the sums of a particular name as you iterate through your whole file. This is an example working code for what you're trying to accomplish: store = {} with open('data.txt') as my_file: for line in my_file: values = line[:-1].split(" ") if values[0] not in store: store[values[0]] = float(values[3]) else: store[values[0]] += float(values[3]) Now if you were interested in a specific name's value you can search for that name in the dictionary: print(store['Mike']) # output is 130.0 print(store['Mary']) # output is 40.0 print(store['Dave']) # output is 20.0
accepted answer of: http://stackoverflow.com/q/52541085
has comment: http://stackoverflow.com/comment/92025558
answers question: http://stackoverflow.com/q/52541085
has comment: http://stackoverflow.com/comment/92023336

http://stackoverflow.com/a/52526201
answers question: http://stackoverflow.com/q/52488728
type: AcceptedAnswer
score: 0
type: Answer
has body: Instead of using jinja2 filters to format the string, I created an HTML table and looped through the variables I needed to display them correctly. Thanks to @gittert for the suggestion!
accepted answer of: http://stackoverflow.com/q/52488728

http://stackoverflow.com/a/52465934
downvote count: 0
has comment: http://stackoverflow.com/comment/91874517
type: Answer
has body: South was the predecessor of django migrate. It became a part of Django core, so no need to install it. If you are having migration issues, you should learn how to fix them, instead of just re-installing. You can edit every single migration file. They are just regular .py files with regular Django functions that do the necessary changes to your tables. Read the error message, try to understand what went wrong, and fix the migration file that caused the error. They are numbered and located in projectfolder/appfolder/migrations/. I am using migrate all the time and never had an issue that wasn't fixable.
accepted answer of: http://stackoverflow.com/q/52465655
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52465655
type: AcceptedAnswer

http://stackoverflow.com/comment/91955621
comment on: http://stackoverflow.com/a/52471065
type: AnswerComment
score: 0
type: Comment
has text: I added `my_fig.ax_joint.add_patch(un_sf_patch)` and received the error `Can not put single artist in more than one figure`. Googling around and checking similar errors, I am not sure how to resolve this.

http://stackoverflow.com/a/52471598
has body: e-16 is essentially 0. You typically can't avoid numerical precision errors when dealing with floats. But you can always chop the tiny values to 0 exactly afterwards if that's important to you. Note that you probably see 1. when printing a only because numpy doesn't show the full precision by default when printing an array. Try print(a[0,0]) and you'll probably see something like 1.00000000005. For example try printing np.array([1.000000001]) and np.array([1.000000001])-1, and np.array([1.000000001])[0]...
type: Answer
answers question: http://stackoverflow.com/q/52471547
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/52494242
downvote count: 0
has answer: http://stackoverflow.com/a/52500433
accepted answer: http://stackoverflow.com/a/52500433
tagged with: python
has body: Using pyjq i am able to parse values from json file. I need to format the output bit more so this can be exported to csv. import json import csv import pyjq emp_data = open('example.json', 'r') emp_data_parsed = json.loads(emp_data.read()) emp = pyjq.all ('.base[].base[].uid, .base[].base[].name', emp_data_parsed) print emp The output I am getting [u'2da21174-0af8-4b5b-b02e-2957a24d70e1', u'fcc5a2c8-3a78-4cc5-9fd3-e7bd59eb36ba', u'4ecf6450-7307-466c-bf19-663ba2fbaf69', None, u'Tommy', u'Sam', Expecting output as below so that can be written to a csv file. uid,name '2da21174-0af8-4b5b-b02e-2957a24d70e1','None' 'fcc5a2c8-3a78-4cc5-9fd3-e7bd59eb36ba','Tommy' '4ecf6450-7307-466c-bf19-663ba2fbaf69','Sam' Following is the sample.json file example.json { "base": [ { "base": [ { "item-number": 1, "type": "access-item", "uid": "2da21174-0af8-4b5b-b02e-2957a24d70e1", "usage": { "last-date": { "iso-8601": "2018-03-19T03:58-0500", }, }, "item-number": 2, "name": "Tommy", "type": "access-item", "uid": "fcc5a2c8-3a78-4cc5-9fd3-e7bd59eb36ba", "item-number": 3, "name": "Sam", "type": "access-item", "uid": "4ecf6450-7307-466c-bf19-663ba2fbaf69", "usage": { "last-date": { "iso-8601": "2018-03-21T07:21-0500", }, }, } ], } ], } I am not sure otherthan pyjq, there is an way of doing this. If so please let me know.
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/52500835
type: Question
upvote count: 2
answer count: 2
linked to: http://stackoverflow.com/q/52428921
has title: Parse multiple json value using pyjq, separated by comma
has answer: http://stackoverflow.com/a/52500835
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91938149
has comment: http://stackoverflow.com/comment/91937463

http://stackoverflow.com/comment/91963170
type: Comment
comment on: http://stackoverflow.com/q/52511653
type: QuestionComment
score: 0
has text: How about starting here: https://www.google.nl/search?q=javascript+guitar+chords+json - finding tools and frameworks are off topic for SO

zoho
type: Tag
tags question: http://stackoverflow.com/q/52574490
tag name: zoho

http://stackoverflow.com/a/52964309
downvote count: 0
upvote count: 2
has body: This solution has helped me out: Close all open Remote Desktop sessions. Launch the Registry editor (regedit.exe). Navigate to one of the following Registry keys, depending on whether you wish to modify the Remote Desktop settings only for the current user or for all users on the computer: HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client HKEY_LOCAL_MACHINE\Software\Microsoft\Terminal Server Client Create a DWORD value named RemoteDesktop_SuppressWhenMinimized and set it to 2. Close the Registry Editor. After these steps are done RDC when minimized will not be suppressed and sikuli will work. Answer taken from: https://support.smartbear.com/testcomplete/docs/testing-with/running/via-rdp/in-minimized-window.html Other solution is to use VNC connection instead of RDC. RealVNC for example. You setup VNC server on machine that sikuli scripts are running on and connect from your other machine. You should even be able to close the connection window and scripts should still be able to run.
type: Answer
accepted answer of: http://stackoverflow.com/q/52531898
answers question: http://stackoverflow.com/q/52531898
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/52449000
tagged with: python-2.7
upvote count: 1
favorite count: 0
tagged with: python
answer count: 0
downvote count: 0
type: UnansweredQuestion
type: Question
has body: I'm working on a script to query A and CNAME records from a list. When I run the script it works, but it skips specific URLs. If I resolve the URLs one at a time from the interpreter, they return an A record fine. Python noob, please be gentle. Thanks! Here's the code that's skipping some URLs: from dns import resolver import dns import os import csv import time errcountA = 0 errcountCNAME = 0 errcountCNAME2 = 0 list = [] combolist = [] sublist1 = open ("c:/temp/sublist2.txt", "r").read().replace('\r', '').splitlines() print sublist1 print "\r\n" print "there are %d total URLs in this list" %len(sublist1) print "\r\n" print "URLs being actually processed:" for url in sublist1: A = [] CNAME = [] CNAME2 = [] print "read %s prior to Resolver" %url.split() try: answer = dns.resolver.query(url, 'A', raise_on_no_answer=True) for rdata in answer: A.append(rdata.address) #time.sleep(1) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers): A = "exception: DNS query name does not exist" errcountA += 1 continue except dns.exception.Timeout: A = "exception: DNS query name does not exist" errcountA += 1 continue except: A = "no IPV4 found" errcountA += 1 continue try: answer = resolver.query(url, 'CNAME') for rdata in answer: CNAME.append(rdata.target) except: CNAME = "no CNAME found" errcountCNAME += 1 continue finally: list = [url, A, CNAME, CNAME2] combolist.append(list) print "read %s after Resolver" %url with open("c:/temp/subsresolvedtest.csv", 'wb') as csvfile: writer = csv.writer(csvfile) for r in combolist: writer.writerow(r) print "\r\n" print "URLs Resolved:" print "\r\n" print combolist print "\r\n" print ("There were %d 'A' record errors") %errcountA print "\r\n" print ("There were %d CNAME record errors") %errcountCNAME print "\r\n" print ("There were %d nested CNAME record errors") %errcountCNAME2 print "\r\n" print ("Done") But if I run the skipped URLs individually from the interpreter, they resolve and return an A record fine: answe…
score: 1
has title: python 2.7 dnspython not resolving all urls when scripted

http://stackoverflow.com/comment/91949814
has text: It's a number extracted from the webpage and is unique for every webpage. It's been defined formerly in original code.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52504017

http://stackoverflow.com/comment/91916225
type: Comment
has text: @OlivierMelançon thanks for the update, but i don't think this will work with the keyword arguments that also need to be passed to `some_function()`
comment on: http://stackoverflow.com/a/52487300
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92108829
score: 0
has text: I have only one column in my target so why it's called multiclass? What is label here?
type: Comment
comment on: http://stackoverflow.com/a/52586762
type: AnswerComment

http://stackoverflow.com/a/52596565
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/92131486
type: Answer
has body: The word boundary matches between the K and the dash. The 2 parts after the dash [$€£]?-? are optional because of the questionmark and then you match one or more times a digit. This results in the match -9 What you might use instead of a word boundary is an assertion that checks if what is before and after the match is not a non whitespace character \S using a negative lookbehind and a negative lookahead. (?&lt;!\S)-?[$€£]?(\d+(?:[,.]\d+)?)(?!\S) Regex demo | Python demo
answers question: http://stackoverflow.com/q/52583674
accepted answer of: http://stackoverflow.com/q/52583674

http://stackoverflow.com/q/52433129
has answer: http://stackoverflow.com/a/76338634
downvote count: 0
has title: python bokeh: get image from webcam and show it in dashboard
favorite count: 0
answer count: 3
linked to: http://stackoverflow.com/q/33948314
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52434555
upvote count: 2
type: Question
possible better answer: http://stackoverflow.com/a/76867470
tagged with: bokeh
has body: I want to display an image - e.g. capture with the webcam - in bokeh. I tried image_url and image_rgba, but both are not working. Image_url is showing nothing, image_rgb shows something, but there seems to be some index shift. # -*- coding: utf-8 -*- from bokeh.plotting import figure, show import scipy.misc import cv2 import matplotlib.pyplot as plt import os # capture video frame from webcam #vc = cv2.VideoCapture(1) vc = cv2.VideoCapture(-0) rval, frame = vc.read() vc.release() # show captured image (figure 1) fig = plt.figure() ax = plt.Axes(fig,[0,0,1,1]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(frame) plt.show() # save captured image scipy.misc.imsave('outfile.jpg', frame) mypath = os.path.join(os.getcwd(),'outfile.jpg') # 1. try using image_url ... not working (figure 2) p = figure() p.image_url(url=[mypath],x=[0],y=[1],w=[10],h=[10]) show(p) # 2. try using image_rgba ... also not working (figure 3) p = figure(x_range=(0,10), y_range=(0,10)) p.image_rgba(image=[frame], x=0, y=0, dw=10, dh=10) show(p) # 3. solution provided by @bigreddot ... flipped but also not working (figure4) img = scipy.misc.imread(mypath)[::-1] # flip y-direction for Bokeh p = figure(x_range=(0,10), y_range=(0,10)) p.image_rgba(image=[img], x=0, y=0, dw=10, dh=10) show(p) update: according to @bigreddot 's comment figure 1 figure 2 figure 3 figure 4 the bokeh version I use is 0.13 the python version 3.6.0
tagged with: image
accepted answer: http://stackoverflow.com/a/52434555
has answer: http://stackoverflow.com/a/76867470

http://stackoverflow.com/q/52460513
has comment: http://stackoverflow.com/comment/91883577
has answer: http://stackoverflow.com/a/52472295
type: Question
linked to: http://stackoverflow.com/q/52487163
answer count: 2
tagged with: layout
has body: The issue is a simple one, getting Kivy to integrate the Timer1 code as a label in FloatLayout. I have this .py file: import kivy kivy.require('1.10.0') from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.app import App from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.floatlayout import FloatLayout from kivy.uix.stacklayout import StackLayout from kivy.clock import Clock from kivy.properties import StringProperty, NumericProperty, ObjectProperty from digitalclock import DigitalClock from kivy.animation import Animation import time class IntroScreen(Screen): pass class ContScreen(Screen): pass class ScreenManagement(ScreenManager): pass backbone = Builder.load_file("main.kv") class Status(FloatLayout): _change = StringProperty() _tnd = ObjectProperty(None) def update(self, *args): self.time = time.asctime() self._change = str(self.time) self._tnd.text = str(self.time) print (self._change) class Timer1(Label): a = NumericProperty(10) # seconds color = 1, 1, 1, 1 font_size = 50 def start(self): Animation.cancel_all(self) # stop any current animations self.anim = Animation(a=0, duration=self.a) def finish_callback(animation, incr_crude_clock): incr_crude_clock.text = "COOL" self.anim.bind(on_complete=finish_callback) self.anim.start(self) def on_a(self, instance, value): self.text = str(round(value, 1)) class XGApp(App): time = StringProperty() def update(self, *args): self.time = str(time.asctime()) def build (self): Clock.schedule_interval(self.update, 1) t1 = Timer1() return backbone xApp = XGApp() if __name__ == "__main__": xApp.run() and the .kv: &lt;ContScreen&gt;: DigitalClock: pos_hint: {'center_x': 0.1, 'center_y': 0.9} size_hint: (0.075, 0.075) StackLayout orientation: "tb-rl" spacing: 15 Button: text: "1" size_hint: None, .16 width: 225 on_press: self.background_color = (1.7, 0, 1.7, 1) t1.start() I am trying to get the Timer1 aspect as a label in FloatLayout on the .k…
has answer: http://stackoverflow.com/a/52483152
accepted answer: http://stackoverflow.com/a/52483152
score: 0
upvote count: 1
downvote count: 1
has title: Kivy - Timer Integration in FloatLayout
possible better answer: http://stackoverflow.com/a/52472295
favorite count: 0
tagged with: kivy-language
tagged with: timer
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/91867565
type: AnsweredQuestion

http://stackoverflow.com/a/52455329
downvote count: 0
has comment: http://stackoverflow.com/comment/91853123
upvote count: 2
has comment: http://stackoverflow.com/comment/91853095
has body: The second attempt kind-of has the right idea, but as you noted, it will cause an infinite recursion when printing it, since the list contains itself. By the expected output, it looks like you want to clone the list, which can be done pretty elegantly with slices: mylist[0] = mylist[:]
type: Answer
answers question: http://stackoverflow.com/q/52455310
score: 2

http://stackoverflow.com/comment/92077740
score: 0
has text: No, we need to know what's inside that iterable. Show the content of `arr` or at least some samples.
comment on: http://stackoverflow.com/q/52570452
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52498677
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/52498917
has answer: http://stackoverflow.com/a/52498748
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52498917
has comment: http://stackoverflow.com/comment/91937882
has comment: http://stackoverflow.com/comment/91937983
has comment: http://stackoverflow.com/comment/91937928
has comment: http://stackoverflow.com/comment/91937924
answer count: 2
has comment: http://stackoverflow.com/comment/91937964
accepted answer: http://stackoverflow.com/a/52498748
favorite count: 0
linked to: http://stackoverflow.com/q/18279063
has comment: http://stackoverflow.com/comment/91937955
has comment: http://stackoverflow.com/comment/91937897
tagged with: glob
tagged with: python
has title: How to print latest file that starts with using python?
score: 0
tagged with: file
has body: Is it possible to print the newest file using startswith? example: startswith "DOG" import subprocess import os import glob list_of_files = glob.iglob("C:\Users\Guest\Desktop\OJT\scanner\*") latest_file = print latest_file

http://stackoverflow.com/a/64994749
type: Answer
has body: Assuming you already have a column with the cumulative return, it is pretty straight forward: you want to get the max value at any given point and compare it with the actual cumulative return of the rows occurring only after such point. Then, if you take the the lowest value, you get the maximum drawdown of the array. import pandas as import pd import numpy as np def max_drawdown(arr: pd.Series) -&gt; int: return np.min(arr / arr.expanding().max()) - 1 In case you need to calculate the cumulative return first, using log makes it pretty straight forward: import numpy as np final['log_return'] = np.log(1 + final['Returns']) final['log_cum_return'] = np.cumsum(final['log_return']) final['cumulative_returns'] = np.expm1(final['log_cum_return'])
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52539335

http://stackoverflow.com/a/52497025
upvote count: 1
has comment: http://stackoverflow.com/comment/91966942
score: 1
has comment: http://stackoverflow.com/comment/91934841
has comment: http://stackoverflow.com/comment/91966986
has comment: http://stackoverflow.com/comment/91934620
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91934572
has body: In your model you forgot to specify to which model the OneToOneField of the User model should point (a Profile), since that profile is defined later in the Python file, you can not use an identifier, you can however use a string literal that contains the name of the model: class User(AbstractUser): USER_TYPE_CHOICES = ( (1,'Student'), (2,'Teacher'), (3,'Stuff') ) profile = models.OneToOneField('Profile', on_delete=models.CASCADE, related_name='user') user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) You will need to make migrations, and migrate in order to add a table that corresponds to your model in the database. Since you reference to the Profile, that means you will need to first construct a Profile before saving the User (since otherwise the profile will be NULL, which is not allowed here): from django.shortcuts import render from .forms import ProfileCreationForm, UserCreationForm from .models import Profile from django.http import HttpResponse def sign_up(request): if request.method == 'POST': user_form = UserCreationForm(instance=request.user,data=request.POST) profile_form = ProfileCreationForm(instance=request.user.profile,data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): profile = profile_form.save() new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.profile = profile new_user.save() return HttpResponse('user created') else: user_form = UserCreationForm() profile_form = ProfileCreationForm() return render(request, 'my_template.html',{'user_form':user_form, 'profile_form':profile_form}) You also forgot to specify the template. Furthermore it is advicable to return a redirect(..) to a view, since otherwise if the user refreshes the browser, a second POST request will be made, and this can thus trigger creating another user.
answers question: http://stackoverflow.com/q/52496980
accepted answer of: http://stackoverflow.com/q/52496980
type: Answer

http://stackoverflow.com/q/52481416
upvote count: 3
answer count: 1
tagged with: wpf
has comment: http://stackoverflow.com/comment/91904654
accepted answer: http://stackoverflow.com/a/57740281
tagged with: ironpython
has body: I was working on IronPython before (with WPF for developing some GUIs), and recently I started to try pythonnet. But I found that the xaml file that worked on IronPython does not work on CPython + pythonnet. In IronPython, I can define a Button.Click in the xaml file, but it seems not possible in CPython. I have tried to look up for the answers, but nothing relevant was found. So hopefully you could save me here... Here is my main script: import clr clr.AddReference(r"wpf\PresentationFramework") from System.IO import StreamReader from System.Windows.Markup import XamlReader from System.Windows import Application, Window from System.Threading import Thread, ThreadStart, ApartmentState class MyWindow(Window): def __init__(self): stream = StreamReader('test.xaml') window = XamlReader.Load(stream.BaseStream) Application().Run(window) def Button_Click(self, sender, e): print('Button has clicked') if __name__ == '__main__': thread = Thread(ThreadStart(MyWindow)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join() And here is the test.xmal: &lt;Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WpfApplication1" Height="300" Width="300"&gt; &lt;Grid&gt; &lt;Button x:Name="BUTTON" Content="Button" HorizontalAlignment="Left" Margin="101,82,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click" Background="#FFFF1616"/&gt; &lt;/Grid&gt; &lt;/Window&gt; The error message I got is: Unhandled Exception: Python.Runtime.PythonException: XamlParseException : 'Failed to create a 'Click' from the text 'Button_Click'.' Line number '6' and line position '132'. Strangly if I load the same xaml and keep the same Class structure in IronPython, the script works just fine: import wpf from System.Windows import Application, Window class MyWindow(Window): def __init__(self): self.ui = wpf.LoadComponent(self, 'test.xaml') def Button_Click(self, sender, e): print('Button has clicked') i…
tagged with: python.net
type: AnsweredQuestion
downvote count: 0
tagged with: .net
favorite count: 0
type: Question
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91905216
has title: Pythonnet Error: XamlParseException : 'Failed to create a 'Click' from the text
has answer: http://stackoverflow.com/a/57740281
has comment: http://stackoverflow.com/comment/91905816

http://stackoverflow.com/q/52481880
linked to: http://stackoverflow.com/q/47653309
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91909585
has answer: http://stackoverflow.com/a/52482312
linked to: http://stackoverflow.com/q/52522884
has title: Selenium: Fetch href from child class element
has comment: http://stackoverflow.com/comment/91905387
favorite count: 0
linked to: http://stackoverflow.com/q/44834358
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/52482312
possible better answer: http://stackoverflow.com/a/52484268
tagged with: selenium
has answer: http://stackoverflow.com/a/52484268
tagged with: web-scraping
has body: I need to find all href inside class="mozaique" My code: gfd = driver.find_elements_by_xpath('/html[1]/body[1]/div[1]/div[4]/div[2]/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]') html:
has comment: http://stackoverflow.com/comment/91905479
type: Question

http://stackoverflow.com/q/52496836
answer count: 1
has comment: http://stackoverflow.com/comment/92043463
has comment: http://stackoverflow.com/comment/91941994
has comment: http://stackoverflow.com/comment/91945157
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91935377
has comment: http://stackoverflow.com/comment/91934166
has comment: http://stackoverflow.com/comment/91969538
has comment: http://stackoverflow.com/comment/91969809
has comment: http://stackoverflow.com/comment/91970707
tagged with: pandas
tagged with: h2o
has comment: http://stackoverflow.com/comment/91965960
has answer: http://stackoverflow.com/a/52502277
type: Question
has comment: http://stackoverflow.com/comment/91973244
has comment: http://stackoverflow.com/comment/91942804
has comment: http://stackoverflow.com/comment/91934797
has body: I am trying to import my 3000 observation &amp; 77 features .csv file as H2O dataframe (while I am on a Spark session): (1st way) # Convert pandas dataframe to H2O dataframe import h2o h2o.init() data_train = h2o.import_file('/u/users/vn505f6/data.csv') However, I am getting the following error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/frame.py", line 102, in __init__ column_names, column_types, na_strings) File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/frame.py", line 143, in _upload_python_object self._upload_parse(tmp_path, destination_frame, 1, separator, column_names, column_types, na_strings) File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/frame.py", line 319, in _upload_parse self._parse(rawkey, destination_frame, header, sep, column_names, column_types, na_strings) File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/frame.py", line 326, in _parse return self._parse_raw(setup) File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/frame.py", line 355, in _parse_raw self._ex._cache.fill() File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/expr.py", line 346, in fill res = h2o.api("GET " + endpoint % self._id, data=req_params)["frames"][0] File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/h2o.py", line 103, in api return h2oconn.request(endpoint, data=data, json=json, filename=filename, save_to=save_to) File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/backend/connection.py", line 402, in request return self._process_response(resp, save_to) File "/u/users/svcssae/pyenv/prod_python_libs/lib/python2.7/site-packages/h2o/backend/connection.py", line 725, in _process_response raise H2OResponseError(data) h2o.exceptions.H2OResponseError: Server error water.exc…
has title: Cannot import .csv file as H2O dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/91969162
score: 0
has comment: http://stackoverflow.com/comment/91934247
has comment: http://stackoverflow.com/comment/92005437

http://stackoverflow.com/comment/91944777
has text: Thanks sir and this ` next_page_url = response.xpath('//li[@class="next right"]/a/@href').extract() if next_page_url: yield scrapy.Request(next_page_url, callback=self.parse)` should be out of the for loop right?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52501701
type: Comment

http://stackoverflow.com/a/52507022
has comment: http://stackoverflow.com/comment/91990525
has comment: http://stackoverflow.com/comment/91989300
has comment: http://stackoverflow.com/comment/91961881
answers question: http://stackoverflow.com/q/52507021
score: 1
has comment: http://stackoverflow.com/comment/91983730
upvote count: 1
has comment: http://stackoverflow.com/comment/91962392
has comment: http://stackoverflow.com/comment/91961798
has comment: http://stackoverflow.com/comment/91972453
accepted answer of: http://stackoverflow.com/q/52507021
has comment: http://stackoverflow.com/comment/91992050
has comment: http://stackoverflow.com/comment/91955423
has comment: http://stackoverflow.com/comment/91990520
has comment: http://stackoverflow.com/comment/91990241
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91955227
has comment: http://stackoverflow.com/comment/91990513
has body: TL;DR: Yes, but faster. @StefanKarpinski, co-creator of Julia, made the following comment here Another difference is that you're using a set in Python and an array in Julia (what Python calls a ‘list’) So according to Stefan, “an array” (probably means 1-dimensional array) is “what Python calls a ‘list’” For a simple example, suppose we want to find the product, P, of 10 million ratios, R, where the numerator of each term is 4n^2, and the denominator of each term is one less than the numerator, R = num/(num - 1), where n = 1 to 10 million. Without trying to do any optimizations of any kind here is a Python-style list comprehension in Julia 1.0.0: julia&gt; P = prod([4n^2/(4n^2 - 1) for n in 1:10_000_000]) 1.5707962875230395 Running this in the Julia 1.0.0 REPL is very fast, essentially instantaneous on my laptop. This is not a benchmark test, but running similar code, modified for Python, with Python 3.6 in the REPL in PyCharm is notably slower. import numpy as np P = np.prod([4*n**2/(4*n**2 - 1) for n in range(1, 10_000_001)]) P 1.5707962875404267 Just visually guessing at speed, Julia is much more than 10 times faster for this list comprehension. What about generators in Julia? Just remove the square brackets inside the prod function call: julia&gt; P = prod(4n^2/(4n^2 - 1) for n in 1:10_000_000) 1.5707962875404267 Julia’s answer is instantaneous on my laptop. This is not a speed comparison between Python and Julia, so I will leave Python at this point. Julia’s 2n for 2 * n is a nice feature. For example, try 2P: julia&gt; 2P 3.1415925750808533 See here.
type: Answer
has comment: http://stackoverflow.com/comment/91984274
has comment: http://stackoverflow.com/comment/91969475

http://stackoverflow.com/comment/92013067
has text: That I don't know, but you know now at least what you are getting as a result.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52536505

http://stackoverflow.com/comment/92049293
type: Comment
has text: I believe this could depend on the amount of intersection you have. Perhaps you can show exactly what kind of input you tested it with.
type: AnswerComment
comment on: http://stackoverflow.com/a/52553930
score: 0

http://stackoverflow.com/a/52452416
answers question: http://stackoverflow.com/q/52451852
score: 0
has comment: http://stackoverflow.com/comment/91848709
has body: You can use a recursive function with a generator: def full_length(d): return sum(1 if not isinstance(i, list) else full_length(i) for i in d) def semi_combos(d, current=[]): if len(current) == len(x) - 1: yield current else: for i in d: if len(set(current+[i])) == len(current)+1: yield from semi_combos(d, current+[i]) def remainder_combos(d, _target, current = []): if full_length(current)+len(_target) == len(x): yield [_target, *current] for i in d: if i not in _target and i not in current: yield from remainder_combos(d, _target, current+[i]) for x in [['a', 'b', 'c'], ['a', 'b', 'c', 'd']]: print([b for i in semi_combos(x) for b in list(remainder_combos(x, i))]) Output: [[['a', 'b'], 'c'], [['a', 'c'], 'b'], [['b', 'a'], 'c'], [['b', 'c'], 'a'], [['c', 'a'], 'b'], [['c', 'b'], 'a']] [[['a', 'b', 'c'], 'd'], [['a', 'b', 'd'], 'c'], [['a', 'c', 'b'], 'd'], [['a', 'c', 'd'], 'b'], [['a', 'd', 'b'], 'c'], [['a', 'd', 'c'], 'b'], [['b', 'a', 'c'], 'd'], [['b', 'a', 'd'], 'c'], [['b', 'c', 'a'], 'd'], [['b', 'c', 'd'], 'a'], [['b', 'd', 'a'], 'c'], [['b', 'd', 'c'], 'a'], [['c', 'a', 'b'], 'd'], [['c', 'a', 'd'], 'b'], [['c', 'b', 'a'], 'd'], [['c', 'b', 'd'], 'a'], [['c', 'd', 'a'], 'b'], [['c', 'd', 'b'], 'a'], [['d', 'a', 'b'], 'c'], [['d', 'a', 'c'], 'b'], [['d', 'b', 'a'], 'c'], [['d', 'b', 'c'], 'a'], [['d', 'c', 'a'], 'b'], [['d', 'c', 'b'], 'a']]
type: Answer

http://stackoverflow.com/a/52491496
has comment: http://stackoverflow.com/comment/91923516
has comment: http://stackoverflow.com/comment/91925618
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52491286
has comment: http://stackoverflow.com/comment/91925465
has body: Here is one of the simplest ways. &gt;&gt;&gt; np.argmax(a * (label == 1)) 5 &gt;&gt;&gt; np.argmax(a * (label == 1), axis=1) array([5]) Coldspeed's method may take more time.
score: 1
upvote count: 1

http://stackoverflow.com/comment/106150930
type: Comment
comment on: http://stackoverflow.com/a/52518404
has text: You installed "pyinstall" instead of "pyinstaller".
score: 0
type: AnswerComment

http://stackoverflow.com/q/52536843
tagged with: python
favorite count: 0
downvote count: 0
possible better answer: http://stackoverflow.com/a/60440351
type: Question
type: AnsweredQuestion
tagged with: wand
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/52537580
has title: How to convert wand.image.Image to PIL.Image?
has answer: http://stackoverflow.com/a/69094262
score: 5
has answer: http://stackoverflow.com/a/52537580
has answer: http://stackoverflow.com/a/60440351
tagged with: type-conversion
upvote count: 5
answer count: 3
has body: I spent whole day on this problem and did not see answer in stack overflow! I tried this but did not work: &gt;&gt; pil_image = Image.frombytes('RGBA', wand_image.size, wand_image.make_blob(format='png'), 'raw') ValueError: not enough image data I appreciate every solution.

http://stackoverflow.com/comment/91827486
score: 2
comment on: http://stackoverflow.com/q/52442340
has text: From [the docs](https://docs.python.org/3/library/exceptions.html#ValueError): "Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError." Seems appropriate. Also remember that you can specify a more detailled cause within the error, e.g. `ValueError("Must be divisible by 2")`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52569010
accepted answer of: http://stackoverflow.com/q/52568890
has body: You can concatenate the two series into a dataframe. There are a lot of options to do so, here is one example which will produce nice names: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt Group_A=pd.Series([26,21,22,26,19,22,26,25,24,21,23,23,18,29,22]) Group_B=pd.Series([18,23,21,20,20,29,20,16,20,26,21,25,17,18,19]) df = pd.DataFrame({"ColumnA" : Group_A, "ColumnB" : Group_B}) sns.set(style="whitegrid") ax=sns.boxplot(data=df , palette='Set2') plt.show()
score: 0
has comment: http://stackoverflow.com/comment/92075107
answers question: http://stackoverflow.com/q/52568890
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/comment/92093239
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52578922
has text: I'm confused - are you using Flask, or Django? You appear to have both here, which just doesn't make any sense.

http://stackoverflow.com/q/52461568
type: Question
has title: Python Qt - Use button via function from outside a class
has body: I am quite new to python. For my problem I cannot seem to find an answer. And sadly I didn't find anything that could held me. I try to call a function from another file in the same folder but it won't work. If I call the same function from the same file, it works just fine. The same goes for external classes. This code works: import sys from PyQt5 import QtWidgets from ui.mainwindow import Ui_MainWindow class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show() self.ui.pushButton.clicked.connect(test_function) def test_function(): window.ui.stackedWidget.setCurrentIndex(1) if __name__=='__main__': app = QtWidgets.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) The following code won't work: import sys from PyQt5 import QtWidgets from ui.mainwindow import Ui_MainWindow from other_file import test_function class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show() self.ui.pushButton.clicked.connect(test_function) if __name__=='__main__': app = QtWidgets.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) other_file.py def test_function(): window.ui.stackedWidget.setCurrentIndex(1) Error: cannot import name 'test_function'
score: 0
has comment: http://stackoverflow.com/comment/91865590
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91865462
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91865569
has comment: http://stackoverflow.com/comment/91865688
answer count: 0
tagged with: pyqt5

http://stackoverflow.com/comment/92036654
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52548632
has text: i will gladly do that! How do i accept the solution? I upvoted your answer, but is that the same thing?
type: AnswerComment

http://stackoverflow.com/q/52439872
has answer: http://stackoverflow.com/a/52440330
has answer: http://stackoverflow.com/a/52440113
score: 0
has title: delete a specific line that includes a key sequence of numbers python
answer count: 3
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91822777
has answer: http://stackoverflow.com/a/52440354
tagged with: python
type: AnsweredQuestion
has body: I have the below datafile and i want to delete the entire line that contains the "30" number in the first column. This number has always this position. What i have thought is to read the file and create a list with this first column and do a check if this number "30" exist on every item on the list and then delete the entire line given the index. However i am not sure how to proceed. Please let me know your thoughts . Datafile Here is what i have tried up to this point: f = open("file.txt","r") lines = f.readlines() f.close() f = open("file.txt","w") for line in lines: if line!="30"+"\n": f.write(line) f.close()
possible better answer: http://stackoverflow.com/a/52440330
tagged with: data-files
type: Question
accepted answer: http://stackoverflow.com/a/52440113

http://stackoverflow.com/a/52460341
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52460011
has comment: http://stackoverflow.com/comment/91908435
score: 1
has comment: http://stackoverflow.com/comment/91908759
answers question: http://stackoverflow.com/q/52460011
downvote count: 0
has body: Using apply and nonzero: &gt;&gt;&gt; df1.apply(lambda x:(x&lt;0).nonzero()[0][:1].tolist()) 400.0 [8] 401.0 [8] 402.0 [8] 403.0 [8] 404.0 [8] 405.0 [8] depth [] dtype: object
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/105014063
type: Comment
score: 1
has text: Min and max use sort order -- try `zsort = np.sort( z ); print( z.min(), zsort[0], z.max(), zsort[-1] )`. The [doc for numpy sort](https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html) says "The sort order for complex numbers is lexicographic", i.e. sort by .real then by .imag.
comment on: http://stackoverflow.com/q/52481376
type: QuestionComment

http://stackoverflow.com/q/52545438
answer count: 1
downvote count: 0
has title: Convert a Dense Vector to a Dataframe using Pyspark
has comment: http://stackoverflow.com/comment/92053740
upvote count: 3
has comment: http://stackoverflow.com/comment/92053719
tagged with: apache-spark
tagged with: pandas
has comment: http://stackoverflow.com/comment/92031285
favorite count: 0
has comment: http://stackoverflow.com/comment/92044847
has body: Firstly I tried everything in the link below to fix my error but none of them worked. How to convert RDD of dense vector into DataFrame in pyspark? I am trying to convert a dense vector into a dataframe (Spark preferably) along with column names and running into issues. My column in spark dataframe is a vector that was created using Vector Assembler and I now want to convert it back to a dataframe as I would like to create plots on some of the variables in the vector. Approach 1: from pyspark.ml.linalg import SparseVector, DenseVector from pyspark.ml.linalg import Vectors temp=output.select("all_features") temp.rdd.map( lambda row: (DenseVector(row[0].toArray())) ).toDF() Below is the Error TypeError: not supported type: &lt;type 'numpy.ndarray'&gt; Approach 2: from pyspark.ml.linalg import VectorUDT from pyspark.sql.functions import udf from pyspark.ml.linalg import * as_ml = udf(lambda v: v.asML() if v is not None else None, VectorUDT()) result = output.withColumn("all_features", as_ml("all_features")) result.head(5) Error: AttributeError: 'numpy.ndarray' object has no attribute 'asML' I also tried to convert the dataframe into a Pandas dataframe and after that I am not able to split the values into separate columns Approach 3: pandas_df=temp.toPandas() pandas_df1=pd.DataFrame(pandas_df.all_features.values.tolist()) Above code runs fine but I still have only one column in my dataframe with all the values separated by commas as a list. Any help is greatly appreciated! EDIT: Here is how my temp dataframe looks like. It just has one column all_features. I am trying to create a dataframe that splits all of these values into separate columns (all_features is a vector that was created using 200 columns) +--------------------+ | all_features| +--------------------+ |[0.01193689934723...| |[0.04774759738895...| |[0.0,0.0,0.194417...| |[0.02387379869447...| |[1.89796699621085...| +--------------------+ only showing top 5 rows Expected output is a dataframe with all 200 col…
has comment: http://stackoverflow.com/comment/92053466
tagged with: python
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/41328799
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/52557525
accepted answer: http://stackoverflow.com/a/52557525
has comment: http://stackoverflow.com/comment/92053477

http://stackoverflow.com/comment/91872570
score: 0
type: QuestionComment
has text: Thanks for coming forward to help. I have updated models with rest of the details.
type: Comment
comment on: http://stackoverflow.com/q/52464457

http://stackoverflow.com/comment/91864069
type: QuestionComment
comment on: http://stackoverflow.com/q/52461010
has text: You want to accumulate everything first, leave your loop *then* return. Your return is too early. When you have exhausted your while loop and it exits, your return should be outside that while.
score: 2
type: Comment

http://stackoverflow.com/q/52514480
type: Question
has title: Are there any Perl's CGI::Carp qw(fatalsToBrowser) alternatives for Python?
has body: I sometimes use CGI::Carp qw(fatalsToBrowser) in Perl CGI programming to transform fatal errors —including compile-time errors— into an HTML error page containing the error message. This is particularly useful in situations where errors aren't log, or when the logs are difficult to access. Are there any similar handy methods for Python?
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91973111
tagged with: python
tagged with: error-reporting
answer count: 0
type: UnansweredQuestion
tagged with: cgi
tagged with: error-handling
has comment: http://stackoverflow.com/comment/91970963
upvote count: 1

http://stackoverflow.com/comment/91868815
type: QuestionComment
comment on: http://stackoverflow.com/q/52435075
has text: @GiacomoAlzetta `shell=True` is a security issue in the same way as sql injection is. As long as there are no moving parts, as variables in the expression, or other means to modify it, it is not an issue. However, there is still an overhead in that the system will open an extra subprocess; it will open a shell process that will then execute the process you want, i.e., `java` in this case.
score: 0
type: Comment

http://stackoverflow.com/a/52519003
type: Answer
has comment: http://stackoverflow.com/comment/91977960
answers question: http://stackoverflow.com/q/52518872
upvote count: 9
type: AcceptedAnswer
downvote count: 0
has body: You should not use Base64 here. The site you link to gives you the hex values of the digest bytes. Use the HMAC.hexdigest() method to get the same value in hex in Python: &gt;&gt;&gt; key = b'secret' &gt;&gt;&gt; message = b'123' &gt;&gt;&gt; digester = hmac.new(key, message, hashlib.sha1) &gt;&gt;&gt; digester.hexdigest() 'b14e92eb17f6b78ec5a205ee0e1ab220fb7f86d7' put differently, your code outputs the correct value, but as Base64-encoded data: &gt;&gt;&gt; digester.digest() b'\xb1N\x92\xeb\x17\xf6\xb7\x8e\xc5\xa2\x05\xee\x0e\x1a\xb2 \xfb\x7f\x86\xd7' &gt;&gt;&gt; base64.urlsafe_b64encode(digester.digest()) b'sU6S6xf2t47FogXuDhqyIPt_htc=' and the value you generated online contains the exact same bytes as the hex digest, so we can generate the same base64 output for that: &gt;&gt;&gt; bytes.fromhex('b14e92eb17f6b78ec5a205ee0e1ab220fb7f86d7') b'\xb1N\x92\xeb\x17\xf6\xb7\x8e\xc5\xa2\x05\xee\x0e\x1a\xb2 \xfb\x7f\x86\xd7' &gt;&gt;&gt; base64.urlsafe_b64encode(bytes.fromhex('b14e92eb17f6b78ec5a205ee0e1ab220fb7f86d7')) b'sU6S6xf2t47FogXuDhqyIPt_htc='
score: 9
accepted answer of: http://stackoverflow.com/q/52518872

http://stackoverflow.com/comment/92058318
type: QuestionComment
comment on: http://stackoverflow.com/q/52559709
has text: or reindex with the list after the groupby, which will ensure you display NaN for groups you are missing completely.
score: 0
type: Comment

http://stackoverflow.com/q/52507803
has answer: http://stackoverflow.com/a/52507911
tagged with: range
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/91956072
answer count: 2
has title: How to get min and max values of ranges with numpy?
has comment: http://stackoverflow.com/comment/91956723
has body: I wonder if there are specific numpy functions to get the heighest and lowest values columns of my ranges. For ranges you can assume that every first dimension of my numpy array respresents the horizontal row of my image. I draw lines in each row of my image to different coordinates. I need to know the start and endpoint of each line in each row. Assume I have the following array: EDIT: I choose a bad range. This is better a = np.array([[0, 1],[0, 2],[0, 3],[0, 4],[1, 0],[1, 1],[1, 2],[1, 3],[1, 4],[1,5],[3, 0],[3, 1],[3, 2],[3, 3],[3, 4],[4, 0],[4, 3],[4, 4],[5,0]]) What I'd like to have is maxvalues/endpoints: array([[0, 4],[1, 5],[3, 4],[4, 4],[5,0]]) minvalues/startpoints: array([[0, 1],[1, 0],[3, 0],[4, 0],[5,0]]) I would loop over the whole array with if conditions and compare row values, but this way I also don't know if it makes sense to use numpy at all for this task. I'm aware of np.amin/amax(array,axis) use, but not how to define efficient ranges. EDIT2: So the only solution I see in the moment is to do something like that: for i in image_height: range_array = a[a[:,0] == i] min = np.amin(range_array,0) max = np.amax(range_array,0)
tagged with: numpy
has answer: http://stackoverflow.com/a/52508786
has comment: http://stackoverflow.com/comment/91956874
has comment: http://stackoverflow.com/comment/91956204
accepted answer: http://stackoverflow.com/a/52508786
tagged with: min
score: 2
type: AnsweredQuestion
tagged with: max
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52507911
type: Question

http://stackoverflow.com/q/52526331
type: Question
has comment: http://stackoverflow.com/comment/91993322
has comment: http://stackoverflow.com/comment/91993579
has comment: http://stackoverflow.com/comment/91992561
score: 0
has title: Using argparse for an input file
has comment: http://stackoverflow.com/comment/91992576
has comment: http://stackoverflow.com/comment/91992701
has body: I am using argparse to take an input file like so: python python_script.py --input_file ~/lab_projects/my_input_file.txt and in the script I use input_file = args.input_file When I run my script I get: ValueError: Invalid file path or buffer object type: class 'list' because when I print(input_file), I get ['my_input_file.txt'] How can I get my argument out of the list and as a string? Thanks in advance!
has comment: http://stackoverflow.com/comment/91995717
favorite count: 0
tagged with: argparse
tagged with: python
has comment: http://stackoverflow.com/comment/91992691
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91992831
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91927152
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52493202
has text: Possible duplicate of [Why encoding in utf-8 still results in ascii?](https://stackoverflow.com/questions/48413726/why-encoding-in-utf-8-still-results-in-ascii)
type: Comment

http://stackoverflow.com/a/52529192
score: 2
answers question: http://stackoverflow.com/q/52528985
upvote count: 2
downvote count: 0
has body: This could be done with whats called a static method. locations = [0,1] class Draw: def __init__(self, locations): self.locations = locations @staticmethod def platforms(variable): print(variable) Draw.platforms(locations) [0, 1]
type: Answer

word2vec
tags question: http://stackoverflow.com/q/52542275
tags question: http://stackoverflow.com/q/52514645
tags question: http://stackoverflow.com/q/52460163
type: Tag
tags question: http://stackoverflow.com/q/52531740
tags question: http://stackoverflow.com/q/52585239
tag name: word2vec

http://stackoverflow.com/comment/92082832
comment on: http://stackoverflow.com/q/52573275
score: 0
type: Comment
type: QuestionComment
has text: Probably iteration is the most readable solution IMO

http://stackoverflow.com/a/52509224
answers question: http://stackoverflow.com/q/52508941
score: 0
has body: You can use split() for example: string_data = "date key name email summary stats date name age where date summary age name date name age where date summary age name" split_string = string_data.split("date") for rows in split_string[1:]: rows = "date" + rows print rows will output: date key name email summary stats date name age where date summary age name date name age where date summary age name
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52508941

swagger-codegen
tag name: swagger-codegen
type: Tag
tags question: http://stackoverflow.com/q/52584921

http://stackoverflow.com/q/52544112
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/92028082
has answer: http://stackoverflow.com/a/52548123
downvote count: 4
answer count: 3
upvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92028831
linked to: http://stackoverflow.com/q/36901
has answer: http://stackoverflow.com/a/52547839
tagged with: python
has body: Using a range loop num set in python 3.7 and putting them all on the same line using the end='' After that though I need on a separate line a print statement but the end='' stops it from appearing on a separate line when I run the module. Any way to work around that? Or even put the range loop on the same line without using the end='' expression? Expected Output 3,6,9,12,15,18,21,24,27,30 That's all folks! My code: #uses loop from 3-30 counting by 3's for num in range(3, 33, 3): print (num, end=' ') #print statement print("That's all folks!")
has answer: http://stackoverflow.com/a/52544188
type: UnansweredQuestion
has title: Print statement after the end=' '
score: -4

http://stackoverflow.com/q/52507283
has comment: http://stackoverflow.com/comment/91969266
has title: AWS Lambda function appending characters in return
score: 0
tagged with: printing
has comment: http://stackoverflow.com/comment/91957161
has answer: http://stackoverflow.com/a/52515328
tagged with: python
has comment: http://stackoverflow.com/comment/91955660
tagged with: return
has comment: http://stackoverflow.com/comment/91955889
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91969315
type: Question
answer count: 1
has body: I have 2 Lambda Functions [A and B]. Function A does a computation and returns 2 strings. Note that I've also tried returning one string. When the function is called alone, the return is the correct expected string. If I call function A inside function B, the return is the correct string but with characters added to each side. Function A1 (two strings returned): def handler(event, context): strings = { "first_string": "This is the first string", "second_string": "This is the second string" } return strings Function A2 (one string returned): def handler(event, context): string = "This is a string" return string Calling A1 in another Lambda Function: return_strings = functionA1(event, context) print(return_strings[0]) print(return_strings[1]) &gt;&gt;&gt; 341 #expected This is the first string &gt;&gt;&gt; 8 #expected This is the second string Calling A2 in another Lambda function: return functionA2(event, context) &gt;&gt;&gt; b'\"This is a string\"' #expected This is a string Any idea what might be encoded in the returns - is it related to calling from another Lambda function? Invoking A1/A2 on their own gives expected returns. Thanks!
accepted answer: http://stackoverflow.com/a/52515328
tagged with: amazon-web-services
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/91969312

function
tags question: http://stackoverflow.com/q/52529122
tag name: function
tags question: http://stackoverflow.com/q/52456976
tags question: http://stackoverflow.com/q/52562941
tags question: http://stackoverflow.com/q/52580685
tags question: http://stackoverflow.com/q/52542585
tags question: http://stackoverflow.com/q/52489618
tags question: http://stackoverflow.com/q/52486467
tags question: http://stackoverflow.com/q/52576669
tags question: http://stackoverflow.com/q/52566810
tags question: http://stackoverflow.com/q/52439284
tags question: http://stackoverflow.com/q/52455701
tags question: http://stackoverflow.com/q/52469881
tags question: http://stackoverflow.com/q/52482060
tags question: http://stackoverflow.com/q/52504741
tags question: http://stackoverflow.com/q/52496458
tags question: http://stackoverflow.com/q/52492961
tags question: http://stackoverflow.com/q/52461963
type: Tag
tags question: http://stackoverflow.com/q/52509190
tags question: http://stackoverflow.com/q/52568474
tags question: http://stackoverflow.com/q/52552440
tags question: http://stackoverflow.com/q/52497159
tags question: http://stackoverflow.com/q/52430484
tags question: http://stackoverflow.com/q/52580960
tags question: http://stackoverflow.com/q/52535407
tags question: http://stackoverflow.com/q/52522346
tags question: http://stackoverflow.com/q/52459081
tags question: http://stackoverflow.com/q/52469667
tags question: http://stackoverflow.com/q/52547323
tags question: http://stackoverflow.com/q/52511123
tags question: http://stackoverflow.com/q/52579189
tags question: http://stackoverflow.com/q/52548555
tags question: http://stackoverflow.com/q/52556009
tags question: http://stackoverflow.com/q/52545099
tags question: http://stackoverflow.com/q/52461010
tags question: http://stackoverflow.com/q/52481607
tags question: http://stackoverflow.com/q/52458612
tags question: http://stackoverflow.com/q/52544063
tags question: http://stackoverflow.com/q/52525811
tags question: http://stackoverflow.com/q/52503515
tags question: http://stackoverflow.com/q/52442723
tags question: http://stackoverflow.com/q/52466372
tags question: http://stackoverflow.com/q/52568734
tags question: http://stackoverflow.com/q/52526343

http://stackoverflow.com/a/52550908
type: Answer
answers question: http://stackoverflow.com/q/52540413
has body: The item does show as selected right away because the time consuming actions are executed before updating the GUI. You can force the GUI to update before executing the actions by using window.update_idletasks().
score: 0

http://stackoverflow.com/q/52478722
has answer: http://stackoverflow.com/a/52480232
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52868649
possible better answer: http://stackoverflow.com/a/52480232
type: Question
tagged with: docker
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52868649
has title: Error when installing pyminizip on docker
has body: I am getting an error while installing pyminizip package inside docker container ( docker version 17.03.1-ce). I am doing it inside virtual environment with python 2.7.13. I ended up with below message while trying to install it. gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Isrc -Izlib123 -I/usr/local/include/python2.7 -c src/py_minizip.c -o build/temp.linux-x86_64-2.7/src/py_minizip.o src/py_minizip.c: In function ‘_compress’: src/py_minizip.c:251: warning: ‘filepathnameinzip’ may be used uninitialized in this function gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Isrc -Izlib123 -I/usr/local/include/python2.7 -c src/zip.c -o build/temp.linux-x86_64-2.7/src/zip.o In file included from src/zip.c:66: src/crypt.h:34: error: redefinition of typedef ‘z_crc_t’ src/zip.h:83: note: previous declaration of ‘z_crc_t’ was here src/zip.c:201: warning: function declaration isn’t a prototype src/zip.c:203: warning: function declaration isn’t a prototype error: command 'gcc' failed with exit status 1 Is there any alternate of pyminizip package ? I want to create a password protected zip. So, even if there is any alternate solution to it, please let me know.
tagged with: python

excel
tags question: http://stackoverflow.com/q/52536056
tags question: http://stackoverflow.com/q/52503077
tags question: http://stackoverflow.com/q/52584291
tags question: http://stackoverflow.com/q/52532147
tag name: excel
tags question: http://stackoverflow.com/q/52507154
tags question: http://stackoverflow.com/q/52488989
tags question: http://stackoverflow.com/q/52511590
tags question: http://stackoverflow.com/q/52451381
tags question: http://stackoverflow.com/q/52553658
tags question: http://stackoverflow.com/q/52486306
tags question: http://stackoverflow.com/q/52472436
tags question: http://stackoverflow.com/q/52475042
tags question: http://stackoverflow.com/q/52452391
tags question: http://stackoverflow.com/q/52553735
tags question: http://stackoverflow.com/q/52516539
tags question: http://stackoverflow.com/q/52511631
tags question: http://stackoverflow.com/q/52505620
tags question: http://stackoverflow.com/q/52507721
tags question: http://stackoverflow.com/q/52451128
tags question: http://stackoverflow.com/q/52552207
tags question: http://stackoverflow.com/q/52518412
type: Tag
tags question: http://stackoverflow.com/q/52451264
tags question: http://stackoverflow.com/q/52556239
tags question: http://stackoverflow.com/q/52582730
tags question: http://stackoverflow.com/q/52571993
tags question: http://stackoverflow.com/q/52569861
tags question: http://stackoverflow.com/q/52492203

http://stackoverflow.com/a/52488372
has comment: http://stackoverflow.com/comment/91932592
score: 2
has comment: http://stackoverflow.com/comment/91929345
answers question: http://stackoverflow.com/q/52488119
downvote count: 0
has body: You can use pandas.concat to concatenate the sequence of data frames into one large data frame and calculate the statistics afterwards like so. import pandas as pd # lst = [construct list of dataframes ...] df = pd.concat(lst, axis=0) means = df.mean() stds = df.std() Edit: if you would like to get the statistics broken down by some key, e.g. wave, you can use the following. means = df.groupby('wave').mean()
upvote count: 2
has comment: http://stackoverflow.com/comment/91931259
has comment: http://stackoverflow.com/comment/91932389
type: Answer

http://stackoverflow.com/comment/91963574
has text: @NellyBarret try this: `conda install -c conda-forge geopy`
comment on: http://stackoverflow.com/a/52505204
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92028846
type: QuestionComment
score: 2
has text: You could call `df = pd.DataFrame({s1.name: s1, s2.name: s2})` to grab the names of each series.
comment on: http://stackoverflow.com/q/52544400
type: Comment

http://stackoverflow.com/a/52503915
type: Answer
has body: You can have all the unique Javascript tags in the layout.html file then for each endpoint use if else statements to render the tag you want for each page. The endpoint is simply the name of the view function. {% if request.endpoint == 'index' %} {% elif request.endpoint == 'another-endpoint' %}
score: 0
answers question: http://stackoverflow.com/q/52444751

http://stackoverflow.com/q/52560787
score: -1
type: Question
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52560883
favorite count: 0
has title: Why tensorflow is not installing using pip?
tagged with: python
has body: I want to install tensorflow using pip. I ran pip install tensorflow but it shows an error message given below: Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow
tagged with: pip
downvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52560883
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/45293436

http://stackoverflow.com/comment/92049452
type: QuestionComment
comment on: http://stackoverflow.com/q/52553658
type: Comment
has text: Why do you expect the worksheet to know this? It's a documented workbook property.
score: 0

http://stackoverflow.com/a/52570754
has comment: http://stackoverflow.com/comment/92078584
has body: import time time.sleep(9) #delay for 9 seconds import test2 hope this helps :)
score: 1
upvote count: 2
has comment: http://stackoverflow.com/comment/92078486
answers question: http://stackoverflow.com/q/52570736
downvote count: 1
type: Answer

http://stackoverflow.com/q/52536463
downvote count: 0
has title: How do i convert this memoization code to dynamic programming (minimum coin change problem)
favorite count: 0
type: UnansweredQuestion
tagged with: memoization
has body: def coinchange(amountofchange): if mem[amountofchange]==-1: if amountofchange==0: mem[amountofchange] = 0 else: m = amountofchange for i in range(len(coin)): if coin[i]&lt;=amountofchange: x = 1+coin(amountofchange-coin[i]) m = min(m,x) mem[amountofchange] = m return mem[amountofchange] I can memoize but cannot find a way to do it dynamically
tagged with: python
answer count: 0
tagged with: dynamic
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/52541850
tagged with: python
type: AnsweredQuestion
tagged with: list
score: 1
accepted answer: http://stackoverflow.com/a/52541913
has body: I am learning python3 list comprehensions. I understand how to format a list comprehension: [equation, for loop, if statement for filtering], but I cannot figure out how to condense three lines of code into a single equation for the 'equation' part. I am taking a number and adding it to itself and then taking the result and adding it to itself and so on to create a sequence of numbers in the list. I can accomplish this by declaring x = 1 and then looping the following: y = x + x x = y Can anybody help me to turn this into a single-lined equation and if possible, resources that I might study to help me with this in the future?
upvote count: 1
type: Question
tagged with: algorithm
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/92023582
has comment: http://stackoverflow.com/comment/92024253
answer count: 1
has title: Python List Comprehensions
downvote count: 0
has answer: http://stackoverflow.com/a/52541913
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52463847
has title: redis not following redis.conf settings
upvote count: 1
has comment: http://stackoverflow.com/comment/91870797
favorite count: 0
has comment: http://stackoverflow.com/comment/91870945
tagged with: redis
has comment: http://stackoverflow.com/comment/91870684
tagged with: python
tagged with: gunicorn
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/91870879
type: Question
has body: I am running redis server and have set the dir to /var/lib/redis and dbfilename to dump.rdb in the redis.conf file but i notice redis starts to produce these errors below 120844:C 23 Sep 02:59:31.098 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:31.198 # Background saving error 42657:M 23 Sep 02:59:37.018 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:37.019 * Background saving started by pid 120868 120868:C 23 Sep 02:59:37.019 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:37.119 # Background saving error 42657:M 23 Sep 02:59:43.035 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:43.036 * Background saving started by pid 120869 120869:C 23 Sep 02:59:43.036 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:43.136 # Background saving error 42657:M 23 Sep 02:59:49.052 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:49.052 * Background saving started by pid 120895 120895:C 23 Sep 02:59:49.053 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:49.153 # Background saving error 42657:M 23 Sep 02:59:55.067 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:55.067 * Background saving started by pid 120939 then i get into redis-cli to fix this with the following commands 127.0.0.1:6379&gt; config set dbfilename dump.rdb OK 127.0.0.1:6379&gt; config set dir /var/lib/redis OK 127.0.0.1:6379&gt; exit and then i check the redis logs now and then it is working fine 42657:M 23 Sep 03:00:43.011 * Background saving started by pid 121168 121168:C 23 Sep 03:00:43.011 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 03:00:43.122 # Background saving error 42657:M 23 Sep 03:00:49.035 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 03:00:49.036 * Background saving started by pid 121170 121170:C 23 Sep 03:00:49.233 * DB saved on disk 121170:C 23 Sep 03:00:49.233 * RDB: 0 MB of memory used by copy-on-write 4265…
score: 1
has comment: http://stackoverflow.com/comment/91870925

http://stackoverflow.com/q/52481006
has answer: http://stackoverflow.com/a/54317762
upvote count: 10
tagged with: keras
favorite count: 0
has body: I use this notebook from Kaggle to run LSTM neural network. I had started training of neural network and I saw that it is too slow. It is almost three times slower than CPU training. CPU perfomance: 8 min per epoch; GPU perfomance: 26 min per epoch. After this I decided to find answer in this question on Stackoverflow and I applied a CuDNNLSTM (which runs only on GPU) instead of LSTM. Hence, GPU perfomance became only 1 min per epoch and accuracy of model decreased on 3%. Questions: 1) Does somebody know why GPU works slower than CPU in the classic LSTM layer? I do not understand why this happens. 2) Why when I use CuDNNLSTM instead of LSTM, training become much more faster and the accuracy of the model decrease? P.S.: My CPU: Intel Core i7-7700 Processor (8M Cache, up to 4.20 GHz) My GPU: nVidia GeForce GTX 1050 Ti (4 GB)
has answer: http://stackoverflow.com/a/78729909
tagged with: gpu
has title: Why is Keras LSTM on CPU three times faster than GPU?
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52481087
accepted answer: http://stackoverflow.com/a/52481087
downvote count: 0
linked to: http://stackoverflow.com/q/41972015
tagged with: machine-learning
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/53064016
score: 10
possible better answer: http://stackoverflow.com/a/54317762

http://stackoverflow.com/a/56719635
answers question: http://stackoverflow.com/q/52430530
has comment: http://stackoverflow.com/comment/116715658
accepted answer of: http://stackoverflow.com/q/52430530
score: 0
type: AcceptedAnswer
type: Answer
has body: The framework was reworked to that the connection was done through a class that uses the __enter__ and __exit__ methods which control the context automatically.
has comment: http://stackoverflow.com/comment/116373773

http://stackoverflow.com/q/52479486
answer count: 0
upvote count: 1
downvote count: 1
has title: "the following arguments are required: action" error on Python
has comment: http://stackoverflow.com/comment/91900197
type: Question
has body: I am beginner for the Python so sorry this basic question. (And sorry for my English) I try to use this github code blocks for Profinet communication. If i call the main.py this way: python main.py -i discover Than I have a this error: usage: main.py [-h] -i INTERFACE {discover,get-param,set-param,read,read-inm0-filter,read-inm0,read-inm1,write-inm1} [target] [param] [value] [additional1] [additional2] main.py: error: the following arguments are required: action And than I try to use this line: python server.py -i eth0 And I have this error: Traceback (most recent call last): File "server.py", line 20, in &lt;module&gt; s = ethernet_socket(args.i, 0x8892) File "/home/name/Documents/profinet-master/util.py", line 25, in ethernet_socket s = socket(AF_PACKET, SOCK_RAW) File "/usr/lib/python3.6/socket.py", line 144, in __init__ _socket.socket.__init__(self, family, type, proto, fileno) PermissionError: [Errno 1] Operation not permitted And that is the etherneth_socket: def ethernet_socket(interface, ethertype): s = socket(AF_PACKET, SOCK_RAW) s.bind((interface, ethertype)) return s How can I use this code or how can I call this python code. Please help me thank you.
has comment: http://stackoverflow.com/comment/91900165
has comment: http://stackoverflow.com/comment/91900482
has comment: http://stackoverflow.com/comment/91902524
score: 0
favorite count: 0
tagged with: ethernet
has comment: http://stackoverflow.com/comment/91901030
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52579114
tagged with: colors
tagged with: python
tagged with: dictionary
has title: Plot dictionary with multiple values in different colors
accepted answer: http://stackoverflow.com/a/52579152
tagged with: plot
type: Question
type: AnsweredQuestion
tagged with: matplotlib
answer count: 1
has body: Is there a way to plot a dictionary with multiple values with different colors? Let's say we have a dictionary: d = {"alpha": [1,2,3,4], "beta": [5,6,7,8]} How could one plot alpha[0], beta[0] ... blue and alpha[1], beta[1] .... yellow etc? Let's say that the values are on y-axis and the keys on the x-axis. My code would look like this: x_multi = [] y_multi = [] for k, v in data_all_bands.iteritems(): x_multi.extend(list(itertools.repeat(int(k[-3:]), len(v)))) y_multi.extend(v) plt_multi = axes[0].scatter(x_multi, y_multi) where data_all_bands looks like this: 2016050 [4.2958281793198241, 3.7025449821599157, 5.1717757645735025, 4.9954723025001719] 2016178 [4.0679016016577032, 2.890807214158575, 4.9627629940324081, 4.8505350289087952] 2016290 [3.6947496139720259, 3.1549071645707891, 4.5131724769284824, 4.4082219917836483]
has answer: http://stackoverflow.com/a/52579152
score: 0

http://stackoverflow.com/q/52576163
has answer: http://stackoverflow.com/a/52582558
upvote count: 0
tagged with: pyscripter
has comment: http://stackoverflow.com/comment/92087948
has comment: http://stackoverflow.com/comment/92087667
has comment: http://stackoverflow.com/comment/92088140
has comment: http://stackoverflow.com/comment/92087703
has comment: http://stackoverflow.com/comment/92087686
type: Question
has body: The red underline won't disappear, so I can't tell what punctuation I've used.
answer count: 2
downvote count: 3
has answer: http://stackoverflow.com/a/54119558
favorite count: 0
has title: How to remove red syntax error underline in PyScripter?
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/q/52506430
upvote count: 1
type: Question
tagged with: opencv
tagged with: visual-studio-2017
has body: Im trying to work with Visual Studio (and Visual Studio Code) in Python with OpenCV library. I want to launch this code from OpenCV's samples that shows live video from my webcam: import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Display the resulting frame cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() But i get an exception in cv2.imshow('frame',frame) line that say: cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow' I installed OpenCV by pip install opencv-python from my command prompt I get the same error when i work on Visual Studio 2017 or Visual Studio Code. I checked privacy of my webcam, its visible to all my apps. With Jupyter Notebook i can run this code perfectly. Do you know the point, why i cant acces to my webcam from VS, but in Jupyter Notebook i can do it without any problems? EDIT 1 When i set cap = cv2.VideoCapture(0) index into -1 code compile, but i get black output. As i said before, in Jupyter i can get acces into my webcam in my laptop. Im using Windows 10 EDIT2 When i add that line before imshow(): if ret: print("error") continue I always get an error output in my command prompt. Even if i wait for a while, it stills printing "error". Like i said couple of times, in Jupyter Notebook i can launch my webcam by code above
tagged with: visual-studio-code
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52520087
tagged with: python
tagged with: visual-studio
has title: Visual Studio, OpenCV, Python - no webcam in app
type: UnansweredQuestion

http://stackoverflow.com/comment/92091242
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52525123
has text: oops! I think this is fixed by adding "self" here: print(event.src_path + self.extra_args[0])

http://stackoverflow.com/q/52543722
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92027710
has comment: http://stackoverflow.com/comment/92027580
favorite count: 0
has title: Performing Function per Calendar Date
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/52543875
type: Question
has comment: http://stackoverflow.com/comment/92027660
accepted answer: http://stackoverflow.com/a/52543875
has comment: http://stackoverflow.com/comment/92027559
has body: I'm currently working on a nutrition planner which will allow users to plan meals per calendar day. As a demo, I've loaded in data from a JSON file including the meal name and calories, allowed users to pick which meal they'd like, etc. I want them to be able to do this for each day and organise it in a calendar. Here is my code for the meal planner, which works how I'd like it to: breakfastInput = input("What would you like for breakfast? ") breakfastChoice = [breakfastChoice for breakfastChoice in breakfast if breakfastInput in breakfastChoice][0] breakfastName = breakfastChoice[0] breakfastCalories = breakfastChoice[1] calories = calories - breakfastCalories print("You have {} calories remaining.".format(calories)) lunchInput = input("What would you like for lunch? ") lunchChoice = [lunchChoice for lunchChoice in lunch if lunchInput in lunchChoice][0] lunchName = lunchChoice[0] lunchCalories = lunchChoice[1] calories = calories - lunchCalories print("You have {} calories remaining.".format(calories)) dinnerInput = input("What would you like for dinner? ") dinnerChoice = [dinnerChoice for dinnerChoice in dinner if dinnerInput in dinnerChoice][0] dinnerName = dinnerChoice[0] dinnerCalories = dinnerChoice[1] calories = calories - dinnerCalories print("You have {} calories remaining.".format(calories)) if input("Would you like any snacks? ") == "yes": print(snacks) snacksInput = input("What snack would you like? ") snacksChoice = [snacksChoice for snacksChoice in snacks if snacksInput in snacksChoice][0] snacksName = snacksChoice[0] snacksCalories = snacksChoice[1] calories = calories - snacksCalories print("You have {} calories remaining.".format(calories)) else: print("Your day has been planned with a remaining {} calories.".format(calories)) How could I allow the user to choose a date and then for this function be performed? This way, for example, a lunchName and dinnerName can be assigned to each day.
has comment: http://stackoverflow.com/comment/92027844

http://stackoverflow.com/q/52450807
has body: I'm using Python 2.7 I have a scenario like this for (root,dirs,files) in os.walk(dir_tree, topdown=True, followlinks=True): for atom in files: # do something with files for dir in dirs: # do something with dirs I am performing an os.walk on a directory tree. This tree has some links. some of these links point to other locations inside the directory tree. Some of the links do not. I want os.walk to only follow links that point to other location in the directory tree eg: A/ temp/ collateral_file_1 B/ link1 -&gt; Somewhere outside A link2 -&gt; A/temp/ C/ file_1 In the above case dir_tree would A/ . When performing an os.walk on A I would like to explore link2 as it is a link to another location within A. but not link1. You might wonder why? The contents of link1 would be explore in a non symlink following walk anyway. But the reason for this I am checking some file patterns that are fed in via a config file for certain properties. eg: All files in A/B/link1/ should have 700 permissions etc. Is there a way I could do this? I thought about os.listdir but it seems like there should be an easier way
has title: Have os.walk follow symlinks conditionally
downvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/11068419
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: os.walk
linked to: http://stackoverflow.com/q/11068419

http://stackoverflow.com/comment/92062514
comment on: http://stackoverflow.com/a/52561914
score: 1
type: AnswerComment
type: Comment
has text: @RickyKim: Why did you leave the loop in there? Do you see any usage for that (other then wasting computing time)?

http://stackoverflow.com/q/52444409
upvote count: 5
answer count: 3
downvote count: 0
has body: If I generate the same graph multiple times using NetworkX and Matplotlib it's rotated randomly on every generation: Run 1: Run 2: Without changing the script or input data, the graph is randomly rotated every time it is generated. Is it possible to specify an orientation? As the graph becomes more densely populated (above are just samples but ultimately I will have thousands of nodes and edges), it will be difficult to see the newly added nodes or edges if they are moved because the graph picture is rotated. import networkx as nx import matplotlib.pyplot as plt from networkx.readwrite import json_graph # # The graph data is loaded from JSON # graph = json_graph.node_link_graph(input_json) pos = nx.spring_layout(graph) nx.draw(graph, pos, with_labels=True, node_size=300) edge_labels=dict([((u,v,),d['weight']) for u,v,d in graph.edges(data=True)]) nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels) plt.savefig("test.png") A second less important question is why are the edges/lines from R1 to R2 and R1 to R5 so much longer? Update: I hadn't set the "length" attribute in the JSON data source.
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52444637
possible better answer: http://stackoverflow.com/a/61527751
tagged with: python
has answer: http://stackoverflow.com/a/52444877
has answer: http://stackoverflow.com/a/61527751
type: AnsweredQuestion
has title: Python NetworkX - Why are graphs always randomly rotated?
tagged with: networkx
type: Question
tagged with: graph
accepted answer: http://stackoverflow.com/a/52444637
score: 5

http://stackoverflow.com/comment/91990909
comment on: http://stackoverflow.com/a/52525410
type: Comment
has text: Why bother with those `if` clauses in your list comps? You should use the `step` arg of `range`.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92095722
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52580282
has text: i guess this is some kind of test/task from a school/university as it makes no sense to make an api call to make something upper case
type: Comment

http://stackoverflow.com/comment/91894705
has text: The Sobel operator and Otsu thresholding might be replaced by the Canny edge detection
type: Comment
comment on: http://stackoverflow.com/a/52461482
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92091041
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52575784
has text: I didn't change anything. I just instantiate the class & call the method `PDFMiner6().PdfFileReader(fpin)` then loop through the result to write it to text file. This is the result txt file https://file.io/C23LXV. I installed `pdfminer.six==20170720` using `pip`

http://stackoverflow.com/comment/92074574
type: AnswerComment
type: Comment
score: 2
has text: why passing as a list?
comment on: http://stackoverflow.com/a/52568523

http://stackoverflow.com/q/52588601
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/75913384
linked to: http://stackoverflow.com/q/8452927
has answer: http://stackoverflow.com/a/76370314
tagged with: pygame
duplicate of: http://stackoverflow.com/q/8452927
has comment: http://stackoverflow.com/comment/92112565
has body: I'm trying to create a website for a university project where you can play some minigames I've programmed with Pygame (Python). How can I make the games executable online (like flashgames)? I'm using php
favorite count: 0
type: Question
downvote count: 2
score: 5
tagged with: python
has title: How can I make a Pygame game executable online?
answer count: 3
upvote count: 7
has comment: http://stackoverflow.com/comment/97610067
has answer: http://stackoverflow.com/a/52658294
has comment: http://stackoverflow.com/comment/92168412

http://stackoverflow.com/a/52516737
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52516504
has comment: http://stackoverflow.com/comment/91973030
has body: You can tackle it with only a single loop. The main focus of the loop is counting the S, say counter1. Inside the for loop, check if the previous one is an N, if so, add to counter2. Else, if the previous is B and the one before that is N, add to counter2. For example, if you have a list of the category, you do: C1, C2 = 0, 0 for i in range(len(category)): if category[i] == 'S': C1 += 1 if category[max(0, i-1)] =='N': C2 += 1 elif (category[max(0, i-1)]=='B') and (category[max(0, i-2)]=='N'): C2 += 1 With this, you can minimize the number of for loops. Hope it helps.

http://stackoverflow.com/comment/91957540
type: Comment
type: QuestionComment
has text: @WarrenWeckesser - that seems to work a lot better, thank you. Do you want to post it as an answer?
score: 0
comment on: http://stackoverflow.com/q/52508217

http://stackoverflow.com/a/52515879
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use PIL for that: from PIL import Image, ImageDraw import numpy as np matrix = np.array([[1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1, 1]]) # Load matrix into image im = Image.fromarray(matrix, mode='I') # Draw line from (1,1) to (9,3) with color 0 draw = ImageDraw.Draw(im) draw.line((1, 1, 9,3), fill=0) Convert back to numpy array: np.array(im) &gt;&gt;&gt; array([[1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 0, 1, 1], [1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1, 1]]) Note that the coordinates are 0-indexed, so the top-left corner is (0,0). Read more: https://pillow.readthedocs.io/en/3.0.x/reference/Image.html https://pillow.readthedocs.io/en/3.0.x/reference/ImageDraw.html
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52515535
answers question: http://stackoverflow.com/q/52515535
score: 1

http://stackoverflow.com/comment/92100559
score: 0
type: AnswerComment
has text: You're right about the other issues, this problem is my priority, and i can clean up the rest later, as I don't see how making `answer[int(location)]` helps the issue as it is still passing a list into the `answer[]`
type: Comment
comment on: http://stackoverflow.com/a/52582767

http://stackoverflow.com/q/52493879
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: numpy
has title: ValueError: setting an array element with a sequence. Trying to classify images using CNN
has comment: http://stackoverflow.com/comment/91929006
has comment: http://stackoverflow.com/comment/91959808
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91938100
type: UnansweredQuestion
tagged with: python
has body: I'm trying to run this code in Pycharm to classify images between normal and abnormal X-Rays using Convolutional Neural Networks (CNN). The code was available online but it classified whether an image has a DOG or a CAT in it. It works fine with CAT-DOG classification but when I change my training and testing directory to X-Rays I get an error as return array(a, dtype=long, copy=False, order=order, subok=True) ValueError: setting an array element with a sequence. I tried looking at similar questions but couldn't understand how to fix this problem. Thanks import cv2 import os import numpy as np from random import shuffle from tqdm import tqdm '''Setting up the env''' TRAIN_DIR = 'C:\\Users\\waqar\\Desktop\\Temp\\chest_xray\\train' TEST_DIR = 'C:\\Users\\waqar\\Desktop\\Temp\\chest_xray\\test' IMG_SIZE = 50 LR = 1e-3 '''Setting up the model which will help with tensorflow models''' MODEL_NAME = 'dogsvscats-{}-{}.model'.format(LR, '6conv-basic') '''Labelling the dataset''' def label_img(img): word_label = img.split('.')[-3] if word_label == 'cat': return [1, 0] elif word_label == 'dog': return [0, 1] '''Creating the training data''' def create_train_data(): training_data = [] for img in tqdm(os.listdir(TRAIN_DIR)): label = label_img(img) path = os.path.join(TRAIN_DIR, img) img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) training_data.append([np.array(img), np.array(label)]) shuffle(training_data) np.save('train_data.npy', training_data) return training_data '''Processing the given test data''' def process_test_data(): testing_data = [] for img in tqdm(os.listdir(TEST_DIR)): path = os.path.join(TEST_DIR, img) img_num = img.split('.')[0] img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) testing_data.append([np.array(img), img_num]) shuffle(testing_data) np.save('test_data.npy', testing_data) return testing_data '''Running the training and the testing in the dataset for our model''' train_data…
tagged with: conv-neural-network
answer count: 0
score: 1

http://stackoverflow.com/comment/92002028
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52516709
has text: @UmerFarooq it failed as below : (is this connectivity issue ?) $ git clone https://github.com/PyCQA/pylint.git Cloning into 'pylint'... ls remote: Enumerating objects: 52, done. remote: Counting objects: 100% (52/52), done. remote: Compressing objects: 100% (32/32), done. error: RPC failed; curl 18 transfer closed with outstanding read data remaining fatal: the remote end hung up unexpectedly86 MiB | 20.00 KiB/s fatal: early EOF fatal: index-pack failed

http://stackoverflow.com/comment/91954626
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52486500
has text: It worked but how did you know to do that? What's the theory behind this solution?
score: 0

http://stackoverflow.com/a/55383938
type: Answer
has comment: http://stackoverflow.com/comment/107244291
answers question: http://stackoverflow.com/q/52566503
score: 6
upvote count: 7
downvote count: 1
has body: I had a similar issue on my mac OS where I couldn't install anything or even upgrade pip from within a virtual environment due to SSL issues. What worked for me was doing the following from inside the virtual environment sudo chown -R ${whoami} /usr/local/Cellar followed by brew install openssl What is the ${whoami} in the first command? It's a placeholder; what you should put there when you run the command is your actual current user. If you don't know your user, in the command line type whoami The output is your user. So if you type that and get johnsmith as output, when you run the first command, you'll replace "${whoami}" with "johnsmith" like this: sudo chown -R johnsmith /usr/local/Cellar

http://stackoverflow.com/q/52457779
has comment: http://stackoverflow.com/comment/91857750
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I have a script that generates DataFrames with 1 row and 50 columns. Each cell of each DataFrame contains a string. However, with the possible exception of one cell, all these strings contain no elements, so they look like this: ''. As a result, each DataFrame looks something like this: Col 1 Col 2 ... Col 49 Col 50 0 "Here it is." Only one of the cells may contain a full sentence (the one in column 49 in this case), but it is unknown what the sentence is and in which column it is located. And I want to return only that sentence. What is a simple way to do this?
has title: How to print the only non-empty cell in a 1 x 50 Dataframe? python
tagged with: python
accepted answer: http://stackoverflow.com/a/52457927
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91857892
score: 1
has answer: http://stackoverflow.com/a/52457961
upvote count: 1
has comment: http://stackoverflow.com/comment/91857784
type: Question
has comment: http://stackoverflow.com/comment/91858014
has comment: http://stackoverflow.com/comment/91857932
possible better answer: http://stackoverflow.com/a/52457961
has comment: http://stackoverflow.com/comment/91857933
has answer: http://stackoverflow.com/a/52458116
has comment: http://stackoverflow.com/comment/91857875
has answer: http://stackoverflow.com/a/52457927

http://stackoverflow.com/q/52535081
downvote count: 2
answer count: 2
favorite count: 0
score: 0
has body: I'm writing some code for a casino game called Baccarat. It's written in Python 3 and I would say that I'm a newbie in Python programming and this is my first project. Problem 1: when I want to quit the game in the first phase of the game it goes to the second phase and asks the next question after typing "q", which is not ok. Bet on Player / Tie / Banker: q Thanks for playing Baccarat. **How much money do you want to bet on q:** Problem 2: when I choose one of "Player/Tie/Banker" choices and go to the next question, whatever I write as an input it always shows me the first elif condition of the bet_amount() function: Bet on Player / Tie / Banker: b you bet on Banker How much money do you want to bet on b: **55** **please type a number between 1 and 10,000** How should I solve these problems? And what is wrong in my code? This is my code: import random, string """ Casino game, Baccarat: there are three choices for users, Player, Tie and Banker. If users choose either player or banker and win their money will be doubled. if the rep goes Tie and they had chosen P or B they get a refund. otherwise they lose their money. E.g: Kevin bets on player, but Banker wins, he loses his money. Kevin bets 100$ on Banker and he wins, he gets 200$. Kevin bets on player or banker, bet goes Tie, he gets his 100$ back. Kevin bets 100$ on Tie, bet goes Tie, he will get 800$. player and banker recieve two cards, if the sum is &lt;= 5, they recieve another card. 9 is the biggest number in baccarat. if users get a 9, and dealer has 8 or lower number, users win the game. """ # list of cards card_lst = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] # value of each card card_value = {"A": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 0, "J": 0, "Q": 0, "K": 0} # the range of money that players can bet money_range = range(1, 10001) class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW …
has answer: http://stackoverflow.com/a/52535282
has title: Baccarat project in Python 3
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52535245
type: UnansweredQuestion
type: Question
upvote count: 2

http://stackoverflow.com/a/71488566
has body: First, let's wrap up an important discussion covered in the comments: your setup.py containing an f-string won't be invoked anyway, unless the client's pip version is extremely old. Older than introduction of support for python_requires metadata, which was in pip 9.0.0 (2016) (changelog). Note that all direct invocations of setup.py are effectively deprecated, and if pip was able to find a wheel distribution then there will be no setup.py executed at all, that file is not even included in the wheel. Now to answer the actual question: it's acceptable to use newer language features anytime, even immediately, as long as your package metadata communicates the minimum required Python version which is supported. You're already doing this in the example code in the question by providing a lower bound on the python_requires: setup( ... python_requires=">=3.6", ... ) The built distribution will have metadata associated advertising that a Python version of at least 3.6 is required, which means Python runtimes older than 3.6 will not attempt to install the package in the first place. In fact, pip will not even attempt to download it in that case. The Python version requirement will be displayed on the project landing page like this: And the actual release file, abcutil-1.1.0.tar.gz, will be "invisible" to lower Python versions for all practical purposes, for example: $ python2 -m pip install --index-url=https://test.pypi.org/simple abcutil Looking in indexes: https://test.pypi.org/simple ERROR: Could not find a version that satisfies the requirement abcutil (from versions: none) ERROR: No matching distribution found for abcutil You may enable pip's verbose logging to witness the package finder seeing and intentionally skipping this distribution: $ python2 -m pip install -i https://test.pypi.org/simple abcutil -v |& grep abcutil-1 Link requires a different Python (2.7.18 not in: u'>=3.6'): https://test-files.pythonhosted.org/packages/89/8a/45a45b35deae088b184b776fb11392e13023ee…
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/126355229
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52540693
has comment: http://stackoverflow.com/comment/126355226
answers question: http://stackoverflow.com/q/52540693
has comment: http://stackoverflow.com/comment/126355082
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/91876400
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52467302
has text: `l3 = [l1[i] + l2[i] for i in range(len(l1))]` just as I was posting, I wasn't sure if there was a better parameter we could implent instead of `range(len)`
type: Comment

http://stackoverflow.com/q/52551205
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52552133
has answer: http://stackoverflow.com/a/52853054
upvote count: 1
tagged with: python-requests
downvote count: 1
type: Question
has body: I would like to find a selected word and take everything from the first period(.) before it and up until the first period(.) after it. example: inside a file call 'text.php' 'The price of blueberries has gone way up. In the year 2038 blueberries have almost tripled in price from what they were ten years ago. Economists have said that berries may going up 300% what they are worth today.' Code example: (I know that if i use a code like this i can find +5 before the word ['that'] and +5 after the word, but i would like to find everything between the period before and after a word.) import re text = 'The price of blueberries has gone way up, that might cause trouble for farmers. In the year 2038 blueberries have almost tripled in price from what they were ten years ago. Economists have said that berries may going up 300% what they are worth today.' find = re.search(r"(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}that(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,5}", text) done = find.group() print(done) return: 'blueberries has gone way up, that might cause trouble for farmers' I would like it to return every sentence with ['that'] in it. Example return(what i'm looking to get): 'The price of blueberries has gone way up, that might cause trouble for farmers', 'Economists have said that berries may going up 300% what they are worth today'
has title: How to retrieve the whole sentence around a selected word?
possible better answer: http://stackoverflow.com/a/52552133
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92041985
tagged with: full-text-search
favorite count: 0
accepted answer: http://stackoverflow.com/a/52853054

http://stackoverflow.com/q/52572006
tagged with: dictionary
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92080552
has comment: http://stackoverflow.com/comment/92080603
has title: dictionaries link
linked to: http://stackoverflow.com/q/8744113
has comment: http://stackoverflow.com/comment/92080626
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/8744113
has answer: http://stackoverflow.com/a/52572078
linked to: http://stackoverflow.com/q/23852480
type: Question
answer count: 1
duplicate of: http://stackoverflow.com/q/2612802
score: 0
has comment: http://stackoverflow.com/comment/92080654
accepted answer: http://stackoverflow.com/a/52572078
has comment: http://stackoverflow.com/comment/92080582
tagged with: python
has body: I'm new to dictionaries and have found the following to be very confusing. resume = [{'name': 'New', 'value1': 'dfgdf'}, {'name': 'garry', 'value1': 'hhhhhh'}] current = resume[0] current['name'] = '24/7 link was not requested...' print(resume) Returns: [{'name': '24/7 link was not requested...', 'value1': 'dfgdf'}, {'name': 'garry', 'value1': 'hhhhhh'}] Why is this happening when a permanent/continuous link between resume and current was not requested? ...... and how can I change this so that current['name'] will update to the new/requested string value and not resume.

http://stackoverflow.com/a/72808431
has comment: http://stackoverflow.com/comment/131686646
has comment: http://stackoverflow.com/comment/135396850
score: 61
has comment: http://stackoverflow.com/comment/137074625
has comment: http://stackoverflow.com/comment/134089068
answers question: http://stackoverflow.com/q/52455774
downvote count: 0
has comment: http://stackoverflow.com/comment/131741376
has comment: http://stackoverflow.com/comment/131712518
upvote count: 61
has body: Unfortunately, I could get neither googletrans nor google_trans_new to work, despite the many proposed fixes that are around. My solution was to switch to the deep_translator package: pip install -U deep-translator Then you can use it like this: >>> from deep_translator import GoogleTranslator >>> GoogleTranslator(source='auto', target='de').translate("keep it up, you are awesome") 'weiter so, du bist toll' See documentation for more info.
type: Answer

variables
tag name: variables
tags question: http://stackoverflow.com/q/52567038
tags question: http://stackoverflow.com/q/52522667
tags question: http://stackoverflow.com/q/52469269
tags question: http://stackoverflow.com/q/52530787
type: Tag
tags question: http://stackoverflow.com/q/52563927
tags question: http://stackoverflow.com/q/52533609
tags question: http://stackoverflow.com/q/52572956
tags question: http://stackoverflow.com/q/52522770
tags question: http://stackoverflow.com/q/52462994
tags question: http://stackoverflow.com/q/52523106

http://stackoverflow.com/a/52575245
accepted answer of: http://stackoverflow.com/q/52575212
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92086168
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92086310
answers question: http://stackoverflow.com/q/52575212
has comment: http://stackoverflow.com/comment/92086235
has comment: http://stackoverflow.com/comment/92086221
has body: Try this: data = """{ "api1":{ "api1": "Num 1", "cooldown": "False" }, "api2":{ "api2": "Num 2", "cooldown": "False" }, "api3":{ "api3": "Num 3", "cooldown": "True" } } """ data = json.loads(data) # example: modify "api1" cooldown to "True" data["api1"]["cooldown"] = "True" print(data)
has comment: http://stackoverflow.com/comment/92086330
has comment: http://stackoverflow.com/comment/92086171

http://stackoverflow.com/comment/91866017
has text: Do you use Python 2.7?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52461896

http://stackoverflow.com/comment/91832732
type: Comment
comment on: http://stackoverflow.com/a/52445009
score: 1
type: AnswerComment
has text: Please add some details as to how Cloud Translation could help solve this problem.

http://stackoverflow.com/q/52454546
answer count: 2
linked to: http://stackoverflow.com/q/3207219
upvote count: 2
has answer: http://stackoverflow.com/a/52454935
score: 0
downvote count: 2
tagged with: pandas
has title: Use pandas.read_csv to read files containing str() in file's name
has comment: http://stackoverflow.com/comment/91852117
has comment: http://stackoverflow.com/comment/91854912
has comment: http://stackoverflow.com/comment/91851788
tagged with: string
possible better answer: http://stackoverflow.com/a/52454935
has body: I am trying to use pandas.read_csv to read files that contain the date in their names. I used the below code to do the job. The problem is that the files name is not consistent as the number of date change the pattern. I was wondering if there is a way to let the code read the file with parts of the name is the date in front of the file name? for x in range(0,10): dat = 20170401+x dat2 = dat+15 file_name='JS_ALL_V.'+str(dat)+'_'+str(dat2)+'.csvp.gzip' df = pd.read_csv(file_name,compression='gzip',delimiter='|')
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52456322
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91852382
has comment: http://stackoverflow.com/comment/91854244
has answer: http://stackoverflow.com/a/52456322
type: Question

http://stackoverflow.com/comment/92017261
comment on: http://stackoverflow.com/a/52529980
type: AnswerComment
score: 0
has text: What do you mean the size remain unchanged? Note that `zeros = np.zeros(array2.shape, dtype=np.int32)` uses array **2**'s shape, and in `zeros[60:-60,:,:] = array1[:,:,:-1]` it uses array **1**'s values.
type: Comment

http://stackoverflow.com/comment/92036111
comment on: http://stackoverflow.com/q/52547705
type: Comment
type: QuestionComment
has text: It seems that the result of `getTestWithAreasAndIssues()` cannot be mapped with the `TestSchema`, it has not the same structure. Think about having an other schema for this specific query.
score: 0

dbscan
tags question: http://stackoverflow.com/q/52560683
tag name: dbscan
tags question: http://stackoverflow.com/q/52479397
type: Tag
tags question: http://stackoverflow.com/q/52567368

http://stackoverflow.com/q/52457595
tagged with: python
tagged with: pygame
favorite count: 0
has comment: http://stackoverflow.com/comment/91865039
upvote count: 3
tagged with: joystick
has comment: http://stackoverflow.com/comment/91865552
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52485962
type: Question
has comment: http://stackoverflow.com/comment/91865522
answer count: 1
downvote count: 0
has title: Using joystick module from PyGame
has body: Exact code with commenting can be found here, or here. while done==False: for event in pygame.event.get(): if event.type == pygame.QUIT: done=True if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.") screen.fill(darkgrey) textPrint.reset() joystick_count = pygame.joystick.get_count() textPrint.print(screen, "Number of joysticks: {}".format(joystick_count) ) textPrint.indent() for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() textPrint.print(screen, "Joystick {}".format(i) ) textPrint.indent() name = joystick.get_name() textPrint.print(screen, "Joystick name: {}".format(name) ) axes = joystick.get_numaxes() textPrint.print(screen, "Number of axes: {}".format(axes) ) textPrint.indent() for i in range( axes ): axis = joystick.get_axis( i ) textPrint.print(screen, "Axis {} value: {:&gt;6.0f}".format(i, axis) ) textPrint.unindent() buttons = joystick.get_numbuttons() textPrint.print(screen, "Number of buttons: {}".format(buttons) ) textPrint.indent() for i in range( buttons ): button = joystick.get_button( i ) textPrint.print(screen, "Button {:&gt;2} value: {}".format(i,button) ) textPrint.unindent() hats = joystick.get_numhats() textPrint.print(screen, "Number of hats: {}".format(hats) ) textPrint.indent() for i in range( hats ): hat = joystick.get_hat( i ) textPrint.print(screen, "Hat {} value: {}".format(i, str(hat)) ) textPrint.unindent() pygame.display.flip() clock.tick(20) With the help of the online PyGame documentation, I was able to produce a screen displaying values for individual Joysticks. How would I translate these values to an event that says this button is pressed, now do this? Something similar to this, for i in range( axes ): axis = joystick.get_axis( i ) textPrint.print(screen, "Axis {} value: {:&gt;6.0f}".format(i, axis) ) if Joystick 2's Axis 3 is equal to 1: print("Joystick 2 is pointing to the right.") if Joystick 2's Axi…
has comment: http://stackoverflow.com/comment/91865048
tagged with: gamepad
linked to: http://stackoverflow.com/q/9961752
has comment: http://stackoverflow.com/comment/91865487
accepted answer: http://stackoverflow.com/a/52485962
score: 3

http://stackoverflow.com/q/52533733
downvote count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52534258
upvote count: 2
tagged with: postgresql
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52534258
tagged with: python-3.x
tagged with: python
tagged with: psycopg2
has body: From my python code i had the method: def start_db(event, context): conn = db() cur = conn.cursor() datada = event['data_start'] dataa = event['data_stop'] if not datada or not dataa: dataa = str(datetime.datetime.now()) datada = str(dataa - datetime.timedelta(days=7)) s_query = "SELECT * FROM a_usage WHERE (bk_tenant = '%s', data_start LIKE '%s'::timestamp, data_stop LIKE '%s'::timestamp);" % (event['bk_tenant'], datada, dataa) cur.execute(s_query) A = cur.fetchone() conn.commit() cur.close() conn.close() return A but when i run my code (db is postgreSQL) an error occur: operator does not exist: timestamp without time zone ~~ timestamp without time zone what's wrong in my code? Thanks in advance
type: AnsweredQuestion
score: 2
has title: python psycopg2 query error timestamp without time zone

http://stackoverflow.com/a/52463126
has body: ~Python 3.6 def return_only_ascii(str) return ''.join([x for x in str if ord(x) &lt; 128]) Python 3.7~ def return_only_ascii(str) return ''.join([x for x in str if x.isascii()]) Result &gt;&gt;&gt; return_only_ascii('José') 'Jos'
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52462906

http://stackoverflow.com/comment/131163522
type: AnswerComment
score: 0
has text: This is great - ready to use code!
type: Comment
comment on: http://stackoverflow.com/a/55101054

http://stackoverflow.com/a/52484268
answers question: http://stackoverflow.com/q/52481880
has body: First, get your parent element: parent = driver.find_element_by_class_name("mozaique") Then get a list of all 'a' tags within your parent element. a = parent.find_elements_by_tag_name("a") Then run a loop to print the hrefs for x in a: print(x.get_attribute("href"))
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/104159419

http://stackoverflow.com/comment/92105764
has text: As per reference question you mentioned, did you try using like this, appointments = db.relationship(Appointment, backref ='doctor') in Doctor Object.
comment on: http://stackoverflow.com/q/52584099
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52557692
accepted answer: http://stackoverflow.com/a/52558215
has title: How to hide/show an axes, not axis in matplotlib
has body: There are plenty of questions (and answers) as to how to hide/show axis on matplotlib figures. How can I hide/show whole axes? I have a figure containing five axes but I want to be able to hide (then show) one of those.
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
score: -1
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/52558215

http://stackoverflow.com/comment/91831860
type: Comment
comment on: http://stackoverflow.com/q/52431823
has text: it was coming up with this message "ValueError: Length of values does not match length of index" so what I did was I changed your suggested to a panda series `df['prediction'] = pd.Series(y_pred_class)` which then allowed me to merge the series with the data frame `dfout = pd.merge(dfpred,df['prediction'].dropna() .to_frame(),how = 'left',left_index = True, right_index = True)` **Please let me know what you think**
score: 0
type: QuestionComment

http://stackoverflow.com/a/52465569
type: Answer
has body: Try setting up a simple Flask app at www.pythonanywhere.com, I think it will do the job for you even with the free account. EDIT: And for sending e-mails, you can use Mailgun, with the free version you can send e-mails to a small number of addresses that need to be validated from the recipient side (to avoid people using it for spam :-))
answers question: http://stackoverflow.com/q/52465469
score: 0

http://stackoverflow.com/comment/91951974
type: Comment
type: QuestionComment
has text: @Aran-Fey what are good options then?
score: 0
comment on: http://stackoverflow.com/q/52505696

http://stackoverflow.com/comment/91828132
comment on: http://stackoverflow.com/q/52442703
has text: Please post a [mcve]. The code you posted throws an exception, and if I fix that part of the code, then it works as expected.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52491501
has answer: http://stackoverflow.com/a/52491781
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52491819
accepted answer: http://stackoverflow.com/a/52491781
has answer: http://stackoverflow.com/a/52491819
has comment: http://stackoverflow.com/comment/91923982
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
tagged with: numpy
has title: numpy: comparing two date values returns TypeError: '>=' not supported between instances of 'int' and 'datetime.datetime'
has body: I'm a newby in python and numpy. While practicing I wrote this code: import pandas as pd import numpy as np from datetime import datetime, timedelta date_today = datetime.now() days = pd.date_range(date_today, date_today + timedelta(7), freq='D') np.random.seed(seed=1111) data = np.random.randint(1, high=100, size=len(days)) df = pd.DataFrame({'test': days, 'col2': data}) df = df.set_index('test') print(df) dates = np.array(df.index) print(dates) start_idx = np.where(dates&gt;=datetime.strptime('2018-01-01', "%Y-%m-%d"))[0][-1] print(start_idx) but it give the below error: Traceback (most recent call last): File "C:/Users/mohammadi/Desktop/sampleDF.py", line 15, in &lt;module&gt; start_idx = np.where(dates&gt;=datetime.strptime('2018-01-01', "%Y-%m-%d"))[0][-1] TypeError: '&gt;=' not supported between instances of 'int' and 'datetime.datetime'

http://stackoverflow.com/a/52559569
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: In order to get more submissions from a user change the limit attribute of the new method. By default I believe the value of limit is 25, but you can raise the limit with this line. redditor.submissions.new(limit=1000) #you can use any number in place of 1000
accepted answer of: http://stackoverflow.com/q/52520949
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52520949

http://stackoverflow.com/q/52484066
tagged with: tdd
type: Question
score: 0
tagged with: python
answer count: 1
tagged with: unit-testing
has body: As far as I understand TDD, we should write minimum amount of tests to fail meeting our code's goal and then write only the code necessary to pass such tests. However, does testing for called functions signatures, including testing for number of passed non-keyworded and keyworded arguments (like Python's *args and **kwargs), should be incorporated into our test suite as well? For instance, if we have a function calling external API that may take numerous arguments with many defaults, I guess it makes sense whether we test we call such API precisely as intended (including passing no more arguments than necessary or checking we pass none of keyworded flags, as we do not need anything else than the default options)?
has title: Should we test for called functions signatures (including number of passed arguments)?
has answer: http://stackoverflow.com/a/52486393
type: UnansweredQuestion

http://stackoverflow.com/q/52458382
has comment: http://stackoverflow.com/comment/91860088
score: 1
has comment: http://stackoverflow.com/comment/91860087
has comment: http://stackoverflow.com/comment/91859278
has comment: http://stackoverflow.com/comment/91859006
duplicate of: http://stackoverflow.com/q/15286401
answer count: 2
has title: Error using end=" " within a function call
favorite count: 0
has answer: http://stackoverflow.com/a/52458610
has answer: http://stackoverflow.com/a/52458414
accepted answer: http://stackoverflow.com/a/52458610
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/15286401
type: AnsweredQuestion
upvote count: 2
has body: The following code works to send a message to a user: mud.send_message(id, rooms[self.current_room]["desc"]) In one part of the game code, I don't want to start on a new line so I try: mud.send_message(id, rooms[self.current_room]["desc"], end=" ") mud.send_message(id, "This starts on the same line as the code above.") This of course raises an error that the third variable (end=" ") is not welcome here. How can I start the second message on the same line? Extra info if needed: def send_message(self, to, message): self._attempt_send(to, message+"\n\r")
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52458414
has comment: http://stackoverflow.com/comment/91860225

http://stackoverflow.com/a/52554612
has comment: http://stackoverflow.com/comment/92072616
has comment: http://stackoverflow.com/comment/92072568
has comment: http://stackoverflow.com/comment/92070056
has comment: http://stackoverflow.com/comment/92072864
upvote count: 2
answers question: http://stackoverflow.com/q/52552784
has comment: http://stackoverflow.com/comment/92048120
has comment: http://stackoverflow.com/comment/92049341
type: Answer
has comment: http://stackoverflow.com/comment/92049497
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92049032
has body: If I well understand what you need, it can already be done thanks to the foreign key to the company model you have on group and ledger. You just have to use in the query the "related_name" value you specified in the model. https://docs.djangoproject.com/en/2.1/topics/db/queries/ Example: # get the companies created by the user companies = company.objects.filter(User=request.user) # select the company you need for example the first one mycompany = companies.first() # then get groups or ledgers related to it groups = mycompany.Company_group.all() ledgers = mycompany.Companys.all() Just a suggestion: try to use always the same format when you declare classes and attributes (like always lowecase), then it become easier to read and use them.
has comment: http://stackoverflow.com/comment/92072751

http://stackoverflow.com/comment/91995235
comment on: http://stackoverflow.com/a/52520267
type: Comment
has text: I edite my origibal post: add print(child.before) and print the ret vaiable. Even the child.before is '', ret is 4...............
type: AnswerComment
score: 0

sublime-anaconda
tags question: http://stackoverflow.com/q/52576573
tag name: sublime-anaconda
type: Tag

http://stackoverflow.com/q/52491972
has comment: http://stackoverflow.com/comment/91924735
tagged with: python
downvote count: 2
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91925431
tagged with: numpy
has comment: http://stackoverflow.com/comment/91924761
has comment: http://stackoverflow.com/comment/91924610
has comment: http://stackoverflow.com/comment/91924505
has answer: http://stackoverflow.com/a/52492332
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91924687
has comment: http://stackoverflow.com/comment/91924679
favorite count: 0
score: -1
has title: How to update python array after certain operation
type: Question
has comment: http://stackoverflow.com/comment/91924637
has body: In the following code, I have an array named List. When for loop runs the first time I slice some values of this array and make a new array named new. Now I want to replace List by new so that when for loop runs the second time it slices values from new not from List. So how can I do that? def update(): low =[1.5, 2.5, 3.0] high = [4.0, 4.5, 5.0] for i in range(len(low)): h1 = low[i] h2 = high[i] List=np.arange(1.0, 5.01, 0.5) hList =[] for k in range(len(List)): hList.append(round(List[k],2)) low_ind =hList.index(low[i]) high_ind = hList.index(high[i]) #Slicing List = List[low_ind:high_ind]`` Here is result `i is: 0 List: [1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ] After_Slicing [1.5 2. 2.5 3. 3.5] i is: 1 List: [1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ] After_Slicing [2.5 3. 3.5 4. ] i is: 2 List: [1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ] After_Slicing [3. 3.5 4. 4.5]`

http://stackoverflow.com/comment/91820284
comment on: http://stackoverflow.com/a/52438634
type: AnswerComment
has text: it's not default.
score: 0
type: Comment

http://stackoverflow.com/q/52432695
tagged with: dictionary
answer count: 0
tagged with: pairing
score: 1
has comment: http://stackoverflow.com/comment/91810392
has comment: http://stackoverflow.com/comment/91809789
upvote count: 1
has body: I wish to pair up two elements. I know this can be done by dictionary but the limitation in dictionary is that two key values cant be same. Example: 1 2 1 3 1 4 4 5 2 3 3 4 3 5 3 6 6 7 i want something like this: {1:2,1:3,1:4,4:5,2:3,3:4,3:5,3:6,6:7} But by using dictionary the output generated is : {1: 4, 2: 3, 3: 6, 4: 5, 6: 7} How can i overcome this problem?
type: Question
has comment: http://stackoverflow.com/comment/91810542
has comment: http://stackoverflow.com/comment/91809937
has comment: http://stackoverflow.com/comment/91810468
has comment: http://stackoverflow.com/comment/91809427
has comment: http://stackoverflow.com/comment/91810270
has title: Pairing elements in python
downvote count: 0
linked to: http://stackoverflow.com/q/1731971
has comment: http://stackoverflow.com/comment/91810591
has comment: http://stackoverflow.com/comment/91809491
has comment: http://stackoverflow.com/comment/91810011
favorite count: 0
has comment: http://stackoverflow.com/comment/91810441
has comment: http://stackoverflow.com/comment/91809418
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91809896
has comment: http://stackoverflow.com/comment/91810610
tagged with: python

python-unittest.mock
tags question: http://stackoverflow.com/q/52563237
tag name: python-unittest.mock
type: Tag
tags question: http://stackoverflow.com/q/52571815

http://stackoverflow.com/comment/91881069
comment on: http://stackoverflow.com/q/52469543
score: 0
type: QuestionComment
has text: @DanielRoseman, I understand that if you put that in that way, that will transfer it to set, but for representation purpose i put it in that way. that is List actually
type: Comment

http://stackoverflow.com/comment/91805418
comment on: http://stackoverflow.com/q/52430392
type: QuestionComment
type: Comment
score: 0
has text: Ask yourself, what is grade?

http://stackoverflow.com/comment/92280152
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52485828
type: QuestionComment
has text: To continue, if you’d like to make your area of study thoughtless for consumers who wish to perform analyses, then create a docker (which I know you mentioned you did not wish to do). But my advice is to either teach the people working with you in depth, or do it yourself because it isn’t reasonable to perform your request.

http://stackoverflow.com/a/60253769
has comment: http://stackoverflow.com/comment/107641154
answers question: http://stackoverflow.com/q/52468956
downvote count: 0
score: 16
has comment: http://stackoverflow.com/comment/129676086
has body: Here is how you do it with torchviz if you want to save the image: # http://www.bnikolic.co.uk/blog/pytorch-detach.html import torch from torchviz import make_dot x=torch.ones(10, requires_grad=True) weights = {'x':x} y=x**2 z=x**3 r=(y+z).sum() make_dot(r).render("attached", format="png") screenshot of image you get: source: http://www.bnikolic.co.uk/blog/pytorch-detach.html
has comment: http://stackoverflow.com/comment/107560626
upvote count: 16
type: Answer

http://stackoverflow.com/comment/91821734
has text: You could just sample your validation data manually using numpy, and then pass it to Keras.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52439468

http://stackoverflow.com/comment/92089931
has text: use "infos = [' '.join(' '.join(info.get_text(", ", strip=True).split()) for info in page_data.find_all('h9'))]"
type: Comment
comment on: http://stackoverflow.com/a/52570315
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92039428
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52550304
has text: Increment `count` instead of decrementing `num`. And if you only want odd numbers, add 2 each time instead of adding one and checking if they are odd. Btw, what you do isn't called sorting.
score: 0

http://stackoverflow.com/comment/91807628
comment on: http://stackoverflow.com/q/52431278
has text: @lv10, I collect basic stock data and make some calculations. if in the process, i recognize some "Trues", than i ask for more data (different data from other site), and again and again until to the end.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52505483
linked to: http://stackoverflow.com/q/3226074
tagged with: regex
has body: The problem, and it may not be easily solved with a regex, is that I want to be able to extract a Windows file path from an arbitrary string. The closest that I have been able to come (I've tried a bunch of others) is using the following regex: [a-zA-Z]:\\([a-zA-Z0-9() ]*\\)*\w*.*\w* Which picks up the start of the file and is designed to look at patterns (after the initial drive letter) of strings followed by a backslash and ending with a file name, optional dot, and optional extension. The difficulty is what happens, next. Since the maximum path length is 260 characters, I only need to count 260 characters beyond the start. But since spaces (and other characters) are allowed in file names I would need to make sure that there are no additional backslashes that could indicate that the prior characters are the name of a folder and that what follows isn't the file name, itself. I am pretty certain that there isn't a perfect solition (the perfect being the enemy of the good) but I wondered if anyone could suggest a "best possible" solution?
type: UnansweredQuestion
tagged with: path
tagged with: file
upvote count: 1
tagged with: python
score: 1
has title: Python regular expression for Windows file path
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52505892
has comment: http://stackoverflow.com/comment/91952182

http://stackoverflow.com/a/52570508
answers question: http://stackoverflow.com/q/52570280
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92077917
has body: Lets say you have a file which looks like- abc def ged adw ret qwer tre.... so on Now when I do readlines the cursor pointing to the file object will be on the first line..and If I do file.readlines.split(' ') will return a list of words in the first line...readline.split('\n') will return the first line itself. Since each line is already split in newlines it will return the same line
downvote count: 0
has comment: http://stackoverflow.com/comment/92077872

http://stackoverflow.com/comment/91917413
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52487664
type: QuestionComment
has text: No, you can't. You can only get the return value of the parent method. If you can modify the code of the parent class, you have all kinds of options. But you say that that's not possible, so I'm sorry but the answer is just a plain old "No".

http://stackoverflow.com/a/52524506
downvote count: 0
has body: Pass the constant as a parameter: def f(x, m): numerator = m**2*(m*s.cos(x/2) - 1)*(m - s.cos(x/2)) denominator = 4*s.cos(x/2)*(1 + m**2 - 2*m*s.cos(x/2))**2 return numerator/denominator fig, ax = plt.subplots() m_arr = s.asarray([1.1, 1.2, 1.3, 1.5, 2.0]) for const_m in m_arr: ax.plot(x, f(x, const_m))
answers question: http://stackoverflow.com/q/52524211
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/52524211
type: AcceptedAnswer

http://stackoverflow.com/comment/91836909
type: QuestionComment
has text: besides calling plt.show() between each plot, I don't know a better way
score: 0
comment on: http://stackoverflow.com/q/52446943
type: Comment

http://stackoverflow.com/q/52535303
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/32788322
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/92014597
type: Question
has body: I have the function get_alerts that returns two String fields. For simplicity let's consider the fixed output of this function: return "xxx", "yyy" (this is to avoid posting the code of get_alerts). Then I have the UDF function and I use when-otherwise expression in Spark DataFrame df. import pyspark.sql.functions as func get_alerts_udf = func.udf(lambda c1, c2, c3: get_alerts(c1, c2, c3), StructType( [ StructField('probability', StringType()), StructField('level', StringType()) ] ) ) df = df \ .withColumn("val", func.when(func.col("is_inside") == 1, get_alerts_udf(1,2,3)) .otherwise(["0","0"]) ) The problem is that otherwise(["0","0"]) does not correspond to the type of the output of the function get_alerts_udf. How do I define otherwise(["0","0"]) to correspond to: StructType( [ StructField('probability', StringType()), StructField('level', StringType()) ] ) UPDATE: I still get the error: pyspark.sql.utils.AnalysisException: u"cannot resolve 'CASE WHEN (is_inside` = 1) THEN &lt;lambda&gt;(c1, c2, c3) ELSE named_struct('col1', '0', 'col2', '0') END' due to data type mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;`. According to the recommendation from a duplicate post, I used otherwise(func.struct(func.lit("xxx"),func.lit("yyy"))).
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/92012490
has comment: http://stackoverflow.com/comment/92043159
linked to: http://stackoverflow.com/q/32788322
has title: How to create correct output in when-otherwise?

plotly
tags question: http://stackoverflow.com/q/52467277
tags question: http://stackoverflow.com/q/52467323
type: Tag
tags question: http://stackoverflow.com/q/52434353
tags question: http://stackoverflow.com/q/52543146
tags question: http://stackoverflow.com/q/52549904
tags question: http://stackoverflow.com/q/52579460
tags question: http://stackoverflow.com/q/52535776
tags question: http://stackoverflow.com/q/52528889
tags question: http://stackoverflow.com/q/52494975
tags question: http://stackoverflow.com/q/52578518
tags question: http://stackoverflow.com/q/52441115
tags question: http://stackoverflow.com/q/52527718
tag name: plotly
tags question: http://stackoverflow.com/q/52468325
tags question: http://stackoverflow.com/q/52584339
tags question: http://stackoverflow.com/q/52467562
tags question: http://stackoverflow.com/q/52537801
tags question: http://stackoverflow.com/q/52551957
tags question: http://stackoverflow.com/q/52521194
tags question: http://stackoverflow.com/q/52568285
tags question: http://stackoverflow.com/q/52485819

http://stackoverflow.com/comment/129676086
score: 0
type: AnswerComment
type: Comment
has text: +1 this is the only answer that actually works for my torchviz. The important part is `requires_grad=True`
comment on: http://stackoverflow.com/a/60253769

http://stackoverflow.com/comment/117379883
type: AnswerComment
has text: Yeah @Glutanimate is well known for his published addons so I'm also surprised he didn't bring it up - maybe he didn't actually use this solution in the end. I guess another way around those constraints could be to add a stable alias for your addon in `sys.modules` to use, like: `sys.modules["myuniqueaddonname"] = sys.modules[__name__]`. There's still technically a chance of collision but at least you can minimize that. Still I think relative imports are the way to go, just as they are in addon code you write yourself.
comment on: http://stackoverflow.com/a/52681711
score: 0
type: Comment

http://stackoverflow.com/q/52538930
tagged with: flask
tagged with: ldap
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52557510
accepted answer: http://stackoverflow.com/a/52557510
has body: I am using FLASK_LDAP_AUTH for login system. I am checking a another server server AD to login. but when i run it only look at my local host ? also it keep saying following error 401 {"error": "unauthorized", "message": "Please authenticate with a valid token", "status": 401} app.config['SECRET_KEY'] = 'somethingsecret' app.config['LDAP_AUTH_SERVER'] = 'ldap://serverIP' app.config['LDAP_TOP_DN'] = 'ou=Users,dc=your_org,dc=TEST.domain' app.register_blueprint(token, url_prefix='/auth') In this link https://github.com/drowolath/flask-ldap-auth its say something with token which is not clear. Hope anyone can help
type: Question
has title: LDAP-login FLASK
tagged with: active-directory
score: 0
answer count: 1

calculation
tags question: http://stackoverflow.com/q/52485217
type: Tag
tag name: calculation

http://stackoverflow.com/q/52451797
downvote count: 0
answer count: 1
has body: Consider the convolutional neural network (two convolutional layers): class ConvNet(nn.Module): def __init__(self, num_classes=10): super(ConvNet, self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.layer2 = nn.Sequential( nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.fc = nn.Linear(7*7*32, num_classes) def forward(self, x): out = self.layer1(x) out = self.layer2(out) out = out.reshape(out.size(0), -1) out = self.fc(out) return out The fully connected layer fc is to have 7*7*32 inputs coming in. The above: out = out.reshape(out.size(0), -1) leads to a tensor with size of (32, 49). This doesn't seem right as the dimensions of input for the dense layer is different. What am I missing here? [Note that in Pytorch the input is in the following format: [N, C, W, H] so no. of channels comes before the width and height of image] source: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/convolutional_neural_network/main.py#L35-L56
favorite count: 0
has answer: http://stackoverflow.com/a/52456426
tagged with: python
has title: How does the reshape work before the fully connected layer in the following CNN model?
score: 2
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: pytorch
upvote count: 2
accepted answer: http://stackoverflow.com/a/52456426
type: Question
tagged with: deep-learning

http://stackoverflow.com/a/52573403
answers question: http://stackoverflow.com/q/52573370
has comment: http://stackoverflow.com/comment/92083070
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52573370
score: 0
type: Answer
has body: One way would be to convert the list to an array and reshape it as follows: new_range=np.array(new_range).reshape(10,10) Output: array([[120, 622, 698, 367, 657, 929, 135, 423, 228, 941], [868, 893, 8, 840, 31, 678, 226, 599, 272, 133], [819, 662, 27, 195, 674, 2, 211, 550, 782, 165], [289, 770, 174, 827, 897, 296, 165, 38, 807, 701], [982, 706, 660, 795, 110, 799, 565, 745, 371, 77], [ 13, 201, 840, 961, 690, 345, 202, 79, 544, 196], [923, 386, 829, 799, 123, 45, 778, 880, 700, 302], [316, 302, 436, 145, 584, 533, 851, 542, 443, 619], [616, 692, 996, 634, 549, 105, 602, 938, 135, 468], [245, 443, 384, 987, 301, 364, 76, 599, 159, 908]])

http://stackoverflow.com/q/52462331
answer count: 4
type: Question
tagged with: syntax-error
score: -2
has answer: http://stackoverflow.com/a/52462344
linked to: http://stackoverflow.com/q/826948
duplicate of: http://stackoverflow.com/q/25445439
downvote count: 2
has answer: http://stackoverflow.com/a/52462349
has answer: http://stackoverflow.com/a/52462360
has comment: http://stackoverflow.com/comment/91866889
favorite count: 0
upvote count: 0
has body: I'm a beginner of Python and I got a problem here. I just copied what my textbook says but I got an error here. I put the following code. if return_age != 0: print"Your age is %s years" %(return_age) Then my laptop says File "&lt;ipython-input-3-8c2f6bc68809&gt;", line 15 print"Your age is %s years" %(return_age) ^ SyntaxError: invalid syntax Please explain how to correct this bug. Thanks in advance.
type: UnansweredQuestion
tagged with: python
has title: Why am I getting a Syntax Error in Python?
has answer: http://stackoverflow.com/a/52462363

http://stackoverflow.com/comment/92082636
comment on: http://stackoverflow.com/a/52573050
type: AnswerComment
score: 0
has text: the python -3 will launch python if I am in the Python-3.6.6 directory but nowhere else. Anywhere else it starts python 2.6.6. py is not recognized as a command anywhere
type: Comment

http://stackoverflow.com/q/52491807
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/91924282
has comment: http://stackoverflow.com/comment/91925314
has title: Fast approach to find elements from one Dataframe in another and return their indexes
has comment: http://stackoverflow.com/comment/91924231
has body: Simply put, I'm trying to compare values from 2 columns of the first DataFrame with the same columns in another DataFrame. The indexes of the matched rows are stored as a new column in first DataFrame. Let me explain: I'm working with geographical features (latitude/longitude) and the main DataFrame -- called df -- has something like 55M observations, which look a little bit like this: As you can see, there are only two rows with data that looks legit (indexes 2 and 4). The second DataFrame -- called legit_df --, is much much smaller and has all the geographical data I consider legit: Without getting into WHY, the main task involves comparing each latitude/longitude observation from df to the data of legit_df. When there's a successful match, the index of legit_df is copied to a new column of df, resulting in df looking like this: The value -1 is used to show when there wasn't a successful match. In the example above, the only observations that were valid are the ones at indexes 2 and 4, which found their matches at indexes 1 and 2 in legit_df. My current approach to solve this problem uses .apply(). Yes, its slow, but I couldn't find a way to vectorize the function below or use Cython to speed it up: def getLegitLocationIndex(lat, long): idx = legit_df.index[(legit_df['pickup_latitude'] == lat) &amp; (legit_df['pickup_longitude'] == long)].tolist() if (not idx): return -1 return idx[0] df['legit'] = df.apply(lambda row: getLegitLocationIndex(row['pickup_latitude'], row['pickup_longitude']), axis=1) Since this code is remarkably slow on a DataFrame with 55M observations, my question is: is there faster way to solve this problem? I'm sharing a Short, Self Contained, Correct (Compilable), Example to help-you-help-me come up with a faster alternative: import pandas as pd import numpy as np data1 = { 'pickup_latitude' : [41.366138, 40.190564, 40.769413], 'pickup_longitude' : [-73.137393, -74.689831, -73.863300] } legit_df = pd.DataFrame(data1) display(legit_df) ########…
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/52492125
accepted answer: http://stackoverflow.com/a/52492125
has comment: http://stackoverflow.com/comment/91925234
possible better answer: http://stackoverflow.com/a/52492160
favorite count: 0
has comment: http://stackoverflow.com/comment/91924154
has comment: http://stackoverflow.com/comment/91924410
tagged with: python
has comment: http://stackoverflow.com/comment/91924609
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/43196907
score: 1
tagged with: apply
has answer: http://stackoverflow.com/a/52492160

http://stackoverflow.com/a/52446510
type: Answer
downvote count: 0
score: 1
has body: Instead of testing for oddness/evenness all the time, use range(start,stop[,step]) with a step of 2 starting with a (corrected, known) odd/even number: def number(x,y): if x &gt; y: if y%2 == 1: # y is smaller &amp;&amp; odd y += 1 # make even return list(range(y,x,2)) # x is &gt; y - start from y to x else: # this is strictly not needed - but more verbose intention-wise if x%2 == 0: # is even x += 1 # make odd return list(range(x,y,2)) print(number(10,32)) print(number(10,2)) You need to also switch x and y if x &gt; y you do not need to iterate a range and add its element to a list iteratively - simply stuff the range-sequence into the list(sequence) constructor and return it Output: [11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31] [2, 4, 6, 8]
upvote count: 1
answers question: http://stackoverflow.com/q/52446347

http://stackoverflow.com/comment/92005000
score: 0
type: Comment
type: QuestionComment
has text: Use data["data"]["USD"].get("price")
comment on: http://stackoverflow.com/q/52532637

http://stackoverflow.com/comment/92081455
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52572412
has text: @Daniel: I understood the problem now. Check my solution below. It might help you

http://stackoverflow.com/comment/91970456
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52512750
has text: Yes it takes the same URL forever and I fetch some part of the content on every url/blog post of the site and keep doing it on every page

http://stackoverflow.com/q/52565436
tagged with: numpy
has title: assigning values to a numpy matrix
tagged with: arrays
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52565444
has body: I am encountering syntax error at line 7 when I am running the code. import numpy as np offset = 2 V1 = np.ones((30,21)) O = np.zeros(an-offset,pn-offset) for i in range(offset+1,an): for j in range(offset+1,pn): O(i-offset,j-offset) = (np.absolute(np.dot(np.array(V1)[:,i],np.array(V2)[:,j])))/(np.linalg.norm(V1[:,i]),np.linalg.norm(V2[:,j])) SyntaxError: can't assign to function call
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/52565444
score: 0

awk
tag name: awk
tags question: http://stackoverflow.com/q/52560361
type: Tag
tags question: http://stackoverflow.com/q/52508710

http://stackoverflow.com/comment/91862945
comment on: http://stackoverflow.com/a/52460462
has text: Thanks, I am trying to practice with while-loops though.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52489856
upvote count: 2
has comment: http://stackoverflow.com/comment/92414666
has comment: http://stackoverflow.com/comment/91938490
has comment: http://stackoverflow.com/comment/91940099
has comment: http://stackoverflow.com/comment/91939448
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91938883
accepted answer of: http://stackoverflow.com/q/52483191
type: Answer
answers question: http://stackoverflow.com/q/52483191
has body: This illustrates the result of fitting two halves of the data to different functions, the lower half to all data with X &lt; 2.0 and the upper half to all data with X >= 1.9, so that there is overlap in the data for the fitted curves. The code switches from one equation to another at the center of the overlap region, X = 1.95. import numpy, matplotlib import matplotlib.pyplot as plt xData=numpy.array([ 1.00094909, 1.08787635, 1.17481363, 1.2617564, 1.34867881, 1.43562284, 1.52259341, 1.609522, 1.69631283, 1.78276102, 1.86426648, 1.92896789, 1.9464453, 1.94941586, 2.00062852, 2.073691, 2.14982808, 2.22808316, 2.30634034, 2.38456905, 2.46280126, 2.54106611, 2.6193345, 2.69748825]) yData=numpy.array([-0.10057627, -0.10172142, -0.10320428, -0.10378959, -0.10348456, -0.10312503, -0.10276956, -0.10170055, -0.09778279, -0.08608644, -0.05797392, 0.00063599, 0.08732999, 0.16429878, 0.2223306, 0.25368884, 0.26830932, 0.27313931, 0.27308756, 0.27048902, 0.26626313, 0.26139534, 0.25634544, 0.2509893 ]) # function for x &lt; 1.95 (fitted up to 2.0 for overlap) def lowerFunc(x_in): # Bleasdale-Nelder Power With Offset # coefficients a = -1.1431476643503597E+03 b = 3.3819340844164983E+21 c = -6.3633178925040745E+01 d = 3.1481973843740194E+00 Offset = -1.0300724909782859E-01 temp = numpy.power(a + b * numpy.power(x_in, c), -1.0 / d) temp += Offset return temp # function for x &gt;= 1.95 (fitted down to 1.9 for overlap) def upperFunc(x_in): # rational equation with Offset # coefficients a = -2.5294212380048242E-01 b = 1.4262697377369586E+00 c = -2.6141935706529118E-01 d = -8.8730045918252121E-02 Offset = -4.8283287597672708E-01 temp = (a * numpy.power(x_in, 2) + b * numpy.log(x_in)) # numerator temp /= (1.0 + c * numpy.power(numpy.log(x_in), -1) + d * numpy.exp(x_in)) # denominator temp += Offset return temp def combinedFunc(x_in): returnVal = [] for x in x_in: if x &lt; 1.95: returnVal.append(lowerFunc(x)) else: returnVal.append(upperFunc(x)) return returnVal modelPredictions = com…
has comment: http://stackoverflow.com/comment/92413385
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91939164
has comment: http://stackoverflow.com/comment/92415197
has comment: http://stackoverflow.com/comment/91939980

http://stackoverflow.com/comment/91804007
score: 0
type: Comment
type: QuestionComment
has text: Yes I've got a ```__init__.py```, but its empty. I didn't show all the files, since its a lot
comment on: http://stackoverflow.com/q/52430174

http://stackoverflow.com/q/52576185
has answer: http://stackoverflow.com/a/52577083
tagged with: while-loop
tagged with: keyboard-events
has body: Just started using python one week ago. At the moment I am trying to code a small program class which creates a menu in a terminal. The idea is to go through the menu using up / down keys. You can select a menu item by pressing enter. I control the keys being pressed using the module "keyboard". In order to use my class, one has to create an object and add menu items by means of the method "add_menu". The latter mentioned method has two arguments, the first one is used for the name of the menu item, the second one is used to hand over a function, which will be called in case enter was pressed. In order to check if a key was pressed, I use the method keyboard.on_press from the module keyboard. In case a key was pressed, the method keyboard.on_press executes the method handle_menu of the menu object. The handle_menu method uses a list named "controller" in order to organize the selection of a menu item. Basically, it is just a list like [0,0,1,0]. The element being 1 indicates the currently selected menu item. Now to my problem: My menu has a menu item "Exit". If this is selected and enter is pressed, I want the whole program to stop. Therefore, if exit was pressed the attribute exit is changed from 0 to 1. In the while loop of my program I always check if object.exit is != 1, if not the program should end. Somehow this does not always work. If I scroll down immediately from the beginning, without pressing enter at other menu items, it works. However, if I press enter several times at other menu items and then go to the exit menu item, the program does not end anymore (or only if I press enter for 10-20 times). I have the feeling that the keyboard.on_press method and the while loop are sometimes uncoupled in the background and run asynchronously? I do not really understand what is going on... import keyboard #Using module keyboard import os class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0…
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: terminal
type: Question
has title: Menu for terminal - Up - Down - Enter - Using module keyboard
accepted answer: http://stackoverflow.com/a/52577083
tagged with: python
tagged with: menu
upvote count: 1
answer count: 1

http://stackoverflow.com/a/69271089
downvote count: 0
score: 21
answers question: http://stackoverflow.com/q/52455774
has comment: http://stackoverflow.com/comment/129946297
has comment: http://stackoverflow.com/comment/127789262
upvote count: 21
has body: Updated Answer as of 2021 Sept pip uninstall googletrans==4.0.0-rc1 pip install googletrans==3.1.0a0 The 3.1.0a0 version works with bulk translation too!
has comment: http://stackoverflow.com/comment/127449642
type: Answer
has comment: http://stackoverflow.com/comment/124246485

http://stackoverflow.com/q/52546854
favorite count: 0
has answer: http://stackoverflow.com/a/52720758
type: AnsweredQuestion
has body: After updated Fabric from 1.4 to 2.4, fab -f &lt;file_path&gt;.&lt;fabfile&gt;.py isn't working anymore. It always throws the error Can't find any collection named 'fabfile'! From fab --help, it stated that -f option is used to -f STRING, --config=STRING Runtime configuration file to use. Thinking to downgrade it to 1.4 since all my project on other hosts are running this version. But i cant't get back the 1.4 installer on net. Anyone could help on this or any workaround for fabric 2.4 ?
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/52720758
upvote count: 5
downvote count: 0
has title: Fabric fab -f : Can't find any collection named 'fabfile'
answer count: 1
tagged with: fabric
tagged with: python

http://stackoverflow.com/comment/92057630
has text: See [Process to convert simple Python script into Windows executable](//stackoverflow.com/q/2136837).
score: 0
comment on: http://stackoverflow.com/q/52559429
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52582830
has title: Can't get full table from requests python
has comment: http://stackoverflow.com/comment/92112105
possible better answer: http://stackoverflow.com/a/52594459
tagged with: post
has answer: http://stackoverflow.com/a/57701680
has answer: http://stackoverflow.com/a/52594459
has body: I'm trying to get the whole table from this website: https://br.investing.com/commodities/aluminum-historical-data But when I send this code: with requests.Session() as s: r = s.post('https://br.investing.com/commodities/aluminum-historical-data', headers={"curr_id": "49768","smlID": "300586","header": "Alumínio Futuros Dados Históricos", 'User-Agent': 'Mozilla/5.0', 'st_date': '01/01/2017','end_date': '29/09/2018', 'interval_sec': 'Daily','sort_col': 'date','sort_ord': 'DESC','action': 'historical_data'}) bs2 = BeautifulSoup(r.text,'lxml') tb = bs2.find('table',{"id":"curr_table"}) It only returns a piece of the table, not the whole date I just filtered. I did see the post page below: Can anyone help me get the whole table I just filtered?
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92102380
accepted answer: http://stackoverflow.com/a/57701680
has comment: http://stackoverflow.com/comment/92101279
favorite count: 0
has comment: http://stackoverflow.com/comment/92100994
tagged with: beautifulsoup
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/92101111
upvote count: 2
answer count: 2
tagged with: web-scraping
tagged with: python-requests
has comment: http://stackoverflow.com/comment/92101055

http://stackoverflow.com/comment/92112412
has text: Have you tried modifying the code I’ve given? What steps have you taken to test it? I suspect the date time rollover is fine - but you always need to test with sufficient input data
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52578751
type: Comment

http://stackoverflow.com/a/52537301
has body: Final solution: def _create_mask_from_tpr(self, df: pd.DataFrame, tpr: Dict[str, Union[str, List[str]]]) -&gt; List[bool]: weekday = int(tpr['day']) - 1 # Offset. start_day, start_month, start_time = tpr['timerange'][0].split(" ") end_day, end_month, end_time = tpr['timerange'][1].split(" ") start_year, end_year = df.index.min().year, df.index.max().year selection_weekday = (df.index.weekday == weekday) start_time = datetime.datetime.strptime(start_time, '%H:%M').time() end_time = datetime.datetime.strptime(end_time, '%H:%M').time() selection_time = ((df.index.time &gt;= start_time) &amp; (df.index.time &lt;= end_time)) selection_date = None for year in range(start_year, end_year + 1): start_date = pd.Timestamp("{}-{}-{}".format(year, start_month, start_day)) end_date = pd.Timestamp("{}-{}-{}".format(year, end_month, end_day)) if selection_date: selection_date = selection_date | ((df.index &gt;= start_date) &amp; (df.index &lt;= end_date)) else: selection_date = ((df.index &gt;= start_date) &amp; (df.index &lt;= end_date)) return (selection_weekday &amp; selection_time &amp; selection_date)
score: 0
answers question: http://stackoverflow.com/q/52533864
type: Answer

http://stackoverflow.com/comment/92054800
type: Comment
has text: It'd be super helpful to show a very clear `input` and then your desired `output` of the result.
type: QuestionComment
comment on: http://stackoverflow.com/q/52558016
score: 1

http://stackoverflow.com/a/52488345
answers question: http://stackoverflow.com/q/52488285
score: 0
has comment: http://stackoverflow.com/comment/91917927
has body: Windows compatibility for certbot is a work in progress. You should consider installing and running on a Linux VM with the following commands: sudo apt-get update $ sudo apt-get install software-properties-common $ sudo add-apt-repository ppa:certbot/certbot $ sudo apt-get update $ sudo apt-get install certbot
type: Answer

http://stackoverflow.com/q/52553954
has answer: http://stackoverflow.com/a/52554125
tagged with: python
tagged with: python-decorators
has body: the task is to call a function 4 times using decorator. The solution is: def my_decorator (func): def wrapper(): func() func() func() func() return wrapper @my_decorator def printer_hp(): print('I am printer HP 4700 LaserJet') return 0 printer_hp() HOWEVER, if I move func to the wrapper args and put parentheses for the @my_decorator: def my_decorator (): def wrapper(func): func() func() func() func() return wrapper @my_decorator() def printer_hp(): print('I am printer HP 4700 LaserJet') return 0 the function is called automatically 4 times without calling it in the main program. Why is that?
accepted answer: http://stackoverflow.com/a/52554125
type: AnsweredQuestion
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/92046994
downvote count: 1
linked to: http://stackoverflow.com/q/739654
type: Question
has title: Undertanding decorators
answer count: 1
linked to: http://stackoverflow.com/q/5929107
favorite count: 0

http://stackoverflow.com/q/52548394
type: Question
has title: In python how to convert string to datetime with timezone
has comment: http://stackoverflow.com/comment/92036118
downvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/1101508
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52548849
has comment: http://stackoverflow.com/comment/92036434
favorite count: 0
has body: I am getting value error while converting string to datetime. Can anyone please help to resolve this issue. &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; date_str = "2018-07-13T17:12:02-0500" &gt;&gt;&gt; t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z") Traceback (most recent call last): File "&lt;pyshell#27&gt;", line 1, in &lt;module&gt; t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z") File "C:\Python27\lib\_strptime.py", line 324, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z' &gt;&gt;&gt; t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%Z") Traceback (most recent call last): File "&lt;pyshell#28&gt;", line 1, in &lt;module&gt; t = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%Z") File "C:\Python27\lib\_strptime.py", line 332, in _strptime (data_string, format)) ValueError: time data '2018-07-13T17:12:02-0500' does not match format '%Y- %m-%dT%H:%M:%S%Z' &gt;&gt;&gt; I am using python version 2.7.14
linked to: http://stackoverflow.com/q/1101508
type: UnansweredQuestion
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/20194496
score: 1
tagged with: python-datetime

http://stackoverflow.com/q/52434130
has comment: http://stackoverflow.com/comment/91815789
has answer: http://stackoverflow.com/a/52434204
answer count: 3
has comment: http://stackoverflow.com/comment/91832917
has answer: http://stackoverflow.com/a/52434762
tagged with: python
possible better answer: http://stackoverflow.com/a/52434204
tagged with: list
has answer: http://stackoverflow.com/a/52434241
accepted answer: http://stackoverflow.com/a/52434762
downvote count: 2
tagged with: amazon-dynamodb
has comment: http://stackoverflow.com/comment/91812101
upvote count: 1
has comment: http://stackoverflow.com/comment/91811900
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91811874
has body: I have a script that appends to a list from a text file. I then use ''.join(mylist) to convert to type str so I can query a DynamoDB table for the said str. This seems to work until I query the table. I notice I am getting empty responses. After printing out each str, I notice they are being returned vertically. How can I format the string properly so my calls to DynamoDB are successful? import boto3 from boto3.dynamodb.conditions import Key, Attr dynamo = boto3.resource('dynamodb') table = dynamo.Table('mytable') s3.Bucket('instances').download_file('MissingInstances.txt') with open('MissingInstances.txt', 'r') as f: for line in f: missing_instances = [] missing_instances.append(line) unscanned = ''.join(missing_instances) for i in unscanned: print(i) response = table.query(KeyConditionExpression=Key('EC2').eq(i)) items = response['Items'] print(items) Contents of MissingInstances.txt: i-xxxxxx i-yyyyyy i-zzzzzz etc etc Output of print(i): i - x x x x x i - y y y y y etc etc Output of print(items): [] [] [] etc etc Desired output: i-xxxxxx i-yyyyyy etc etc
score: -1
tagged with: boto3
type: Question
has comment: http://stackoverflow.com/comment/91811918
has title: ''.join(name) prints vertically and API call to DynamoDB fails when trying to write a str
linked to: http://stackoverflow.com/q/493386
tagged with: string
favorite count: 0

http://stackoverflow.com/comment/92035306
type: Comment
has text: This is close to what I had before, can you explain the count[total-2] = count[total-2] + 1 ? Thanks!
comment on: http://stackoverflow.com/a/52547819
score: 0
type: AnswerComment

http://stackoverflow.com/q/52532176
tagged with: while-loop
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/92003826
has comment: http://stackoverflow.com/comment/92003664
has answer: http://stackoverflow.com/a/53087797
has body: 7.0 and I am wanting to know what I've done wrong with this code. I want it to loop infinitely and say vcmine start but I've done I've tried using for while and tried spamming the code over and over I just want it to print this code into a game so that I don't have to be at my pc but I can only get it to work with it only saying it once please help I've something wrong and I don't know what from pynput.keyboard import Key, Controller import time keyboard = Controller () while True: for char in "vcmine start": keyboard.press(char) keyboard.release(char) time.sleep(0.03) break while True: keyboard.press(key.enter) keyboard.press(key.enter) break
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92003671
has title: Whats wrong with this code loop in python pynput loop indent wrong
type: UnansweredQuestion
upvote count: 0
favorite count: 0
score: -1

http://stackoverflow.com/q/52556542
score: -1
has body: I've installed recently odoo 11 in my computer. I was trying to access the payroll module to try the salaries feature but I'm not being able to find it. I've checked the show all features in accountant module but the part where I should put the contracts and where I could extract the pay slip is not showing up. How can I make it available? Thanks
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52559281
favorite count: 0
has title: Odoo 11 community payroll module
tagged with: python
tagged with: odoo-11
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92055428
downvote count: 1
type: Question
tagged with: odoo

http://stackoverflow.com/q/52511704
has comment: http://stackoverflow.com/comment/92266344
favorite count: 0
has comment: http://stackoverflow.com/comment/91967568
has comment: http://stackoverflow.com/comment/91965278
tagged with: sql-server
has comment: http://stackoverflow.com/comment/91967403
has comment: http://stackoverflow.com/comment/91979938
has body: I am using "django-pyodbc-azure" 3rd party library for making connection and django1.11 and python version 3.5.2 *** Error in `/home/ubuntu/GET-Services_mssql/env_mssql/bin/python': double free or corruption (!prev): 0x00007f7f08078a90 *** ======= Backtrace: ========= /lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f7f2a7a17e5] /lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7f7f2a7aa37a] /lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f7f2a7ae53c] /usr/lib/x86_64-linux-gnu/libodbc.so.2(SQLDriverConnectW+0x9a0)[0x7f7f24055100] /home/ubuntu/GET-Services_mssql/env_mssql/lib/python3.5/site-packages/pyodbc.cpython-35m-x86_64-linux-gnu.so(_Z14Connection_NewP7_objectbblbS0_R6Object+0x2c3)[0x7f7f242a52a3] /home/ubuntu/GET-Services_mssql/env_mssql/lib/python3.5/site-packages/pyodbc.cpython-35m-x86_64-linux-gnu.so(+0x111de)[0x7f7f242a21de] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyCFunction_Call+0x77)[0x4e9ba7] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalFrameEx+0x59f5)[0x53c6d5] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalFrameEx+0x4b04)[0x53b7e4] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalFrameEx+0x4b04)[0x53b7e4] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalFrameEx+0x4b04)[0x53b7e4] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python[0x540199] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalFrameEx+0x50b2)[0x53bd92] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalFrameEx+0x4b04)[0x53b7e4] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python[0x5434af] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyCFunction_Call+0x4f)[0x4e9b7f] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalFrameEx+0x614)[0x5372f4] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyEval_EvalCodeEx+0x13b)[0x540f9b] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python[0x4ebd23] /home/ubuntu/GET-Services_mssql/env_mssql/bin/python(PyObject_Call+0x47)[0x5c1797] /hom…
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/52669412
has title: Any Solution to SQLDriverConnect Error in Django Occurred Below using pyodbc
has comment: http://stackoverflow.com/comment/91979535
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91982899
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/91963678
score: 1
tagged with: ubuntu
type: Question
has comment: http://stackoverflow.com/comment/91978292
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91964058

http://stackoverflow.com/comment/92027052
comment on: http://stackoverflow.com/q/52543529
has text: Maybe you want/need to create a new sublist with each iteration of the outer loop - like this https://stackoverflow.com/a/52542948/2823755
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52559412
upvote count: 2
has answer: http://stackoverflow.com/a/52561946
has title: Search nested json / dict for multiple key values matching specified keys
answer count: 1
tagged with: nested
favorite count: 0
has comment: http://stackoverflow.com/comment/92058523
has comment: http://stackoverflow.com/comment/92059156
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/41777880
type: AnsweredQuestion
score: 2
has body: I have a Python object with multiple layers of dicts and lists that contain keys that I need to get the values from. I found an answer using recursive generators that will allow me to pull the value of one key, but not multiple keys. Here's the code: with open('data.json') as f: json_data = json.load(f) def find_key(obj, key): if isinstance(obj, dict): yield from iter_dict(obj, key, []) elif isinstance(obj, list): yield from iter_list(obj, key, []) def iter_dict(d, key, indices): for k, v in d.items(): if k == key: yield indices + [k], v if isinstance(v, dict): yield from iter_dict(v, key, indices + [k]) elif isinstance(v, list): yield from iter_list(v, key, indices + [k]) def iter_list(seq, key, indices): for k, v in enumerate(seq): if isinstance(v, dict): yield from iter_dict(v, key, indices + [k]) elif isinstance(v, list): yield from iter_list(v, key, indices + [k]) for c in find_key(json_data, 'customer_count'): print(c) Result: (['calendar', 'weeks', 0, 'days', 1, 'availabilities', 0, 'customer_count'], 14) (['calendar', 'weeks', 0, 'days', 2, 'availabilities', 0, 'customer_count'], 7) Another post has an example to extract multiple keys, but doesn't recurse through the entire object: [...] keys = ("customer_count", "utc_start_at", "non_resource_bookable_capacity") for k in keys: keypath, val = next(find_key(json_data, k)) print("{!r}: {!r}".format(k, val)) Result: 'customer_count': 14 'utc_start_at': '2018-09-29T16:45:00+0000' 'non_resource_bookable_capacity': 18 How do I iterate through the entire object and extract the three keys shown above? My desired result would look something like this: 'customer_count': 14 'utc_start_at': '2018-09-29T16:45:00+0000' 'non_resource_bookable_capacity': 18 'customer_count': 7 'utc_start_at': '2018-09-29T16:45:00+0000' 'non_resource_bookable_capacity': 25 sample json
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/52561946
linked to: http://stackoverflow.com/q/47037281
linked to: http://stackoverflow.com/q/45334930

http://stackoverflow.com/comment/91931760
type: QuestionComment
has text: sorry for bad example, just wanted to clarify task with n and k
comment on: http://stackoverflow.com/q/52495502
score: 0
type: Comment

http://stackoverflow.com/comment/117379753
has text: @Inkling it shouldn’t be that hard to retool the replacements based on how many elements there are in each filename that’s being edited. Note that the OP _never mentioned those additional constraints_. I’m sorry that you found that my answer doesn’t work for you but that’s the fault of the question not including an accurate description of the Ankiweb upload system.
comment on: http://stackoverflow.com/a/52681711
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91926566
type: QuestionComment
has text: `d = OrderedDict((k[0], k[1:]) for k in a)`.
score: 1
comment on: http://stackoverflow.com/q/52492913
type: Comment

http://stackoverflow.com/q/52551878
has comment: http://stackoverflow.com/comment/92042896
tagged with: ipython
upvote count: 18
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92061266
has body: Trying to open a jupyter notebook file (.ipynb file) with this command ipython notebook filename.ipynb then I am getting Below Error while using ipython.. Traceback (most recent call last): File "c:\python\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\python\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Python\Scripts\ipython.exe\__main__.py", line 5, in &lt;module&gt; File "c:\python\lib\site-packages\IPython\__init__.py", line 55, in &lt;module&gt; from .terminal.embed import embed File "c:\python\lib\site-packages\IPython\terminal\embed.py", line 16, in &lt;module&gt; from IPython.terminal.interactiveshell import TerminalInteractiveShell File "c:\python\lib\site-packages\IPython\terminal\interactiveshell.py", line 18, in &lt;module&gt; from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode ModuleNotFoundError: No module named 'prompt_toolkit'
tagged with: jupyter
has answer: http://stackoverflow.com/a/52554137
favorite count: 0
has title: Problems upgrading Ipython (prompt_toolkit incompatibilities)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92063645
tagged with: python
score: 18
has comment: http://stackoverflow.com/comment/92043075
has comment: http://stackoverflow.com/comment/92064483
has comment: http://stackoverflow.com/comment/92061569

http://stackoverflow.com/a/78410804
has body: If you are not absolutely required to use the complete text query you can use a table object to define the from clause and SQLAlchemy will quote the table name if required. There where clause (and order by etc.) can be left as text, although they must be placed within the appropriate method calls. import sqlalchemy as sa ... query = sa.select(sa.text('*')).select_from(sa.table(db_table)).where('idCars = :p2') with engine.connect() as conn: rows = conn.execute(query, {'p2': id_cars}) If you can afford the upfront cost of table reflection you can use a Table object instead, which will give you an exception at reflection time if there is no table with the provided name. ... cars = sa.Table(db_table, sa.MetaData(), autoload_with=engine) query = sa.select(cars).where(sa.text(idCars = :p2)) # or query = sa.select(cars).filter_by(**{ ... Once you have a Table instance you have access to the full power of the SQLAlchemy (Core) API, should you want to use it.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52494572
downvote count: 0
score: 1

http://stackoverflow.com/q/52485537
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91915233
has body: I am very new to learning Python (using v3) and trying to do two things which I suspect can be done with one program. The first part is as follows: Assume csv file 1 has 6 columns by thousands of rows but each group of ten rows needs to be placed into a new rows that will in effect have 60 columns. E.g. Input1.csv is : Id, name, text1, text2, text3, text4, unique code Id, name, text1, text2, text4, text4, unique code (some of the IDs are duplicates And the output1 needs to be: Unique Id, name, text1, text2, text3, text4, text5, Unique Id2, name, text1, text2, text3... (60 columns) and then it moves to row2... I am working with this code to start (but open to other ideas): import csv with open('Input1.csv','r', encoding='utf-8-sig', errors='ignore') as infile, open('Output1.csv', 'w' , encoding='utf-8-sig') as outfile: fieldnames = ['id', 'text1', 'text2', 'text3', 'text4', 'text5'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for i in range (0,5): for row in csv.DictReader(infile): for j in range (0,9): for column in csv.DictReader(infile): writer.writerow(column) I am trying to loop though the 6 columns and then through 10 rows to then output each row as 60 columns... Traceback shows: Traceback (most recent call last): File "C:/Users/marc/PycharmProjects/first/Convert1.py", line 12, in writer.writerow(column) File "C:\Users\marc\AppData\Local\Programs\Python\Python37-32\lib\csv.py", line 155, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "C:\Users\marc\AppData\Local\Programs\Python\Python37-32\lib\csv.py", line 151, in _dict_to_list + ", ".join([repr(x) for x in wrong_fields])) Part 2 will be adding the new csv to another csv inserting the columns as a group at a particular spot and possibly re-arranging the columns (I am doing part of the column re-arranging above with the fieldnames.
type: Question
has title: Transpose CSV rows and columns
has comment: http://stackoverflow.com/comment/91912710
score: 0
has comment: http://stackoverflow.com/comment/91914896
tagged with: python
answer count: 0

http://stackoverflow.com/comment/91873643
type: QuestionComment
has text: Thank you so much people, I'll try be more relevant the next time I post!!
comment on: http://stackoverflow.com/q/52465721
score: 0
type: Comment

http://stackoverflow.com/q/52493360
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/52493377
has body: In the pandas package of python I'd like to group by, so that I keep a specific order. The below code seems to do this, but is there a faster / simpler way? Or is it guaranteed, that the group by function of pandas keeps the order of records in the source dataframe? import pandas as pd sep = ' - ' df1 = pd.DataFrame([[1,"apple",1],[1,"banana",3],[1,"pear",2],[2,"lemon",3],[2,"orange",1],[2,"apple",2]]) df1.columns = ["id","product","seq"] df1 = df1.sort_values(by=["id","seq"]) pd.DataFrame(df1.groupby('id',as_index=False)['product'].apply(lambda x: sep.join(x)))
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has title: How to group by in pandas keeping a specific order?
has answer: http://stackoverflow.com/a/52493377
tagged with: python

http://stackoverflow.com/comment/91928668
comment on: http://stackoverflow.com/q/52493353
type: Comment
score: 0
has text: A dictionary check would go a long way (`aeiou khzftl` is currently allowed), although it would still let things like `This is a lazy test on` pass.
type: QuestionComment

http://stackoverflow.com/comment/92057487
comment on: http://stackoverflow.com/q/52559429
has text: but you have to open the image each time from the file
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92036383
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52548544
type: Comment
has text: I doesn't want that I need to need a seperate dataframe that has not replaced columns of df1

http://stackoverflow.com/q/52500014
answer count: 1
has answer: http://stackoverflow.com/a/52500168
type: UnansweredQuestion
has title: Time analysis of daily data w/ pandas
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
has body: I have a timeseries of observations with a resolution of one minute for several non continuous but complete days. The data is organized as a pivot table with days on the columns and times on the rows. 2006-01-21 2006-01-24 ... 2006-02-08 2006-03-22 00:00:00 5.80 4.14 ... 7.03 4.27 00:01:00 4.71 5.22 ... 7.04 5.66 00:02:00 4.82 5.57 ... 4.11 5.04 00:03:00 3.20 4.11 ... 7.38 4.79 00:04:00 2.67 4.08 ... 6.39 6.91 I have to perform statistics on observations happening at the same time in different days, also considering the effects of time aggregation (resampling). Mean StD 00:00:00 ... ... 00:01:00 ... ... 00:02:00 ... ... Mean StD 00:10:00 ... ... 00:20:00 ... ... 00:30:00 ... ... For now I am just keeping the dataframe as a pivot table, converting the index and columns to respectively a datetime.time and datetime.date object, but I have issues when: Trying to select columns beetween two dates Resampling the dataframe to a coarser time resolution (e.g. 10 mins) Can you suggest the most effective way to structure the dataframe for this kind of operation?
upvote count: 1

http://stackoverflow.com/comment/91957011
comment on: http://stackoverflow.com/q/52504941
score: 3
has text: If you're using Python3, you probably want message_from_bytes.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92055196
type: Comment
has text: thanks for the prompt response. I need to replace the null with value of list(key). here 92881926.0 and this value should get replaced, where ever null present in the list(this value will be same for the entire list. once or more times in the list)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52558163

http://stackoverflow.com/comment/92085987
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52574510
has text: still for sentence 'a' + 'a' + 'a' prints 4 times 'a' + 'a' + 'a'

http://stackoverflow.com/comment/91857078
type: QuestionComment
comment on: http://stackoverflow.com/q/52453471
score: 1
has text: I doesn't see any grey active background. Can you provide a screenshot? This will be more better.
type: Comment

http://stackoverflow.com/q/52514684
downvote count: 0
tagged with: web
score: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52514763
type: Question
has body: I made a change to my models.py and then I have entered this line to make migrations: django-admin makemigrations and got this error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have tried defining the environment variable by export DJANGO_SETTINGS_MODULE=mysite.settings but seems to have no effect.
has comment: http://stackoverflow.com/comment/91969297
has answer: http://stackoverflow.com/a/52514783
tagged with: django
tagged with: python
answer count: 3
upvote count: 1
accepted answer: http://stackoverflow.com/a/52514783
possible better answer: http://stackoverflow.com/a/52514820
has title: When I try to make migrations in django I get an error of undefined DJANGO_SETTINGS_MODULE
has answer: http://stackoverflow.com/a/52514820
type: AnsweredQuestion

http://stackoverflow.com/q/52524790
tagged with: python-3.x
type: Question
tagged with: multithreading
upvote count: 1
tagged with: python
tagged with: zeromq
has body: I am trying to create a ZMQ Subscriber that writes to a CSV every certain amount of time (The time doesn't matter as much) My problem im having is in my write class. When I'm run the c.acquire to acquire the lock it doesnt do anything and the loop just freezes The c.acquire in my ZMQ_Thread class is actually working so Im not sure what I'm doing wrong. Any pointers or tips would be amazing. Thanks in advance. import zmq import pandas as pd import time import threading c = threading.Condition() df = pd.DataFrame() s = 0 m = 0 h = 0 d = 0 def counter(): global h,s,m,d while True: s += 1 print("Second:{}".format(s)) if s &gt;=60: m +=1 s = 0 if m &gt;= 60: h += 1 m = 0 if h &gt;= 24: d += 1 h = 0 time.sleep(1) class write(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.name = name def run(self): global df while True: print('sleeping') time.sleep(12) c.acquire() print('acquired') print(df) with open("FILE", 'a') as f: df.to_csv(f, encoding = 'utf-8', index = False, header = False) c.release() c.notify() z = zmq_thread() z.run() class zmq_thread(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.name = name def run(self): global df print('DF Created') context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://localhost:#####") socket.setsockopt_string(zmq.SUBSCRIBE, 'TOPIC') print('socket connected') count = 0 while True: c.acquire() try: count +=1 if count == 10: print('ZMQ Break') c.notify() c.release() print('Lock released') return df message = socket.recv_string() message2 = socket.recv_string() if message == 'TOPIC': message2_split = message2.split(",") message4 = pd.Series(message2_split) df = df.append(message4, ignore_index=True) print('ZMQ Running') except KeyboardInterrupt: break counter = threading.Thread(target = counter) write_csv1 = write("Write_csv") zmq_loop = zmq_thread('Start_ZMQ') counter.start() write_csv1.start() zmq_loop.start()
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52526302
tagged with: pandas
answer count: 1
has title: Threading Condition Acquire lock is not actually acquiring the lock
score: 1
favorite count: 0

http://stackoverflow.com/comment/91955104
type: Comment
score: 0
has text: You already have the "Pythonic" way to do this with a list. The shorter syntax you suggest is available with `numpy` arrays.
type: QuestionComment
comment on: http://stackoverflow.com/q/52507303

http://stackoverflow.com/comment/91912946
type: Comment
comment on: http://stackoverflow.com/a/52455143
type: AnswerComment
has text: Yes, that's pretty much it. [`QProcess::execute`](http://doc.qt.io/qt-5/qprocess.html#execute) is a `static` member function and acts more or less like [`std::system`](https://en.cppreference.com/w/cpp/utility/program/system): it starts the specified program and waits for it to complete, so no information of any sort is available until it returns. `QProcess::start`, on the other hand, simply schedules the requested process for execution and any progress/output/state change is reported via the usual `Qt` signal/slot mechanism.
score: 0

http://stackoverflow.com/a/52495998
score: 1
answers question: http://stackoverflow.com/q/52495824
has body: To communicate in a thread-safe manner you can use Queue. The get() method blocks if the queue is empty, and waits until a new element is put(): from multiprocessing import Process, Queue def f(q): while True: element = q.get() print(element) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() q.put([42, None, 'hello']) p.join()
downvote count: 0
has comment: http://stackoverflow.com/comment/91932501
has comment: http://stackoverflow.com/comment/91932407
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91932822

http://stackoverflow.com/a/52563504
downvote count: 0
answers question: http://stackoverflow.com/q/52562882
type: Answer
score: 3
has body: Using set and dictionary comprehension L = [d1, d2] dups = set(d1.keys() &amp; d2.keys()) d = {k: [L[0][k], L[1][k]] if k in dups else i[k] for i in L for k in i} {'first': [1, 9], 'second': [4, 5], 'third': 8, 'fourth': 3}
upvote count: 3

http://stackoverflow.com/q/52477488
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91896078
type: Question
duplicate of: http://stackoverflow.com/q/52284187
downvote count: 0
favorite count: 0
has title: how to skip default parameter before *args in python
has body: I have written a function with different type of arguments named, default, arbitrary, keyword arguments. def my_func(x,y=4, *args, **kwargs): print(kwargs) print(args) When I call this function, my_func(2,3,4,5,6,7,8,a=40,b=90) the arguments taken are as follows.. x = 2, y = 3, args = [4, 5, 6, 7, 8] kwargs = {a:40, b:90} But what I want is, since y has default value, I want to skip it. the arguments should be taken as, x = 2, y = 4, args = [3, 4, 5, 6, 7, 8] kwargs = {a:40, b:90} Is there any possibility to do this? Thank you very much.

http://stackoverflow.com/comment/91877130
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52467633
has text: try and change the port to 8080 or other
type: AnswerComment

http://stackoverflow.com/comment/92040674
comment on: http://stackoverflow.com/q/52550898
type: Comment
type: QuestionComment
has text: Do not do parameter formatting yourself. Probably the `.query(..)` function has a way to "inject" parameters in an SQL-injection safe way.
score: 0

http://stackoverflow.com/comment/91813353
has text: For completeness, do `list(np.arange(n))`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52434904
type: Comment

http://stackoverflow.com/comment/91923110
comment on: http://stackoverflow.com/a/52491203
type: Comment
score: 0
has text: Just one more thing to ask, so X_train[0] and X_train[0,:] are computationally equivalent as they both have to perform `__getitem__` call only once?
type: AnswerComment

http://stackoverflow.com/comment/91961563
has text: you can use df["Very Interested"] = df["Very Interested"].astype(np.float64) to convert the dtypes. Make sure it is loaded as a float before you round off.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52498449
score: 0

http://stackoverflow.com/comment/92115886
has text: yeah I have done this in company details template '{% url 'accounting_double_entry:grouplist' pk=company_details.pk %}'
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52588536

http://stackoverflow.com/comment/135522296
has text: When you say "The GIL does not prevent these operations from running concurrently" does that mean the points you laid down, are run in concrurrent fashion and NOT parallel? In that case, how is this statement true "Python's threads are real threads"? because thread means parallel
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/74936772
type: Comment

http://stackoverflow.com/comment/92020742
has text: @benvc I'm not sure - I know that we use sqlite for unittesting and mysql from devstacks to production.
score: 1
comment on: http://stackoverflow.com/q/52536673
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52465368
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52465317
has body: multiprocessing module basically spawns up multiple instances of python interpreter, so there is no worry of GIL. multiprocessing uses the same API used by threading module if you have used it previously. You seem to be confused between multiprocessing, threading (you referring as multithreading) and X-core processor. No matter what, when you start Python (CPython implementation) it will only use one core of your processor. Threading is distributing the load between the different component of the script. Suppose you have to interact with an external API, your script has to wait for communication to finish until it proceeds next. You have are making multiple similar calls, it will take linear time. Whereas if you use threading, you can do those calls parallelly. See also: PyPy implementation of Python
score: 2

http://stackoverflow.com/a/52558819
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52558756
upvote count: 2
answers question: http://stackoverflow.com/q/52558756
has body: It's normally discouraged as it detracts from readability, from PEP8: Compound statements (multiple statements on the same line) are generally discouraged. Yes: if foo == 'blah': do_blah_thing() do_one() do_two() do_three() Rather not: if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three() While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines! Rather not: if foo == 'blah': do_blah_thing() for x in lst: total += x while t &lt; 10: t = delay() Definitely not: if foo == 'blah': do_blah_thing() else: do_non_blah_thing() try: something() finally: cleanup() do_one(); do_two(); do_three(long, argument, list, like, this) if foo == 'blah': one(); two(); three()

http://stackoverflow.com/comment/91943248
type: Comment
has text: [Obligatory XKCD 327 Link](https://xkcd.com/327/)
comment on: http://stackoverflow.com/a/52500894
score: 3
type: AnswerComment

http://stackoverflow.com/q/52502508
tagged with: python
tagged with: dictionary
score: 2
has comment: http://stackoverflow.com/comment/91945673
type: Question
has title: Counting issue wth Python dictionaries
has answer: http://stackoverflow.com/a/52502601
downvote count: 0
has comment: http://stackoverflow.com/comment/91945758
tagged with: counting
has answer: http://stackoverflow.com/a/52504433
has answer: http://stackoverflow.com/a/52502588
has answer: http://stackoverflow.com/a/52502561
favorite count: 0
has body: So I'm trying to count unique letter in this function. If their are unique letters return True if there isn't return False. In the word 'Programming' there are two r's and two m's and two g's. Its return True where the actual answer is False? Is my logic wrong here? def unique_chars_in_string(input_string): unique_chars = {} if input_string == "": return True for letter in input_string: if letter in unique_chars: unique_chars[letter]+=1 else: unique_chars[letter]=1 for k in unique_chars: if unique_chars[k] &gt; 1: return False else: return True print(unique_chars_in_string('Programming'))
upvote count: 2
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52502602

http://stackoverflow.com/comment/91885769
type: QuestionComment
comment on: http://stackoverflow.com/q/52471901
type: Comment
has text: https://circleci.com/docs/2.0/configuration-reference/#run
score: 0

http://stackoverflow.com/q/52488122
type: Question
has answer: http://stackoverflow.com/a/52488198
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91917563
favorite count: 0
has comment: http://stackoverflow.com/comment/91917762
has comment: http://stackoverflow.com/comment/91917527
accepted answer: http://stackoverflow.com/a/52488198
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91924111
has comment: http://stackoverflow.com/comment/91917542
has comment: http://stackoverflow.com/comment/91917721
has body: I'm writing to a file and I call flush() after I'm done. Is it safe to force quit the program say pulling the power plug without calling close() on the file? Is calling flush() sufficient that the file won't become corrupt.
has comment: http://stackoverflow.com/comment/91917579
type: AnsweredQuestion
score: 1
tagged with: file
has title: Do you need to call close if you already flush to make content survives unexpected reboot?
has comment: http://stackoverflow.com/comment/91917578

http://stackoverflow.com/comment/91907190
has text: You're welcome, an answer acceptance would be appreciated ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/52482684
score: 0
type: Comment

http://stackoverflow.com/a/52486345
type: Answer
answers question: http://stackoverflow.com/q/52486243
has comment: http://stackoverflow.com/comment/91918891
has body: Looks like the company name is in your index, to get this out as a column you can try running: df = df.reset_index() If this isn't the case try creating a small reproducible example Edit: From your comment I'm not 100% clear but I think you have blank strings in your company name column for each of your rows which are just a person? In which case first replace the blank strings with missings, and then forward fill. df = df.replace(r'^\s+$', np.nan, regex=True) df["Company name"] = df["Company name"].fillna(method="ffill")
score: 0

http://stackoverflow.com/comment/91991761
type: AnswerComment
comment on: http://stackoverflow.com/a/52525795
has text: Wow `pray hands emoji`, thank you so much. The `thousands=','` is exactly what I needed...
type: Comment
score: 1

http://stackoverflow.com/comment/92629142
has text: Manually marking previous runs as success should do the trick.
type: AnswerComment
comment on: http://stackoverflow.com/a/52834976
type: Comment
score: 1

http://stackoverflow.com/comment/91849456
has text: @Mahesh first flatten the string column to single columns , then we just `unstack`
type: AnswerComment
comment on: http://stackoverflow.com/a/52453074
type: Comment
score: 1

http://stackoverflow.com/comment/91935286
type: Comment
comment on: http://stackoverflow.com/q/52497333
type: QuestionComment
has text: @Willem Ah, *that's* what you specifically responded to. That wasn't very clear. And sure, this isn't terribly efficient by any means; I'd expect it to be for practicing recursive functions.
score: 1

http://stackoverflow.com/a/52441652
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91831667
has comment: http://stackoverflow.com/comment/137243602
has body: In order to store data for the lifetime of a single request, how should that be done? The g object is designed for this. The documentation states: Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. Although the documentation refers to g as "global", that's not really accurate - "thread-global" would be better. In order to store data for the lifetime of an application, how should that be done? I think the answer to this question answers this as well (or better) than I could: Preserving global state in a flask application Flask could be used in a multi-process environment. Is it correct to assume that in such a mode of operation there will be multiple application-wide objects? (This would imply that all of these app or g objects then need to be initialized individually for the lifetime of each worker process.) In a multi-process environment, each request is handled as a seperate thread, and g is intialized and destroyed on a per-request basis, so there will be as many concurrent g object as threads - though each thread can only see it's own. In most scenarios I suspect there should only ever one app object, an instance of the Flask() class created by the programmer, i.e. app = Flask(__name__) or similar. Blueprints and Application Dispatching are two way of having "multiple" application objects, in as far as you have multiple applications running concurrently.
accepted answer of: http://stackoverflow.com/q/52441176
has comment: http://stackoverflow.com/comment/91834438
score: 12
answers question: http://stackoverflow.com/q/52441176
type: AcceptedAnswer
upvote count: 12

http://stackoverflow.com/comment/92067663
type: Comment
type: QuestionComment
has text: So an insecure system will be continued, it that really a defensible choice? I guess the security is not important. Interesting because so many times it is claimed that the security flaws will be resolved in the next revision and here we are at that revision, I guess this is proof that is not be true in practice.
comment on: http://stackoverflow.com/q/52548500
score: 0

http://stackoverflow.com/comment/92118328
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52441280
has text: Please add some notes on why this question was downvoted so that I can improve. I felt it was a valid question to ask on SO and I did my research. Thanks!

http://stackoverflow.com/a/54808668
type: Answer
has comment: http://stackoverflow.com/comment/96442097
answers question: http://stackoverflow.com/q/52566503
has body: I came across this while attempting to compile Python 3.7.2 for Ubuntu 18.04 LTS Make sure you have all the dependencies required to build Python's built-in modules. Run make 2&gt;&amp;1 | tee make.txt after configure and look for warnings of modules that failed to build. If modules fail to build, Python won't fail the install it simply won't build those modules leading to the kind of error you're seeing. After installing the dependencies, make sure to run configure again.
score: 0

http://stackoverflow.com/comment/92098746
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52574294
score: 0
has text: @PaulPanzer In my case, A, B, etc. are arrays. When I try your solution, I get `TypeError: list object is not an iterator`.

http://stackoverflow.com/q/52525876
score: 1
has comment: http://stackoverflow.com/comment/92054485
has comment: http://stackoverflow.com/comment/92061451
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/92016434
has comment: http://stackoverflow.com/comment/92060203
has body: When I use Scipy minimize in the example below, it finds a non minimal solution - can someone please help me modify this to find the minimum? I have four constraints: 1) guesses of guess array must sum to one, 2) guesses must be > 0, and 3) any guess from the initial guess array that is over the threshold must be set equal to the threshold and held constant. Edit: 4th constraint - no guess can be greater than the threshold. I didn't use constraints for the last 3 constraints I have. For constraint 2, I used a bounds. For constraint 3, I did that in the performMinimize method before calling scipy's minimize method. from scipy.optimize import minimize import numpy as np from numpy import array def objective(initialGuesses, threshold): overThreshold = initialGuesses[np.where((threshold &lt; initialGuesses[:]))] underThreshold = initialGuesses[np.where((threshold &gt;= initialGuesses[:]))] overThreshold[:] = threshold sumUnderThreshold = np.sum(underThreshold) oppositeSumOverTreshold = 1 - np.sum(overThreshold) transformedGuess = underThreshold / sumUnderThreshold * oppositeSumOverTreshold thresholdedResults = np.concatenate((overThreshold, transformedGuess)) squaredError = np.square(thresholdedResults - initialGuesses) / initialGuesses return np.sum(squaredError) def performMinimizeSo(initialGuesses, threshold): overThreshold = initialGuesses[np.where((threshold &lt; initialGuesses[:]))] overThreshold[:] = threshold underThreshold = initialGuesses[np.where((threshold &gt;= initialGuesses[:]))] # Says one minus the sum of all variables minus the sum of weights over the threshold must be zero cons = ({'type': 'eq', 'fun': lambda x: 1 - sum(x) - sum(overThreshold)}) minimum = minimize(objective, underThreshold, args=(threshold), method='SLSQP', constraints=cons, bounds=[(0, None) for i in range(len(underThreshold))], ) allGuesses = np.append(overThreshold, minimum.x) return allGuesses def testCaseForSo(): initialGuesses = array([ [0.1], [0.05], [0.05], [0.05], [0.05], [0.…
tagged with: optimization
has comment: http://stackoverflow.com/comment/92059811
upvote count: 1
has comment: http://stackoverflow.com/comment/92060758
has comment: http://stackoverflow.com/comment/92059878
favorite count: 0
has comment: http://stackoverflow.com/comment/92019496
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92054087
has comment: http://stackoverflow.com/comment/92019103
tagged with: python
has title: SciPy optimize minimize finds non minimal answer
has comment: http://stackoverflow.com/comment/91995027
tagged with: mathematical-optimization
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/91866411
type: QuestionComment
type: Comment
has text: @CharlesDuffy ...? ... the whole code is literally in the question
comment on: http://stackoverflow.com/q/52462030
score: 0

http://stackoverflow.com/comment/91970654
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52515495
has text: Can't we do that common for all 4, without depending on the text of the tag?
score: 0

http://stackoverflow.com/comment/92026634
comment on: http://stackoverflow.com/q/52487390
type: Comment
score: 0
type: QuestionComment
has text: Done. If you do find a way to skip tests, I'm curious to see what you find.

http://stackoverflow.com/comment/91885928
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52464870
has text: Thank you Bazingaa. I use `ax4.grid(False)` and it is much better. But what if I still want the gridline for twin axis (ax2), how can I achieve this? either `ax4.grid(zorder =0)` or `h2 = ax4.bar(x_pos, data.new_acid_2.values, label=my_label,zorder=1)` does not work to make gridline of twin axis behind bar and legend.

http://stackoverflow.com/comment/91845262
has text: @nosklo: I know, it is to replace the OP's for loop. But unless I define global price inside the function, I am getting this UnboundLocalError.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52450904

http://stackoverflow.com/a/54104886
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52556735
has body: Following your instructions, below value worked for me in my "locale.json" config : "locale":"en-US" // Changes will not take effect until VS Code has been restarted.

http://stackoverflow.com/comment/92058091
score: 0
type: AnswerComment
type: Comment
has text: your solution to split a file is a bad idea for files large enough to not fit into memory all at once. he said he has a large file.
comment on: http://stackoverflow.com/a/52546064

http://stackoverflow.com/a/52547862
has comment: http://stackoverflow.com/comment/92035160
answers question: http://stackoverflow.com/q/52547620
score: 3
has body: MATLAB 2D indexing extracts a rectangular submatrix that its rows and columns are reordered based on the provided index vectors. But if you have a list of rows and columns and want to extract the corresponding elements you should convert 2D index to linear index and for it you can use sub2ind: M = zeros(5); indices = 1:5; idx = sub2ind([5,5],indices(1:end-1), indices(1:end-1)+1); M(idx) = 1 Alternatively you can directly use linear indexing: M = zeros(5); M(5+1:5+1:end) = 1 How does linear indexing work? In MATLAB data are stored in column major format: 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 When you use the range 6:6:end it means that you want starting form element 6 with the step size 6 to extract elements so you want the elements [6 12 18 24]. This indexing scheme can be extended to ND arrays and non square matrices.
upvote count: 3
has comment: http://stackoverflow.com/comment/92035417
accepted answer of: http://stackoverflow.com/q/52547620
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92035079
has comment: http://stackoverflow.com/comment/92035042
type: Answer
has comment: http://stackoverflow.com/comment/92035410

http://stackoverflow.com/comment/92002355
type: Comment
score: 0
has text: If you check my paragraph about `\1` and `sub()`, you can see how the word is being kept. That should help you figure out how to remove the word inside the parens as well.
comment on: http://stackoverflow.com/a/52530120
type: AnswerComment

http://stackoverflow.com/a/52496439
downvote count: 0
has body: You can use the following function that sticks to the basics, as your professor apparently prefers: def split(s): output = [] delimiters = {' ', '\t', '\n'} delimiter_found = False for c in s: if c in delimiters: delimiter_found = True elif output: if delimiter_found: output.append('') delimiter_found = False output[-1] += c else: output.append(c) return output so that: print(split('duff_beer 4.00')) print(split('a b c\n')) print(split('\tx y \n z ')) would output: ['duff_beer', '4.00'] ['a', 'b', 'c'] ['x', 'y', 'z']
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52495936
type: Answer

http://stackoverflow.com/q/52460717
has body: I have a data set with some 300 columns, each of them depth-dependent. The simplified version of the Pandas DataFrame would look something like this: import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy_optimize import curve_fit df1 = pd.DataFrame({'depth': [1.65, 2.15, 2.65, 3.15, 3.65, 4.15, 4.65, 5.15, 5.65, 6.15, 6.65, 7.15, 7.65, 8.15, 8.65], '400.0': [13.909261, 7.758734, 3.513627, 2.095409, 1.628918, 0.782643, 0.278548, 0.160153, -0.155895, -0.152373, -0.147820, -0.023997, 0.010729, 0.006050, 0.002356], '401.0': [14.581624, 8.173803, 3.757856, 2.223524, 1.695623, 0.818065, 0.300235, 0.173674, -0.145402, -0.144456, -0.142969, -0.022471, 0.010802, 0.006181, 0.002641], '402.0': [15.253988, 8.588872, 4.002085, 2.351638, 1.762327, 0.853486, 0.321922, 0.187195, -0.134910, -0.136539, -0.138118, -0.020945, 0.010875, 0.006313, 0.002927], '403.0': [15.633908, 8.833914, 4.146499, 2.431543, 1.798185, 0.874350, 0.333470, 0.192128, -0.130119, -0.134795, -0.136049, -0.019307, 0.012037, 0.006674, 0.003002], '404.0': [15.991816, 9.066159, 4.283401, 2.507818, 1.831721, 0.894119, 0.344256, 0.196415, -0.125758, -0.133516 , -0.134189, -0.017659, -0.013281,0.007053, 0.003061], '405.0': [16.349725, 9.298403, 4.420303, 2.584094, 1.865257, 0.913887, 0.355041, 0.200702, -0.121396, -0.132237, -0.132330, -0.016012, 0.014525, 0.007433, 0.003120] }) What I need to do is to estimate the K in the equation below. Basically each column corresponds to a I(z) profile. The I(0) has to be calculated, for which I used the curve_fit, as a reference I'm using this helpful post: https://stackoverflow.com/a/15369787/7541421 x = df1.depth # Column values as a function of depth y = df1['400.0'] plt.plot(x, y, 'ro',label="Original Data") def func(def func(x, I0, k): # a = I0, b = k return I0 * np.exp(-k*x) popt, pcov = curve_fit(func, x, y) print ("E0 = %s , k = %s" % (popt[0], popt[1])) plt.plot(x, func(x, *popt), label="Fitted Curve") Could this be done for each column sepa…
has answer: http://stackoverflow.com/a/52460802
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: regression
tagged with: scipy
accepted answer: http://stackoverflow.com/a/52460802
type: Question
score: 3
has title: Curve fitting for each column in Pandas + extrapolate values
linked to: http://stackoverflow.com/q/3433486
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52437663
answers question: http://stackoverflow.com/q/52436084
has body: Using dict Ex: text_string = 'I came, I saw, I conquered!' word_list=['I','saw','Britain'] text_string = text_string.lower() print(dict((i, text_string.count(i)) for i in map(str.lower, word_list))) Output: {'i': 3, 'britain': 0, 'saw': 1}
score: 0
type: Answer

one-hot-encoding
tags question: http://stackoverflow.com/q/52456357
tags question: http://stackoverflow.com/q/52430798
tags question: http://stackoverflow.com/q/52475578
type: Tag
tag name: one-hot-encoding

http://stackoverflow.com/a/52507689
upvote count: 3
has body: You can use dict.__getitem__ or its syntactic sugar []: res = sorted(AccountValues, key=lambda x: (x['portfolio_ref'], -x['percent'])) Remember that dictionaries are not indexable by integers. Historically (pre-3.6), they are not even ordered. Even in Python 3.7, you cannot directly extract the nth key or value. Result: print(res) [{'portfolio_ref': 1, 'tag': 'NetLiq', 'value': '70976.05', 'currency': 'USD', 'percent': 100.0}, {'portfolio_ref': 1, 'tag': 'FullInit', 'value': '20642.95', 'currency': 'USD', 'percent': 0.0}, {'portfolio_ref': 1, 'tag': 'FullMaint', 'value': '21350.54', 'currency': 'USD', 'percent': 0.0}]
score: 3
answers question: http://stackoverflow.com/q/52507652
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52507652
downvote count: 0
type: Answer

http://stackoverflow.com/q/52493365
score: 3
answer count: 1
has title: Indices that KFold split method return for a DataFrame is it iloc or loc?
favorite count: 0
tagged with: python
tagged with: sklearn-pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52493578
upvote count: 3
has body: When we use _KFold.split(X) where X is a DataFrame, the indices that gets generated to split data into training and test set, is it iloc (Purely integer-location based indexing for selection by position) or is it loc (loc of group of rows and columns by label(s))?
type: Question
downvote count: 0
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52493578
tagged with: pandas

http://stackoverflow.com/comment/92027256
score: 0
type: Comment
has text: Yes, and that is the mystery here. The code doesn&#39;t thrown an error, yet when I check in JADE, the column isn't updated.
type: AnswerComment
comment on: http://stackoverflow.com/a/52543634

http://stackoverflow.com/comment/101949614
has text: But in your answer, you've written: "Port 29092 would be for access external to the docker network"
type: Comment
comment on: http://stackoverflow.com/a/52440056
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91891155
score: 0
type: Comment
type: QuestionComment
has text: I only have Python 3.7 installed
comment on: http://stackoverflow.com/q/52445406

http://stackoverflow.com/comment/91848219
has text: Why are you using `sudo`? I suggest you do `pip install` instead.
type: Comment
comment on: http://stackoverflow.com/q/52452344
type: QuestionComment
score: 0

http://stackoverflow.com/a/52586038
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/92107052
upvote count: 3
has comment: http://stackoverflow.com/comment/92107247
accepted answer of: http://stackoverflow.com/q/52584099
answers question: http://stackoverflow.com/q/52584099
type: AcceptedAnswer
downvote count: 0
has body: You are trying to access doctor_id.first_name. But the name of the relationship is doctor. If you are converting the result of the query to a list of dicts, then you should serialize the appointment.doctor relationship also, so that the dict looks like { id: 12, doctor: { id: 34 } } Then you can access it like this &lt;td&gt;{{ a.doctor.first_name }}&lt;/td&gt; But if you are just planning to use it in jinja template, then what is the need to serialize the objects? Instead you can just pass the result of the query.all() to the template. Jinja can directly access the python objects and show the data. So instead of result =appointments_schema.dump(all_appmts), try doing this all_appmts = db.session.query(Appointment) .filter_by(patient_id=id) .join(Doctor) return render_template('patient.html', all_appointments=all_aptmts.all()) And then keep the jinja template as the same {% for a in all_appointments %} &lt;td&gt;{{ a.doctor.first_name }}&lt;/td&gt; {% endfor %} It will work

http://stackoverflow.com/q/52433640
has comment: http://stackoverflow.com/comment/91811185
answer count: 1
linked to: http://stackoverflow.com/q/45663070
has title: Pandas Dataframe Display missing gridlines (Jupyter Notebook)
tagged with: dataframe
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52433808
tagged with: display
type: Question
tagged with: pandas
tagged with: python
has body: For some reason, whenever I create a dataframe in pandas from reading in data from a file, I don't have gridlines: I have checked my settings for pd.options for all display attributes and everything was set to the default. Can anyone help me change the formatting of my dataframe? This format happens even when I open new python notebooks within jupyter notebook.
linked to: http://stackoverflow.com/q/49888173
upvote count: 1

http://stackoverflow.com/q/52528475
tagged with: pip
tagged with: git
type: Question
has comment: http://stackoverflow.com/comment/91996470
has title: Pip install from Private Repo
tagged with: github
has comment: http://stackoverflow.com/comment/91996579
score: 0
has comment: http://stackoverflow.com/comment/91996506
tagged with: python
has body: I am trying to pip install from a private repo. I can clone from my repo and push and pull and that works fine so I think my public and private keys are fine I have read as much as I could but can't seem to get around the error. Using a Mac, Here is what I am trying. (venv) Mac:Projects$ pip install git+ssh://git@github.com/private_repo/git_stuff.git#egg=git_stuff Error: Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; IOError: [Errno 2] No such file or directory: '/private/var/folders/3d/s4d37gtgd1dfgfg18tmfd_nvsdfr1111gn/x/pip-install-abcdfs/git-stuff/setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3d/s4d37gtgd1dfgfg18tmfd_nvsdfr1111gn/x/pip-install-7RccWF/git-stuff/ setup.py file on project setuptools.setup( name="git_stuff", version="0.0.1", author="Example Author", author_email="test.com", description="A small example package", url="https://github.com/private_repo/git_stuff.git", packages=setuptools.find_packages(), ) Things I have tried: Updating setup tools. version setuptools 40.4.3 Updating pip . version 18.0 Python version 2.7.10
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/76452576
has comment: http://stackoverflow.com/comment/134811519
type: Answer
answers question: http://stackoverflow.com/q/52452724
has body: The above probably answered your query. I asked ChatGPT to do something similar. Move all selected objects to 0,0,0, export each file as .rs - in-case it is helpful here it is: CODE: // Get the selected objects string $selectedObjects[] = ls -selection; // Loop through each selected object for ($object in $selectedObjects) { // Get the object name string $objectName = match "[^|]+$" $object; // Move the object to the origin using setAttr setAttr ($object + ".translate") 0 0 0; // Construct the export path string $exportPath = "C:/YourPath/" + $objectName + ".rs"; // Create a temporary group and parent the object under it string $tempGroup = `group -em -n ($objectName + "_tempGroup")`; parent $object $tempGroup; // Export the temporary group as a Redshift proxy file rsProxy -fp $exportPath -sl $tempGroup; // Unparent the object from the temporary group parent -w $object; // Delete the temporary group delete $tempGroup; print("Exported " + $object + " as " + $exportPath + "\n"); }
score: 0

http://stackoverflow.com/q/52522884
tagged with: python
score: -2
answer count: 1
has body: I need all the lines which contains the text '.mp4'. The Html file has no tag! My code: import urllib.request import demjson url = ('https://myurl') content = urllib.request.urlopen(url).read()
tagged with: web-scraping
has title: Extracting variables from Javascript inside HTML
upvote count: 0
has answer: http://stackoverflow.com/a/52523377
type: AnsweredQuestion
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52523377
type: Question
downvote count: 2

http://stackoverflow.com/comment/92000060
type: QuestionComment
has text: Sorry Mohit, I didn't understand your comment. I dont see any files in migrations. I get this error when I run "python manage.py makemigrations"
comment on: http://stackoverflow.com/q/52530330
score: 0
type: Comment

http://stackoverflow.com/comment/91946900
type: AnswerComment
type: Comment
has text: Thank you very much for your informations. I only need this server to use some API for some application. And i have only one HTML page to send some POST request to the server. You still think that i have to setup other way or could be ok for my purpose?
comment on: http://stackoverflow.com/a/52503068
score: 0

http://stackoverflow.com/q/52449800
tagged with: django-models
type: Question
upvote count: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91842659
favorite count: 0
has answer: http://stackoverflow.com/a/52449965
has body: Is it possible to use the symmetrical property from models.ManyToManyField so that I can create a transitive dependency between the records? For example, in my code I have: class User(models.Model): website = models.ForeignKey('myapp.Website') related_users = models.ManyToManyField('self', related_name='users', symmetrical=True) When I do: user_a.related_users.add(user_b) user_a.related_users.all() # returns the user B user_b.related_users.all() # returns the user A Everything is working as expected here, the relationship is symmetrical. But when I do: user_b.related_users.add(user_c) user_b.related_users.all() # returns user A and user C user_c.related_users.all() # returns user B I want user C to return user A and user B automatically, because user C is user B, which is user A, therefore user C is user A too. Is it possible to achieve that or do I have to manually add the association between user A and user C?
has title: Using Django ManyToMany symmetrical property to build transitive dependency
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91842899
tagged with: manytomanyfield
tagged with: many-to-many
score: 1

http://stackoverflow.com/a/52458719
has body: If cube == -1, then abs(cube + 1) == 0, and range(abs(cube + 1)) is empty. So, no iteration happens (because there's nothing to iterate over), and the name guess is never created. Also, range is not a function, it's a class.
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52458678

http://stackoverflow.com/comment/92104169
comment on: http://stackoverflow.com/q/52584589
has text: do you hope to get a performance boost with the help of `multithreading`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52469543
has body: I have this dictionary (key,list) index={'chair':['one','two','two','two'],'table':['two','three','three']} and i want this #1. number of times each value occurs in each key. ordered descending indexCalc={'chair':{'two':3,'one':1}, 'table':{'three':2,'two':1}} #2. value for maximum amount for each key indexMax={'chair':3,'table':2} #3. we divide each value in #1 by value in #2 indexCalcMax={'chair':{'two':3/3,'one':1/3}, 'table':{'three':2/2,'two':1/2}} I think I should use lambda expressions, but can't come up with any idea how i can do that. Any help?
score: 4
has title: Counting distinct dictionary values
tagged with: python
has comment: http://stackoverflow.com/comment/91881034
answer count: 4
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52469630
has comment: http://stackoverflow.com/comment/91881042
upvote count: 4
tagged with: dictionary
has answer: http://stackoverflow.com/a/52469887
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52469630
tagged with: list
has answer: http://stackoverflow.com/a/52469603
downvote count: 0
possible better answer: http://stackoverflow.com/a/52469603
type: Question
has comment: http://stackoverflow.com/comment/91881069
has answer: http://stackoverflow.com/a/52469922
has comment: http://stackoverflow.com/comment/91881048

http://stackoverflow.com/comment/91919187
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52489013
has text: Welcome to SO. It would be helpful if you can share what have you tried so far and where have you stuck? Your current question is too broad to answer.
type: Comment

http://stackoverflow.com/a/52595047
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52584097
answers question: http://stackoverflow.com/q/52584097
type: Answer
has body: Your posting to the wrong link! If you do not know it, just leave the action empty in the html insted of action="." !

http://stackoverflow.com/q/52435678
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Can't Get Dictionary For Loop to Pull Strings From the Correct Columns
type: Question
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/52436088
has comment: http://stackoverflow.com/comment/91814759
has answer: http://stackoverflow.com/a/52436088
has answer: http://stackoverflow.com/a/52435745
answer count: 2
downvote count: 0
has body: I am trying to create a dictionary from two columns in an Excel file. My code is as follows: import openpyxl from openpyxl import load_workbook wb = load_workbook('country_data.xlsx') sheet = wb["List of countries"] for i in range(1, 198): list1 = list(sheet.cell(row=i, column=1).value) list2 = list(sheet.cell(row=i, column=3).value) dictionary = dict(zip(list1,list2)) print(dictionary) I fixed my original error (forgot I didn't need to start my columns from zero) but now when I print my dictionary or lists, it seems like they each pulled in random values. I'm trying to pull in values from column 1 and column 3 of my excel file. My columns look like this: Col1 Col3 ger Germany eng England fra France spa Spain etc etc Yet, when I go to print my dictionary, it seems to have pulled random letters from unknown columns in my excel file and is only printing this: {'z': 'a', 'w': 'f', 'e': 'r'} How can I fix this error? I am trying to make column1 the key for my dictionary and column 3 my value.
favorite count: 0
has comment: http://stackoverflow.com/comment/91814832
accepted answer: http://stackoverflow.com/a/52435745

http://stackoverflow.com/comment/91967356
score: 0
type: AnswerComment
type: Comment
has text: Why the 'rb' mode? If we're talking about a regular old text file `open` doesn't need an explicit mode since the default 'r' works fine oO
comment on: http://stackoverflow.com/a/52513552

http://stackoverflow.com/q/52578522
type: AnsweredQuestion
tagged with: network-programming
score: 1
type: Question
answer count: 2
tagged with: udp
has title: Converting string to bytes prints weird-looking hex-code in console
has body: Introduction my problem: I am trying to write a C++ program that receives data over UDP using WinSock2. For that, I have a prewritten Python script that sends 10-byte packets to a specified port, where the C++ program then receives them. I have gotten the data transfer to work, however I am confused about the data that is being sent. My problem: I am running the Python script from cmd, which prints the sent text on console. I have also added a line into the script, which converts the string to bytes to verify, what exactly is being sent. The first line is the one I added, fairly simple: logger.debug("Sending packet len %s, data %s", sizeof(packet), bytes(packet)) logger.debug("Sending packet len %s, data %s", sizeof(packet), packet) And this is the output in my terminal (from 3 different packets sent): What confuses me, is I would expect the hex code to contain only hexadecimal symbols, but instead there are some quite seemingly random symbols/letters there as well, even though the actual printed text looks just fine. Can someone explain to me, where do these symbols come from, as I am not sure how am I supposed to interpret this information on the receiving end in my C++ code.
has answer: http://stackoverflow.com/a/52578596
accepted answer: http://stackoverflow.com/a/52578596
possible better answer: http://stackoverflow.com/a/52578574
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52578574
favorite count: 0
tagged with: c++
downvote count: 0

http://stackoverflow.com/q/52445338
tagged with: python
tagged with: c++
accepted answer: http://stackoverflow.com/a/52630711
has title: Compiling Tensor flow example custom op for GPU
has body: Following the online example provided by Tensorflow I am having trouble using the custom op they define under GPU kernels. The instructions to build the example list three required files: header file // kernel_example.h #ifndef KERNEL_EXAMPLE_H_ #define KERNEL_EXAMPLE_H_ template &lt;typename Device, typename T&gt; struct ExampleFunctor { void operator()(const Device&amp; d, int size, const T* in, T* out); }; #if GOOGLE_CUDA // Partially specialize functor for GpuDevice. template &lt;typename Eigen::GpuDevice, typename T&gt; struct ExampleFunctor { void operator()(const Eigen::GpuDevice&amp; d, int size, const T* in, T* out); }; #endif #endif //KERNEL_EXAMPLE_H_ [1] commented out ((1) Here I have commented out KERNEL_EXAMPLE_H_ on the last line, as it causes a compile error.) .cc file // kernel_example.cc #include "kernel_example.h" &lt;--------[2] replaced example.h #include "tensorflow/core/framework/op_kernel.h" using namespace tensorflow; using CPUDevice = Eigen::ThreadPoolDevice; using GPUDevice = Eigen::GpuDevice; // CPU specialization of actual computation. template &lt;typename T&gt; struct ExampleFunctor&lt;CPUDevice, T&gt; { void operator()(const CPUDevice&amp; d, int size, const T* in, T* out) { for (int i = 0; i &lt; size; ++i) { out[i] = 2 * in[i]; } } }; // OpKernel definition. // template parameter &lt;T&gt; is the datatype of the tensors. template &lt;typename Device, typename T&gt; class ExampleOp : public OpKernel { public: explicit ExampleOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { // Grab the input tensor const Tensor&amp; input_tensor = context-&gt;input(0); // Create an output tensor Tensor* output_tensor = NULL; OP_REQUIRES_OK(context, context-&gt;allocate_output(0, input_tensor.shape(), &amp;output_tensor)); // Do the computation. OP_REQUIRES(context, input_tensor.NumElements() &lt;= tensorflow::kint32max, errors::InvalidArgument("Too many elements in tensor")); ExampleFunctor&lt;…
upvote count: 1
answer count: 1
tagged with: tensorflow
tagged with: bazel
has answer: http://stackoverflow.com/a/52630711
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/52570288
type: Answer
has comment: http://stackoverflow.com/comment/92077412
has comment: http://stackoverflow.com/comment/92078009
score: 0
has body: At a first glance , it seems that connect.py has got more code than you have pasted in your question. Anyways, assuming connect.py does not require any input parameters to run, simply use subprocess's check_output method to get the stdout message and store it in a variable for further use. from subprocess import check_output out = check_output(["ssh", "1.1.1.1", "\"python Connect.py\""])
answers question: http://stackoverflow.com/q/52570005

console
tags question: http://stackoverflow.com/q/52480104
type: Tag
tags question: http://stackoverflow.com/q/52567900
tag name: console
tags question: http://stackoverflow.com/q/52433464

http://stackoverflow.com/a/52447759
answers question: http://stackoverflow.com/q/52447356
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91847317
type: Answer
has comment: http://stackoverflow.com/comment/91930561
score: 3
downvote count: 0
has body: You can put a simple pure python version of this together like: def get_path(data, path, default=None): try: for item in path: data = data[item] return data except (KeyError, TypeError, IndexError): return default nice_data = {'a': [None, {'q': {'e': 'Hello!'}}]} bad_data = {'a': 6} path = ['a', 1, 'q', 'e'] print('Good', get_path(nice_data, path)) # Hello! print('Bad', get_path(bad_data, path)) # None Not super fancy, but it works. If you want to do something in one less line, with a bit more power, we can use something like ObjectPath (https://pypi.org/project/objectpath/): from objectpath import Tree def get_object_path(data, path, default=None): try: return Tree(data).execute(path) except (KeyError, TypeError, IndexError): return default path = '$.a[1].q.e' print('Good', get_object_path(nice_data, path)) print('Bad', get_object_path(bad_data, path)) We still have to put our own error handling on, and it's going to be much slower, but it can support all sorts of fancy queries (from the docs): In weather readings find cities where temperature is higher than 25°C and the sky is clear. $..*[@..temp &gt; 25 and @.clouds.all is 0].name
accepted answer of: http://stackoverflow.com/q/52447356
upvote count: 3

http://stackoverflow.com/q/52511123
favorite count: 0
has answer: http://stackoverflow.com/a/52511313
has body: new_list=["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"] all_possible=[] #print of all possible combinations y=0 z=0 def writer(): for z in range(0, 26): all_possible.append(new_list[0] + "" + new_list[y] + "" + new_list[z]) z = 0 def reader(): for y in range(0, 26): writer() reader() print(all_possible) all_possible=[] for y in range(0, 26): for z in range(0, 26): all_possible.append(new_list[0] + "" + new_list[y] + "" +new_list[z]) z = 0 print(all_possible) So I created this code to print a list that prints all the combinations of the alphabet with 3 characters and I also want to do that with a function but for some reason when I put the same thing in a function it doesn't print the same way for some reason. Can you help?
upvote count: 2
type: UnansweredQuestion
has title: Why doesn't this print the same list
tagged with: python
has answer: http://stackoverflow.com/a/52511271
type: Question
has answer: http://stackoverflow.com/a/52511348
tagged with: function
tagged with: arrays
has comment: http://stackoverflow.com/comment/91962333
answer count: 3
score: 2
downvote count: 0

http://stackoverflow.com/q/52484199
has answer: http://stackoverflow.com/a/52484350
has title: Series' object has no attribute 'decode in pandas
type: Question
accepted answer: http://stackoverflow.com/a/52484350
has body: I am trying to decode utf-8 encoded text in python. The data is loaded to a pandas data frame and then I decode. This produces an error: AttributeError: 'Series' object has no attribute 'decode'. How can I properly decode the text that is in pandas column? &gt;&gt; preparedData.head(5).to_dict( ) {'id': {0: 1042616899408945154, 1: 1042592536769044487, 2: 1042587702040903680, 3: 1042587263643930626, 4: 1042586780292276230}, 'date': {0: '2018-09-20', 1: '2018-09-20', 2: '2018-09-20', 3: '2018-09-20', 4: '2018-09-20'}, 'time': {0: '03:30:14', 1: '01:53:25', 2: '01:34:13', 3: '01:32:28', 4: '01:30:33'}, 'text': {0: "b'\\xf0\\x9f\\x8c\\xb9 are red, violets are blue, if you want to buy us \\xf0\\x9f\\x92\\x90, here is a CLUE \\xf0\\x9f\\x98\\x89 Our #flowerpowered eye &amp;amp; cheek palette is AL\\xe2\\x80\\xa6 '", 1: "b'\\xf0\\x9f\\x8e\\xb5Is it too late now to say sorry\\xf0\\x9f\\x8e\\xb5 #tartetalk #memes'", 2: "b'@JillianJChase Oh no! Please email your order # to social@tarte.com &amp;amp; we can help \\xf0\\x9f\\x92\\x95'", 3: 'b"@Danikins__ It\'s best applied with our buffer brush! \\xf0\\x9f\\x92\\x9c\\xc2\\xa0"', 4: "b'@AdelaineMorin DEAD \\xf0\\x9f\\xa4\\xa3\\xf0\\x9f\\xa4\\xa3\\xf0\\x9f\\xa4\\xa3'"}, 'hasMedia': {0: 0, 1: 1, 2: 0, 3: 0, 4: 0}, 'hasHashtag': {0: 1, 1: 1, 2: 0, 3: 0, 4: 0}, 'followers_count': {0: 801745, 1: 801745, 2: 801745, 3: 801745, 4: 801745}, 'retweet_count': {0: 17, 1: 94, 2: 0, 3: 0, 4: 0}, 'favourite_count': {0: 181, 1: 408, 2: 0, 3: 0, 4: 14}} My data looks like the above. I want to decode the 'text' column. ExampleText = b'\xf0\x9f\x8c\xb9 are red, violets are blue, if you want to buy us \xf0\x9f\x92\x90, here is a CLUE \xf0\x9f\x98\x89 Our #flowerpowered eye &amp; cheek palette is AL\xe2\x80\xa6' I could decode the text above as ExampleText = ExampleText.decode('utf8') However, when I try to decode text from a pandas dataframe column, I get the error. I tried like this, preparedData['text'] = preparedData['text'].decode('utf8') Then …
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/52520342
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52520755
has title: Using Python search for a string in each file in a folder and subfolders
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: python-os
linked to: http://stackoverflow.com/q/7012921
has comment: http://stackoverflow.com/comment/91980316
has body: I have written some code for all files in a folder but I want to check for the string even in sub folders. Suggest me for sub folders from os import listdir path='D:\\PyScripts' keywords=['version','navigate'] for file in listdir('D:\\PyScripts'): with open('D:\\PyScripts\\'+ file,'r') as f: data=f.read() data=data.lower() valid_keys=list(map(counters,keywords)) if valid_keys: ****Some logic*****
duplicate of: http://stackoverflow.com/q/7012921
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52520755
favorite count: 0
has comment: http://stackoverflow.com/comment/91980350

http://stackoverflow.com/comment/92060160
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52560205
has text: So there's nothing to be done on my end to successfully scrape off of it? Definitely a bummer if so.

http://stackoverflow.com/comment/92057066
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52558547
has text: I can run my app with `python -m xxx.xxx`, why is that? In "main package" are you referring to the top 'xxx' folder? this one is only the project (and repository) root, it's not a package.
score: 0

http://stackoverflow.com/q/52478042
has answer: http://stackoverflow.com/a/52478183
answer count: 3
tagged with: pandas
tagged with: delimiter
has body: In one DataFrame some columns are in the DataFrame. I want to column value to split by "/" using index. Below are the list of columns where i want to split the data. Eg:- split_columns = ['Fuel', 'Air Pollution Score', 'City MPG', 'Hwy MPG', 'Cmb MPG', 'Greenhouse Gas Score'] If in Fuel contain data then the output should be like "ethanol/gas". Here is my code- split_columns = ['Fuel', 'Air Pollution Score', 'City MPG', 'Hwy MPG', 'Cmb MPG', 'Greenhouse Gas Score'] for c in split_columns: df1[c] = df1[c].apply(lambda x: x.split("/")[0]) df2[c] = df2[c].apply(lambda x: x.split("/")[1]) When i execute above code then i found an error "Index out of range".
favorite count: 0
has answer: http://stackoverflow.com/a/56483813
has title: How do I split by "/" delimiters using index in python?
upvote count: 2
accepted answer: http://stackoverflow.com/a/52478214
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: indexoutofboundsexception
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52478214
possible better answer: http://stackoverflow.com/a/52478183

http://stackoverflow.com/a/52575801
score: 2
has body: You can do all the grouping in pandas. The idea behind this solution: Create a new column subset that has the subset dictionary you want. Group dataframe by col1 into a new data frame. Here the subset is connected to each item from col1. Extract the series subset. Loop through this series and collect the data for your json in a list. Convert that list to json with Python native tools. import pandas as pd import json df = pd.read_csv('test_old.csv', sep=',', dtype={ "col1" : str, "col2" : str, "col3" : str }) # print(df) - compare with example df['subset'] = df.apply(lambda x: {'col2': x.col2, 'col3': x.col3 }, axis=1) s = df.groupby('col1').agg(lambda x: list(x))['subset'] results = [] for col1, subset in s.iteritems(): results.append({'col1': col1, 'subset': subset}) with open('ExpectedJsonFile.json', 'w') as outfile: outfile.write(json.dumps(results, indent=4)) UPDATE: Since there's a problem with the example, insert a print(df) line after the pd.read_csv and compare. The imported data frame should show as: col1 col2 state col3 val2 val3 val4 val5 0 95110 2015-05-01 CA 50 30.0 5.0 3.0 3 1 95110 2015-06-01 CA 67 31.0 5.0 3.0 4 2 95110 2015-07-01 CA 97 32.0 5.0 3.0 6 The final result shows like this [ { "col1": "95110", "subset": [ { "col2": "2015-05-01", "col3": "50" }, { "col2": "2015-06-01", "col3": "67" }, { "col2": "2015-07-01", "col3": "97" } ] } ] Tested with Python 3.5.6 32bit, Pandas 0.23.4, Windows7
has comment: http://stackoverflow.com/comment/92091458
has comment: http://stackoverflow.com/comment/92091760
has comment: http://stackoverflow.com/comment/92100614
has comment: http://stackoverflow.com/comment/92091670
downvote count: 0
answers question: http://stackoverflow.com/q/52574728
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/92110132

http://stackoverflow.com/comment/91905292
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52481029
has text: Thanks for the proposition, so indeed I should split my script into 2 files. When I'll do it, I'll try this method which looks very clean and compact. Where does the `__all__` attribute be define? top of the file? in a system class?

http://stackoverflow.com/comment/92048645
score: 2
comment on: http://stackoverflow.com/q/52555027
has text: the traceback shows you that `re.search("a\\\\x3d(-?\d+);", tkk_expr)` is of type `None`. so you should investigate if gets assigned the expected value
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91948006
has text: Please provide some example data and expected output. Also: You don't use `S` in your lambda function. Can you explain what you're trying to accomplish there?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52503728
score: 0

http://stackoverflow.com/q/52465868
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91883983
has comment: http://stackoverflow.com/comment/91884126
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a simple use case. I want to read a text file into a pandas file and iterate through the unique id s to plot a x-y graph. Worked for me fine at many other projects but now i get the TypeError: 'int' object is not iterable. At first I got TypeError: 'numpy.float64' object is not iterablethat is why I changed the type of id to int (see code). But that does not work either. I do not see why. Any ideas? f = open(file,"r+") with open(file,"r+") as f1: data10 = f1.read() TESTDATA = StringIO(data11) df = pd.read_table(TESTDATA, sep=" ") df.columns = ["x", "y", "id"] #Astype because i got the error TypeError: 'numpy.float64' object is not iterable df.id = df.id.astype(int) #get unique values of column id list1=df['id'].tolist() list1=list(set(list1)) fig, ax = plt.subplots() for i ,g in list1: x = df[df.id==i]['x'] y = df[df.id==i]['y'] g.plot(x='x',y='x', marker='o', ax=ax, title="Evaluation")
has title: TypeError: 'int' object is not iterable when iterating through pandas column
has comment: http://stackoverflow.com/comment/91884017
has comment: http://stackoverflow.com/comment/91876064
has answer: http://stackoverflow.com/a/52474511
has comment: http://stackoverflow.com/comment/91876114
tagged with: loops
downvote count: 1
type: Question
score: -1
tagged with: iteration
tagged with: typeerror
tagged with: pandas

http://stackoverflow.com/q/52519887
has answer: http://stackoverflow.com/a/52520394
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/52519968
has body: How to assign this to a variable instead of printing it? print(*df.values.flatten(), sep=',')
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52520394
tagged with: python
possible better answer: http://stackoverflow.com/a/52519959
has answer: http://stackoverflow.com/a/52519959
upvote count: 2
answer count: 3
has title: Flattening dataframe with separator to variable
tagged with: dataframe
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91828701
type: Comment
type: QuestionComment
has text: [Try redirecting with a status code 307](https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect) on POST requests.
comment on: http://stackoverflow.com/q/52439234
score: 0

http://stackoverflow.com/q/52445427
has title: process created in UWSGI does not finish in threaded mode
has body: I am using CentOS 7 with uwsgi(2.0.17.1), uwsgi-plugin-python2 (2.0.17) and Flask (1.0.2). I have a flask application that runs many shell commands. Some of them hangs indefinitely. I am sharing one of them as an example below, it is easy to reproduce. I am using uwsgi in threaded mode. #!/usr/bin/python from flask import Flask import subprocess app = Flask(__name__) @app.route("/test/") def test(): print 'state 1' p = subprocess.Popen(['ntpdate', '-u', '0.pool.ntp.org'],close_fds=True) print 'state 2' out, err = p.communicate() print 'state 3' print 'output: {}'.format(out) print 'error: {}'.format(err) return 'finish' uwsgi command: # uwsgi --ini uwsgi.conf --http-socket :8001 uwsgi conf file: [uwsgi] #virtual env's base folder base = /root/plaground home = /usr/ #cmd options bin = /usr/sbin/uwsgi #python module to import module = app:app pythonpath = /root/playground catch-exceptions = true plugins-dir = /usr/lib64/uwsgi/ plugins = python need-app = true master = true threads = 10 After starting uwsgi, first request to /test route completes succesfully, Second one stucking on command line execution and holds response forever. The first call output: state 1 state 2 21 Sep 16:02:48 ntpdate[19943]: adjust time server 78.46.53.11 offset -0.000224 sec state 3 output: None error: None The second call output: state 1 state 2 ps aux output after second call: # ps aux | grep ntpdate root 20820 0.0 0.0 23632 1516 pts/3 S&lt;+ 16:03 0:00 ntpdate -u 0.pool.ntp.org strace -p 20820 output: # strace -p 20820 strace: Process 20820 attached restart_syscall(&lt;... resuming interrupted call ...&gt;) = 0 poll([{fd=3, events=POLLIN}, {fd=4, events=POLLIN}], 2, 60000) = 0 (Timeout) poll([{fd=3, events=POLLIN}, {fd=4, events=POLLIN}], 2, 60000) = 0 (Timeout) process fd list: # ls -l /proc/20820/fd total 0 lr-x------ 1 root root 64 Eyl 21 16:05 0 -&gt; /dev/null lrwx------ 1 root root 64 Eyl 21 16:05 1 -&gt; /dev/pts/3 lrwx------ 1 root root 64 Eyl 21 16:03 2 -&gt; /dev/pts/3 lrwx-----…
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
answer count: 0
score: 1
upvote count: 1
tagged with: uwsgi
tagged with: multiprocessing
type: Question
tagged with: flask
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92083580
score: 0
has text: Welcome to Stack Overflow! Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) by showing _why_ this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made.
type: AnswerComment
comment on: http://stackoverflow.com/a/52572419
type: Comment

http://stackoverflow.com/q/52542007
possible better answer: http://stackoverflow.com/a/52542180
has answer: http://stackoverflow.com/a/52542180
type: Question
answer count: 2
has title: Trouble merging .xlsx files with pandas
score: 0
has answer: http://stackoverflow.com/a/52542382
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: pandas
tagged with: python
has body: I am operating with python 2.7 and I wrote a script that should take the name of two .xlsx files, use pandas to convert them in two dataframe and then concatenate them. The two files under consideration have the same rows and different columns. Basically, I have these two Excel files: I would like to keep the same rows and just unite the columns. The code is the following: import pandas as pd file1 = 'file1.xlsx' file2 = 'file2.xlsx' sheet10 = pd.read_excel(file1, sheet_name = 0) sheet20 = pd.read_excel(file2, sheet_name = 0) conc1 = pd.concat([sheet10, sheet20], sort = False) output = pd.ExcelWriter('output.xlsx') conc1.to_excel(output, 'Sheet 1') output.save() Instead of doing what I expected (given the examples I read online), the output becomes something like this: Does anyone know I could I improve my script? Thank you very much.
accepted answer: http://stackoverflow.com/a/52542382
type: AnsweredQuestion

http://stackoverflow.com/a/52454382
has comment: http://stackoverflow.com/comment/91851444
has comment: http://stackoverflow.com/comment/91868033
type: Answer
score: 3
has body: I use the tf.slice wrong in this case, it's should be like this: a = tf.slice(a, [0, 0, 0, 0], [50, 100, 1, 512]) b = tf.squeeze(a) You can find out why by look at the tf.slice documentation
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52453285

http://stackoverflow.com/comment/91874055
type: Comment
type: QuestionComment
has text: That's just because 70 is very big surely? Try something smaller and experiment till you get the right size.
comment on: http://stackoverflow.com/q/52460939
score: 0

http://stackoverflow.com/comment/91891679
has text: What do you mean you don't have information about the exception? You've stored the exception in the variable `e`, and you can do whatever you want with it.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52475075

http://stackoverflow.com/q/52474747
has comment: http://stackoverflow.com/comment/91901810
linked to: http://stackoverflow.com/q/50806075
answer count: 0
upvote count: 3
type: Question
score: 3
has comment: http://stackoverflow.com/comment/95299438
tagged with: anaconda
linked to: http://stackoverflow.com/q/53488063
has body: C:\Users\user&gt;python C:\Users\franc\Anaconda3\etc\keras\load_config.py 1&gt;temp.txt C:\Users\user&gt;set /p KERAS_BACKEND= 0&lt;temp.txt C:\Users\user&gt;del temp.txt C:\Users\user&gt;python -c "import keras" 1&gt;nul 2&gt;&amp;1 C:\Users\user&gt;if errorlevel 1 ( ver 1&gt;nul set "KERAS_BACKEND=theano" python -c "import keras" 1&gt;nul 2&gt;&amp;1 ) when I open anaconda, after have uptadated some packages I have the above output in Anaconda prompt, could it be a problem?
has comment: http://stackoverflow.com/comment/91891568
downvote count: 0
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Why I have this output when I open anaconda?
has comment: http://stackoverflow.com/comment/91892120

http://stackoverflow.com/a/52542382
accepted answer of: http://stackoverflow.com/q/52542007
type: Answer
answers question: http://stackoverflow.com/q/52542007
score: 0
has body: The best answer here really depends on the exact shape of your data. Based on the example you have provided it looks like the data is indexed identically between the two dataframes with differing column headers that you want preserved. If this is the case this would be the best solution: import pandas as pd file1 = 'file1.xlsx' file2 = 'file2.xlsx' sheet10 = pd.read_excel(file1, sheet_name = 0) sheet20 = pd.read_excel(file2, sheet_name = 0) conc1 = sheet10.merge(sheet20, how="left", left_index=True, right_index=True) output = pd.ExcelWriter('output.xlsx') conc1.to_excel(output, sheet_name='Sheet 1', ignore_index=True) output.save() Since there is a direct match between the number of rows in the two initial dataframes it doesn't really matter if a left, right, outer, or inner join is used. In this example I used a left join. If the rows in the two data frames do not perfectly line up though, the join method selected can have a huge impact on your output. I recommend looking at pandas documentation on merge/join/concatenate before you go any further.
type: AcceptedAnswer

http://stackoverflow.com/comment/91805687
type: AnswerComment
has text: I got this error when I did that: AttributeError: 'int' object has no attribute 'lower'
comment on: http://stackoverflow.com/a/52430840
score: 1
type: Comment

http://stackoverflow.com/a/52466983
answers question: http://stackoverflow.com/q/52466901
has comment: http://stackoverflow.com/comment/91875654
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91884714
has body: The problem is here: if y not in row_array[0][r] The in operator checks if the left-hand side is in the sequence or iterable on the right hand side. But type(row_array[0][r]) will return int, which is not an iterable.
has comment: http://stackoverflow.com/comment/91880850
downvote count: 0
score: 1

http://stackoverflow.com/a/52496141
accepted answer of: http://stackoverflow.com/q/52493079
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52493079
type: AcceptedAnswer
has body: The data in your Excel file has header information in the first row, so setting header=None is the reason why there are string values in your data instead of putting it as column names. If you delete the header kwarg xlsxfile = pd.ExcelFile("C:\\Users\\AchourAh\\Desktop\\PL14_IPC_03_09_2018_SP_Level.xlsx") data = xlsxfile.parse('Sheet1', index_col = None) everything should work and you should get a dataframe like this: data 0 PP SP000045856 COP COR SP000045856 PAUS 0 1 201723 0 2000 1 2 201724 12560 40060 2 3 201725 -17760 15040 3 4 201726 -5840 16960 4 5 201727 10600 4480 5 6 201728 0 14700 6 7 201729 4760 46820 However, you could do the same thing even a little shorter by directly using the read_excel-function of pandas: data = pd.read_excel('C:\\Users\\AchourAh\\Desktop\\PL14_IPC_03_09_2018_SP_Level.xlsx', 'Sheet1') Your scatter-plot can then be done e.g. like data.plot('SP000045856 COP COR', 'SP000045856 PAUS', 'scatter') or perhaps better readable but identical: data.plot.scatter('SP000045856 COP COR', 'SP000045856 PAUS') And the linear regression could be done like slope, intercept, r_value, p_value, std_err = stats.linregress(data['SP000045856 COP COR'], data['SP000045856 PAUS'])
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92066963
comment on: http://stackoverflow.com/a/52564043
type: AnswerComment
score: 0
type: Comment
has text: I use numpy. img[msk] = value results in [[7,4][7,7]], it's a fast way to change any entry to a value depending on a boolean array of equal dimension

http://stackoverflow.com/comment/91841541
type: QuestionComment
comment on: http://stackoverflow.com/q/52448660
type: Comment
score: 1
has text: Thank you Willem, you have helped me several times. I you post in an answer I'll mark it is correct so you get the deserved points.

http://stackoverflow.com/comment/91920414
comment on: http://stackoverflow.com/a/52475284
type: Comment
has text: Yes, exactly. Thank you for this.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52579782
has title: Two random values from list needs to match with images
has comment: http://stackoverflow.com/comment/92095809
linked to: http://stackoverflow.com/q/33460872
has answer: http://stackoverflow.com/a/52677723
answer count: 1
has body: Background: I have a small feature in my Tkinter application which randomizes two random values from list and prints them to GUI. But I'm struggling to get right image (team logo) with random value. Goal: is to random team name (from list of 28 teams) and GUI should show team logo also. Pressing button "RANDOM" and it generates Team1 &amp; Team2 and both should have logos next of the texts. I have done research about: I had time with this answer, but I could not figure it out. This dice game kinda does it but I need two values instead of one and my list is full of strings. Example: https://stackoverflow.com/a/27913052/5132305 import random import tkinter as tk from PIL import ImageTk, Image # Use a class that hold all Team data class Team(): def __init__(self, name, img_filename): self.name = name self.img_filename = img_filename @property def image(self): # TODO: Open image file and return .PhotoImage object team_logo = Image.open("%s.jpg" % (self.img_filename)) render = ImageTk.PhotoImage(team_logo) self.img_filename.image = render return self.img_filename #This is how the class prints def __str__(self): return "Name: {} Image:{}".format(self.name, self.img_filename) class MainWindow(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) root.geometry("700x450") text_1 = tk.Label(text="VS", fg="red", anchor="center") text_1.place(relx=.5, rely=.5, anchor="center") text_2 = tk.Label(text="RANDOM GAME", fg="green", anchor="n") text_2.pack(side="top") # Button for randomize self.parent = parent self.frame = tk.Frame(self.parent) self.randomButton = tk.Button(self.frame, text = 'RANDOM', command=self.genRanTeam) self.randomButton.pack(side="bottom") self.frame.pack(side="bottom") self.home_name = tk.StringVar() self.visitor_name = tk.StringVar() if 0: # TODO: Implement Team.image # Images, I should somehow use this with home/visitor label? # Yes, look at TODO in def genRanTeam(... load = Image.open("%s.jpg" % (self.hom…
downvote count: 0
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/52677723
upvote count: 2
has comment: http://stackoverflow.com/comment/92117381
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/92282486
tagged with: loops
linked to: http://stackoverflow.com/q/28798496
type: Question
linked to: http://stackoverflow.com/q/27902190
linked to: http://stackoverflow.com/q/5130301

http://stackoverflow.com/comment/91862624
has text: @Mark_Anderson I still think there is no reason to delete the entries, as you can just set them to a different value. And I am confused still. Are we saying that we want `False` for `foo` and `True` for `bar`, or are we just setting them all to `True`? That is how I interpreted the original problem.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52460201

http://stackoverflow.com/comment/91951929
comment on: http://stackoverflow.com/q/52505489
has text: @Martijn It is a tuple created by tensorflow `sess.run` and eventually [reduce_mean](https://www.tensorflow.org/api_docs/python/tf/reduce_mean) function and it doesn't raise and exception upon division. That's why I'm asking this second question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52488804
type: Answer
answers question: http://stackoverflow.com/q/52488587
has body: I tested your function, and as others said, if you want to print something, make sure to print it before the return. Because what return does is simply return the output and get out of the function call (what I mean is: nothing below return will run). You could do something like the following to test your code: def test(a): if a: return True return False a = None if test(a): print("True, input is not null") else: print("False, input is null!") returns: False, input is null!
score: 0

http://stackoverflow.com/comment/91813218
score: 0
has text: I've been putting off messing with functions, for way too long. This may be a good way to wrap my head around them. thank you sir
type: Comment
comment on: http://stackoverflow.com/a/52433459
type: AnswerComment

http://stackoverflow.com/q/52475010
has answer: http://stackoverflow.com/a/52476076
accepted answer: http://stackoverflow.com/a/52476076
score: 0
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has body: My dataframe: df: order quantity A 1 B 1 C 2 D 3 E 3 F 4 My goal is to create a group from this Dataframe based on the Quantity value. My desired result. df: group order quantity 1 A 1 B 1 C 2 2 D 3 E 1 3 E 2 F 2 4 F 2 So here my desired result is based on quantity. Max value of quantity is 4. In group1, group2 &amp;group3 the total values (A+B+C=4)(i.e keeping the max vale of quantity as 4). In group4 we can see that no values to add so the group is formed by the left over(here it is 2). In group2&amp;group3 you can see the value of E and F are divided. So in future I can select the group by its name or number. Note: My actual order(column["order"]) looks like this "PMC11-AA1L1PAVWJJ+Z1" its a string. Is this possible in python. If so kindly suggest me the method. I could practice and learn.
type: Question
has title: How to create a group by spliting the dataframe using python
possible better answer: http://stackoverflow.com/a/52480204
has answer: http://stackoverflow.com/a/52480204
answer count: 2

http://stackoverflow.com/comment/92020408
has text: The problem is in some of the sheets. First column ‘Date’ is not read while others have it as the first column.
comment on: http://stackoverflow.com/q/52529948
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91915301
comment on: http://stackoverflow.com/a/52485614
score: 0
has text: Path does work now @hellpanderr. However! Heh, it writes the entirety of the path all the way from the home folder. I fixed that now by adding another line to your split code. images_df['id'] = images_df['id'].str.split('S2/').str[1]. But back to the problem of it only merging 44 in total. I can't post pictures in the comment section. But it seems that the merge only allows for 44 matches. The original data consist of both numbers and letters unfortunately. They are real world data taken over 20 years. So some of the samples are named like "Midt-1", some 92-849 and some 3230494.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92067938
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52564975
has text: `p.apply_async(..).get()` is a blocking op.

http://stackoverflow.com/comment/91996470
score: 1
has text: Do you have a `setup.py` in your project?
comment on: http://stackoverflow.com/q/52528475
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91923516
type: Comment
comment on: http://stackoverflow.com/a/52491496
has text: What if there are negative numbers in `a`?
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91869246
type: Comment
comment on: http://stackoverflow.com/a/52447641
has text: One last doubt, Suppose I deployed `index.html` at SiteA with domain `SiteA.com` (which is the main domain for my web app) and now I want to use the python code, should I deploy `flaskajax.py` at SiteB with domain `SiteB.com` so that when I press a button at SiteA, It can send a request to SiteB? Is this how they do it? Is there a way to test it in the above way? maybe through AWS EC2 instance or Heroku?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92014362
score: 1
has text: Different use cases requires different solutions. That's why `aiohttp.ClientSession` supports both async context manager and async close methods.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52537388

http://stackoverflow.com/comment/91963053
has text: BeautifulSoup library has lot's of functionality for extracting data from HTML, you might find using that library easier than this approach
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52511522
score: 0

http://stackoverflow.com/q/52564275
has answer: http://stackoverflow.com/a/52564394
tagged with: python-3.x
tagged with: tuples
tagged with: python
tagged with: pygame
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92066982
type: Question
has title: Complex operations with Python (pygame.math.Vector2)
accepted answer: http://stackoverflow.com/a/52564394
score: 0
has body: I'm learning Python and came across a complex expression that derives from pygame.Vector2: import pygame x = pygame.math.Vector2 (1,2) b = x * 5 - (1, 2) print (x) print (b) Result: [1,2] [4,8] In the above case, the same x * 5 operation is performed both for the 1 and 2 values of Vector2, resulting in (5, 10) respectively; and then both results are subtracted from the tuple (1, 2), resulting in [4,8] However if I do assign a simple tuple to x: x = (1, 2), instead of Vector2, I get the error: TypeError: unsupported operand type (s) for -: 'tuple' and 'tuple' My question is: At what times in Python I can perform these complex operations?
answer count: 1

http://stackoverflow.com/comment/92089703
type: Comment
score: 0
has text: Looking at [this Django issue](https://code.djangoproject.com/ticket/24709), it doesn't seem like this case is supported :(
comment on: http://stackoverflow.com/q/52575447
type: QuestionComment

http://stackoverflow.com/comment/91868210
comment on: http://stackoverflow.com/q/52463007
type: Comment
has text: What is your question?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92084744
comment on: http://stackoverflow.com/q/52564735
score: 0
type: QuestionComment
type: Comment
has text: I am using python 3.6.5 on mac.

http://stackoverflow.com/q/52561265
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django. DRY. Same context in get request
answer count: 0
score: 1
has body: I am trying to make a voting app in django. Here the view that display a vote. class DetailVoteView(View): """ Displays the vote If vote is active allows to vote If vote is completed shows winners and top 5 """ vote = None vote_for_chars = None page_title = '' def dispatch(self, request, *args, **kwargs): self.vote = Vote.objects.get(id=kwargs['id']) self.vote_for_chars = self.vote.voteforcharacter_set.all() self.page_title = self.vote.title return super(DetailVoteView, self).dispatch(request, *args, **kwargs) def get(self, request, id): if is_active_vote(self.vote): nominates = self.vote_for_chars return render(request, 'vote_detail/active_vote_detail.html', context={ 'page_title': self.page_title, 'vote': self.vote, 'votes_name': self.page_title, 'nominates': nominates, }) else: winners = [] top_fives = [] if self.vote.voteforcharacter_set.count() != 0: sorted = self.vote.voteforcharacter_set.order_by('-votes_number') winner_number_votes = sorted[0].votes_number winners = self.vote_for_chars.filter(votes_number__exact=winner_number_votes) top_fives = sorted[winners.count():5 + winners.count()] return render(request, 'vote_detail/completed_vote_detail.html', context={ 'page_title': self.page_title, 'vote': self.vote, 'votes_name': self.page_title, 'winners': winners, 'top_fives': top_fives }) def post(self, request, id): vote_for_chars = self.vote_for_chars id_to_vote = request.POST.get("id_to_vote") char_to_vote = vote_for_chars.get(character__id=id_to_vote) char_to_vote.votes_number += 1 char_to_vote.save() return HttpResponseRedirect('/') The code is not DRY as I suppose. Because, there is the same context in get reuqest. I need to use a mixins feature? How can I improve it? Thanks. EDITED. Added code for templates. acvtive_vite_detail.html {% extends 'base/base.html' %} {% block content %} {% csrf_token %} Vote: {{ vote }}. Choose: {% for item in nominates %} {% include "base/listOutput.html" %} {{ item.character.name }} {% endfor %} Vote! {% endblock content %…
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92061143
has comment: http://stackoverflow.com/comment/92061219
downvote count: 0
has comment: http://stackoverflow.com/comment/92061582

http://stackoverflow.com/q/52430465
linked to: http://stackoverflow.com/q/613183
has answer: http://stackoverflow.com/a/52430682
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91804535
has body: I have a Dictionary like {'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}} How would I be able to sort this by the "frequency" attribute?
type: Question
has title: How to sort a dictionary by attribute value?
has comment: http://stackoverflow.com/comment/91805588
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52430499
accepted answer: http://stackoverflow.com/a/52430499
possible better answer: http://stackoverflow.com/a/52430682
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52504401
type: UnansweredQuestion
has body: Is there a way to align multiple pandas Series or DataFrames. Say I have a list of pandas Series, and want to: only keep index elements that are present in all series (inner join) all series have index elements that are the union of all indices (outer join) The following code achieves what I want (for inner and outer join) import pandas as pd import itertools def align(pd_objects, join='outer', axis=0): """apply align on all combinations of the list of pd objects""" for (i, j) in itertools.combinations(range(len(pd_objects)), 2): (pd_objects[i], pd_objects[j]) = pd_objects[i].align(pd_objects[j], join, axis) return tuple(pd_objects) s_1 = pd.Series(['a', 'b', 'c', 'd'], index=[1, 2, 3, 4]) s_2 = pd.Series(['b', 'c', 'd'], index=[2, 3, 4]) s_3 = pd.Series(['a', 'b', 'c'], index=[1, 2, 3]) Where: (s_1x, s_2x, s_3x) = align([s_1, s_2, s_3], join='inner', axis=0) Returns three series with indices ['b', 'c'] And: (s_1y, s_2y, s_3y) = align([s_1, s_2, s_3], join='outer', axis=0) Returns three series with indices ['a', 'b', 'c', 'd'] But I guess there is a much more Pythonic and efficient way to do it
has comment: http://stackoverflow.com/comment/91963019
type: Question
has title: How to align multiple pandas Series or DataFrames
upvote count: 4
downvote count: 0
favorite count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/23668427
tagged with: python
has comment: http://stackoverflow.com/comment/91953853
score: 4
answer count: 0

http://stackoverflow.com/comment/91993866
type: AnswerComment
score: 0
has text: no, you are right there's no error message, but if c has another value, other than 1, 2, 3 or 4 i want this program to output the message "Error".
type: Comment
comment on: http://stackoverflow.com/a/52527085

http://stackoverflow.com/q/52468131
has answer: http://stackoverflow.com/a/52468453
type: AnsweredQuestion
score: 0
tagged with: authentication
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/52468453
has title: How can I create a login program that checks for availability on Python?
has body: I'm making a user login for a little project I'm working on at school, practising my file handling and whatnot. For the most part, it's going fine, but I'm having trouble when I try and create new users. The new user needs to have an original username and password to be created, otherwise, it should tell them that their choice is unavailable. For some reason, it works fine with the first username and password in the files and makes the user retry. But when I try and create a new user with a name that I know I shouldn't be able to, it lets me. def signUp(): username = str(input("\nPlease enter your new username ")) file = open ("usernames.txt","r") for x in file: if username in x: print ("\nThat username is already in use, please try another") signUp() else: print ("Your username is now ",username) file.close() password = input("\nPlease create a password ") file = open ("passwords.txt","r") for x in file: if password in x: print ("\nThat password is already in use, please try another") signUp() else: print ("Your password is now ", password," Don't forget it") file.close() file = open ("usernames.txt","a") file.write (username) file.write ("\n") file.close() file = open ("passwords.txt","a") file.write (password) file.write ("\n") file.close() print ("\nYour login details have been saved") print ("Please login") logIn() In the username file, it has the names: Alex Josh The password file has: 123qwe ewq321 The code works for Alex and 123qwe and stops them from being repeated, but not for Josh or ewq321. At the moment, I'm not looking for any other improvements. I'll refine it all later. For now, I just need help with this little predicament. I understand that my explanation is a little confusing, so it might help to copy what I've already done and play around with it. Obviously, this isn't the whole code, so it might not make perfect sense.
tagged with: python

http://stackoverflow.com/comment/91988818
type: Comment
score: 0
type: AnswerComment
has text: @Sebastiaan_L it is perfectly fine to ask many, many questions here on Stackoverflow. Flood away!
comment on: http://stackoverflow.com/a/52520051

http://stackoverflow.com/comment/91833840
has text: when I run manage.py it throws this "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?"
comment on: http://stackoverflow.com/q/52445331
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91887096
type: Comment
score: 0
type: AnswerComment
has text: @Stick1000 I understand you want them together being the same
comment on: http://stackoverflow.com/a/52472596

http://stackoverflow.com/a/52564682
downvote count: 0
type: Answer
upvote count: 6
has body: Logically, nested dictionaries (and lists) is a kind of recursion, so if you want to avoid logical recursion, that's impossible. But, since recursion is just recursion, you can keep a stack of your own and simulate that in a loop: def flatten(dct, c=None): if c is None: c = [] stack = [dct] while stack: # non-empty d = stack.pop() for k, v in d.items(): c.append(k) if v: stack.append(v) return c This function well emulates the behavior of function recursion, with a custom stack. There's one potential downside: Theoretically, a dictionary like {1: None, 2: {3: None, 4: None}, 5: None} should be flattened as [1, 2, 3, 4, 5], while this method would give [1, 2, 5, 3, 4]. This is much like a DFS search vs a BFS search on a graph. But, since dictionary is unordered, this shouldn't be a big matter (unless you're using collections.OrderedDict), and that's why I say this is a potential downside.
answers question: http://stackoverflow.com/q/52564639
score: 6

http://stackoverflow.com/a/52584967
has comment: http://stackoverflow.com/comment/92104690
score: 0
answers question: http://stackoverflow.com/q/52584889
has body: Try converting to a string first then encode that string. #convert to unicode teststring = unicode(teststring, 'utf-8') #encode it with string escape teststring = teststring.encode('unicode_escape') #then run check on test string. if event == testString do #this code.
has comment: http://stackoverflow.com/comment/92104713
type: Answer

http://stackoverflow.com/q/52494999
tagged with: dataframe
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52495492
tagged with: pandas
has title: Pandas - count since last transaction
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52495492
has body: I have a dataframe (call it txn_df) that contains monetary transaction records, here are the significant columns in this problem: txn_year txn_month custid withdraw deposit 2011 4 123 0.0 100.0 2011 5 123 0.0 0.0 2011 6 123 0.0 0.0 2011 7 123 50.1 0.0 2011 8 123 0.0 0.0 Assume also that we have multiple customers here. withdraw and deposit 0.0 value for both means no transaction has taken place. What I want to do is to produce a new column that indicates how many months has occurred since there was a transaction. Something similar to this: txn_year txn_month custid withdraw deposit num_months_since_last_txn 2011 4 123 0.0 100.0 0 2011 5 123 0.0 0.0 1 2011 6 123 0.0 0.0 2 2011 7 123 50.1 0.0 3 2011 8 123 0.0 0.0 1 The only solution so far that I can think of is to produce a new column has_txn (which is either 1/0 or True/False) when either one of withdraw and deposit has value > 0.0 but I can't continue from there.
upvote count: 3

http://stackoverflow.com/comment/92057632
type: QuestionComment
has text: @jackvern, I've tried to clarify your question. If this isn't what you want, please edit it so it is clear.
score: 0
comment on: http://stackoverflow.com/q/52559403
type: Comment

http://stackoverflow.com/comment/92074014
has text: I was just joking about it. It was actually very well written, that's why it looked strange to me. What I would expect after the question, though, as I already said, is what you had tried so far and where you thought the improvement could be applied. This allows other people to focus more on your real problem. I am not sure about the downvote, but my guess is that it might be just because of this. I took the liberty to upbote it to set it to 0 again :)
comment on: http://stackoverflow.com/q/52500240
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/137283469
comment on: http://stackoverflow.com/a/61922605
has text: @bluenote, a number like `0.1` in full precision should printed as `0.1000000000000000055511151231257827021181583404541015625` since 0.1 is not representable in IEEE 754. The representation as `0.1` is just enough digits to distinguish it from it's closest IEEE 754 representable neighbors. I would argue that most people looking for "full precision" are really after `0.1000000000000000055511151231257827021181583404541015625` and not `0.1`, at least I was looking for this.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52495623
tagged with: google-app-engine
tagged with: python
type: AnsweredQuestion
tagged with: google-bigquery
downvote count: 1
type: Question
has body: We are using GAE standard and as per google documentation, we are expected to vendor dependencies in some folder using pip install requirement-name -t lib/. We want to use both BigQuery &amp; pub-sub in the same GAE project which is I think not a very rare combination. Now the issue is at a time we are able to install only one of the client libraries as both share google&gt;cloud namespace whichever is installed later will override earlier dependency. Screenshots:- 1) When only BigQuery client library is installed:- 2) After installing pip install -t lib/ google-cloud-pubsub What can be the issue and solution for the same? UPDATE:- Further tried installing these two dependencies in the virtual environment without vendoring in lib/ folder, there both dependencies are getting installed without overwriting each other. So looked like the issue is with vendoring in folder. Screenshot for the same without vendoring dependencies.
has answer: http://stackoverflow.com/a/52502117
has comment: http://stackoverflow.com/comment/91933340
has comment: http://stackoverflow.com/comment/91933083
tagged with: google-cloud-platform
tagged with: google-cloud-pubsub
answer count: 1
score: 1
accepted answer: http://stackoverflow.com/a/52502117
favorite count: 0
has title: google-cloud dependencies getting overriden in python app engine
upvote count: 2

http://stackoverflow.com/comment/91947244
score: 0
type: Comment
type: QuestionComment
has text: I'd suggest updating your question with more details… that said, have a look in the docs: https://docs.python.org/3/library/email.examples.html
comment on: http://stackoverflow.com/q/52503156

http://stackoverflow.com/q/52512150
score: 1
accepted answer: http://stackoverflow.com/a/52513211
upvote count: 1
has title: Recursive function to go inside dictionary of dictionary
type: Question
possible better answer: http://stackoverflow.com/a/52512883
has answer: http://stackoverflow.com/a/52512801
has answer: http://stackoverflow.com/a/52512883
has body: I have to recursively look for dictionary whose values doesn't contain another dictionary and then create a new dictionary based on that,Currently my recursive function is able to handle dictionary of dictionaries b= {'order': {'id': u'62211'}, 'no': 0, 'data': 340, 'instruction': {'id': u'99AA', 'version': u'1', 'validation': ('nota', None), 'time': 9001, 'instructions': [], 'restart': True}} temp_1={} import copy def getKeys(d): for k,v in d.items(): if isinstance(v, dict): getKeys(v) else: temp_1[k]=v return temp_1 a= getKeys(b) Output {'no': 0, 'version': u'1', 'time': 9001, 'validation': ('nota', None), 'data': 340, 'id': u'62211', 'restart': True, 'instructions': []} but when there are instances where dictionaries are coming inside a list or tuple not sure how to handle that in a recursive way. ab={'apple':9,'ball':{'cat':8,'www':('data',{'new':'hello','ppp':('dat',[{'jjj':'world'}])})}} expected output: { 'apple':9,'cat':8,'new':'hello','jjj':'world'}
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52513211
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: recursion

http://stackoverflow.com/a/55935852
has body: I would suggest using tabulate. It can output the data in various table formats. from tabulate import tabulate import pandas as pd df = pd.read_csv('data.csv') print(tabulate(df, headers='keys', tablefmt='psql')) Example: from tabulate import tabulate import pandas as pd df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007], 'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']}) print(tabulate(df, headers='keys', tablefmt='psql')) +----+-----------+-------------+ | | col_two | column_3 | |----+-----------+-------------| | 0 | 0.0001 | ABCD | | 1 | 1e-05 | ABCD | | 2 | 1e-06 | long string | | 3 | 1e-07 | ABCD | +----+-----------+-------------+ Supported table formats are: "plain" "simple" "github" "grid" "fancy_grid" "pipe" "orgtbl" "jira" "presto" "psql" "rst" "mediawiki" "moinmoin" "youtrack" "html" "latex" "latex_raw" "latex_booktabs" "textile"
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52520711
downvote count: 0
type: Answer

http://stackoverflow.com/a/52507704
upvote count: 1
has comment: http://stackoverflow.com/comment/91955882
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52507652
has body: You just have to combine all the things you did correctly: sort keys as a tuple and the proper way of referencing a dict entry: &gt;&gt;&gt; sorted(AccountValues, key=lambda x: (x["portfolio_ref"], -x["percent"])) [{'tag': 'NetLiq', 'portfolio_ref': 1, 'value': '70976.05', 'percent': 100.0, 'currency': 'USD'}, {'tag': 'FullInit', 'portfolio_ref': 1, 'value': '20642.95', 'percent': 0.0, 'currency': 'USD'}, {'tag': 'FullMaint', 'portfolio_ref': 1, 'value': '21350.54', 'percent': 0.0, 'currency': 'USD'}] Better yet, use sorted(AccountValues, key=itemgetter("portfolio_ref", "percent")) Your first attempt failed because x[1] and x[4] are not valid references into the dictionaries: you have to use the labels you originally gave, not relative positions. Your second attempt is deficient only because you don't have the secondary sort key.

http://stackoverflow.com/comment/91840835
type: Comment
has text: You know we can see you are answering yourself, you don't need to pretend to be someone giving you the answer :')
comment on: http://stackoverflow.com/a/52448474
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91819591
type: Comment
type: QuestionComment
has text: Show the complete Traceback
comment on: http://stackoverflow.com/q/52438313
score: 0

http://stackoverflow.com/comment/92046991
type: Comment
has text: It should look like: `WHERE ... keyword.name REGEXP Donut|Pizza` (tested it locally. So it looks like you did something wrong, or the query originates from somewhere else.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52553732

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/52474981
tag name: qpushbutton

http://stackoverflow.com/q/52568718
has comment: http://stackoverflow.com/comment/92093394
tagged with: selenium
has comment: http://stackoverflow.com/comment/92075891
has answer: http://stackoverflow.com/a/52571490
tagged with: webdriver
type: Question
has body: Hi I am trying to locate an element containing text '01.0000', but there is a source code containing '01.00' before this line. How can I locate this element? source code: Communication and Media Studies09.01 Communication, General09.0100 Speech Communication and Rhetoric09.0101 Mass Communication/Media Studies09.0102 Communication and Media Studies, Other09.0199 Animal Sciences01.09 here are the codes I tried: driver.find_element_by_xpath("//span/div/a/span[text()= 01.0000]") driver.find_element_by_xpath("//span/div/a/span[normalize-space()= 01.0000]") driver.find_element_by_xpath("//span/div/a/span[./text()= 01.0000]") I kept getting 01.00 element instead of 01.0000 element.
score: -1
answer count: 1
has comment: http://stackoverflow.com/comment/92075668
favorite count: 0
tagged with: xpath
has comment: http://stackoverflow.com/comment/92075247
has title: How to exact a number using xpath through Selenium and Python
downvote count: 2
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52571490
tagged with: selenium-webdriver
type: AnsweredQuestion

http://stackoverflow.com/comment/92451765
type: Comment
comment on: http://stackoverflow.com/a/52737094
score: 1
has text: _every_ macos installation comes with python, _The command `which python` should return nothing_ is a dangerous instruction, unless you want him to keep reinstalling his OS
type: AnswerComment

http://stackoverflow.com/a/52460793
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Something like this could work. For each group where quantity is greater than 4, apply a function that does the row splitting and stores into a temp dataframe, then combine everything together to get your desired output: df = pd.DataFrame({'idx': ['A', 'B', 'C', 'D'], 'quantity': [3, 4, 10, 11]}) def split_quant(df): quantities = ([4]*(df['quantity'].iat[0] // 4)) + [df['quantity'].iat[0] % 4] temp = pd.DataFrame({'idx': df['idx'].iat[0], 'quantity': quantities }, index=range(len(quantities))) temp = temp[temp['quantity']!=0] return temp df_split = df[df['quantity'] &gt; 4].groupby('idx').apply(split_quant) output = df[df['quantity'] &lt;= 4].append(df_split).reset_index(drop=True) writer = pd.ExcelWriter('output.xlsx') output.to_excel(writer, 'Sheet1', index=False) writer.save() The above will give you the following output dataframe: idx quantity 0 A 3 1 B 4 2 C 4 3 C 4 4 C 2 5 D 4 6 D 4 7 D 3 EDIT: I took the liberty of running some timing tests of the various methods. Using Pandas' groupby and apply saves a lot of time and avoids the nested loops over the input data (although I'm sure theres an even faster way that can avoid the apply as well...) Mine: 5.49 ms ± 240 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) @Iqbal Basyar: 22.8 ms ± 1.47 ms per loop (mean ± std. dev. of 7 runs, 100 loops each) @sobek 17.7 ms ± 922 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
has comment: http://stackoverflow.com/comment/91872116
has comment: http://stackoverflow.com/comment/91872013
has comment: http://stackoverflow.com/comment/91871220
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52459977
has comment: http://stackoverflow.com/comment/91872030
accepted answer of: http://stackoverflow.com/q/52459977

http://stackoverflow.com/comment/92088931
has text: Downloading the css file and parse them, I'm already doing it but it takes a bit too much processing time. Could you explain me more about the XPATH/CSS rule, because I tried that and I thought that I would need the class/id/name of the element in order to get the CSS from it. Also could you enlight me about your first option "grab all the Style tages"?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52559637

http://stackoverflow.com/comment/92313954
comment on: http://stackoverflow.com/q/52583316
type: Comment
has text: Thanks: https://github.com/dask/dask-ml/issues/390
score: 0
type: QuestionComment

http://stackoverflow.com/a/52555522
has comment: http://stackoverflow.com/comment/92049883
answers question: http://stackoverflow.com/q/52555368
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92050897
type: Answer
has body: If you must stick with numbers (though I'd go with the string option first) from math import log10, floor s = 2 # digits to shift by p = 10 ** s # that as a power of 10 n = 1234 rhs = n // p # right hand side of result (here 12) rhs_n = floor(log10(rhs)) + 1 # number of digits in rhs rhs + (n % p) * 10 ** rhs_n # add other digits, n % p, shifted by size of rhs and all together in a function from math import log10, floor def rotate(n, s): p = 10 ** s rhs = n // p return rhs + (n % p) * 10 ** (floor(log10(rhs)) + 1)

http://stackoverflow.com/q/52528486
tagged with: django-urls
possible better answer: http://stackoverflow.com/a/52528559
type: Question
tagged with: django-admin
accepted answer: http://stackoverflow.com/a/52601830
has comment: http://stackoverflow.com/comment/91997178
score: 0
has title: Django Admin page won't let me delete or add users/group. urls error
has answer: http://stackoverflow.com/a/52529165
answer count: 3
has answer: http://stackoverflow.com/a/52601830
has comment: http://stackoverflow.com/comment/91996511
has comment: http://stackoverflow.com/comment/91997387
has answer: http://stackoverflow.com/a/52528559
has comment: http://stackoverflow.com/comment/91996632
has comment: http://stackoverflow.com/comment/91997011
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91996459
linked to: http://stackoverflow.com/q/25716185
has body: I just set up my own Django server but I am having trouble with the admin page. When I try adding or deleting users or basically whenever I send POST request from Django admin page, I am getting the following error: Raised by: django.contrib.admin.options.changelist_view Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^register/$ [name='register'] ^$ ^login/$ [name='login'] ^static\/(?P&lt;path&gt;.*)$ The current path, auth/user/, didn't match any of these. Normal pages work fine. I am only getting the errors on Admin page.I tried doing python manage.py migrate but there are no migrations to apply. I am guessing this has to do with urls.py or settings.py files. re_path('^admin/', admin.site.urls) url pattern is already there, I am not sure why it is still giving the error. Path structure: -root -mysite -urls.py -settings.py -wsgi.py -views.py -forms.py -templates -static -passenger_wsgi.py -manage.py This is my urls.py file: from django.urls import re_path from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ re_path('^admin/', admin.site.urls), re_path('^register/$', register_page, name='register'), re_path('^$', home_page), re_path('^login/$', login_page, name='login'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And this is settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'key' DEBUG = True ALLOWED_HOSTS = ['myip'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.…

http://stackoverflow.com/q/52474817
favorite count: 0
tagged with: distribution
has answer: http://stackoverflow.com/a/52477039
type: Question
upvote count: 2
answer count: 2
tagged with: python
has body: Specifically given a 2-D matrix, how to find median for every column's positive elements? Mathematically speaking: return B, where B[i] = median({A[j, i] | A[j, i] &gt; 0}) I know that median can by computed by tf.contrib.distributions.percentile tf.boolean_mask(A, tf.greater(A, 0)) outputs a 1-D list instead of a matrix.
tagged with: conditional-statements
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52476419
has title: How to get median of column positive elements in a tensor/matrix?
type: UnansweredQuestion
tagged with: median
score: 2
downvote count: 0

http://stackoverflow.com/a/52449914
score: 4
answers question: http://stackoverflow.com/q/52449639
has comment: http://stackoverflow.com/comment/91843112
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: You can get the json loader to build an OrderedDict: import json import collections with open('example.json') as f: json_object = json.load(f,object_pairs_hook=collections.OrderedDict)
type: Answer
accepted answer of: http://stackoverflow.com/q/52449639

http://stackoverflow.com/a/65602635
type: Answer
score: 3
has body: This solution from pythonpedia.com solved the issue for me. Reproducing here for longevity, all credit to ImportanceOfBeingEarnest and the page https://pythonpedia.com/en/knowledge-base/44863375/how-to-change-spacing-between-ticks-in-matplotlib- . Answer from ImportanceOFBeingEarnest: The spacing between ticklabels is exclusively determined by the space between ticks on the axes. Therefore the only way to obtain more space between given ticklabels is to make the axes larger. In order to determine the space needed for the labels not to overlap, one may find out the largest label and multiply its length by the number of ticklabels. One may then adapt the margin around the axes and set the calculated size as a new figure size. import numpy as np import matplotlib.pyplot as plt N = 150 data = np.linspace(0, N, N) plt.plot(data) plt.xticks(range(N)) # add loads of ticks plt.grid() plt.gca().margins(x=0) plt.gcf().canvas.draw() tl = plt.gca().get_xticklabels() maxsize = max([t.get_window_extent().width for t in tl]) m = 0.2 # inch margin s = maxsize/plt.gcf().dpi*N+2*m margin = m/plt.gcf().get_size_inches()[0] plt.gcf().subplots_adjust(left=margin, right=1.-margin) plt.gcf().set_size_inches(s, plt.gcf().get_size_inches()[1]) plt.savefig(__file__+".png") plt.show() Note that if the figure shown in the plotting window is larger than the screen, it will be shrunk again, so the resized figure is only shown in its new size when saved. Or, one may choose to incorporate it in some window with scrollbars.
downvote count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/135847470
answers question: http://stackoverflow.com/q/52523710

http://stackoverflow.com/comment/91952455
comment on: http://stackoverflow.com/q/52505861
type: QuestionComment
type: Comment
has text: It's not an event, because it's not listed in the [Event reference](https://discordpy.readthedocs.io/en/rewrite/api.html#event-reference). Remove all references to `ctx`. No one is invoking a command, so there can't be an invocation context. You need to add `self` as the first argument of all the methods of the cog, including events and commands. I'm not sure how you're determining what channel to interact with, but you need to get that channel inside the coroutine (after the bot has started). Your function signature also requires a number, so you must pass one.
score: 0

http://stackoverflow.com/a/52436519
type: Answer
score: 2
has body: You could define your own function f = lambda x: sin(x) if x&lt;1 else cos(x) and then use numpy's builtin vectorizer f_broadcasting = np.vectorize(f). This doesn't offer any speed improvements (and the additional overhead can slow down small problems), but it gives you the desired broadcasting behavior.
has comment: http://stackoverflow.com/comment/91816918
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52436499
accepted answer of: http://stackoverflow.com/q/52436499

encryption
tags question: http://stackoverflow.com/q/52575131
tags question: http://stackoverflow.com/q/52484383
tags question: http://stackoverflow.com/q/52463971
tags question: http://stackoverflow.com/q/52536655
tag name: encryption
tags question: http://stackoverflow.com/q/52574959
tags question: http://stackoverflow.com/q/52542923
type: Tag

http://stackoverflow.com/comment/91995424
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52527885
has text: `return` the database from `createDatabase`, then pass that as an argument to `searchDatabase`. If you provide more of your code (specifically where you are calling these functions) I can give better advice.

http://stackoverflow.com/comment/92031137
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52545527
has text: I tried adding the spaces, but it was pretty much the same due to digits. And thank you so much for the link, I tried searching in a lot of ways how to fix this, but missed that link.

http://stackoverflow.com/comment/92081147
type: QuestionComment
comment on: http://stackoverflow.com/q/52567704
score: 1
has text: Where are you checking the item count? If you are checking it in AWS Management console, it would take a few hours to show the correct count. It is not updated real time.
type: Comment

http://stackoverflow.com/comment/92047304
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot.. it was as simple as that.
comment on: http://stackoverflow.com/a/52554177

http://stackoverflow.com/comment/120878043
has text: I've got similar issue which alas the above approach does not resolve. In my case wanting progress reporting from the mpi example on https://emcee.readthedocs.io/en/stable/tutorials/parallel/ . The code runs alright but I don't see any output until the subprocess is complete.
comment on: http://stackoverflow.com/a/52576723
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52451858
has body: Here's a reasonably efficient solution that gives you fairly random output that obeys the constraints, although it doesn't cover the full solution space. We can ensure that the number of zeroes and ones are equal by ensuring that the number of single zeros equals the number of single ones, and the number of pairs of zeros equals the number of pairs of ones. In a perfectly random output list we'd expect the number of singles to be roughly double the number of pairs. This algorithm makes that exact: each list has 12 singles of each type, and 6 pairs. Those run lengths are stored in a list named runlengths. On each round, we shuffle that list to get the sequence of run lengths for the zeros, and shuffle it again to get the sequence of run lengths for the ones. We then fill the output list by alternating between runs of zeroes and ones. To check that the lists are correct we use the sum function. If there are equal numbers of zeroes and ones the sum of a list is 24. from random import seed, shuffle seed(42) runlengths = [1] * 12 + [2] * 6 bits = [[0], [1]] for i in range(10): shuffle(runlengths) a = runlengths[:] shuffle(runlengths) b = runlengths[:] shuffle(bits) out = [] for u, v in zip(a, b): out.extend(bits[0] * u) out.extend(bits[1] * v) print(i, ':', *out, ':', sum(out)) output 0 : 0 0 1 0 0 1 1 0 1 0 1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 1 1 0 1 1 0 1 : 24 1 : 0 1 0 0 1 0 1 1 0 0 1 0 1 0 1 0 0 1 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 0 1 0 1 0 1 1 0 0 1 0 1 1 0 1 : 24 2 : 0 0 1 1 0 0 1 0 0 1 0 1 0 1 1 0 1 0 1 1 0 0 1 0 1 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 1 1 0 0 1 : 24 3 : 0 0 1 0 1 1 0 0 1 1 0 1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 1 0 0 1 0 1 1 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 : 24 4 : 1 1 0 0 1 0 1 0 1 0 1 1 0 1 1 0 1 0 1 1 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 0 : 24 5 : 1 1 0 1 0 1 0 1 1 0 1 0 1 1 0 0 1 0 1 0 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 0 1 0 0 : 24 6 : 1 0 1 0 0 1 0 0 1 0 0 1 1 0 0 1 1 0 1 0 0 1 1 0 1 1 0 1 1 0 1 0 1…
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52451211
type: Answer

http://stackoverflow.com/a/52605133
answers question: http://stackoverflow.com/q/52587514
upvote count: 1
score: 1
has body: If you look at the documentation for set_edge_attributes you will see the syntax is (G, values, name), for the simplest form of the function which takes a scalar (1 in this case) and assigns it to the attribute weight for all of the edges: nx.set_edge_attributes(G, 1, 'weight')
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52587514
type: Answer

http://stackoverflow.com/q/52445281
type: UnansweredQuestion
has body: I started using the ansible_runner python library and i really like it. https://github.com/ansible/ansible-runner https://ansible-runner.readthedocs.io/en/latest/ The only thing is that I need to retrieve a registered variable. And I just can't find how. import ansible_runner class Infra: def __init__(self, extravars, envvars, private_data_dir): self.extravars = extravars self.envvars = envvars self.private_data_dir = private_data_dir self.runner = None def create(self): self.run("create.yml") def destroy(self): self.run("destroy.yml") def run(self, playbook): self.runner = ansible_runner.run( private_data_dir=self.private_data_dir, playbook=playbook, verbosity=5, extravars=self.extravars, envvars=self.envvars ) if __name__ == "__main__": extravars = {} envvars = {} private_data_dir = "" i = infra(extravars, envvars, private_data_dir) i.create() Now after I created the infra, I want to retrieve the IP which is registered in my create.yml - name: "Get terraform output" shell: &gt; cd {{ TERRAFORM_CONTEXT_PATH }} &amp;&amp; \ export TF_VAR_provisionning_ssh_private_key_path={{ SSH_PRIVATE_KEY }} &amp;&amp; \ terraform output -json register: terraform_output Is it something possible? I looked in the runner.events, but I haven't found it. Thanks
tagged with: python
downvote count: 0
score: 1
type: Question
has title: In the ansible_runner python library, is it possible to retrieve registered variable from the playbooks with the runner?
has answer: http://stackoverflow.com/a/56562613
tagged with: ansible
upvote count: 1
answer count: 1
tagged with: ansible-runner
tagged with: devops
favorite count: 0

http://stackoverflow.com/a/52553411
has body: the problem has been solved by adding chardet detection of encoding
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52537634

http://stackoverflow.com/q/52545207
has answer: http://stackoverflow.com/a/75214960
has answer: http://stackoverflow.com/a/52547418
type: Question
answer count: 2
downvote count: 0
score: 1
has title: Trying to save a video into a folder but it show 0 KB.What is the problem?
has body: I am trying to save video using VideoCapture object in openCv using python. But the video is saved as 'output.avi' but its size is showing as 0 KB. Need your help, not able to find out the error. cap = cv2.VideoCapture("C:\\farhana\\Tom.und.Jerry.Piraten.auf.Schatzsuche.mp4") out = cv2.VideoWriter("C:\\farhana\\output.avi", -1, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv2.flip(frame,0) out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows()
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: opencv

http://stackoverflow.com/a/52537864
has comment: http://stackoverflow.com/comment/92015562
downvote count: 0
answers question: http://stackoverflow.com/q/52537767
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92015267
has body: use STATIC_ROOT = os.path.join(BASE_DIR, 'static/') and then run python manage.py collectstatic It will create a folder named static in your project directory. There you will find all your css and js files
score: 1
has comment: http://stackoverflow.com/comment/92020191

http://stackoverflow.com/q/52584889
tagged with: python
tagged with: emoji
has comment: http://stackoverflow.com/comment/92104759
has comment: http://stackoverflow.com/comment/92208684
has comment: http://stackoverflow.com/comment/92105402
has title: How to compare emojis in python
linked to: http://stackoverflow.com/q/25707222
has comment: http://stackoverflow.com/comment/92104842
has answer: http://stackoverflow.com/a/52584967
has comment: http://stackoverflow.com/comment/92105259
has comment: http://stackoverflow.com/comment/92131428
has body: I have a set of ics data that I am tryin to parse in python. This date uses emjois to indicate different types of events. So I am trying to use these emjois in an if statement tell what type of event it is. I am trying to compare like this: if event == '✈️': do something here When event equals a ✈️ it is not evaluating true. I'm guessing it has something to do with the encoding, but I can't wrap my head around it. Any help would be much appreciated
type: UnansweredQuestion
tagged with: unicode
has comment: http://stackoverflow.com/comment/92105014
has comment: http://stackoverflow.com/comment/92128879
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92124707
has comment: http://stackoverflow.com/comment/92104729
type: Question
has comment: http://stackoverflow.com/comment/92104905
has answer: http://stackoverflow.com/a/52637850
has comment: http://stackoverflow.com/comment/92104949
has comment: http://stackoverflow.com/comment/92105464
linked to: http://stackoverflow.com/q/41604811
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92105294

http://stackoverflow.com/q/52551033
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/52551159
has answer: http://stackoverflow.com/a/52551144
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92041064
has comment: http://stackoverflow.com/comment/92040876
has comment: http://stackoverflow.com/comment/92041002
type: Question
tagged with: bubble-sort
has comment: http://stackoverflow.com/comment/92040939
score: 0
tagged with: key-value
answer count: 2
upvote count: 1
downvote count: 1
has body: I am trying to do bubble sort in descending order input={"m":1,"i":4,"s":4,"P":2} output={"i":4,"s":4,"p":2,"m":1} but a type error occurs. How can I do this? Below is the code: dict={"m":1,"i":4,"s":4,"P":2} for key,value in dict.items(): if(dict[key]&lt;dict[key+1]): temp=dict[key] dict[key]=dict[key+1] dict[key+1]=temp print(dict)
has title: bubble sorting in dictionary in python
has comment: http://stackoverflow.com/comment/92041036
favorite count: 0
has comment: http://stackoverflow.com/comment/92040886
has answer: http://stackoverflow.com/a/52551159
accepted answer: http://stackoverflow.com/a/52551144
has comment: http://stackoverflow.com/comment/92040963
has comment: http://stackoverflow.com/comment/92040859
has comment: http://stackoverflow.com/comment/92041120
has comment: http://stackoverflow.com/comment/92041019
tagged with: python

http://stackoverflow.com/q/52449246
tagged with: pandas
tagged with: python
has body: I am using the sqlalchemy module to import a .sqlite3 sheet and create an engine to form a database. The number of rows in my sql file is far more than I require - how do I format the range of rows that are selected to go into the database? For example, the first 10000 rows of a 100000 row file are to be imported only. Here is what I have so far: import pandas as pd import sqlalchemy import os db_dir = os.path.join("file_path_found_here", 'sqlfile.sqlite3') database_url = f'sqlite:///{db_dir}' engine = sqlalchemy.create_engine(database_url) if os.path.isfile(db_dir): df = pd.read_sql('FSC_Data', engine, index_col=['time']) print(df)
has title: Select a certain range of rows to create a db
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91841842
type: Question
tagged with: row
tagged with: sqlalchemy
tagged with: sql
linked to: http://stackoverflow.com/q/18107953
answer count: 1
has answer: http://stackoverflow.com/a/52449502
score: 0

http://stackoverflow.com/q/52462692
favorite count: 0
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91867695
tagged with: python
has title: print(x) TypeError: 'str' object is not callable
downvote count: 1
has answer: http://stackoverflow.com/a/52463586
linked to: http://stackoverflow.com/q/111234
type: Question
has answer: http://stackoverflow.com/a/52462734
answer count: 2
score: -1
has body: import random print("guass a number in between 0 t0 10") x=random.randint(0,10) print(x) while True: print=("if i have to think lower press 1,if i have to think higher press 2,if correct press 3") y=int(input("press your choice")) if y==1: x=random.randint(0,x) print(x) elif y==2: x=random .randint(x,10) print(x) elif y==3: print("thank you") else: print("chosee a valid no") break can any 1 help me in it......

http://stackoverflow.com/comment/91869112
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52463602
has text: yeah cool, it is not efficient to convert to string :( I think decimal is stored in memory as two integers...

http://stackoverflow.com/comment/91852382
type: QuestionComment
type: Comment
has text: what is the error, please provide your code snippet and error.
score: 0
comment on: http://stackoverflow.com/q/52454546

http://stackoverflow.com/comment/92105843
comment on: http://stackoverflow.com/a/52584960
type: Comment
score: 1
type: AnswerComment
has text: Tbh, when I see timestamps I prefer converting it to seconds and skip the whole datetime thing altogether.

http://stackoverflow.com/comment/92076987
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52502112
has text: @Chris Conlan Thanks. I used to think subprocess will create a new process id and it will have zero effect on the parent process (python runtime). Please help me understand where I am wrong.

http://stackoverflow.com/comment/91852442
has text: for item, cost in (expenses): worksheet.write(row, col, item) worksheet.write(row, col + 1, cost) worksheet.write(row, col + 1, customer) row += 1. Is this correct for a third row?
type: Comment
comment on: http://stackoverflow.com/a/52452185
type: AnswerComment
score: 0

http://stackoverflow.com/a/52433633
has body: If you're gonna use pandas, use pandas to load the data too. import pandas from scipy.stats import mannwhitneyu hcl_data = pandas.read_table(hcl_file, sep="\t") print(mannwhitneyu(hcl_data.loc[hcl_data['type'] == "II"], hcl_data.loc[hcl_data['type'] == "III"])) I'm not entirely sure which columns you're trying to test so I can't be more specific. You might need to flatten the data before you pass it to scipy.
type: Answer
answers question: http://stackoverflow.com/q/52433424
has comment: http://stackoverflow.com/comment/91846014
has comment: http://stackoverflow.com/comment/91845986
score: 0

http://stackoverflow.com/comment/91920636
type: AnswerComment
has text: Hi @MarkSamuel, you need to use xpath as this way: `(//div[@class='modal-content']//*[contains(@class,'Package-channels--heading ng-binding')]) [index]`. for heading. Could you give it a try?
type: Comment
comment on: http://stackoverflow.com/a/52453446
score: 1

http://stackoverflow.com/comment/91954361
comment on: http://stackoverflow.com/a/52506935
type: AnswerComment
has text: @piRSquared this is interesting behavior , which mean when we do `replace` , pandas restore the intermediate variable somewhere . :-)
score: 0
type: Comment

http://stackoverflow.com/comment/91903811
score: 0
has text: @payne: it's a constan value, `datetime.datetime.now().isoformat()`, for example.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52481090

http://stackoverflow.com/q/52547143
accepted answer: http://stackoverflow.com/a/52547190
tagged with: while-loop
downvote count: 0
has title: Why specify index range in order to write a while loop list in Python?
favorite count: 0
has answer: http://stackoverflow.com/a/52547198
upvote count: 2
has answer: http://stackoverflow.com/a/52547190
possible better answer: http://stackoverflow.com/a/52547203
has answer: http://stackoverflow.com/a/52547212
tagged with: python
has answer: http://stackoverflow.com/a/52547203
has body: mean_temp.txt = city,country,month ave: highest high,month ave: lowest low Beijing,China,30.9,-8.4 Cairo,Egypt,34.7,1.2 London,UK,23.5,2.1 Nairobi,Kenya,26.3,10.5 New York City,USA,28.9,-2.8 Sydney,Australia,26.5,8.7 Tokyo,Japan,30.8,0.9 mean_temp = open('mean_temp.txt', 'r') city_temp = mean_temp.readline().split(",") while city_temp[0]: print(city_temp[0], city_temp[2]) city_temp = mean_temp.readline().split(",") mean_temp.close() The assignment is to just print the highest temperature for each city (ex: Beijing, 30.9). My first attempt at solving this problem was to simply write the while loop as "while city_temp: ". I still don't quite understand why I need to specify the index for the while loop to not make the "out of index" error. Why do I need to write "while city_temp[0]:"? I thought the while loop will naturally end once it reaches the end of the list... :( Would love and appreciate help on this thank you!
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: file
tagged with: loops
type: Question
tagged with: indexing

http://stackoverflow.com/a/52542305
downvote count: 0
type: Answer
score: 3
answers question: http://stackoverflow.com/q/52542053
upvote count: 3
has body: I found that powsimp could do what you want from sympy import symbols, exp from sympy import exp, powsimp x, a, b = symbols('x, a, b', real=True) f = exp(a*x)*exp(b*x) powsimp(f) Output exp(a*x + b*x) powdenest also (in this case) do the same Reference to powsimp Reference to powdenest

http://stackoverflow.com/comment/91957172
type: Comment
comment on: http://stackoverflow.com/a/52473988
type: AnswerComment
score: 0
has text: Thanks Adrian for your answer but I don't know yet how to use CDO in Anaconda on Windows. I've installed python-cdo packages but it's not working reading your lines.

http://stackoverflow.com/a/52497227
type: Answer
has comment: http://stackoverflow.com/comment/91934822
downvote count: 0
has body: You need to convert a to a string before you write it with str(a) You should also remove the print call as there should be nothing to print from your file operation f.write(str(a))
score: 9
has comment: http://stackoverflow.com/comment/91935115
upvote count: 9
answers question: http://stackoverflow.com/q/52497195

http://stackoverflow.com/q/52583576
has title: Python : Update Values of a Column based on Date Range from another Data Frame
score: 2
linked to: http://stackoverflow.com/q/45515826
has body: There are 2 dataframes df and events which look like below: import pandas as pd df = pd.DataFrame({'Place':['university','residential','hospital','university','residential','hospital'], 'Date':['2017-01-01','2017-01-01','2017-01-01','2017-01-02','2017-01-02','2017-01-02'], 'Event':['None','None','None','None','None','None'] }) events = pd.DataFrame({'Place':['university','residential','hospital'], 'Start_Date':['2017-01-01','2017-01-01','2017-01-01'], 'End_Date':['2017-02-26','2017-01-02','2017-01-02'], 'Event':['UniHolidays','PublicHoliday','PublicHoliday']}) #Convert to datetime events.Start_Date = pd.to_datetime(events.Start_Date.astype(str), format='%Y-%m-%d') events.End_Date = pd.to_datetime(events.End_Date.astype(str), format='%Y-%m-%d') df.Date = pd.to_datetime(df.Date.astype(str), format='%Y-%m-%d') df has 1 record for every date in 2017 for each place df: Date Place Event 2017-01-01 university None 2017-01-01 residential None 2017-01-01 hospital None 2017-01-02 university None 2017-01-02 residential None 2017-01-02 hospital None The second dataframe contains events for these places but with a date range events: Place Start_Date End_Date Event a 2017-01-01 2017-02-26 UniHoliday b 2017-01-01 2017-01-02 PublicHoliday c 2017-01-01 2017-01-02 PublicHoliday The task is to update df using events such that if df.Place = events.Place and df.Date is in range (events.Start_Date, events.End_Date) then df.Event should be updated with the corresponding event.Event The expected output is: Date Place Event 2017-01-01 university UniHoliday 2017-01-01 residential PublicHoliday 2017-01-01 hospital PublicHoliday 2017-01-02 university UniHoliday 2017-01-02 residential PublicHoliday 2017-01-02 hospital PublicHoliday There are no overlapping events, every place has a unique record of events so far I have been thinking along the lines of: Populate column in data frame based on a range found in another dataframe ,But can't get my head around it. Any help is appreciated. Thank you!
tagged with: dataframe
tagged with: date
type: Question
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52583596
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52514564
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52514483
has body: You want an inner merge. By default, common columns will be used for merging: res = df1.merge(df2, how='inner') print(res) col1 col2 col3 col4 col5 col6 0 Apple store1 1 3 123 50 1 Tree store2 1 3 451 32
score: 1

http://stackoverflow.com/comment/91994845
comment on: http://stackoverflow.com/q/52526476
score: 0
type: Comment
type: QuestionComment
has text: It looks like your values are all integers. If so, `5 < values_ < 6` cannot possibly be true; one or both of those comparisons should be `<=`.

http://stackoverflow.com/q/52457097
type: Question
has body: The below code is supposed to count instances of a particular word in a text file, though it seems to only work for individual letters. Using a string of two letters or more always returns a count of 0. I have checked, and the input I have been using should definitely not return a count of 0 for the given files. Any ideas? def count_of_word(filename, word_to_count): """Counts instances of a particular word in a file""" try: with open(filename) as file_object: contents = file_object.read() except FileNotFoundError: print("File " + filename + " not found") else: word_count = contents.lower().count(word_to_count) print("The count of the word '" + word_to_count + "' in " + filename + " is " + str(word_count))
type: AnsweredQuestion
has title: Counting instances of words from a file in Python, only works for single letters
score: -1
has answer: http://stackoverflow.com/a/52457157
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/91856757
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/52457858
has answer: http://stackoverflow.com/a/52457858
tagged with: python
has comment: http://stackoverflow.com/comment/91856548
accepted answer: http://stackoverflow.com/a/52457157
has comment: http://stackoverflow.com/comment/91856445
downvote count: 1

http://stackoverflow.com/comment/91856504
comment on: http://stackoverflow.com/q/52457024
type: Comment
type: QuestionComment
score: 0
has text: What `svd_solver` do you use?

http://stackoverflow.com/q/52483327
has comment: http://stackoverflow.com/comment/91908510
tagged with: python
accepted answer: http://stackoverflow.com/a/52483615
has title: Remove a precise curve from a figure in python
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91908226
tagged with: matplotlib
has body: If I do the following import matplotlib.pyplot as plt list1=[1,2,3] list2=[4,5,6] fig1=plt.figure(1) plt.plot(list1) plt.plot(list2) plt.show() I will plot in the same figure both list1 and list2. What should I do if later I decide that I need only to plot list1 in the figure and I want to remove the curve of list2 ? If possible, I would like to do it without using add_subplot or other similar commands. I am assuming that the xlim and ylim are the same for the two curves.
score: 0
has answer: http://stackoverflow.com/a/52483615
answer count: 1
has comment: http://stackoverflow.com/comment/91908308
has comment: http://stackoverflow.com/comment/91908133
has comment: http://stackoverflow.com/comment/91910224

http://stackoverflow.com/q/52511989
favorite count: 0
duplicate of: http://stackoverflow.com/q/1422155
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/52512072
has answer: http://stackoverflow.com/a/52512053
accepted answer: http://stackoverflow.com/a/52512053
linked to: http://stackoverflow.com/q/1422155
tagged with: c#
has comment: http://stackoverflow.com/comment/91963703
has title: C# Equivalent to Python's map()?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91963755
has body: Normally in Python 2/3 we may use the following code to split two space-separated integers into two variables: a,b = map(int,input().split()) Is there a short C# equivalent to this? (i.e nothing as long as below) string[] template = Console.ReadLine().Split(); a = Convert.ToInt32(template[0]); b = Convert.ToInt32(template[1]);
possible better answer: http://stackoverflow.com/a/52512072
type: Question
has comment: http://stackoverflow.com/comment/91964826
answer count: 2
has comment: http://stackoverflow.com/comment/91963838
downvote count: 0
score: 4

http://stackoverflow.com/a/52497090
has comment: http://stackoverflow.com/comment/91935430
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Follow these steps - 1) Try imapclient example in this documentation - https://imapclient.readthedocs.io/en/2.1.0/ 2) In order to parallelize fetching message, you need to partition your e-mails so that each thread fetches different e-mail. One of the criteria could be date field. 3) Write a method using example code in documentation and parameterize search criteria (server.search). 4) Call above method in the multiprocessing code. Example for multiprocessing can be found at - https://docs.python.org/3/library/multiprocessing.html 5) You can also check "SEARCH commands" section in the RFC http://www.faqs.org/rfcs/rfc3501.html to select your partitioning criteria if date is not suitable.
score: 1
answers question: http://stackoverflow.com/q/52494682
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52494682

http://stackoverflow.com/comment/91941549
comment on: http://stackoverflow.com/q/52499771
type: QuestionComment
has text: Are you invoking the lambda via apigateway from your web browser?
score: 0
type: Comment

http://stackoverflow.com/q/52440134
has title: swapping two rows in multi-index pandas dataframe
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: For simple table such as the following: df = pd.DataFrame([[1,2,3],[4,5,6]], index=['a','b']) 0 1 2 a 1 2 3 b 4 5 6 we can swap two rows 'a' and 'b' by calling: df.loc[['b','a'],:] Out[21]: 0 1 2 b 4 5 6 a 1 2 3 I expected the loc() call takes the same effect for the following multi-level index table: df = pd.DataFrame(np.arange(12).reshape((4, 3)), index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]], columns=[['Ohio', 'Ohio', 'Colorado'], ['Green', 'Red', 'Green']]) Ohio Colorado Green Red Green a 1 0 1 2 2 3 4 5 b 1 6 7 8 2 9 10 11 but when I run: df.loc[['b','a'],:] The table remains the same. I could swap the rows by calling the following though: df.reindex(index=['b', 'a'], level=0) Ohio Colorado Green Red Green b 1 6 7 8 2 9 10 11 a 1 0 1 2 2 3 4 5 What has happened to my df.loc[['b','a'],:]?
tagged with: python
score: 2
answer count: 0
tagged with: multi-index
type: Question
tagged with: pandas
downvote count: 0
tagged with: swap

http://stackoverflow.com/comment/91836584
has text: you need to remove the negation: `re.search('(NM_\d+)[.]', 'NM_000051.3').group(1)`
comment on: http://stackoverflow.com/q/52446846
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52477839
type: Question
has answer: http://stackoverflow.com/a/58485560
score: 7
has body: I want to print floats with precision 4. I use numpy , jupyter notebook I tried: %precision %.4g %precision 2 np.set_printoptions(precision=2) print(0.6776776) the output: 0.6776776 Any Ideas what is wrong ? # Name Version ipython 6.4.0 ipython_genutils 0.2.0 msgpack-python 0.5.6 python 3.6.5 python-dateutil 2.7.3
tagged with: numpy
downvote count: 0
answer count: 1
tagged with: precision
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
has title: printing float precision precision in numpy jupyter notebook
upvote count: 7

http://stackoverflow.com/a/52515830
accepted answer of: http://stackoverflow.com/q/52515244
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52515244
upvote count: 1
type: AcceptedAnswer
has body: json={} all_results={} restaurants=[] for i in restaurant: restaurant=Restaurant.objects.get(id=i.id) restaurant_serializer=RestaurantSerializers(restaurant) json['distace'] = i.distance json['review_count']=reviews json['liked']=False restaurants.append(json) all_results['nearby_restaurants']=restaurants all_results['popular_restaurants']=restaurants return all_results your code snipe return all_results which is a list,so what you get is list rather than a dict. so you can redefine all_results to dict and change some code. I dont test in my script, but you can try it. last, you maybe try to user pdb to debug you code.here is one good post about pdb python-debugging-pdb
type: Answer

http://stackoverflow.com/comment/91859693
type: Comment
has text: Thank you for your answer. It was helpful, but i tried, as you suggested, removing del a and it worked. Still, aren't tuples supposed to be immutable.
comment on: http://stackoverflow.com/a/52458687
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92095215
type: QuestionComment
has text: The DataFrame you have doesn't have a column named target, I am not sure what we can do about that. You should check your assumptions or data.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52579754

matplotlib-venn
tag name: matplotlib-venn
type: Tag
tags question: http://stackoverflow.com/q/52555809

http://stackoverflow.com/comment/91874117
has text: Or `pd.DataFrame([data],index=columns).T`
comment on: http://stackoverflow.com/a/52466164
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/q/52451228
tagged with: loops
has body: I'm new to Python, sorry for the level of this question. This is my output (prices from a website). I'm wondering how to convert them into a list of ints for price_list_items in price_list: for values in price_list_items: x= values.rstrip(' zł') print(x) 479 000 355 000 269 000 499 000 289 000 The desired result will like this [479 000,355 000,... ]. Also, I want to be able to perform basic with the values. I found this thread How to convert a for loop output into a list (python), but it didn't help me.
type: Question
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/52451268
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52451792
accepted answer: http://stackoverflow.com/a/52451792
linked to: http://stackoverflow.com/q/33390493
possible better answer: http://stackoverflow.com/a/52451268
type: AnsweredQuestion
has title: How to convert a for loop output into a python list

http://stackoverflow.com/a/52531753
upvote count: 1
has body: Example : The columns of interest are company_id (string) and company_score (float). So, You can use groupby company_id column and convert its result into a dictionary of DataFrames: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({ ... "company_id": ["AA", "AB", "AA", "CD", "AB"], ... "company_score": [.07, .08, .06, .0003, .09], ... "company_region": ["NW", "NE", "NW", "NW", "NE"]}) &gt;&gt;&gt; df company_id company_region company_score 0 AA NW 0.0700 1 AB NE 0.0800 2 AA NW 0.0600 3 CD NW 0.0003 4 AB NE 0.0900 &gt;&gt;&gt; dict_of_companies = {k: v for k, v in df.groupby('company_id')} &gt;&gt;&gt; import pprint &gt;&gt;&gt; pprint.pprint(dict_of_companies) {'AA': company_id company_region company_score 0 AA NW 0.07 2 AA NW 0.06, 'AB': company_id company_region company_score 1 AB NE 0.08 4 AB NE 0.09, 'CD': company_id company_region company_score 3 CD NW 0.0003} &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/52531196
downvote count: 0
has comment: http://stackoverflow.com/comment/92003259
type: Answer
score: 1

http://stackoverflow.com/comment/92015324
has text: Joost, in terminal I do: export FLASK_APP=test.py, then flask run, server goes up, surfing to localhost:5000 gives "Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52534377
type: AnswerComment

http://stackoverflow.com/a/52445009
type: Answer
has comment: http://stackoverflow.com/comment/91832732
has body: you need to use google cloud for this. Cloud Translation edit: after creating a google cloud account use this API for translation POST https://translation.googleapis.com/language/translate/v2 documentation
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52444561

http://stackoverflow.com/a/52546569
upvote count: 9
has comment: http://stackoverflow.com/comment/133706475
score: 9
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52545937
has body: Install python-xlib: pip3 install python-xlib Try this: from Xlib import display d = display.Display() root = d.screen().root query = root.query_tree() for c in query.children: # returns window name or None name = c.get_wm_name() if name: print(name) I'm not sure about the other properties. query.children is a list of Window objects, so some research on those should turn up something. Window object docs.
type: Answer
has comment: http://stackoverflow.com/comment/121403314
accepted answer of: http://stackoverflow.com/q/52545937

http://stackoverflow.com/comment/91845723
has text: Please accept and upvote the answer, if it was of any help. Thanks :)
type: Comment
comment on: http://stackoverflow.com/a/52451210
type: AnswerComment
score: 0

http://stackoverflow.com/a/52541812
has body: You created an integer los. You accept an input string strzal. If you want to compare them, you need to cast one to the type of the other. You probably want to make the input an integer: zal = int(strzal) if zal != los: print("") Else, you could make your random number a string: strlos = str(los) if strzal != strlos: print("")
answers question: http://stackoverflow.com/q/52541450
score: 0
type: Answer

http://stackoverflow.com/q/52434247
has comment: http://stackoverflow.com/comment/91817568
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91815534
downvote count: 0
answer count: 1
has body: I know that to get a pixel color in Pygame I use get_at. But I need to get a pixel that is outside my screen, ie, I have an image already blitted with just a portion visible. For example, a 1000x1000 image inside a 500,500 screen will only have 50% visible, the rest will be "off" the screen. So I need to access the portion off the screen. But if I reference get_at with a coordinate greater or less then the screen dimensions, Pygame stops with an error: IndexError: pixel index out of range import pygame W = 1600 H = 600 pygame.init() screen = pygame.display.set_mode([W, H]) image = pygame.image.load('huge_background.png').convert_alpha() screen.blit(image, [-5000, -420]) pygame.display.update() screen.get_at([100, -5]) # generates "IndexError: pixel index out of range" How can I get the background image pixel color outside the screen dimensions? Here is the currently visible pygame screen (1600 x 600). The 3 lines (in magenta) are the collision "detectors": And here is the background that will scroll (8000 x 8000): So here is an idea of the scenario: So, the collision detector lines might exceed the pygame screen limits but need to "read" the outside pixels to detect the collision.
has comment: http://stackoverflow.com/comment/91813919
has comment: http://stackoverflow.com/comment/91817573
tagged with: colors
has answer: http://stackoverflow.com/a/52512109
has title: How to get a pixel color outside of screen in pygame?
tagged with: pygame
has comment: http://stackoverflow.com/comment/91813323
has comment: http://stackoverflow.com/comment/91813483
favorite count: 0
has comment: http://stackoverflow.com/comment/91814189
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: pixel

http://stackoverflow.com/a/52445179
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52445132
upvote count: 5
has comment: http://stackoverflow.com/comment/91835346
has body: Important note: I really need to emphasize that while this solution did solve the original question's problem, string concatenation used within SQL query text usually indicates a SQL injection vulnerability. Don't do this. Consider that most packages and libraries for SQL connections will offer a bona fide method for passing data into your query using placeholders along with parameters- use this. If you are determined to use string concatenation anyway- don't concatenate data from external sources/users/clients/anyone but 'you.' You have been warned. Original answer If ID is a nvarchar, you need to be casting id to be that as well. Data = pd.read_sql_query("SELECT * from Data where [ID] = CAST(" + id + " AS NVARCHAR(10))", engine) NOTE: I passed in a 10 for your NVARCHAR(size), but you'll ultimately have to determine what that should be.
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91840991
has comment: http://stackoverflow.com/comment/91864943
score: 5
accepted answer of: http://stackoverflow.com/q/52445132
has comment: http://stackoverflow.com/comment/91833571

http://stackoverflow.com/comment/91910775
comment on: http://stackoverflow.com/q/52483655
score: 0
type: Comment
type: QuestionComment
has text: @yorodm, that was the answer `await asyncio.sleep` Thanks! You can read the second part of my question to see what I'm trying to accomplish.

http://stackoverflow.com/comment/92102398
score: 1
comment on: http://stackoverflow.com/q/52583677
type: Comment
type: QuestionComment
has text: Check this post https://stackoverflow.com/questions/52547598/joining-pandas-dataframes-on-column-name-matches-row-value-with-same-index/52547708#52547708

http://stackoverflow.com/q/52521728
has comment: http://stackoverflow.com/comment/91983499
tagged with: python
accepted answer: http://stackoverflow.com/a/52526717
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91983464
score: 1
upvote count: 1
type: Question
tagged with: algorithm
tagged with: data-structures
has comment: http://stackoverflow.com/comment/91993069
has answer: http://stackoverflow.com/a/52526717
has comment: http://stackoverflow.com/comment/91983746
has comment: http://stackoverflow.com/comment/91983398
has comment: http://stackoverflow.com/comment/91984825
answer count: 1
has body: Can someone help me verify if my pseudocode works correctly so the function presented appends n numbers to a list? I need help with an assignment on my first year on data-science. We are learning about data structures and about doubly linked lists. I understand the logic behind doubly linked list I think, but the I have a hard time writing what's happening in pseudocode. "Assignment 1: Let the list S be empty as a start. Now input n (natural numbers, e.g.: 1, 2, 3 ...) one at the time. When the last number of n is placed into the list, the list will be a sorted list containing the n numbers. Describe why we'll get a sorted n number in O(n^2) time." My answer to the assignment is written below, and I am really unsure if it's correct. // Our nodes will consist of 3 cells in each object. // key = a number (int) // prev = address pointer to previous node // next = address pointer til next node // This function creates an empty list function emptyList() L = new List{head = nil, size = 0} return L // This function creates a node. function makeNode(val) node = new Node{prev = NIL, key = val, next = NIL} return node // This function inserts n amount of nodes to an empty list function InsertNodes(n) // Create an empty list, S. emptyList() // Initiate the first node S.head = makeNode(1) for i = 2 to n-1 prevNode = makeNode(i-1) newNode = makeNode(i) while newNode.prev == NIL do // connect addresses of nodes prevNode.next = newNode.prev newNode.prev = prevNode.next The course is about algorithms and discrete mathematics
downvote count: 0
has title: Insert n amount of values to an empty doubly linked list (pseudocode)
has comment: http://stackoverflow.com/comment/91984450
favorite count: 0
has comment: http://stackoverflow.com/comment/91986301
tagged with: doubly-linked-list

http://stackoverflow.com/comment/91920576
comment on: http://stackoverflow.com/a/52475826
score: 0
type: AnswerComment
type: Comment
has text: @EricLopez-Reyes There is no need for `val`. I have edited my answer.

http://stackoverflow.com/q/52466741
has comment: http://stackoverflow.com/comment/91875273
score: -3
downvote count: 3
possible better answer: http://stackoverflow.com/a/52467723
has answer: http://stackoverflow.com/a/52467723
has answer: http://stackoverflow.com/a/52504251
has body: I need to call an API from android application but can't get it working.. Same py code works fine.. How to port the following python code in Android using Retrofit? import requests import json head = {'X-API-KEY':'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'} args = {'item1', 'value'} c = requests.post("http_link",data=json.dumps(args),headers=head) print(c.text) If solution is available without Using the retrofit library please do share. I tried to implement the above python code in the application using the retrofit library in the following way... Interface : public interface Safety_aws_api { String BASE_URL = "httplink"; @Headers("{X-API-KEY:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}") @POST("Apisender") Call&lt;ModelApiResponse&gt; getApi(@Body Model_ApiCaller model_apiCaller); } Model Classes : public class Model_ApiCaller { public String getApiName() { return apiName; } public void setApiName(String apiName) { this.apiName = apiName; } private String apiName; public Model_ApiCaller( String apiName){ this.apiName = apiName; } public Model_ApiCaller(){ } } public class ModelApiResponse { private String types, Api; public String getTypes() { return types; } public void setTypes(String types) { this.types = types; } public String getApi() { return Api; } public void setApi(String api) { Api = api; } } Helper class : public class RetroHelper { private static Retrofit retrofit = new Retrofit.Builder() .baseUrl(Safety_aws_api.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); public static Safety_aws_api api = retrofit.create(Safety_aws_api.class); } Calling Function : private void getCodes( Model_ApiCaller model_apiCaller) { Call&lt;ModelApiResponse&gt; call = RetroHelper.api.getApi(model_apiCaller); call.enqueue(new Callback&lt;ModelApiResponse&gt;() { @Override public void onResponse(Call&lt;ModelApiResponse&gt; call, Response&lt;ModelApiResponse&gt; response) { tv_sample_data.setText( response.body().getApi()); } @Override public void onFailure(Call&lt;ModelApiRespo…
has comment: http://stackoverflow.com/comment/91877085
type: AnsweredQuestion
tagged with: java
type: Question
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/91875348
accepted answer: http://stackoverflow.com/a/52504251
favorite count: 0
has comment: http://stackoverflow.com/comment/91895700
has title: Sending POST request in Android ( Java) using Retrofit,.. working similar to following python code
tagged with: retrofit
tagged with: android
tagged with: python

http://stackoverflow.com/q/52461244
has body: I'm new to Amazon's Boto3 API. I created a basic diagram of my sample architecture shown below, with an ELB, 4 instances, 2 subnets and and 2 target groups in 2 different Availability Zones (2 instances in each target group). I know how to create an EC2 instance, a target group, subnets, and an ELB. But what ELB functions to use, is not clear to me. How I can attach the ELB to other components? Basically, how to add instances to the ELB? I'm not sure what next steps and functions are needed now. Here is my simple code so far: def create_load_balancer(load_balancer_name, vpcid, subnets, security_group): command = "aws elbv2 create-load-balancer --name " + load_balancer_name + " --subnets " + subnets + " --security-groups " + security_group+" --scheme internet-facing --type application" response = os.popen(command).read() // ....created 4 instances, subnets, and security groups ... //now ELB: #Load Balancer elb = boto3.client('elbv2') elb.create_target_group( Name='boto3-target-a', Protocol='HTTP', Port=80, VpcId=vpc.id) elb.create_target_group( Name='boto3-target-b', Protocol='HTTP', Port=80, VpcId=vpc.id) response = elb.create_load_balancer(Name="elb_boto3", Listeners=[ { 'Protocol': 'tcp', 'LoadBalancerPort': 80, 'InstanceProtocol': 'tcp', 'InstancePort': 80, 'SSLCertificateId': 'string'}, ], Subnets=[subnet1,subnet2], SecurityGroups=[sec_group], Scheme='internet-facing', Type='application')
tagged with: amazon-elb
type: Question
has comment: http://stackoverflow.com/comment/91873959
has title: How to create and attach a ELB properly in Boto3
tagged with: boto3
has comment: http://stackoverflow.com/comment/91867408
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/52462600
answer count: 1
downvote count: 0
favorite count: 0
tagged with: aws-elb
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/52462600
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/52469499
accepted answer of: http://stackoverflow.com/q/52468080
upvote count: 3
has comment: http://stackoverflow.com/comment/91881429
has body: Yes, this is exactly what mixins (or, more generally, classes) exist for. A class is supposed to encapsulate all the features associated with a specific concept or purpose (like your A and B, but also like your X and Y). I believe you're overthinking this. You probably know how to use classes, and mixins are really just classes that were given a fancy name because they require multiple inheritance in order to work. (Because mixins are not always complete classes capable of functioning by themselves; they're a collection of features that can be attached to other classes.) Classes are about separation of concerns. One concern - one class. Implement a class for each of the 4 concepts A, B, X and Y, and then combine them (with multiple inheritance) as you see fit. I strongly suggest reading What is a mixin, and why are they useful?. The (current) highest rated answer does a good job explaining that mixins exist precisely for situations like this.
score: 3
answers question: http://stackoverflow.com/q/52468080
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91881471

http://stackoverflow.com/q/52463652
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91873972
has comment: http://stackoverflow.com/comment/91873586
has title: What is the way to reference an image from within a bottle template?
has body: When within a bottle template file, what is the way to reference a static file? for example this one? &lt;body background='/static/img/digital.gif'&gt; Why the above relative file fails to load the image? How can i reference it correctly? If i try it as: &lt;body background="{{ static_file( 'digital.gif', root='./static/img' }}"&gt; The image also fail to render. Why Bottle fail to render the image even if no 'static_file' function is used?
favorite count: 0
linked to: http://stackoverflow.com/q/24739925
has answer: http://stackoverflow.com/a/52468934
upvote count: 1
tagged with: python
tagged with: bottle
possible better answer: http://stackoverflow.com/a/52469686
has comment: http://stackoverflow.com/comment/91879031
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52469686
score: 1
has comment: http://stackoverflow.com/comment/91878477
type: Question
accepted answer: http://stackoverflow.com/a/52468934

http://stackoverflow.com/q/52524978
has body: I'm very new to pandas sorry for not making much sense. I have a sense that groupby by the category but, I am not sure how to run functions within groupby. I want to find the dates from a given row in Date1 and see if any dates(in date2) of the same id is within 7 days. I thought about splitting date1 and date2 by doing but i'm not sure where to go from there. g1 = df'Category', 'Date1' g2 = df'Category', 'Date2' dif = pd.Timedelta(7, unit='D') df['isDateWithin7Days'] = np.where((g1['Category'] == g2['Category'])(df['Date1'] &gt; g2['Date2']-dif, True, False)) I get this error ValueError: operands could not be broadcast together with shapes (50537,) (3,) df1: category date1 date2 blue 1/1/2018 blue 1/2/2018 blue 1/5/2018 blue 2/1/2018 green 1/3/2018 green 1/1/2018 red 12/1/2018 red 11/1/2018 Expected results: category date1 date2 isDateWithin7Days? EarliestDate? blue 1/1/2018 True 1/2/2018 blue 2/1/2018 False 0 green 1/3/2018 False 0 red 12/1/2018 False 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52525607
type: Question
has title: how can i get compare two date columns with the same category in pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91991194
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91991979
tagged with: group-by
has answer: http://stackoverflow.com/a/52525607
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/52511733
has answer: http://stackoverflow.com/a/52511981
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52511895
accepted answer: http://stackoverflow.com/a/52511794
type: Question
has answer: http://stackoverflow.com/a/52511895
has answer: http://stackoverflow.com/a/52511794
score: 0
answer count: 3
has body: print("What would you like to do:\n1. Enter new information\n2. House- based statsitics\n3. Specific Criteria statistics") while True: try: option = input("Enter 1 2 or 3: ") except ValueError: option = input("Enter 1 2 or 3: ") if option &lt; 1 and option &gt; 3: option = input("Enter 1 2 or 3: ") else: break print(option) I'm trying to make sure my input is between 1 to 3, when I do this I'll get a TypeError, but if I change it to int(option = input("Enter 1 2 or 3: ")) it will return an error if a string is entered.
tagged with: validation
has title: Validating input and checking if it's in a range
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/91963395

http://stackoverflow.com/q/52490719
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/91922312
score: 1
has comment: http://stackoverflow.com/comment/91923620
has comment: http://stackoverflow.com/comment/91923210
linked to: http://stackoverflow.com/q/29525808
has body: I'm currently trying to build a small flask app in python which takes in a csv via pandas and paginates the results. I've already finished the process of importing the dataset with pandas, converting it to a list of dictionaries and paginating the results into a table using flask_paginate. Now, I'd like to extend this code to allow querying of terms in the dataset for example (show and paginate all results where 'Customer Name' contains 'Barry'). I'm aware ill need to use an input box and process a post request but I am very unsure of how to wire it all together in the index route. Any help would be greatly appreciated thanks. Code for app.py from flask import Flask, render_template from flask_paginate import Pagination, get_page_args import pandas app = Flask(__name__) app.debug = True df = pandas.read_csv('static/superstore.csv') data = df.to_dict(orient = 'records') def get_users(offset=0, per_page=20): return data[offset: offset + per_page] @app.route('/') def index(): page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(data) pagination_users = get_users(offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template('index.html', data=pagination_users, page=page, per_page=per_page, pagination=pagination) Code for index.html flask-bootstrap example Pagination Example Order ID Order Date Profit Unit Price Order Quantity Customer Name Region {% for item in data %} {{ item['Order ID'] }} {{ item['Order Date'] }} {%if item['Profit'] > 0%} {{ item['Profit'] }} {%else%} {{ item['Profit'] }} {%endif%} {{ item['Unit Price'] }} {{ item['Order Quantity'] }} {{ item['Customer Name'] }} {{ item['Region'] }} {% endfor %} {{ pagination.links }} Screenshot: Screenshot of localhost:5000/
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91923458
has comment: http://stackoverflow.com/comment/91923109
tagged with: flask
linked to: http://stackoverflow.com/q/12433304
has title: Flask pagination combined with query
tagged with: pandas
tagged with: python
favorite count: 0

duplicates
tags question: http://stackoverflow.com/q/52432919
tags question: http://stackoverflow.com/q/52468552
type: Tag
tags question: http://stackoverflow.com/q/52579274
tags question: http://stackoverflow.com/q/52492949
tags question: http://stackoverflow.com/q/52488961
tags question: http://stackoverflow.com/q/52452286
tags question: http://stackoverflow.com/q/52509491
tags question: http://stackoverflow.com/q/52539318
tag name: duplicates

linux-mint
type: Tag
tags question: http://stackoverflow.com/q/52459159
tag name: linux-mint
tags question: http://stackoverflow.com/q/52465660

http://stackoverflow.com/q/52587991
has comment: http://stackoverflow.com/comment/92111630
type: Question
has body: This is my JSON file: { "pass": "test", "users": "joel" } And this is my Python code: with open("auth.json", "r") as f: data = json.load(f) This is error I am getting: Traceback (most recent call last): File "W:/ComputerScienceDiceGame/dice.py", line 21, in data = json.load(f.read()) File "C:\Python33\lib\json__init__.py", line 268, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read' I know this is probably easy but I can't find the root cause of the issue.
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/92111748
downvote count: 4
linked to: http://stackoverflow.com/q/20199126
upvote count: 0
has comment: http://stackoverflow.com/comment/92111251
has title: TypeError while loading JSON in Python
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: -4
has comment: http://stackoverflow.com/comment/92111257
has answer: http://stackoverflow.com/a/52588196

http://stackoverflow.com/comment/91918734
score: 0
comment on: http://stackoverflow.com/q/52462747
type: Comment
type: QuestionComment
has text: What language is this ?

http://stackoverflow.com/q/52581428
score: 1
has comment: http://stackoverflow.com/comment/92098049
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: How to do urlconf in django 2.0+
has body: I have created a view at example.views.py, and here is my urls.py file: from django.urls import path urlpatterns = [ path('/', example.views.index, name='index'), ] However, when I run django's runserver, I get the following error: path('/', example.views.index, name='index'), NameError: name 'example' is not defined What do I need to do to fix this? Quoting the view doesn't help either.
type: AnsweredQuestion
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/52581498
type: Question
has comment: http://stackoverflow.com/comment/92098445
tagged with: django-urls
accepted answer: http://stackoverflow.com/a/52581498
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91983372
type: Comment
type: QuestionComment
has text: You will do something along the lines of `self.ids.oftbutton.text = new_text` in your Python logic (where `self` refers to the screen instance that your button is a child of)
comment on: http://stackoverflow.com/q/52521654
score: 0

data-structures
tags question: http://stackoverflow.com/q/52521728
tags question: http://stackoverflow.com/q/52453028
tag name: data-structures
tags question: http://stackoverflow.com/q/52511590
tags question: http://stackoverflow.com/q/52574777
tags question: http://stackoverflow.com/q/52490250
tags question: http://stackoverflow.com/q/52562415
tags question: http://stackoverflow.com/q/52505438
tags question: http://stackoverflow.com/q/52577109
type: Tag
tags question: http://stackoverflow.com/q/52584656

http://stackoverflow.com/comment/91864151
type: Comment
comment on: http://stackoverflow.com/a/52460802
has text: So basically for every column (`400`, `401`, etc) you need to generate the predictions for each value of `depth`, using the slope and intercept for each of those columns, yes?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52497559
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52495742
has body: Try deleting /etc/resolv.conf Backup the file before deleting it.
score: 1

http://stackoverflow.com/comment/91919950
type: Comment
comment on: http://stackoverflow.com/a/52489374
has text: @DYZ I support you, whatever you say, i don't know a everything :-)
score: 0
type: AnswerComment

http://stackoverflow.com/a/52554259
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52554197
type: Answer
answers question: http://stackoverflow.com/q/52554197
has body: The concatenation k+str(i) is repeated for some combinations of k and i. Dictionary keys must be unique. This causes existing keys to be overwritten. I suggest you use tuple keys instead which, in addition, aligns data structure with your logic: for k, v in text_list.iteritems(): for i in range(100): data_item[(k, i)] = v
upvote count: 5
score: 5

http://stackoverflow.com/comment/91830113
type: AnswerComment
type: Comment
has text: hmmm, I see typo in `s1.add(s2).where(s2.gt(0), 0)`, I think you want `s1.add(s2.where(s2.gt(0), 0))`
comment on: http://stackoverflow.com/a/52443640
score: 0

http://stackoverflow.com/comment/92429290
comment on: http://stackoverflow.com/q/52535488
has text: @Chris Running with the default SESSION_ENGINE on Standard Dynos
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91877353
comment on: http://stackoverflow.com/q/52467743
has text: Is the question purely theoretical, or you found any use to this kind of construct? @Makoto it does not depend on the previous use / definition of `foo1`.
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/91813600
comment on: http://stackoverflow.com/q/52434934
type: Comment
type: QuestionComment
score: 0
has text: m1[0] is m1[1] → True; m2[0] is m2[1] → False. Now I see the problem. Thank you.

http://stackoverflow.com/comment/91887977
score: 0
type: Comment
type: QuestionComment
has text: Check this question : https://stackoverflow.com/questions/16255496/format-negative-integers-in-twos-complement-representation
comment on: http://stackoverflow.com/q/52473023

http://stackoverflow.com/comment/91908859
type: Comment
type: QuestionComment
has text: Is there any way this search can be made NOT CASE SENSITIVE????
comment on: http://stackoverflow.com/q/52432675
score: 0

http://stackoverflow.com/comment/92062759
has text: I will note there's at least one use case for having a dynamic application serve static files: when you need access control over them. But in this case, the endpoint is actually dynamic, despite the *content* being static. The endpoint has to access a user store, allow users to log in/out, and check the privileges of the user every time a request is made.
comment on: http://stackoverflow.com/q/52559079
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91870940
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52460039
type: AnswerComment
has text: there is no reason. As i am beginner thats the way i learnt ;)

header
type: Tag
tags question: http://stackoverflow.com/q/52495373
tags question: http://stackoverflow.com/q/52552401
tag name: header

http://stackoverflow.com/a/52485016
downvote count: 0
has comment: http://stackoverflow.com/comment/91911521
accepted answer of: http://stackoverflow.com/q/52484958
upvote count: 2
answers question: http://stackoverflow.com/q/52484958
has comment: http://stackoverflow.com/comment/91911556
type: AcceptedAnswer
has body: You can redefine your index as new_df = petrol[(petrol_attrib&gt;Lower_Inner_Fence) &amp; (petrol_attrib&lt;Upper_Inner_Fence)] new_df.index=range(0,len(petrol)) #you can define your range as required OR new_df = petrol[(petrol_attrib&gt;Lower_Inner_Fence) &amp; (petrol_attrib&lt;Upper_Inner_Fence)].reset_index(inplace=True,drop=True)
type: Answer
score: 2

http://stackoverflow.com/comment/92085350
type: QuestionComment
has text: ok goal here is to keep interface to a system simple for user and it should not be rigid.
comment on: http://stackoverflow.com/q/52574433
score: 0
type: Comment

http://stackoverflow.com/comment/91917885
comment on: http://stackoverflow.com/q/52488269
score: 0
type: Comment
has text: @vash_the_stampede yes
type: QuestionComment

http://stackoverflow.com/q/52443621
favorite count: 0
has answer: http://stackoverflow.com/a/52444004
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 1
type: Question
has body: I have installed xlrd successfully, however, on attempting to use a command of xlrd: xlrd.open_workbook('datafile.xls') I get the following error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'xlrd' is not defined I cannot understand this error and how to rectify it.
upvote count: 2
tagged with: xlrd
has comment: http://stackoverflow.com/comment/91830202
has title: Cannot figure out this error in python 3Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'xlrd' is not defined
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/19934248

http://stackoverflow.com/q/52474645
type: Question
has comment: http://stackoverflow.com/comment/91898121
has comment: http://stackoverflow.com/comment/91891714
downvote count: 0
possible better answer: http://stackoverflow.com/a/52502597
has comment: http://stackoverflow.com/comment/91898575
linked to: http://stackoverflow.com/q/42592234
has comment: http://stackoverflow.com/comment/91897183
accepted answer: http://stackoverflow.com/a/52480354
linked to: http://stackoverflow.com/q/10948589
has body: My goal is to detect the characters on images of this kind. I need to improve the image so that Tesseract does a better recognition, probably by doing the following steps: Rotate the image so that the blue rectangle is horizontal [Need help on this] Crop the image according to the blue rectangle [Need help on this] Apply a thresholding filter and a gaussian blur Use Tesseract to detect the characters img = Image.open('grid.jpg') image = np.array(img.convert("RGB"))[:, :, ::-1].copy() # Need to rotate the image here and fill the blanks # Need to crop the image here # Gray the image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Otsu's thresholding ret3, th3 = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Gaussian Blur blur = cv2.GaussianBlur(th3, (5, 5), 0) # Save the image cv2.imwrite("preproccessed.jpg", blur) # Apply the OCR pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe' tessdata_dir_config = r'--tessdata-dir "C:/Program Files (x86)/Tesseract-OCR/tessdata" --psm 6' preprocessed = Image.open('preproccessed.jpg') boxes = pytesseract.image_to_data(preprocessed, config=tessdata_dir_config) Here is the output image I get which is not perfect for the OCR: OCR problems: The blue rectangle is sometimes recognized as characters, this is why I would like to crop the image Sometimes Tesseract recognizes the characters on a line as a word (GCVDRTEUQCEBURSIDEEC) and some other times as individual letters. I would like it to be always a word. The little pyramid at the bottom right is recognized as a character Any other suggestions to improve the recognition are welcome
tagged with: ocr
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52480354
tagged with: python
tagged with: computer-vision
has title: Improve a picture to detect the characters within an area
has answer: http://stackoverflow.com/a/52502597
tagged with: opencv
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52475050
upvote count: 3
has answer: http://stackoverflow.com/a/52484357

http://stackoverflow.com/a/52510778
type: Answer
has comment: http://stackoverflow.com/comment/91963048
accepted answer of: http://stackoverflow.com/q/52510752
has comment: http://stackoverflow.com/comment/91961758
upvote count: 1
has comment: http://stackoverflow.com/comment/91963106
has comment: http://stackoverflow.com/comment/91961875
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91963120
has body: I think need merge with default inner join: brands = pd.DataFrame({ 'Person': ['dave', 'mike', 'sall', 'doug'], 'Car Brand': ['Kia', 'Ford', 'Ford', 'BMW'] }) my_dataframe = pd.DataFrame({ 'Brand':['Toyota','Toyota','BMW', 'BMW', 'BMW', 'Ford'], 'Speeds':[40,50,20,10,30,40], 'Colour':list('abcdef') }) print (my_dataframe) Brand Speeds Colour 0 Toyota 40 a 1 Toyota 50 b 2 BMW 20 c 3 BMW 10 d 4 BMW 30 e 5 Ford 40 f d = {'Car Brand':'Brand'} df = brands.rename(columns=d).merge(my_dataframe, on='Brand') print (df) Person Brand Speeds Colour 0 mike Ford 40 f 1 sall Ford 40 f 2 doug BMW 20 c 3 doug BMW 10 d 4 doug BMW 30 e If need list of dictionaries: my_list = df.to_dict(orient='records')
answers question: http://stackoverflow.com/q/52510752

http://stackoverflow.com/q/52436558
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52436888
has answer: http://stackoverflow.com/a/52436638
tagged with: python
upvote count: 24
answer count: 4
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/20528328
has body: With a datetime index to a Pandas dataframe, it is easy to get a range of dates: df[datetime(2018,1,1):datetime(2018,1,10)] Filtering is straightforward too: df[ (df['column A'] = 'Done') &amp; (df['column B'] &lt; 3.14 )] But what is the best way to simultaneously filter by range of dates and any other non-date criteria?
has answer: http://stackoverflow.com/a/62292662
has answer: http://stackoverflow.com/a/52436991
score: 24
type: Question
has title: Pandas filtering with datetime index

http://stackoverflow.com/q/52534202
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/52184478
tagged with: python
has comment: http://stackoverflow.com/comment/92013959
upvote count: 3
has answer: http://stackoverflow.com/a/55485332
has comment: http://stackoverflow.com/comment/92007763
tagged with: tensorflow
type: Question
score: 3
has comment: http://stackoverflow.com/comment/92010303
has title: Keras backend (tensorflow) vs Keras
has body: I would like to custom a Keras loss function but I do not really understand something. If I use tensorflow as a backend for Keras, do I need to use functions from keras.backend or can I use functions directly from tensorflow. I only see posts where people are using functions from keras.backend but not from tensorflow (even if tensorflow has much more functions). Are there reasons to do so? For a toy example : from keras import backend as K import tensorflow as tf def loss_keras(y_true, y_pred): square_error = K.square(y_pred - y_true) loss = K.mean(square_error) return loss def loss_tf(y_true, y_pred): square_error = tf.squared_difference(y_pred, y_true) loss = tf.reduce_mean(square_error) return loss Both of these functions work well but one is using directly tensorflow and the other is using keras.backend functions. I know that this is a silly example but when you want to do more complicated stuff, I thought that using tensorflow would be easier than keras functions as there are more functions available
answer count: 1
downvote count: 0
tagged with: keras

http://stackoverflow.com/a/52549710
score: 1
has body: How about using a kernel with shape (3, 3, 1) instead (3, 3)? kernel2d = np.ones((3, 3)) conv2d = lambda x: convolve(x, kernel2d, mode="wrap") result2d = xr.apply_ufunc(conv2d, da[:, :, 0]) kernel3d = np.ones((3, 3, 1)) conv3d = lambda x: convolve(x, kernel3d, mode="wrap") result3d = xr.apply_ufunc(conv3d, da) (result2d == result3d[:, :, 0]).all() # -&gt; True Another option is to use vectorization logic in xr.apply_ufunc, which may be closer to what you tried to do kernel = np.ones((3, 3)) conv = lambda x: convolve(x, kernel, mode="wrap") result = xr.apply_ufunc(conv, da, input_core_dims='x', 'y', output_core_dims='x', 'y', vectorize=True) (result2d == result.transpose('x', 'y', 'z')).all() # --&gt; True This option is only prepared for convenience and therefore it might be much slower than the first one where the calculation is vectorized.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52529152
type: Answer
has comment: http://stackoverflow.com/comment/92057077
upvote count: 1
answers question: http://stackoverflow.com/q/52529152

http://stackoverflow.com/comment/91862786
has text: 1) This code has syntax errors. 2) It is not clear what you are asking
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52460389

http://stackoverflow.com/comment/92008603
score: 1
has text: Your explanation of what you're trying to do assumes too much context that may be obvious to you, but to anyone else reading is completely lost. If you want to get the name of an object's class, use `self.__class__.__name__`. If you just want the name of a class by itself, look at the `__name__` attribute of the class like `A.__class__` (this is exactly the same as doing `self.__class__.__name__` in a method on an instance of that class; `self.__class__` is just `A` itself).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52533844

k-means
tags question: http://stackoverflow.com/q/52522050
type: Tag
tags question: http://stackoverflow.com/q/52577420
tag name: k-means
tags question: http://stackoverflow.com/q/52556885
tags question: http://stackoverflow.com/q/52514645

http://stackoverflow.com/a/52453937
downvote count: 0
has body: I'd go with: import numpy as np import pandas as pd r = np.random.random_sample((5,)) data=pd.Series(r).quantile(q = np.linspace(0,1,11)) print(*data.index,'\n', *data)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52453840
score: 1

http://stackoverflow.com/q/52507548
has title: Access a namedtuple from subclass
answer count: 0
has body: I am new to python and I am trying to use a namedTuple I have in my base class from my subclass however I am not having any luck from collections import namedtuple class BaseExample(object): User = namedtuple('User', ['username', 'password']) job_employer_1 = User() job_employer_2 = User() job_seeker = User() class Example(BaseExample): job_employer = User() In my Example class I have an error for the User() which is as follows Unresolved reference 'User' How would I access it?
type: Question
has comment: http://stackoverflow.com/comment/91959708
tagged with: tuples
score: 0
has comment: http://stackoverflow.com/comment/91955528
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91957629
has comment: http://stackoverflow.com/comment/91959785
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52581439
downvote count: 0
has comment: http://stackoverflow.com/comment/92098141
score: 1
has body: I am looking for the earliest date in col2 that is within 7 days from dates in col1 df1: category date1 date2 blue 1/1/2018 blue 1/2/2018 blue 1/5/2018 blue 2/1/2018 green 1/3/2018 green 1/8/2018 red 12/1/2018 red 11/1/2018 red 12/5/2018 Expected results: category date1 date2 isDateWithin7Days? EarliestDate? blue 1/1/2018 True 1/2/2018 blue 2/1/2018 False 0 green 1/3/2018 False 1/8/2018 red 12/1/2018 False 12/5/2018 With much help, I have the code to return TRUE and FALSE if there are dates with 7 days. As I understand the .between() method, that it only returns boolean values. How can I have it to return a date also? df['date1'] = pd.to_datetime(df['date1'], format = '%m-%d-%y') df['date2'] = pd.to_datetime(df['date2'], format = '%m-%d-%y') df1 = df.dropna(subset = ['date1']).drop(columns = ['date2']) df2 = df.dropna(subset = ['date2']).drop(columns = ['date1']) df3 = df1.merge(df2, on = 'category') df3['date2'].between(df3['date1'] - pd.Timedelta(days=7), df3['date1'] + pd.Timedelta(days=7)) df3['isDateWithin7Days?'] = df3['date2'].between(df3['date1'] - pd.Timedelta(days=7), df3['date1'] + pd.Timedelta(days=7)) df3 = df3.groupby(['category', 'date1'])['isDateWithin7Days?'].sum().reset_index() df3['isDateWithin7Days?'] = np.where(df3['isDateWithin7Days?'] &gt; 0, True, False)
favorite count: 0
type: Question
tagged with: python
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52581743
has comment: http://stackoverflow.com/comment/92235524
tagged with: group-by
accepted answer: http://stackoverflow.com/a/52581743
tagged with: date
tagged with: pandas
type: AnsweredQuestion
has title: how can I get the earliest date from col2 that is within 7 days of col1 with the same category?

http://stackoverflow.com/comment/91984483
comment on: http://stackoverflow.com/q/52522386
type: Comment
type: QuestionComment
has text: sure, in the first row, where 1 appears, the next unique value is 5, in the second row, the next unique (different) value is 2, in the third 2 is still the next unique value
score: 0

http://stackoverflow.com/comment/128478864
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52453247
has text: As it seems, one can not do that I suggested above. I have justed tested that, and an "TypeError: can only concatenate list (not "int") to list" appeared. Anyone can answer why? A solution to this error seems to be "l = l + [l[-1] + 1]", though.
score: 0

http://stackoverflow.com/q/52564624
has body: I always use mypy in my Python programs. What is the type (from typing) for immutable objects, the ones that could be used for a dictionary key? To put back into context, I want to write a class inherited from dictionary and I have the following code class SliceableDict(dict): def __getitem__(self, attr:Any) -&gt; Any: return super().__getitem__(attr) Type hints in that case are pretty useless, isn't it? Thanks
tagged with: python
tagged with: python-3.x
answer count: 2
tagged with: mypy
has title: What is the type of immutable object in Python (for mypy)
score: 8
has answer: http://stackoverflow.com/a/52564650
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52564646
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52564650
possible better answer: http://stackoverflow.com/a/52564646
upvote count: 8
type: Question

http://stackoverflow.com/q/52432051
favorite count: 0
has answer: http://stackoverflow.com/a/52432186
tagged with: python
tagged with: regex
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/52432186
type: Question
has title: Break Pandas series into multiple DataFrame columns based on string position
tagged with: pandas
has body: Given a Pandas Series with strings, I'd like to create a DataFrame with columns for each section of the Series based on position. For example, given this input: s = pd.Series(['abcdef', '123456']) ind = [2, 3, 1] Ideally I'd get this: target_df = pd.DataFrame({ 'col1': ['ab', '12'], 'col2': ['cde', '345'], 'col3': ['f', '6'] }) One way is creating them one-by-one, e.g.: df['col1'] = s.str[:3] df['col2'] = s.str[3:5] df['col3'] = s.str[5] But I'm guessing this is slower than a single split. I tried a regex, but not sure how to parse the result: pd.DataFrame(s.str.split("(^(\w{2})(\w{3})(\w{1}))")) # 0 # 0 [, abcdef, ab, cde, f, ] # 1 [, 123456, 12, 345, 6, ]
downvote count: 0
answer count: 1
tagged with: string

http://stackoverflow.com/comment/92052177
comment on: http://stackoverflow.com/q/52555918
score: 0
type: Comment
type: QuestionComment
has text: At the moment I run the tasks from the box they are on via shell_plus. by importing them, and then calling them directly for example: [1]: from tasks import run_single_test [2]: run_single_test('test_name')

http://stackoverflow.com/comment/91879798
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52468491
has text: @blue_note did you run this ? because I'm pretty sure you can't split a list object in your for statement

http://stackoverflow.com/q/52486851
tagged with: linux
tagged with: python
accepted answer: http://stackoverflow.com/a/52486991
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Filter /var/log/messages file data from target machine by date & time
has answer: http://stackoverflow.com/a/52486991
type: Question
has body: I am using below python script to filter data from /var/log/messages file of target machine by date &amp; time . But getting syntax error I am using python version 2.7 &amp; will not be able to upgrade python version #!/usr/bin/python import cgi, cgitb import os from subprocess import PIPE, Popen def cmdline(command): process = Popen( args=command, stdout=PIPE, shell=True ) return process.communicate()[0] out4=cmdline('sshpass -p redhat ssh -o ConnectTimeout=6 -o NumberOfPasswordPrompts=2 -o StrictHostKeyChecking=no -tt ricky@192.168.0.50 "echo redhat | sudo -S zless /var/log/messages* | grep \'^Sep 9\' | awk \' \$3 &gt; "09:30" &amp;&amp; \$3 &lt; "23:50" \' "') print(out4) Getting below output while executing this script Connection to 192.168.0.50 closed. awk: $3 &gt; 09:30 &amp;&amp; $3 &lt; 23:50 awk: ^ syntax error awk: $3 &gt; 09:30 &amp;&amp; $3 &lt; 23:50 awk: ^ syntax error [sudo] password for ricky: Anyone please help me to correct it
upvote count: 1
answer count: 1
tagged with: shell
favorite count: 0

http://stackoverflow.com/a/52454150
downvote count: 0
answers question: http://stackoverflow.com/q/52453821
type: Answer
has body: You can convert it to a dict indexed by name with values in tuples instead: d = {} with open('filename', 'r') as myfile: for line in myfile: _, name, *values = line.strip().split("\t") d[name] = values print(d) With your sample input, this will output: {'John': ('27', 'doctor', 'Chicago'), 'Nick': ('33', 'engineer', 'Washington')}
score: 1
upvote count: 1

http://stackoverflow.com/comment/91814485
type: Comment
has text: This is quite interesting and weird. Are those really spaces and not tabs? (You can *sort of* tell in Notepad by moving the cursor around to see if you ever seem to "jump" multiple spaces, but to really be sure, you need either a hex editor or a programmer's editor which can show different symbols to mark spaces versus tabs. Or you could use Python itself.) Also, where are you getting the CSV from? Does it *have to* be a CSV?
type: QuestionComment
comment on: http://stackoverflow.com/q/52433957
score: 0

http://stackoverflow.com/q/52490326
favorite count: 0
score: 8
tagged with: python-3.x
type: UnansweredQuestion
type: Question
has title: How to detect a self referencing list in python
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52490346
upvote count: 8
tagged with: python
has body: I have been trying to find a self-referencing loop in a list. I have referenced the list like this: a = [1, 2, None] a[2] = a What is the right way to detect this loop in python?

http://stackoverflow.com/q/52504347
has answer: http://stackoverflow.com/a/56148129
has answer: http://stackoverflow.com/a/52504535
tagged with: python-typing
favorite count: 0
has answer: http://stackoverflow.com/a/52512427
has comment: http://stackoverflow.com/comment/91970475
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52512686
has body: In Python documentation for typing & type hints we have the below example: Vector = List[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] Vector type alias clearly shows that type aliases are useful for simplifying complex type signatures. However, what about aliasing primitive data types? Let's contrast two basic examples of function signatures: URL = str def process_url(url: URL) -> URL: pass vs. def process_url(url: str) -> str: pass Version with type alias URL for primitive type str is: self-documenting (among others, now I can skip documenting returned value, as it should be clearly an url), resistant to type implementation change (I can switch URL to be Dict or namedtuple later on without changing functions signatures). The problem is I cannot find anyone else following such practice. I am simply afraid that I am unintentionally abusing type hints to implement my own ideas instead of following their intended purpose. Note from 2020-10 Python 3.9 introduces "flexible function and variable annotations", which allows to make annotations like: def speed_1(distance: "feet", time: "seconds") -> "miles per hour": pass def speed_2( distance: Annotated[float, "feet"], time: Annotated[float, "seconds"] ) -> Annotated[float, "miles per hour"]: pass Which renders aliasing data types for documenting purposes rather redundant! See: https://www.python.org/dev/peps/pep-0593/ https://realpython.com/python39-new-features/#annotated-type-hints
score: 23
downvote count: 1
upvote count: 24
has comment: http://stackoverflow.com/comment/91949214
type: Question
has title: Type hints: Is it a bad practice to alias primitive data types?
has answer: http://stackoverflow.com/a/77135606

http://stackoverflow.com/a/52540002
has body: You forgot to join the lines back together. Furthermore from a software design point of view, you are doing to much in the code fragment: it is better to encapsulate the functionalities in functions, like: def wordcase(word): if len(word) % 2 == 0: # even return word.lower() else: # odd return word.upper() Then we can even perform the processing "online" (as in line-per-line): while True: line = input() if not line: break else: print(' '.join(wordcase(word) for word in line.split()))
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52539861
downvote count: 0

http://stackoverflow.com/comment/91875999
score: 0
type: Comment
has text: @ΝικόλαοςΒέργος, see update. And yes 'GET' is default, but when you override it you should explicitly specify all methods you want to listen to. Because you literally override default value ('GET'). You can check bottle code here: https://github.com/bottlepy/bottle/blob/master/bottle.py#L884
comment on: http://stackoverflow.com/a/52466633
type: AnswerComment

http://stackoverflow.com/comment/92040584
type: QuestionComment
has text: I wanted to get string between `$startMsg$` and `$endMsg$` pairs
comment on: http://stackoverflow.com/q/52539808
score: 0
type: Comment

http://stackoverflow.com/comment/91843443
score: 0
comment on: http://stackoverflow.com/q/52449920
has text: Read [this](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html) as to why you shouldn't do this.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91868055
has text: @Christina yes, don't add 1 he must have assume that since you are doing +1 in your code you may want the index to be in that way.
type: AnswerComment
comment on: http://stackoverflow.com/a/52462805
type: Comment
score: 0

http://stackoverflow.com/q/52551909
has body: i have the following code in my Jupyter : import pandas as pd import quandl df=quandl.get('WIKI/GOOGL') print(df.head()) #upto here its working but here comes the error df=df'Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume', df['HL_PCT']=(df['Adj. High']-df['Adj. Low'])/df['Adj. Close'] df['PCT_change']=(df['Adj. Close']-df['Adj. Open'])/df['Adj. Open'] df=df'Adj. Close','HL_PCT','PCT_change','Adj.Volume' print(df.head()) this generates the following error: \local\programs\python\python37-32\lib\site-packages\ipykernel_launcher.py:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-11-c981ac0a05ec&gt; in &lt;module&gt;() 2 df['HL_PCT']=(df['Adj. High']-df['Adj. Low'])/df['Adj. Close']*100.0 3 df['PCT_change']=(df['Adj. Close']-df['Adj. Open'])/df['Adj. Open']*100.0 ----&gt; 4 df=df'Adj. Close','HL_PCT','PCT_change','Adj.Volume' 5 print(df.head()) c:\users\xyz\appdata\local\programs\python\python37-32\lib\site- packages\pandas\core\frame.py in __getitem__(self, key) 2680 if isinstance(key, (Series, np.ndarray, Index, list)): 2681 # either boolean or fancy integer index -&gt; 2682 return self._getitem_array(key) 2683 elif isinstance(key, DataFrame): 2684 return self._getitem_frame(key) c:\users\xyz\appdata\local\programs\python\python37-32\lib\site-packages\pandas\core\frame.py in _getitem_array(self, key) 2724 return self._take(indexer, axis=0) 2725 else: -&gt; 2726 indexer = self.loc._convert_to_indexer(key, axis=1) 2727 return self._take(indexer, axis=1) 2728 c:\users\xyz\appdata\local\programs\python\python37-32\lib\site-packages\pandas\core\indexing.py in _convert_to_indexer(self, obj, axi…
tagged with: jupyter
tagged with: artificial-intelligence
score: 2
has comment: http://stackoverflow.com/comment/92044938
downvote count: 0
tagged with: bigdata
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/92043485
type: AnsweredQuestion
has title: How to solve column not in index in python machhine learning
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52551972
accepted answer: http://stackoverflow.com/a/52551972
answer count: 1
has comment: http://stackoverflow.com/comment/92042840
favorite count: 0

http://stackoverflow.com/q/52556009
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/52556099
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92050841
has comment: http://stackoverflow.com/comment/92050580
has answer: http://stackoverflow.com/a/66210895
type: Question
has body: I'be trying to get an special input from the user and then save it in something like a dictionary. The input I have in mind is something like: &gt;&gt;&gt; id 1230 and I want it to be save in the form of: {"id":1230} or [(id,1230)] my problem is that there are actually two variables,one is a string and another is an integer,so somehow I have the get a line from the user,then the first and second parts should be separated and saved in one of the forms I mentioned. I know it has to do with the map() function and maybe a lambda expression is also used.once I used such a code to get two integers: x,y = map(int,input().split()) but I really don't know how to do it with a string and integer. Thank you very much
has answer: http://stackoverflow.com/a/52556109
has answer: http://stackoverflow.com/a/52556160
accepted answer: http://stackoverflow.com/a/52556160
has answer: http://stackoverflow.com/a/52556099
upvote count: 4
has title: map() function getting input
tagged with: function
has comment: http://stackoverflow.com/comment/92050669
has answer: http://stackoverflow.com/a/52556098
downvote count: 0
answer count: 7
score: 4
has answer: http://stackoverflow.com/a/52556100
has answer: http://stackoverflow.com/a/52556122
favorite count: 0
has comment: http://stackoverflow.com/comment/92050611
has comment: http://stackoverflow.com/comment/92050606
tagged with: input
tagged with: python

http://stackoverflow.com/comment/92036936
has text: add 'total_deals' and 'total_coupons' to values.example: `xxx.values('store_id','store_name','store_site','affiliate_url', 'total_deals', 'total_coupons').xxx`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52547247
type: Comment

http://stackoverflow.com/a/52503514
answers question: http://stackoverflow.com/q/52483503
type: Answer
score: 2
has body: The answer from here should work if you don't mind importing unittest, python mocking raw input in unittests. The main_test() part can then be removed from you projects and taken care of in the testing script. The "return_values" then correspond to you mock inputs.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92010079
accepted answer of: http://stackoverflow.com/q/52483503

http://stackoverflow.com/comment/91820202
type: Comment
score: 2
has text: whitespace is by default, so split() is enuff
type: AnswerComment
comment on: http://stackoverflow.com/a/52438634

http://stackoverflow.com/q/52576147
has body: I am trying to add a header to my existing csv file and there are already content in it. I am just wondering if there is any piece of code that could insert a header row at the top (such as ['name','age','salary','country'] without affecting the contents. Also this code is connected to API so I will run it multiple times. So just wondering if it is possible to detect whether a header exists to avoid multiple header lines. THank you and hope you all a good day!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92087935
type: Question
score: 0
has answer: http://stackoverflow.com/a/52577069
has title: how to add header to existing csv files using python without rewrite all the existing content
answer count: 1
tagged with: csv-write-stream
tagged with: python-2.7
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/52577069
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/91819887
score: 1
type: AnswerComment
has text: df = df.sort_values(['Value', 'Distance'], ascending=False) will sort both Value and Distance in descending. I guess the requirement is distance should be minimum. I will suggest one change - Pass the ascending parameter as a list [False,True] This will ensure value is max and distance is min
type: Comment
comment on: http://stackoverflow.com/a/52438223

http://stackoverflow.com/comment/91933219
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52495492
has text: @chris A - you are right. Thanks for the catch. Updated to the solution
type: AnswerComment

http://stackoverflow.com/q/52470351
score: 0
has body: I have following plot: which has been generated with this code: import pandas as pd import numpy as np import matplotlib.pyplot as plt ttc = pd.read_excel("../XLSX_Files/Baseline_Data.xlsx", sheet_name="Data")["TTC"] risks = col.OrderedDict( [("very low", 0), ("low", 0), ("medium-to-low", 0), ("medium", 0), ("high-to-medium", 0), ("high", 0), ("very high", 0)]) ---- Part in which risks get filled --- for x in risks: risk_distribution.append(float(risks[x]) / len(ttc)) x = np.arange(1, len(risks) + 1) y = np.arange(0.0, 0.4, 0.05) xticks = risks.keys() fig, ax = plt.subplots() plt.plot(x, risk_distribution) ax.set_ylim(0, 0.4) plt.show() So my actual question is: How can I add a risk heatmap as background (the same as this one: https://www.latestquality.com/risk-heat-map/) What I've tried to far: import seaborn as sns risk_heatmap = [ [1.2, 0.7, 0.7, 0.3, 0, 0, 0], [1.2, 0.7, 0.7, 0.7, 0.5, 0, 0], [1.2, 1.2, 1.2, 0.7, 0.7, 0, 0], [2.0, 1.2, 1.2, 1.2, 0.7, 0.7, 0], [2.0, 2.0, 2.0, 1.2, 1.2, 0.7, 0.7] ] ax = sns.heatmap(risk_heatmap, linewidth=0.5, cbar=False, cmap="RdYlGn") But this gives me some weird looking graph. Is there a possible way to add the heatmap without losing the y dimension?
accepted answer: http://stackoverflow.com/a/52470421
tagged with: python
tagged with: heatmap
tagged with: plot
type: Question
type: AnsweredQuestion
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52470421
tagged with: python-2.7
answer count: 1
has title: Heatmap as background of a Plot in matplotlib

http://stackoverflow.com/comment/91969637
type: QuestionComment
comment on: http://stackoverflow.com/q/52514920
has text: @Igle hi i have added the codes i have tried
score: 0
type: Comment

http://stackoverflow.com/comment/91843569
score: 0
type: Comment
type: QuestionComment
has text: Are you sure you want to use `&`, not `and`?
comment on: http://stackoverflow.com/q/52449995

http://stackoverflow.com/comment/92067997
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52564813
has text: `params` should be a dict just like `headers`. And the URL looks like it is missing `.format(uuid=...)`.
score: 2

http://stackoverflow.com/q/52466496
has answer: http://stackoverflow.com/a/52474017
has body: I created some really trivial script to just open browser with specific URL it looks like this: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get("http://www.python.org") Once I execute this with command python /path/to/file.py I get an error: Traceback (most recent call last): File "/home/pi/tmp/test.py", line 4, in &lt;module&gt; driver = webdriver.Chrome() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 75, in __init__ desired_capabilities=desired_capabilities) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 251, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 320, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally (chrome not reachable) (The process started from chrome location /usr/bin/chromium is no longer running, so ChromeDriver is assuming that Chrome has crashed.) (Driver info: chromedriver=2.40,platform=Linux 4.14.69-v7+ armv7l) It seems like I run out of memory or idk. Any idea what could be wrong?
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/50027278
type: Question
linked to: http://stackoverflow.com/q/51720561
tagged with: raspberry-pi
upvote count: 1
favorite count: 0
has title: selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start with Selenium and Chrome on RaspberryPi
answer count: 1
tagged with: chromium
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/91880863
type: UnansweredQuestion
tagged with: selenium
tagged with: python

http://stackoverflow.com/comment/91845346
has text: @KaranM I could try and help you better, but there are too many unknowns for me in your code. Please explain the format of the match. `\S+` just matches 1+ non-whitespace chars, but you are looking for `-` and `.` there, why?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52448475

http://stackoverflow.com/q/52574514
downvote count: 0
has body: I'm very newbie to python, when I was installing packages through pip3, I messed up with "sudo pip3" and "pip3" (I didn't know the difference that time). Recently I want to remove all the packages installed before, I have tried pip3 freeze &gt; rquirements.txt pip3 uninstall -r requirements.txt -y and I get Cannot uninstall 'apturl'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall than I tried to add sudo with -H flag sudo -H pip3 uninstall -r requirements.txt -y this time I get lots of packages not uninstalled Not uninstalling apturl at /usr/lib/python3/dist-packages, outside environment /usr Not uninstalling asn1crypto at /usr/lib/python3/dist-packages, outside environment /usr Not uninstalling brlapi at /usr/lib/python3/dist-packages, outside environment /usr Not uninstalling certifi at /usr/lib/python3/dist-packages, outside environment /usr Not uninstalling chardet at /usr/lib/python3/dist-packages, outside environment /usr Not uninstalling command-not-found at /usr/lib/python3/dist-packages, outside environment /usr . . . I have no idea what happened, need some help
has title: how to remove all packages installed by pip when some of them are installed through sudo pip3 others not
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: uninstallation
tagged with: pip
tagged with: python
score: 2
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52579646

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/52562888

http://stackoverflow.com/comment/92081832
score: 0
type: Comment
has text: Alright I tried indenting the code and adding the break statement and it works but it is rolling the same dice value? Like it displays rolled a 4 5 times or rolled a 6 4 times and shows the score. Is it some error or just 'random'?
comment on: http://stackoverflow.com/a/52572651
type: AnswerComment

http://stackoverflow.com/a/52577001
has body: You can iterate it like this: def getIndex(b, desc): for i in range(len(b)): if b[0] is desc: return i for i in range(len(A)): A[i].append(B[getIndex(B, A[1])][1] + A[i][2]) Of course there must be some shortcuts such as lambda expressions, yield, etc. but this would be the foundational solution.
has comment: http://stackoverflow.com/comment/92089230
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52576867

http://stackoverflow.com/a/52572425
accepted answer of: http://stackoverflow.com/q/52458708
type: Answer
has body: Here is the solution after trying many things: if str(photo.path) == str(photo.file): return The above code will be true only if there was no new file uploaded during object update.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52458708

http://stackoverflow.com/comment/92097477
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52581057
has text: No, apply is not inherently faster. Pandas is really complicated in terms of what happens under the covers, but it won't be exploiting numpy in any way with your current approach.

http://stackoverflow.com/comment/91896508
comment on: http://stackoverflow.com/a/52477398
type: AnswerComment
has text: Thanks! Much appreciated. I'll give this a test run.
score: 0
type: Comment

http://stackoverflow.com/comment/119936213
type: QuestionComment
comment on: http://stackoverflow.com/q/52431372
score: 0
has text: How did this end up working with the labels?
type: Comment

http://stackoverflow.com/a/52443548
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52441372
has body: You have the right idea! The thing you're missing is that RGB values of 255,255,255 is white, not black. As well, the transparency "A" axis goes from 0 - 255, where 0 is opaque and 255 is completely transparent. Examples: If the RGBA values are (255,255,255,0), then you will see black. This is because the transparency is set to 0. If the RGBA values are (255,255,255,255), then you will see white. If the RGBA values are (135, 23, 53, 255), then you'll see dark red (your example in the code.) Small thing for visibility, consider setting a test patch rather than a test pixel, like so: self.world[20:40, 30:50, :] = [135, 23, 53, 128]
upvote count: 3
answers question: http://stackoverflow.com/q/52441372

http://stackoverflow.com/q/52447485
has comment: http://stackoverflow.com/comment/91839560
has title: Copying row from scrolled_window to clipboard
has comment: http://stackoverflow.com/comment/91839598
tagged with: python
has comment: http://stackoverflow.com/comment/91850355
has comment: http://stackoverflow.com/comment/91840454
has body: I'm trying to copy content of a row being displayed from a treeview, to use in a separate editor program. I found a potential solution using Tkinter and the clipboard_append() function, which seems to work within the original script, but does not modify the system clipboard and thus make the data available to the editor program. Obviously I am missing something and need at least a few hints. Using pyperclip seems like overkill for my needs, which are simply to lookup entries in a membership MySQL database with some 24K rows and copy a single selected row into an editor program.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91837967
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91856644
type: Question
has answer: http://stackoverflow.com/a/52459526
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52552264
has body: I have tried the following to convert the time to Indian time for testing. But got many errors. See what I tried til now: &gt;&gt;&gt; df = pd.read_csv("Real.csv",encoding='utf-16',index_col=0) &gt;&gt;&gt; df.tail(1).index Index(['2018.09.27 16:43:00'], dtype='object', name='Time') &gt;&gt;&gt; df.tail(1).index.tz_convert('Asia/Kolkata') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Index' object has no attribute 'tz_convert' &gt;&gt;&gt; df.index.tz_convert('Asia/Kolkata').tail(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Index' object has no attribute 'tz_convert' &gt;&gt;&gt; df.index.tz_localize('GMT').tz_convert('Asia/Kolkata').tail(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Index' object has no attribute 'tz_localize' Here is the sample csv: 2018.09.27 16:34:00,0.94259,0.94276,0.94253,0.94276,0.002,-0.004,-0.001,-0.001,-0.007,0.001,0.002,0.001 2018.09.27 16:35:00,0.94275,0.94275,0.94249,0.94253,0.002,-0.002,-0.001,0,-0.006,0.002,0,0.001 2018.09.27 16:36:00,0.94253,0.94259,0.94235,0.94241,0,-0.003,0,0,-0.005,-0.001,0.001,0.002 2018.09.27 16:37:00,0.94241,0.94258,0.94237,0.94256,0,-0.003,0,0.001,-0.005,0,0.001,0.001 2018.09.27 16:38:00,0.94256,0.94256,0.94238,0.94245,0.001,0,0.001,0.005,0.001,0.001,-0.002,-0.001 2018.09.27 16:39:00,0.94246,0.9426,0.9423899999999999,0.94254,0.001,0,-0.001,0.003,-0.001,0.002,-0.001,0 2018.09.27 16:40:00,0.94252,0.94275,0.94252,0.94274,0.002,0.001,0,0.003,0,0.003,-0.002,-0.001 2018.09.27 16:41:00,0.94274,0.94278,0.94265,0.94268,0.001,-0.002,-0.001,0.002,-0.001,0.002,0.001,-0.001 2018.09.27 16:42:00,0.94268,0.94285,0.94268,0.94272,0,-0.001,0.001,0.002,-0.002,0.002,0,-0.001 2018.09.27 16:43:00,0.94272,0.94282,0.9426600000000001,0.9428,0.001,-0.001,0.002,0.001,-0.002,0.002,0,0 I am trying to check if the last index, which is Time, is equal to the current time as pe…
accepted answer: http://stackoverflow.com/a/52553538
score: 0
has title: Checking if the last Time of CSV is current time or not using Pandas Python3
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/92044039
tagged with: python-3.x
linked to: http://stackoverflow.com/q/13866926
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/52553729
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/52553729
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92043950
type: Question
has answer: http://stackoverflow.com/a/52553538

http://stackoverflow.com/q/52572654
has title: UnboundLocalError, I am in an Intro class so i need it dumbed down as to how i go about fixing this error
type: Question
has answer: http://stackoverflow.com/a/52573314
has comment: http://stackoverflow.com/comment/93611877
has body: I get that the error is with getSales being refrenced before assignment but I do not understand how I fix that. I am a first semester into to programming class so I've read other questions with the same error but I cant grasp the concept of how it affects my code. I apologize that this is very much a repeat question. def main(): monthlySales = getSales() #call to get sales salesIncrease = getIncrease() #call to get sales increase storeAmount = storeBonus(monthlySales) #call to get the store bonus empAmount = empBonus(salesIncrease) #call to get the employee bonus printBonus = printBonus(storeAmount, empAmount) #call to print amounts #This function gets the monthly sales def getSales(): monthlySales = input('Enter the monthly sales $') monthlySales = float(monthlySales) return monthlySales #This function gets the percent of increase in sales def getIncrease(): salesIncrease = input('Enter percent of sales increase. For Example 4% should be entered as 4: ') salesIncrease = float(salesIncrease) salesIncrease = salesIncrease / 100 return salesIncrease #This function determines the storeAmount bonus def storeBonus(monthlySales): if monthlySales &gt;=110000: storeAmount = 6000 elif monthlySales &gt;=100000: storeAmount = 5000 elif monthlySales &gt;=90000: storeAmount = 4000 elif monthlySales &gt;= 80000: storeAmount = 3000 else: storeAmount = 0 return storeAmount #This function determines the empAmount bonus def empBonus(salesIncrease): if salesIncrease &gt;= 5: empAmount = 75 if salesIncrease &gt;= 4: empAmount = 50 if salesIncrease &gt;= 3: empAmount = 40 return empAmount #This function prints the bonus information def printBonus(storeAmount, empAmount): print 'The store bonus amount is $', storeAmount print 'The employee bonus amount is $', empAmount if storeAmount == 6000 and empAmount == 75: print 'Congrats! You have reached the highest bonus amounts possible!' #calls main main()
answer count: 1
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/92081833
has comment: http://stackoverflow.com/comment/92082211
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52520755
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52520342
type: AcceptedAnswer
type: Answer
has body: This is how it can be done. I tested using my folder files. Change it up for your needs. import os from os import walk path='D:\\files' keywords=['test','this'] for root, dirs, files in walk(path): for name in files: with open(os.path.join(root, name),'r') as f: data=f.read() data=data.lower() print(data)
answers question: http://stackoverflow.com/q/52520342
upvote count: 2
score: 1

http://stackoverflow.com/a/52527554
accepted answer of: http://stackoverflow.com/q/52527528
answers question: http://stackoverflow.com/q/52527528
type: AcceptedAnswer
score: 1
has comment: http://stackoverflow.com/comment/91994678
has body: You can just do this and this will break the loop for y or n while isPet_list_elem not in ('y','n'):
type: Answer
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/52465587
has comment: http://stackoverflow.com/comment/91873156
has title: Plotting contour in python
tagged with: matplotlib
has body: I have an np array of shape (15,2) When I meshgrid first and second dimension of this array and write a function of this array, and then plot using contour, the output is blank. I don't understand what's wrong. Please guide me. The code is: M=[[12.647,4.2439],[13.744,8.9295],[13.93,9.191 ],[16.223,12.452 ], [16.475 , 12.784 ], [16.535 , 12.813 ], [16.774 , 13.377 ], [16.949 , 13.465 ], [17.295 , 13.494 ], [17.329 , 13.613 ], [18.183 , 14.683 ], [19.055 , 14.871 ], [19.098 , 15.487 ], [21.798 , 16.23 ], [22.241 , 16.411 ]] x1,y1=np.meshgrid(M[:,0],M[:,1]) F=np.sqrt(x1**2 + y1**2) plt.contour(x1,y1,F) Here M is a np array of (15,2). Is the problem with the values of M?
has answer: http://stackoverflow.com/a/52465794
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91873063
has comment: http://stackoverflow.com/comment/91873090
tagged with: contour
upvote count: 0
accepted answer: http://stackoverflow.com/a/52465794
answer count: 1
score: -6
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91872987
downvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/comment/92058067
type: AnswerComment
score: 0
type: Comment
has text: I read that, but I was wondering if omitting that call means the deferred key is not created and thus the program could malfunction.
comment on: http://stackoverflow.com/a/52559642

http://stackoverflow.com/q/52566855
tagged with: data-fitting
has answer: http://stackoverflow.com/a/52573522
tagged with: distribution
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52573522
has comment: http://stackoverflow.com/comment/92077435
score: 1
has body: I am trying to do a lognorm distribution fit but the resulting paramter seem a bit odd. Could you please show me my mistake or explain to me if I am misinterpreting the parameters. import numpy as np import scipy.stats as st data = np.array([1050000, 1100000, 1230000, 1300000, 1450000, 1459785, 1654000, 1888000]) s, loc, scale = st.lognorm.fit(data) #calculating the mean lognorm_mean = st.lognorm.mean(s = s, loc = loc, scale = scale) The resulting mean is: 945853602904015.8. But this doesn't make any sense. The mean should be: data_ln = np.log(data) ln_mean = np.mean(data_ln) ln_std = np.std(data_ln) mean = np.exp(ln_mean + np.power(ln_std, 2)/2) Here the resulting mean is 1391226.31. This should be correct. Can you please help me with this topic? Best regards Norbi
upvote count: 1
tagged with: scipy
type: Question
tagged with: statistics
has title: Lognorm distribution fitting
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92079876
tagged with: python

http://stackoverflow.com/q/52490427
has title: 'UnicodeDecodeError' in Tweepy API
has comment: http://stackoverflow.com/comment/91921705
tagged with: twitter
linked to: http://stackoverflow.com/q/52339729
type: Question
score: 0
tagged with: api
answer count: 1
has body: Alright, so here's what I have: import tweepy import time #login credentials twitter account consumer_key = '------' consumer_secret = '-----' access_token = '-----' access_secret = '-----' #login auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) search_query = "I'm" user = api.me() print(user.name) max_tweets = 100 #reply for tweet in tweepy.Cursor(api.search, q=search_query).items(max_tweets): c=tweet.text.encode('utf8') c=c.replace("im ","") answer="@"+tweet.user.screen_name+" Hi " + c + ", I'm Dad!" print ("Reply:",answer) api.update_status(status=answer,in_reply_to_status_id=tweet.id) time.sleep(300) #every 5 minutes Now, the error I recieve is this: Traceback (most recent call last): File "C:\Python27\twitterbotdad.py", line 26, in &lt;module&gt; answer="@"+tweet.user.screen_name+" Hi " + c + ", I'm Dad!" UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 33: ordinal not in range(128) &gt;&gt;&gt; =================== Would anyone mind assisting me? I have been trying to fix this, but I am not getting anywhere.
has answer: http://stackoverflow.com/a/52569892
tagged with: python
tagged with: tweepy
tagged with: bots
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91923079

http://stackoverflow.com/a/52508700
has body: Use sep with \s for any spaces not only tabs, engine='python' for removing warning: df=pd.read_csv('dum.txt',engine='python',sep='\s') print(df) Output: Type T1 T2 T3 T4 T5 0 Tag Good Good Good Good Good 1 object1 1.1 2.1 3.1 4.1 5.1 2 object2 1.2 2.2 3.2 4.2 5.2 3 object3 1.3 2.3 3.3 4.3 5.3 4 object4 1.4 2.4 3.4 4.4 5.4 5 object5 1.5 2.5 3.5 4.5 5.5 6 object6 1.6 2.6 3.6 4.6 5.6 7 object7 1.7 2.7 3.7 4.7 5.7 8 object8 1.8 2.8 3.8 4.8 5.8 Or if want two rows of columns (i would not recommend because then it's hard to use): df=pd.read_csv('dum.txt',engine='python',sep='\s',header=[0,1]) print(df) Output: Type T1 T2 T3 T4 T5 Tag Good Good Good Good Good 0 object1 1.1 2.1 3.1 4.1 5.1 1 object2 1.2 2.2 3.2 4.2 5.2 2 object3 1.3 2.3 3.3 4.3 5.3 3 object4 1.4 2.4 3.4 4.4 5.4 4 object5 1.5 2.5 3.5 4.5 5.5 5 object6 1.6 2.6 3.6 4.6 5.6 6 object7 1.7 2.7 3.7 4.7 5.7 Otherwise default direct read_csv (like pd.read_csv('dum.txt')) will return: Type\tT1\tT2\tT3\tT4\tT5 0 Tag\tGood\tGood\tGood\tGood\tGood 1 object1\t1.1\t2.1\t3.1\t4.1\t5.1 2 object2\t1.2\t2.2\t3.2\t4.2\t5.2 3 object3\t1.3\t2.3\t3.3\t4.3\t5.3 4 object4\t1.4\t2.4\t3.4\t4.4\t5.4 5 object5\t1.5\t2.5\t3.5\t4.5\t5.5 6 object6\t1.6\t2.6\t3.6\t4.6\t5.6 7 object7\t1.7\t2.7\t3.7\t4.7\t5.7 8 object8\t1.8\t2.8\t3.8\t4.8\t5.8
has comment: http://stackoverflow.com/comment/91958601
type: Answer
has comment: http://stackoverflow.com/comment/91957668
downvote count: 1
score: 3
has comment: http://stackoverflow.com/comment/91958624
has comment: http://stackoverflow.com/comment/91957649
has comment: http://stackoverflow.com/comment/91958693
upvote count: 4
has comment: http://stackoverflow.com/comment/91957675
answers question: http://stackoverflow.com/q/52508642

http://stackoverflow.com/comment/111197500
has text: I'm confused, what are the pros/cons of `pickle vs np.save/z` etc?
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52444921

http://stackoverflow.com/q/52555877
answer count: 1
tagged with: text-files
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: list
has body: I'm trying to create a code with Python 3 to import text files to python, converting it to lists and then calculate something with it like average marks. Text file: number name subject1 subject2 subject3 subject4 subject5 1234567 Jun 5 7 0 6 4 3526435 Merie 5 5 7 0 0 2230431 Kaes 6 10 0 8 6 7685433 Endré 4 7 8 7 5 0364678 Ontoinette 0 2 8 8 8 1424354 Yerôme 7 9 0 5 0 4536576 Mamal 8 0 8 7 8 1256033 Eiana 0 0 0 0 0 5504657 Wetra 6 6 7 0 6 9676575 Aalika 0 6 0 0 8 0253756 Oamira 3 8 6 7 10
type: Question
tagged with: arrays
has title: Python | how do i make a program that calculates math
has answer: http://stackoverflow.com/a/52556023
score: 0
linked to: http://stackoverflow.com/q/21546739

http://stackoverflow.com/comment/91877274
comment on: http://stackoverflow.com/a/52467633
score: 0
type: AnswerComment
type: Comment
has text: OK i will change the port and let u know. I have already updated the fulfillment every time i get a new URL tunnel

http://stackoverflow.com/comment/91900261
has text: where have you saved this file?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52475446

http://stackoverflow.com/a/52558562
type: Answer
answers question: http://stackoverflow.com/q/52558060
has comment: http://stackoverflow.com/comment/92055829
has body: Since you are adding to the head of the list: def add(self, data): new_node = node(data) new_node.set_next(self.head) self.head = new_node That means your list is reversed. Therefore you have to do a reverse check during the merge: if L1.data &gt;= L2.data: full text: class node(): def __init__(self, data, next_node = None): self.data = data self.next_node = next_node def get_data(self): return self.data def get_next(self): return self.next_node def set_next(self, new_node): self.next_node = new_node class LinkList(object): def __init__(self, head = None): self.head = head def add(self, data): new_node = node(data) new_node.set_next(self.head) self.head = new_node def printlist(self): current_node = self.head while (current_node != None): print (current_node.get_data(), end = "-&gt;") current_node = current_node.get_next() print () def merge(L1, L2): temp = None if L1 is None: return L2 if L2 is None: return L1 if L1.data &gt;= L2.data: temp = L1 temp.next_node = merge(L1.next_node, L2) else: temp = L2 temp.next_node = merge(L1, L2.next_node) return temp def main(): list1 = LinkList() list1.add(10) list1.add(20) list1.add(30) print("list2: ", end=" " ) list1.printlist() list2 = LinkList() list2.add(11) list2.add(21) list2.add(51) print("list2: ", end=" " ) list2.printlist() list3 = LinkList() list3.head = merge(list1.head, list2.head) print("merge link list: ", end=" " ) list3.printlist() if __name__ == "__main__": main()
score: 0

http://stackoverflow.com/q/52491330
has body: Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name 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) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Count class UserSerializer(serializers.ModelSerializer): # name = serializers.StringRelatedField() # company_name = serializers.CharField() class Meta: model = User fields = '__all__' here is my views.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer I am getting api like this.. Here i am getting id instead of company_name. [ { "id": 1, "name": "soubhagya", "company_name": 1 }, { "id": 2, "name": "nihar", "company_name": 2 } ] But i am expecting output-- like this: [ { "id": 1, "name": "soubhagya", "company_name": "google" }, { "id": 2, "name": "nihar", "company_name": "facebook" } ] I am expecting my api like this. with company_name. And i wants to post the data from same api in rest fr…
has answer: http://stackoverflow.com/a/70645264
tagged with: python
has title: How to get foreignkey field name instead of id in django rest framework
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69542282
has answer: http://stackoverflow.com/a/52491357
downvote count: 0
has answer: http://stackoverflow.com/a/52491567
tagged with: django
score: 13
type: Question
has answer: http://stackoverflow.com/a/52491365
possible better answer: http://stackoverflow.com/a/52491567
upvote count: 13
answer count: 6
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/64389273
accepted answer: http://stackoverflow.com/a/52491357

http://stackoverflow.com/comment/92047912
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52552017
has text: @RémiBaudoux But be aware that this isn't very Pythonic. The next developer (or user of your library) might be very surprised at this behavior.

http://stackoverflow.com/a/52454805
upvote count: 1
has comment: http://stackoverflow.com/comment/91852362
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52454730
score: 1
has body: Check each column barring id in column 1 (df.iloc[:, 1:]) using the string accessor to see if it contains the letter a, and then use any along the rows (axis=1). Convert the boolean result to an integer (1 or 0). &gt;&gt;&gt; df.assign(contains_a=df.iloc[:, 1:].apply(lambda s: s.str.contains('a')).any(axis=1).astype(int)) id item1 item2 item3 contains_a 0 1 a b c 1 1 2 c d e 0 2 3 a e NaN 1 Too make this more general for multiple targets: targets = ['aa', 'a', 'b', 'c'] d = {'contains_{}'.format(target): df.iloc[:, 1:].apply(lambda s: s.str.contains(target)).any(axis=1).astype(int) for target in targets} &gt;&gt;&gt; df.assign(**d) id item1 item2 item3 contains_a contains_aa contains_b contains_c 0 1 a b c 1 0 1 1 1 2 c d e 0 0 0 1 2 3 a e NaN 1 0 0 0

http://stackoverflow.com/comment/91888825
has text: Use `==`. Dictionaries don't care about order and until recent versions, weren't meant to be ordered.
comment on: http://stackoverflow.com/q/52473178
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52491442
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52491492
tagged with: python-2.7
has body: I want to remove duplicated rows that values in column B and C after rounding them to 2 decimal places are equal import pandas as pd df = pd.DataFrame({"A":["f1", "f2", "f3", "f4"], "B":[1.2579,1.2586,1.7223,1], "C":[8.2579,8.2586,12.7223,14.0]}) A B C 0 f1 1.2579 8.2579 1 f2 1.2586 8.2586 2 f3 1.7223 12.7223 3 f4 1.0000 14.0000 Here, row 0 and 1 have the same value after rounding. Instead of creating column B_round and C_round to drop duplicates like this df['B_round'] = df['B'].values.round(2) df['C_round'] = df['C'].values.round(2) df = df.drop_duplicates(subset=['B_round', 'C_round'], keep='first') which I have to remove columns again df = df.drop(['B_round', 'C_round'], axis=1) A B C 0 f1 1.2579 8.2579 2 f3 1.7223 12.7223 3 f4 1.0000 14.0000 Because my real data is big. Is there a way to remove them without creating new set of columns?
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52491492
tagged with: python
has title: Pandas: drop duplicated rows with same "rounded" values without creating new columns
type: AnsweredQuestion

http://stackoverflow.com/a/52525083
has body: Based on the file snippet you provided, here is how you can replace those empty lines Pandas is storing as NaNs with a blank string. import numpy as np df = pd.read_csv("scedon_etoimo.csv") df = df.replace(np.nan, "", regex=True) This will allow you to do everything on the base Pandas DataFrame without reading through your file(s) more than once. That being said, I would also recommend preprocessing your data before loading it in as that is often times a much safer way to handle data in non-uniform layouts.
answers question: http://stackoverflow.com/q/52524500
type: Answer
score: 0

http://stackoverflow.com/q/52452857
has answer: http://stackoverflow.com/a/52454189
tagged with: turtle-graphics
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
linked to: http://stackoverflow.com/q/48289171
has comment: http://stackoverflow.com/comment/91849344
type: Question
has comment: http://stackoverflow.com/comment/91849217
has answer: http://stackoverflow.com/a/70142706
has comment: http://stackoverflow.com/comment/91849259
has comment: http://stackoverflow.com/comment/91849167
linked to: http://stackoverflow.com/q/1406145
score: 0
answer count: 2
has body: I am attempting to create a quick turtle display using Tkinter, but some odd things are happening. First two turtle windows are being created, (one blank, one with the turtles), secondly, any attempt of turning the tracer off is not working. This might be a simple fix but at the moment I cannot find it. Any help would be appreciated, Below is the code: import tkinter as tk import turtle window = tk.Tk() window.title('Top 10\'s') def loadingscreen(): canvas = tk.Canvas(master = window, width = 500, height = 500) canvas.pack() arc1 = turtle.RawTurtle(canvas) arc2 = turtle.RawTurtle(canvas) #clean up the turtles and release the window def cleanup(): turtle.tracer(True) arc1.ht() arc2.ht() turtle.done() #animate the turtles def moveTurtles(rangevar,radius,extent,decrease): for distance in range(rangevar): arc1.circle(-radius,extent = extent) arc2.circle(-radius,extent = extent) radius -= decrease #Set the turtle def setTurtle(turt,x,y,heading,pensize,color): turt.pu() turt.goto(x,y) turt.pd() turt.seth(heading) turt.pensize(pensize) turt.pencolor(color) #draw on the canvas def draw(): #set variables rangevar = 200 radius = 200 decrease = 1 extent = 2 #setup and draw the outline turtle.tracer(False) setTurtle(arc1,0,200,0,40,'grey') setTurtle(arc2,14,-165,180,40,'grey') moveTurtles(rangevar,radius,extent,decrease) #setup and animate the logo turtle.tracer(True) setTurtle(arc1,0,200,0,20,'black') setTurtle(arc2,14,-165,180,20,'black') moveTurtles(rangevar,radius,extent,decrease) #main program def main(): turtle.tracer(False) arc1.speed(0) arc2.speed(0) draw() cleanup() if __name__ == "__main__": try: main() except: print("An error occurred!!") loadingscreen() Essentially I am creating a Tk window, then a canvas, then two turtles, and then animating these turtles
has comment: http://stackoverflow.com/comment/91849150
has title: Turtle in Tkinter creating multiple windows

http://stackoverflow.com/comment/91938006
comment on: http://stackoverflow.com/q/52497430
has text: For proper functioning of pywin32 you need to run the post install script from the scripts folder (you can find this in your python installation directory). Open a command prompt with admin rights; navigate to the scripts folder and run: `pywin32_postinstall.py -install`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91845572
score: 0
comment on: http://stackoverflow.com/q/52451049
type: Comment
type: QuestionComment
has text: Also replace `model_fit = model.fit()` by `model.fit()`

http://stackoverflow.com/a/52518768
type: Answer
has body: Ok. So the problem was in 'Content-Type': 'application/x-www-form-urlencoded', I noticed it in the very beginning but did not pay any further attention. So Stupid. In order to pass this page the payload should be urlencoded as indicated by Content_Type. Here is how to do that. import urllib payload = {'captcha': '865944', 'sroVal': 'TADIKONDA(714)', 'sroId': '714', 'regyear': '2017', 'doct': '1', 'districtCode': '7', 'path': '/APCARDECClient', 'selectedSroId': 'null', 'docSel': '1', } payload = urllib.urlencode(payload) yield scrapy.Request(url, method ="POST", body=payload ,headers=headers, callback = self.details1)
answers question: http://stackoverflow.com/q/52506767
score: 0

http://stackoverflow.com/q/52456284
favorite count: 0
accepted answer: http://stackoverflow.com/a/52460746
tagged with: python
tagged with: pygame
tagged with: collision
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52460746
upvote count: 1
has comment: http://stackoverflow.com/comment/91855113
tagged with: sprite
type: Question
has title: How do I use .spritecollide() in pygame to detect for collisions?
has body: I am trying to learn how to use pygame by creating a simple 'shmup' game with blocks. When running the code, no errors are shown, however the game does not seem to be detecting collisions between the sprites. Am I using this incorrectly? Any help much appreciated. If it would be easier to run the code for yourself that should be possible as there are no external files used. hits = pygame.sprite.spritecollide(player,mobs, False) if hits: running = False All code: import pygame import random import time pygame.init() pygame.mixer.init() width = 480 height = 600 black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) #initialise pygame and create window screen = pygame.display.set_mode((width,height)) pygame.display.set_caption("Shoot 'Em Up!") clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): def __init__(self): #this is mandatory, it loads the built in sprite function/code pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50,40)) self.image.fill(green) self.rect = self.image.get_rect() self.rect.centerx = width / 2 self.rect.bottom = height - 10 self.speedx = 0 def update(self): self.speedx = 0 #thi section makes the sprite move, sets x speed keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx # sets the boundaries of screen if self.rect.right &gt; width: self.rect.right = width if self.rect.left &lt; 0: self.rect.left = 0 class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((30,40)) self.image.fill(red) self.rect = self.image.get_rect() self.rect.x = random.randrange(0, width - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) #randomising angle of movement self.speedx = random.randrange(-3, 3) def update(self): self.rect.x += self.speedx self.rect.y += self.speedy if self.rect.top &gt; height + 10…
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/92086898
score: 0
type: AnswerComment
type: Comment
has text: I thought pca.components_ are eigenvectors in sklearn. Are these different?
comment on: http://stackoverflow.com/a/52574914

http://stackoverflow.com/q/52506043
downvote count: 0
has body: The documentation for pdfminer is poor at best. I was initially using pdfminer and had it working for some PDF files then I ran into some bugs and realized I should be using pdfminer.six I want to extract the text from each page of the PDF so that way I can keep tabs on where I found specific words and such. Using the documentation: from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfpage import PDFTextExtractionNotAllowed from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfdevice import PDFDevice # Open a PDF file. fp = open('mypdf.pdf', 'rb') # Create a PDF parser object associated with the file object. parser = PDFParser(fp) # Create a PDF document object that stores the document structure. # Supply the password for initialization. document = PDFDocument(parser, password) # Check if the document allows text extraction. If not, abort. if not document.is_extractable: raise PDFTextExtractionNotAllowed # Create a PDF resource manager object that stores shared resources. rsrcmgr = PDFResourceManager() # Create a PDF device object. device = PDFDevice(rsrcmgr) # Create a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page contained in the document. for page in PDFPage.create_pages(document): interpreter.process_page(page) We've parsed all the pages but there is no documentation on how to get what elements or anything from the PDFpage I looked though the PDFPage.py file for a way to extract the text from each PDF page and of course it's not that simple. To complicate matters theres at least 3 versions of pdfminer and of course over time things have been upgraded so any examples I can find are not compatible.
type: Question
tagged with: pdfminer
upvote count: 2
has answer: http://stackoverflow.com/a/57022360
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
tagged with: parsing
favorite count: 0
type: UnansweredQuestion
has title: Extracting text from each PDF page using pdfminer.six
tagged with: python
score: 2

http://stackoverflow.com/q/52538273
has answer: http://stackoverflow.com/a/52538463
type: UnansweredQuestion
tagged with: python
has title: Incorporate side conditions into Keras neural network
tagged with: tensorflow
type: Question
answer count: 1
tagged with: keras
score: 0
has body: I want to train my neural network (in Keras) with an additional condition on the output elements. An example: Minimize my loss function MSE between network output y_pred and y_true. Additionally, ensure that the norm of y_pred is less or equal 1. Without the condition, the task is straightforward. Note: The condition is not necessarily the vector norm of y_pred. How can I implement the additional condition/restriction in a Keras (or maybe Tensorflow) model?

http://stackoverflow.com/comment/91805775
type: QuestionComment
comment on: http://stackoverflow.com/q/52430998
score: 0
has text: are all the strings exactly like this? There's 3 segments?
type: Comment

http://stackoverflow.com/comment/92050606
score: 0
has text: Where are you getting the input from, a call to `input`? `map` actually doesn't really apply here.
comment on: http://stackoverflow.com/q/52556009
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92084810
has text: @Parfait Could you please share your approach? For me the child object list is one of the field of the parent object. If you have better database model then please share
score: 0
comment on: http://stackoverflow.com/q/52571043
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91832970
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52431179
has text: You can find info about some method here https://www.scipy-lectures.org/advanced/mathematical_optimization/

http://stackoverflow.com/comment/92028473
type: QuestionComment
type: Comment
has text: Do you want to parse output as a string?
comment on: http://stackoverflow.com/q/52544301
score: 0

http://stackoverflow.com/comment/91923276
comment on: http://stackoverflow.com/q/52462008
type: Comment
type: QuestionComment
has text: Hi Alex it very common to run multiple instance/program using twistd. It will not interrupt each other unless 2 of them using same port to run a server. It is working for me perfect, I am running around 10 to 15 instance on same server, and not get any till now.
score: 1

http://stackoverflow.com/q/52489460
type: AnsweredQuestion
score: 3
type: Question
answer count: 1
downvote count: 0
tagged with: dataset
favorite count: 0
accepted answer: http://stackoverflow.com/a/52490369
tagged with: python
has body: I am new to Pytorch and CNN. I am kind of confused about Data Preprocessing. Not sure how to go about transform.Normalising the dataset (in essence how do you calculate mean and std v for your custom dataset ?) I am loading my data using ImageFolder. The images are of different sizes. train_transforms = transforms.Compose([transforms.Resize(size=224), transforms.ToTensor(), transforms.Normalize((?), (?)) ]) train_dataset = datasets.ImageFolder(root='roota/', transform=train_transforms)
has title: Data preprocessing for custom dataset in pytorch (transform.Normalize)
tagged with: conv-neural-network
tagged with: pytorch
upvote count: 3
has answer: http://stackoverflow.com/a/52490369

http://stackoverflow.com/comment/91939550
score: 0
has text: That's weird you model expects a 10 dimensional output and you were able to train it on a one dimensional target.? Please do cross check the saved model using `trained_model.summary()`. And make sure the model you have trained and trained model are the same
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52499274

http://stackoverflow.com/comment/91932024
score: 1
has text: They're pretty much `for (int passnum = alist.length() - 1; passnum > 0; --passnum) { for (int i = 0; i < passnum; ++i) { /* ... */ } }`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52495773

http://stackoverflow.com/comment/91984845
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52522339
has text: yeah, i copied it from an answer i found on SO
type: AnswerComment

http://stackoverflow.com/comment/92042014
comment on: http://stackoverflow.com/q/52550444
score: 0
type: Comment
type: QuestionComment
has text: Still it would have been better if Python returns some meaningful error instead of Segmentation faults all the time...

http://stackoverflow.com/a/52546733
type: Answer
has body: This would be what a Collection can be used for. You may create the Polygon once and supply it to a PatchCollection. Then define all the points where to place this polygon as offsets. import matplotlib.pyplot as plt import matplotlib.collections as mcol import matplotlib.transforms as mtrans import numpy as np poly = plt.Polygon(((1,0),(0,0),(1,1),(2,1)), fc = 'b', closed = True) x,y = np.meshgrid(np.arange(15), np.arange(10)) # create PatchCollection with all coordinates within x=(0..14), y=(0..9) as offsets pcol = mcol.PatchCollection([poly,], offsets=np.c_[x.flatten(), y.flatten()], offset_position="data", transOffset=mtrans.IdentityTransform(), transform=plt.gca().transData) # colorize the patches pcol.set_array(np.random.rand(15*10)) plt.gca().add_collection(pcol) plt.gca().set(xlim=(0,16),ylim=(0,10)) plt.show()
score: 0
answers question: http://stackoverflow.com/q/52541377

http://stackoverflow.com/q/52504199
has body: I have the following code. I would think the initializer is run before the tasks are executed, but apparently I'm getting errors indicating some tasks are run without that thread being initialized. import threading import random from multiprocessing.dummy import Pool, Value, Queue, Manager def init_worker(): global thread_local thread_local = threading.local() thread_local.worker_idx = random.randint(0, 10) print("++++++++++++++++++++++++ worker %s" % thread_local.worker_idx) def run(idx): print(dir(thread_local)) worker_idx = thread_local.worker_idx print("==================== TASK ID %s by worker %s ====================" % (idx, worker_idx)) pool = Pool(2, init_worker) pool.map(run, range(10), chunksize=1) Output: ++++++++++++++++++++++++ worker 1 ++++++++++++++++++++++++ worker 7 ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'worker_idx'] ==================== TASK ID 0 by worker 7 ==================== ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'worker_idx'] ==================== TASK ID 2 by worker 7 ==================== ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'worker_idx'] ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__…
has answer: http://stackoverflow.com/a/52504690
type: Question
tagged with: python-multithreading
tagged with: python
has title: Python multiprocessing.dummy thread pool runs more tasks with `map` without thread initialized
score: 0
tagged with: multithreading
answer count: 1
accepted answer: http://stackoverflow.com/a/52504690
tagged with: threadpool
type: AnsweredQuestion

http://stackoverflow.com/a/52532368
score: 2
has comment: http://stackoverflow.com/comment/92004409
has comment: http://stackoverflow.com/comment/92004470
downvote count: 0
has body: You can just use index-based assignment: In [16]: df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'], ...: 'B': ['B0', 'B1', 'B2'], ...: 'C': ['C0', 'C1', 'C2']}, ...: index=[0, 1, 2]) In [17]: df1 Out[17]: A B C 0 A0 B0 C0 1 A1 B1 C1 2 A2 B2 C2 In [18]: df1['D'] = False In [19]: df1 Out[19]: A B C D 0 A0 B0 C0 False 1 A1 B1 C1 False 2 A2 B2 C2 False You can also use .assign which returns a new data-frame if you don't want to modify the original: In [20]: df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'], ...: 'B': ['B0', 'B1', 'B2'], ...: 'C': ['C0', 'C1', 'C2']}, ...: index=[0, 1, 2]) In [21]: df1 Out[21]: A B C 0 A0 B0 C0 1 A1 B1 C1 2 A2 B2 C2 In [22]: df1.assign(D=False) Out[22]: A B C D 0 A0 B0 C0 False 1 A1 B1 C1 False 2 A2 B2 C2 False In [23]: df1 Out[23]: A B C 0 A0 B0 C0 1 A1 B1 C1 2 A2 B2 C2 And using pd.concat here is really not useful, you could have simply assigned the list! Either way, it's still much much slower: In [44]: import timeit In [45]: setup = 'import pandas as pd; df = pd.DataFrame({"a":list(range(100000))})' In [46]: lstcomp = "df['D'] = [False for item in range(len(df.index))]" In [47]: assgnmt = "df['D'] = False" In [48]: timeit.timeit(lstcomp, setup, number=100) Out[48]: 0.6879564090049826 In [49]: timeit.timeit(assgnmt, setup, number=100) Out[49]: 0.008814844011794776 As for your list-comprehension, it is not necessary, but it is definitely over-complicated. You said you tried iterating over the index, but "it didn't work", but you never explained how it didn't work. It works for me: In [24]: [False for item in list(range(len(df1.index)))] Out[24]: [False, False, False] In [25]: [False for item in df1.index] Out[25]: [False, False, False] Note, your's is doubly inefficient because it calls list on the range object, which creates a whole list instead of taking advantage of range's fixed-memory behavior (not to mention iterating twice).
has comment: http://stackoverflow.com/comment/92004198
upvote count: 2
has comment: http://stackoverflow.com/comment/92004182
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52532317
answers question: http://stackoverflow.com/q/52532317
type: Answer
has comment: http://stackoverflow.com/comment/92004088

http://stackoverflow.com/comment/91937983
comment on: http://stackoverflow.com/q/52498677
has text: @WillemVanOnsem I interpreted as the specific string method `startswith()` in which case I think the circumstances that I described would be the only way of doing it
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91952846
type: QuestionComment
comment on: http://stackoverflow.com/q/52506099
has text: With your current setup, during the first few loops of your inner loops, count will always be less then 2, and therefore will always append the key, therefore I agree with @juanpa.arrivillaga, where you may need to move that `if count <= 2` to outside of the inner for-loop.
score: 0
type: Comment

http://stackoverflow.com/q/52437024
has answer: http://stackoverflow.com/a/52437058
favorite count: 0
has answer: http://stackoverflow.com/a/52437399
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has body: I am looking for something quite specific that I can't quite find the answer to. I have two dataframes. One that contains an ID, latitude and longitude. The other has just an ID. I want to store in a list the latitude and longitude as long as the ID from Dataframe A exists in Dataframe B using list comprehension. I can get the first part working fine, but matching the IDs appears to be causing a problem. This is what I have so far: heat_data = [[row['latitude'],row['longitude']] for index, row in extract.iterrows() if row['NBN Location Id'] in closed['SP Order Location ID']] To me, that says store 'latitude' and 'longitude' from extract as long as the ID exists in the other dataframe (closed). However this causes no data to be retrieved. Can anyone guide me as to where I'm going wrong? If I exclude the last 'if' statement, it works fine. So how else am I supposed to be doing this if statement? Thanks!
type: Question
possible better answer: http://stackoverflow.com/a/52437399
has title: Python list comprehension with loop over dataframe
accepted answer: http://stackoverflow.com/a/52437058
tagged with: dataframe
score: 4
tagged with: list-comprehension
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/52527435
tagged with: string
accepted answer: http://stackoverflow.com/a/52527671
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/91994816
has comment: http://stackoverflow.com/comment/91994485
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91994483
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52527671
answer count: 2
has comment: http://stackoverflow.com/comment/91994760
upvote count: 0
has comment: http://stackoverflow.com/comment/91994546
has body: I have a string as the following: '1:CH,AG,ME,GS,AP,CH,HE,AC,AC,AG,CA,HE,AT,AT,AC,AT,OG,NE,AG,AC,CS,OD\n&amp;:TA,EB,PA,AC,BR,TH,PO,AC,2I,AC,TH,PE,TH,AZ,AZ,ZE,CS,OD,CH,EO,ZE,OG\n&amp;:TH,ZE,ZE,HE,HE,HP,HP,OG,HP,ZE\n2:ZE,FD,FD,AG,EO,OG,AG,NE,RU,GS,HP,ZE,ZE,HM,HM,PC,PC,AS,AS,TY,TY,AG\n&amp;:AG,GS,NO,EU,ZF,HE,AT,AT,OD,OD,EB,OD,GS,TR,OD,AC,TR,GS,OD,TR,OD,AT,GS\n&amp;:CA,GS,NE,GS,AG,PS,HL,AG,NE,ID,AJ,AX,DI,OD,ME,AT,GS,MU,HO,PB,LT,9Z,PT,9Y\n&amp;:9W,9X,AR,9V,9U,9T,AX,9S,9R,AT,AJ,DI,ST,EA,AG,ME,NE,MU,9Q,9P,9O,9N,9M,9L\n&amp;:9K,ID,MG,OD,FY,AU,AU,HR,HR,9J,TL,9I,9H,9G,9F,AC,BR,AC,9E,9D,9C,9B,99\n' As you can see, I would like to get the '\n(number or &amp; here):' replaced by ',' Since they all start with '\n' and end with ':' I believe that there should be a way to replace them all at once. The output would be as the sort: 'CH,AG,ME,GS,AP,CH,HE,AC,AC,AG,CA,HE,AT,AT,AC,AT,OG,NE,AG,AC,CS,OD,TA,EB,PA,AC,BR,TH,PO,AC,2I,AC,TH,PE,TH,AZ,AZ,ZE,CS,OD,CH,EO,ZE,OG,TH,ZE,ZE,HE,HE,HP,HP,OG,HP,ZE,ZE,FD,FD,AG,EO,OG,AG,NE,RU,GS,HP,ZE,ZE,HM,HM,PC,PC,AS,AS,TY,TY,AG,AG,GS,NO,EU,ZF,HE,AT,AT,OD,OD,EB,OD,GS,TR,OD,AC,TR,GS,OD,TR,OD,AT,GS,CA,GS,NE,GS,AG,PS,HL,AG,NE,ID,AJ,AX,DI,OD,ME,AT,GS,MU,HO,PB,LT,9Z,PT,9Y,9W,9X,AR,9V,9U,9T,AX,9S,9R,AT,AJ,DI,ST,EA,AG,ME,NE,MU,9Q,9P,9O,9N,9M,9L,9K,ID,MG,OD,FY,AU,AU,HR,HR,9J,TL,9I,9H,9G,9F,AC,BR,AC,9E,9D,9C,9B,99' What could work was making a for lop for numbers and &amp;. string.replace('\n&amp;:',',') for i in range(1,20): string.replace('\ni:',',') But I believe there must be a better way.
possible better answer: http://stackoverflow.com/a/52527695
has answer: http://stackoverflow.com/a/52527695
has comment: http://stackoverflow.com/comment/91994509
has title: Remove variable parts of a string that start and end the same
tagged with: python-2.x

http://stackoverflow.com/comment/131651580
score: 3
has text: I believe `Mapping` is only covariant over it's value, not it's key.
comment on: http://stackoverflow.com/a/52487800
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91918969
comment on: http://stackoverflow.com/q/52488523
score: 0
has text: I'm not sure about the top O(n!), I'll check it after I've had some sleep & I'm not on my phone. ;) The O(n) all look correct.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91977178
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52518140
has text: Can you try using 1000, 2000, 3000,4000 as well just to see if there is some crossover point?

http://stackoverflow.com/q/52435224
tagged with: python-3.x
tagged with: django-2.0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/103857478
has body: When I attempt to pass a python list through to JavaScript in the template it doesn't parse the list into an JS array as expected but instead returns this [&amp;quot;Groceries&amp;quot;, &amp;quot;Clothing&amp;quot;, &amp;quot;Takeaways&amp;quot;, &amp;quot;Alcohol&amp;quot;] causing the page to break. view.py def labels(): category_labels = [] for item in Purchase.objects.order_by().values_list('type', flat=True).distinct(): category_labels.append(item) return category_labels def index(request): try: purchases = Purchase.objects.all().order_by('-time') total_spending = round(Purchase.objects.aggregate(Sum('amount'))['amount__sum'], 2) except Purchase.DoesNotExist: raise Http404("Could not find any purchases.") context = { 'purchases': purchases, 'total_spending': total_spending, 'spending_by_category': prepare_total_spending(), 'total_spending_all_categories': total_spending_all_categories(), 'labels': json.dumps(labels()), } return render(request, 'main/index.html', context) index.html &lt;script type="text/javascript"&gt; console.log(JSON.parse("{{labels}}")) # =&gt; converts this to console.log([&amp;quot;Groceries&amp;quot;, &amp;quot;Clothing&amp;quot;, &amp;quot;Takeaways&amp;quot;, &amp;quot;Alcohol&amp;quot;]) in JS and breaks. &lt;/script&gt;
has comment: http://stackoverflow.com/comment/91814036
type: Question
has comment: http://stackoverflow.com/comment/91813960
tagged with: javascript
has answer: http://stackoverflow.com/a/52435603
score: 0
answer count: 1
has title: json.dump not converting python list to JS array

http://stackoverflow.com/comment/92051597
type: QuestionComment
comment on: http://stackoverflow.com/q/52556435
score: 1
has text: Have you tried using a tool like https://regex101.com/ to validate test your regex?
type: Comment

melt
tags question: http://stackoverflow.com/q/52484858
type: Tag
tag name: melt

http://stackoverflow.com/q/52527152
has title: Why did I get a memory error for np.sqrt on a machine with seemingly ample RAM?
tagged with: memory
score: 0
has comment: http://stackoverflow.com/comment/91994158
has comment: http://stackoverflow.com/comment/91994164
has comment: http://stackoverflow.com/comment/91994291
type: UnansweredQuestion
tagged with: python
has body: I'm running a simple Python program that takes many hours to create a large (102,000 x 102,000) float32 array (A). Total memory occupied by the array is ~40GiB, and I'm running this on an Amazon EC2 virtual machine (running Ubuntu) with 130GiB of RAM. There are no other user processes running, and I can use 'top' to see that, in fact, the program is only using about 56GiB during the array creation phase (don't ask me why it's using even that much), consistently leaving about about 68GiB free, even after allowing for system processes. So far, so good. But the near-final line in the program is A = np.sqrt(A) and at this point, the program crashes with a memory error. I don't understand why this is happening, even allowing for the need for a temporary array of the same size (this should still leave about 28 GiB free). The only thing I can think of is that np.sqrt() might be internally using float64 for the scratch space. Is there any other possible explanation? My only workaround right now is to compute the square root element-by-element in for loops.
answer count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/91998368
score: 0
type: AnswerComment
type: Comment
has text: Eliminated the sync. Code simpler, but behaves the same (works on X1, not well on T61). 0 seems to show the window. I'll look into qwidgetvideosink, but I don't see any quick python examples on it, so it might take me a while to work it out.
comment on: http://stackoverflow.com/a/52507512

navigation-drawer
tags question: http://stackoverflow.com/q/52465547
type: Tag
tag name: navigation-drawer

http://stackoverflow.com/q/52475698
favorite count: 0
has comment: http://stackoverflow.com/comment/91892893
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
type: Question
linked to: http://stackoverflow.com/q/15891038
has comment: http://stackoverflow.com/comment/91892872
tagged with: dataframe
duplicate of: http://stackoverflow.com/q/15891038
tagged with: int
has answer: http://stackoverflow.com/a/52475812
has title: How to convert all object type values in a dataframe to int
tagged with: pandas
has body: Anyone know how to convert all column values in dataframe to int? lets say i have a dataframe containing A B C 1 2 1 3 2 1 1 4 5 dtypes is object how do i convert it to int or numeric
downvote count: 0
answer count: 1

http://stackoverflow.com/a/52463781
has body: from session.keys() have you tried popping out keys? # remove the keyname from the session if it is there session.pop('key_name')
type: Answer
upvote count: 11
accepted answer of: http://stackoverflow.com/q/52463734
has comment: http://stackoverflow.com/comment/91869595
has comment: http://stackoverflow.com/comment/91869611
score: 11
has comment: http://stackoverflow.com/comment/91869589
has comment: http://stackoverflow.com/comment/91869535
has comment: http://stackoverflow.com/comment/91869720
answers question: http://stackoverflow.com/q/52463734
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52476887
type: Answer
has comment: http://stackoverflow.com/comment/91897619
has comment: http://stackoverflow.com/comment/91897561
has body: Here, I tried solving it. Here is my code : bracket_string = '[apple]and[orange]and[apple]again!' def find_tags(string1): start = False data = '' data_list = [] for i in string1: if i == '[': start = True if i != ']' and start == True: if i != '[': data += i else: if data != '': data_list.append(data) data = '' start = False return(data_list) x = find_tags(bracket_string) print(x) The function will return a list of items that were between brackets of a given string parameter. Any advice will be appreciated.
answers question: http://stackoverflow.com/q/52475852
accepted answer of: http://stackoverflow.com/q/52475852
has comment: http://stackoverflow.com/comment/91895571
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/52555492
has answer: http://stackoverflow.com/a/52555837
has answer: http://stackoverflow.com/a/52555848
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
possible better answer: http://stackoverflow.com/a/52555848
accepted answer: http://stackoverflow.com/a/52555837
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92049781
favorite count: 0
upvote count: 2
has body: I'm trying to understand how multiprocessing works in python and having some issues. This is the example: import multiprocessing def func(): return 1 p = multiprocessing.Pool() result = p.apply_async(func).get() When .get() function is called, the code is just stuck. What am I doing wrong?
has comment: http://stackoverflow.com/comment/92051611
tagged with: python
has title: Multiprocessing goes stuck after .get()
has comment: http://stackoverflow.com/comment/92051213
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/92013654
score: 0
comment on: http://stackoverflow.com/a/52533406
type: AnswerComment
has text: I copy pasted the exactly first, it wrote nothing but a empty file. I thought you put something for to do , check this link now, it looks as your code https://codeshare.io/G70M7j
type: Comment

http://stackoverflow.com/a/52476593
type: Answer
answers question: http://stackoverflow.com/q/52475852
has comment: http://stackoverflow.com/comment/91916131
has comment: http://stackoverflow.com/comment/91911043
score: 0
has body: You can solve this using a simple for loop over all characters of your text. You have to remember if you are inside a tag or outside a tag - if inside you add the letter to a temporary list, if you encounter the end of a tag, you add the whole templorary list as word to a return list. You can solve the numbering using enumerate(iterable, start=1) of the list of words: def find_tags(text): inside_tag = False tags = [] # list of all tag-words t = [] # list to collect all letters of a single tag for c in text: if not inside_tag: inside_tag = c == "[" # we are inside as soon as we encounter [ elif c != "]": t.append(c) # happens only if inside a tag and not tag ending else: tags.append(''.join(t)) # construct tag from t and set inside back to false inside_tag = False t = [] # clear temporary list if t: tags.append(''.join(t)) # in case we have leftover tag characters ( "[tag" ) return list(enumerate(tags,start=1)) # create enumerated list x = find_tags('[apple]and[orange]and[apple]again!') # x is a list of tuples (number, tag): for nr, tag in x: print("{}-{}".format(nr, tag), end = ", ") Then you specify ',' as delimiter after each print-command to get your output. x looks like: [(1, 'apple'), (2, 'orange'), (3, 'apple')]

http://stackoverflow.com/q/52544117
linked to: http://stackoverflow.com/q/46923423
has comment: http://stackoverflow.com/comment/92057379
score: 0
has comment: http://stackoverflow.com/comment/92029576
has comment: http://stackoverflow.com/comment/92082265
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: memory-leaks
tagged with: python
has body: I've got code like this: async def worker(self): while True: proxies = get_proxies() for proxy in proxies: await self.add_proxy_to_queue(proxy) async def add_proxy_to_queue(self, proxy): while self.proxies_semaphore.locked(): await asyncio.sleep(0.001) asyncio.ensure_future(self.process_proxy(proxy)) async def process_proxy(self, proxy): async with self.proxies_semaphore: # send network request and wait for the resposne with timeout I've changed it like this: async def worker(self): while True: proxies = get_proxies() for proxy in proxies: await self.add_proxy_to_queue(proxy) async def add_proxy_to_queue(self, proxy): async with self.proxies_semaphore: # &lt;-- HERE ARE THE CHANGES asyncio.ensure_future(self.process_proxy(proxy)) async def process_proxy(self, proxy): async with self.proxies_semaphore: # send network request and wait for the resposne with timeout and it's still leaking, but much slower. What am I doing wrong and how to debug asyncio code, how say to look inside event loop and see which tasks are actually there?
answer count: 0
has title: What am I doing wrong and how to debug memory leaks with python's asyncio?
type: Question
has comment: http://stackoverflow.com/comment/92031215

sphinx-apidoc
tag name: sphinx-apidoc
tags question: http://stackoverflow.com/q/52560257
type: Tag

http://stackoverflow.com/comment/91924637
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52491972
score: 0
has text: Why do you need `new` to begin with? just write `List = List[low_ind:high_ind]`

http://stackoverflow.com/q/52478792
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52478883
has comment: http://stackoverflow.com/comment/91898809
has comment: http://stackoverflow.com/comment/91898770
tagged with: pickle
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52478883
has title: How to convert n number of images (in jpg format) to .p (pickle) format?
type: Question
has comment: http://stackoverflow.com/comment/91898557
score: -1
has comment: http://stackoverflow.com/comment/91898559
has body: I have a folder abc with images in .jpg format. I need to convert these images to single xyz.p (pickled) file. How to pickle these images? I want to implement something like this: > import pickle > training_file = "dataset/train.p" > with open(training_file, mode='rb') as f: > train = pickle.load(f) X_train, y_train = train['features'], train['labels']
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/92049303
type: QuestionComment
comment on: http://stackoverflow.com/q/52555225
score: 0
has text: Possible duplicate of [How to sort a dataFrame in python pandas by two or more columns?](https://stackoverflow.com/questions/17141558/how-to-sort-a-dataframe-in-python-pandas-by-two-or-more-columns)
type: Comment

http://stackoverflow.com/comment/92070351
type: Comment
has text: [this](https://stackoverflow.com/questions/5937337/building-python-with-ssl-support-in-non-standard-location) would be handy for you :)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52566503

http://stackoverflow.com/q/52539644
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92019387
has title: Requests package and API documentation
has answer: http://stackoverflow.com/a/52540038
tagged with: python-requests
has answer: http://stackoverflow.com/a/52539738
type: Question
has body: I'm having trouble understanding where to add parameters defined by API documentation. Take BeeBole's documentation for example, which specifies that to get an absence by ID, the following request is required: { "service": "absence.get", "id": "absence_id" } They provide only one URL in the documentation: BeeBole is accepting HTTP POST requests in a json-doc format to the following URL: https://beebole-apps.com/api/v2 How would this be implemented in the context of Python requests? The following code I've tried returns 404: import requests payload = { "service": "absence.get", "id": "absence_id" } auth = { "username": "API_token", "password": "x" } url = "https://beebole-apps.com/api/v2" req = requests.get(url, params=payload, auth=auth).json()
possible better answer: http://stackoverflow.com/a/52540038
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92019157
has comment: http://stackoverflow.com/comment/92019028
has comment: http://stackoverflow.com/comment/92019042
has comment: http://stackoverflow.com/comment/92018923
tagged with: python
accepted answer: http://stackoverflow.com/a/52539738

http://stackoverflow.com/comment/92080757
score: 0
type: AnswerComment
type: Comment
has text: @Rhys no, **everything in Python works like this**.
comment on: http://stackoverflow.com/a/52572078

http://stackoverflow.com/a/55360366
answers question: http://stackoverflow.com/q/52466038
downvote count: 0
has body: If you do not want to guess each time how long does it take to load the page and set some random seconds to sleep, you can use Explicit Waits. Example: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("http://somedomain/url_that_delays_loading") try: element = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.ID, "myDynamicElement")) ) except common.exceptions.TimeoutException: print('TimeoutException') finally: driver.quit() # do what you want after necessary elements are loaded This will solve the problem when time.sleep() becomes too low compared to the refreshing speed of the webpage.
type: Answer
score: 2
upvote count: 2

curve-fitting
tags question: http://stackoverflow.com/q/52502896
tag name: curve-fitting
tags question: http://stackoverflow.com/q/52502563
tags question: http://stackoverflow.com/q/52523786
tags question: http://stackoverflow.com/q/52450658
tags question: http://stackoverflow.com/q/52483191
tags question: http://stackoverflow.com/q/52524919
tags question: http://stackoverflow.com/q/52518662
tags question: http://stackoverflow.com/q/52460717
tags question: http://stackoverflow.com/q/52491800
tags question: http://stackoverflow.com/q/52573085
type: Tag

http://stackoverflow.com/comment/92100839
type: AnswerComment
has text: according to log you provided, Flake8 tries different environment or python in first place.This happens often if you have a few Python versions installed.
score: 0
comment on: http://stackoverflow.com/a/52582873
type: Comment

http://stackoverflow.com/q/52566462
accepted answer: http://stackoverflow.com/a/52569052
has title: How to use dask bag and delayed to join 2 mapping functions?
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: dask
has body: I have 2 functions: find_components and processing_partition_component import random import dask.bag as db def find_components(partition): # it will return a list of components return [x for x in range(1, random.randint(1,10))] def processing_partition_component(part_comp): print("processing %s" % part_comp) partitions=['2','3','4'] I want to compute find_components() on a partition then get the output of each partition to generate tasks for processing_partition_component(). And the computation shouldn't wait for all the find_coponents() to be completed. In order words, the processing_partition_component() should be call right after one of processing_partition is finished.I have tried this, but it is not what I want: db.from_sequence(partitions, partition_size=1).map(find_components).map(processing_partition_component).compute() # Output: processing [1, 2, 3, 4, 5] processing [1, 2] processing [1, 2, 3, 4, 5, 6, 7, 8, 9] You can see the processing_partition_component() take the whole output of find_components() for example: [1, 2, 3, 4, 5] as it in put. What I want is the task should fan-out after find_components() and each processing_partition_component() should only take 1 element like 1, 2, 3, 4 or 5. The expected print out is processing 1 processing 2 processing 3 .... processing 1 # from another output of find_components ... If this is multi-threaded the order of print out will be mixed up so Processing 1 can be printed out 3 times next to each other I don't know how to do that using dask.bag and dask.delayed. I am using latest dask with python3 Thanks,
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52569052

http://stackoverflow.com/comment/91867565
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52460513
score: 0
has text: what is `t1`???

http://stackoverflow.com/comment/92102692
comment on: http://stackoverflow.com/q/52583710
score: 0
type: QuestionComment
type: Comment
has text: Can both columns ever have `T`? or it will it only be one?

http://stackoverflow.com/comment/91852456
score: 0
type: Comment
has text: Instead of replacing it with an empty line, just skip writing anything in its place.
type: AnswerComment
comment on: http://stackoverflow.com/a/52454928

http://stackoverflow.com/q/52475717
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52478399
accepted answer: http://stackoverflow.com/a/52478399
tagged with: arrays
score: 0
has comment: http://stackoverflow.com/comment/91895909
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has body: import numpy as np a = np.zeros((10,10)) startx = 1 starty = 1 endx = 7 endy = 8 how can I mask line (startx, starty) -&gt; (endx, endy) with width 3 on array a ? Any efficient way?
has comment: http://stackoverflow.com/comment/91893230
tagged with: python
type: AnsweredQuestion
has title: How can I make a line mask which is not parallel to xy-axis on numpy arrays?

http://stackoverflow.com/comment/91899242
comment on: http://stackoverflow.com/a/52455949
score: 0
type: Comment
has text: It is rounded. The actual value is less than 1. `sigmoid(np.array([20,3]))[0] < 1.0 ===> True`
type: AnswerComment

http://stackoverflow.com/comment/92091240
type: Comment
type: QuestionComment
has text: can you show your code? I guess you may se dummy coding & number of levels differ in train and test datasets
comment on: http://stackoverflow.com/q/52577999
score: 0

http://stackoverflow.com/a/60644024
answers question: http://stackoverflow.com/q/52534658
upvote count: 8
downvote count: 2
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/107923718
has body: This solution worked for me from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.headless = True driver = webdriver.Firefox(options=options)

http://stackoverflow.com/comment/92061170
comment on: http://stackoverflow.com/a/52561089
type: AnswerComment
score: 0
has text: I'm not sure how that `Referer` sol'n would work, but my current way is via a programmatically inserted ` ` tag which is similar to replacing the links in `index.html`.
type: Comment

http://stackoverflow.com/q/52463788
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52827108
downvote count: 0
has title: Shuffle and split 2 numpy arrays so as to maintain their ordering with respect to each other
answer count: 3
tagged with: python
favorite count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/52827108
possible better answer: http://stackoverflow.com/a/52463862
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52463862
score: 1
has body: I have 2 numpy arrays X and Y, with shape X: [4750, 224, 224, 3] and Y: [4750,1]. X is the training dataset and Y is the correct output label for each entry. I want to split the data into train and test so as to validate my machine learning model. Therefore, I want to split them randomly so that they both have the correct ordering after random split is applied on X and Y. ie- every row of X is correctly has its corresponding label unchanged after the split. How can I achieve the above objective ?
has answer: http://stackoverflow.com/a/52827186
type: Question

http://stackoverflow.com/a/52504826
accepted answer of: http://stackoverflow.com/q/52504741
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: A nested function function_2 is an object in the local namespace of the outer function. It doesn't even exist as a function when function_1 is not running. Normally, a nested function either performs a private computation for the outer function, or gets returned in some form or another. In the latter case, you can run function_1 to get a reference to function_2. Any object that you want to import should be in the global namespace, or at least directly referenceable from it. A better design would be x = 3 def function_1(x): y = x + 7 # Do some stuff, including using function_2 return y def function_2(value): # Do some stuff return value And keep in mind that defining a function is not the same as running it. As a corollary, the x inside function_1 is not the same as the x that you set to 3 at the module level. Update for your update You absolutely can make function_1 into a class, and make function_2 a method of it: class function_1: def __call__(self, x): y = x + 7 value = self.function_2(y) return y, value @staticmethod def function_2(value): return value In this case you could do the following in your other script: from test import function_1 f1 = function_1() # Call it: f1(7) # Call function_2: function_1.function_2('blah') # Or alternatively: f1.function_2('foo')
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52504741

http://stackoverflow.com/a/52526016
type: AcceptedAnswer
has body: You need to provide all rows to writerows(...) - it takes a list of rows and each row is a list of columns:: import csv header = ["h1","h2","h3"] row1 = [11,12,13] row2 = [21,22,23] # always use newline="" for csv-module opened file with open('Alquran.csv', 'a', newline="") as file: coba=csv.writer(file) # list of rows, each row is a list of columns coba.writerows( [header, row1, row2] ) with open('Alquran.csv',"r") as r: print(r.read()) Output: h1,h2,h3 11,12,13 21,22,23 To later add more information: another_row = [31,32,33] with open('Alquran.csv', 'a', newline="") as file: coba=csv.writer(file) # list of 1 row, containing 3 columns coba.writerows( [another_row] ) with open('Alquran.csv',"r") as r: print(r.read()) Output after adding: h1,h2,h3 11,12,13 21,22,23 31,32,33 Doku: csv.writerows(..) for seperate row-writing, read Difference between writerow() and writerows() methods of Python csv module
accepted answer of: http://stackoverflow.com/q/52525924
type: Answer
answers question: http://stackoverflow.com/q/52525924
score: 0

http://stackoverflow.com/comment/91939891
type: QuestionComment
has text: can you update the question with `trained_model.summary()` .?
score: 0
comment on: http://stackoverflow.com/q/52499274
type: Comment

http://stackoverflow.com/q/52513626
has title: TFTPy import, no module named tftpy
type: Question
score: 1
tagged with: python-import
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/79329227
tagged with: importerror
has answer: http://stackoverflow.com/a/54191378
tagged with: python
type: UnansweredQuestion
tagged with: pip
upvote count: 1
has body: I installed TFTPy with both pip and pip3. Then i followed the example on the TFTPy documentation, which follows: import tftpy server = tftpy.TftpServer('/tftpboot') server.listen('0.0.0.0', 69) But I get the error ImportError: No module named tftpy I also tried using from tftpy import tftpy. I tried using Python 2, Python 2.7 and Python 3, but still get the same error. All help is appreciated

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/52440337
tags question: http://stackoverflow.com/q/52526841
tags question: http://stackoverflow.com/q/52508256
tags question: http://stackoverflow.com/q/52445035

http://stackoverflow.com/comment/92014475
type: Comment
score: 0
has text: @BryanOakley, I've tried Toplevel for the second win instead of Tk, but I still get the same problem.
comment on: http://stackoverflow.com/q/52535324
type: QuestionComment

http://stackoverflow.com/comment/91922487
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52490852
has text: I referred that .. it is related to particular filename not a folder of images @codelearner

http://stackoverflow.com/comment/92053697
type: QuestionComment
has text: Do you happen to overwrite your `settings.py` in your production deployment, or add a `localsettings.py` that could override some variables?
type: Comment
comment on: http://stackoverflow.com/q/52458979
score: 0

http://stackoverflow.com/comment/91992701
type: QuestionComment
comment on: http://stackoverflow.com/q/52526331
has text: I am using nargs='+'
score: 0
type: Comment

http://stackoverflow.com/comment/92027263
type: Comment
comment on: http://stackoverflow.com/a/52543337
has text: Yes it does eventually execute, but it takes a very long time. Is this not integrating with Sympy? How would i evaluate with numpy instead of lambda? Edit: Would i put that in the while loop or would it work on its own?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92077274
comment on: http://stackoverflow.com/q/52570253
score: 0
type: Comment
type: QuestionComment
has text: Your template was not found. It does not exist or your template loader is not properly configured.

http://stackoverflow.com/q/52445834
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52476730
answer count: 3
has title: Shape detection with opencv/python
favorite count: 0
has answer: http://stackoverflow.com/a/52451076
tagged with: python
tagged with: computer-vision
has body: I'm trying to teach my test automation framework to detect a selected item in an app using opencv (the framework grabs frames/screenshots from the device under test). Selected items are always a certain size and always have blue border which helps but they contain different thumbnail images. See the example image provided. I have done a lot of Googling and reading on the topic and I'm close to getting it to work expect for one scenario which is image C in the example image. example image This is where there is a play symbol on the selected item. My theory is that OpenCV gets confused in this case because the play symbol is basically circle with a triangle in it and I'm asking it to find a rectangular shape. I found this to be very helpful: https://www.learnopencv.com/blob-detection-using-opencv-python-c/ My code looks like this: import cv2 import numpy as np img = "testimg.png" values = {"min threshold": {"large": 10, "small": 1}, "max threshold": {"large": 200, "small": 800}, "min area": {"large": 75000, "small": 100}, "max area": {"large": 80000, "small": 1000}, "min circularity": {"large": 0.7, "small": 0.60}, "max circularity": {"large": 0.82, "small": 63}, "min convexity": {"large": 0.87, "small": 0.87}, "min inertia ratio": {"large": 0.01, "small": 0.01}} size = "large" # Read image im = cv2.imread(img, cv2.IMREAD_GRAYSCALE) # Setup SimpleBlobDetector parameters. params = cv2.SimpleBlobDetector_Params() # Change thresholds params.minThreshold = values["min threshold"][size] params.maxThreshold = values["max threshold"][size] # Filter by Area. params.filterByArea = True params.minArea = values["min area"][size] params.maxArea = values["max area"][size] # Filter by Circularity params.filterByCircularity = True params.minCircularity = values["min circularity"][size] params.maxCircularity = values["max circularity"][size] # Filter by Convexity params.filterByConvexity = False params.minConvexity = values["min convexity"][size] # Filter by Inertia params.filterByIn…
has answer: http://stackoverflow.com/a/52456057
type: AnsweredQuestion
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91894820
downvote count: 1
possible better answer: http://stackoverflow.com/a/52451076
type: Question
tagged with: opencv
accepted answer: http://stackoverflow.com/a/52476730
upvote count: 0
score: -1

http://stackoverflow.com/a/52519178
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91978336
answers question: http://stackoverflow.com/q/52519115
has body: You can pass list of columns names to parameter index: pivoted_df = pd.pivot_table(df, index=['id','UID','number','XID'], columns='FieldTitle', values='Value', aggfunc='first').reset_index() print (pivoted_df) FieldTitle id UID number XID fname lname 0 1 12 123 345 aaa bbb 1 2 23 432 543 ccc ddd If want dynamically add values to index parameter: cols = df.columns.difference(['FieldTitle','Value']).tolist() pivoted_df = pd.pivot_table(df, index=cols, columns='FieldTitle', values='Value', aggfunc='first').reset_index() print (pivoted_df)
has comment: http://stackoverflow.com/comment/91977975
has comment: http://stackoverflow.com/comment/91978001
has comment: http://stackoverflow.com/comment/91978063
has comment: http://stackoverflow.com/comment/91978211
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91978582
has comment: http://stackoverflow.com/comment/91978467
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91979080
has comment: http://stackoverflow.com/comment/91979647
accepted answer of: http://stackoverflow.com/q/52519115
has comment: http://stackoverflow.com/comment/91978117

http://stackoverflow.com/q/52556735
has answer: http://stackoverflow.com/a/54104886
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/54104886
accepted answer: http://stackoverflow.com/a/52557264
answer count: 2
has comment: http://stackoverflow.com/comment/92052542
has body: I can't figure out how to install the Python extension in VSCode in another language, specifically - I want it to be in English, but instead it is being installed in the language of my operating system, which is Russian. How can I install the Python extension in another language, or change the language to English? The VSCode installation is in English. My OS is Windows 7. I've tried googling it, no luck. ~~~ My "locale.json" config: "locale":"en" // Changes will not take effect until VS Code has been
tagged with: visual-studio-code
tagged with: locale
downvote count: 0
tagged with: ide
has comment: http://stackoverflow.com/comment/92052577
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: How to change Python extension locale in VSCode?
upvote count: 3
has answer: http://stackoverflow.com/a/52557264

http://stackoverflow.com/a/52484218
downvote count: 0
answers question: http://stackoverflow.com/q/52484043
type: Answer
has body: This is how I would do it dicts = { 'd1': {'goober': True, 'horse': 42}, 'd2': {'goober': True, 'horse': 42}, 'd3': {'goober': False, 'horse': 71} } desired_dict = {} group_num = 0 for d in dicts: for dd in desired_dict: # check if the dict exists in out desired_dict if desired_dict[dd]['dict'] == dicts[d]: # if yes, just update the keys desired_dict[dd].get('keys', []).append(d) break else: group_num += 1 # else make a new dictionary group group_name = 'group{0}'.format(group_num) desired_dict[group_name] = {'dict': dicts[d], 'keys': [d, ]} print(desired_dict) Out: {'group1': {'dict': {'goober': True, 'horse': 42}, 'keys': ['d1', 'd2']}, 'group2': {'dict': {'goober': False, 'horse': 71}, 'keys': ['d3']}}
score: 1
has comment: http://stackoverflow.com/comment/91910591
upvote count: 1

http://stackoverflow.com/a/52522836
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52522736
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52522736
type: Answer
has body: I agree with the comments that this might work better using a tabular form such as the pandas library, for example import pandas as pd df = pd.DataFrame({"dates":dates, "num":range(0,361)}) df.to_csv("my_csv.csv", index=False) This assumes your lists have equal length
downvote count: 0

http://stackoverflow.com/comment/91977703
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52518946
has text: Could you edit the post to add an example of what output do you expect?
type: Comment

http://stackoverflow.com/comment/91936610
comment on: http://stackoverflow.com/a/52489070
has text: `pred` is a numpy array, so you can convert it to a Pandas array with the same index as `test` if you want. (like `pred = pd.Series(model_fit.forecast(len(test)), index=test.index)`.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52511980
answer count: 1
has answer: http://stackoverflow.com/a/52512652
has body: I have the following pandas dataframe: col1 col2 col3 2 [0.006576649077136777, 0.0030259599523339924, ... [0.00567579212503948, -0.005498750236370691, 0... [-0.015786838188947716, 0.0042899171402874135,... 3 [-0.44547847984244543, -0.4482984342731749, 0.... [-0.022185524120646238, -0.38181444829591676, ... [-0.015786838188947716, 0.0042899171402874135,... 4 [-0.0014395623253532755, 0.0030226929032053595... [0.0035941013456355217, 0.0047566422661906695,... [-0.015786838188947716, 0.0042899171402874135,... 5 [0.00967978470638314, 0.011863989585765296, -0... [-0.011894506407398607, -0.003642684750775637,... [-0.015786838188947716, 0.0042899171402874135,... These represent vectors that I will have to fit into a DBSCAN. However I am having a hard time converting them into a matrix as every try will convert them into a matrix of arrays, how can I convert them into a 90 by 7190 matrix? This is what I've tried: np.asarray(df_veccol for col in df_vec.columns.values).reshape((90,7190)) and this is what i've got array([[array([ 0.00657665, 0.00302596, -0.01135427, -0.00063256, -0.00735737, 0.00150661, 0.00318936, 0.00109255, 0.00557719, 0.00958158, 0.00103098, 0.00706684, 0.00597235, -0.00502784, 0.00395275, 0.01183221, -0.00067338, 0.0042127 , -0.00281012, -0.00501378, -0.00103368, -0.00374887, 0.01158366, 0.00259053, -0.00764409, -0.00156182, -0.0018044 , 0.01153042, 0.00258852, 0.00294213]), array([-0.44547848, -0.44829843, 0.42276216, -0.22452319, -0.36380471,
tagged with: python
has comment: http://stackoverflow.com/comment/91963946
has title: Convert pandas columns of arrays to reshaped np.array
accepted answer: http://stackoverflow.com/a/52512652
type: AnsweredQuestion
type: Question
tagged with: numpy
score: 0
tagged with: pandas
tagged with: matrix

http://stackoverflow.com/a/52516454
accepted answer of: http://stackoverflow.com/q/52516340
type: Answer
upvote count: 4
has body: More general solution for None and NaNs values is use notnull function, anothe solution is use list comprehension. Also pandas string functions working very nice with None and NaNs: df['new1'] = df['item1'].apply(lambda x: x.lower() if pd.notnull(x) else x) df['new2'] = [x.lower() if pd.notnull(x) else x for x in df['item1']] df['new3'] = df['item1'].str.lower() print (df) id item1 item2 item3 new1 new2 new3 0 1 AK b c ak ak ak 1 2 CK d e ck ck ck 2 3 None e NaN None None None df=pd.DataFrame({'id':[1,2,3],'item1':['AK',np.nan,None], 'item2':['b','d','e'],'item3':['c','e',np.nan]}) print (df) id item1 item2 item3 0 1 AK b c 1 2 NaN d e 2 3 None e NaN df['new1'] = df['item1'].apply(lambda x: x.lower() if pd.notnull(x) else x) df['new2'] = [x.lower() if pd.notnull(x) else x for x in df['item1']] df['new3'] = df['item1'].str.lower() print (df) id item1 item2 item3 new1 new2 new3 0 1 AK b c ak ak ak 1 2 NaN d e NaN NaN NaN 2 3 None e NaN None None None List comprehesnion is faster in big DataFrames if not necessary check missing values: large = pd.Series([random.choice(string.ascii_uppercase) + random.choice(string.ascii_uppercase) for _ in range(100000)]) In [275]: %timeit [x.lower() if pd.notnull(x) else x for x in large] 73.3 ms ± 4.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [276]: %timeit large.str.lower() 28.2 ms ± 684 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) In [277]: %timeit [x.lower() for x in large] 14.1 ms ± 784 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/52516340
type: AcceptedAnswer

http://stackoverflow.com/comment/91993165
has text: Take a look at the `divmod` built-in function.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52526653

http://stackoverflow.com/a/52541837
answers question: http://stackoverflow.com/q/52540886
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: You can use pandas.Index.map: import pandas as pd from math import sqrt df = pd.DataFrame({'col1': (1,2,3), 'col2': (3,4,6),}, index=[1,4,9]) df Out: col1 col2 1 1 3 4 2 4 9 3 6 mapped_index = df.index.map(sqrt) mapped_index Out: Float64Index([1.0, 2.0, 3.0], dtype='float64') Then, if you need, you can just iterate through the result: for i in df.index.map(sqrt): ....

http://stackoverflow.com/q/52577737
has comment: http://stackoverflow.com/comment/92090850
tagged with: list
tagged with: index-error
downvote count: 1
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/52580139
score: 0
has comment: http://stackoverflow.com/comment/92095462
answer count: 1
has title: Python index out of range?_
accepted answer: http://stackoverflow.com/a/52580139
favorite count: 0
tagged with: python-3.x
has body: The function should delete arguments between () and insert them as a single argument in the list. (Test test2) works. At (Test Test2) (Test3 Test4) it shows an error: if args[i].startswith('('): IndexError: list index out of range Here is the function: def format_args(args): start_string = None end_string = None in_string = False o_string = '' for i in range(1, len(args)): if args[i].startswith('('): if not in_string: start_string = i in_string = True if in_string: if args[i].endswith(')'): o_string += args[i] end_string = i for r in range(start_string, end_string+1): args.pop(start_string) args.insert(start_string, o_string) o_string = '' in_string = False else: o_string += args[i] + ' ' return args inp = raw_input('args: ') args = inp.split(' ') args.insert(0, "test") print(format_args(args))
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/92239828
comment on: http://stackoverflow.com/a/52559642
type: AnswerComment
score: 0
type: Comment
has text: i'm not sure how you would even create such constraints in sqlite...it may not be possible due to the above.

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/52557058
tag name: lemmatization

http://stackoverflow.com/q/52486823
accepted answer: http://stackoverflow.com/a/52504543
type: Question
score: 5
has body: I want to make a QListWidget with a resize handle at the bottom (similar to text fields you see on webpages like this one). I've seen a few people asking the same question out there but did not find a complete example. I have some code which is nearly there, but it flickers during resize so I'm guessing there is something I am missing about resize policies or layouts or something... Here's my "working" example. The theory is pretty simple, you just measure the distance of the mouse move in the widget's mousePressEvent and resize/reposition accordingly. Unfortunately I'm missing something basic and I don't know what: from PyQt4 import QtGui import sys class Grip(QtGui.QLabel): def __init__(self, parent, move_widget): super(Grip, self).__init__(parent) self.move_widget = move_widget self.setText("+") self.min_height = 50 self.mouse_start = None self.height_start = self.move_widget.height() self.resizing = False self.setMouseTracking(True) def showEvent(self, event): super(Grip, self).showEvent(event) self.reposition() def mousePressEvent(self, event): super(Grip, self).mousePressEvent(event) self.resizing = True self.height_start = self.move_widget.height() self.mouse_start = event.pos() def mouseMoveEvent(self, event): super(Grip, self).mouseMoveEvent(event) if self.resizing: delta = event.pos() - self.mouse_start height = self.height_start + delta.y() if height &gt; self.min_height: self.move_widget.setFixedHeight(height) else: self.move_widget.setFixedHeight(self.min_height) self.reposition() def mouseReleaseEvent(self, event): super(Grip, self).mouseReleaseEvent(event) self.resizing = False def reposition(self): rect = self.move_widget.geometry() self.move(rect.right(), rect.bottom()) class Dialog(QtGui.QDialog): def __init__(self): super(Dialog, self).__init__() layout = QtGui.QVBoxLayout() self.setLayout(layout) list_widget = QtGui.QListWidget() layout.addWidget(list_widget) gripper = Grip(self, list_widget) layout.addWidget(QtGui.QLabel("Test")) self.setGeometr…
tagged with: pyqt4
has title: Custom QSizeGrip to resize a QListWidget
has answer: http://stackoverflow.com/a/52489219
has answer: http://stackoverflow.com/a/52504543
has answer: http://stackoverflow.com/a/52489556
tagged with: pyqt
possible better answer: http://stackoverflow.com/a/52489219
has answer: http://stackoverflow.com/a/52489234
favorite count: 0
tagged with: qlistwidget
upvote count: 5
tagged with: python
answer count: 4
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52542812
has answer: http://stackoverflow.com/a/52542948
tagged with: python
tagged with: append
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/92025552
has title: Appending to a new list for every loop
accepted answer: http://stackoverflow.com/a/52542948
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/92025674
answer count: 1
downvote count: 0
favorite count: 0
has body: I am running a for loop and appending a value into a list for every file run in loop. When I use append(), during the second run through the for loop it appends the new values into the same list as in the first run through loop. Is there a way to append and create a new list everytime it runs through loop? phaseresult_i =[] for i in range(len(folder)): data = np.loadtxt(dir + folder[i]) time = data[:,0]-2450000 magnitude = data[:,1] print ('File:', folder[i],'\n','Time:',time,'\n', 'Magnitude:', magnitude) print(len(time), len(magnitude)) for t in range(len(time)): #print(t,time[t]) floor = math.floor((time[t]-time[0])/Period) phase_i = ((time[t]-time[0])/Period)-floor phaseresult_i.append(phase_i) print(len(time), len(phaseresult_i)) The length of the array of time and length of array of phase result is not the same after the second time through loop.

http://stackoverflow.com/q/52456976
type: AnsweredQuestion
tagged with: loops
tagged with: methods
has title: How to run the same method concurrently without waiting for loop to end?
type: Question
has body: As seen in my code below, I have a function that produces an animation of a circle when the user clicks on the window. My problem is, for me to have another circle appear and move after one is already spawned, I have to wait for the previous one to finish its loop of movement. After one circle has finished its "i in range" loop at the end of the snowfall function, then I can click and produce another circle. I want to be able to click at any time and have as many circles moving simultaneously as I want (I'm aware I've limited it to 10 times in the code under the function). It looks like I need away to run the same method multiple times concurrently. from graphics import* from random import* win = GraphWin("Graphics Practice", 500, 500) colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"] def snowfall(randColour): point = win.getMouse() circle = Circle(point, 40) circle.draw(win) circle.setFill(colours[randColour]) for i in range(1000): circle.move(0, 1) time.sleep(0.002) randColour = randint(0, 8) for i in range (10): repeatColour = randColour snowfall(randColour) randColour = randint(0, 8) while randColour == repeatColour: randColour = randint(0, 8) win.getMouse() win.close() One of my failed attempts at multithreading this: from graphics import* from random import* win = GraphWin("Graphics Practice", 500, 500) colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"] def snowfall(randColour): point = win.getMouse() circle = Circle(point, 40) circle.draw(win) circle.setFill(colours[randColour]) for i in range(1000): circle.move(0, 1) time.sleep(0.002) randColour = randint(0, 8) t1 = threading.Thread(target = snowfall, args = randColour) for i in range (10): repeatColour = randColour t1.start() t1.join() randColour = randint(0, 8) while randColour == repeatColour: randColour = randint(0, 8) win.getMouse() win.close() Most recent code: from graphics import* from random import* win = GraphWin("Grap…
tagged with: concurrency
accepted answer: http://stackoverflow.com/a/52481403
score: 0
tagged with: function
answer count: 1
has answer: http://stackoverflow.com/a/52481403
has comment: http://stackoverflow.com/comment/91856234
tagged with: python

http://stackoverflow.com/q/52552838
has answer: http://stackoverflow.com/a/52556632
type: Question
has title: Django: Require admin approval for patch and post
has answer: http://stackoverflow.com/a/52555959
answer count: 3
downvote count: 0
tagged with: admin
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/52552913
tagged with: rest
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm trying to write my REST API in Django so that if someone makes a patch or post it will require someone with access to Django's admin panel to actually write the changes, but it'll be pending and visible to the admin till then, is this possible? Or do I have to create a model for the pending request then make the patch and post create new entities?
score: 3
upvote count: 3

http://stackoverflow.com/comment/91965608
has text: Or have I misunderstood? You have duplicate names under different user_id? It would be better if you could give an example, it's not clear exactly what is duplicated or the criteria for determining a duplicate since names are notoriously difficult to deal with
comment on: http://stackoverflow.com/q/52512819
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52513200
type: Question
tagged with: for-loop
tagged with: python-2.7
score: 0
answer count: 2
has title: Adding two list into a dictionary and allowing values with similar titles to merge
has body: I have just imported some columns into two lists in python. I am trying to add both lists together into a dictionary and have unique objects with totaled values. For example, 'Apple' and 'Apple' will return 'Apple': 14.0' since both are combined together. How do I produce the desired output? Do I have to add anything to my for loop? listA = ['Apple', 'Apple', 'Banana', 'Orange', 'Pineapple', 'Pineapple'] listB = ['5.0', '9.0', '12.0', '2.0', '8.0', '1.0'] dict={} for i, x in zip((listA),(listB)): dict[i]=x Output: {'Apple':'9.0', 'Banana':'12.0', 'Orange':'2.0', 'Pineapple':'1.0'} Desired output: {'Apple':'14.0', 'Banana':'12.0', 'Orange':'2.0', 'Pineapple':'9.0'}
has answer: http://stackoverflow.com/a/52513287
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52513296
accepted answer: http://stackoverflow.com/a/52513296
possible better answer: http://stackoverflow.com/a/52513287

http://stackoverflow.com/q/52508293
tagged with: inequalities
has comment: http://stackoverflow.com/comment/91957975
type: Question
tagged with: constraints
has comment: http://stackoverflow.com/comment/91985447
has comment: http://stackoverflow.com/comment/91957667
tagged with: solver
has comment: http://stackoverflow.com/comment/92020636
has comment: http://stackoverflow.com/comment/91957760
has comment: http://stackoverflow.com/comment/91959225
has comment: http://stackoverflow.com/comment/91957863
has comment: http://stackoverflow.com/comment/91956954
has comment: http://stackoverflow.com/comment/91957776
has comment: http://stackoverflow.com/comment/91957818
has comment: http://stackoverflow.com/comment/91959474
has comment: http://stackoverflow.com/comment/91956982
has comment: http://stackoverflow.com/comment/91991343
score: 0
has comment: http://stackoverflow.com/comment/91985342
tagged with: python
has comment: http://stackoverflow.com/comment/91958900
tagged with: linear-programming
has comment: http://stackoverflow.com/comment/91985588
has comment: http://stackoverflow.com/comment/91957836
answer count: 0
has comment: http://stackoverflow.com/comment/91985562
has body: I feel like there is an elegant Python solution for this problem that I've been trying to solve with VBA. Can someone please help? How can I generate a list of numbers that meet the following criteria: Are all integers The total is first split between types. The numbers are further split into subtypes and optimized to meet the required percentages. The total sum does not exceed the specified Total. Example of this problem: You plan to build a maximum of 102 residential units. Construction type: 40% of them will be Studios and 60% will be Townhouse construction type. (Could have more or fewer types) There are two Priority lists for the future occupants for the apartments: Assisted and Unassisted The unit allocation percentages in the Assisted(A) list are required to be fully met and the Unassisted(U) list is flexible. We'd like the Unassisted(U) list to be up to 20% of the Total units if possible, but we definitely need a minimum of 80% of the Total units to be Assisted(A) units. The Assisted(A) units are a total of 102x80% = 81.6 units (already not an integer) A minimum of 10% of the Assisted(A) list units must be for elderly individuals. A minimum of 40% of the Assisted(A) list units must be for families. The remaining 50% of the Assisted(A) list units are for aspiring data scientists. The remaining 20% of the Total units are Unassisted(U) occupancy units. So: Total: 102 units. Construction_type_categories=[.4, .6] (102 units split into Studios and Townhouses: 40% and 60%) Assisted=[.1,.4,.5] (80%+ of the total units are Assisted, further categorized as elderly, family, other occupancy according to the percentages in the list) Unassisted units are the remaining units that were not part of the 80%+ of the Assisted list. (up to 20% of total units) Result: [4,16,12,8,7,25,19,11] Breakdown: 4 Studio Units Assisted for elderly 16 Studio Units Assisted for families 12 Studio Units for other Assisted occupancy type 8 Studio Units (Unassisted) 7 Townhouse Units Assisted fo…
has title: Dynamically generate constrained solutions that meet multiple criteria
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91959579

http://stackoverflow.com/comment/92000935
has text: Still not clear on what the precise problem is. If you want to read in a whole load of files you can store the data in an array. For example an array of shape `(N_files, N_cols, N_entries)`. Then you can access whatever data you need based on position in the array.
type: QuestionComment
comment on: http://stackoverflow.com/q/52487727
score: 0
type: Comment

http://stackoverflow.com/comment/92016618
type: QuestionComment
type: Comment
has text: all the characters in you example are [ASCII](http://www.asciitable.com/) char
score: 1
comment on: http://stackoverflow.com/q/52538443

http://stackoverflow.com/comment/92078062
score: 0
type: QuestionComment
type: Comment
has text: Unrelated sidenote: these are terrible passwords, you should **never** use them.
comment on: http://stackoverflow.com/q/52570225

http://stackoverflow.com/q/52450422
accepted answer: http://stackoverflow.com/a/52450606
has answer: http://stackoverflow.com/a/52450556
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52450606
has body: I have the following dataframe: d = {'Postcode': ['M3A','M4A','M5A','M6A','M9A','M1B'], 'Borough': ['North York', 'Downtown Toronto', 'Etobicoke', 'Scarborough', 'East York', 'York'], 'Neighbourhood': ['Parkwoods', 'Victoria Village', 'Harbourfront', 'Regent Park', 'Lawrence Heights', 'Lawrence Manor']} post_df = pd.DataFrame(data = d) Which yields something like: Postcode Borough Neighbourhood 0 M3A North York Parkwoods 1 M4A Downtown Toronto Victoria Village 2 M5A Etobicoke Harbourfront 3 M6A Scarborough Regent Park 4 M9A East York Lawrence Heights 5 M1B York Lawrence Manor I want to get all the latitudes and longitudes for each postal code. I figured out this code to do so: import geocoder # initialize your variable to None lat_lng_coords = None # loop until you get the coordinates while(lat_lng_coords is None): g = geocoder.google('{}, Toronto, Ontario'.format(postal_code_from_df)) lat_lng_coords = g.latlng latitude = lat_lng_coords[0] longitude = lat_lng_coords[1] now my question is: Using the previous code, I would like to get each latitude and longitude for each postal code and add them to 2 new columns in this existing df called 'Latitude' and 'Longitude'. How could I do that using a single loop to avoid searching each postal code coordinates one by one? Thank you very much in advance
possible better answer: http://stackoverflow.com/a/52450556
type: AnsweredQuestion
has title: How to get coordinates from postal codes and add them into df using a loop
tagged with: loops
tagged with: coordinates
type: Question
answer count: 2

http://stackoverflow.com/q/52517273
score: 19
has answer: http://stackoverflow.com/a/52518438
linked to: http://stackoverflow.com/q/5409450
has body: I'm using two different decorators from two different libraries. Lets say: @decorator1(param1, param2) and @decorator2(param3, param4). That I often use in many functions as: from moduleA import decorator1 from moduleB import decorator2 @decorator2(foo='param3', bar='param4') @decorator1(name='param1', state='param2') def myfunc(funcpar1, funcpar2): ... Since it happens every time, I would like to create a custom decorator that handle both of them. Something like: @mycustomdecorator(name='param1', state='param2', foo='param3', bar='param4') def myfunc(funcpar1, funcpar2): ... How do I achieve that?
has comment: http://stackoverflow.com/comment/91976014
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91974212
downvote count: 0
has comment: http://stackoverflow.com/comment/92047237
has comment: http://stackoverflow.com/comment/91974289
type: Question
possible better answer: http://stackoverflow.com/a/52518813
upvote count: 19
has comment: http://stackoverflow.com/comment/91976320
answer count: 3
has title: Merging Python decorators with arguments into a single one
accepted answer: http://stackoverflow.com/a/52518438
tagged with: python-decorators
favorite count: 0
has answer: http://stackoverflow.com/a/52518457
has comment: http://stackoverflow.com/comment/91974331
duplicate of: http://stackoverflow.com/q/5409450
has answer: http://stackoverflow.com/a/52518813
has comment: http://stackoverflow.com/comment/91975467
has comment: http://stackoverflow.com/comment/91974092
tagged with: python
has comment: http://stackoverflow.com/comment/91974394

http://stackoverflow.com/a/52479283
score: 2
has comment: http://stackoverflow.com/comment/91932054
has body: You may use subprocess.PIPE to pass data between your main process and spawned subprocess. Main script: import subprocess def main(): for idx in range(3): a = input( 'Please enter parameter to pass to subprocess ({}/{}): ' .format(idx + 1, 3)) print('Child in progress...') pipe = subprocess.Popen( args='python child.py', stdin=subprocess.PIPE, stdout=subprocess.PIPE) pipe.stdin.write(str(a).encode('UTF-8')) pipe.stdin.close() print('Child output is:') print(pipe.stdout.read().decode('UTF-8')) if __name__ == '__main__': main() Child script: import sys import time def main(a): for dummy in range(3): time.sleep(.1) print(a) if __name__ == '__main__': a = sys.stdin.read() main(a) Output: &gt;&gt;&gt; python main.py Please enter parameter to pass to subprocess (1/3): qwe Child in progress... Child output is: qwe qwe qwe Please enter parameter to pass to subprocess (2/3): qweqwe Child in progress... Child output is: qweqwe qweqwe qweqwe Please enter parameter to pass to subprocess (3/3): 123 Child in progress... Child output is: 123 123 123
has comment: http://stackoverflow.com/comment/91908344
has comment: http://stackoverflow.com/comment/91934304
upvote count: 3
has comment: http://stackoverflow.com/comment/91933833
answers question: http://stackoverflow.com/q/52478339
type: Answer
downvote count: 1

http://stackoverflow.com/q/52482614
has body: I have a ZMQ feed and a scheduler from package Schedule that I am trying to call in different while loops. The zmq feed will run for 3 hours then my scheduler from package Schedule will run my processing function which stops the ZMQ process cleanly (currently using multiprocessing) do the actual processing on the data then restart the process at the end of the function. The reason im doing this currently is because I believe there is an issue with multi threading continuously appending zmq feed data to the dataframe while the actually data processing is happening. So that leads me to using multi processing. I have tried just creating processes out of the functions then starting them and calling join process = Process(target = run, args = ('bob',)) process1 = Process(target = schedule1, args = 'bob',) process.start() process1.start() process.join() process1.join() and with Pool(2) as p: p.map(process, "1") p.map(process1, "1") run and schedule 1 are my functions with Pool(2) as p: p.map(schedule1, "1") p.map(run, "1") Just tried this above and now its just stuck not printing anything from my while loops telling me its active. So not sure whats goin on here and pool = Pool() result1 = pool.apply_async(schedule, '1') result2 = pool.apply_async(run, '1') They all don't work and do not start any of my two while loops. While multithreading could at least do that. The reason I moved to multiprocessing was due to the fact that I can stop and start processing at will cleanly and easily with .terminate() then .join(), then restart it with .start() .join() Any help would be useful or any pointers to where I'm going wrong. The arguments in all the functions are dummy arguments built in for the .map because you need to pass arguments.
has comment: http://stackoverflow.com/comment/91911091
score: 0
tagged with: pandas
tagged with: python
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/91911533
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/91907528
tagged with: multiprocessing
type: Question
has title: Problem with Multi-Threading/Multi-Processing

http://stackoverflow.com/comment/134584368
comment on: http://stackoverflow.com/a/52456914
score: 0
type: Comment
type: AnswerComment
has text: Just to complement this answer: `&` is the logical `AND` operator, `|` is the logical `OR` and `~` is the logical `NOT`

http://stackoverflow.com/q/52470819
has comment: http://stackoverflow.com/comment/91883770
tagged with: mysql
has comment: http://stackoverflow.com/comment/91884320
has title: Converting the return value of a SELECT in mysql
has answer: http://stackoverflow.com/a/52478789
accepted answer: http://stackoverflow.com/a/52478789
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/91883733
tagged with: python
has body: I'm fairly new to MySQL so I'm not sure if I'm thinking about this wrong, but I have a database column of type DATETIME. I populate this data using the following statement: INSERT INTO check_times (fullname, time) VALUES (%s, FROM_UNIXTIME(%s)) ON DUPLICATE KEY UPDATE time=FROM_UNIXTIME(%s) fullname is a unique string and I am either adding a new row or updating the time value if it already exists. The timestamp I have is a Unix timestamp but I store it in the database as a DATETIME so that I can see easily what date it is when viewing the data. My issue is that in my application I need to compare the timestamp I have in the app (a Unix timestamp) against the value in the database. When I get the value in the database I receive a datetime object (in python) and I am unable to compare the two values. How would I go about getting mysql to convert the returned datetime value back into a Unix timestamp, allowing for easy conversion? I thought it might be something like the following: SELECT UNIX_TIMESTAMP(time) FROM check_times WHERE fullname=%s based from this page, but it didn't work. Using the following python code I get a return value of a tuple containing (2018, ) cursor = self.connection.cursor() cursor.execute("SELECT UNIX_TIMESTAMP(time) FROM check_times WHERE fullname=%s", (fullname,)) time = cursor.fetchone() cursor.close() If I run the above code but with the command SELECT time FROM check_times WHERE fullname=%s instead I get a tuple with a datetime.datetime object of the date stored in the database. I'm not sure what terms I can google as everything I try doesn't return helpful information. Thanks
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/91806779
type: QuestionComment
has text: If you don't know the purpose of a constant, have a look at the [docs](https://docs.python.org/3/library/socket.html#socket.AF_INET).
comment on: http://stackoverflow.com/q/52431424
type: Comment
score: 1

http://stackoverflow.com/comment/91872137
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52465094
has text: unique modulus numbers means the modulus values( for example 421 mod 26 ) calculated for each randomly selected numbers should be different or select 16 random numbers those having different modulus values from 1 to 26 as mentioned above.
score: 0

http://stackoverflow.com/a/52549719
has body: From the docs my approach would be: # Import libs import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata from matplotlib.path import Path from matplotlib.patches import PathPatch # Create some example data x = np.array([1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6]) y = np.array([1,2,3,4,2,3,4,5,3,4,5,6,4,5,6,7,5,6,7,8,6,7,8,9]) z = np.linspace(0,100,len(y)) # Grid and interpolate between points yi, xi = np.mgrid[int(y.min()):int(y.max()),int(x.min()):int(x.max())] zi = griddata((x, y), z, (xi, yi), method='nearest') # Plot the figure im = plt.imshow( zi, extent=[x.min(), x.max(), y.min(), y.max()], origin="lower", interpolation='bicubic', aspect='auto', clip_path=patch, clip_on=True) plt.colorbar() path = Path([[1, 1], [1, 4], [6, 9], [6, 6], [1, 1]]) patch = PathPatch(path, facecolor='none') plt.gca().add_patch(patch) im.set_clip_path(patch) For calculating the corners of your area you could define a function: def corners(x, y): xl = np.min(x) yl = np.min(y) xh = np.max(x) yh = np.max(y) return [[xl, yl], [xl, np.max(y[x==xl])], [xh, yh], [xh, np.min(y[x==xh])], [xl, yl]] and replace the explicit points in the patch with that: ... path = Path(corners(x, y)) ... EDIT: with patch = PathPatch(path, facecolor='none', edgecolor='none') you can purely clip, without necessarily showing the edges of the clippath.
score: 3
answers question: http://stackoverflow.com/q/52548812
accepted answer of: http://stackoverflow.com/q/52548812
downvote count: 0
upvote count: 3
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52685243
type: Answer
answers question: http://stackoverflow.com/q/52573400
score: 0
has body: import json import boto3 import datetime from dateutil.tz import tzutc def lambda_handler(event, context): resource = boto3.resource('iam') client = boto3.client('iam') sns = boto3.client('sns') today = datetime.datetime.now() physicalString ='Below users not logged into AWS console for 90 days\n' final_report = '' final_result = '' number =int(1) for user in resource.users.all(): if user.password_last_used is not None: delta = (today - user.password_last_used.replace(tzinfo=None)).days if delta &gt;= 0: final_result= str(number) + " username: "+ [user.user_name][0]+" - "+str(delta) + "days\n" final_report = final_report+final_result number=number+1 response = sns.publish( TopicArn='arn:aws:sns:XXXXXXXXXXXX:AWS_KMSKEY', Message= physicalString + final_report, Subject='IAM USER' ) above code is working we are able to get list of users output as below:- 1 username: abc- 102days 2 username: efg- 190days 3 username: zyz- 164days

http://stackoverflow.com/q/52494128
has answer: http://stackoverflow.com/a/52500454
has comment: http://stackoverflow.com/comment/91928956
answer count: 10
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52500454
has answer: http://stackoverflow.com/a/52494213
has answer: http://stackoverflow.com/a/52494329
linked to: http://stackoverflow.com/q/4978738
downvote count: 1
has answer: http://stackoverflow.com/a/52494369
type: Question
accepted answer: http://stackoverflow.com/a/52494213
has answer: http://stackoverflow.com/a/52510401
has comment: http://stackoverflow.com/comment/91929191
linked to: http://stackoverflow.com/q/16576553
has answer: http://stackoverflow.com/a/59856978
has answer: http://stackoverflow.com/a/59042633
has answer: http://stackoverflow.com/a/74616175
score: 84
has body: There's a function which takes optional arguments. def alpha(p1="foo", p2="bar"): print('{0},{1}'.format(p1, p2)) Let me iterate over what happens when we use that function in different ways: &gt;&gt;&gt; alpha() foo,bar &gt;&gt;&gt; alpha("FOO") FOO,bar &gt;&gt;&gt; alpha(p2="BAR") foo,BAR &gt;&gt;&gt; alpha(p1="FOO", p2=None) FOO,None Now consider the case where I want to call it like alpha("FOO", myp2) and myp2 will either contain a value to be passed, or be None. But even though the function handles p2=None, I want it to use its default value "bar" instead. Maybe that's worded confusingly, so let me reword that: If myp2 is None, call alpha("FOO"). Else, call alpha("FOO", myp2). The distinction is relevant because alpha("FOO", None) has a different result than alpha("FOO"). How can I concisely (but readably) make this distinction? One possibility would usually be to check for None within alpha, which would be encouraged because that would make the code safer. But assume that alpha is used in other places where it is actually supposed to handle None as it does. I'd like to handle that on the caller-side. One possibility is to do a case distinction: if myp2 is None: alpha("FOO") else: alpha("FOO", myp2) But that can quickly become much code when there are multiple such arguments. (exponentially, 2^n) Another possibility is to simply do alpha("FOO", myp2 or "bar"), but that requires us to know the default value. Usually, I'd probably go with this approach, but I might later change the default values for alpha and this call would then need to be updated manually in order to still call it with the (new) default value. I am using python 3.4 but it would be best if your answers can provide a good way that works in any python version. The question is technically finished here, but I reword some requirement again, since the first answer did gloss over that: I want the behaviour of alpha with its default values "foo", "bar" preserved in general, so it is (probably) not an …
has answer: http://stackoverflow.com/a/60667694
favorite count: 0
has title: Call function without optional arguments if they are None
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52495111
upvote count: 85

http://stackoverflow.com/comment/130315879
type: Comment
has text: Note, that if you install from a requirements.txt with `-r` you should first create the empty Pipfile, so that pipenv knows, next to where it should put .venv
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52540270

http://stackoverflow.com/q/52467049
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has body: Suppose we have a following toy version of master-worker pipeline to parallel data collection # pip install gym import gym import numpy as np from multiprocessing import Process, Pipe def worker(master_conn, worker_conn): master_conn.close() env = gym.make('Pendulum-v0') env.reset() while True: cmd, data = worker_conn.recv() if cmd == 'close': worker_conn.close() break elif cmd == 'step': results = env.step(data) worker_conn.send(results) class Master(object): def __init__(self): self.master_conns, self.worker_conns = zip(*[Pipe() for _ in range(10)]) self.list_process = [Process(target=worker, args=[master_conn, worker_conn], daemon=True) for master_conn, worker_conn in zip(self.master_conns, self.worker_conns)] [p.start() for p in self.list_process] [worker_conn.close() for worker_conn in self.worker_conns] def go(self, actions): [master_conn.send(['step', action]) for master_conn, action in zip(self.master_conns, actions)] results = [master_conn.recv() for master_conn in self.master_conns] return results def close(self): [master_conn.send(['close', None]) for master_conn in self.master_conns] [p.join() for p in self.list_process] master = Master() l = [] T = 1000 for t in range(T): actions = np.random.rand(10, 1) results = master.go(actions) l.append(len(results)) sum(l) Because of the Pipe connections between master each worker, for every time step, we have to send a command to the worker through the Pipe, and the worker sends back the results. We need to do this for a long horizon. This will be sometimes a bit slow due to frequent communications. Therefore, I am wondering if by using latest Python feature asyncio combined with Process to replace Pipe, could it be potentially speedup due to IO concurrency, if I understand its functionality correctly.
tagged with: python-asyncio
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has title: Python (3.7+) multiprocessing: replace Pipe connection between master and workers with asyncio for IO concurrency
upvote count: 1
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/52467149

http://stackoverflow.com/a/52529109
has body: You can try the following list comprehension: length = [''.join([str(len(i)) for i in l]) for l in Names] Which gives you: &gt;&gt;&gt; length ['654', '756', '665'] You can convert this to int after using map if that's what you need: &gt;&gt;&gt; list(map(int, length)) [654, 756, 665] If I misunderstood your question, and instead you want a list of 3 lists, then you can do: length = [[len(i) for i in l] for l in Names] &gt;&gt;&gt; length [[6, 5, 4], [7, 5, 6], [6, 6, 5]]
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52529086
answers question: http://stackoverflow.com/q/52529086
type: Answer
score: 2

http://stackoverflow.com/q/52466282
possible better answer: http://stackoverflow.com/a/52466446
downvote count: 0
has answer: http://stackoverflow.com/a/52466446
type: Question
score: 3
upvote count: 3
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52466422
accepted answer: http://stackoverflow.com/a/52466422
favorite count: 0
has title: How to do array operation of a cell in Pandas
tagged with: python
has answer: http://stackoverflow.com/a/52466474
has body: Basically, my dataframe looks like this: id | refers ---------------- 1 | [2,3] 2 | [1,3] 3 | [] I want to add another column which show how many times that id is referred by another id. For example: id | refers | referred_count ---------------------------------- 1 | [2,3] | 1 2 | [1,3] | 1 3 | [] | 2 My current code looks like this: citations_dict = {} for index, row in data_ref.iterrows(): if len(row['reference_list']) &gt; 0: for reference in row['reference_list']: if reference not in citations_dict: citations_dict[reference] = {} d = data_ref.loc[data_ref['id'] == reference] citations_dict[reference]['venue'] = d['venue'] citations_dict[reference]['reference'] = d['reference'] citations_dict[reference]['citation'] = 1 else: citations_dict[reference]['citation'] += 1 The problem is that, this code takes so long. I am wondering how to do it faster, maybe using pandas?
type: AnsweredQuestion

http://stackoverflow.com/a/52454846
upvote count: 2
has comment: http://stackoverflow.com/comment/91859815
has body: The keys of data come from get_name_tag, whose values come from the result of the re.findall method, which returns a list of matching substrings with 1 capture group in you regex, which is why get_name_tag, as a list, gets converted to ['2018034'] when it is formatted with '%s' % get_name_tag. Change: get_name_tag = re.findall(".A(\d{7}).", all_files[i]) to: get_name_tag = re.findall(".A(\d{7}).", all_files[i])[0] and your code would work as expected.
accepted answer of: http://stackoverflow.com/q/52454775
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52454775
score: 2

http://stackoverflow.com/comment/92025253
comment on: http://stackoverflow.com/a/52541218
type: Comment
has text: Thanks for your reply. Would you care to elaborate a little bit more on your definition of "expensive" please? Do you mean that it will eat up more memory or is it more prone to error? Both methods give me what I want but the sorting of the results seem different. I will need to find time to compile your answer into the second method and compare the results. Thanks again
score: 0
type: AnswerComment

http://stackoverflow.com/a/52506615
has body: Using a filled numpy.ma.masked_array: a = df.A.values b = df.B.values c = list(map(dct.get, b)) out = np.ma.masked_array(b, np.in1d(a, sel)).filled(c) array(['u', 'x', 'w', 'v', 'y'], dtype=object) On smaller arrays, broadcasting offers a minor speedup: a = np.array(df.A) b = np.array(df.B) c = list(map(dct.get, b)) mask = (a[:, None] == sel).any(1) np.ma.masked_array(b, mask).filled(c)
upvote count: 3
answers question: http://stackoverflow.com/q/52506364
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/comment/91846254
has text: You could have stuck to `for i in li:` and used `x1=in_circle(i)` since you are not using an index anywhere. So using `range` is unnecessary here
comment on: http://stackoverflow.com/a/52451210
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/52505018
accepted answer: http://stackoverflow.com/a/52505184
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/16516623
has comment: http://stackoverflow.com/comment/91950889
type: Question
tagged with: arrays
has answer: http://stackoverflow.com/a/52505184
answer count: 1
has title: replace substrings based on index range with dictionary values from a string
tagged with: string
has comment: http://stackoverflow.com/comment/91950612
tagged with: python-3.x
has body: I have the following string/sentence ( not grammatically correct) s = "The user should be able to audit log to view the audit log entries." And I have a dictionary with similar keys: d = {'audit' : 'class1', 'audit log' : 'class2', 'audit log entries' : 'class3'} I'm able to get the index ranges of substrings which will match the keys in dictionary and I need to replace the keys matched with their values. final_ranges = [(49, 66), (27, 36)] #list length may vary I want to iterate over the index ranges and replace the substrings. I tried the following code: for i in final_ranges: for k,v in d.items(): if s[i[0]:i[1]] == k: print(s[0:i[0]] + v + s[i[1]:]) which will output: The user should be able to audit log to view the class3. The user should be able to class2 to view the audit log entries. But I want the substring replacements to occur in one sentence itself. The user should be able to class2 to view the class3. I went through this link . But it is not based on index ranges.
tagged with: python

http://stackoverflow.com/comment/91947420
has text: No, it's a handler for the signal `connection_created`. See [here](https://docs.djangoproject.com/en/2.1/topics/signals/) for how Django Signals works and especially scroll down to "Where should this code live?" to see where you put the code. Basically create a handlers.py file (or signals.py) inside your app and make sure you import it in `ready()` of apps.py
comment on: http://stackoverflow.com/q/52501435
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52582983
has body: roll_AI(player) only terminates if dice_value==1 but then sets point=0 and returns 0. So no points can add up towards 100
has comment: http://stackoverflow.com/comment/92102519
score: 0
answers question: http://stackoverflow.com/q/52582947
has comment: http://stackoverflow.com/comment/92101304
type: Answer
has comment: http://stackoverflow.com/comment/92101328

http://stackoverflow.com/comment/92047720
score: 0
has text: Thank you @gittert i added that, but the response i am getting is that name is not defined
type: AnswerComment
comment on: http://stackoverflow.com/a/52552849
type: Comment

http://stackoverflow.com/q/52559614
tagged with: python-2.7
score: 0
has body: I started learning python. I am wondering how to split a list that has two delimiters. INPUT 1,2,3,4,5;2 My code: with open(path, 'r') as f: for fs in f: ip= fs.rstrip('\n').split(',') print (ip) My output: ['1', '2', '3', '4', '5;2'] Desired output ['1', '2', '3', '4', '5', '2'] Can i please now how to remove the semicolon in the list. Thanks
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: python-requests
linked to: http://stackoverflow.com/q/4998629
downvote count: 1
duplicate of: http://stackoverflow.com/q/4998629
has answer: http://stackoverflow.com/a/52559664
has title: Spliting a python list with two delimeters
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52559690
favorite count: 0

http://stackoverflow.com/comment/92062322
score: 0
has text: @Nicole Please provide expected output
type: Comment
comment on: http://stackoverflow.com/q/52559308
type: QuestionComment

http://stackoverflow.com/a/52484711
has body: Let's fix your immediate issue: you have an else with no corresponding if statement. Syntactically, this is because you have an intervening "out-dented" statement, the print, which terminates your series of ifs. Logically, this is because you have two levels of decision: "Is this a number 0-20?", and "Within that range, how big is it?" The problem stems from writing only one level of ifs to make this decision. To keep close to your intended logic flow, write a general if on the outside, and encapsulate your small/medium/large decision and print within that branch; in the other branch, insert your "none of the above" statement: n = int(input("number= ")) if 0 &lt;= n &lt;= 20: if n &lt; 5: a = "small" elif n &lt; 10: a = "medium" else: a = "large" print("this number is", a) else: print("that's not a number from 0 to 20")
type: Answer
accepted answer of: http://stackoverflow.com/q/52484609
answers question: http://stackoverflow.com/q/52484609
upvote count: 3
has comment: http://stackoverflow.com/comment/91911183
has comment: http://stackoverflow.com/comment/91911945
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91917871
comment on: http://stackoverflow.com/q/52488269
type: QuestionComment
type: Comment
score: 1
has text: And what is the error or output (edit the questions to show it as properly formatted text)?

http://stackoverflow.com/comment/91986846
type: QuestionComment
has text: `a=np.linalg.lstsq(b,c)[0][None,:]` solves the matrix equation b*a-c=0 (by least squares), but it may be close enough to `abs`
comment on: http://stackoverflow.com/q/52523211
score: 0
type: Comment

http://stackoverflow.com/comment/92051492
comment on: http://stackoverflow.com/q/52556450
score: 1
has text: If that is a profile detail view, you surely have the `user` of the profile object readily available as a context variable.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92033529
score: 1
comment on: http://stackoverflow.com/q/52546813
type: Comment
type: QuestionComment
has text: Why are you doing this at all? Isn't the burden on the user to remember their login name?

http://stackoverflow.com/a/59701814
has comment: http://stackoverflow.com/comment/120670502
answers question: http://stackoverflow.com/q/52483266
has body: I might be a little to the party, but a more Pythonic way of doing this is using a map and a list comprehension. It can operate on a list of the list with any number of values. l = [['a','bob'],['a','bob'],['a','john']] [list(map(lambda x: x if x != 'bob' else 'b', i)) for i in l] it gives you the desired output [['a', 'b'], ['a', 'b'], ['a', 'john']] The main idea is that the inner loop is iterating through the inner loop and using the simple lambda function to perform the replacement. I hope that this helps anyone else who is looking out for something similar.
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/52521857
downvote count: 0
answers question: http://stackoverflow.com/q/52521594
has body: Join the path and the filename together and pass that to pd.to_csv: import os path = 'C:\Users\ab\Desktop\conversion' output_file = os.path.join(path,'Combined Book.csv') final2.to_csv(output_file, index=False)
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/comment/91949596
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52504497
has text: Use `[a-zA-Z0-9]` to match any of these characters.
score: 0

http://stackoverflow.com/q/52529353
has body: I have a dictionary as follows: d = {key: [val1, val2, val3....], key2: [valx, valy, valz, ...], key3: [vala, valb, valc, ...], ....} If I want to print the key and the select the second element for all the keys, meaning in this example, I want to show: key: val2 key2: valy key3: valb What do I write?
has answer: http://stackoverflow.com/a/52529424
has answer: http://stackoverflow.com/a/52529443
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52530098
has title: How to select nth element from all the keys?
has answer: http://stackoverflow.com/a/52529420
has comment: http://stackoverflow.com/comment/92099330
type: Question
has comment: http://stackoverflow.com/comment/92100137
has comment: http://stackoverflow.com/comment/91997928
score: 0
has comment: http://stackoverflow.com/comment/91998586

http://stackoverflow.com/comment/91902216
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52479249
has text: @It'sNele After a first(wrong) answer I've updated a new one. Check it :)

http://stackoverflow.com/comment/92082681
score: 3
comment on: http://stackoverflow.com/q/52572434
type: Comment
type: QuestionComment
has text: I'd expect the executable you're looking for to be in `/usr/local/bin` after you install it. Do you see it there? It might be named more specifically than you want (e.g. `python3.6`, not just `python3`). You can probably fix that with a symlink. In any case, your `PATH` should name a folder, not a specific file.

http://stackoverflow.com/q/52570005
downvote count: 1
has title: Run python script function in remote machine
has comment: http://stackoverflow.com/comment/92077006
type: Question
has body: I have script in remote device and I want to run specific function in python script in remote device remote device has below script: #connect.py class ConnectDevice: def __init__(self, ip): connect.Device(ip) def get_devicestate(self): state = show.Device_State return state configured password less connection from source machine to remote machine function get_devicestate return up or down. How to get get_devicestate output from source machine. source machine has below script: import os import sys import time import getpass import errno import json import subprocess import threading from subprocess import call from subprocess import check_output call(["ssh", "1.1.1.1", "\"python Connect.py\""])#This is just example how to run script from source to remote. Need help how to run function get_devicestate and get value.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92077156
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/52570288
tagged with: python
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/92048119
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52553318
has text: I have tried to change manually the default user agent with the following command: scrapy shell -s USER_AGENT="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36" 'https://www.ftse.com/products/indices/uk'. but the response I get is still incomplete
score: 0

http://stackoverflow.com/a/52481403
type: Answer
has comment: http://stackoverflow.com/comment/91922951
has comment: http://stackoverflow.com/comment/91999617
has body: One problem is that you are attempting to join thread t1 immediately after starting it. To join a thread is to wait for it to finish, so instead of starting ten threads, you are starting and then waiting for a thread ten times. However, threading is the wrong approach here. Most graphics packages do not allow multiple threads to draw to the same graphics context, for good reasons of performance and fluidity. This means that you need to turn your drawing threads "inside out", putting the state of each animated object in a "sprite", so that the state of each animated object is in its own instance. Then, instead of using separate threads for each sprite, you run through all your sprites and update them in a single loop, as shown below. (Note that I introduced win.checkMouse(), which does a non-blocking check for a mouse event, and therefore allows you to add a sprite per click, which is what I believe you intended.) from graphics import * from random import * win = GraphWin("Graphics Practice", 500, 500) colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"] class Snowflake(object): def __init__(self, randColour, point): self.circle = Circle(point, 40) self.circle.draw(win) self.circle.setFill(colours[randColour]) def next_frame(self): self.circle.move(0, 1) randColour = randint(0, 8) sprites = [] for i in range(100): point = win.checkMouse() if point: randColour = randint(0, 8) sprites.append(Snowflake(randColour, point)) for s in sprites: s.next_frame() time.sleep(0.1) win.close()
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92015672
has comment: http://stackoverflow.com/comment/92017845
has comment: http://stackoverflow.com/comment/91913380
upvote count: 2
has comment: http://stackoverflow.com/comment/92017937
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91949392
accepted answer of: http://stackoverflow.com/q/52456976
has comment: http://stackoverflow.com/comment/92015134
has comment: http://stackoverflow.com/comment/92018745
has comment: http://stackoverflow.com/comment/92017969
answers question: http://stackoverflow.com/q/52456976

http://stackoverflow.com/q/52510443
possible better answer: http://stackoverflow.com/a/52510581
has comment: http://stackoverflow.com/comment/91960886
score: 0
has title: Use numpy.random.seed() when selecting subset of rows from large csv w/o knowing exact length
accepted answer: http://stackoverflow.com/a/52510850
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/845058
has body: train_df = pd.read_csv(train_file, header=0, skiprows=lambda i: i&gt;0 and random.random() &gt; 0.3) I had this but realized this won't be reproducible. Is there a way to randomly select a subset of rows from a large csv without knowing the length of that file in a reproducible manner? Seems like this is something read_csv would support. I know there is a function df.sample(random_state=123) However, Id need this functionality when reading in the csv because of the size of the file. I know for certain that the number of rows is more than 900k, so I can do... np.random.seed(42) skip = np.random.randint(0,900000,200000) train_df = pd.read_csv(train_file, header=0, skiprows=skip) But this doesn't give every row an equal chance of making it into the sample, so not ideal. Can read_csv scan a csv and return the length of the file?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52510581
has answer: http://stackoverflow.com/a/52510850
has answer: http://stackoverflow.com/a/52510632
type: Question

http://stackoverflow.com/comment/92037032
has text: print doesn't seem to do anything - maybe because it's a subprocess?
type: AnswerComment
comment on: http://stackoverflow.com/a/52529700
score: 0
type: Comment

http://stackoverflow.com/comment/92092976
type: Comment
comment on: http://stackoverflow.com/a/52578896
has text: Not in this case, since he sorts the columns and then does both, use the keys as the header line and then write each value in the same order: `[str(o[col]) for col in cols]`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91912915
type: AnswerComment
has text: to run this code do i need to ad import numpy as np? what other ones would i need to use? could you edit that in then i will run it and accept your answer!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52485654

tcp
tags question: http://stackoverflow.com/q/52503413
type: Tag
tags question: http://stackoverflow.com/q/52537487
tags question: http://stackoverflow.com/q/52431424
tags question: http://stackoverflow.com/q/52462500
tags question: http://stackoverflow.com/q/52578146
tag name: tcp

http://stackoverflow.com/q/52565921
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52566083
upvote count: 2
has comment: http://stackoverflow.com/comment/92069400
possible better answer: http://stackoverflow.com/a/52566002
tagged with: python
has answer: http://stackoverflow.com/a/52566002
accepted answer: http://stackoverflow.com/a/52566083
type: AnsweredQuestion
score: 1
has body: t = ("rotation: %d%%\t [note]"% 123) in jupyter notebook when you type t and run cell output: rotation: 123%\t [note] I want to get result is follow here: output: rotation: 123% [note]
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92069627
has comment: http://stackoverflow.com/comment/92069443
linked to: http://stackoverflow.com/q/19331404
has title: why "%" in python string invalidates the transfer character
answer count: 2
has comment: http://stackoverflow.com/comment/92069511

http://stackoverflow.com/a/52785455
downvote count: 0
score: 1
has body: VSCODE working fine for me a) Install VSCODE or upgrade to version 1.28.1 b) REFRESH Python Extension If you face any issue like timeout etc read https://github.com/Microsoft/vscode-python/issues/2410 very carefully Edit settings.json of python extension a) Disable Terminal: Activate Environment Activate Python Environment in Terminal created using the Extension. b) enable Terminal: Execute In File Dir When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder. c) Remove pythonW and put python in Python Path Path to Python, you can use a custom version of Python by modifying this setting to include the full path. Everything above from https://github.com/Microsoft/vscode-python/issues/2410 Though a happy ending I can foresee a future of unstable releases for a wonderful VSCODE and even better Python Extension
upvote count: 1
answers question: http://stackoverflow.com/q/52462326
type: Answer

http://stackoverflow.com/comment/91869212
type: QuestionComment
score: 1
has text: Possible duplicate of [Bottle.py HTTP Auth?](https://stackoverflow.com/questions/13272528/bottle-py-http-auth)
comment on: http://stackoverflow.com/q/52461587
type: Comment

http://stackoverflow.com/a/52485176
has body: It is advised to use normal python lists and then at the end convert the list to a numpy array. x = np.asarray(x)
downvote count: 1
score: -1
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52485119

http://stackoverflow.com/q/52452687
has answer: http://stackoverflow.com/a/52452722
answer count: 1
downvote count: 0
has title: Django ImageField will not display on webpage
favorite count: 0
has body: I am using an imageField in my Django model and the photo is not being recognized when I try to display it in the html. Here is my models.py from django.db import models class LatestRelease(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=300) cover = models.ImageField(upload_to='personal/static/img/') display = models.BooleanField(default=True) Here is view.py from django.shortcuts import render from personal.models import LatestRelease def index(request): releases = LatestRelease.objects.all() return render(request, "personal/home.html", {'releases': releases}) HTML code {% for release in releases %} &lt;img src="{{ release.cover.url }}" class='' height='235' width='235'&gt; {% endfor %} So basically, the image path {{ release.cover.url }} is /personal/static/img/[image name] and my photos only appear to show up when I use the url path /static/img/[image name] as the source. Is there anyway to take /personal out of the string that is created from {{ release.cover.url }} ? Or to make it so that my img source accepts files under /personal/static/img/[image name]?
tagged with: model
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/52452722
type: AnsweredQuestion
score: 4
tagged with: imagefield
type: Question
upvote count: 4

http://stackoverflow.com/q/52500736
has comment: http://stackoverflow.com/comment/91942274
has body: I am trying to solve some Reinforcement learning problems. For this I want to get a basic example with a 2D grid (graphically, not just with X's or something) to create an RL task on it. I use Pycharm and tried the following code I saw in an online tutorial. But nothing graphically appears on my display when I run it. Can anyone help me with this? from cmath import rect from tensorflow import fill, size grid = [ [-1]*8 for n in range(8)] grid[0][0]=-1 grid [7][7]=-1 w=70 def setup(): size(800, 600) def draw(): x,y = 0,0 #starting position for row in grid: for col in row: if col == 1: fill(250,0,0) else: fill(255) rect(x,y,w,w) x=x+w # move right y=y+w #move down x = 0 #rest to left edge
has comment: http://stackoverflow.com/comment/91942288
answer count: 0
has comment: http://stackoverflow.com/comment/91942319
type: UnansweredQuestion
tagged with: python
has title: How to create a 2d mesh with points on it graphically in Python (Pycharm)?
has comment: http://stackoverflow.com/comment/91942092
tagged with: 2d
has comment: http://stackoverflow.com/comment/91942663
has comment: http://stackoverflow.com/comment/91942397
type: Question
has comment: http://stackoverflow.com/comment/91942644
score: 0

http://stackoverflow.com/comment/119623604
comment on: http://stackoverflow.com/q/52561549
score: 0
type: Comment
type: QuestionComment
has text: Hey, Neil. If you ever made any progress on this I'd love to know because I'm trying to do the same thing. I have a python application that acts as a bluetooth slave and I would like it to be able to reconnect to the master when the app is restarted. I think the app needs to initiate the bluetooth connection as a slave and then somehow indicate to the master that it should reconnect to a specific service uuid that the slave is providing. This seems to be a pretty standard use case with my real bluetooth devices, but reverse engineering it has been challenging.

http://stackoverflow.com/a/52540957
has comment: http://stackoverflow.com/comment/92053928
type: Answer
has body: Since your text report fields are of a fixed length, you could extract the header with one function and the data with another one. So, in your sample each row of data is 151 characters. Since the header is much shorter, you can easily know if the row in the current loop is from the header or it is data. I would suggest to split the row by ':' if it is header and by '|' if it is data. By the end of the loop, you will have each row with the fields properly separated. If you have further trouble with managing the data, or you need more detail, I suggest regex module.
upvote count: 1
answers question: http://stackoverflow.com/q/52537776
score: 1
has comment: http://stackoverflow.com/comment/92049757
downvote count: 0
has comment: http://stackoverflow.com/comment/92053904

http://stackoverflow.com/q/52578323
type: Question
has title: missing stop words from spacy en_core_web_lg
tagged with: stanford-nlp
tagged with: nltk
possible better answer: http://stackoverflow.com/a/52579036
upvote count: 2
answer count: 2
has body: I downloaded en_core_web_lg(en_core_web_lg-2.0.0) but when I load it and used it on spacy. But it seems to miss lots of basic common stop words such as "be", "a" etc. Am I missing correct version ? import nltk n = nltk.corpus.stopwords.words('english') "be" in n O/P: True import spacy nlp = spacy.load("en_core_web_lg") nlp.vocab["be"].is_stop O/P: False
accepted answer: http://stackoverflow.com/a/52581357
favorite count: 0
has answer: http://stackoverflow.com/a/52579036
has answer: http://stackoverflow.com/a/52581357
tagged with: python
tagged with: nlp
type: AnsweredQuestion
tagged with: spacy
score: 1
downvote count: 1

http://stackoverflow.com/comment/92027591
comment on: http://stackoverflow.com/q/52543649
type: QuestionComment
type: Comment
has text: check it out https://stackoverflow.com/questions/10759117/converting-jpg-images-to-png
score: 0

http://stackoverflow.com/q/52564639
type: Question
has answer: http://stackoverflow.com/a/52564696
has answer: http://stackoverflow.com/a/72988392
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/52568116
possible better answer: http://stackoverflow.com/a/52564682
has answer: http://stackoverflow.com/a/52564682
linked to: http://stackoverflow.com/q/931762
downvote count: 0
has comment: http://stackoverflow.com/comment/94690546
favorite count: 0
tagged with: python-3.x
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/52568116
has title: How to flatten a nested dictionary without recursion?
has answer: http://stackoverflow.com/a/76354370
linked to: http://stackoverflow.com/q/952914
has body: I came across this function that can flatten a dictionary: def flatten(dictionnary, container=None): if container is None: container = [] for k, v in dictionnary.items(): container.append(k) if v: flatten(v, container) return container to test it I created a dictionnay that is nested n times like so: nesteddict = {} for i in range(n, 0, -1): emptydict = {} emptydict[i] = nesteddict nesteddict = emptydict the function works while n is less than 999, otherwise it hit recursion limit: RecursionError: maximum recursion depth exceeded while calling a Python object so after a little bit of searching it seems that any recursive function can rewritten to iteration but I cant see how it could be done for the function I have to produce the same results. Another weird problem I came across while playing with this is if I try the code below for n &gt;= 998: nesteddict = {} for i in range(n, 0, -1): emptydict = {} emptydict[i] = nesteddict nesteddict = emptydict print(nesteddict) I get recursion error: RecursionError: maximum recursion depth exceeded while getting the repr of an object which is weird since I dont see any recursion here.
type: AnsweredQuestion

http://stackoverflow.com/q/52509921
type: Question
has answer: http://stackoverflow.com/a/52511152
has comment: http://stackoverflow.com/comment/91960410
has body: This is data from a lab experiment (around 717 lines of data). Rather than trying to excell it, I want to import and graph it on either python or matlab. I'm new here btw... and am a student! "" "Test Methdo","exp-l Tensile with Extensometer.msm" "Sample I.D.","Sample108.mss" "Speciment Number","1" "Load (lbf)","Time (s)","Crosshead (in)","Extensometer (in)" 62.638,0.900,0.000,0.00008 122.998,1.700,0.001,0.00012 more numbers : see Screenshot of more data from my file I just can't figure out how to read the line up until a comma. Specifically, I need the Load numbers for one of my arrays/list, so for example on the first line I only need 62.638 (which would be the first number on my first index on my list/array). How can I get an array/list of this, something that iterates/reads the list and ignores strings? Thanks! NOTE: I use Anaconda + Jupyter Notebooks for Python &amp; Matlab (school provided software). EDIT: Okay, so I came home today and worked on it again. I hadn't dealt with CSV files before, but after some searching I was able to learn how to read my file, somewhat. import csv from itertools import islice with open('Blue_bar_GroupD.txt','r') as BB: BB_csv = csv.reader(BB) x = 0 BB_lb = [] while x &lt; 7: #to skip the string data next(BB_csv) x+=1 for row in islice(BB_csv,0,758): print(row[0]) #testing if I can read row data Okay, here is where I am stuck. I want to make an arraw/list that has the 0th index value of each row. Sorry if I'm a freaking noob! Thanks again!
has title: Reading a numbers off a list from a txt file, but only upto a comma
has answer: http://stackoverflow.com/a/52511157
upvote count: 2
has comment: http://stackoverflow.com/comment/91998658
downvote count: 0
has answer: http://stackoverflow.com/a/52512512
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91959910
has comment: http://stackoverflow.com/comment/91960037
tagged with: python
answer count: 4
tagged with: matlab
score: 2
has answer: http://stackoverflow.com/a/52511378

http://stackoverflow.com/q/52497601
type: AnsweredQuestion
has body: The cmap gradient seems to apply vertically. Is there a way to apply the gradient horizontally? Here's my code: import numpy as np import matplotlib.pyplot as plt # Generate data... x = 25, 32, 18, 21, 28, 22, 29, 31 y = 5, 5, 5, 5, 5, 5, 5, 5 # Plot... plt.scatter(x, y, c=y, s=500, cmap='RdYlGn', alpha=0.8) plt.show()
accepted answer: http://stackoverflow.com/a/52497849
upvote count: 1
downvote count: 1
type: Question
tagged with: matplotlib
has title: Matplotlib Horizontal Gradient
score: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52497849
tagged with: python

http://stackoverflow.com/a/52532118
has body: in python you can use list comprehensions to make this easy to read: items_for_a = [float(v) for i, v in results.items() if i in ListA] total_a = sum(items_for_a) the dicttotal you want to print is strange, though. I don't think you want to print variable names as dictionary keys. in python2 you should use .iteritems() instead of .items()
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92003667
score: 1
accepted answer of: http://stackoverflow.com/q/52531984
answers question: http://stackoverflow.com/q/52531984
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/91911887
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52485123
has text: that is because "Blue Meeting" doesn't have a year in the example given, I assumed it's an error
score: 0

http://stackoverflow.com/a/52551130
type: Answer
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52547801
has body: You can use whatever you want for worker threads, but only a single thread (the "GUI thread") can actually draw things on the screen. That's how it happens in browsers, too -- slave processes basically render pages in memory and send pixel data to the master process that draws them; the master process sends back user input and such. Rendering standard GUI elements in memory isn't possible for most stock GUI toolkits, including Tk ('cuz it's an uncommon requirement) so you can't do that. It is typically possible at windowing system level (e.g. in Windows, it's via MemoryDC) which is what browsers take advantage of.
answers question: http://stackoverflow.com/q/52547801

http://stackoverflow.com/q/52584273
has answer: http://stackoverflow.com/a/52601091
accepted answer: http://stackoverflow.com/a/52601091
tagged with: python
has comment: http://stackoverflow.com/comment/92103495
favorite count: 0
has body: So I have a python webscraper right now that, when ran, gives the user a prompt to pick 1, 2, 3, or all. These options scrape the website/s according to the number. I want to make a python gui that, when the buttons are pressed (or checkboxes) they run the functions associated with 1, 2, 3, or all! Here is some of my code so you know where I am started off with: from tkinter import * #import statement for dependencies master = Tk() var1 = IntVar() Checkbutton(master, text='Scraper 1', variable=var1).grid(row=0, sticky=W) var2 = IntVar() Checkbutton(master, text='Scraper 2', variable=var2).grid(row=1, sticky=W) var3 = IntVar() Checkbutton(master, text='Scraper 3', variable=var3).grid(row=2, sticky=W) mainloop() and here is some of my scraper code so you see what I mean with the options 1, 2, 3, or all: import os, re, scrapy, sys, subprocess, xlwt from tempfile import TemporaryFile question2 = input("Which sites? 1 Grainger, 2 instrumart, 3 TruTechTools, 4 FWWebb, or All (1/2/3/All)") if(question2 == "1"): scraper = 1 elif(question2 == "2"): scraper = 2 elif(question2 == "3"): scraper = 3 elif(question2 == "4"): scraper = 4 else: scraper = "all" if (scraper == 1): subprocess.call('scrapy runspider graingerScraper.py -o info.json') fo = open("info.json", "r")#opens the file for our program to reference. Setting fo to the file, and as a read file variable print ("Name of the file: ", fo.name)#we don't need this, its just nice for our output rn line = fo.readlines()#creating a String variable = our names.json file Please help me understand how to link the buttons to running actual scraper code!
tagged with: tkinter
tagged with: web-scraping
tagged with: scrapy
downvote count: 1
type: AnsweredQuestion
has title: How to use Tkinter python GUI to RUN my webscraper?
has comment: http://stackoverflow.com/comment/92104044
type: Question
has comment: http://stackoverflow.com/comment/92115372
answer count: 1
score: 0
upvote count: 1

http://stackoverflow.com/q/52509107
has title: Selenium Chrome can only open once
has comment: http://stackoverflow.com/comment/92000118
score: 0
answer count: 1
type: UnansweredQuestion
has body: I have two files using Selenium to run different tasks. I can run them separately(only one running), but if I want to run the two files no matter at the same time or run it one by one. The second one will crash with the following errors. File "site-packages\selenium\webdriver\chrome\webdriver.py", line 75, in __ini __ File "site-packages\selenium\webdriver\remote\webdriver.py", line 156, in __in t__ File "site-packages\selenium\webdriver\remote\webdriver.py", line 251, in star _session File "site-packages\selenium\webdriver\remote\webdriver.py", line 320, in exec te File "site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in c eck_response elenium.common.exceptions.WebDriverException: Message: unknown error: Chrome fa led to start: crashed (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location C:\Program Files (x86)\Google\Chrome Application\chrome.exe is no longer running, so ChromeDriver is assuming that C rome has crashed.) (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c19 e),platform=Windows NT 6.1.7601 SP1 x86_64) The code is quite simple like: u = getpass.getuser() chrome_options = Options() ## Add the user information chrome_options.add_argument('user-data-dir=C:\\Users\\%s\\AppData\\Local\\Google\\Chrome\\User Data' % (u)) ## SF Case page source = "https://na66.salesforce.com/500?fcf=00BC0000008hfCI" driver = webdriver.Chrome(chrome_options=chrome_options) driver.get(source) Any suggestions please?
has comment: http://stackoverflow.com/comment/91995944
tagged with: python
linked to: http://stackoverflow.com/q/49270109
linked to: http://stackoverflow.com/q/35602896
has comment: http://stackoverflow.com/comment/91964792
has comment: http://stackoverflow.com/comment/92073868
tagged with: selenium
has answer: http://stackoverflow.com/a/52608535
type: Question
linked to: http://stackoverflow.com/q/52394408

http://stackoverflow.com/q/52562006
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52562038
upvote count: 1
score: 1
duplicate of: http://stackoverflow.com/q/301134
type: Question
answer count: 2
has body: I'm trying to make a python program for a given software than will scan&amp;run another certain python function at choice (or .py file altogether). However I can't import a function name set in a variable. import glob functions_list = glob.glob('*.py') #all my python files are found #pick any specific file to import import a[3] This fails with SyntaxError: invalid syntax. Is there any way to do this? My idea is to have a TkInter selection list where I click to run the .py I selected.
has answer: http://stackoverflow.com/a/52562036
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/301134
has title: Python: Import from variable after finding all files in dir
tagged with: python

http://stackoverflow.com/a/52572564
score: 1
has body: doc2 = document.readlines() print(doc2) doc3 = doc2.split(['\n']) The type() of doc2 would already be an array because file.readlines() always return an array of lines within the file. You cannot simply split an array. From the look of your problem, your file may potentially have \n escape characters so this would be captured also within the arrays.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52570280
downvote count: 0

http://stackoverflow.com/a/52511618
type: Answer
answers question: http://stackoverflow.com/q/52509933
score: 0
has body: look here for the confusion matrix another approach would be to use pandas or another similar lib to plot it

http://stackoverflow.com/comment/92109811
type: QuestionComment
comment on: http://stackoverflow.com/q/52587280
has text: That's not one hot at all. What is it supposed to be and why does it look like that? Can you explain?
score: 0
type: Comment

http://stackoverflow.com/comment/91944901
comment on: http://stackoverflow.com/q/52498137
score: 0
has text: For pdf viewing with tkinter, see: https://stackoverflow.com/questions/26653929/pdf-viewer-for-python-tkinter it may help even though it is few year old now.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52430388
score: 0
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/91816291
has answer: http://stackoverflow.com/a/79506039
has title: Exposing sash or handle of tkinter.ttk.Panedwindow?
type: Question
has comment: http://stackoverflow.com/comment/91816045
has answer: http://stackoverflow.com/a/52458372
accepted answer: http://stackoverflow.com/a/52458372
has comment: http://stackoverflow.com/comment/91805551
answer count: 2
possible better answer: http://stackoverflow.com/a/79506039
has body: Is there a way to show the sash/handle of the ttk.Panedwindow widget? These options are not available in it stylename (see below). Stylename = TPanedwindow Layout = [('Panedwindow.background', {'sticky': ''})] Element(s) = ['Panedwindow.background'] Panedwindow.background options: ('background',) Documentation has described that these options are not support, while they are available in tk.Panedwindow. Still, I want to verify its veracity and if anyone knows how to expose the sash/handle of the ttk.Panewindow widget?

http://stackoverflow.com/q/52526013
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/58726729
has answer: http://stackoverflow.com/a/58726729
type: Question
score: 0
answer count: 2
has body: I am trying to retrieve data from Kudu. But I am not able to install kudu-python package in anaconda or my server. Can I get some help with it? The documentation on the internet is not really clear.
tagged with: apache-kudu
has comment: http://stackoverflow.com/comment/91991978
has title: how to read from Kudu to python
has answer: http://stackoverflow.com/a/52787317
accepted answer: http://stackoverflow.com/a/52787317

http://stackoverflow.com/comment/92105235
score: 0
comment on: http://stackoverflow.com/a/52584873
type: Comment
has text: @dmnte - What do you need return if value is not valid?
type: AnswerComment

http://stackoverflow.com/comment/92086755
type: AnswerComment
comment on: http://stackoverflow.com/a/52575320
type: Comment
has text: I only want a team of `3`, but my input list can be larger than 6 and can be of length that is not divisible 3.
score: 0

http://stackoverflow.com/q/52529065
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
tagged with: text
has answer: http://stackoverflow.com/a/52529129
type: Question
answer count: 1
has body: What is the BeautifulSoup method for retrieving text from an element. I haveprices = soup.find_all('p', class_='price_color') and want to retrieve the text from prices. I tried p = prices.get_text() but got an error stating: 'ResultSet' object has no attribute 'text'
has title: BeautifulSoup method to retrieve the text from an element
score: 0

http://stackoverflow.com/q/52464699
tagged with: python-3.x
has title: How do I set layout's fixed height in PyQt5?
downvote count: 0
tagged with: pyqt5
has answer: http://stackoverflow.com/a/52468447
accepted answer: http://stackoverflow.com/a/52468447
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91876946
type: Question
has body: I am trying to set a fixed height for QHBoxLayout. To elaborate more on that, I need to set a specific height for my Horizontal layout. However, I cannot find the proper way to do so. What should I do to make this happen? hbox1 = QHBoxLayout()
tagged with: pyqt
answer count: 1
tagged with: qlayout
upvote count: 3
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/91936003
type: Comment
type: QuestionComment
score: 0
has text: or omit the download argument completely
comment on: http://stackoverflow.com/q/52497777

http://stackoverflow.com/q/52441766
type: Question
has body: Currently, I'm trying to integrate django wagtail with existing project, I use wagtail for blog and then I create routablepage within the wagtail. How can I reverse to that page from my django index page ?
has comment: http://stackoverflow.com/comment/91963365
has comment: http://stackoverflow.com/comment/91832844
score: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: How to link to wagtail routablepage from outside cms?
answer count: 0

http://stackoverflow.com/comment/91812729
has text: @U9-Forward this whole question is Jinja2
type: Comment
comment on: http://stackoverflow.com/q/52434588
score: 1
type: QuestionComment

http://stackoverflow.com/comment/91857363
score: 1
has text: those are individual dataframes, you can see the type of groups , just use loc in printing row
comment on: http://stackoverflow.com/q/52457461
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52435660
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52447691
type: Question
has body: I am trying to do password validation on wtform like this: email = StringField('Email', validators=[DataRequired(), Email()]) def validate_password(self, password): print(self) user = dbSession.execute( "SELECT * FROM users WHERE email = :email", {"email": self.email.data} ).fetchone() print(user) if not bcrypt.check_password_hash(user.password, password.data): raise ValidationError('Incorrect Password.') i want to get the email from other field, but i guess it's not working, i tried email.data but it isn't defined. also, it's not logging in console. in js, you log an object like this. I wanted to see the self's properties and the user, i want to log like this in python. console.log('user =', user); help?
tagged with: flask
has answer: http://stackoverflow.com/a/52447691
score: 0
has title: how to get data of another field in wtform validate_?
answer count: 1
tagged with: python
tagged with: flask-wtforms

http://stackoverflow.com/q/52444016
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/56645232
has answer: http://stackoverflow.com/a/52444231
has answer: http://stackoverflow.com/a/52444321
type: Question
has answer: http://stackoverflow.com/a/52444345
answer count: 6
tagged with: python-3.6
score: 0
has answer: http://stackoverflow.com/a/56939898
has title: How to make the following substitution in string using regex in Python?
has body: I'm trying to make a substitution in the following string: poem=''' If I can stop one heart from breaking, I shall not live in vain; If I can ease one life the aching, Or cool one pain, Or help one fainting robin Unto his nest again, I shall not live in vain. ''' The requirement are as below in the given string: If the pattern has characters 'ai' or 'hi', replace the next three characters with *\*. If a word has 'ch' or 'co', replace it with 'Ch' or 'Co'. I tried the following methods: print(re.sub(r"ai\w{3}|hi\w{3}",r"(ai|hi)*\*",poem)) Output: If I can stop one heart from breaking, I shall not live in vain; If I can ease one life the aching, Or cool one pain, Or help one f(ai|hi)*\*ng robin Unto his nest again, I shall not live in vain. print(re.sub(r"ch|co",r"Ch|Co",poem)) Output: If I can stop one heart from breaking, I shall not live in vain; If I can ease one life the aCh|Coing, Or Ch|Cool one pain, Or help one fainting robin Unto his nest again, I shall not live in vain. You can see the output is not as per the requirements. Please help me find the correct regex expression.
has answer: http://stackoverflow.com/a/56046340

http://stackoverflow.com/q/52539973
has comment: http://stackoverflow.com/comment/111016152
has title: Django celery and channels example
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: django-channels
tagged with: django
tagged with: python
tagged with: amazon-s3
has body: I have a Django app and need to generate files that can take up to a minute, so I pass that off to a background worker. Currently, the process works as follows. I post to the server that replies with a URL that I can poll. I then poll the server every 2 seconds and either sends back "busy" or a url of where the file is located in my S3 bucket. I want to replace this polling with Django channels, but unsure what is the best way to achieve this as I can't find any examples online. is channels even intended for something like this? My current thoughts are the following: Start the file generation as soon as the client opens a connection to on a specific route (previously this would have been a post) The background task gets started as soon as the client connects and get the channel name as a paramenter Once it is done it sends back the file path to the consumer which in turn sends it to the browser where I'll use JS to create a download button. Below is an example: @shared_task def my_bg_task(channel_name): #some long running calc here channel_layer = get_channel_layer() async_to_sync(channel_layer.send)(channel_name, {'type': 'generation_done', 'f_path': 'path/to/s3/bucket'}) class ReloadConsumer(WebsocketConsumer): def connect(self): my_bg_task.delay(self.channel_name) self.accept() def generation_done(self, event): self.send(text_data=json.dumps({event})) Is this the best way to achieve this? Obviously from a security point of the it should not be accessible to anybody other than the user that opened the connection.
tagged with: celery
type: Question
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/q/52548671
tagged with: python
has answer: http://stackoverflow.com/a/52548732
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52568426
type: Question
has body: I started learning Python and I noticed that the website teaching me will usually write like this: variable = 4 + 5 however even if I write: variable=4+5 I still get no errors and it runs properly. So are those spaces are important or not?
has comment: http://stackoverflow.com/comment/92073772
answer count: 3
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: In Python, are the spaces important to code variable = 4 + 5 Or is it fine to code it as variable=4+5?
has answer: http://stackoverflow.com/a/52548959

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/52529033
tags question: http://stackoverflow.com/q/52546180

http://stackoverflow.com/comment/92013789
comment on: http://stackoverflow.com/q/52535934
score: 0
type: QuestionComment
type: Comment
has text: Are you using service accounts? i.e. how are you authenticating..

http://stackoverflow.com/q/52515594
tagged with: python
has title: Trying to make a simple chessboard for school
answer count: 4
has answer: http://stackoverflow.com/a/52517704
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91970966
has answer: http://stackoverflow.com/a/52515844
score: -2
has body: So Ive got this far with my code: rivi = input("Enter dimensions \n") dimension = int(rivi) while dimension &lt;= 0: rivi = input("dimension") dimension = int(rivi) else: for h in range(dimension): for l in range(dimension): i = ((h + l + 1) % 2) print(i, end=('')) print() My only question is how I change the 1s and 0s that come out of the code to something else?
has answer: http://stackoverflow.com/a/52515813
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52515998
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/92101831
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52494220
score: 0
has text: "I also want the values to be first-class citizen in my Enum solution" - but `enum.Enum` does that. `enum.Enum` values are first-class, fully-featured objects. You can define methods on them, you can distinguish them from ordinary ints, etc. Your elaboration and your self-answer suggest that you want your enum to be a mere collection of aliases for ordinary ints and strings.

http://stackoverflow.com/a/52540359
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52540197
accepted answer of: http://stackoverflow.com/q/52540197
has body: New Answer You were overcomplicating your problem with your conditions, your problem can be reduced to this: df.groupby(df.active.ne(df.active.shift()).cumsum()).d1.cumsum().div(3) * df.active 0 569.700000 1 1859.600000 2 3269.733333 3 4822.033333 4 0.000000 5 0.000000 6 0.000000 7 0.000000 8 0.000000 9 0.000000 10 0.000000 11 0.000000 12 0.000000 13 0.000000 14 0.000000 15 0.000000 16 0.000000 17 0.000000 18 0.000000 19 0.000000 20 31246.066667 21 94343.800000 22 159148.000000 23 228009.933333 dtype: float64 Old Answer (I think it's still useful to include to explain the logic of what was being attempted) You only want the cumulative sum of consecutive regions of 1s, however, when you get to the end of your DataFrame, you are continuing with the cumulative sum of the rest of the DataFrame. One solution is calculting the cumsum per group of consecutive 1s, and then using this result in your final check. I also like to avoid chaining calls to np.where when np.select is much easier to read. s = df.groupby(df.active.ne(df.active.shift()).cumsum()).d1.cumsum() c1 = df.month.gt(1) &amp; df.active c2 = df.month.gt(1) &amp; ~df.active df.assign(calculate=np.select([c1, c2], [s.div(3), 0], df.d1.div(3))) month active d1 calculate 0 1 1 1709.1 569.700000 1 2 1 3869.7 1859.600000 2 3 1 4230.4 3269.733333 3 4 1 4656.9 4822.033333 4 5 0 48566.0 0.000000 5 6 0 0.0 0.000000 6 7 0 0.0 0.000000 7 8 0 0.0 0.000000 8 9 0 0.0 0.000000 9 10 0 0.0 0.000000 10 11 0 0.0 0.000000 11 12 0 0.0 0.000000 12 13 0 0.0 0.000000 13 14 0 0.0 0.000000 14 15 0 0.0 0.000000 15 16 0 0.0 0.000000 16 17 0 0.0 0.000000 17 18 0 0.0 0.000000 18 19 0 0.0 0.000000 19 20 0 0.0 0.000000 20 1 1 93738.2 31246.066667 21 2 1 189293.2 94343.800000 22 3 1 194412.6 159148.000000 23 4 1 206585.8 228009.933333
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52597255
answers question: http://stackoverflow.com/q/52569883
upvote count: 1
has comment: http://stackoverflow.com/comment/92155084
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92154109
accepted answer of: http://stackoverflow.com/q/52569883
has comment: http://stackoverflow.com/comment/92158919
has comment: http://stackoverflow.com/comment/92137122
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92155234
has body: Consider building a data frame of your files and meta data. Then, run by to read files and save by groups. Below does not guarantee equal-sized files but does output CSV files in 1GB-byte blocks. files &lt;- list.files(pattern = ".csv") # csvs in work directory file_sizes &lt;- file.size(files) # sizes in bytes (no sapply needed) cum_sizes &lt;- cumsum(file_sizes) # cumulative bytes file_read_groups &lt;- as.integer(cum_sizes / 1e9) # floor multiples of 1 GB # FILE DATA FRAME BUILD files_df &lt;- data.frame(files, file_sizes, cum_sizes, file_read_groups, row.names = NULL, stringsAsFactors = FALSE) # PROCESS BY GROUP output &lt;- by(files_df, files_df$file_read_groups, function(sub) { # READ CSVs AND BIND IN ONE DATA FILES tmp &lt;- do.call(rbind, lapply(sub$files, read.csv)) # EXPORT FILE TO DISK write.csv(tmp, paste0(sub$file_read_groups[[1]], ".csv"), row.names = FALSE) })
has comment: http://stackoverflow.com/comment/92166123

http://stackoverflow.com/comment/91847167
type: Comment
comment on: http://stackoverflow.com/a/52445201
score: 1
has text: Thanks Andy, I tried, but without the first line, because I already have a venv. The second line doesn't work for me, it said that source is not found as a command. The las two didn't installed the Jupyter Notebook. Thanks for your help.
type: AnswerComment

http://stackoverflow.com/comment/91878360
has text: You need to replace `d` by `car_dict `
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52468293
type: Comment

http://stackoverflow.com/comment/91950492
score: 0
has text: @WillemVanOnsem: I had a typo there, I fixed it in a minute or two.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52504979

http://stackoverflow.com/comment/94390714
comment on: http://stackoverflow.com/a/53769209
type: AnswerComment
has text: A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](https://meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted](https://stackoverflow.com/help/deleted-answers).
score: 0
type: Comment

http://stackoverflow.com/comment/91933949
has text: As @PROTOCOL said: `'42'.isdigit()` -> `True` and `'-42'.isdigit()` -> `False`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52496390

http://stackoverflow.com/comment/92029906
has text: dont count on random seed for repeatable randomness ... even using the same seed you will get different outcomes on different OS and between different python versions ... (not an answer i know ...)
type: QuestionComment
comment on: http://stackoverflow.com/q/52544935
score: 0
type: Comment

http://stackoverflow.com/comment/92035237
type: Comment
has text: @echan00 Yeah, but... the question here is. What is it your are trying to do? Do you want to validate the splits before output? Could possibly build a program that either splits or appends.
comment on: http://stackoverflow.com/q/52547846
score: 0
type: QuestionComment

http://stackoverflow.com/q/52566549
favorite count: 0
tagged with: python
score: 1
type: Question
type: AnsweredQuestion
has body: I have a numpy array like below: import pandas as pd import numpy as np np.random.seed(10) data = np.random.randint(0, 10, size=(1000, 4, 3)) I want to be able to flatten this data into a df with 12 columns and 1000 rows. What I've done is: df = pd.DataFrame( index=range(data.shape[0])) for i in range(data.shape[1]): for j in range(data.shape[2]): df[str(i)+'_'+str(j)] = pd.DataFrame((data[:,i,j])) By doing so, I'll be able to flatten this 3d data into 2d pandas df. - Does anyone know any neat built-in function that I can use, in addition to what I've done?
accepted answer: http://stackoverflow.com/a/52566704
tagged with: pandas
upvote count: 1
has title: Built-in function for flatten a 3d array into pandas df?
answer count: 1
has answer: http://stackoverflow.com/a/52566704
downvote count: 0

http://stackoverflow.com/comment/91893188
has text: It's really weird and I dont know how to solve it :( Could it be something related with the plotting library?
comment on: http://stackoverflow.com/a/52474388
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92036502
comment on: http://stackoverflow.com/a/52548342
type: AnswerComment
score: 0
type: Comment
has text: I enter in this code, however, I'm still getting the same string WITH white spaces.

http://stackoverflow.com/comment/92025586
type: QuestionComment
has text: No, I think that somewhere in your code you actually use User model. And I suggested to find that place.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52534075

http://stackoverflow.com/q/52581881
has title: Keeping track of number of characters removed in strings, python `strip()`
has comment: http://stackoverflow.com/comment/92098986
has body: I have a pair of strings. In this case, let's think of them as two separate strings assigned to unique variables. These strings have equal length: var1 = 'AnAppleADayKeepsTheDoctorAway' var2 = '000Ig00000noranceIsBliss00000' The most efficient way I know to strip beginning and trailing characters from a string in Python is the method strip(): print(var2.strip('0')) 'Ig00000noranceIsBliss' I would like to remove the same number of character from the string var1, as they are a "pair". In this case, that would be remove the first three characters and the trailing five characters, i.e. 'ppleADayKeepsTheDocto' Is there a method which allows me to efficiently strip characters like in var1 and then keep track of the number of these characters to do the same for the second string,var2? I'm not sure strip() would be the best method for this task. EDIT: Obviously, there's a solution. e.g. length_original = len(var2) num_left_chars = len(var2) - len(var2.lstrip('0')) num_right_chars = len(var2.rstrip('0')) edited = var1[num_left_chars:num_right_chars] print(edited) ## printed ## 'ppleADayKeepsTheDocto' I'm looking for an efficient solution. If there a quicker Pythonic method?
accepted answer: http://stackoverflow.com/a/52581987
has comment: http://stackoverflow.com/comment/92101660
score: 2
type: AnsweredQuestion
tagged with: string
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52581991
type: Question
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/92099267
has answer: http://stackoverflow.com/a/52581976
tagged with: strip
has comment: http://stackoverflow.com/comment/92099291
has comment: http://stackoverflow.com/comment/92099053
has answer: http://stackoverflow.com/a/52581987
possible better answer: http://stackoverflow.com/a/52581976
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/52600246

http://stackoverflow.com/a/52484386
has comment: http://stackoverflow.com/comment/91910349
score: 0
type: AcceptedAnswer
has body: If your code works when the array starts with a 0 but not a 1, you can simply check for this explicitly: if arr[0] == 1: # The first element is a 1, set output accordingly else: # Your original code here If you do not insist on the use of XOR, I suggest to solve the whole problem using a generator expression with an explicit call to next, like so: index = next(i for i, el in enumerate(input_arr) if el == 1) You can also use the builtin index method on lists (and tuples): index = input_arr.index(1)
type: Answer
accepted answer of: http://stackoverflow.com/q/52484250
answers question: http://stackoverflow.com/q/52484250

http://stackoverflow.com/q/52498342
tagged with: python-3.x
tagged with: python
possible better answer: http://stackoverflow.com/a/52498501
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52498504
type: Question
has title: searching and replacing words with upper and lower cases of the same word
has answer: http://stackoverflow.com/a/52498504
has answer: http://stackoverflow.com/a/52498501
tagged with: replace
score: 0
answer count: 2
has body: The point of this script is to replace multiple strings of words despite if the word starts with a lower case letter or upper case letter. code example: import re from re import sub def word_replace(text, replace_dict): rc = re.compile(r"[A-Za-z_]\w*") def translate(match): word = match.group(0) return replace_dict.get(word, word) return rc.sub(translate, text) old_text = """Bob: say why don't you play ball jeff: i have no idea bob: well maybe you should """ replace_dict = { "Bob" : 'bob baller', "debug" : "fix", 'ship': 'boat' } what i get is: bob baller: say why don't you play ball jeff: i have no idea bob: well maybe you should what i would like to get out of the text is both "Bob" and "bob" then replace them both with bob baller. To clear up the question a little bit more, what i am trying to do is replace the word 'bob' (or any-word in replace_dict) if it's upper-case or lower case.

http://stackoverflow.com/q/52445705
tagged with: relational-database
tagged with: python
has title: Odoo 10: How to insert value to a many2one field in table with create method?
upvote count: 1
duplicate of: http://stackoverflow.com/q/52421672
type: AnsweredQuestion
tagged with: oncreate
tagged with: odoo
has body: my many2one field in models.py : commercial_group = fields.Many2one("simcard.simcard") I want to add a new value in this many2one field using create method. That value I am getting from an SOAP response which i am parsing using element tree: response=requests.post(self.url,cert=self.cert,data=body,headers=self.headers) element = ElementTree.fromstring(response.content.decode('utf-8')) body_el = element.find('{schemas.xmlsoap.org/soap/envelope}Body') commercial_group=body_el.find('{example.com}commercialGroup') And I want to create a new record with this commercialGroup field and some other fields : record.sudo().create({ "icc": icc.text, "imsi": imsi.text, "msisdn": msisdn.text, "lte_status": lte_status.text, "life_cycle_status": life_cycle_status.text, "sim_model": simmodel.text, "gprs_status": gprsStatus.text, "consumption_monthly_data_limit": consumption_monthly_data_limit.text, "consumption_monthly_data_value": consumption_monthly_data_value.text, "consumption_monthly_data_thrReached": consumption_monthly_data_thrReached.text, "commercial_group": commercial_group.text, "country": country.text, "operator": operator.text }) http.request.env.cr.commit() and i get this error : INFO test odoo.sql_db: bad query: INSERT INTO "simcard_simcard" ("id", "consumption_monthly_data_limit", "consumption_monthly_data_thrReached", "msisdn", "country", "lte_status", "consumption_monthly_data_value", "life_cycle_status", "icc", "gprs_status", "sim_model", "operator", "commercial_group", "imsi", "create_uid", "write_uid", "create_date", "write_date") VALUES(nextval('simcard_simcard_id_seq'), '0', '0', '34590169', 'CH', 'false', '0', 'ACTIVE', '89293165951', '2', 'M2M Plug-in', 're', '1GB_dynPool_Plus_LTE', '29782', 1, 1, (now() at time zone 'UTC'), (now() at time zone 'UTC')) RETURNING id 2018-09-19 13:44:27,441 5714 ERROR test odoo.http: Exception during JSON request handling. Traceback (most recent call last): File "/Users/anubhavjhalani/odoo10/odoo/http.py", line 642, in _handle…
has answer: http://stackoverflow.com/a/52445914
type: Question
accepted answer: http://stackoverflow.com/a/52445914
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/52545977
has comment: http://stackoverflow.com/comment/92031797
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/92051646
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92031854
upvote count: 2
linked to: http://stackoverflow.com/q/17912307
has answer: http://stackoverflow.com/a/52557200
has comment: http://stackoverflow.com/comment/92033726
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am writing a script that is responsible for reading some values from a .csv file and write them in another .csv file. header = ["Title", "Authors", "Year", "Abstract", "Keywords"] fields_number = int(input("Enter the number of fields you want to get: ")) field_names = list() field_values = list() for i in range(0, fields_number): field_name = input("Enter the field name: ") field_names.append(field_name) try: with open(filename) as csvfile: rowsreader = csv.DictReader(csvfile) for row in rowsreader: print(row) json_row = '{' for i in range(0, len(field_names)): field = field_names[i] json_row += '"{}":"{}"'.format(header[i], row[field]) json_row += ',' if (i &lt; len(field_names) - 1) else '}' field_values.append(json.loads(json_row)) except IOError: print("Could not open csv file: {}.".format(filename)) I am getting the following output: Traceback (most recent call last): File "slr_helper.py", line 58, in &lt;module&gt; main() File "slr_helper.py", line 37, in main json_row += '"{}":"{}"'.format(header[i], row[field]) KeyError: 'Authors' The beginning of the csv file has the following values: Authors,Author Ids,Title,Year,Source title,Volume,Issue,Art. No.,Page start,Page end,Page count,Cited by,DOI,Link,Abstract,Author Keywords,Index Keywords,Sponsors,Publisher,Conference name,Conference date,Conference location,Conference code,Document Type,Access Type,Source,EID "AlHogail A., AlShahrani M.","51060982200;57202888364;","Building consumer trust to improve Internet of Things (IoT) technology adoption",2019, But the code is printing this when reading the csv file: OrderedDict([('\ufeffAuthors', 'AlHogail A., AlShahrani M.'), ('Author Ids', '51060982200;57202888364;'),... I would like to know how to avoid this OrderedDict([('\ufeff, since it is causing the error I am getting.
has comment: http://stackoverflow.com/comment/92031777
type: Question
has title: csv.reader returning "OrderedDict" value in a field name
accepted answer: http://stackoverflow.com/a/52557200
has comment: http://stackoverflow.com/comment/92031814
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92033353

http://stackoverflow.com/a/52508202
has body: Based on your comments, the data you're being served doesn't actually include carriage returns or newlines, it includes the text representing the escapes for carriage returns and newlines (so it really has a backslash, r, backslash, n in the data). It's otherwise already in the form you want, so you don't need to involve the csv module at all, just interpret the escapes to their correct value, then write the data directly. This is relatively simple using the unicode-escape codec (which also handles ASCII escapes): import codecs # Needed for text-&gt;text decoding # ... retrieve data here, store to res ... # Converts backslash followed by r to carriage return, by n to newline, # and so on for other escapes decoded = codecs.decode(res, 'unicode-escape') # newline='' means don't perform line ending conversions, so you keep \r\n # on all systems, no adding, no removing characters # You may want to explicitly specify an encoding like UTF-8, rather than # relying on the system default, so your code is portable across locales with open(title, 'w', newline='') as f: f.write(decoded) If the strings you receive are actually wrapped in quotes (so print(repr(s)) includes quotes on either end), it's possible they're intended to be interpreted as JSON strings. In that case, just replace the import and creation of decoded with: import json decoded = json.loads(res)
answers question: http://stackoverflow.com/q/52505583
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91982025
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52505583
score: 3

http://stackoverflow.com/comment/92043024
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52551312
has text: @MohanRadhakrishnan: I made the question clearer, thanks!
score: 0

http://stackoverflow.com/comment/91924509
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52490517
score: 0
has text: `print(company_pair[stock])` what value is returned

http://stackoverflow.com/comment/91830710
has text: Oh right, I forgot that they added the `args` thing. This is a very recent update though, apparently introduced in 1.9. Maybe you are using an outdated version of Tensorflow?
type: Comment
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/52443952

http://stackoverflow.com/comment/106720883
score: 0
type: AnswerComment
has text: Since there is `flush_secs`, should I call `.flush()`? I mean does the `tf.summary.FileWriter` automatically call `.flush()` in `.add_summary()`?
type: Comment
comment on: http://stackoverflow.com/a/52502679

http://stackoverflow.com/q/52581572
score: 1
upvote count: 1
tagged with: python-requests
type: Question
has body: I'm trying to access the secured part of this website: https://www.amundi-ee.com/psf/#login with this code: import requests,time,lxml LOGIN = 'https://www.amundi-ee.com/psf/#login' PROTECTED_PAGE = 'https://www.amundi-ee.com/psf/#avoirs' payload = { 'identifiant': '000000', 'pwd': '111111', } headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'} with requests.session() as s: s.post(LOGIN, headers=headers, data=payload) time.sleep(2) f = s.get(PROTECTED_PAGE) I got both post &amp; get a 200 status code but I can see that I'm not connected. So I'm guessing that there are missing arguments in my payload, but can't figure which. This is the code of the form (there is no hidden field): &lt;form name="formulaire" role="form" class="form-horizontal form-margin" autocomplete="off"&gt; &lt;div class="row clearfix"&gt; &lt;div class="col-md-offset-4 col-md-3 col-sm-5 col-sm-offset-2 col-xs-11"&gt; &lt;div class="form-group "&gt;&lt;label for="identifiant" class="control-label"&gt;&lt;i key="ui.page.login.identifier" class="i18n_resource"&gt;Identifiant&lt;/i&gt; &lt;span class="glyphicon glyphicon-question-sign aPopoverTrigger i18n_resource" data-toggle="popover" data-container="body" data-apopovercontent=".aPopoverContent_identifiant" data-original-title="Identifiant"&gt;&lt;/span&gt; &lt;span class="aPopoverContent_identifiant hidden"&gt;&lt;i key="ui.page.login.identifier_description" class="i18n_resource"&gt;Votre identifiant correspondant à votre numéro de compte, indiqué sur vos relevés de compte d'Epargne Salariale &amp;amp; Retraite ou votre certificat d'affiliation de votre contrat PER Entreprises.&lt;/i&gt;&lt;/span&gt;&lt;/label&gt; &lt;input id="identifiant" name="mail" class="form-control" type="text" value="" autocomplete="off" style="background-image: url(&amp;quot;[binary]&amp;quot;); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px;…
tagged with: javascript
has title: Why requests can't access the secured page on this website?
tagged with: post
has answer: http://stackoverflow.com/a/52586513
tagged with: get
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52581820
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52445257
possible better answer: http://stackoverflow.com/a/52445277
has answer: http://stackoverflow.com/a/52445283
tagged with: python
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/3459098
downvote count: 7
type: Question
duplicate of: http://stackoverflow.com/q/3459098
accepted answer: http://stackoverflow.com/a/52445283
answer count: 2
has answer: http://stackoverflow.com/a/52445277
upvote count: 0
has comment: http://stackoverflow.com/comment/91833312
has body: What are the various ways in which we can create a list containing 50 one's using python?
has title: What are the possible ways to create a list containing 50 ones in python?
score: -7
favorite count: 0

http://stackoverflow.com/comment/91953476
has text: Place your code in the same directory as WS_Vardata is in and run it
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52506344

http://stackoverflow.com/comment/91841181
type: Comment
comment on: http://stackoverflow.com/a/52448216
score: 0
type: AnswerComment
has text: Thanks! This worked perfectly! Just to elaborate on a generalized way to match the instance of when we have *key1* or *key2*. matches = re.findall(r'\[([^][]*"key.*"[^][]*)]', text_file.read())

http://stackoverflow.com/comment/91916579
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52487623
has text: Thanks, would I just want to replace the line elem.text = elem.text.replace('4.36', '5') with this?
type: AnswerComment

http://stackoverflow.com/comment/91937924
type: Comment
type: QuestionComment
score: 0
has text: Only if the file name startswith some datetime string and you know exactly which string you're looking for.
comment on: http://stackoverflow.com/q/52498677

http://stackoverflow.com/q/52586577
tagged with: automl
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has title: Using refit() in auto-sklearn for incremental learning
type: Question
has body: I have a large dataset with 50k rows and 10k columns. I am trying to fit this data using classifiers in auto-sklearn. Due to limited resources, I have partitioned the data into batches and intend to use incremental learning. Is it possible to use the autosklearn.classification.AutoSklearnClassifier.fit() on first batch followed by autosklearn.classification.AutoSklearnClassifier.refit() on the rest of the batches? The API documentation says: refit(X, y) Refit all models found with fit to new data. Necessary when using cross-validation. During training, auto-sklearn fits each model k times on the dataset, but does not keep any trained model and can therefore not be used to predict for new data points. This methods fits all models found during a call to fit on the data given. This method may also be used together with holdout to avoid only using 66% of the training data to fit the final model. Parameters: X : array-like or sparse matrix of shape = [n_samples, n_features] The training input samples. y : array-like, shape = [n_samples] or [n_samples, n_outputs] The targets. Does this mean refit is valid only when cross validation is used on the original data or does the first line mean that subsequent batches of data can be re-trained on the same model? Any ideas/thoughts?
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/52589733
has comment: http://stackoverflow.com/comment/120635657
downvote count: 0

http://stackoverflow.com/q/52506837
has comment: http://stackoverflow.com/comment/91954223
has title: change python directory from conda
has body: Recently, I installed miniconda, and because of which, my default python directory seems to have changed to, /home/user/miniconda3/bin/python Also, the default version seems to have changed to python 3.7 instead of python 2.7 And I cannot seem to install various libraries like tensorflow. How do I get my python back to normal?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52506902
tagged with: python
tagged with: miniconda
type: Question
tagged with: ubuntu
score: 0
has comment: http://stackoverflow.com/comment/91964505
answer count: 1

http://stackoverflow.com/comment/92031823
type: AnswerComment
type: Comment
has text: I have a little question, according to a random ID I want to paint that place, I failed to do the following.the code is here. https://codepen.io/sinanelms/pen/MqdNNY?editors=1010 `//random selected function random(){ var ran=Math.floor(Math.random() * 82); if(obj.id==ran){obj.animate({fill: '#000'}, 200); } } setInterval(function(){random();}, 1000); //random end`
score: 0
comment on: http://stackoverflow.com/a/52498594

http://stackoverflow.com/q/52484582
score: 0
has body: I'm trying to work with email messages in Python 3.7 and struggling with what looks like compatibility issues. The docs mention email.message.Message having an iter_parts method that should allow me to do a non-recursive walk of message parts. This doesn't exist on messages returned from mailbox messages and it's taken me a while to get it behaving. For example, I can generate a dummy message with: from email.message import EmailMessage msg = EmailMessage() msg['Subject'] = 'msg 1' msg.add_alternative("Plain text body", subtype='plain') msg.add_alternative(" HTML body ", subtype='html') msg.add_attachment(b"Nothing to see here!", maintype='data', subtype='raw') and then dump out the parts with: def iter_parts(msg): ret = msg.get_content_type() if msg.is_multipart(): parts = ', '.join(iter_parts(m) for m in msg.iter_parts()) ret = f'{ret} [{parts}]' return ret iter_parts(msg) which gives me: multipart/mixed [multipart/alternative [text/plain, text/plain], data/raw] but if I save this to a mbox file and reload it: import mailbox mbox = mailbox.mbox('/tmp/test.eml') mbox.add(msg) iter_parts(mbox[0]) it tells me AttributeError: 'mboxMessage' object has no attribute 'iter_parts' Initially I thought it might be related to https://stackoverflow.com/a/45804980/1358308 but setting factory=None doesn't seem to do much in Python 3.7. Am posting my solution, but would like to know if there are better options!
answer count: 1
has title: non-recursive walk of email message from mailbox message
has answer: http://stackoverflow.com/a/52484584
tagged with: python-3.x
tagged with: mbox
type: UnansweredQuestion
tagged with: python
type: Question
linked to: http://stackoverflow.com/q/45804579

http://stackoverflow.com/q/52576304
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92096105
has title: how can i deselect a previously selected row in kivy recycleview
has comment: http://stackoverflow.com/comment/92092542
has answer: http://stackoverflow.com/a/52582075
tagged with: python
tagged with: kivy
possible better answer: http://stackoverflow.com/a/57022008
favorite count: 0
has answer: http://stackoverflow.com/a/57022008
tagged with: kivy-language
upvote count: 2
accepted answer: http://stackoverflow.com/a/52582075
score: 0
downvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92090271
has body: i need help deselect selected Label Item in RecycleView with SelectableLabel view. any ideas how to solve it ? i understand it should be written somewhere in 'def apply_selection' but im having trouble getting it to work example: i want to be able to preform another click on the selected row and that the selection will be removed. i think the code for this should go here: def apply_selection(self, rv, index, is_selected): ''' Respond to the selection of items in the view. ''' self.selected = is_selected i tried using a third input to specify the current selection but its not really working. 1. is this method is where i need to modify in order to achieve what im after ? 2. if so, any ideas how to do so correctly ?

http://stackoverflow.com/q/52498407
possible better answer: http://stackoverflow.com/a/52498465
type: Question
has title: How to ask for a boolean input from a user to qualify if statements and print a sentence using that information in Python
tagged with: boolean
has body: I'm here with my first (hopefully not last) query for you. I'm trying to get information from the user, specifically boolean values to determine if they are male/female and tall/short, then print the correct statement of "You are a tall/short male/female" is_tall = input("Are you tall?") is_male = input("Are you male?") if is_tall and is_male: print("You are a tall male") elif is_tall and not(is_male): print("You are a tall female") elif not(is_tall) and is_male: print("You are a short male, sorry") else: print("You are a short female, sorry") My code runs and always returns "You are a tall male", searching reveals this is because the user's input is considered always true as it is a string. I've seen other examples for grabbing boolean values but not for grabbing two and using them both within if statements. Am I anywhere close here, what am I missing? I know I can't use bool() around the input to convert it.
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52498465
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52498469
accepted answer: http://stackoverflow.com/a/52498469
has comment: http://stackoverflow.com/comment/91937643
tagged with: python
type: AnsweredQuestion
tagged with: if-statement
has answer: http://stackoverflow.com/a/52498528

http://stackoverflow.com/a/54661576
has comment: http://stackoverflow.com/comment/96470496
has comment: http://stackoverflow.com/comment/96474057
type: Answer
has comment: http://stackoverflow.com/comment/97376690
downvote count: 1
upvote count: 16
answers question: http://stackoverflow.com/q/52529403
has body: I guess there is a bug in Tk. I am on MacOS 10.14.3 If you maximize and minimize the tkinter window the text on the button appears, another solution that worked for me is from tkinter import * from tkinter import ttk button1 = ttk.Button(*your args here*)
has comment: http://stackoverflow.com/comment/97808702
has comment: http://stackoverflow.com/comment/97800634
has comment: http://stackoverflow.com/comment/96265542
score: 15

http://stackoverflow.com/q/52455774
has answer: http://stackoverflow.com/a/69548749
has answer: http://stackoverflow.com/a/65353677
tagged with: google-translate
has answer: http://stackoverflow.com/a/67874518
has answer: http://stackoverflow.com/a/55402301
has answer: http://stackoverflow.com/a/74569157
has comment: http://stackoverflow.com/comment/121279791
has body: I was trying googletrans and it was working quite well. Since this morning I started getting below error. I went through multiple posts from stackoverflow and other sites and found probably my ip is banned to use the service for sometime. I tried using multiple service provider internet that has different ip and stil facing the same issue ? I also tried to use googletrans on different laptops , still same issue ..Is googletrans package broken or something google did at their end ? &gt;&gt;&gt; from googletrans import Translator &gt;&gt;&gt; translator = Translator() &gt;&gt;&gt; translator.translate('안녕하세요.') Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; translator.translate('안녕하세요.') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 172, in translate data = self._translate(text, dest, src) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate token = self.token_acquirer.do(text) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 180, in do self._update() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 59, in _update code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') AttributeError: 'NoneType' object has no attribute 'group'
linked to: http://stackoverflow.com/q/70673172
has title: googletrans stopped working with error 'NoneType' object has no attribute 'group'
has answer: http://stackoverflow.com/a/52456197
favorite count: 0
has answer: http://stackoverflow.com/a/69271089
has comment: http://stackoverflow.com/comment/91854182
has answer: http://stackoverflow.com/a/52885859
score: 224
tagged with: googletrans
has answer: http://stackoverflow.com/a/65113191
has answer: http://stackoverflow.com/a/72808431
accepted answer: http://stackoverflow.com/a/52456197
tagged with: python
answer count: 18
has answer: http://stackoverflow.com/a/65386909
tagged with: nlp
has answer: http://stackoverflow.com/a/53362009
upvote count: 225
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61858275
has answer: http://stackoverflow.com/a/52487148
has answer: http://stackoverflow.com/a/71099343
has comment: http://stackoverflow.com/comment/94021447
downvote count: 1
possible better answer: http://stackoverflow.com/a/65109346
has answer: http://stackoverflow.com/a/73748983
type: Question
has answer: http://stackoverflow.com/a/68471570
linked to: http://stackoverflow.com/q/52446811
has answer: http://stackoverflow.com/a/65109346

http://stackoverflow.com/a/52520644
has comment: http://stackoverflow.com/comment/91984978
type: AcceptedAnswer
score: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/52510439
answers question: http://stackoverflow.com/q/52510439
downvote count: 0
has body: Dude I am having the same problem. From I have researched the answer is actually to throw a catch all at the end of your urls in django. I can only find the old way of doing it. url(r'^(%s)?$' % '|'.join(routes), TemplateView.as_view(template_name='index.html')) I am not sure how to do it with path but I had found it earlier. It might be re_path(r'.*', views.index) Just let me know if that works so I can go home and use it :)
has comment: http://stackoverflow.com/comment/91985268
upvote count: 8

http://stackoverflow.com/a/52452371
accepted answer of: http://stackoverflow.com/q/52451602
answers question: http://stackoverflow.com/q/52451602
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91849541
has comment: http://stackoverflow.com/comment/91849553
has body: This is too long for a comment. I think you can change your http_theme_path to html_static_path. Something like: html_static_path = ['_static'] def setup(app): app.add_stylesheet("css/theme.css") This will add _static/css/theme.css to your generated doc. edit I am adding some tips about publish docs on RTD. On RTD, there are some default themes installed. I'm not sure what is installed but at least includes sphinx_rtd_theme. RTD uses a specific sphinx version. Last time I checked, it is sphinx==1.6.7, and this time I check it is sphinx&lt;1.8. As there is some minor difference even between middle version changes, you may want to use a fixed version by specify sphinx==1.7.x in your requirements.txt.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52525290
has answer: http://stackoverflow.com/a/52525890
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91990364
has comment: http://stackoverflow.com/comment/91991521
has comment: http://stackoverflow.com/comment/91990426
upvote count: 1
tagged with: python
downvote count: 3
type: Question
has title: How to assign a numerical value to a user string input in Python
score: -2
has comment: http://stackoverflow.com/comment/91990495
has comment: http://stackoverflow.com/comment/91990360
has answer: http://stackoverflow.com/a/52525859
tagged with: python-3.6
answer count: 3
has body: I have a school assignment, where it requests a number of user inputs determining whether the user wants milk, juice, its size For example, milk costs $4.00, upgrading to large costs $0.40,. At the end, the output should read for ex. Large Milk,cost: $4.55 My issue is, how do I assign a value to each corresponding string input? At the end of the following code, the cost just spits out for sum of strings, as opposed to actually adding up the cost of each and spitting out the total number value. I just can't seem to figure out what I should be doing here.
has answer: http://stackoverflow.com/a/52525970
favorite count: 0

http://stackoverflow.com/q/52464002
tagged with: anaconda
score: 1
has body: I just created a new conda environment with python version 3.5.6. I installed one package called zipline, everything OK. I activated the environment and that looks OK. When I run some test code, I get an error that its trying to use a dependency (numpy) and it outside my new environment. It is using the code for numpy from the default python installation on my MacOSX computer, which is a python 2.7 version. This has got my mind troubled. Why should it be looking at any packages that aren't installed in my current environment? So I figure I just needed to install a new version of numpy inside my python 3.5 env. But when I try to do that, conda tells me all dependencies are already met. Here's the error. You can see the first line, it is importing the new package that I installed inside my new env. Then it is trying to get numpy, and looking is a python 2.7 folder. From my perspective it seems it should never be looking in that 2.7 folder while my env is activated. I never installed numpy so it seems it should just say that the module is not found. Traceback (most recent call last): File "markowitz.py", line 1, in &lt;module&gt; from zipline.utils.factory import load_bars_from_yahoo File "/Users/apple/anaconda/envs/env_zipline_p36/lib/python3.5/site-packages/zipline/__init__.py", line 17, in &lt;module&gt; import numpy as np File "/Users/apple/anaconda/lib/python2.7/site-packages/numpy/__init__.py", line 142, in &lt;module&gt; from . import add_newdocs File "/Users/apple/anaconda/lib/python2.7/site-packages/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/Users/apple/anaconda/lib/python2.7/site-packages/numpy/lib/__init__.py", line 8, in &lt;module&gt; from .type_check import * File "/Users/apple/anaconda/lib/python2.7/site-packages/numpy/lib/type_check.py", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "/Users/apple/anaconda/lib/python2.7/site-packages/numpy/core/__init__.py", line 26, in &lt;module&gt; rais…
type: Question
has comment: http://stackoverflow.com/comment/91915218
has title: Why Conda is using a python package outside my environment?
downvote count: 0
tagged with: conda
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/92013391
type: UnansweredQuestion
tagged with: package
upvote count: 1
tagged with: python

http://stackoverflow.com/a/70486320
downvote count: 0
has comment: http://stackoverflow.com/comment/136316415
score: 1
has comment: http://stackoverflow.com/comment/135563625
has body: I noticed that the solutions offered by others weren't satisfying your initial question, so I came up with a simple and synchronous solution for you, there is no need for fancy multithreading. This problem can be solved by using a lower-level library such as socket that comes built-in with python. The idea is sending the get request and not caring whether the other party returns a 200 or 400+, thus allowing us to truly fire and forget, not wasting any precious time, not awaiting anything. Here is the full code demonstrating the usefulness and implementation and the general idea is doing write_only_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) write_only_client.connect((target_host, target_port)) write_only_client.send(request.encode()) write_only_client.close() notice how we don't do any write_only_client.recv calls, which is exactly why we are able to do a true fire and forget. P.S. Although it is not practiced in my code example, it is best to keep the socket open and have it as a global variable to avoid it being garbage collected during a scope change, as closing the socket too soon might cause problems (it did cause problems when I closed an SSL connection to an API).
upvote count: 1
answers question: http://stackoverflow.com/q/52526353
has comment: http://stackoverflow.com/comment/136319572
type: Answer

http://stackoverflow.com/a/52467633
has comment: http://stackoverflow.com/comment/91877101
type: Answer
has comment: http://stackoverflow.com/comment/91877391
has comment: http://stackoverflow.com/comment/91877130
has comment: http://stackoverflow.com/comment/91877333
score: 0
has body: I think you should use https://ae3df23b.ngrok.io/webhook. You are missing the path. Also, use https and generate a new ngrok URL and update the fulfilment.
has comment: http://stackoverflow.com/comment/91877274
has comment: http://stackoverflow.com/comment/91877263
answers question: http://stackoverflow.com/q/52467563

http://stackoverflow.com/a/52511635
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52511354
has body: You can do in this way: with open("file.csv", "r") as fp: reader = csv.reader(fp, delimiter=",") rows = [x[:3] + [','.join(x[3:])] for x in reader] df = pd.DataFrame(rows) df.columns = df.iloc[0] df = df.reindex(df.index.drop(0)) print df

http://stackoverflow.com/comment/92069040
score: 0
type: Comment
type: QuestionComment
has text: By “duplicate” do you mean “repeaed” i.e. there may be more than two occurrences of the same value/record?
comment on: http://stackoverflow.com/q/52565665

http://stackoverflow.com/comment/91949732
comment on: http://stackoverflow.com/a/52504338
has text: In fact, scrap that, try my rewrite of it (edited answer)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52555848
type: Answer
has body: i do not have enough details to know exactly what is the problem. but i have real strong guess that putting those lines: p = multiprocessing.Pool() result = p.apply_async(func).get() inside a function will fix your problem. try this: import multiprocessing def func(): return 1 def main(): p = multiprocessing.Pool() result = p.apply_async(func).get() print(result) if __name__ == '__main__': main() tell me if it worked :)
answers question: http://stackoverflow.com/q/52555492
score: 0

http://stackoverflow.com/a/52507124
score: 0
answers question: http://stackoverflow.com/q/52506764
has body: My preference lies in using xmltodict. But from the link you have posted, it seems you are wanting to make the .find("filename") from within the tag and not a tag (which isn't present in your xml-data as is also stated in a comment). That is, your code could be changed "minimally" (I don't know ElementTree well enough to say what the best solution is) to something like: for annotation in tree.findall("annotation") filename = annotation.find("filename") filename.text = "001.jpg"
type: Answer

http://stackoverflow.com/comment/92114851
type: Comment
has text: @JoenTeer Hash `#` is an invalid character in JSON, you need `//` for comments because JSON is just JavaScript. Also, the code you post doesn't generate this error message. See [mcve].
comment on: http://stackoverflow.com/a/52588196
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91836236
has text: eh there is 12 plot ...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52446527
score: 0

http://stackoverflow.com/comment/91881841
type: Comment
has text: hjpaulj, Perhaps my above question was not made well enough to express my issue. sys.argv[1] seems to contain everything after the application name. I understand the concept and that sys.argv[:1] should contain all after the program but the core problem here is that sys.argv[1] seems to contain the entire string after the program name thuse the print out of just sys.argv[1] being the test --optionalArg myArg Updating question with new information.
comment on: http://stackoverflow.com/q/52459427
score: 0
type: QuestionComment

http://stackoverflow.com/q/52539986
has answer: http://stackoverflow.com/a/52542800
answer count: 2
downvote count: 0
tagged with: grid-search
tagged with: data-science
favorite count: 0
has answer: http://stackoverflow.com/a/52540308
upvote count: 8
has title: Scoring in Gridsearch CV
tagged with: python
score: 8
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/52540308
has body: I just started with GridSearchCV in Python, but I am confused what is scoring in this. Somewhere I have seen scorers = { 'precision_score': make_scorer(precision_score), 'recall_score': make_scorer(recall_score), 'accuracy_score': make_scorer(accuracy_score) } grid_search = GridSearchCV(clf, param_grid, scoring=scorers, refit=refit_score, cv=skf, return_train_score=True, n_jobs=-1) What is the intent of using these values, i.e. precision, recall, accuracy in scoring? Is this used by gridsearch in giving us the optimized parameters based on these scoring values.... like for the best precision score it finds the best parameters or something like that? It calculate precision, recall, accuracy for the possible parameters and gives the result, now the question is if this is true, then it select best parameters based on precision, recall or accuracy? Is the above statement true?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52542800
type: Question

http://stackoverflow.com/a/52580864
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52580747
has body: If the ordering field in the inner Meta class of a model is not specified does does the generated SQL query return results with items at randomized positions? If you do not specify an order (nor through the Meta, or by an .order_by clause in the queryset), then Django will construct a query like: SELECT model.* FROM model (perhaps with other clauses, but not with an ORDER BY statement). This means that the database has the freedom to return the record in any order. It does not mean that the database will "shuffle" the records, but you simply can not say for sure in what order the records will be retrieved. Some databases will return the record in (reverse) "edit timestamp" order, so the most recent added/edited records first. But this is not something that you should depend on (you can see this as an implementation detail). It furthermore can also depend on the query itself if there are JOINs involved, since then the table can get ordered due to the JOINing process. But in general the idea is that it can return the records in any order, and changes to the table, can result in changes in the ordering. This has some implications on pagination, since if a user moves to the next page, and meanwhile the order changes, the queryset will not per se have the same order when the user fetches the next page. Therefore you better order the queryset (in one way or another). For example by the id.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91944701
type: QuestionComment
comment on: http://stackoverflow.com/q/52501405
has text: thanks for your comment joe
score: 0
type: Comment

http://stackoverflow.com/comment/91927447
comment on: http://stackoverflow.com/q/52493079
score: 0
has text: if I remove the astype line I receive this: TypeError: 0 is not a string in the scatter plot line that's why I converted to string do you have any idea how to scatter plot without receiving this error
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91808212
type: QuestionComment
has text: I tried to pass the -L parameter, including the path to where I found libgomp.a (`C:\msys64\mingw64\lib\gcc\x86_64-w64-mingw32\7.3.0`), but it still gives the same error.
comment on: http://stackoverflow.com/q/52430325
score: 0
type: Comment

http://stackoverflow.com/q/52582390
downvote count: 2
has title: Python applying iterative linregress
upvote count: 1
has comment: http://stackoverflow.com/comment/92100733
type: Question
has body: I am working to get to the following output. Dataset first: I have been using the following code to get to the output but failing every time: import numpy as np import pandas as pd from scipy import stats df=pd.read_excel('I:/Python/Data/Copy.xlsx') grouped = df.groupby('Test Event') for test_event, g in grouped: print('Test Event: {}'.format(test_event)) df_np=np.array(g) x=np.array(df_np[:,3],dtype=float) y=np.array(df_np[:,4],dtype=float) for i, pair in enumerate(zip(x, y)): slope, intercept, r_value, p_value, std_err = stats.linregress(np.delete(x,i),np.delete(y,i)) print('slope', slope, 'for data without pair', i, ':', pair) This is what is needed: For every Test Event, there is a unique ID. For every Unique ID, there is a slope. The way the slope is obtained is mentioned in Comment section of the image. How do I go about solving this issue? In jupyter notebook, the final output needed is as follows: It gives output only for 'data without pair 9' for test events 111 and 112. I need 'data without pair 0',..., 'data without pair 9' as outputs per event.
has comment: http://stackoverflow.com/comment/92100008
accepted answer: http://stackoverflow.com/a/52582952
has comment: http://stackoverflow.com/comment/92100878
tagged with: numpy
has comment: http://stackoverflow.com/comment/92100697
has comment: http://stackoverflow.com/comment/92099956
answer count: 1
favorite count: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52582952
has comment: http://stackoverflow.com/comment/92100762
tagged with: jupyter-notebook
score: -1
has comment: http://stackoverflow.com/comment/92100085
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/91895871
type: Comment
comment on: http://stackoverflow.com/a/52477308
has text: Yes, `(k[0] != v[0]) ` ==> `num` & `(k[-1] != v[-1])` ==> `tex`...You can test by printing k[0], v[0] and k[-1], v[-1]
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91827663
type: Comment
has text: Thank you for the advice :)
comment on: http://stackoverflow.com/a/52440375
score: 0
type: AnswerComment

http://stackoverflow.com/q/52446826
tagged with: scikit-learn
type: UnansweredQuestion
tagged with: python
has title: Is there any way to get SciKit-Learn to use the hard drive?
has comment: http://stackoverflow.com/comment/91836668
type: Question
has comment: http://stackoverflow.com/comment/91838225
has body: I'm very new to scikit-learn and machine learning in general. I have a data set which comprises 140,565 rows and 17 columns. I'm using someone else's code which runs a Random Forest model, on a machine that has a 2.7GHz processor, 4GB RAM, Windows 10. Obviously 4GB RAM isn't enough, and I can't upgrade this system (ultrabook). It has an SSD in it. Is there a way to configure scikit to use the hard drive instead of RAM (more space at the expense of speed)?
has answer: http://stackoverflow.com/a/52446927
score: 0
answer count: 1

http://stackoverflow.com/a/52478883
answers question: http://stackoverflow.com/q/52478792
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
has body: please try this : file = open('data.pkl', 'wb') pickle.dump(image, file) file.close()
type: Answer
accepted answer of: http://stackoverflow.com/q/52478792

http://stackoverflow.com/a/52545973
has body: If you'd rather not use regex: string1 = "I have $(food1), $(food2), $(food3) for lunch" string2 = "I have rice, soup, vegetable for lunch" trans_table = str.maketrans({'$': '', '(': '', ')': '', ',': ''}) { substr1.translate(trans_table): substr2.translate(trans_table) for substr1, substr2 in zip(string1.split(),string2.split()) if substr1 != substr2 } Output: {'food1': 'rice', 'food2': 'soup', 'food3': 'vegetable'} Alternatively, something a bit more flexible: def substr_parser(substr, chars_to_ignore='$(),'): trans_table = str.maketrans({char: '' for char in chars_to_ignore}) substr = substr.translate(trans_table) # More handling here return substr { substr_parser(substr1): substr_parser(substr2) for substr1, substr2 in zip(string1.split(),string2.split()) if substr1 != substr2 } Same output as above.
type: Answer
answers question: http://stackoverflow.com/q/52545751
score: 0

http://stackoverflow.com/comment/92384949
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52562106
has text: I've also tried running the same situation with Python 3.4 as that allows me to keep enum34 which is a requirement of one of my packages and still it fails

http://stackoverflow.com/comment/91845640
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52451007
score: 1
has text: *"... but couldn't get it to work."* Please include the exact, complete error message in the question.

http://stackoverflow.com/q/52453635
favorite count: 0
tagged with: python-3.x
has title: Changing the Duplicate values in the multi dimensional list in Python
has comment: http://stackoverflow.com/comment/91850284
tagged with: python
has body: I've a list of lists like this: [[10000, 10001, 10002, 115050, 11506,11786,11787, 11788], [12553,12554,10001,10002], [9500, 9501, 9502, 9503, 9759, 9760, 9761, 11778,11779, 11780, 11781,11782, 12112, 12113]] What I want to do is, find the duplicate values that are in these lists, and change them by 1 or 2 as required, so that there would be no duplicate or overlap at all. I can't change them to random values, because they are pixel values and changing them hugely will distort my result. I tried something like this: even = [[10000, 10001, 10002, 115050, 11506,11786,11787, 11788], [12553,12554,10001,10002], [9500, 9501, 9502, 9503, 9759, 9760, 9761, 11778,11779, 11780, 11781,11782, 11788, 11789, 12112, 12113]] if(len(even)&gt;1): inter = [] for i in range(len(even)-1): #intersections = [set(even[i]).intersection(even[j]) for j in range(i+1, len(even)) ] for j in range(i+1, len(even)-1): intersect = list(set(even[i]).intersection(even[j])) if len(intersect)&gt;0: for inte in intersect: even[j][even[j].index(inte)] =even[j][even[j].index(inte)]+1 print("we changed the value here", index) print(even) This is hardly and decent solution, because it fails in this very example. I tried to do it with numpy as well. length = len(sorted(even,key=len, reverse=True)[0]) y=np.array([xi+[None]*(length-len(xi)) for xi in even]) print( y, even) y[:,1:] *=(np.diff(y,axis=1)!=0) However this code would change the duplicate values to 0, which I don't desire. Any help would be really appreciated. Two things to Note: there shouldn't be any duplicate value in any of the lists inside the list, and the changed value shouldn't have the huge difference, 1,2 + or - depending upon, how we can mitigate the duplication. Thanks in advance.
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52453669
type: Question
has answer: http://stackoverflow.com/a/52453758
downvote count: 0
score: 4
upvote count: 4
possible better answer: http://stackoverflow.com/a/52453758
answer count: 2
accepted answer: http://stackoverflow.com/a/52453669
has comment: http://stackoverflow.com/comment/91850308

http://stackoverflow.com/q/52476567
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 3
has body: I'm using the below code to rename few hundreds of files, it works great when the file is smaller than 1GB in size, but when it encounter larger files it doesn't extract anything and the resulted file name is blank. import os, linecache for filename in os.listdir(path): if not filename.startswith("out"): continue # less deep file_path = os.path.join(path, filename) # folderpath + filename fourteenline = linecache.getline(file_path, 14) # maybe 13 for 0-based index? new_file_name = fourteenline[40:40+50].rstrip() # staring at 40 with length of 50 os.rename(file_path, os.path.join(path, new_file_name))
upvote count: 3
has answer: http://stackoverflow.com/a/52492136
has comment: http://stackoverflow.com/comment/91894870
possible better answer: http://stackoverflow.com/a/52480720
type: Question
has answer: http://stackoverflow.com/a/52480720
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91894831
accepted answer: http://stackoverflow.com/a/52492136
has title: Renaming files will not work with >1 GB file
favorite count: 0

http://stackoverflow.com/comment/91883288
has text: One fundamental thing of pandas is it is built on top of numpy and so it runs matrix or blockwise operations as opposed to looping. You appear to be running aggregations which can be done in SQL query or in pandas without any looping. Please post current data and desired results.
comment on: http://stackoverflow.com/q/52469045
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92006451
type: Comment
comment on: http://stackoverflow.com/a/52533661
score: 0
type: AnswerComment
has text: The question is about identifying a specifile file type.

http://stackoverflow.com/a/79499973
type: Answer
has body: Found this article useful in understanding this at a practical level. Re-reading the accepted answer after this made sense.
answers question: http://stackoverflow.com/q/52465237
score: 0

http://stackoverflow.com/a/52487781
type: Answer
answers question: http://stackoverflow.com/q/52480307
has body: I got the problem. Infamous like a forgotten semicolumn. urlpatterns = [ path(r'reports/&lt;int:game_id&gt;/)', views.get_pdf_report, name='get_pdf_report'), path(r'teams/&lt;int:team_id&gt;/)', views.get_team_formation, name='get_team_formation'), path(r'game-instance/&lt;int:game_id&gt;/)', views.get_match_instance, name='get_match_instance'), url(r'^api-auth/', include('rest_framework.urls')), url(r'^', include(router.urls)) ] Do you see the forgotten, and unexplainable brackets? Just at the end of the url pattern?!
score: 0

http://stackoverflow.com/comment/97032365
has text: @saurabheights is there some boiler plate code or template that I could use to save some time? (I'm currently in an end-of-trimester rush and won't be able to touch this for a while.)
score: 0
comment on: http://stackoverflow.com/q/52469866
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91929940
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52494567
score: 0
has text: also I advice you to use MPTT library (https://django-mptt.readthedocs.io/en/latest/models.html) if you did not do that yet for mother-child relations.

http://stackoverflow.com/q/52460389
has comment: http://stackoverflow.com/comment/91862794
answer count: 1
has answer: http://stackoverflow.com/a/52460462
accepted answer: http://stackoverflow.com/a/52460462
has title: Adding dictionary items, while loop
has comment: http://stackoverflow.com/comment/91862962
tagged with: python
has comment: http://stackoverflow.com/comment/91862802
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91862928
has comment: http://stackoverflow.com/comment/91862888
has comment: http://stackoverflow.com/comment/91862786
has comment: http://stackoverflow.com/comment/91862847
type: Question
has body: I am unsure what to equal spent to. I am trying to add the [2] dictionary item for each key. movies = { 1:('The Shawshank Redemption' , 'Bob', 25, 5), 2:('The Godfather', 'Kelly', 25, 4), 3:('The Dark Knight', 'Tyler', 25, 3), 4:('12 Angry Men', 'Bob', 25, 4), 5:('The Shawshank Redemption' , 'Bill', 35, 4), 6:('The Godfather', 'Sally', 35, 5), 7:('The Dark Knight', 'Suzy', 19, 5), 8:('12 Angry Men', 'Frank', 19, 3), 9:('The Shawshank Redemption' , 'Sally', 35, 5), 10:('The Godfather', 'Leslie', 40, 2), 11:('The Green Knight', 'Tom', 35, 2), 12:('14 Angry Men', 'Kaitlyn', 25, 4)} spent = x = 1 while spent &lt; max(movies.keys()): spent += movies[x][2] x += 1 else: print ('The total money spent is:', spent)
has comment: http://stackoverflow.com/comment/91862817
score: 0
has comment: http://stackoverflow.com/comment/91862924

http://stackoverflow.com/a/52488287
accepted answer of: http://stackoverflow.com/q/52488252
type: Answer
has comment: http://stackoverflow.com/comment/91917903
upvote count: 5
score: 5
has body: Are you looking for cumcount? If so, you can ditch the loop and vectorize your solution. df = df.set_index(df.groupby(level=0).cumcount(), append=True) print(df) Count Price Fruit Color Apple Red 0 3 $1.29 Green 1 9 $0.99 Pear Red 0 25 $2.59 Green 1 26 $2.79 Lime Green 0 99 $0.39 Or, if you'd prefer doing this in one fell swoop, df_unindexed = pd.read_csv(data) df = df_unindexed.set_index(['Fruit', 'Color', df.groupby('Fruit').cumcount()]) print(df) Count Price Fruit Color Apple Green 0 9 $0.99 Red 1 3 $1.29 Lime Green 0 99 $0.39 Pear Green 1 26 $2.79 Red 0 25 $2.59 To rename the index, use rename_axis: df = df.rename_axis(['Fruit', 'Color', 'Bob']) print(df) Count Price Fruit Color Bob Apple Red 0 3 $1.29 Green 1 9 $0.99 Pear Red 0 25 $2.59 Green 1 26 $2.79 Lime Green 0 99 $0.39
answers question: http://stackoverflow.com/q/52488252
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52433821
type: Answer
has body: There is indeed: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; h, w = 4, 6 &gt;&gt;&gt; &gt;&gt;&gt; A = np.random.randint(0, 100, (h, w, 3)) &gt;&gt;&gt; B = np.random.randint(0, h*w, (h, w, 2)) % [h, w] &gt;&gt;&gt; &gt;&gt;&gt; C = np.zeros(A.shape) &gt;&gt;&gt; for i in range(B.shape[0]): ... for j in range(B.shape[1]): ... C[i, j, :] = A[B[i, j, 0], B[i, j, 1], :] ... &gt;&gt;&gt; &gt;&gt;&gt; C2 = A[(*np.moveaxis(B, 2, 0),)] &gt;&gt;&gt; np.all(C == C2) True
has comment: http://stackoverflow.com/comment/91814153
has comment: http://stackoverflow.com/comment/91813671
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52433737
upvote count: 2
answers question: http://stackoverflow.com/q/52433737

http://stackoverflow.com/q/52454250
has comment: http://stackoverflow.com/comment/91852772
type: Question
upvote count: 2
has body: I'm passing a video as input, and the grabbed video is the output. the output is showing in the window but at the end its throwing an attribute error and video file is saving with the given name but its an empty file. I went through many questions similar to this, and I tried all those answers but the output was same. Can anyone tell me what is the mistake in this code? import imutils import numpy as np import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") args = vars(ap.parse_args()) lower = np.array([0, 0, 20], dtype="uint8") upper = np.array([25, 255, 255], dtype="uint8") if not args.get("video", False): camera = cv2.VideoCapture('videos/15-IMG_1090.MOV') fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) else: camera = cv2.VideoCapture('videos/15-IMG_1093.MOV') fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) while True: # grab the current frame (grabbed, frame) = camera.read() if args.get("video") and not grabbed: break # resize the frame, convert it to the HSV color space, # and determine the HSV pixel intensities that fall into # the speicifed upper and lower boundaries frame = imutils.resize(frame, width=500) converted = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) skinMask = cv2.inRange(converted, lower, upper) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)) skinMask = cv2.erode(skinMask, kernel, iterations=2) skinMask = cv2.dilate(skinMask, kernel, iterations=2) skinMask = cv2.GaussianBlur(skinMask, (3, 3), 0) skin = cv2.bitwise_and(frame, frame, mask=skinMask) out.write(skin) cv2.imshow("images", np.hstack([frame, skin])) # if the 'q' key is pressed, stop the loop if cv2.waitKey(1) &amp; 0xFF == ord("q"): break camera.release() out.release() cv2.destroyAllWindows() And here is the error. Traceback (most recent call last): File "E:/Harshitha/python learning/python/vide…
has comment: http://stackoverflow.com/comment/91854639
has comment: http://stackoverflow.com/comment/91856041
favorite count: 0
has comment: http://stackoverflow.com/comment/91852221
tagged with: python
has title: Video not saving in opencv python
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91855260
has comment: http://stackoverflow.com/comment/91855811
tagged with: opencv

http://stackoverflow.com/a/52497383
type: Answer
has body: because you do not specify what happens, when x = "". this leads to an error if x is indeed an empty string, because then your function returns type None, which is unexpected by the caller.
downvote count: 1
score: 3
answers question: http://stackoverflow.com/q/52497333
upvote count: 4

http://stackoverflow.com/comment/91957832
type: AnswerComment
has text: thanks but appear my file is really complicated it is a txt and within the lines that are not very well structures collection of information . see example : 8995391 78090 2018-05-06 09:50:59.4446230 BUNDABERG CENTRAL NULL 134 NULL 7 JSW 2018-05-06 09:50:59.9881146 2018-05-06 09:50:59.9881146
type: Comment
comment on: http://stackoverflow.com/a/52493262
score: 0

http://stackoverflow.com/q/52588378
tagged with: python
has answer: http://stackoverflow.com/a/52588567
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
tagged with: numpy
tagged with: arrays
accepted answer: http://stackoverflow.com/a/52588567
score: 0
answer count: 1
favorite count: 0
has title: Find the corresponding [x,y] coordinates for a given z coordinate value
has body: I have a 3D array, and I were to find the greatest Z-coordinate in that array. After that I need to find the corresponding X and Y coordinate values based on the Z-coordinate. How can I achieve it quickly via numpy? What I did: I used argsort to first sort the given 3D array, then used np. max(array) to find the greatest Z-coordinate. I do not know how else to continue. Can numpy.where be useful here? Thanks!

ipython
tags question: http://stackoverflow.com/q/52480667
tag name: ipython
tags question: http://stackoverflow.com/q/52494488
type: Tag
tags question: http://stackoverflow.com/q/52551878
tags question: http://stackoverflow.com/q/52496972
tags question: http://stackoverflow.com/q/52547769

http://stackoverflow.com/comment/91893715
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52475728
type: QuestionComment
has text: This is unclear. Please [edit your question](https://stackoverflow.com/posts/52475728/edit) with a precise description of what you are looking to achieve.

http://stackoverflow.com/a/52612403
has comment: http://stackoverflow.com/comment/92191022
has comment: http://stackoverflow.com/comment/92199230
has comment: http://stackoverflow.com/comment/92206466
has comment: http://stackoverflow.com/comment/92194276
has body: I think I understand what you are trying to do. I have no idea of the relative performance of our two machines so maybe you can benchmark it yourself. from PIL import Image import numpy as np # Load images, convert to RGB, then to numpy arrays and ravel into long, flat things a=np.array(Image.open('a.png').convert('RGB')).ravel() b=np.array(Image.open('b.png').convert('RGB')).ravel() # Calculate the sum of the absolute differences divided by number of elements MAE = np.sum(np.abs(np.subtract(a,b,dtype=np.float))) / a.shape[0] The only "tricky" thing in there is the forcing of the result type of np.subtract() to a float which ensures I can store negative numbers. It may be worth trying with dtype=np.int16 on your hardware to see if that is faster. A fast way to benchmark it is as follows. Start ipython and then type in the following: from PIL import Image import numpy as np a=np.array(Image.open('a.png').convert('RGB')).ravel() b=np.array(Image.open('b.png').convert('RGB')).ravel() Now you can time my code with: %timeit np.sum(np.abs(np.subtract(a,b,dtype=np.float))) / a.shape[0] 6.72 µs ± 21.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Or, you can try an int16 version like this: %timeit np.sum(np.abs(np.subtract(a,b,dtype=np.int16))) / a.shape[0] 6.43 µs ± 30.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) If you want to time your code, paste in your function then use: %timeit compare_images_pil(img1, img2)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92190829
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/92204499
type: Answer
accepted answer of: http://stackoverflow.com/q/52560845
answers question: http://stackoverflow.com/q/52560845
has comment: http://stackoverflow.com/comment/92168752
has comment: http://stackoverflow.com/comment/123018619
upvote count: 5

http://stackoverflow.com/a/52537068
downvote count: 0
type: Answer
upvote count: 12
has comment: http://stackoverflow.com/comment/92013709
accepted answer of: http://stackoverflow.com/q/52536997
answers question: http://stackoverflow.com/q/52536997
score: 12
type: AcceptedAnswer
has body: you can rewrite this as follows: new_list = [y for x in nested_list for d, y in enumerate(x) if d == 1] loops are in the "natural" order, and the condition is in the end. Include y only if d==1 one possible result (because dicts aren't ordered): [{'c': 3, 'd': 4}, {'c': 7, 'd': 8}] Note that in your case, it's simpler and more efficient (O(n) vs O(n**2)) to write: new_list = [x[1] for x in nested_list] the only difference is that if x is too short the latter code will break so maybe test length: new_list = [x[1] for x in nested_list if len(x)&gt;1]

http://stackoverflow.com/a/52503327
accepted answer of: http://stackoverflow.com/q/52502495
answers question: http://stackoverflow.com/q/52502495
has body: I don't know why most of the answers have list1+list2 as it will just append the list(s) which is not the expected output. You can try something as below. Taking order from your example provided where one element is from smaller list and other from the bigger list. input1='John Becky William Isaac' input2='James Ryan' input1=input1.split(' ') input2=input2.split(' ') new=[] max_list,min_list=(input1,input2) if len(input1)&gt;len(input2) else (input2,input1) for i in range(len(min_list)): new.append(min_list[i]+' '+max_list[i]) new += max_list[len(min_list):] print(' '.join(new)) # James John Ryan Becky William Isaac
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1
type: Answer

http://stackoverflow.com/comment/109313133
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55513812
has text: @atinjanki Hi, thanks for the feedback. It may related to scipy version, I've updated my response.
score: 0

http://stackoverflow.com/q/52431937
has answer: http://stackoverflow.com/a/52432022
has title: How to count frequency in a time period by group using pandas
accepted answer: http://stackoverflow.com/a/52432022
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: Suppose I have sorted sample dataframe looks like this CustomerID CallID Date 123 1 01/30/2017 123 2 01/31/2017 123 3 02/03/2017 123 4 02/07/2017 123 5 02/08/2017 I want to count how many calls did I received from the same customer in the past 7 days as of each date. The desired output dataframe would be CustomerID CallID Date NumOfCallsOneWeek 123 1 01/30/2017 1 123 2 01/31/2017 2 123 3 02/03/2017 3 123 4 02/07/2017 2 123 5 02/08/2017 3 Note as of 02/07/2017, the 2 calls on 01/30/2017 are received over a week ago, so they are not counted. How do I do this in pandas? Thank you for your help.
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/92022861
has text: @Tanmayjain probably both because they aren't within 0.01 of each other
score: 0
comment on: http://stackoverflow.com/q/52541204
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52562063
tagged with: attributes
tagged with: python
accepted answer: http://stackoverflow.com/a/52570621
type: AnsweredQuestion
has title: Button' object has no attribute python callback
type: Question
has comment: http://stackoverflow.com/comment/92077823
answer count: 1
has comment: http://stackoverflow.com/comment/92070411
tagged with: callback
has body: I want to have the callback function for the btn1 to change the player1.center_y and to interact with my program in general(changing values in the Gameclass). However I get the error 'Button' object has no attribute 'player1' when the button is clicked. Is it because the instance class in wrong or something?.I am kind of new to OOP. here is the relevant code: class Gameclass(Widget): def on_touch_move(self, touch): if touch.x &lt; self.width / 3: self.player1.center_y = touch.y if touch.x &gt; self.width - self.width / 3: self.player2.center_y = touch.y def callback(self): self.player1.center_y = 22 self.player2.center_y = 250 btn1 = Button(text='click me') btn1.bind(on_press=Gameclass.callback)
score: 0
has answer: http://stackoverflow.com/a/52570621
tagged with: kivy

http://stackoverflow.com/q/52569472
has answer: http://stackoverflow.com/a/52569648
favorite count: 0
tagged with: postgresql
tagged with: python
accepted answer: http://stackoverflow.com/a/52569574
type: AnsweredQuestion
upvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/52569574
possible better answer: http://stackoverflow.com/a/52569648
has title: How can I sort by a DateTimeField and choose distinct elements based on a ForeignKey?
has comment: http://stackoverflow.com/comment/92076086
type: Question
has body: I am using PostgreSQL as database for my Django project. I have the following models: class Food(models.Model): """Stores a food entry""" name = models.CharField(max_length=50) image_id = models.CharField(max_length=20) description = models.TextField() class SurveyResult(models.Model): """Stores survey food result based on emoji and personality""" emoji = models.CharField(max_length=10) personality = models.CharField(max_length=50) food = models.ForeignKey(Food, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) rating = models.PositiveSmallIntegerField(default=0) I need to write a query sorted by '-timestamp', and just get distinct values for 'food'. This is my what I have tried: SurveyResult.objects.order_by('-timestamp').distinct('food') However, I am getting the following error: ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("recommender_surveyresult"."food_id") "r... I have read several answers from several questions, and I found an answer that basically says to do something like this: SurveyResult.objects.order_by('food', '-timestamp').distinct('food') However, I am not getting what I want that is the latest SurveyResult objects that have a distinct food. How can I achieve this? Let's suppose I have the following table in my database: # surveyresults id emoji personality food timestamp rating 1 :) Famous US 1 2018-01-01 - 9:00 1 2 XD Famous CN 3 2018-01-01 - 9:10 2 3 :) Famous NZ 5 2018-01-01 - 9:15 3 4 :( Famous FR 5 2018-01-01 - 9:35 4 5 XD Famous US 1 2018-01-01 - 9:45 5 6 ;) Famous JP 4 2018-01-01 - 9:55 5 7 :o Famous SP 4 2018-01-01 - 10:00 5 The query should give me the folowing: id emoji personality food timestamp rating 7 :o Famous SP 4 2018-01-01 - 10:00 5 5 XD Famous US 1 2018-01-01 - 9:45 5 4 :( Famous FR 5 2018-01-01 - 9:35 4 2 XD Famous CN 3 2018-01-01 - 9:10 2 I would also like to know if it is possible to achieve this just with one query.
score: -1
has comment: http://stackoverflow.com/comment/92076048
answer count: 2
downvote count: 1

http://stackoverflow.com/q/52500052
has comment: http://stackoverflow.com/comment/91940695
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52500218
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: isinstance
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52500218
type: Question
score: 4
upvote count: 4
has title: How do i use correctly the isinstance()
has body: def convBin(): cont = [] rest = [] dev = [] decimal = [] print("Give me a number: ") valor = input() if isinstance(valor, int): while valor &gt; 0: z = valor // 2 resto = x%2 valor = valor // 2 cont.append(z) rest.append(resto) cont.reverse() rest.pop() dev.append(cont[1]) for i in rest: dev.append(rest[i]) print(" ") print("Lista de devoluciones: ") print(dev) print("") elif isinstance(valor, float): a = valor // 1 b = valor % 1 while a &gt; 0: z = a // 2 resto = a%2 a = a // 2 cont.append(z) rest.append(resto) cont.reverse() rest.pop() dev.append(cont[1]) for i in rest: dev.append(rest[i]) print("How many decimals do you want?") num = input() while num &gt; 0: dec = b * 1 dec2 = dec//1 dec %= 1 decimal.append(dec2) print("Full part: ") print(dev) print("Decimal part:") print(num) else: print("An error has appeared") I'm studying Python on my own, so I know that I have big mistakes in the code. Any advice is welcome. This code is for a binary converter. Got a problem with the isinstance(). When I try the code, at the moment that read by keyboard it ignores the "if" and it goes directly to the "else". For example: 1. It asks you a number. 2. It goes to the first if and compare the x type with int(for some reason it is false). 3. It goes to the `elif` and does the same(check if its float). 4. Both are false so it goes to else and prints the error.

http://stackoverflow.com/a/52549043
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92037634
score: 1
answers question: http://stackoverflow.com/q/52548977
has body: The correct name is quandl, all lowercase as shown in the docs. Therefore try import quandl
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52548977
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92037658

http://stackoverflow.com/comment/92010895
score: 0
type: Comment
type: QuestionComment
has text: Are you using a version of the IE driver that is compatible with the version of IE installed on your EC2 server?
comment on: http://stackoverflow.com/q/52533297

http://stackoverflow.com/a/53337554
has comment: http://stackoverflow.com/comment/117279349
has comment: http://stackoverflow.com/comment/103596290
score: 13
has comment: http://stackoverflow.com/comment/106227149
has body: When using ImageFolder class and with no custom loader, pytorch uses PIL to load image and converts it to RGB. Default Loader if torchvision image backend is PIL: def pil_loader(path): with open(path, 'rb') as f: img = Image.open(f) return img.convert('RGB') You can use torchvision's Grayscale function in transforms. It will convert the 3 channel RGB image into 1 channel grayscale. Find out more about this at here A sample code is below, import torchvision as tv import numpy as np import torch.utils.data as data dataDir = 'D:\\general\\ML_DL\\datasets\\CIFAR' trainTransform = tv.transforms.Compose([tv.transforms.Grayscale(num_output_channels=1), tv.transforms.ToTensor(), tv.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainSet = tv.datasets.CIFAR10(dataDir, train=True, download=False, transform=trainTransform) dataloader = data.DataLoader(trainSet, batch_size=1, shuffle=False, num_workers=0) images, labels = iter(dataloader).next() print (images.size())
answers question: http://stackoverflow.com/q/52439364
downvote count: 0
type: Answer
upvote count: 13

http://stackoverflow.com/q/52585737
type: AnsweredQuestion
has body: The html like this: ... title1 subtitle1 title2 subtitle2 title1 subtitle1 ... python code almost like this: ........ if soup.select("#market-summary")[0].findAll('li'): prices = soup.select("#market-summary")[0].findAll('li') if prices is not None and len(prices) > 0: price = [ {'size': x.find(class_="title").get_text(), 'price': x.find(class_="subtitle").get_text()} for x in prices ] return price return 'price?' return 'li?' ........ ........ Now I start running this program the program is running. and The console was printing the price but just two or three mins, I got error message: 'IndexError: list index out of range' and program interrupted and i tried it again and again. the always 'IndexError: list index out of range' why the didn't show me 'price?' or 'li?'. Case BeautifulSoup?
type: Question
has answer: http://stackoverflow.com/a/52585794
tagged with: pyspider
score: 0
answer count: 1
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52585794
tagged with: python
has title: Why use BeautifulSoup find_all method will results in an error(list index out of range)?

http://stackoverflow.com/comment/92077500
has text: @nemo good point. But you do not necessarily get the best solution out of several possible. Anyway, in order to do that in python, this should be fine: > from numpy import random >random.seed(5)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52522810

http://stackoverflow.com/q/52518746
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52537374
has answer: http://stackoverflow.com/a/52524559
answer count: 3
downvote count: 0
tagged with: tensorflow-datasets
favorite count: 0
linked to: http://stackoverflow.com/q/37063952
possible better answer: http://stackoverflow.com/a/52535578
has answer: http://stackoverflow.com/a/52535578
accepted answer: http://stackoverflow.com/a/52537374
tagged with: python
has title: Create stateful counter with TF Dataset and Eager
type: AnsweredQuestion
has body: I'm trying to add an accumulator in my Tensorflow Dataset pipeline. Basically, I have this: def _filter_bcc_labels(self, labels, labels_table, bcc_count): bg_counter = tf.zeros(shape=(), dtype=tf.int32) def _add_to_counter(): tf.add(bg_counter, 1) # Here the bg_counter is always equal to 0 tf.Print(bg_counter, [bg_counter]) return tf.constant(True) return tf.cond(tf.greater_equal(bg_counter, tf.constant(bcc_count, dtype=tf.int32)), true_fn=lambda: tf.constant(False), false_fn=_add_to_counter) ds = ds.filter(lambda file, position, img, lbls: self._filter_bcc_labels(lbls, {"BCC": 0, "BACKGROUND": 1}, 10)) My goal here is to increment the bg_counter when the tf.cond false_fnis reached but my variable always has the value 0, it never actually increments. Someone can explain to me what is happening? Bear in mind I'm using TF eager and I can't use ds.make_initializable_iterator() then feed in my bg_counter initial value. Thanks
score: 1
upvote count: 1

http://stackoverflow.com/q/52545774
tagged with: python
tagged with: regex
has body: I wrote a function to extract integer from strings. The strings example is below and it is a column in my dataframe. The output I got is in square bracket, with a lot of numbers inside. I want to use those numbers to compute further, but when I check what it is, instead of integer, it is a Nonetype. Why is that? and how can I convert it into integer so I can find .sum() or .mean() with the output numbers I got? Ideally, I want the extracted integer as another column like with str.extract(regex, inplace=True). Here is part of my data, which is a column in my dataframe df2017 Bo medium lapis 20 cash pr gr Porte monnaie dogon vert olive 430 euros carte Bo noires 2015 fleurs clips moins brillant 30 ... Necklace No 20 2016 80€ carte Grecs 20h00 salo... Bo mini rouges 30 carte 13h it Necklace No 17 2016 100€ cash pr US/NYC crois ... Chocker No 1 2016 + BO No 32 2016 70€ cash pr … Here is my code def extract_int_price(): text=df2017['Items'].astype(str) text=text.to_string() amount=[int(x) for x in re.findall('(?&lt;!No\s)(?&lt;!new)(?!2016)(\d{2,4})+€?', text)] print (amount) Thank you!
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52545974
has answer: http://stackoverflow.com/a/52545992
type: Question
answer count: 3
tagged with: pandas
upvote count: 1
possible better answer: http://stackoverflow.com/a/52545974
favorite count: 0
tagged with: extract
has title: function to extract integer with regex returns nonetype
has answer: http://stackoverflow.com/a/52546114
accepted answer: http://stackoverflow.com/a/52546114

http://stackoverflow.com/comment/91883899
has text: @stovfl That question is different from mine
comment on: http://stackoverflow.com/q/52466043
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52493328
has body: Suppose I have the following list in Python: my_list = [10] * 95 Given n, I want to replace any other m elements with zero in my list, while keeping the next n elements. For example, if n = 3 and m = 2, I want my list to look like: [10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0] If it can't be filled perfectly, as is the case with n = 4 and m = 2, then it's OK if my list looks like this: [10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0] How should I try to solve this problem?
has answer: http://stackoverflow.com/a/52493423
has answer: http://stackoverflow.com/a/52493584
has answer: http://stackoverflow.com/a/52497576
has comment: http://stackoverflow.com/comment/91934049
has title: Periodically replacing values in a list
downvote count: 6
has comment: http://stackoverflow.com/comment/91938449
answer count: 8
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91927705
possible better answer: http://stackoverflow.com/a/52493738
has comment: http://stackoverflow.com/comment/91938412
has answer: http://stackoverflow.com/a/52493738
has comment: http://stackoverflow.com/comment/91927566
has comment: http://stackoverflow.com/comment/91927830
score: 24
has answer: http://stackoverflow.com/a/52493598
has comment: http://stackoverflow.com/comment/91938454
has answer: http://stackoverflow.com/a/52614902
tagged with: replace
type: Question
has comment: http://stackoverflow.com/comment/91934293
has comment: http://stackoverflow.com/comment/91943756
has answer: http://stackoverflow.com/a/52493671
favorite count: 0
upvote count: 30
has answer: http://stackoverflow.com/a/52493987
accepted answer: http://stackoverflow.com/a/52493671
tagged with: python
has comment: http://stackoverflow.com/comment/91927595
linked to: http://stackoverflow.com/q/2764017

http://stackoverflow.com/a/52568520
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52568304
has body: You should use flask-pymongo like this: from flask import Flask from flask_pymongo import PyMongo app = Flask(__name__) app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase" mongo = PyMongo(app) So in run.py, you should use this code: from flask import Flask from app import api_bp from db import mongo def create_app(config_filename): app = Flask(__name__) app.config.from_object(config_filename) app.register_blueprint(api_bp, url_prefix='/api') # mongo.init_app(app) # remove this line return app # def logger(): # def database(): if __name__ == "__main__": app = create_app("config") py_mongo = mongo(app) app.run(host='0.0.0.0', port=8080, debug=True)

http://stackoverflow.com/comment/92082828
score: 1
type: Comment
type: QuestionComment
has text: The operation you're looking for is "flatten" the list. Then take the length of the flattened list
comment on: http://stackoverflow.com/q/52573275

http://stackoverflow.com/comment/91955682
type: QuestionComment
has text: Please don't give an off-site reference to "the entire code". We need the [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) in the question.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52507359

http://stackoverflow.com/comment/91857784
comment on: http://stackoverflow.com/q/52457779
has text: No, I do not know it beforehand.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52524736
has body: I've been trying to use pg8000 to interact with my SQL server, but for some reason, it won't accept params properly. It does seem to recognize the paramstyle, and then knows to change those to the PostgreSQL params, but it never seems to pass the params through. I looked at the documentation example here (link) for examples, and they didn't work. Here are some examples: query = """ SELECT * FROM schema.table_name """ conn = pg8000.connect(**credential_dict) cursor = conn.cursor() cursor.execute(query) This example works. The next two do not: query = """ SELECT * FROM %s """ conn = pg8000.connect(**credential_dict) cursor = conn.cursor() cursor.execute(query, 'schema.table_name') query = """ SELECT * FROM %s """ conn = pg8000.connect(**credential_dict) cursor = conn.cursor() cursor.execute(query, ('schema.table_name',)) These queries fail, but the error I get says the error is at the $1 which pg8000 converts the %s to. What am I doing wrong?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91989598
tagged with: python
has answer: http://stackoverflow.com/a/66940589
has title: pg8000 Can't Parameterize Queries
has answer: http://stackoverflow.com/a/52524887
has comment: http://stackoverflow.com/comment/91990016
type: Question
has comment: http://stackoverflow.com/comment/91989873
tagged with: pg8000
tagged with: postgresql
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91990192

http://stackoverflow.com/comment/92052466
score: 0
type: QuestionComment
type: Comment
has text: I'd suggest learning how classes work in python, your use of `Bitfinex.__init__` probably isn't doing what you expect
comment on: http://stackoverflow.com/q/52556616

http://stackoverflow.com/a/52534556
answers question: http://stackoverflow.com/q/52533665
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92009149
has comment: http://stackoverflow.com/comment/92008495
has body: Let's go in detail over your code. The first thing I noticed is that you need to add the pass keyword to any block that is empty in python. Also, you are forgetting to open your block by not using a color. So, if I run the code as is, I get this: File "main.py", line 2 def __init__(self) ^ SyntaxError: invalid syntax Going down to the second method, in the first letter of the print method (P), you notice that is in uppercase. In programming, naming conventions are important, so print() should be all in lowercase. Let's take a look at the errors marked in the second method: As mentioned above, correct print(). Moving on to the next thing, Size is underlined in green. I would suggest you get a linting program for your code, in this case, by convention variables should start with a lowercase letter. If we fix those two things, the state of your code is this: ok, nice, things are getting better now. But, why self has a red underline? The reason of that self contextualize the current instance calling this method of this class. the issue is that the stack property has not been declared, in order to do this, change your code to be like this: class stack: def __init__(self): self.stack = [] def stacksize(self): size = len(self.stack) print('size is', size) Notice that I deleted pass, and assigned an empty list to the stack member variable. Of course you will decide that the stack member variable will be, in this case I just went to add it as a list. Ok, now, the final question would be, why size is None? With the code changes I added, it should now return zero (0) because the stack list is empty, but there is a list. Classes by convention start with an uppercase letter. Finally, how could you access the top element of the stack? Like this: The context of this code of course is outside the class context, notice it does not have self., but it should be the same for your self.stack. I hope this helps pal! :)

http://stackoverflow.com/q/52483655
score: 0
has comment: http://stackoverflow.com/comment/91910775
has title: In python+aiohttp, are the routes multithreaded? How can I communicate between the routes while their code is running?
has comment: http://stackoverflow.com/comment/91910951
type: UnansweredQuestion
tagged with: python
has body: I have a python-aiohttp web service. I want to have the routes interact with each other in this way: # http://base/pause async def pause_server(self, request): self._is_paused = True return json_response(data={'paused': true}) # http://base/resume async def resume_server(self, request): self._is_paused = False return json_response(data={'paused': false}) # http://base/getData async def get_data(self, request): while self._is_paused: time.sleep(0.1) return json_response(data=data) I've found that if I call pause_server, and then in a separate tab call get_data, the server sleeps as I expect, but once I call resume_server, the resume_server code never gets called and the server continues to sleep indefinitely in the get_data code. Is this something I can do with python-aiohttp? I would've guessed that each route runs on its own thread, but if that were the case, I'd have expected this code to work. Why do I want to do this? I'm doing some behave testing of a python application which uses aiohttp to host REST services. While my page is loading, I want to show some "Loading..." text on the screen. When I write my behave tests now, they look like this: Scenario: Load the page Given the server takes 5 seconds to respone And I go to the page Then the data is 'Loading...' Given I wait 5 seconds Then the data is '&lt;data&gt;' This relies on the server taking a certain amount of time to run. If I set the server to wait too long, the tests take forever to run. If I set the wait too short, the tests start to fail because it takes a while to actually run them. I'd rather do something like this: Scenario: Load the page Given I pause the server # calls pause_server endpoint And I go to the page # calls get_data endpoint Then the data is 'Loading...' Given I resume the server # calls resume_server endpoint Then the data is '&lt;data&gt;'
tagged with: aiohttp
answer count: 0
tagged with: multithreading
type: Question
has comment: http://stackoverflow.com/comment/91909216

http://stackoverflow.com/q/52539749
type: AnsweredQuestion
has body: I am looking to build a function in Python which creates a simple OLS regression with the following equation: Y_i - Y_i-1 = A + B(X_i - X_i-1) + E In words, Y_Lag = alpha + beta(X_Lag) + Error term Currently, I have the following dataset (This is a short version) Note: Y = Historic_Rate df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), columns=['Historic_Rate', 'Overnight', '1M', '3M', '6M']) So, what I'm trying to build is that I iteratively take an X variable and put it into a simple linear regression, the code I have built so far looks like this: #Start the iteration process for the regression to in turn fit 1 parameter #Import required packages import pandas as pd import numpy as np import statsmodels.formula.api as sm #Import dataset df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), columns=['Historic_Rate', 'Overnight', '1M', '3M', '6M']) #Y_Lag is always 1 time period only df['Y_Lag'] = df['Historic_Rate'].shift(1) #Begin the process with 1 lag, taking one x variable in turn array = df[0:0] array.drop(array.columns[[0,5]], axis=1, inplace=True) for X in array: df['X_Lag'] = df['X'].shift(1) Model = df[df.columns[4:5]] Y = Model['Y_Lag'] X = Model['X_Lag'] Reg_model = sm.OLS(Y,X).fit() predictions = model.predict(X) # make the predictions by the model # Print out the statistics model.summary() So, in essence, I'm looking to create a list of the column headers, which, in turn, will systematically go through my loop and each variable will be lagged and then regressed against a lagged Y variable. I'd also appreciate knowledge of how to output a model.X where X is the Xth iteration of the array, for a dynamic naming of variables.
tagged with: regression
has answer: http://stackoverflow.com/a/52540273
type: Question
accepted answer: http://stackoverflow.com/a/52540273
has title: Python: Loop a variable for a simple OLS
score: 4
tagged with: numpy
tagged with: for-loop
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
upvote count: 4

http://stackoverflow.com/q/52472824
tagged with: system-calls
tagged with: python
has answer: http://stackoverflow.com/a/52473359
type: UnansweredQuestion
tagged with: sockets
type: Question
has title: Python udp socket.recvfrom what packets will this receive?
answer count: 1
has body: I just started working with udp in python, and came up with the following client for talking back and forth with the server I'm writing. My question is about the recvfrom call. What packets will it receive? Will it get any packets or is there some registration that happens that says I want the results from the thing I sent to? I'm more curious about it at lower level, like what syscalls are being made. #!/usr/bin/python3 # shell.py # # Usage: # # ./shell.py &lt;IP_ADDR&gt; &lt;PORT&gt; import sys import socket SERVER_IP = sys.argv[1] SERVER_PORT = int(sys.argv[2]) MAX_MESSAGE_LEN = 4096 # set up the right socket type sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) target = (SERVER_IP, SERVER_PORT) try: while True: data = input("&gt; ") sent = sock.sendto(data.encode('utf-8'), target) data, server = sock.recvfrom(MAX_MESSAGE_LEN) print(repr(server)) print("Got {}".format(data)) finally: print("Closing socket") sock.close()
score: 0
tagged with: udp

http://stackoverflow.com/comment/92029066
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52544571
has text: Which byte arrays you think? binp and binInput are same, hash and dgst are not same. hash contains only positive numbers, dgst in java contains some negative numbers, but this is why I am moduling that by 26.. but some of them are different as in python

http://stackoverflow.com/q/52464967
has comment: http://stackoverflow.com/comment/91871793
tagged with: python
tagged with: opencv
linked to: http://stackoverflow.com/q/51688973
tagged with: python-tesseract
score: 1
has answer: http://stackoverflow.com/a/52465257
upvote count: 1
type: Question
has body: I have this python script that can detect the Number plate out of a car image. The number plate I have gotten is this number plate image after applying some openCV tools such as edge detection and morphological transformation. The number plate I got: However, the detected plate number I got after using pytesseract OCR library is : Detected Text : HHOHVBBGE This is the original Number plate: how can i get better accuracy output?
answer count: 1
downvote count: 0
tagged with: ocr
favorite count: 0
tagged with: python-3.x
has title: Python - Image processing and optical character reader
type: UnansweredQuestion

http://stackoverflow.com/q/52483763
type: Question
downvote count: 0
has title: Django - Authenticate against existing DB
answer count: 1
has answer: http://stackoverflow.com/a/52484239
has comment: http://stackoverflow.com/comment/91909597
favorite count: 0
has comment: http://stackoverflow.com/comment/91909446
type: UnansweredQuestion
has body: Apologies if this is simple or my terminology is off, this is my first django project. I haven't been able to find a similar solution for this online. I have an existing application, with a postgres DB where I authenticate my users. I have wrote an application in Django to interact with some tables and display info to the user. I would like to use Django to login and track User sessions against this DB. so I can use the features like {% if user.is_authenticated %} but I don't want to use the migrate command so I don't want to change the existing DB. I can access the table where the account info is as I created a model for it. I see you can use remote user logon param but I cant find any sample or guide on how to use it and am completely lost. Right now I create a login form in the views page. Then get the username and password that is entered, but I don't know what to do next. Also would need to hash the password. Is there a libray in djano that will do that for the app. Any pointers or online guides for this would be appreciated. Here is the views for login if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.data['account_email'] password = form.data['account_password'] user = authenticate(username=email) if user.check_password(password): login(request, user) return redirect('myapp:cust_select') else: # Username and password did not match raise ValidationError('Invalid Username/Password') return render(request, 'myapp/login.html', {'form' : form} backends.py from django.conf import settings from django.contrib.auth import get_user_model class UserAuthBackend(object): def authenticate(self, username=None, password=None): try: account = get_user_model() user = account.objects.get(account_email=username) if user: return user except account.DoesNotExist: print "account not found" return None def get_user(self, user_id): try: account = get_user_model() return account.objects.get(pk=user_id) except User.DoesNotExist: return None m…
tagged with: django
tagged with: python
score: 1
tagged with: authentication
upvote count: 1

http://stackoverflow.com/comment/92099967
comment on: http://stackoverflow.com/q/52580706
score: 0
has text: I think you are approaching the problem from wrong side. Don't try to merge already scraped data. Scrape them in such way that you get properly structured data in the first place.
type: Comment
type: QuestionComment

apache
tag name: apache
tags question: http://stackoverflow.com/q/52483932
tags question: http://stackoverflow.com/q/52560124
tags question: http://stackoverflow.com/q/52512606
tags question: http://stackoverflow.com/q/52448861
tags question: http://stackoverflow.com/q/52478149
type: Tag

http://stackoverflow.com/comment/92040149
has text: Is it possible to refactor `df['ref'] = ...` for more readability without compromising on speed?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52550430

http://stackoverflow.com/q/52512790
tagged with: seaborn
type: UnansweredQuestion
has body: In the figure the y-axis labels are in decimals from (0 to 1) i.e (0.1, 0.2, 0.4 etc). How can I convert this into a % format (10%, 20%, 40% etc). Just 10, 20, 40 also will do. Thanks, John g = sns.catplot(x="who", y="survived", col="class", ... data=titanic, saturation=.5, ... kind="bar", ci=None, aspect=.6)
has title: Python seaborn catplot - How do I change the y-axis scale to percentage
tagged with: python
tagged with: matplotlib
upvote count: 8
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52516671
answer count: 1
favorite count: 0
score: 8

http://stackoverflow.com/comment/91905780
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52482121
has text: Hmm I thought that was the solution but I keep getting that 'primes' is not defined' when i try to pass it in as an argument @SuperStew
type: AnswerComment

http://stackoverflow.com/q/52507108
upvote count: 1
downvote count: 0
favorite count: 0
has title: How to print the column name on Pandas DataFrame row?
has answer: http://stackoverflow.com/a/52507487
has answer: http://stackoverflow.com/a/52507278
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52507195
score: 1
type: Question
has answer: http://stackoverflow.com/a/52507195
has body: I have this DataFrame: df = pd.DataFrame({'day':['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017','1/6/2017','1/7/2017'], 'event':['Rain','Sunny','Snow','Snow','Rain','Sunny','Sunny'], 'temperature': [32, 35, 28,24,32,31,''],'windspeed':[6,7,2,7,4,2,'']}) df I am trying to find the headers for the missing values on index 6: for x in df.loc[6]: if x == '': print(df.columns.values) else: print(x) I have tried searching and the closest I could get was what I have now. Ultimately I'm trying insert these values into the dataframe: temperature = 34, windspeed = 8. But my first step was simply trying to build the loop/if statement that says if x=='' &amp; [COLUMN_NAME] == 'temperature'... and that is where I got stuck. I'm new to python, just trying to learn Pandas. I need to only return the column I'm on, and not a list of all the columns.
possible better answer: http://stackoverflow.com/a/52507278
tagged with: dataframe
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/91841842
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to create a large pandas dataframe from an sql query without running out of memory?](https://stackoverflow.com/questions/18107953/how-to-create-a-large-pandas-dataframe-from-an-sql-query-without-running-out-of)
comment on: http://stackoverflow.com/q/52449246
score: 0

http://stackoverflow.com/comment/92047737
comment on: http://stackoverflow.com/q/52498544
score: 0
type: Comment
has text: I didn't find any solution and really need to correct this to be able to find the best parameters for my ANN... Please anybody help...
type: QuestionComment

http://stackoverflow.com/comment/91844304
has text: @Kiran No worries. Glad I could help. If you gave more information on your actual image, I'd be able to write some code for you that demonstrates how to do it... but of course if you want to discover that yourself, you're definitely more than welcome to do so. Good luck!
type: AnswerComment
comment on: http://stackoverflow.com/a/52450294
score: 0
type: Comment

http://stackoverflow.com/comment/91951303
has text: @Jean-FrançoisFabre nope, it checks the entire thing for doubles and then tests the results, are you saying a better design would stop as soon as a double is encountered, if so I agree that would save resources
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52504433
type: Comment

http://stackoverflow.com/q/52509276
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/52509860
accepted answer: http://stackoverflow.com/a/52509378
tagged with: python
favorite count: 0
has title: Django error __init__() takes 1 positional argument but 2 were given
tagged with: django
type: AnsweredQuestion
has body: I'm currently making a simple get/post api with django 2.1. After i run the server and go to the .../article/ url it return an error init() takes 1 positional argument but 2 were given TRACE BACK: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/article/ Django Version: 2.1 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', 'api.apps.ApiConfig'] 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 "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in dispatch 483. response = self.handle_exception(exc) File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in…
type: Question
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/52509378
upvote count: 5
downvote count: 0
possible better answer: http://stackoverflow.com/a/52509860
has comment: http://stackoverflow.com/comment/91958707

http://stackoverflow.com/comment/91932683
score: 0
has text: @СтаниславКитаев I am looking into it, just posted this as a baseline solution...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52495982

http://stackoverflow.com/comment/92034020
has text: Thank you so much for your explanation! really appreciate it :)
type: Comment
comment on: http://stackoverflow.com/a/52547198
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92087661
score: 0
comment on: http://stackoverflow.com/a/52576084
type: Comment
has text: @Neb I mean if the user inputs like for example a space or a tab, that's still allowed
type: AnswerComment

http://stackoverflow.com/q/52433274
answer count: 1
tagged with: python
has body: I am trying to create a beginner level program to better understand programming in python. A simple while true loop that adds a value of 1 to X and prints "help" or "doing something" depending on if x is less than or greater than 10; and then breaks when x is greater than 20. Im also attempting to add in a keyboard interrupt as well to break the loop if its not too complicated.. Any tips help, I get an error Traceback (most recent call last): File "so.py", line 23, in &lt;module&gt; help() File "so.py", line 11, in help x += 1 UnboundLocalError: local variable 'x' referenced before assignment Code: import time x = 1 try: def help(): print("Help.") time.sleep(2) x += 1 def doStuff(): print("Doing Stuff") time.sleep(2) x += 1 while True: if x &lt; 10: help() elif x &lt; 20 and x &gt; 10: doStuff() else: break except KeyboardInterrupt: exit()
type: UnansweredQuestion
has title: UnboundLocalError: local variable 'x'
tagged with: loops
linked to: http://stackoverflow.com/q/423379
type: Question
has answer: http://stackoverflow.com/a/52433379
duplicate of: http://stackoverflow.com/q/423379
score: 0

http://stackoverflow.com/comment/91997784
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52529179
type: Comment
has text: @StephenRauch sorry for confusion, which are in code.

http://stackoverflow.com/q/52484087
score: 15
has comment: http://stackoverflow.com/comment/92033558
answer count: 3
tagged with: python-asyncio
has body: I am experiencing a long (3-hour) delay (EDIT: the delay is brief at first and then gets longer throughout the day) in processing data pushed from a websocket server to my client.py. I know that it is not delayed by the server. For example every 5 seconds I see the keep_alive log-event and its respective timestamp. So that runs smoothly. But when I see a data frame processed in logs is actually 3 hours after when the server sent it. Am I doing something to delay this process? Am I calling my coroutine 'keep_alive' correctly? keep_alive is just a message to the server to keep the connection alive. The server echos the message back. Also am I logging too much? Could that be delaying the processing (I don't think so since I'm seeing the logging events occur right away). async def keep_alive(websocket): """ This only needs to happen every 30 minutes. I currently have it set to every 5 seconds. """ await websocket.send('Hello') await asyncio.sleep(5) async def open_connection_test(): """ Establishes web socket (WSS). Receives data and then stores in csv. """ async with websockets.connect( 'wss://{}:{}@localhost.urlname.com/ws'.format(user,pswd), ssl=True, ) as websocket: while True: """ Handle message from server. """ message = await websocket.recv() if message.isdigit(): # now = datetime.datetime.now() rotating_logger.info ('Keep alive message: {}'.format(str(message))) else: jasonified_message = json.loads(message) for key in jasonified_message: rotating_logger.info ('{}: \n\t{}\n'.format(key,jasonified_message[key])) """ Store in a csv file. """ try: convert_and_store(jasonified_message) except PermissionError: convert_and_store(jasonified_message, divert = True) """ Keep connection alive. """ await keep_alive(websocket) """ Logs any exceptions in logs file. """ try: asyncio.get_event_loop().run_until_complete(open_connection()) except Exception as e: rotating_logger.info (e) EDIT: From the documentation - I'm thinking that this might have something to do with it - bu…
has comment: http://stackoverflow.com/comment/91998542
tagged with: python
has answer: http://stackoverflow.com/a/52576784
linked to: http://stackoverflow.com/q/52708756
has comment: http://stackoverflow.com/comment/92058175
accepted answer: http://stackoverflow.com/a/52573379
favorite count: 0
tagged with: python-3.x
has title: Long delay in using asyncio and websockets in Python 3
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52608090
type: Question
upvote count: 15
possible better answer: http://stackoverflow.com/a/52608090
has answer: http://stackoverflow.com/a/52573379
has comment: http://stackoverflow.com/comment/92016217
downvote count: 0
tagged with: websocket

http://stackoverflow.com/comment/92080827
has text: @Aran-Fey any language is good to go, I want to learn how it is done in both languages
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52572169

http://stackoverflow.com/comment/92105249
type: Comment
has text: @Neil - then is necessary convert it to strings by `.astype(str)`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52584960

http://stackoverflow.com/comment/91872188
type: Comment
type: AnswerComment
has text: Nevermind it was my fault, I didn't indent correctly! Thanks again!
comment on: http://stackoverflow.com/a/52463148
score: 0

http://stackoverflow.com/a/52453247
downvote count: 0
answers question: http://stackoverflow.com/q/52435589
accepted answer of: http://stackoverflow.com/q/52435589
score: 5
type: AcceptedAnswer
has body: Your code example seems to have bigger problems than form. You get your desired output only with luck. Repeated execution will yield different results. That's because += is not an atomic operation. Multiple processes can read the same old value one after another, before any of them has updated it and they will write back the same values. To prevent this behaviour, you'll have to use a Manager.Lock additionally. To your original question about "good form". IMO it would be cleaner, to let the main-function of the child process foo_parallel, pass global_dict explicitly into a generic function add(var). That would be a form of dependency injection and has some advantages. In your example non-exhaustively: allows isolated testing increases code reusability easier debugging (detecting non-accessibility of the managed object shouldn't be delayed until addis called (fail fast) less boilerplate code (for example try-excepts blocks on resources multiple functions need) As a side note. Using list comprehensions only for it's side effects is considered a 'code smell'. If you don't need a list as result, just use a for-loop. Code: import os from multiprocessing import Process, Manager def add(l): l += [l[-1] + 1] return l def foo_parallel(global_dict, lock): with lock: l = global_dict['a'] global_dict['a'] = add(l) print(os.getpid(), global_dict) if __name__ == '__main__': N_WORKERS = 5 with Manager() as manager: lock = manager.Lock() global_dict = manager.dict(a=[0]) pool = [Process(target=foo_parallel, args=(global_dict, lock)) for _ in range(N_WORKERS)] for p in pool: p.start() for p in pool: p.join() print('result', global_dict)
has comment: http://stackoverflow.com/comment/128479779
has comment: http://stackoverflow.com/comment/128490062
upvote count: 5
has comment: http://stackoverflow.com/comment/128478838
type: Answer
has comment: http://stackoverflow.com/comment/128478864

http://stackoverflow.com/q/52582730
has body: I need to read this .xlsm database and some of the cells values I need are derived from Excel functions. To accomplish this I used: from openpyxl import load_workbook wb = load_workbook('file.xlsm', data_only=True, keep_vba=True) ws = wb['Plan1'] And then, for every cell I wanted to read: ws.cell(row=row, column=column).value This works fine for getting the data out. But the problem comes with saving. When I do: wb.save('file.xlsm') It saves the file, but all the formulas inside the sheets are lost My dilemma is reading the cell's displayed values on one of the database's sheet without modifying them, writing the code's output in a new sheet and saving it.
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52586478
tagged with: python
tagged with: python-3.x
tagged with: openpyxl
tagged with: excel
type: AnsweredQuestion
has title: Reading cell value without redefining it with Openpyxl
accepted answer: http://stackoverflow.com/a/52586478

http://stackoverflow.com/q/52516757
answer count: 2
score: 0
linked to: http://stackoverflow.com/q/15335753
favorite count: 0
has comment: http://stackoverflow.com/comment/91973037
type: UnansweredQuestion
tagged with: nmap
has comment: http://stackoverflow.com/comment/91974445
has answer: http://stackoverflow.com/a/55014980
upvote count: 1
tagged with: python
has body: Not sure what I'm missing. I'm trying to import the nmap module and use the nmap.PortScanner(). I am using Linux. When I go to run the program in the terminal I get: File "/usr/local/lib/python2.7/dist-packages/nmap/nmap.py", line 137, in __init__ raise PortScannerError('nmap program was not found in path') nmap.nmap.PortScannerError: 'nmap program was not found in path' When I run: which nmap I get: /usr/bin/nmap When I execute nmap --version I get: Nmap version 7.60 ( https://nmap.org ) Platform: x86_64-pc-linux-gnu Compiled with: liblua-5.3.3 openssl-1.1.0g nmap-libssh2-1.8.0 libz-1.2.8 libpcre-8.39 libpcap-1.8.1 nmap-libdnet-1.12 ipv6 Compiled without: Available nsock engines: epoll poll select
downvote count: 1
has title: nmap PortScannerError, can't find nmap
has comment: http://stackoverflow.com/comment/91974349
has answer: http://stackoverflow.com/a/53427272
type: Question

http://stackoverflow.com/comment/109353718
has text: You can try code above with -u param on python: %runrealcmd python -u build_database.py. Moreover you should put Kamil Niski's runrealcmd code to .ipython\profile_default\startup\runcmd.py so it automatically load custom magic
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52576723

http://stackoverflow.com/comment/91973493
type: Comment
score: 1
has text: @CheyRav90 - I hope I understand it well, please check edited answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/52513947

http://stackoverflow.com/comment/92163748
type: Comment
type: QuestionComment
has text: @siberiancrane I got it working the same day. Thanks for your last suggestion. It helped!
comment on: http://stackoverflow.com/q/52579010
score: 0

http://stackoverflow.com/q/52496390
has comment: http://stackoverflow.com/comment/91933922
has comment: http://stackoverflow.com/comment/91933985
has title: What is the fastest way to make sure a str is a int?
has comment: http://stackoverflow.com/comment/91933805
has comment: http://stackoverflow.com/comment/91934567
has comment: http://stackoverflow.com/comment/91933538
has comment: http://stackoverflow.com/comment/91933879
has answer: http://stackoverflow.com/a/52496877
has comment: http://stackoverflow.com/comment/91933790
has body: I'm trying to make sure a string is a int in Python 3.6, here is four ways. But I don't know which one is the fastest, or could someone give me a faster one? import re input_value = '012345678901' def test1(value_str): value_str = value_str.lstrip('0') try: value_int = int(value_str) except ValueError: return False return len(str(value_int)) == len(value_str) def test2(value_str): return re.match('\d+$', value_str) is not None def test3(value_str): num_set = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} for i in value_str: if i not in num_set: return False return True def test4(value_str): return value_str.isdigit() I tested them with timeit, here is the result: run 1000000 times test1: 0.920672991022002 run 1000000 times test2: 1.1261013330076821 run 1000000 times test3: 0.8881843989947811 run 1000000 times test4: 0.16987622604938224 Edit notes: After testing many times, I know this: for unsigned number, test4 is the fastest. for signed number, if it includes'-'or'+' like '-123', test2 is always slow, others depends on how to remove the sign. I'm still not sure. And the lstrip('0') in test1 is just for this
has comment: http://stackoverflow.com/comment/91933639
has comment: http://stackoverflow.com/comment/91935122
has comment: http://stackoverflow.com/comment/91933997
type: Question
has comment: http://stackoverflow.com/comment/91934747
has comment: http://stackoverflow.com/comment/91934771
has answer: http://stackoverflow.com/a/52497624
score: 0
has comment: http://stackoverflow.com/comment/91933949
has comment: http://stackoverflow.com/comment/91934881
answer count: 3
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91933752
has answer: http://stackoverflow.com/a/52498764
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91934136
has comment: http://stackoverflow.com/comment/91935007
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91933924
has comment: http://stackoverflow.com/comment/91934378
tagged with: python

http://stackoverflow.com/comment/92064493
score: 0
type: Comment
has text: @user9023836, I'm happy if it helped. You can accept the answer by turning the check mark green or upvote. :D
type: AnswerComment
comment on: http://stackoverflow.com/a/52508030

http://stackoverflow.com/comment/91957812
has text: @chepner to be honest, it's because my company want me to do so..to keep users from reaching the source code SO directly, althrough we all know it doesn't help
comment on: http://stackoverflow.com/q/52502061
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91823995
type: Comment
type: QuestionComment
has text: Use regular expressions
score: 0
comment on: http://stackoverflow.com/q/52440321

http://stackoverflow.com/comment/91826370
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52440712
has text: is it odoo 8 or 9?

http://stackoverflow.com/q/52439021
tagged with: multithreading
upvote count: 1
has body: this code works in idle3 but in a console(MAC, Windows Linux) thread2 is instantly closing if set to daemon. Is there any explanation for that ? Maybe also a workaround to properly have a daemon thread asking for user input ? import queue import threading import sys def worker(q): _text = '' while _text == '': _text = q.get() print('[worker]input was ',_text) sys.exit() def dialog(q): while True: try: _select = input('[dialog]enter text:') if _select != '': q.put(_select) except EOFError: pass except KeyboardInterrupt: print("bye") sys.exit(0) except Exception as e: print(e) sys.exit(1) if 'esc'.lower() in _select.lower(): sys.exit() q = queue.Queue() thread1 = threading.Thread(target=worker,args=(q,)) thread2 = threading.Thread(target=dialog,args=(q,)) thread1.setDaemon(True) thread2.setDaemon(True) print('start asking') thread1.start() thread2.start() thanks for any hint on the issue
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52439457
score: 1
type: Question
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0
has title: Why is Python3 daemon thread instantly closing in console?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52439457

http://stackoverflow.com/q/52508044
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52508145
tagged with: web-scraping
has title: Python Web-scraping charmap issue, works fine in IDLE not in ATOM IDE? why?
tagged with: urllib
type: Question
has body: While doing simple url read request from python. I have encountered the follow issue in my Atom IDE, while doing in idle I didn't receive the error, what may be the reason for it. Below is the code. from urllib.request import urlopen html = urlopen("https://morvanzhou.github.io/static/scraping/basic-structure.html").read().decode('utf-8') print(html) Below is the error:
answer count: 1
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: utf-8

http://stackoverflow.com/comment/91880700
has text: They are on the same machine and the client program is inside the same folder as the file whereas the server is on another.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52469037
score: 0

http://stackoverflow.com/comment/91989311
score: 1
comment on: http://stackoverflow.com/q/52524343
has text: The server needs to do all communications via the client socket returned by `.accept()`, not the original server socket.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52517008
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52513365
upvote count: 1
has body: OK this began as a comment but it was too big to be useful. First of all by your definition there isn't a unique combination. Let me explain: Since, you don't want to repeat any 2 numbers that have already appeared in a triplet the order by which they appear matters and change the combination. An example to make it clear: Given you start with: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] one possible sequence (different than yours) could be: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] [[1, 5, 10], [4, 8, 12], [7, 11, 15], [9, 14, 3],[ 2, 6, 13]] (simply swap 9 for 10 in your second combination). This though makes 1 and 5 unusable again in the same triplet so in that sequence your second combination [[1, 5, 9], [4, 8, 12], [7, 11, 15], [10, 14, 3],[2, 6, 13]] cannot appear in my sequence. So, how do you define unique? There is a problem in your definition I think. I am not even sure that the order makes any difference in the length of the sequence. check if this triplet has not been used before If you are not interested in a unique sequence but rather your want your limitation to apply to a sequence and get as many combinations as possible then the above won't work. You should check if 2 numbers are contained in a triplet not if a triplet has appeared before. Your criterion will fail to identify that the combination [[1, 5, 9], [4, 7, 13], [8, 11, 15], [10, 14, 3], [2, 6, 12]] is unacceptable although all triplets haven't appear before. Hope this helps. Anyway, If I misunderstood something make an edit.
type: Answer
has comment: http://stackoverflow.com/comment/91976109

http://stackoverflow.com/comment/92089009
type: AnswerComment
type: Comment
has text: Just to be clear Your code as well as my revised code just Highlight the First column (after index col) in the DataFrame.. Thanks.
comment on: http://stackoverflow.com/a/52529813
score: 0

http://stackoverflow.com/q/52529669
has answer: http://stackoverflow.com/a/52529742
has body: if all(data_Window['CI']!=np.nan): I have used the all() function with if so that if column CI has no NA values, then it will do some operation. But i got syntax error.
accepted answer: http://stackoverflow.com/a/52529739
type: AnsweredQuestion
type: Question
tagged with: pandas
tagged with: python
has title: how can i check all the values of dataframe whether have null values in them without a loop
score: 0
has answer: http://stackoverflow.com/a/52529739
answer count: 3
possible better answer: http://stackoverflow.com/a/52529742
has answer: http://stackoverflow.com/a/52529791

http://stackoverflow.com/q/52503963
type: Question
duplicate of: http://stackoverflow.com/q/26640129
downvote count: 0
has title: What is the most efficient way to regex search an entire Pandas Dataframe?
has comment: http://stackoverflow.com/comment/91948561
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91949343
has comment: http://stackoverflow.com/comment/91949289
answer count: 0
type: UnansweredQuestion
has body: I need to count the number of occurrences of a regex pattern in an entire dataframe. Is the following the most efficient method? df = df.applymap(str) count = 0 for col in df: count = count + df[col].str.contains(regex_search, case=False).sum() print('Count: ', count)
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91949323
score: 1
linked to: http://stackoverflow.com/q/26640129

http://stackoverflow.com/comment/91924758
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52491953
has text: Are multiple matches a possibility? What should happen in such a case?
score: 0

http://stackoverflow.com/q/52584730
upvote count: 2
type: UnansweredQuestion
has title: Wrong spacy similarity result
tagged with: python
has comment: http://stackoverflow.com/comment/92300865
type: Question
has answer: http://stackoverflow.com/a/52709532
score: 2
answer count: 1
downvote count: 0
has body: I just install spacy package in python with MacBook, and start to learn spacy similarity function; however, I observed wrong results. Input: import spacy nlp = spacy.load('en_core_web_sm') tokens = nlp(u'dog cat banana') for token1 in tokens: for token2 in tokens: print(token1.text, token2.text, token1.similarity(token2)) Output: dog dog 1.0 dog cat -1.8432091e-22 dog banana -0.00349403 cat dog -1.8432091e-22 cat cat 1.0 cat banana -1.8395509e-22 banana dog -0.00349403 banana cat -1.8395509e-22 banana banana 1.0 I did similar things on window10 PC, the result makes sense. I don't know what wrong with MacBook settings. I tried with en_core_web_md model, it still has the same problem.
linked to: http://stackoverflow.com/q/52388291
favorite count: 0
tagged with: spacy

http://stackoverflow.com/a/52589121
score: 0
has comment: http://stackoverflow.com/comment/92114234
has body: What you are complaining about is a shell issue. The shell applies its convention of single quotes to parse arguments. Actually I find the PyCharm behaviour as understandable and consistent; if no shell is involved, nobody does the job you expect. If you insist on running that from pycharm, I'd suggest another passing method (e.g. via file) or to apply some unquoting mechanism as urllib.parse.unquote. See also here for a dated but still correct description of command line parameters in general, and specifically: The ANSI C standard does not specify what constitutes a command-line argument, because operatring systems vary considerably on this point. However, the most common convention is as follows: Each command-line argument must be separated by a space or a tab character. Commas, semicolons, and the like are not considered separators.
type: Answer
answers question: http://stackoverflow.com/q/52588535

http://stackoverflow.com/comment/92078616
type: Comment
comment on: http://stackoverflow.com/a/52569640
score: 1
has text: If you can make an HTTP/REST/SOAP request to an online application to get the info you need on one particular item, you could make a python script which iterates over every data piece you have, sending it to that endpoint. I don't know about your particular problem, but they are web applications, it is likely they work by accepting some POST or GET request. Just make it from python while iterating over your dataset, and store the results. If you have more info on the applications you talk about, we may help more.
type: AnswerComment

http://stackoverflow.com/a/53550195
answers question: http://stackoverflow.com/q/52433957
score: 0
has body: What worked for me was writing a module to do some "pre-processing" of the CSV file as follows. The key line is where the "writer" has the parameter "quoting=csv.QUOTE_ALL". Hopefully this is useful to others. def work(Source_CSV): from __main__ import * import csv, arcpy, os # Derive name and location for newly-formatted .csv file Head = os.path.split(Source_CSV)[0] Tail = os.path.split(Source_CSV)[1] name = Tail[:-4] new_folder = "formatted" new_path = os.path.join(Head,new_folder) Formatted_CSV = os.path.join(new_path,name+"_formatted.csv") #arcpy.AddMessage("Formatted_CSV = "+Formatted_CSV) # Populate the new .csv file with quotation marks around all field contents ("quoting=csv.QUOTE_ALL") with open(Source_CSV, 'rb') as file1, open(Formatted_CSV,'wb') as file2: # Instantiate the .csv reader reader = csv.reader(file1, skipinitialspace=True) # Write column headers without quotes headers = reader.next() # 'next' function actually begins at the first row of the .csv. str1 = ''.join(headers) writer = csv.writer(file2) writer.writerow(headers) # Write all other rows wrapped in double quotes writer = csv.writer(file2, delimiter=',', quoting=csv.QUOTE_ALL) # Write all other rows, at first quoting none... #writer = csv.writer(file2, quoting=csv.QUOTE_NONE,quotechar='\x01') for row in reader: # ...then manually doubling double quotes and wrapping 3rd column in double quotes. #row[2] = '"' + row[2].replace('"','""') + '"' writer.writerow(row) return Formatted_CSV
type: Answer

http://stackoverflow.com/a/52504865
accepted answer of: http://stackoverflow.com/q/52504640
score: 1
upvote count: 1
has body: Use apply and replace the string with seller name Sample df import pandas as pd df=pd.DataFrame({'seller_name':['Lucas'],'url':['http://sanyo.mapi/s3/e42390aac371?item_title=Branded%20boys%20Clothing&amp;seller_name=102392852&amp;buyer_item=106822419_1056424990']}) import re def myfunc(row): return(re.sub('(seller_name=\d{1,})','seller_name='+row.seller_name,row.url)) df['url']=df.apply(lambda x: myfunc(x),axis=1)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52504640
type: Answer

http://stackoverflow.com/comment/91916987
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52486840
score: 0
has text: @DanMašek I've added an example of what the function might look like, could you provide an example of what the vecorised pattern would look like? By access pattern do you mean like a 1D array?

http://stackoverflow.com/q/52451132
has title: How to remove duplicate value among columns irresppective of their order in python or pyspark?
tagged with: pyspark
has answer: http://stackoverflow.com/a/52451326
has body: I have a dataframe in which i have duplicate value among columns. I want to remove only those values from the dataframe that are common for all the columns INPUT DATAFRAME: +----------+-----------+------------+ | A | B | C | +----------+-----------+------------+ | Food | Chill | Traveller | +----------+-----------+------------+ | Chill | Food | Chill | +----------+-----------+------------+ | Traveller| Glamour | Glamour | +----------+-----------+------------+ | Novel | Traveller | Party | +----------+-----------+------------+ | Pub | Party | Driving | +----------+-----------+------------+ OUTPUT DATAFRAME: +----------+-----------+------------+ | A | B | C | +----------+-----------+------------+ | Food | Party | Driving | +----------+-----------+------------+ | Novel | Food | Party | +----------+-----------+------------+ | Pub | Glamour | Glamour | +----------+-----------+------------+ Is there any effective way to do this in python or pyspark?
type: Question
answer count: 2
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/52451427
tagged with: pandas
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91845680
has comment: http://stackoverflow.com/comment/91845682

http://stackoverflow.com/a/52496419
accepted answer of: http://stackoverflow.com/q/52496374
has comment: http://stackoverflow.com/comment/91933384
type: AcceptedAnswer
downvote count: 0
has body: You can use the python module glob (https://docs.python.org/3/library/glob.html) Specifically, glob.glob('folder1/folder2/*.pkl') will return a list of all .pkl files in folder2.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52496374
score: 2

http://stackoverflow.com/q/52534972
linked to: http://stackoverflow.com/q/28092394
favorite count: 0
has answer: http://stackoverflow.com/a/52535582
has title: Getting indices of specific elements from python list
answer count: 5
has answer: http://stackoverflow.com/a/52535668
has comment: http://stackoverflow.com/comment/92011251
possible better answer: http://stackoverflow.com/a/52535354
tagged with: python
has comment: http://stackoverflow.com/comment/92009220
has answer: http://stackoverflow.com/a/52535421
tagged with: indexing
type: AnsweredQuestion
tagged with: list
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92010681
type: Question
has comment: http://stackoverflow.com/comment/92009187
tagged with: find
has body: I have a list with small and big numbers like this: [234, 454, 123444, 123, 234, 122234, 234, 354, 654, 123231, 234, 342, 1231231] The "big numbers" are at least 10 times bigger than the smaller numbers. In total, there are 4 "big numbers" in the list: 123444, 122234, 123231 and 1231231. I want to find the indices of the 3rd and 4th "big numbers": values: 234 454 123444 123 234 122234 234 354 654 123231 234 342 1231231 indices: 0 1 2 3 4 5 6 7 8 9 10 11 12 As you can see, the 3rd "big number" has the index 9, and the 4th "big number" has the index 12. Therefore the output should be 9 and 12.
tagged with: arrays
has answer: http://stackoverflow.com/a/52535354
has comment: http://stackoverflow.com/comment/92011037
linked to: http://stackoverflow.com/q/20044096
has answer: http://stackoverflow.com/a/52535124
upvote count: 2
accepted answer: http://stackoverflow.com/a/52535668
linked to: http://stackoverflow.com/q/20618804

audio-analysis
type: Tag
tag name: audio-analysis
tags question: http://stackoverflow.com/q/52461914

http://stackoverflow.com/comment/91859201
comment on: http://stackoverflow.com/q/52458508
type: Comment
type: QuestionComment
has text: what is your CUDA version? How many GPU do you have ?
score: 0

http://stackoverflow.com/comment/92051047
score: 0
type: Comment
type: QuestionComment
has text: Indeed, 10 per min seems to be a pretty benign rate and since it's working from the shell a banning seems unlikely... on the other hand: you never know.
comment on: http://stackoverflow.com/q/52555653

http://stackoverflow.com/q/52546212
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/51705452
has comment: http://stackoverflow.com/comment/92532510
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/92532405
has comment: http://stackoverflow.com/comment/92032195
has title: "TypeError: Start() missing 1 required positional argument: 'self'"
type: Question
downvote count: 0
has body: I do not understand what "TypeError: Start() missing 1 required positional argument: 'self'" means. I require clarification about what this error message refers to and what is required to fix it. While this other Stack Overflow question answers about the "need to instantiate the Application object and call start on that, not on the class", I have absolutely no clue what this explanation implies using as simplest of language possible. What kind of code fixing is specifically required to fix this kind of error? The program that I am making also has this kind of error, but I don't know where exactly in my program is making this error; when I press my custom-made record button, it shows the following error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) TypeError: Start() missing 1 required positional argument: 'self' Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) TypeError: Start() missing 1 required positional argument: 'self' My program does not have 1699 lines; it only has about 128 lines. Here is my entire program, with the approximately 128 lines to show you it does indeed not have 1699 lines as well as to show you my program that contained this confusing error: import tkinter as tk from tkinter import PhotoImage import time class TimeCheck(): def __init__(self, parent=None, **kw): self._start = 0.0 self._elapsedtime = 0.0 self._running = 0 def trianglemove(move_x, move_y): canvas.move (triangle3, move_x, move_y) def _update(self): self._elapsedtime = time.time() - self._start self._setTime(self._elapsedtime) self._timer = self.after(50, self._update) def _setTime(self, elap): """ Set the time string to Minutes:Seconds:Hundreths """ minutes = int(elap/60) seconds = int(elap - minutes*60.0) hseconds = int(…
has comment: http://stackoverflow.com/comment/92032212
has comment: http://stackoverflow.com/comment/92032298
has answer: http://stackoverflow.com/a/52546288
answer count: 1
has comment: http://stackoverflow.com/comment/92033148
favorite count: 0
tagged with: python-3.x
tagged with: tkinter

http://stackoverflow.com/q/52545943
tagged with: stripe-payments
tagged with: parsing
tagged with: python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has title: Parsing Stripe data from webhook event invoice.payment_succeeded
has answer: http://stackoverflow.com/a/52546187
accepted answer: http://stackoverflow.com/a/52546187
type: Question
score: 0
has body: I'm catching a webhook from Stripe for invoices that succeed which provides me with this amount: 7500 currency: usd description: None discountable: True id: sub_DfLYbarfoo livemode: True metadata: {} object: line_item period: {u'start': 1537694450, u'end': 1569930450} plan: {u'active': True, u'product': u'prod_Bzxbarfoo', u'transform_usage': None, u'name': u'Agent - Yearly', u'aggregate_usage': None, u'created': 1513986904, u'tiers_mode': None, u'interval': u'year', u'tiers': None, u'object': u'plan', u'id': u'ra-yearly', u'currency': u'usd', u'amount': 7500, u'interval_count': 1, u'trial_period_days': 2, u'livemode': True, u'usage_type': u'licensed', u'metadata': {u'qb_product': u'71'}, u'nickname': u'Agent - Yearly', u'statement_descriptor': u'foobar.com/charge', u'billing_scheme': u'per_unit'} proration: False quantity: 1 subscription: None subscription_item: si_DfLYfoo type: subscription I want to extract the data from 'plan' and parse it for use in a Zapier process. I've narrowed down the exact data I need using the following code data = input['data'] begin_index = data.find('plan:') + 6 end_index = data.rfind('}') + 1 plan = data[begin_index:end_index] which provides me with {u'active': True, u'product': u'prod_Bzxbarfoo', u'transform_usage': None, u'name': u'Agent - Yearly', u'aggregate_usage': None, u'created': 1513986904, u'tiers_mode': None, u'interval': u'year', u'tiers': None, u'object': u'plan', u'id': u'ra-yearly', u'currency': u'usd', u'amount': 7500, u'interval_count': 1, u'trial_period_days': 2, u'livemode': True, u'usage_type': u'licensed', u'metadata': {u'qb_product': u'71'}, u'nickname': u'Agent - Yearly', u'statement_descriptor': u'foobar.com/charge', u'billing_scheme': u'per_unit'} I'm not sure what the leading 'u' characters is doing on each key and value, but it is preventing me from parsing this into usable json.
answer count: 1
tagged with: zapier

http://stackoverflow.com/comment/91831687
score: 1
has text: To get you started: https://stackoverflow.com/questions/3422262/take-a-screenshot-with-selenium-webdriver
comment on: http://stackoverflow.com/q/52443426
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52498778
has body: Answering my own question because I did not find an easy solution on StackOverflow: def apply_custom_colormap(image_gray, cmap=plt.get_cmap('seismic')): assert image_gray.dtype == np.uint8, 'must be np.uint8 image' if image_gray.ndim == 3: image_gray = image_gray.squeeze(-1) # Initialize the matplotlib color map sm = plt.cm.ScalarMappable(cmap=cmap) # Obtain linear color range color_range = sm.to_rgba(np.linspace(0, 1, 256))[:,0:3] # color range RGBA =&gt; RGB color_range = (color_range*255.0).astype(np.uint8) # [0,1] =&gt; [0,255] color_range = np.squeeze(np.dstack([color_range[:,2], color_range[:,1], color_range[:,0]]), 0) # RGB =&gt; BGR # Apply colormap for each channel individually channels = [cv2.LUT(image_gray, color_range[:,i]) for i in range(3)] return np.dstack(channels) image_gray = cv2.imread('./lena.jpg', cv2.IMREAD_GRAYSCALE) image_bgr = apply_custom_colormap(image_gray, cmap=plt.get_cmap('bwr')) cv2.imshow('image with colormap', image_bgr) cv2.waitKey(0) Produces the image:
score: 6
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52498777
answers question: http://stackoverflow.com/q/52498777
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92073051
comment on: http://stackoverflow.com/q/52566728
type: Comment
score: 0
has text: Show us your full view class
type: QuestionComment

http://stackoverflow.com/comment/91976268
comment on: http://stackoverflow.com/q/52518305
has text: Updated the post with my INSTALLED_APPS
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52527544
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52527703
tagged with: python
tagged with: recursion
upvote count: 3
score: 0
downvote count: 3
has answer: http://stackoverflow.com/a/52529326
has body: How would I approximate the following equation using recursion? Here is an iterative approach: def calculateFrac(num): result = 0 for i in range(num): if i % 2 == 0: result = result + 1 / (2 * i + 1) else: result = result - 1 / (2 * i + 1) print(4 * result) print(calculateFrac(10))
type: Question
has comment: http://stackoverflow.com/comment/91994975
has title: Approximate this equation using recursion 4 * (1 - (1 /3 ) + (1 / 5) - (1 / 7) + (1 / 9) - (1 / 11) ... )
has answer: http://stackoverflow.com/a/52527664
answer count: 3
has comment: http://stackoverflow.com/comment/91994949
linked to: http://stackoverflow.com/q/33923
has comment: http://stackoverflow.com/comment/91994800
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/92537011
comment on: http://stackoverflow.com/q/52517466
type: QuestionComment
type: Comment
has text: Change the amplitude (height) and frequency (more ripples) of the oscillation function.
score: 0

http://stackoverflow.com/q/52453037
has comment: http://stackoverflow.com/comment/91849247
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91849672
has comment: http://stackoverflow.com/comment/91849261
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91853818
has comment: http://stackoverflow.com/comment/91850104
has title: convert python 2 to python 3: read image file
has comment: http://stackoverflow.com/comment/91850042
type: Question
has comment: http://stackoverflow.com/comment/91850075
tagged with: database
has answer: http://stackoverflow.com/a/52470959
score: 0
has body: In python 2, I use: import MySQLdb pathFileName = "/Users/ldam/Documents/test.png" f = open(pathFileName, 'r') img = f.read() f.close() conn = MySQLdb.connect(host='localhost', user='user', passwd='password', db='db') cursor = conn.cursor() inssql = "INSERT Data_images(data) VALUES('%s')" cursor.execute(inssql % MySQLdb.escape_string(img)) cursor.close() conn.close() Arcoding to the comments under, in python 3 I read file as bytes: f = open(pathFileName, 'rb') img = f.read() f.close() conn = MySQLdb.connect(host='localhost', user='user', passwd='password', db='db') cursor = conn.cursor() inssql = "INSERT Data_images(data) VALUES('%s')" cursor.execute(inssql % MySQLdb.escape_string(img)) cursor.close() conn.close() However, I have tried many way to insert the img data into table database but none of them work. Can anyone help me to save the img data into database. Thanks a lot.
answer count: 1
has comment: http://stackoverflow.com/comment/91849310

http://stackoverflow.com/q/52533615
has body: Am trying to create a CCBlade effects like that of fruit Ninja for my game and so am trying to clear the tail of the canvas to look like that of fruit ninja blade but i have no idea how to do it. Here is the code from random import random from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Color, Line class Blade(Widget): def on_touch_down(self, touch): color = (random(), 1, 1) with self.canvas: Color(*color, mode='hsv') touch.ud['line'] = Line(points=(touch.x, touch.y), pointsize=5) def on_touch_up(self, *touch): self.canvas.clear() def on_touch_move(self, touch): touch.ud['line'].points += [touch.x, touch.y] self.clearTail(touch) def clearTail(self, touch): #How can i clear the tail of the canvas as i move my finger #so that the line looks like it continuesly follows my finger #I want the lenght of the line to be about 5cm or a bit long #And no matter how long i move my finger #the line must follows it and must not exceed 5cm or a bit longer (maybe 7cm - 15cm) #AM TRYING TO ARCHIEVE CCBLADE EFFECT LIKE THAT OF FRUIT NINJA pass class BladeApp(App): def build(self): parent = Widget() self.bldEfx = Blade() parent.add_widget(self.bldEfx) return parent if __name__ == '__main__': BladeApp().run() How can i clear the tail of the canvas as i move my finger so that the line looks like it continuesly follows my finger. It should look like fruit ninja Blade effect. Is there any other way i can achieve fruit ninja blade effect on kivy.
tagged with: python
tagged with: kivy
tagged with: kivy-language
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52543373
has title: Kivy - fruit ninja Blade effect
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/52543373
type: Question

http://stackoverflow.com/comment/92068016
comment on: http://stackoverflow.com/a/52564839
score: 1
type: AnswerComment
type: Comment
has text: The latter is not the best approach actually .. you'll lose data

http://stackoverflow.com/q/52470712
tagged with: python
has body: I'm not really sure how to ask this, so I apologize if this is a repeat question. I have this data frame that looks something like this: | ID | Attend_x | Attend_y | Attend_z | | 1 | No | No | No | | 2 | No | No | Yes | | 3 | No | Yes | No | | 4 | No | Yes | Yes | I've been trying to figure out the right combination of group_by and count to get it to look like this: | | Yes | No | |Attend_x| 0 | 4 | |Attend_y| 2 | 2 | |Attend_z| 2 | 2 | I'm honestly stumped. So any advice is super appreciated. Thanks!
type: Question
has answer: http://stackoverflow.com/a/52470857
accepted answer: http://stackoverflow.com/a/52470857
type: AnsweredQuestion
has title: Group Value Count By Column with Pandas Dataframe
tagged with: dataframe
score: 0
answer count: 1
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/q/52433215
has comment: http://stackoverflow.com/comment/91810979
has body: I have a series of data with half hour intervals. I need to take a rolling 4 (whole) week average of Tuesday, Wednesday, and Thursday, for each half hour interval in the dataset. So the first 'window' would have averages for times 00:00:00, 00:30:00,...,23:00:00, 23:30:00 for weeks 1-4. Then the next window would have averages for weeks 2-5 etc. I have the following dataset, which has daily data, but only including Tuesday, Wednesday, and Thursday (for whatever reason other days are not used in calculating the averages). Furthermore, within those days, I have data in half hour intervals (but only including half hour time intervals of 00:00:00, 00:30:00, 01:00:00, and 01:30:00 in the sample). datetime timeblock speed 1/3/2017 0:00 0:00:00 81.186885 1/3/2017 0:30 0:30:00 NaN 1/3/2017 1:00 1:00:00 85.277724 1/3/2017 1:30 1:30:00 85.077176 1/4/2017 0:00 0:00:00 80.691608 1/4/2017 0:30 0:30:00 79.223225 1/4/2017 1:00 1:00:00 82.330169 1/4/2017 1:30 1:30:00 79.495578 1/5/2017 0:00 0:00:00 74.162426 1/5/2017 0:30 0:30:00 75.206492 1/5/2017 1:00 1:00:00 77.6484 1/5/2017 1:30 1:30:00 72.61875 1/10/2017 0:00 0:00:00 77.785555 1/10/2017 0:30 0:30:00 80.617395 1/10/2017 1:00 1:00:00 80.094947 1/10/2017 1:30 1:30:00 77.697473 1/11/2017 0:00 0:00:00 74.7104 1/11/2017 0:30 0:30:00 75.691326 1/11/2017 1:00 1:00:00 74.639803 1/11/2017 1:30 1:30:00 81.797268 1/12/2017 0:00 0:00:00 79.571042 1/12/2017 0:30 0:30:00 78.083612 1/12/2017 1:00 1:00:00 78.747287 1/12/2017 1:30 1:30:00 78.128129 1/17/2017 0:00 0:00:00 76.509323 1/17/2017 0:30 0:30:00 77.256 1/17/2017 1:00 1:00:00 78.627085 1/17/2017 1:30 1:30:00 81.588 1/18/2017 0:00 0:00:00 77.82543 1/18/2017 0:30 0:30:00 80.231272 1/18/2017 1:00 1:00:00 NaN 1/18/2017 1:30 1:30:00 74.656384 1/19/2017 0:00 0:00:00 77.37165 1/19/2017 0:30 0:30:00 80.328705 1/19/2017 1:00 1:00:00 80.011531 1/19/2017 1:30 1:30:00 79.643781 1/24/2017 0:00 0:00:00 81.167016 1/24/2017 0:30 0:30:00 NaN 1/24/2017 1:00 1:00:00 83.128695 1/24/2017 1:30 1:30:00 77.7994…
type: Question
upvote count: 2
has title: Pandas groupby and rolling 4 week window
answer count: 1
has comment: http://stackoverflow.com/comment/91831978
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52482141
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91840194
has comment: http://stackoverflow.com/comment/91881450
has comment: http://stackoverflow.com/comment/91881567
tagged with: python
score: 2
downvote count: 0

http://stackoverflow.com/comment/92144966
type: Comment
comment on: http://stackoverflow.com/a/52594737
has text: In all honesty, I copied a lot of code from another project because it had a lot of the stuff I need. Good thing to know that I can cut down on a lot of unused code with your help!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92043678
comment on: http://stackoverflow.com/a/52543548
has text: I mean I understand the solution, but in my case what will be the query: something like: collection.update({}, {$rename: {item["item"][key]: item["item"][new_item_id]}}, False, True)?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92001586
comment on: http://stackoverflow.com/a/52529387
type: Comment
score: 1
type: AnswerComment
has text: Yes it worked fine. It asked me for the inventories twice, and after I entered them the second time, it printed them and asked me to press enter to continue. I pressed enter and the program exited. Are you running the same code that you put on pastebin?

http://stackoverflow.com/a/55402301
type: Answer
answers question: http://stackoverflow.com/q/52455774
score: 1
upvote count: 1
has body: Making the following change to gtoken made it work for me: RE_TKK = re.compile(r'tkk:\'(.+?)\'') def __init__(self, tkk='0', session=None, host='translate.google.com'): self.session = session or requests.Session() self.tkk = tkk self.host = host if 'http' in host else 'https://' + host def _update(self): """update tkk """ # we don't need to update the base TKK value when it is still valid r = self.session.get(self.host) self.tkk = self.RE_TKK.findall(r.text)[0] now = math.floor(int(time.time() * 1000) / 3600000.0) if self.tkk and int(self.tkk.split('.')[0]) == now: return # this will be the same as python code after stripping out a reserved word 'var' code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') # unescape special ascii characters such like a \x3d(=) I obtained this snippet from the ticket here. Note that this is slightly different from other change suggested earlier by Kerem. For other uninitiated folks like me, gtoken.py can be found within AppData\Local\Continuum\anaconda3\site-packages\googletrans on a Windows machine using Anaconda. To find AppData, go into the address bar in file explorer, type '%AppData%', and hit Enter.
downvote count: 0

http://stackoverflow.com/a/52528152
upvote count: 2
has body: It looks like when you pass a list into loc or iloc on a dataframe, a dataframe will always be returned (notice that df['date'] == '20180924' is a list of booleans). type(df.loc[df['date'] == '20180924']) = pandas.core.frame.DataFrame type(df.loc[[0]]) = pandas.core.frame.DataFrame type(df.iloc[[0]]) = pandas.core.frame.DataFrame However, if you pass in an index (assuming your dataframe is not multiindexed) into loc or iloc on a dataframe, it will result in a Series: type(df.loc[0]) = pandas.core.series.Series type(df.iloc[0]) = pandas.core.series.Series df.loc[0] and df.iloc[0] are identical (though this is not always the case, see here why). This is the result: date 20180926 price 100 Name: 0, dtype: object Likewise, if you pass in an index into iloc on a Series, it will result in a scalar (i.e. a value is returned): type(df.iloc[0].iloc[0]) In this case you are picking the 0th positioned element in the series df.iloc[0], which is '20180926'. Notice that calling df.iloc[0].loc[0] is not valid as 0 is NOT an index in this series. The indexes in df.iloc[0] series are date and price.
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52527978

http://stackoverflow.com/comment/91860376
has text: It isn't clear to me what you are trying to do. What would be some example input with the corresponding expected output?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52459081

newline
tags question: http://stackoverflow.com/q/52486730
tag name: newline
type: Tag
tags question: http://stackoverflow.com/q/52445319
tags question: http://stackoverflow.com/q/52505583

http://stackoverflow.com/a/52517918
type: Answer
answers question: http://stackoverflow.com/q/52517432
has body: If I understand your prime problem, this is a simple solution. import random lists = [] for a in range(10): lists.append(random.randint(1, 10)) print "lists",sorted(lists)
score: 0

http://stackoverflow.com/q/52535142
favorite count: 0
type: Question
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/52535928
linked to: http://stackoverflow.com/q/45149614
answer count: 2
downvote count: 2
has body: I have a couple of files inside a folder called: output. The files are a.shp, a.dbf, a.shx, b.shp, b.dbf, b.shx, etc . How to make a folder 'exports' inside output and then inside 'exports', one called a and put automatically there a.shp, etc and so on for the other letter files? Example: from glob import glob folder = C:/Users/user/Desktop/programs/merge/output for i in glob(folder + '/*'): if ('a') in i: print(i) gives C:/Users/user/Desktop/programs/merge/output\a.dbf C:/Users/user/Desktop/programs/merge/output\a.shp C:/Users/user/Desktop/programs/merge/output\a.shx What I tried: from glob import glob folder = C:/Users/user/Desktop/programs/merge/output os.mkdir(folder +'/'+ 'exports' ) for i in glob(folder + '/*'): if ('a') in i: os.mkdir(folder +'/'+ 'exports' + '/' + i.split("\\")[-1]) # Creates a folder for each extension as well which is not needed. I want only by the name. # and somehow all these files have to be moved to these folders
has answer: http://stackoverflow.com/a/52535375
type: UnansweredQuestion
has title: Put files with certain name to a folder with its name
upvote count: 0

exception
tags question: http://stackoverflow.com/q/52507941
tags question: http://stackoverflow.com/q/52541181
tags question: http://stackoverflow.com/q/52475075
type: Tag
tags question: http://stackoverflow.com/q/52580105
tags question: http://stackoverflow.com/q/52471919
tags question: http://stackoverflow.com/q/52444076
tags question: http://stackoverflow.com/q/52529365
tag name: exception
tags question: http://stackoverflow.com/q/52509910
tags question: http://stackoverflow.com/q/52515470

environment
tags question: http://stackoverflow.com/q/52507974
type: Tag
tag name: environment
tags question: http://stackoverflow.com/q/52462994

http://stackoverflow.com/comment/91936987
type: Comment
has text: Do you open the php or python file ?
comment on: http://stackoverflow.com/q/52497320
score: 0
type: QuestionComment

http://stackoverflow.com/q/52448943
tagged with: http-status-code-404
tagged with: node.js
type: AnsweredQuestion
has title: Python Flask Node.js failed to load resources 404
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52449236
has comment: http://stackoverflow.com/comment/91841399
score: -1
has body: Hi I am trying to send data from node to python. I read this is possible via 2 server with express and Flask. However when I run the code I receive an error (see below) Python script from flask import Flask, request import json app = Flask(__name__) @app.route('/') def index(): return "Flask server" @app.route('/postdata', methods = ['POST']) def postdata(): data = request.get_json() print(data) # do something with this data variable that contains the data from the node server return json.dumps({"newdata":"hereisthenewdatayouwanttosend"}) if __name__ == "__main__": app.run(port=5000) The Node script var express = require('express'); var bodyParser = require('body-parser'); var request = require('request-promise'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/postdatatoFlask', async function (req, res) { var data = { data1: "foo", data2: "bar" } var options = { method: 'POST', uri: 'http://localhost:3000/postdata', body: data, json: true // Automatically stringifies the body to JSON }; var returndata; var sendrequest = await request(options) .then(function (parsedBody) { console.log(parsedBody); returndata = parsedBody; }) .catch(function (err) { console.log(err); }); res.send(returndata); }); app.listen(3000); However if I now try to execute the post request with http://localhost:3000/postdatatoFlask I get the 404 error PS C:\Users\danie\Desktop\nodepythonproject> node nodepython { StatusCodeError: 404 - "\n\n\n\nError\n\n\n Cannot POST /postdata \n\n\n" at new StatusCodeError (C:\Users\danie\node_modules\request-promise-core\lib\errors.js:32:15) at Request.plumbing.callback (C:\Users\danie\node_modules\request-promise-core\lib\plumbing.js:104:33) at Request.RP$callback [as _callback] (C:\Users\danie\node_modules\request-promise-core\lib\plumbing.js:46:31) at Request.self.callback (C:\Users\danie\node_modules\request\request.js:185:22) at emitTwo (events.js:126:13) at Request.emit (events.js:214:7) a…
upvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/52449236
tagged with: python

http://stackoverflow.com/a/52548701
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
has body: The scope of footnotes is limited to the document only, and is not global for the entire document set. You could implement citations or a glossary.
type: Answer
accepted answer of: http://stackoverflow.com/q/52547869
answers question: http://stackoverflow.com/q/52547869

http://stackoverflow.com/q/52481028
tagged with: python
type: AnsweredQuestion
has title: How to check if a column whether contains a specific element after grouping by?
upvote count: 2
accepted answer: http://stackoverflow.com/a/52481056
downvote count: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/52481263
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52481056
possible better answer: http://stackoverflow.com/a/52481159
has body: I want to check whether the column app grouping by the column user contains a specific element, such as b. import pandas as pd df=pd.DataFrame({'user':[1,1,1,2,2,3,3],'app':['a','b','c','a','c','b','c']}) Input: app user 0 a 1 1 b 1 2 c 1 3 a 2 4 c 2 5 b 3 6 c 3 Expected: app user contains_b 0 a 1 1 1 b 1 1 2 c 1 1 3 a 2 0 4 c 2 0 5 b 3 1 6 c 3 1
has answer: http://stackoverflow.com/a/52481159

http://stackoverflow.com/comment/91986515
has text: How to read my url. i have edited my code. hope it will be helpful.
comment on: http://stackoverflow.com/a/52523377
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52541033
has comment: http://stackoverflow.com/comment/92024937
upvote count: 2
has title: Cannot install anything via PIP to virtual environment
linked to: http://stackoverflow.com/q/50639973
has answer: http://stackoverflow.com/a/52562412
has comment: http://stackoverflow.com/comment/92025529
has body: When starting a new virtual environment, I am finding it impossible to install any packages via pip. For example, if I try to install mock within a brand new virtualenv, I get the following error: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/lib/python2.7/site-packages/mock.pyc' Consider using the `--user` option or check the permissions. If I try to install with the --user option, I get this error: Can not perform a '--user' install. User site-packages are not visible in this virtualenv. In accordance with this stackoverflow question, I tried changing the ownership of the folder containing my virtual environment but no luck. I know using sudo for pip will mess up the install. This hasn't happened before, and I am utterly stuck. Please help.
type: Question
has comment: http://stackoverflow.com/comment/92025410
has comment: http://stackoverflow.com/comment/92022107
accepted answer: http://stackoverflow.com/a/52562412
answer count: 1
has comment: http://stackoverflow.com/comment/92024491
has comment: http://stackoverflow.com/comment/92023291
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92024204
tagged with: python
has comment: http://stackoverflow.com/comment/92022252
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/52573418
downvote count: 0
score: 1
type: Question
has body: I have five datasets that I have added a 'Year' column to, like this: newyork2014['Year'] = 2014 newyork2015['Year'] = 2015 newyork2016['Year'] = 2016 newyork2017['Year'] = 2017 newyork2018['Year'] = 2018 However, I'm wondering if there's a more Pythonic way of doing this, perhaps with a function? I don't want to change the actual dataframe into a string though, but I want to "stringify" the name of the dataframe. Here's what I was thinking: def get_year(df): df['Year'] = last four digits of name of df return df
tagged with: pandas
has answer: http://stackoverflow.com/a/52573560
accepted answer: http://stackoverflow.com/a/52573560
upvote count: 1
answer count: 1
favorite count: 0
has title: Create a new column with partial name from dataframe
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52525482
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91990794
type: UnansweredQuestion
tagged with: python
has body: I have a storage model from which I need to get objects in the form of a tree and do it like this: if model == 'Storage': if method == 'Read': try: list_sr = [] storage = Storage.objects.all() for item_sr in list(storage): dict_sr = {} if item_sr.id_parent_id == 0: dict_sr['text'] = item_sr.name dict_sr['id'] = str(item_sr.id) dict_sr['expanded'] = True if item_sr.id_parent_id != 0: dict_sr['children'] = [{'text:' + item_sr.name + ", leaf = True"}] list_sr.append(dict_sr) result = {'expanded': 'true', 'text': 'Storage', 'children': list_sr} jsonFormat = json.dumps(result, indent=4, sort_keys=True, default=str) print('Look' + str(jsonFormat)) ... Output of the dictionary data the result displays the following form: { "children": [ { "expanded": true, "id": "9", "text": "Title 1" }, { "children": [ "{'text:Test 1, leaf = True'}" ] }, { "children": [ "{'text:Test 2, leaf = True'}" ] }, { "expanded": true, "id": "12", "text": "Title 2" }, { "children": [ "{'text:Test 3, leaf = True'}" ] }, { "children": [ "{'text:Test 4, leaf = True'}" ] } ], "expanded": "true", "text": "Storage" } I need to have the data in this form: expanded: true, text: "Storage", children:[ { text: "Title 1", id: '9', expanded: true, children: [ { text: "Test 1", leaf: true , }, { text: "Test 2", leaf: true } ] }, { text: "Title 2", id: '12', expanded: true, children: [ { text: "Test 3", leaf: true , }, { text: "Test 4", leaf: true } ] } ] In python, I'm new and therefore I can not generate the correct data in a loop so that they have a representation suitable for Ext.data.TreeStore. How do I change the code in a loop to get the data in the correct form?
score: 2
answer count: 0
upvote count: 2
has title: Creating a tree in json with python from model objects
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/92002697
downvote count: 0

http://stackoverflow.com/comment/92022466
type: QuestionComment
type: Comment
has text: Your simplified example works fine, assuming you call `trigger` first after defining the three functions (and ignoring the trailing `:`s in the definition of `trigger`). You still haven't provided a concrete example that reproduces the error you are getting.
comment on: http://stackoverflow.com/q/52540892
score: 0

http://stackoverflow.com/a/52478713
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52478484
accepted answer of: http://stackoverflow.com/q/52478484
has body: If you're using Python 3.5+, you can instead use: a, *b, c = liste so that a and c would be the first and the last item in the liste list, and b would be the sublist in between, which is what your code apparently intends to do.

http://stackoverflow.com/comment/91905784
score: 0
type: QuestionComment
has text: @sloth I'm trying to find if there is a good dupe, surely there is a canonical?
type: Comment
comment on: http://stackoverflow.com/q/52482027

http://stackoverflow.com/q/52572165
upvote count: 3
tagged with: cluster-computing
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/92348446
has title: how to manually construct a dendrogram from encoded linkage matrix
tagged with: dendrogram
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92110468
type: UnansweredQuestion
tagged with: python
tagged with: linkage
score: 3
answer count: 0
has body: I have created an encoded linkage matrix using python scipy.cluster.hierarchy.linkage module and exported the data as JSON containing following matrix [[ 1. 5. 0.82352941 2. ] [ 4. 7. 0.82857143 2. ] [ 9. 11. 0.84313725 2. ] [ 6. 14. 0.84883721 3. ] [ 2. 8. 0.85714286 2. ] [10. 12. 0.86046512 2. ] [ 0. 15. 0.87098646 3. ] [ 3. 13. 0.87114625 3. ] [18. 20. 0.90143223 5. ] [17. 21. 0.91183896 7. ] [16. 19. 0.91359709 6. ] [22. 23. 0.92420979 13. ]] What is the algorithm for manually constructing a dendrogram, so that i can write code to draw a dendrogram using libraries like D3 from this linkage matrix

http://stackoverflow.com/comment/101073127
type: AnswerComment
comment on: http://stackoverflow.com/a/56667946
has text: Running it from the terminal (outside of VSCode) also solved it for me, running Firefox 68.0.1., Selenium 3.141.0 and geckodriver v0.24.0. That setup [is compatible](https://firefox-source-docs.mozilla.org/testing/geckodriver/geckodriver/Support.html) and then actually works after invoking it from the regular terminal (even without headless).
type: Comment
score: 1

http://stackoverflow.com/a/52582442
answers question: http://stackoverflow.com/q/52580262
score: 1
has body: This should be want you want finder.apply_ngram_filter(lambda w1, w2, w3: sum([w1 n propernouns, w2 in propernouns, w3 in propernouns]) &gt;= 2)
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52580262
type: AcceptedAnswer
type: Answer
upvote count: 1

http://stackoverflow.com/q/52523295
has comment: http://stackoverflow.com/comment/91987020
has title: Crontab will not execute my python program
score: 0
has comment: http://stackoverflow.com/comment/91986235
tagged with: cron
tagged with: python
has comment: http://stackoverflow.com/comment/91986260
answer count: 0
has comment: http://stackoverflow.com/comment/91986476
type: UnansweredQuestion
has body: I wrote this crontab python program from crontab import CronTab cron = CronTab(tab="""* * * * * command""") job = cron.new(command=r'C:\Users\Flo\Desktop\tata\Aldo\aldoCheck.py') job.minute.every(1) #job.dow.on('MON', 'THU') cron.write() But it wont work As you see it should execute 'aldoCheck.py' every minute, but it wont do it ... I dont really know much about how CronTab works on windows (neither on ubuntu or ox, but im running it on windows) and how it works as a library in python, so every explanation it's relevant to me, thank you P.S. Yes , i tried command= r'python C:\...' , but nope...
type: Question
has comment: http://stackoverflow.com/comment/91987623

http://stackoverflow.com/comment/92008019
type: QuestionComment
comment on: http://stackoverflow.com/q/52534395
has text: This looks like an XY problem. Also related: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables
type: Comment
score: 1

http://stackoverflow.com/comment/91973953
score: 0
comment on: http://stackoverflow.com/q/52516539
type: Comment
type: QuestionComment
has text: Can you also add the complete traceback of the error? That way it is often easier to identify the cause of the error.

http://stackoverflow.com/comment/92100894
comment on: http://stackoverflow.com/q/52582637
score: 0
type: Comment
type: QuestionComment
has text: Thanks, Robin, I tried what you said regarding global max, however, the error remains the same. I updated the question

http://stackoverflow.com/q/52465718
duplicate of: http://stackoverflow.com/q/36384760
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91873166
score: -1
has body: I have an array like this ar = np.array([[0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1, 1, 1]]) I want to get array([[0., 0.], [1., 1.], [0., 0.], [1., 0.], [0., 0.], [1., 1.], [0., 1.], [1., 1.]]) If I do as below I get ar.reshape(8,2) array([[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 0], [0, 1], [1, 1]]) My decision is npar = np.zeros((np.asarray(ar).shape[1],np.asarray(ar).shape[0])) npar[:, 0] = ar[0] npar[:, 1] = ar[1] npar array([[0., 0.], [1., 1.], [0., 0.], [1., 0.], [0., 0.], [1., 1.], [0., 1.], [1., 1.]]) But is there more fast &amp; convinient way?
duplicate of: http://stackoverflow.com/q/38086005
tagged with: numpy
upvote count: 0
answer count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/52465767
favorite count: 0
tagged with: reshape
tagged with: python
linked to: http://stackoverflow.com/q/36384760
type: AnsweredQuestion
has title: Reshape np.array(n, m) to np.array(m, n)
accepted answer: http://stackoverflow.com/a/52465767

http://stackoverflow.com/q/52437746
has answer: http://stackoverflow.com/a/52437854
score: 2
has body: Importing my package shows 'os' as submodule of my package. Example: Suppose I have a package with the following structure: -- setup.py -- my_package |-- __init__.py |-- example.py example.py could be: import os def helloWorld(): print('Hello World') The package is installed using python setup.py install. When further using import my_package I find my_package.example.os. How can I avoid 'os' from appearing as submodule? I use python 2.7
tagged with: pypi
tagged with: import
type: Question
has title: why 'os' appears as submodule of my package
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52532083
upvote count: 1
type: Answer
has body: Your PNG image is probably palettised as it has only two colours and that is economically saved with a palette (1 byte of index into palette per pixel instead of 3 bytes of RGB triplet per pixel). Ensure it is RGB with: maze = np.array(Image.open('maze.png').convert('RGB'))
downvote count: 0
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52530546
answers question: http://stackoverflow.com/q/52530546

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/52467563
type: Tag
tags question: http://stackoverflow.com/q/52490642

http://stackoverflow.com/comment/92007052
comment on: http://stackoverflow.com/a/52533938
score: 0
type: Comment
has text: The setter is useless and (imho) even harmful here.
type: AnswerComment

http://stackoverflow.com/a/52518139
has body: You have a 1x3x4x2 tensor train_dataset. Your softmax function's dim parameter determines across which dimension to perform Softmax operation. First dimension is your batch dimension, second is depth, third is rows and last one is columns. Please look at picture below (sorry for horrible drawing) to understand how softmax is performed when you specify dim as 1. In short, sum of each corresponding entry of your 4x2 matrices are equal to 1. Update: The question which dimension the softmax should be applied depends on what data your tensor store, and what is your goal. Update: For image classification task, please see the tutorial on official pytorch website. It covers basics of image classification with pytorch on a real dataset and its a very short tutorial. Although that tutorial does not perform Softmax operation, what you need to do is just use torch.nn.functional.log_softmax on output of last fully connected layer. See MNIST classifier with pytorch for a complete example. It does not matter whether your image is RGB or grayscale after flattening it for fully connected layers (also keep in mind that same code for MNIST example might not work for you, depends on which pytorch version you use).
accepted answer of: http://stackoverflow.com/q/52513802
answers question: http://stackoverflow.com/q/52513802
upvote count: 18
has comment: http://stackoverflow.com/comment/91983272
type: AcceptedAnswer
downvote count: 0
score: 18
has comment: http://stackoverflow.com/comment/91984807
type: Answer

http://stackoverflow.com/comment/92041002
has text: I am not sure about bubblesort but if you just want to sort the values, Python supports `OrderededDict`. Maybe you can look into that https://docs.python.org/2/library/collections.html#collections.OrderedDict
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52551033

http://stackoverflow.com/comment/91849890
has text: So you are saying, no need to iterate through each slide , just open the slide and make changes and then save it ?
type: AnswerComment
comment on: http://stackoverflow.com/a/52453187
score: 0
type: Comment

http://stackoverflow.com/q/52476573
has body: The purpose of this code is to scrape a web page and extract data from a table then convert it to pandas data frame. The scraping and data extracting went well. The output is like this: Release Date Time Actual Forecast Previous Sep 09, 2018 (Aug) 21:30 0.7% 0.5% 0.3% Aug 08, 2018 (Jul) 21:30 0.3% 0.2% -0.1% Jul 09, 2018 (Jun) 21:30 -0.1% 0.1% -0.2% Jun 08, 2018 (May) 21:30 -0.2% -0.1% -0.2% May 09, 2018 (Apr) 21:30 -0.2% -0.1% -1.1% Apr 10, 2018 (Mar) 21:30 -1.1% -0.5% 1.2% Mar 08, 2018 (Feb) 21:30 1.2% 0.8% 0.6% Feb 08, 2018 (Jan) 21:30 0.6% 0.7% 0.3% But when I tried to convert it to data frame I got an error. Here is the code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import pandas as pd url = 'https://www.investing.com/economic-calendar/chinese-cpi-743' driver = webdriver.Chrome(r"D:\Projects\Tutorial\Driver\chromedriver.exe") driver.get(url) wait = WebDriverWait(driver,10) while True: try: item = wait.until(EC.visibility_of_element_located((By.XPATH,'//*[contains(@id,"showMoreHistory")]/a'))) driver.execute_script("arguments[0].click();", item) except Exception:break for table in wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//*[contains(@id,"eventHistoryTable")]//tr'))): data = [item.text for item in table.find_elements_by_xpath(".//*[self::td or self::th]")] for data in data: df = pd.DataFrame(data.strip(), columns=['Release Date', 'Time', 'Actual', 'Forecast', 'Previous']) print(df) Here is the error: Traceback (most recent call last): File "D:/Projects/Tutorial/ff.py", line 22, in df = pd.DataFrame(data.strip(), columns=['Release Date', 'Time', 'Actual', 'Forecast', 'Previous']) File "C:\Users\Sayed\Anaconda3\lib\site-packages\pandas\core\frame.py", line 422, in init raise ValueError('DataFrame constructor not properly called!') ValueError: DataFrame constructor not properly called!
score: 0
tagged with: pandas
answer count: 1
has title: selenium pandas dataframe constructor not properly called
tagged with: python
has answer: http://stackoverflow.com/a/52478061
type: AnsweredQuestion
tagged with: selenium
type: Question
accepted answer: http://stackoverflow.com/a/52478061

http://stackoverflow.com/a/52483373
has comment: http://stackoverflow.com/comment/91908517
answers question: http://stackoverflow.com/q/52483266
has comment: http://stackoverflow.com/comment/91908455
has comment: http://stackoverflow.com/comment/91908328
downvote count: 0
has comment: http://stackoverflow.com/comment/91908834
has comment: http://stackoverflow.com/comment/91908764
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/91908363
has comment: http://stackoverflow.com/comment/91908480
has body: Because str.replace doesn't work in-place, it returns a copy. As immutable objects, you need to assign the strings to elements in your list of lists. You can assign directly to your list of lists if you extract indexing integers via enumerate: L = [['a','bob'],['a','bob'],['a','john']] for i, x in enumerate(L): for j, a in enumerate(x): if 'bob' in a: L[i][j] = a.replace('bob', 'b') Result: [['a', 'b'], ['a', 'b'], ['a', 'john']] More Pythonic would be to use a list comprehension to create a new list. For example, if only the second of two values contains names which need checking: L = [[i, j if j != 'bob' else 'b'] for i, j in L]

http://stackoverflow.com/a/52563898
type: AcceptedAnswer
downvote count: 0
has body: I was able to solve this by passing the env variable in Popen function: subprocess.Popen(["/path/to/envA/python", "/path/to/appA/manage.py", "migrate"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={"PATH": "/path/to/envA/python"})
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52563703
score: 1
answers question: http://stackoverflow.com/q/52563703

http://stackoverflow.com/comment/91811235
type: Comment
score: 0
type: AnswerComment
has text: Pretty slick. Thanks!
comment on: http://stackoverflow.com/a/52432603

http://stackoverflow.com/comment/91847365
comment on: http://stackoverflow.com/a/52451920
type: Comment
has text: I see I will try to fix it.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91971890
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52504153
score: 0
has text: Thanks for your response. I've edited my question accordingly.

http://stackoverflow.com/q/52581584
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92181888
type: Question
has comment: http://stackoverflow.com/comment/92184840
has comment: http://stackoverflow.com/comment/92178554
has title: Darkflow -- No module named 'darkflow.cython_utils.cy_yolo_findboxes'
has body: I've succesfully installed darkflow-1.0.0 (https://github.com/thtrieu/darkflow) on the Windows 10 using the pip install . command. Successfully built darkflow Installing collected packages: darkflow Found existing installation: darkflow 1.0.0 Uninstalling darkflow-1.0.0: Successfully uninstalled darkflow-1.0.0 Successfully installed darkflow-1.0.0 After this, I'm trying to run python flow --h, which gives me following error: Traceback (most recent call last): File "flow", line 4, in &lt;module&gt; from darkflow.cli import cliHandler File "C:\Users\filda\Desktop\FIT_VUT\BP\YOLO\YOLO_keras\darkflow\darkflow\cli.py", line 3, in &lt;module&gt; from .net.build import TFNet File "C:\Users\filda\Desktop\FIT_VUT\BP\YOLO\YOLO_keras\darkflow\darkflow\net\build.py", line 7, in &lt;module&gt; from .framework import create_framework File "C:\Users\filda\Desktop\FIT_VUT\BP\YOLO\YOLO_keras\darkflow\darkflow\net\framework.py", line 1, in &lt;module&gt; from . import yolo File "C:\Users\filda\Desktop\FIT_VUT\BP\YOLO\YOLO_keras\darkflow\darkflow\net\yolo\__init__.py", line 2, in &lt;module&gt; from . import predict File "C:\Users\filda\Desktop\FIT_VUT\BP\YOLO\YOLO_keras\darkflow\darkflow\net\yolo\predict.py", line 7, in &lt;module&gt; from ...cython_utils.cy_yolo_findboxes import yolo_box_constructor ModuleNotFoundError: No module named 'darkflow.cython_utils.cy_yolo_findboxes' So i tried to build the Cython extensions using the python setup.py build_ext --inplace command, which gives me the following error: (base) C:\Users\filda\Desktop\FIT_VUT\BP\YOLO\YOLO_keras\darkflow-master&gt;python setup.py build_ext --inplace running build_ext building 'darkflow.cython_utils.nms' extension creating build\temp.win-amd64-3.5 creating build\temp.win-amd64-3.5\Release creating build\temp.win-amd64-3.5\Release\darkflow creating build\temp.win-amd64-3.5\Release\darkflow\cython_utils C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX64\x64\cl.exe /c /n…
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52632847
has comment: http://stackoverflow.com/comment/92169391
favorite count: 0
has comment: http://stackoverflow.com/comment/92185307
tagged with: darkflow
tagged with: python
has comment: http://stackoverflow.com/comment/92179346
has comment: http://stackoverflow.com/comment/92189250
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92178720
score: 1
accepted answer: http://stackoverflow.com/a/52632847
upvote count: 1

http://stackoverflow.com/comment/91912233
comment on: http://stackoverflow.com/q/52485146
has text: Where is the image id stored? In its filename?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/129450219
comment on: http://stackoverflow.com/q/52555368
score: 0
type: Comment
type: QuestionComment
has text: Numbers **do not have** digits.

http://stackoverflow.com/comment/91870283
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52458367
has text: Yes, i dont know how to solve this

http://stackoverflow.com/q/52531665
has answer: http://stackoverflow.com/a/52532673
has body: I'm using Python script to scrap google, this is what I get when script finishes. Imagine if I have 100 results (I showed 2 for example). {'query_num_results_total': 'Око 64 резултата (0,54 секунде/и)\xa0', 'query_num_results_page': 77, 'query_page_number': 1, 'query': 'example', 'serp_rank': 1, 'serp_type': 'results', 'serp_url': 'example2.com', 'serp_rating': None, 'serp_title': '', 'serp_domain': 'example2.com', 'serp_visible_link': 'example2.com', 'serp_snippet': '', 'serp_sitelinks': None, 'screenshot': ''} {'query_num_results_total': 'Око 64 резултата (0,54 секунде/и)\xa0', 'query_num_results_page': 77, 'query_page_number': 1, 'query': 'example', 'serp_rank': 2, 'serp_type': 'results', 'serp_url': 'example.com', 'serp_rating': None, 'serp_title': 'example', 'serp_domain': 'example.com', 'serp_visible_link': 'example.com', 'serp_snippet': '', 'serp_sitelinks': None, 'screenshot': ''} This is script usage code import serpscrap import pprint import sys config = serpscrap.Config() config_new = { 'cachedir': '/tmp/.serpscrap/', 'clean_cache_after': 24, 'sel_browser': 'chrome', 'chrome_headless': True, 'database_name': '/tmp/serpscrap', 'do_caching': True, 'num_pages_for_keyword': 2, 'scrape_urls': False, 'search_engines': ['google'], 'google_search_url': 'https://www.google.com/search?num=100', 'executable_path': '/usr/local/bin/chromedriver', 'headers': { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Connection': 'keep-alive', }, } arr = sys.argv keywords = ['example'] config.apply(config_new) scrap = serpscrap.SerpScrap() scrap.init(config=config.get(), keywords=keywords) results = scrap.run() for result in results: print(result) I want to stop script if in results is some url I want, for example "example.com" If I have https here 'serp_url': 'https://example2.com' I want to check it and stop script if I give argument without https, …
favorite count: 0
tagged with: python
upvote count: 2
possible better answer: http://stackoverflow.com/a/52532673
has title: Python find value in array by filter
downvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52533228
accepted answer: http://stackoverflow.com/a/52533228
type: Question
answer count: 2

http://stackoverflow.com/comment/92018579
type: AnswerComment
score: 0
type: Comment
has text: That's really what I want. Thanks a lot.
comment on: http://stackoverflow.com/a/52530208

http://stackoverflow.com/comment/92081651
type: Comment
type: QuestionComment
has text: You need to post your code. I'll bet anything you forgot to use a raw string for the regexp, so the backslashes aren't being passed through to the regexp processor.
score: 3
comment on: http://stackoverflow.com/q/52572612

size
type: Tag
tag name: size
tags question: http://stackoverflow.com/q/52475749

http://stackoverflow.com/a/52524065
has comment: http://stackoverflow.com/comment/91987830
answers question: http://stackoverflow.com/q/52524014
upvote count: 2
has body: You may need to adding T df.drop('avg',1).set_index('class').T.plot(kind='bar')
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52524014

http://stackoverflow.com/comment/92077483
type: Comment
type: QuestionComment
has text: Possible duplicate of [Attribute Error: 'list' object has no attribute 'split'](https://stackoverflow.com/questions/30042334/attribute-error-list-object-has-no-attribute-split) ... Found with search terms: `python split readlines AttributeError: 'list' object has no attribute 'split'`
comment on: http://stackoverflow.com/q/52570280
score: 0

http://stackoverflow.com/comment/91915085
score: 0
type: AnswerComment
type: Comment
has text: Correct, and then you write Javascript code on the client side in order to access/use what you passed back. Look at the examples here: https://api.jquery.com/jquery.post/.
comment on: http://stackoverflow.com/a/52486332

http://stackoverflow.com/a/52511260
has body: It seems like you don't want the time component at all; it doesn't make sense to store it if you intend to zero it out in all cases. Keep just the date, and in your serializer, use the date to instantiate a datetime. from datetime import date, datetime # Where t would normally be a date from your model... t = date.today() print(datetime(t.year, t.month, t.day).isoformat()) # 2018-09-26T00:00:00 You haven't given us information regarding how you're generating this JSON, but if you're using Django's built-in serialization, you can write a custom encoder to handle translating dates into zero-time datetimes in this manner.
answers question: http://stackoverflow.com/q/52510834
score: 0
type: Answer

http://stackoverflow.com/q/52526442
has comment: http://stackoverflow.com/comment/91994171
has body: I would like to control a python script that continuously collects data from a sensor (while loop). I would like to be able to start and stop this script by simply clicking a button. I have tried several solutions that included jQuery.ajax requests, but that sadly did not start the script. What should be noted is that I only want to start the script, I do not want any output/return values from it. Below is my code, which is not working. Nothing happens when I click a button. I'm not using Python framework to serve the site. I am running my own web server using a Raspberry Pi with PHP, Apache. Below is the code for only start script without stop. At the present moment I'd like to only run the script. Python code: #!/usr/bin/python3 #!/usr/bin/env python import smbus import sys import time import MySQLdb from time import sleep from datetime import datetime import math fd = 0x20 #outputs fd2 = 0x21 #inputs dane = 0 state = "" bus = smbus.SMBus(1) bus.write_byte(fd2, 0xff) while True: dane = bus.read_byte(fd2) if dane == 0xf8: print "OK" bus.write_byte(fd,0x03) time.sleep(0.4) state = 'Jest OK' elif dane == 0xf9: bus.write_byte(fd,0x00) #LED ON print "Kontaktron nr.1" time.sleep(0.4) bus.write_byte(fd,0x02) #LED OFF state = 'Kontaktron nr.1' time.sleep(0.4) elif dane == 0xfa: bus.write_byte(fd,0x00) #LED ON print "PIR" time.sleep(0.4) bus.write_byte(fd,0x02) #LED OFF state = 'Czujnik PIR nr.1' time.sleep(0.4) elif dane == 0xfc: bus.write_byte(fd,0x00) #LED ON print "Kontaktron nr.2" time.sleep(0.4) bus.write_byte(fd,0x02) #LED OFF state = 'Kontaktron nr.2' time.sleep(0.4) else: bus.write_byte(fd,0x00) print "more sensors" time.sleep(0.4) bus.write_byte(fd,0x02) state = 'Wiecej czujnikow' time.sleep(0.4) db = MySQLdb.connect("localhost", "adrian", "3kr39uvk", "AlarmBD") cursor = db.cursor() try: cursor.execute("INSERT INTO czujniki (id, nazwa_czujnika, data_czujnika) VALUE (NULL,%s,NOW())",[state]) db.commit() except MySQLdb.Error, e: print "An error has occurred. %s" %e…
has comment: http://stackoverflow.com/comment/92002861
tagged with: javascript
score: 0
tagged with: ajax
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
answer count: 0
has title: Executing python script with infinite loop through website button not working
type: Question

http://stackoverflow.com/q/52489103
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/52489265
tagged with: python-3.6
tagged with: while-loop
has answer: http://stackoverflow.com/a/52491562
type: UnansweredQuestion
tagged with: python
has body: Given a value of x, I need to display x items on each page. For eg: I have a list of 10 items. Given x = 3 I need to display 3 items on page1, 3 on page2, 3 on page3 and 1 on page4 value of x can be odd or even. Stuck on how to break or start a new list for the second iteration.
score: 0
has title: Adding x number of items to each page : Python
has comment: http://stackoverflow.com/comment/91919563
type: Question

http://stackoverflow.com/q/52443107
has comment: http://stackoverflow.com/comment/91829047
type: AnsweredQuestion
tagged with: numpy
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52448000
has title: Array slicing raises IndexError: too many indices for array
tagged with: h5py
tagged with: python
has body: I have some data (from an HDF5 file) which I want to get only some columns. I tried slicing the array but got an IndexError and I cannot fathom why. Any idea? Code: &gt;&gt;&gt; type(x) numpy.ndarray &gt;&gt;&gt; x array([((1537445457, 517647), 0.45301986, 13.807418, 0.10681067, 6.856901 , 2.8895614, 15.341972, 2.8160472, 5.7942305, 67.95573, 2.5007493, 13.925896, 1.4587704, 6.1075644, 68.347534, 2.6885383, 15.334871, 0.31526774, 5.9454284, 0.713507 , nan, nan, nan, 0., 0., 0., 0., 0.), ((1537445457, 630955), 0.5777189 , 13.807683, 0.10421388, 6.8743234, 2.7194788, 14.866684, 2.753199 , 5.7411118, 68.38666, 3.0199409, 14.754977, 1.4933671, 5.7361865, 67.82245 , 3.4682775, 15.384485, 0.3508615 , 6.3675985, 0.31907487, nan, nan, nan, 0., 0., 0., 0., 0.)], dtype=[('time', [('sec', '&lt;u4'), ('usec', '&lt;u4')]), ('0', '&lt;f4'), ('1', '&lt;f4'), ('2', '&lt;f4'), ('3', '&lt;f4'), ('4', '&lt;f4'), ('5', '&lt;f4'), ('6', '&lt;f4'), ('7', '&lt;f4'), ('8', '&lt;f4'), ('9', '&lt;f4'), ('10', '&lt;f4'), ('11', '&lt;f4'), ('12', '&lt;f4'), ('13', '&lt;f4'), ('14', '&lt;f4'), ('15', '&lt;f4'), ('16', '&lt;f4'), ('17', '&lt;f4'), ('18', '&lt;f4'), ('19', '&lt;f4'), ('20', '&lt;f4'), ('21', '&lt;f4'), ('22', '&lt;f4'), ('23', '&lt;f4'), ('24', '&lt;f4'), ('25', '&lt;f4'), ('26', '&lt;f4')]) &gt;&gt;&gt; x[0, [0, 1]] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-123-41118eda084a&gt; in &lt;module&gt;() ----&gt; 1 x[0, [0, 1]] IndexError: too many indices for array
has comment: http://stackoverflow.com/comment/91829968
accepted answer: http://stackoverflow.com/a/52448000
has answer: http://stackoverflow.com/a/52444730
has comment: http://stackoverflow.com/comment/91829108
possible better answer: http://stackoverflow.com/a/52444730
type: Question

http://stackoverflow.com/q/52559452
has title: Find columns within a certain percentile of a DataFrame
accepted answer: http://stackoverflow.com/a/52559618
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52559720
has comment: http://stackoverflow.com/comment/92057625
has comment: http://stackoverflow.com/comment/92057553
tagged with: dataframe
tagged with: percentile
possible better answer: http://stackoverflow.com/a/52559720
has comment: http://stackoverflow.com/comment/92057855
tagged with: pandas
has body: Having a multi-column dataframe, I'm interested in how to keep/get the part of the dataframe that fall between the 25th and 75th percentiles per each column ? I need to remove the rows (which are just time steps) that have values outside the 25-75 percentile range import numpy as np import pandas as pd df1 = pd.DataFrame({ '400.0': [13.909261, 13.758734, 13.513627, 13.095409, 13.628918, 12.782643, 13.278548, 13.160153, 12.155895, 12.152373, 12.147820, 13.023997, 15.010729, 13.006050, 13.002356], '401.0': [14.581624, 14.173803, 13.757856, 14.223524, 14.695623, 13.818065, 13.300235, 13.173674, 14.145402, 14.144456, 13.142969, 13.022471, 14.010802, 14.006181, 14.002641], '402.0': [15.253988, 15.588872, 15.002085, 15.351638, 14.762327, 14.853486, 15.321922, 14.187195, 15.134910, 15.136539, 15.138118, 15.020945, 15.010875, 15.006313, 15.002927], '403.0': [15.633908, 14.833914, 15.146499, 15.431543, 15.798185, 14.874350, 14.333470, 14.192128, 15.130119, 15.134795, 15.136049, 15.019307, 15.012037, 15.006674, 15.003002], }) I expect to see a lower number of rows, so I have to eliminate a range of measurements that act as outliers of the timeseries. This is from the original data set, where the x-axis shows the rows. So I need somehow to remove this blob by setting a percentile criteria At the end I'd take the most strict criteria to apply it for the entire dataframe
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92057739
type: Question
has comment: http://stackoverflow.com/comment/92057937
tagged with: python
has answer: http://stackoverflow.com/a/52559618
has comment: http://stackoverflow.com/comment/92057585

http://stackoverflow.com/comment/91975431
type: AnswerComment
comment on: http://stackoverflow.com/a/52503733
has text: In the example above, frame is to be consider as a replacement of your original dataframe. Could you provide an example of your original dataframe. Note that sample could be applied to your original dataframe.
type: Comment
score: 0

http://stackoverflow.com/a/52525959
has comment: http://stackoverflow.com/comment/91992551
has comment: http://stackoverflow.com/comment/91993217
score: 0
has body: Just get the value of the first column. cur.execute('SELECT name, avg_points FROM players ORDER BY avg_points DESC LIMIT 1') row = cur.fetchone() best_player_name = row[0]
accepted answer of: http://stackoverflow.com/q/52525895
answers question: http://stackoverflow.com/q/52525895
type: Answer
has comment: http://stackoverflow.com/comment/91992236
has comment: http://stackoverflow.com/comment/91992780
type: AcceptedAnswer

http://stackoverflow.com/comment/91965960
score: 0
has text: Several notes: It would really help to see full reproducible example. The code above is not as we don't see how you're starting H2O & Spark. Can you please share the command line commands? The second issue is probably because you are using import_file. Import file method expects the file to be already distributed on all H2O nodes in the cluster or stored on some distributed storage such as HDFS. You should use h2o.upload_frame instead if you have the data locally. The first issue is probably because you are using inconsistent versions of H2O & SW. The CLI commands would help.
comment on: http://stackoverflow.com/q/52496836
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91813471
has text: Where did you define the ElectricCar class?
comment on: http://stackoverflow.com/q/52434994
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52524919
accepted answer: http://stackoverflow.com/a/52555801
tagged with: scipy
type: Question
score: 5
tagged with: sympy
upvote count: 5
downvote count: 0
linked to: http://stackoverflow.com/q/32590720
has answer: http://stackoverflow.com/a/52531460
has comment: http://stackoverflow.com/comment/91991525
has answer: http://stackoverflow.com/a/52544596
tagged with: curve-fitting
has body: I have some data I want to fit using a Fourier series of 2nd, 3rd, or 4th degree. While this question and answer on stack overflow gets close to what I want to do using scipy, they already pre-define their coefficients as tau = 0.045 always. I want my fit to find possible coefficients (a0, w1, w2, w3, etc) with 95% confidence interval just like the MATLAB curve fit equivalent for the Fourier series does. The other option I saw was using the fourier_series from sympy however this function only works with symbolic parameters fitting to a defined function rather than raw data. 1) Is there a way for the sympy fourier_series to take in raw data rather than a function or another work around using this library? 2) Or scipy curve-fitting for the data given that there's multiple unknown's (the coefficients)
favorite count: 0
possible better answer: http://stackoverflow.com/a/52544596
answer count: 5
has comment: http://stackoverflow.com/comment/91992391
tagged with: python
has title: Fourier Series Fit in Python
has comment: http://stackoverflow.com/comment/91993490
tagged with: matlab
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52555801
has answer: http://stackoverflow.com/a/70030803
has answer: http://stackoverflow.com/a/68847361

http://stackoverflow.com/comment/91991663
has text: You should try a threshold using OTSU as first step and then (depending of the result) count all the non zero pixels directly.
comment on: http://stackoverflow.com/q/52525903
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91943529
comment on: http://stackoverflow.com/q/52491894
type: Comment
type: QuestionComment
score: 0
has text: @cricket_007 Yes, because this is a project from work and it would be my boss's decision to update it to a newer version...

http://stackoverflow.com/comment/91989011
has text: See the above edit.
type: QuestionComment
comment on: http://stackoverflow.com/q/52524586
score: 1
type: Comment

http://stackoverflow.com/q/52554981
upvote count: 4
answer count: 1
has body: In Python standard library there is a number of implicit interfaces that are expected to be implemented in various cases. For example, coroutines and tasks are "awaitable", meaning they implement the __await__ method; context managers need to implement __enter__ and __exit__; iterables implement __next__; and so on. Is there a single place where all those interfaces are documented, or does one need to hunt them through the documentation?
favorite count: 0
has answer: http://stackoverflow.com/a/52555004
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 1
accepted answer: http://stackoverflow.com/a/52555004
type: Question
has comment: http://stackoverflow.com/comment/92048545
has title: Are all standard library Python interfaces documented somewhere in one place?
has comment: http://stackoverflow.com/comment/92048540

http://stackoverflow.com/a/52486356
upvote count: 6
answers question: http://stackoverflow.com/q/52486306
accepted answer of: http://stackoverflow.com/q/52486306
has body: According to How to access the real value of a cell using the openpyxl module for python when loading the workbook you have to set data_only to True: wb = load_workbook("file.xlsx", data_only=True)
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6

http://stackoverflow.com/comment/91924940
comment on: http://stackoverflow.com/q/52492143
score: 1
has text: As the error says, you are not passing a keyword argument of `array` to the `format` method and yet you have `{array}` in your formatting string.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91940688
type: Comment
has text: Thanks for your answer. If i = 23 will give IndexError: list index out of range
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52499631

http://stackoverflow.com/a/52563488
accepted answer of: http://stackoverflow.com/q/52547705
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: I got what I wanted with: test_schema = TestSchema(exclude=('user',)) areas_schema = AreaSchema(many=True, exclude=('test', 'user',)) issues_schema = IssueSchema(many=True, exclude=('test', 'user',)) and later: test, error = test_schema.dump(test_result) areas, error = areas_schema.dump(test_result.areas) issues, error = issues_schema.dump(test_result.issues) return jsonify({'test': test, 'areas': areas, 'issues': issues}) If someone get to know why test_detailed_schema = Test_DetailedSchema() with class Test_DetailedSchema(ma.ModelSchema): test = ma.Nested('TesSchema') areas = ma.Nested('AreaSchema', many=True, exclude=('test', 'user',)) issues = ma.Nested('IssueSchema', many=True, exclude=('test', 'user',)) Do not return the same result , please let the response here
type: Answer
answers question: http://stackoverflow.com/q/52547705

http://stackoverflow.com/comment/91965014
score: 0
type: Comment
has text: I added `os.environ["TF_CPP_MIN_LOG_LEVEL"]="2"` and `tf.logging.set_verbosity(tf.logging.ERROR)`, that has made the PNG warnings disappear. The JPEG lines still show up, though, actually they are not log lines, they are outputted to the UNIX error output, so `2>/dev/null` can be a radical solution against them. Still, a less radical solution (that lets other information go through) would be welcome :-)
comment on: http://stackoverflow.com/a/52512480
type: AnswerComment

http://stackoverflow.com/q/52551247
favorite count: 0
accepted answer: http://stackoverflow.com/a/52558484
tagged with: pandas
has body: I am trying to build a super dictionary which holds within a number of lower level libraries Concept I have interest rates for my retail bank for the last 12 years and I am trying to model the interest rates by using a portfolio of different bonds. Regression formula Y_i - Y_i-1 = A + B(X_i - X_i-1) + E In words, Y_Lag = alpha + beta(X_Lag) + Error term Data Note: Y = Historic Rate df = pd.DataFrame(np.random.randint(low=0, high=10, size=(100,17)), columns=['Historic Rate', 'Overnight', '1M', '3M', '6M','1Y','2Y','3Y','4Y','5Y','6Y','7Y','8Y','9Y','10Y','12Y','15Y']) Code thus far #Import packages required for the analysis import pandas as pd import numpy as np import statsmodels.api as sm def Simulation(TotalSim,j): #super dictionary to hold all iterations of the loop Super_fit_d = {} for i in range(1,TotalSim): #Create a introductory loop to run the first set of regressions #Each loop produces a univariate regression #Each loop has a fixed lag of i fit_d = {} # This will hold all of the fit results and summaries for col in [x for x in df.columns if x != 'Historic Rate']: Y = df['Historic Rate'] - df['Historic Rate'].shift(1) # Need to remove the NaN for fit Y = Y[Y.notnull()] X = df[col] - df[col].shift(i) X = X[X.notnull()] #Y now has more observations than X due to lag, drop rows to match Y = Y.drop(Y.index[0:i-1]) if j = 1: X = sm.add_constant(X) # Add a constant to the fit fit_d[col] = sm.OLS(Y,X).fit() #append the dictionary for each lag onto the super dictionary Super_fit_d[lag_i] = fit_d #Check the output for one column fit_d['Overnight'].summary() #Check the output for one column in one segment of the super dictionary Super_fit_d['lag_5'].fit_d['Overnight'].summary() Simulation(11,1) Question I seem to be overwriting my dictionary with every loop and I'm not evaluating the i properly to index the iteration as lag_1, lag_2, lag_3 etc. How do I fix this? Thanks in advance
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
tagged with: statsmodels
has answer: http://stackoverflow.com/a/52558484
has title: Python: Super Dictionary of Simple OLS
score: 1
tagged with: for-loop
tagged with: arrays
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/91929277
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52494318
score: 1
has text: Did you verify that mysql is actually running, for example by running `ps aux | grep mysqld` in a terminal?

http://stackoverflow.com/q/52524996
tagged with: django
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/52528516
upvote count: 1
tagged with: celery
type: Question
has title: Django - Update field value after 7 days with Celery
answer count: 1
downvote count: 0
has body: My today Question is how i can change value of field after 7 days using Celery My models: class Episode(models.Model): availability_free_users = models.DateTimeField(default=datetime.now()+timedelta(days=7)) availability = models.BooleanField(default=False) So i want to update availability to true if today date (only date not hour) = availability_free_users
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91888708
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52473190
has text: It is unclear what you want to do. Do you want to compare your denoised image with a "noise free" original image (i.e. you added synthetic noise, you are doing an experiment to evaluate the denoising algorithm) or do you want to estimate how much noise is in a natural image?
score: 0

http://stackoverflow.com/comment/91853566
type: QuestionComment
comment on: http://stackoverflow.com/q/52455549
score: 0
type: Comment
has text: What if you simply do not pass the `fmt` argument at all? Does it work?

http://stackoverflow.com/comment/123710945
type: Comment
comment on: http://stackoverflow.com/a/68770800
score: 4
type: AnswerComment
has text: Commenting out "pre_save" and "post_save" solved my issue.

http://stackoverflow.com/comment/91957892
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52483365
has text: Be sure your local mongo server is running while examining compass
score: 0

http://stackoverflow.com/comment/91828213
type: Comment
type: QuestionComment
has text: Hey sorry, it was wrong, corrected it. Please check. Row4 df1.a == df2.a matching but other column values(c,d) are not matching (Gap more than +- 10), so its mismatch
comment on: http://stackoverflow.com/q/52442372
score: 0

http://stackoverflow.com/a/52480245
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91916934
has comment: http://stackoverflow.com/comment/91934981
has comment: http://stackoverflow.com/comment/91901917
has body: Try this: self.connection_cursor.execute(query, tuple_of_query_parameters) if commit: self.connection_cursor.commit() #put commit here, immediately after execute I think that will do the trick.
accepted answer of: http://stackoverflow.com/q/52480036
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91935211
has comment: http://stackoverflow.com/comment/91920209
upvote count: 2
answers question: http://stackoverflow.com/q/52480036

http://stackoverflow.com/q/52493353
has comment: http://stackoverflow.com/comment/91938212
has comment: http://stackoverflow.com/comment/91927967
tagged with: validation
downvote count: 0
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/91938389
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91929380
tagged with: matlab
tagged with: user-input
has comment: http://stackoverflow.com/comment/91929111
score: 2
has body: I have a GUI interface in Matlab (or also Python) that asks the user for a comment to a certain event. That comment is important and is loaded in a database for future traceability of the event. That comment have to be detailed. I would like to avoid lazy user inputs such as: " " "aaaaaaaaaaaaaa" "safsafafa" "test" "x" "........." "qwerty" etc and ask for a re-input if the "lazy input" is detected like this: valid_input = 0; while valid_input~=1 valid_input = 0; user_input = ''; user_input=InputTextRequest('Insert significant mandatory comment'); switch user_input case {'exit','quit'} out = Popup('PROCEDURE ABORTED','PROCEDURE HAS BEEN ABORTED BY USER'); return otherwise if CheckCommentValidity( user_input)~=1 msg={'Comment field have to be significant:', [user_input ' is not valid, add details.']}; out = Popup('NOTE NOT ACCEPTED',msg); valid_input = 0; else valid_input = 1; end end end The problem is to detect if the user_input is valid or not. I came out with a function that uses for the validation 4 different parameters in the input string: the number of unique chars n_unique the total number of chars n_tot the number of spaces n_space the number of vowels n_vowels I was wondering what checks I can do between this parameters to determine the string validity? I'm Italian so I know that my language uses for example more vowels than english but anyway, does exist a list of parameters/thresholds that describes a "correct" input? Now I'm using this function with parameters thresholds determined at a rough guess. function valid = CheckCommentValidity( user_input) valid=0; %parameters n_unique = length(unique(strrep(user_input,' ',''))); %number of unique chars excluded spaces n_tot = length(user_input); %number of chars n_space = sum(user_input==' '); %number of spaces n_space = sum(ismember( user_input, 'aeiou')); %sub checks conformity_check(1) = n_unique &gt; 8; conformity_check(2) = n_tot &gt;= 10; conformity_check(3) = n_space &gt;= 1; conformity_check(4) = n_vowe…
has comment: http://stackoverflow.com/comment/91928668
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91927930
type: Question
has title: Check user input string to avoid "lazy typing"
has comment: http://stackoverflow.com/comment/91938437

http://stackoverflow.com/q/52584356
upvote count: 1
has body: After installing mySQL version 8.0 and typed in terminal mySQL -u root -p as headfirst python mentioned. but doesn't work. I googled it and I found, the answer is path addition. but didn't find bin folder. How to add path? or how to find bin folder?
favorite count: 0
has comment: http://stackoverflow.com/comment/92103612
answer count: 0
downvote count: 0
has title: installing mysql there's no bin folder
has comment: http://stackoverflow.com/comment/92103632
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92103821
score: 1
tagged with: bin
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/92103896
has comment: http://stackoverflow.com/comment/92103941
has comment: http://stackoverflow.com/comment/92104123

http://stackoverflow.com/comment/91939170
comment on: http://stackoverflow.com/a/52497819
type: AnswerComment
score: 0
type: Comment
has text: I see. I've updated my answer with a solution to apply the headers globally to requests that are not made in a session.

http://stackoverflow.com/a/52488075
has body: One way is to use a list comprehension and then add part of the start of the list to the final group if needed. def split_list(the_list, chunk_size): chunks = [the_list[i:i+chunk_size] for i in range(0, len(the_list), chunk_size)] chunks[-1] += the_list[:(chunk_size - len(the_list)) % chunk_size] return chunks
answers question: http://stackoverflow.com/q/52487712
score: 0
type: Answer

http://stackoverflow.com/comment/91939077
comment on: http://stackoverflow.com/q/52499124
score: 0
type: QuestionComment
type: Comment
has text: It changes the variable but those changes are local to the function. You can use Global variables or return the updated values to reflect the changes or use a different data structure like lists in which you can make the changes inside the function and changes would be reflected to other functions as well

http://stackoverflow.com/comment/91928325
comment on: http://stackoverflow.com/a/52493730
score: 0
type: AnswerComment
type: Comment
has text: Thanks for your replying, but do I need to `write datetime` or something else? And here is the error `File "pandas\_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Datum'`

http://stackoverflow.com/comment/91868171
type: QuestionComment
has text: min(list1), done
score: 0
comment on: http://stackoverflow.com/q/52462777
type: Comment

http://stackoverflow.com/a/52542790
answers question: http://stackoverflow.com/q/52542140
has comment: http://stackoverflow.com/comment/92028596
type: AcceptedAnswer
has body: Couldn't find in in docs. It's in the reference guide: https://docs.bokeh.org/en/latest/docs/reference/models/annotations.html#bokeh.models.annotations.Legend.inactive_fill_color e.g. plot.legend.inactive_fill_color = "blue"
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/92027916
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52542140
score: 3

http://stackoverflow.com/a/52503308
answers question: http://stackoverflow.com/q/52503082
upvote count: 2
has comment: http://stackoverflow.com/comment/91947519
has body: Sure. You can even have a general solution that should work for any such game def game(rules, i): return ''.join(word for divisor, word in rules if not i%divisor) or i # Possibly str(i) _fizzbuzzbang_rules = sorted({2: "Fizz", 3: "Buzz", 4: "Bang"}.items()) def fizzbuzzbang(i): return game(_fizzbuzzbang_rules, i) # You could also use partial # fizzbuzzbang = partial(game, _fizzbuzzbang_rules) Some examples: &gt;&gt;&gt; fizzbuzzbang(2) 'Fizz' &gt;&gt;&gt; fizzbuzzbang(3) 'Buzz' &gt;&gt;&gt; fizzbuzzbang(5) 5 &gt;&gt;&gt; fizzbuzzbang(12) 'FizzBuzzBang'
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/92062997
type: Comment
comment on: http://stackoverflow.com/q/52560862
has text: I am confused: Your plot shows labels `"hmmm"` but those letters do not even appear in the code. Instead, one would expect to see labels starting with `"T"` followed by some number. I'm sure once you provide a [mcve], i.e. a runnable code that reproduces the undesired behaviour it'll be solvable within some minutes.
score: 1
type: QuestionComment

http://stackoverflow.com/q/52572581
has title: a.__add__(a) is different with a+a
favorite count: 0
type: UnansweredQuestion
has body: python 3.7.0 in the following code a+a and a.__add__(a) could be different how can I let a+a return a.__add__(a)? import tensorflow as tf class T(tf.Tensor): def __init__(self, data): super().__init__(data.op, data.value_index, data.dtype) def res(self, arg): print("ADD") return super().__add__(arg) setattr(self,"__add__",res.__get__(self,T)) a = T(tf.constant([1,2,3])) a+a print("--- a line ---") a.__add__(a) run it and get --- a line --- ADD because I want to reload several builtin function with the similar rules I want to use a loop to realize. so defining function directly in class such as class lalala(): def __add__(self,args): return blabla not works for me BTW, I found metaclass works import tensorflow as tf class MetaT(type): def __new__(cls, n, b, a): def res(self, arg): print("ADD") return super(self.__class__, self).__add__(arg) a["__add__"] = res return type.__new__(cls, n, b, a) class T(tf.Tensor, metaclass=MetaT): def __init__(self, D): super().__init__(D.op, D.value_index, D.dtype) a = T(tf.constant([1,2,3])) b = a+a print("--- a line ---") b = type(a).__add__(a,a) this output: ADD --- a line --- ADD
tagged with: python
has answer: http://stackoverflow.com/a/52572656
downvote count: 3
upvote count: 1
type: Question
score: -2
linked to: http://stackoverflow.com/q/10376604
answer count: 1
duplicate of: http://stackoverflow.com/q/10376604

http://stackoverflow.com/q/52578043
has body: I want to replace a parameter value from the URL using the following code. After replacing the value of parameter I get the following data in variable query_dict { 'part': ['snippet,replies'], 'allThreadsRelatedToChannelId': ['UCBqUbOUyAsTB7Xc7xQAHWZA'], 'maxResults': ['100'], 'pageToken': 'QURTSl9pMGhfWTZoU3dPX2dNendrSUZqRU1IVk5mTmVvVkpxT2c3dkJBbzdNME80SldsWnY0dHFYck9raUpxT0dqRm9pZ2k4Smo1Q2ZKSE5NWmZLWEVkcm5acC1paU9HUFpUaTlKdVljYjFqOUx5YzVVQzA4bmlSYkVxOGNISDVWY0E2ZmVuMVN5TFB6bWx2MGc=', 'key': my_key } When I try to build url using unparse method it gives the following error not enough values to unpack (expected 7, got 6). What's wrong? Following is the current code r = urllib.request.urlopen(url) a=r.read().decode('utf-8') data =json.loads(a) parts = urlparse(url) query_dict = parse_qs(parts.query) query_dict['pageToken'] = data['nextPageToken'] build_url=urllib.parse.urlunparse(query_dict)
answer count: 2
score: 5
favorite count: 0
has comment: http://stackoverflow.com/comment/92091874
upvote count: 5
tagged with: python
tagged with: python-3.x
has title: Want to build URL after parsing using python 3
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52578116
has answer: http://stackoverflow.com/a/58644277
has comment: http://stackoverflow.com/comment/92091324
type: Question

http://stackoverflow.com/q/52549143
has title: python accessing variable of high level from lower level class
has answer: http://stackoverflow.com/a/52549191
has comment: http://stackoverflow.com/comment/92037352
upvote count: 3
answer count: 3
has body: I have a class inside a class like this: class Robot(object): def __init__(self): self.name = 'ganken' class Speaker(object): pass Let’s say I want to access Robot.name from Speaker, how do I do that
has answer: http://stackoverflow.com/a/52549253
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/52549388
downvote count: 0
has comment: http://stackoverflow.com/comment/92037371
has comment: http://stackoverflow.com/comment/92037333
type: Question

http://stackoverflow.com/a/52451853
score: 4
answers question: http://stackoverflow.com/q/52451794
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52451794
has body: As the error says args has to be a tuple. You can turn the current version easily into a tuple by using args=(inputs,) Note the additional comma.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52493834
score: 5
has body: Yes Union[A,B] means that value can be either of type A or of type B.. This does not imply that you can treat the value as if it was A or B at your choice. That's precisely the use of an intersection type. When you have a Union[A,B] you have to check if the value is A, and if so handle it like A, or if it is B, and handle it like a B. The advantage is that you know that it wont be an other type C, so you have a defined list of types to check against. But you still need to check in some way.
upvote count: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52493462
answers question: http://stackoverflow.com/q/52493462

http://stackoverflow.com/a/62730167
has body: Extending @Vaishali's answer. To handle the remaining columns without having to specify each one you could create a dictionary and have that as the argument for the agg(regate) function. dict = {} for col in df: if (col == 'column_you_wish_to_merge'): dict[col] = ' '.join else: dict[col] = 'first' # or any other group aggregation operation df.groupby(['key1', 'key2'], as_index=False).agg(dict)
answers question: http://stackoverflow.com/q/52546386
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/a/65009222
answers question: http://stackoverflow.com/q/52581369
type: Answer
has body: You can use the following approach it will be much more intuitive and easier to maintain. import numpy as np def Mult(self,Matrix): result = ClassMatrix() # not sure about addRow and addColumn methods but # if we can simply update content or pass it as a param to constructor # then next 2 statements will not be required result.addRow(self.numberofRows) result.addColumn(Matrix.numberofColumns) # using numpy dot product for matrix multiplication result.content = np.dot(self.content, Matrix.content) return result
score: 0

http://stackoverflow.com/a/52581991
score: 1
downvote count: 0
has body: You can use lstrip(..) and rstrip(..) separately, and each time count the number of characters that were removed, and slice with these characters: var1 = 'AnAppleADayKeepsTheDoctorAway' var2 = '000Ig00000noranceIsBliss00000' n0 = len(var2) var3 = var2.lstrip('0') nl = n0 - len(var3) var2s = var3.rstrip('0') var1s = var1[nl:len(var2s)+nl] So we slice var1s in such way that we remove nl leading characters (the number of characters we removed with lstrip(..)), and then we ensure that the length is the same as the number of characters in var2s (var2 after both lstrip(..) and rstrip(..)). We thus then obtain: &gt;&gt;&gt; var1s 'ppleADayKeepsTheDocto' &gt;&gt;&gt; var2s 'Ig00000noranceIsBliss'
type: Answer
answers question: http://stackoverflow.com/q/52581881
upvote count: 1

http://stackoverflow.com/comment/92067467
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52564696
type: AnswerComment
has text: Plus, it's not recommended to `sys.setrecursionlimit` to an arbitrarily high value, as it relies heavilybl on system resources.

http://stackoverflow.com/q/52450640
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52451062
type: AnsweredQuestion
upvote count: 2
tagged with: jinja2
type: Question
accepted answer: http://stackoverflow.com/a/52451062
tagged with: airflow
has body: I'm attempting to use the jinja templating to parse some json found in xcom into a dictionary. Note below that Operator and templated_field are psuedo-code. def xcom_from_json(xcom): xcom_loaded = json.loads(xcom) logging.info(pformat(f'xcom loaded: {xcom_loaded}', indent=3)) return xcom_loaded PythonOperator(python_callable=some_callable, op_args=[f'{{{{ (ti.xcom_pull("{task_id}") | xcom_from_json)["data"]["stats"] }}}}']) The above works, almost. In the some_callable method I get the parsed jinja, but it comes out as a stringified dict instead of a raw dict. This doesn't make sense, because you can see the structure being traversed as a dict in the jinja template. Does jinja stringify everything coming out of a template? If yes, is there a way to not do that?
has title: airflow rendered template becomes a string
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52460913
has answer: http://stackoverflow.com/a/61411225
favorite count: 0
has title: Compiling Cython with Xcode 10
type: UnansweredQuestion
tagged with: xcode
tagged with: python
has comment: http://stackoverflow.com/comment/91864495
upvote count: 6
has answer: http://stackoverflow.com/a/52466939
score: 6
tagged with: cython
has comment: http://stackoverflow.com/comment/91869716
has comment: http://stackoverflow.com/comment/91875541
type: Question
has comment: http://stackoverflow.com/comment/91868729
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91864088
has body: I have tried to compile a simple example with Cython and got this linker error (macOS, Xcode 10): gcc -fno-strict-aliasing -I/anaconda2/envs/python2.7-base/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/anaconda2/envs/python2.7-base/include/python2.7 -c noway.cpp -o build/temp.macosx-10.6-x86_64-2.7/noway.o -std=c++11 -Os -stdlib=libc++ -mmacosx-version-min=10.7 g++ -bundle -undefined dynamic_lookup -L/anaconda2/envs/python2.7-base/lib -arch x86_64 -arch x86_64 build/temp.macosx-10.6-x86_64-2.7/one.o build/temp.macosx-10.6-x86_64-2.7/noway.o -L/anaconda2/envs/python2.7-base/lib -o /Users/dkotsur/Projects/InCeM/IF-MedialAxis/test/noway.so clang: warning: libstdc++ is deprecated; move to libc++ with a minimum deployment target of OS X 10.9 [-Wdeprecated] ld: library not found for -lstdc++ clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'g++' failed with exit status 1 My anaconda environment is this: Python 2.7.15 |Anaconda custom (64-bit)| (default, May 1 2018, 18:37:05) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin It seems like anaconda uses libstdc++ instead of libc++ for Mac. But I have no clues how to fix it. Had anyone have something similar? Any clues on how to deal with that? Here is my code setup.py if platform.system() == "Windows": extra_args = ["/std:c++latest", "/EHsc"] elif platform.system() == "Darwin": extra_args = ['-std=c++11', "-Os", "-stdlib=libc++", "-mmacosx-version-min=10.7"] else: extra_args = [] compile_files = [ "one.pyx", "noway.cpp", ] include_paths = [ ] ext_modules = [Extension("noway", compile_files, language='c++', include_dirs=include_paths, extra_compile_args=extra_args)] setup(cmdclass={'build_ext': build_ext}, ext_modules=cythonize(ext_modules)) one.pyx: import cython cdef extern from "noway.hpp": cdef void noway(); def nway(): noway() noway.hpp #ifndef noway_h #define noway_h void noway(); #endif noway.cpp #include "noway.hpp" #include…

http://stackoverflow.com/q/52462960
has comment: http://stackoverflow.com/comment/91868146
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/91868130
has body: I have created a 2d matrix using Scipy's coo_matrix, and have a matrix M as such: df = pd.DataFrame(columns=["hub", "auth", "weight"]) M = coo_matrix((df.iloc[:,2], (df.iloc[:,0],df.iloc[:,1])), shape=(len(hubs) + len(auths), len(hubs) + len(auths))) M = M.todense() [[0 0 0 1 1 1 0] [0 0 0 1 1 0 0] [0 0 0 0 0 0 1] [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]] I can successfully slice the array to get its columns and the elements in each column: col = M[:,3] val = col[0] where val is equal to 1. I try to do something similar to extract a row: row = M[0] val = row[2] which should also return 1, but instead val returns [[0 0 0 1 1 1 0]] What am I doing wrong here?
type: Question
tagged with: arrays
has comment: http://stackoverflow.com/comment/91868174
score: -1
has comment: http://stackoverflow.com/comment/91868050
answer count: 1
has answer: http://stackoverflow.com/a/52463000
has comment: http://stackoverflow.com/comment/91868126
has comment: http://stackoverflow.com/comment/91868056
favorite count: 0
has title: Can't access row elements in Python 2d array?
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91868169
has comment: http://stackoverflow.com/comment/91868123

http://stackoverflow.com/q/52545317
has answer: http://stackoverflow.com/a/52545402
type: UnansweredQuestion
tagged with: python
has title: Creating a function for unstacking a dataframe
type: Question
has comment: http://stackoverflow.com/comment/92030725
has answer: http://stackoverflow.com/a/52545589
has answer: http://stackoverflow.com/a/52545460
score: 0
has comment: http://stackoverflow.com/comment/92030693
answer count: 3
tagged with: pandas
has body: Currently I have a data frame that is somewhat structured like this InvoiceNo Month Year Size 1 1 2014 7 2 1 2014 8 3 2 2014 11 4 3 2015 9 5 7 2015 8.5 and so on... I am trying to create a function that will segment the Dframe by year, and group by the size and the month, and then count the InvoiceNo, and then finally unstack that dataframe. What I have been doing is something like this: x = 2014 def Year_calc(df): return df[df['Year'] == x].groupby(['Size','Month']).agg({'InvoiceNo': 'count'}).unstack(0).columns.droplevel(0).fillna(0) and then df2014 = Year_calc(df) But it returns this output: Float64Index([], dtype='float64', name='Size') Anyone able to point out what I am doing wrong?

http://stackoverflow.com/q/52548448
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/52548540
type: Question
has answer: http://stackoverflow.com/a/52548568
accepted answer: http://stackoverflow.com/a/52548568
answer count: 3
tagged with: pandas
upvote count: 1
has body: I have a pandas dataframe. One of the columns of the dataframe is a dict object. The following dataframe is a toy example of the real dataframe: DF = pd.DataFrame({'id':[1,2,3], 'col1':[{'a':1, 'b':2, 'c':3}, {'a':3, 'b':4, 'c':5}, {'a':None, 'b':5, 'c':6}]}) I would like to split the col1 in columns: one column per dictionary key. All the rows have the same keys. After the splitting the dataframe should look like: id a b c 1 1 2 3 2 3 4 5 3 None 5 6 NOTE: I got the dict column from a jsonb column in postgresql.
has answer: http://stackoverflow.com/a/52548540
favorite count: 0
has title: How to split a pandas column of type dict in columns?
has answer: http://stackoverflow.com/a/52548535
has comment: http://stackoverflow.com/comment/92036404
tagged with: python

http://stackoverflow.com/a/52584363
has body: My very lousy and redundant solution. dataframe['difference'] = dataframe['A'] - dataframe['B'] dataframe['temporary_a'] = np.array(dataframe.difference) &gt; 0 dataframe['temporary_b'] = np.array(dataframe.difference.shift(1)) &lt; 0 cross_directions = [] for index,row in dataframe.iterrows(): if not row['temporary_a'] and not row['temporary_b']: cross_directions.append("up") elif row['temporary_a'] and row['temporary_b']: cross_directions.append("down") else: cross_directions.append("not") dataframe['cross_direction'] = cross_directions
answers question: http://stackoverflow.com/q/52584053
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92103683

http://stackoverflow.com/q/52469795
tagged with: python-3.x
has body: I would like to make a request. Those are parameters that are required. The problem is that I don't know how to create an array that I would be able to pass a parameter in order to make an request using suds library. $dogetitemsinfo_request = array( 'sessionHandle' =&gt; '22eb99326c6be29aa16d07d622bcfbcbee94ad54846f2f4e03_1', 'itemsIdArray' =&gt; array(975967833, 886978949), ); This is my class for making requests: class OffersViewAndOptions: @classmethod def doGetItemsInfo( cls, sessionHandle, itemsIdArray, ): global client client = Client('https://webapi.allegro.pl/service.php?wsdl') response = client.service.doGetItemsInfo( sessionHandle=sessionHandle, itemsIdArray=itemsIdArray, ) do_get_items_info = { 'itId': response.item[0].item[0].itId, } return do_get_items_info Here is my frist attempt to pass an array as parameter array = [6688519219, 6688519219] getitem = OffersViewAndOptions.doGetItemsInfo(session_handle_part, array) Here is the response: suds.WebFault: Server raised fault: 'Element '{https://webapi.allegro.pl/service.php}itemsIdArray': Character content other than whitespace is not allowed because the content type is 'element-only'. Second I searched on SO for possible solutions and I found this: array = client.factory.create('array') array.item = [7554257498, 6688519219] request.option=array Here is the response: suds.TypeNotFound: Type not found: 'array' This documentation may be helpful: https://allegro.pl/webapi/documentation.php/show/id,1093
type: UnansweredQuestion
tagged with: soap
tagged with: python
downvote count: 0
answer count: 0
score: 1
tagged with: suds
type: Question
has title: How to create an array for WSDL and pass it as an argument using suds?
upvote count: 1
tagged with: wsdl
favorite count: 0

http://stackoverflow.com/comment/92103743
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52584420
has text: What is the error message?

http://stackoverflow.com/comment/91890760
type: Comment
has text: Closing parenthesis missing in `print()` statement.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52474483

http://stackoverflow.com/comment/92082947
score: 0
comment on: http://stackoverflow.com/q/52573025
type: Comment
type: QuestionComment
has text: I agree it is not a duplicate. That question however has useful information. Beside others it describes one problem that you have, namely, sending '100 continue' in response when the check does not pass violates the spec of how 'expect: 100 continue' should be processed.

http://stackoverflow.com/a/52536583
score: 2
downvote count: 0
has body: sortedcontainers may be what you want. It will keep the key in sorted order rather than insert order, which is different from collections.OrderedDict. Install $ pip install sortedcontainers To achieve what you want from sortedcontainers import SortedDict def find_nearest(sorted_dict, lookup): key = sorted_dict.iloc[sorted_dict.bisect_left(lookup) - 1] return sorted_dict[key] sd = SortedDict({0: '0', 4: '4', 8: '8', 12: '12'}) print(find_nearest(sd, 4)) # 0 print(find_nearest(sd, 3)) # 0 print(find_nearest(sd, 12)) # 8 The time complexity of this method is O(log n)
type: Answer
answers question: http://stackoverflow.com/q/52535803
upvote count: 2

http://stackoverflow.com/q/52559882
tagged with: concurrency
tagged with: celery
has title: How can I asynchronously receive processed messages in Celery?
downvote count: 0
type: UnansweredQuestion
has body: I'm writing a data processing pipeline using Celery because this speeds things up considerably. Consider the following pseudo-code: from celery.result import ResultSet from some_celery_app import processing_task # of type @app.task def crunch_data(): results = ResultSet([]) for document in mongo.find(): #Around 100K - 1M documents job = processing_task.delay(document) results.add(job) return results.get() collected_data = crunch_data() #Do some stuff with this collected data I successfully spawn four workers with concurrency enabled and when I run this script, the data is processed accordingly and I can do whatever I want. I'm using RabbitMQ as message broker and rpc as backend. What I see when I open the RabbitMQ management UI: First, all the documents are processed then, and only then, are the documents retrieved by the collective results.get() call. My question: Is there a way to do the processing and subsequent retrieval simultaneously? In my case, as all documents are atomic entities that do not rely on each other, there seems to be no need to wait for the job to be processed completely.
score: 1
tagged with: asynchronous
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52601901
tagged with: rabbitmq
answer count: 1

srp-protocol
tags question: http://stackoverflow.com/q/52499526
type: Tag
tag name: srp-protocol

http://stackoverflow.com/comment/92105334
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52585200
has text: use pip freeze and check whether it is installed?

http://stackoverflow.com/comment/91967849
score: 1
type: AnswerComment
has text: @shakthydoss exactly, my bad. Fixed!
comment on: http://stackoverflow.com/a/52494446
type: Comment

http://stackoverflow.com/comment/92003051
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52530120
type: AnswerComment
has text: got it, your comments helped, thanks

http://stackoverflow.com/a/52450556
answers question: http://stackoverflow.com/q/52450422
has comment: http://stackoverflow.com/comment/91844502
has body: Hi you need to define your geocoder function and loop it on your df. I am passing your Postal code column one by one in the function and to fetch values from geocoder and assigning and storing it into two new columns latitude and longitude. See below: import geocoder def get_geocoder(postal_code_from_df): # initialize your variable to None lat_lng_coords = None # loop until you get the coordinates while(lat_lng_coords is None): g = geocoder.google('{}, Toronto, Ontario'.format(postal_code_from_df)) lat_lng_coords = g.latlng latitude = lat_lng_coords[0] longitude = lat_lng_coords[1] return latitude,longitude for i in range(0,len(post_df)): post_df['Latitude'][i],post_df['Longitude'][i]=get_geocoder(post_df.iloc[i]['Postcode']) This should work for you.
upvote count: 2
has comment: http://stackoverflow.com/comment/91845687
has comment: http://stackoverflow.com/comment/91845000
has comment: http://stackoverflow.com/comment/91844287
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91844409
downvote count: 0

http://stackoverflow.com/q/52504067
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: css
has comment: http://stackoverflow.com/comment/91948806
has answer: http://stackoverflow.com/a/52505344
type: Question
has body: I'm still just playing around with Django and cannot figure out what I am doing wrong with my CSS file. My HTML works but not the CSS. I'm guessing it has something to do with settings.py or some special "Django code" I'm not using. Here is the code for my HTML (what I am guessing is the relevant code to show). Here is my HTML: home HELLO WORLD! Here is my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ecommerce005.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Here is my urls.py: from django.conf.urls import url from django.contrib import admin from .views import home_page urlpatterns = [ url(r'^$', home_page), url(r'^admin/', admin.site.urls), ] Here is my views.py: from django.http import HttpResponse from django.shortcuts import render def home_page(request): return render(request, "index.html", {}) The order of my file are as follows: 'src' directory: 1) 'css' folder holds my styles.css file 2) 'projectname' folder contains all of my django files shown above 3) 'templates' folder holds my index.html file Please be as specific as possible. I found sources online but they seemed too vague for me to find a solution. I appreciate your help.
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52507586
has comment: http://stackoverflow.com/comment/91948687
has answer: http://stackoverflow.com/a/52505839
has title: Why will the css in my django project not render?

http://stackoverflow.com/comment/92075537
comment on: http://stackoverflow.com/a/52568492
score: 0
type: Comment
has text: I still couldn't get it to work, the email was never sent. No error messages, I updated the question with the new code.
type: AnswerComment

http://stackoverflow.com/comment/91892702
type: Comment
has text: This looks good but I don't know what text it will be I get it from {MyText}
comment on: http://stackoverflow.com/a/52475596
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92058048
has text: just filter before the groupby, that should do it
type: Comment
comment on: http://stackoverflow.com/q/52559709
type: QuestionComment
score: 1

http://stackoverflow.com/a/52491462
has comment: http://stackoverflow.com/comment/91923526
upvote count: 1
answers question: http://stackoverflow.com/q/52491417
has body: IIUC I think you need: d = {l:(1,'None') for l in list1} d {((1, 4, 2), (0, 5, 8), (3, 6, 7)): (1, 'None'), ((1, 5, 2), (0, 4, 8), (3, 6, 7)): (1, 'None')} For 0th element: d = {l:(1,'None') for l in list_val[0]} d {(1, 4, 2): (1, 'None'), (0, 5, 8): (1, 'None'), (3, 6, 7): (1, 'None')} or d = {v2:(1,'None') for v1 in list1 for v2 in v1} d {(1, 4, 2): (1, 'None'), (0, 5, 8): (1, 'None'), (3, 6, 7): (1, 'None'), (1, 5, 2): (1, 'None'), (0, 4, 8): (1, 'None')}
score: 1
has comment: http://stackoverflow.com/comment/91923705
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91923504

http://stackoverflow.com/comment/92057554
has text: And 0.754 isn't. It's not clear to me at all what you are asking.
comment on: http://stackoverflow.com/q/52559403
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/52533084
has comment: http://stackoverflow.com/comment/92005613
answers question: http://stackoverflow.com/q/52523757
score: 1
upvote count: 1
has body: You shoud think it maybe RESTful,then you will know how to do it import requests headers = { 'Content-Type': 'application/x-www-form-urlencoded' } pj = {} for page in range(1,3): data = [('addr', '1FoWyxwPXuj4C6abqwhjDWdz6D4PZgYRjA'),('page',page)] response = requests.post('https://api.omniexplorer.info/v1/address/addr/details/', headers=headers , data = data) response = response.json() print(response) pj[page] = response["transactions"] value = list(pj.values()) print(value[0] == value[1])
downvote count: 0
type: Answer

http://stackoverflow.com/q/52432324
has comment: http://stackoverflow.com/comment/91809688
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/56450518
has answer: http://stackoverflow.com/a/52433255
tagged with: git
type: Question
score: 14
has body: I am trying to implement a Google Cloud function that is based on code in a Git style repository. I have the code linked to Google Cloud Platform's "Source Repositories" and my function runs fine when I copy and paste the code into the GCP Function "Inline editor". When I switch to the "Cloud Source repository" option, I can tell that it is reading from that repository; I worked through other errors prior to this one. However, after resolving prior/other issues, now I'm getting this error: Function load error: File main.py that is expected to define function doesn't exist my files are in a structure similar to this, with main.py in the root directory: . ├── package | ├──script1.py | └──script2.py ├── package2 ├── ... ├── main.py └── requirements.txt It's reading fine from requirements.txt (some of the prior errors came from that reading process), but why is it not reading from main.py? My setup in the GCP Function looks like this: I have tried to move main.py to another directory in the project and setting the "Directory with source code" to that directory, but that gave me an error saying that it couldn't find that directory. Any constructive ideas? Edit / Additional Information I am using a branch from my repository other than master, and I am using a Google Cloud Pubsub topic trigger for this function.
has answer: http://stackoverflow.com/a/62020124
has comment: http://stackoverflow.com/comment/91809964
tagged with: google-cloud-platform
accepted answer: http://stackoverflow.com/a/52433255
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/59704678
has title: Google Cloud Function - Function load error: File main.py that is expected to define function doesn't exist
answer count: 5
possible better answer: http://stackoverflow.com/a/56343750
tagged with: google-cloud-functions
tagged with: python
has answer: http://stackoverflow.com/a/56343750

http://stackoverflow.com/comment/91918004
comment on: http://stackoverflow.com/q/52488043
type: Comment
type: QuestionComment
has text: Completly forgot to put it the post, there it is
score: 0

http://stackoverflow.com/a/52539943
has comment: http://stackoverflow.com/comment/92022369
answers question: http://stackoverflow.com/q/52539542
has body: for i in rest will give you the actual item in the list, and not index. From your code, it seems that you want to append the value. But actually, you are treating the value as index again, and trying to fetch it from the array. for i in rest: dev.append(rest[i]) Fix: Just change above to: dev.extend(rest) But this code, takes a value from rest, then again uses that value as an index, and if that value i turns out to be a float, it throws an exception. You haven't mentioned which line gives you this error. But I think it must be this one. It might give many other unexpected errors like array out of bound, etc This is the error I get, if I run your code for valor = 18.5 https://ideone.com/HGagLb Traceback (most recent call last): File "./prog.py", line 71, in File "./prog.py", line 51, in convBin TypeError: list indices must be integers or slices, not float Difference between the above example, and the one below(from your code, where you handle int): x = 0 while x &lt;= (len(rest) - 1): dev.append(rest[x]) x += 1 is that, in the first case, i is actually the item(int or float) in the list rest, while in the later one, it's a valid index.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92027742
has comment: http://stackoverflow.com/comment/92020658
has comment: http://stackoverflow.com/comment/92056342
type: Answer
has comment: http://stackoverflow.com/comment/92019783
has comment: http://stackoverflow.com/comment/92021781
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92020007
has comment: http://stackoverflow.com/comment/92021145
has comment: http://stackoverflow.com/comment/92020826
accepted answer of: http://stackoverflow.com/q/52539542
has comment: http://stackoverflow.com/comment/92020989

http://stackoverflow.com/a/52453608
answers question: http://stackoverflow.com/q/52453412
downvote count: 0
has comment: http://stackoverflow.com/comment/91850325
upvote count: 2
has comment: http://stackoverflow.com/comment/91850278
has comment: http://stackoverflow.com/comment/91850613
has body: Along with the reST markup of .. rst-class: center, try combining the CSS selectors, like so: .center h1, .center h2 { text-align: center; } Thus only h1 and h2 in the documentation will be centered.
type: Answer
score: 2

http://stackoverflow.com/q/52434334
has comment: http://stackoverflow.com/comment/91812187
answer count: 0
tagged with: dynamic
has comment: http://stackoverflow.com/comment/91824197
type: Question
has title: How to print a table with dynamic values?
tagged with: tabular
has comment: http://stackoverflow.com/comment/91823713
has body: I am trying to print a 2d matrix with dynamic values. Basically I would like something that looks like this: --------------------------------------------- | Column 1 | Column 2 | Column 3 | Column 4 | --------------------------------------------- | A | A_2 | A_3 | A_4 | | B | B_2 | B_3 | B_4 | | C | C_2 | C_3 | C_4 | --------------------------------------------- With A_2, A_3... being dynamic (updating constantly). The print method is maybe not the best solution, thus any other idea to generate this kind of table in a relative fast way is welcomed. I thought I could build a class to be very general. Something like this: class Viewer: def __init__(self, header_columns): # start building the viewer def update_row(self, data_row): # add the row if it does not exist # else, update the row with new values # and update the table printed def main(): header = ['id', 'value1', 'value2'] myview = Viewer(header) # start updating the values for i in range(10): firstid = {'id': 'A', 'value1': i, 'value2': i} myview.update_row(firstid) To be even more general, the column headers could be updated with the Keys of the rows objects. However, I do not understand how I can do that. I read I could use the library Curses (I use Mac OS), but I'm really not sure if it can do the job
has comment: http://stackoverflow.com/comment/91823257
score: 0
tagged with: printing
has comment: http://stackoverflow.com/comment/91813116
has comment: http://stackoverflow.com/comment/91812267
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91812375
linked to: http://stackoverflow.com/q/12503655
tagged with: python

http://stackoverflow.com/comment/92057805
type: Comment
type: QuestionComment
has text: That entry is DAG in scope, I'm looking specifically for Task sequencing, the below code works fine for dynamic parallel tasking, but not serial
score: 0
comment on: http://stackoverflow.com/q/52558018

conditional-statements
tags question: http://stackoverflow.com/q/52467556
tags question: http://stackoverflow.com/q/52461285
tags question: http://stackoverflow.com/q/52463142
tags question: http://stackoverflow.com/q/52468543
tags question: http://stackoverflow.com/q/52523259
tag name: conditional-statements
tags question: http://stackoverflow.com/q/52522667
tags question: http://stackoverflow.com/q/52474817
tags question: http://stackoverflow.com/q/52468132
tags question: http://stackoverflow.com/q/52514207
type: Tag

http://stackoverflow.com/q/52431821
answer count: 3
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52431950
tagged with: python-3.x
has body: Here are the requirements: Write a function that accepts a dictionary where the key is a letter and the value is a list of words that begin with that letter and returns a dictionary where the key is a letter and the value is the average length of the words in the list For example, if word_dictionary={"a":['am','apple','along','alive'],"b":['big','believe','beef']}, the outcome should be {"a":4.25, "b"=4.6666667} Here are what I have done right now: word_dictionary={"a":['am','apple','along','alive'],"b":['big','believe','beef']} def average_word(word_dictionary): for lis in word_dictionary.values(): length=0 ave=0 for word in lis: length+=len(word) ave=float(len(word))/len(lis) print(ave) Unfortunately, my outcome is not a dictionary but a list of numbers like this: 0.5 1.25 1.25 1.25 1.0 2.3333333333333335 1.3333333333333333 Can anybody help with it?
tagged with: python
tagged with: dictionary
has title: build dictionary for which value is average length of word
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52431944
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/52431950
has answer: http://stackoverflow.com/a/52431971
accepted answer: http://stackoverflow.com/a/52431971
has comment: http://stackoverflow.com/comment/91807487
has comment: http://stackoverflow.com/comment/91807464

http://stackoverflow.com/comment/92052065
type: Comment
has text: Are all of the items in `sales` guaranteed to have a matching item in `weeks`?
comment on: http://stackoverflow.com/q/52556720
score: 0
type: QuestionComment

http://stackoverflow.com/a/61928836
has comment: http://stackoverflow.com/comment/131580525
has body: You can delete all the .pyc files in your folder to resolve it. find . -name \*.pyc -delete
upvote count: 24
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/127208827
score: 24
answers question: http://stackoverflow.com/q/52477683

http://stackoverflow.com/a/77071755
downvote count: 0
has body: Remember also to install the scheduler library upon which the telegram depends: pip install APScheduler
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52556939

atomic
type: Tag
tag name: atomic
tags question: http://stackoverflow.com/q/52432061

http://stackoverflow.com/a/52450233
has body: The error message is very explicit: return (data[i - 1] + data[i])/2 TypeError: unsupported operand type(s) for /: 'tuple' and 'int' It says that the program is trying to divide a tuple by an int. So, data[i - 1] + data[i] is a tuple, and that means that each of data[i - 1] and data[i] are tuples and not numbers as you may be expecting. Note that the error occurs inside the statistics.median function. Check that you are passing arguments with the right type to this function.
score: 2
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52450139

http://stackoverflow.com/comment/91883949
score: 0
type: Comment
type: QuestionComment
has text: Convert your range paramters to int: `int((len(randnum))/3)`
comment on: http://stackoverflow.com/q/52470987

pyinstaller
tags question: http://stackoverflow.com/q/52458165
type: Tag
tags question: http://stackoverflow.com/q/52484481
tags question: http://stackoverflow.com/q/52446677
tags question: http://stackoverflow.com/q/52562106
tag name: pyinstaller
tags question: http://stackoverflow.com/q/52486324
tags question: http://stackoverflow.com/q/52499540
tags question: http://stackoverflow.com/q/52538892
tags question: http://stackoverflow.com/q/52557224
tags question: http://stackoverflow.com/q/52492082
tags question: http://stackoverflow.com/q/52451471
tags question: http://stackoverflow.com/q/52450342
tags question: http://stackoverflow.com/q/52537634
tags question: http://stackoverflow.com/q/52499323

http://stackoverflow.com/comment/91910734
type: Comment
type: QuestionComment
has text: Why do you mean by better? What's wrong with lists?
comment on: http://stackoverflow.com/q/52484359
score: 0

http://stackoverflow.com/a/52462923
type: Answer
has comment: http://stackoverflow.com/comment/91868551
has body: It can depends on your docker-compose.yml exact content. See for instance the section "An interactive debugger inside a running container!" of the article "A Simple Recipe for Django Development In Docker (Bonus: Testing with Selenium)" from Adam King. His docker-compose.yml includes: version: "2" services: django: container_name: django_server build: context: . dockerfile: Dockerfile image: docker_tutorial_django stdin_open: true tty: true volumes: - .:/var/www/myproject ports: - "8000:8000" In it, see: stdin_open: true tty: true [Those 2 lines] are important, because they let us run an interactive terminal. Hit ctrl-c to kill the server running in your terminal, and then bring it up in the background with docker-compose up -d. docker ps tells us it’s still running: We need to attach to that running container, in order to see its server output and pdb breakpoints. The command docker attach django_server will present you with a blank line, but if you refresh your web browser, you’ll see the server output. Drop import pdb; pdb.set_trace() in your code and you’ll get the interactive debugger, just like you’re used to.
answers question: http://stackoverflow.com/q/52462866
score: 0
has comment: http://stackoverflow.com/comment/91868490

http://stackoverflow.com/comment/91942691
score: 0
type: AnswerComment
has text: No problem, great you figured it out :)
comment on: http://stackoverflow.com/a/52500581
type: Comment

http://stackoverflow.com/comment/91858618
has text: you can use django-ckeditor
type: QuestionComment
comment on: http://stackoverflow.com/q/52458225
score: 0
type: Comment

http://stackoverflow.com/comment/91836088
type: AnswerComment
score: 0
has text: @Hackerman thanks alot. it worked. problem was with indentation and declaring my list at the wrong place
type: Comment
comment on: http://stackoverflow.com/a/52446461

http://stackoverflow.com/q/52516638
linked to: http://stackoverflow.com/q/27937037
has answer: http://stackoverflow.com/a/52518285
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52516875
has body: I see this has been asked in this site here. Borrowed ideas from that post but doesn't work in my case. I am reading some data from a Excel sheet and trying to convert it into Pandas data frame with column and row index. The 1st row is a year header with Excel and I have tried to make it as a column header by doing df.columns=df.iloc[0] So when i run df.columns, it retruns: Index([None, 2014.0, 2015.0, 2016.0, 2017.0, 2018.0], dtype='object', name=0) My problem now is to convert the column with Month names as row names. I have tried df.set_index('None',inplace=True) But this returns KeyError: 'None' Why can't I call 'None' since this is said to be one of the column names. How do i convert these month names that could be called from for charting to xaxis later? any datetime format? Edit: Adding a sample data here Update: I solved it by df.columns = ['Month', 2014, 2015, 2016, 2017, 2018] and df.drop(df.index[0])
accepted answer: http://stackoverflow.com/a/52518285
has comment: http://stackoverflow.com/comment/91977852
answer count: 4
has answer: http://stackoverflow.com/a/52516907
has comment: http://stackoverflow.com/comment/91977621
tagged with: python
type: AnsweredQuestion
has title: change a specific column into row names in Pandas
possible better answer: http://stackoverflow.com/a/52516776
has comment: http://stackoverflow.com/comment/91973125
has answer: http://stackoverflow.com/a/52516776
type: Question

http://stackoverflow.com/q/52462215
type: AnsweredQuestion
favorite count: 0
accepted answer: http://stackoverflow.com/a/52462336
type: Question
tagged with: python
has title: discord.py - How do I send a message to multiple channels?
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: discord.py
has answer: http://stackoverflow.com/a/52462336
has body: So... I wanted to make an code so it send an message to an specific channel I want so it send this message in chat #logs and #mod-log Heres the code: channel = discord.utils.get(user.server.channels, name=['logs', 'mod-log']) embed = discord.Embed(name="MEMBER_WARNED", description="------------------------------------------------------", color=0xffaa00) embed.set_author(name="MEMBER_WARNED:\nMember Warned") embed.add_field(name="Warned by: ", value="{}".format(author.mention), inline=False) client = bot await client.send_message(channel, embed=embed)

http://stackoverflow.com/q/52557869
has body: The plots below show 1st. a symlog scale (ax.set_xscale("symlog")) and 2nd. a log scale (ax.set_xscale("log") As you can see the 0 does not appear in the logscale but my x values consist of (0, 0.001, 0.01, 0.1, 1, 10, 100). I would like to find a way to have a scale like in the 2nd plot that shows my 0 value as well. A suggested solution is to use symlog. Plot 1 shows the result. 0 is there but the labels around 0 (0,0.001,0.01,0.1) are located all right next to each other. I lost the property of a scale with identical distances between the labels no matter what value they have. Does anyone know how to fix that?
has comment: http://stackoverflow.com/comment/92054660
has comment: http://stackoverflow.com/comment/92054750
answer count: 1
has comment: http://stackoverflow.com/comment/92054509
tagged with: axis-labels
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/52558726
tagged with: plot
type: AnsweredQuestion
has title: How to use a symlog scale with log scale property of identical distance between labels
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/92054860
accepted answer: http://stackoverflow.com/a/52558726

http://stackoverflow.com/q/52490716
tagged with: python
has comment: http://stackoverflow.com/comment/91950334
has comment: http://stackoverflow.com/comment/91950232
type: UnansweredQuestion
tagged with: multithreading
tagged with: selenium
type: Question
has title: How to use Multiprocessing with Selenium in Python
tagged with: python-multiprocessing
has body: I am trying to use multiprocessing using selenium in python. My code is as follows: from selenium import webdriver from multiprocessing import Pool import xlwings as xw driver = webdriver.Chrome('chromedriver.exe') driver.get("https://example.com") wb = xw.Book('my_file.xlsm') sht = wb.sheets["Sheet1"] final_list = [] search = driver.find_element_by_id("ContentPlaceHolder1_txtByName") for item in search: z = item.find_element_by_class_name("valuetext") info = z.find_element_by_tag_name("span") final_list.append(info.text) def automate(num): col = num list_item = final_list[num] sht.range(1, col).value = each if __name__ == '__main__': p = Pool(processes=4) data = p.map(automate,range(1,20)) The issue I'm having is for each of the 4 processes the web page is re-opened again and I don't understand why. If p.map is only targeting the automate function then why is the rest of the code run for every process? I'm still new to multiprocessing so am not sure if that's just how it works.Is there another way to do this to ensure the processes only target the function itself, or is there a way I could use threading?
has answer: http://stackoverflow.com/a/52491247
answer count: 1
score: 0
tagged with: python-multithreading

http://stackoverflow.com/q/52524590
has title: Appending Rows to a data frame
has answer: http://stackoverflow.com/a/52525887
score: 0
answer count: 2
tagged with: pandas
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52524787
type: Question
has body: I am stuck on a simple task. I want to create an empty DataFrame and append rows to it based on a query of another dataset. I have tried the answers here but I am missing something ..beginner Pythoner. Any help would be appreciated. I want to take the top 3 rows of each state and add them into a new dataframe for processing. I tried to append also.. def test(): #get the list of states states_df = census_df.STNAME.unique() population_df = pd.DataFrame() for st in states_df: temp_df = pd.DataFrame(census_df[census_df['STNAME'] == st].nlargest(3,'CENSUS2010POP')) pd.concat([temp_df, population_df], ignore_index = True) return 1

http://stackoverflow.com/q/52527702
type: AnsweredQuestion
has body: I would like to replace multiple strings in a file for example an IP Address and would like to tag them so that any re-occurrence will be marked with the same name. For example, if this is my file: 2018-09-13 19:00:00,317 INFO -util.SSHUtil: Waiting for channel close 2018-09-13 19:00:01,317 INFO -util.SSHUtil: Waiting for channel close 2018-09-13 19:00:01,891 INFO -filters.BasicAuthFilter: Client IP:192.168.100.98 2018-09-13 19:00:01,891 INFO -filters.BasicAuthFilter: Validating token ... 2018-09-13 19:00:01,892 INFO -authentication.Tokenization: Token:192.168.100.98:20180913_183401is present in map 2018-09-13 19:00:01,892 INFO -configure.ConfigStatusCollector: status. 2018-09-13 19:00:01,909 INFO -filters.BasicAuthFilter: Client IP:192.168.100.98 2018-09-13 19:00:01,909 INFO -filters.BasicAuthFilter: Validating token ... 2018-09-13 19:00:01,910 INFO -authentication.Tokenization: Token:192.168.100.98:20180913_183401is present in map 2018-09-13 19:00:01,910 INFO -restadapter.ConfigStatusService: configuration status. 2018-09-13 19:00:01,910 INFO -configure.Collector: Getting configuration status. 2018-09-13 19:00:02,318 INFO -util.SSHUtil: Processing the ssh command execution results standard output. 2018-09-13 19:00:02,318 INFO -util.SSHUtil: Processing the ssh command execution standard error. 2018-09-13 19:00:02,318 INFO -util.SSHUtil: Remote command using SSH execution status: Host : [10.2.251.129] User : [root] Password : [***********] Command : [shell ntpdate -u 132.132.0.88] STATUS : [0] 2018-09-13 19:00:02,318 INFO -util.SSHUtil: STDOUT : [Shell access is granted to root 14 Sep 01:00:01 ntpdate[16063]: adjust time server 132.132.0.88 offset 0.353427 sec ] 2018-09-13 19:00:02,318 INFO -util.SSHUtil: STDERR : [] 2018-09-13 19:00:02,318 INFO -util.SSHUtil: Successfully executed remote command using SSH. 2018-09-13 19:00:02,318 INFO Successfully executed the command on VCenter :10.2.251.129 It should become: 2018-09-13 19:00:00,317 INFO -util.SSHUtil: Waiting for…
has answer: http://stackoverflow.com/a/52528191
type: Question
accepted answer: http://stackoverflow.com/a/52528191
score: 0
answer count: 1
has title: Replace multiple strings in a file by tagging them
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/52469866
has title: Displaying images on Tensorboard (through Keras)
upvote count: 5
accepted answer: http://stackoverflow.com/a/55856716
linked to: http://stackoverflow.com/q/52462058
has comment: http://stackoverflow.com/comment/97024782
has comment: http://stackoverflow.com/comment/98374889
tagged with: keras
has comment: http://stackoverflow.com/comment/93166295
has comment: http://stackoverflow.com/comment/93166226
tagged with: tensorboard
possible better answer: http://stackoverflow.com/a/54968450
downvote count: 0
has body: My X_test are 128x128x3 images and my Y_test are 512x512x3 images. I want to show, after each epoch, how the input (X_test) looked, how the expected output (Y_test) looked, but also how the actual output looked. So far, I've only figured out how to add the first 2 in Tensorboard. Here is the code that calls the Callback: model.fit(X_train, Y_train, epochs=epochs, verbose=2, shuffle=False, validation_data=(X_test, Y_test), batch_size=batch_size, callbacks=get_callbacks()) Here is the Callback's code: import tensorflow as tf from keras.callbacks import Callback from keras.callbacks import TensorBoard import io from PIL import Image from constants import batch_size def get_callbacks(): tbCallBack = TensorBoard(log_dir='./logs', histogram_freq=1, write_graph=True, write_images=True, write_grads=True, batch_size=batch_size) tbi_callback = TensorBoardImage('Image test') return [tbCallBack, tbi_callback] def make_image(tensor): """ Convert an numpy representation image to Image protobuf. Copied from https://github.com/lanpa/tensorboard-pytorch/ """ height, width, channel = tensor.shape print(tensor) image = Image.fromarray(tensor.astype('uint8')) # TODO: maybe float ? output = io.BytesIO() image.save(output, format='JPEG') image_string = output.getvalue() output.close() return tf.Summary.Image(height=height, width=width, colorspace=channel, encoded_image_string=image_string) class TensorBoardImage(Callback): def __init__(self, tag): super().__init__() self.tag = tag def on_epoch_end(self, epoch, logs={}): # Load image img_input = self.validation_data[0][0] # X_train img_valid = self.validation_data[1][0] # Y_train print(self.validation_data[0].shape) # (8, 128, 128, 3) print(self.validation_data[1].shape) # (8, 512, 512, 3) image = make_image(img_input) summary = tf.Summary(value=[tf.Summary.Value(tag=self.tag, image=image)]) writer = tf.summary.FileWriter('./logs') writer.add_summary(summary, epoch) writer.close() image = make_image(img_valid) summary = tf.Summary(value=[…
has answer: http://stackoverflow.com/a/54968450
favorite count: 0
has comment: http://stackoverflow.com/comment/97032365
tagged with: python
has comment: http://stackoverflow.com/comment/97032830
has answer: http://stackoverflow.com/a/55856716
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/98383730
tagged with: tensorflow
type: Question
answer count: 2
score: 5

http://stackoverflow.com/a/52534836
answers question: http://stackoverflow.com/q/52532479
score: 0
has body: The question itself is a little bit too broad and it is hard to answer it without knowing what your trying to do. It seems like that is a basic web application functionality that Django deals with its models and forms. I suggest, first thing first, you go through Django "getting started" tutorial: https://www.djangoproject.com/start/ However I'm going to assume now that you do know about Django basics and that for some reason you do not want to create a form for that functionality. In that case you could add a URL to those &lt;a&gt; tags, each pointing to a view that saves a specific value, for example: def save_positive(request): ... def save_neutral(request): ... def save_negative(request): ... But this seems like bad programming practice to say the least. I strongly recommend you check the tutorial mentioned above, or at least the forms documentation https://docs.djangoproject.com/en/2.1/topics/forms/ Because a form looks like the solution to your problem :)
type: Answer

http://stackoverflow.com/q/52440622
tagged with: aws-glue
upvote count: 3
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/70085377
downvote count: 0
tagged with: pyspark
has body: How can we write user-defined functions in AWS-Glue script using PySpark (Python) on either Dynamic-frame or Data-frame?
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/49179884
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52518259
has title: How to write user-defined function in AWS-Glue Script?
score: 3

http://stackoverflow.com/q/52460604
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52460605
linked to: http://stackoverflow.com/q/13180740
type: UnansweredQuestion
has body: PyPy warning about timeit: (my-pypy-env) $ python -m timeit --setup "from simulation import benchmark" "benchmark()" WARNING: timeit is a very unreliable tool. use perf or something else for real measurements ten loops, average of 7: 106 +- 0.383 msec per loop (using standard deviation) Using perf: (my-pypy-env) $ python -m perf timeit --setup 'from simulation import benchmark' 'benchmark()' Median +- std dev: 97.8 ms +- 2.3 ms
tagged with: python
has title: Why PyPy considers "timeit" as unreliable tool for Python performance measurement?
has comment: http://stackoverflow.com/comment/91863840
type: Question

http://stackoverflow.com/q/52479714
has comment: http://stackoverflow.com/comment/135474143
downvote count: 6
upvote count: 3
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/52479818
answer count: 4
has title: How to sum elements inside a nested list?
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/91900407
has answer: http://stackoverflow.com/a/52481443
has body: So, I have a list that looks something like this [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]], [[19, 20], [21, 22], [23, 24]]] And I want it to look like this [[3, 7, 11], [15, 19, 23], [27, 31, 35], [39, 43, 27]] that is 3 = sum([1, 2]), 7 = sum([3, 4]), .... I have tried nesting for loops but I haven't found anything that got the desired result, does anyone know how I could do this?
has answer: http://stackoverflow.com/a/52479806
type: Question
linked to: http://stackoverflow.com/q/993984
has answer: http://stackoverflow.com/a/76852877
tagged with: sum

http://stackoverflow.com/comment/91822450
comment on: http://stackoverflow.com/a/52439444
type: Comment
has text: updated the answer as requested. But consider the last approach in my answer - that seems to be the easiest and simplest ( unless you plan to have some more sophisticated validation )
score: 1
type: AnswerComment

remote-debugging
tag name: remote-debugging
tags question: http://stackoverflow.com/q/52532802
tags question: http://stackoverflow.com/q/52462866
type: Tag

http://stackoverflow.com/a/67889192
type: Answer
answers question: http://stackoverflow.com/q/52588453
has comment: http://stackoverflow.com/comment/121212590
downvote count: 0
score: 5
has body: the edges of the graph should not overlap Using the connectionstyle parameter to plot arcs with a pre-determined curvature does not reduce edge-edge or node-edge overlaps. With straight edges, overlaps with other plot elements are often inevitable. However, if we are allowed to plot curved edges, we can route each edge such that it avoids other nodes and edges as much as possible. This effect can be achieved by inserting control points into each edge, effectively segmenting each edge into short sub-edges. We can then use the standard Fruchterman-Reingold algorithm (called spring_layout in networkx) to simulate the graph as a system of springs, where all nodes and control points repel each other but connected nodes and control points also attract each other. The positions of the (original) nodes are kept fixed, while we let the positions of the edge control points anneal to their equilibrium position. I have an implementation of this approach here. The code is part of a python network plotting library called netgraph, of which I am the author. netgraph is fully compatible with networkx and igraph Graph objects, so it should be easy and fast to generate good looking graphs. #!/usr/bin/env python import matplotlib.pyplot as plt import networkx as nx from netgraph import Graph # pip install netgraph g = nx.florentine_families_graph() Graph(g, edge_layout='curved') plt.show()
upvote count: 5

http://stackoverflow.com/comment/91998321
has text: Sorry. I sent a message on the way. I added 'width=8' but it doesn't work. As usual the text of the button shows blank.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52529403

http://stackoverflow.com/comment/91918019
type: QuestionComment
comment on: http://stackoverflow.com/q/52488269
has text: Ohhh, I didn't realize it was resetting them! It works when I remove the alice = 0 bob = 0 from the loop!
score: 0
type: Comment

http://stackoverflow.com/q/52563757
has comment: http://stackoverflow.com/comment/92066131
has comment: http://stackoverflow.com/comment/92067212
score: 0
tagged with: sqlite
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92066091
has title: SQLite Copying data to second table from first table
type: Question
has body: I have two tables created from below query in SQLite: CREATE TABLE people ( id integer unique primary key, first_name text, middle_name text, last_name text, email text, phone text ); CREATE TABLE companies ( id integer unique primary key, name text, url text, contact integer, FOREIGN KEY(contact) REFERENCES people(id) ); I have all the data available in the first table, but I want to popup id in second table same as id in the first table.name in the companies table is concatenated string of first_name text,middle_name,last_name in people table. I want something like "UPDATE companies SET contact = (SELECT people.id FROM people WHERE companies.name = people.first_name || "," || "people.second_name"; it will be great if I can show the string in people table is the subset of string in companies table I am a beginner in python and SQlite both.

http://stackoverflow.com/a/52525146
type: Answer
answers question: http://stackoverflow.com/q/52524500
has body: Try: df.replace(to_replace=r'[\n\r\t]', value='', regex=True, inplace=True) This instruction replaces each \n, \r and Tab with nothing. Due to inplace argument, no need to substitute the result to df again. Alternative: Use to_replace=r'\s' to eliminate also spaces, maybe in selected columns only.
score: 0

http://stackoverflow.com/q/52478604
has answer: http://stackoverflow.com/a/52478654
score: 0
has body: i want to calculate frequency of each unique word from a given list. for eg. Input list = ['kasol', 'kasol', 'manali', 'delhi', 'delhi', 'manali, 'kasol'] Output = kasol - 3 manali - 2 delhi - 2 i tried def frequency(a, x): count = 0 for i in a: if i == x: count += 1 return count but it is not working.
type: Question
has title: Frequency of each string from given list
linked to: http://stackoverflow.com/q/2600191
duplicate of: http://stackoverflow.com/q/2600191
answer count: 1
tagged with: string
type: UnansweredQuestion
tagged with: count
tagged with: python

http://stackoverflow.com/comment/108036571
score: 1
has text: This didn't work for me: Exmaple: 'Porción de espacio'
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52431620

http://stackoverflow.com/comment/92182686
score: 0
comment on: http://stackoverflow.com/q/52482311
type: Comment
type: QuestionComment
has text: and on my machine , python3.7 also I get because of this `sys.stdout` overwrite the `TypeError`

http://stackoverflow.com/q/52530300
tagged with: python
linked to: http://stackoverflow.com/q/48881228
type: AnsweredQuestion
score: 3
tagged with: azure-blob-storage
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52530385
accepted answer: http://stackoverflow.com/a/52530385
has title: How can I read a text file from Azure blob storage directly without downloading it to a local file(using python)?
has comment: http://stackoverflow.com/comment/91999840
tagged with: azure
has comment: http://stackoverflow.com/comment/91999922
answer count: 1
downvote count: 0
has body: How can i reads a text blob in Azure without downloading it? I am able to download the file and then read it but, i prefer it to be read without downloading. print("\nList blobs in the container") generator = block_blob_service.list_blobs(container_name) for blob1 in generator: print("\t Blob name: " + blob.name) Is there any operation in 'blob1' object, which would allow me to read the text file directly.(like blob1.read or blob1.text or something like this)?
favorite count: 0

http://stackoverflow.com/comment/92100609
comment on: http://stackoverflow.com/a/52582767
type: Comment
has text: @Hirschy running for me
score: 0
type: AnswerComment

http://stackoverflow.com/a/52548824
answers question: http://stackoverflow.com/q/52548555
score: 0
type: Answer
has body: In addition to already good answers, this is what I would use: def sum_and_average(test_data): data_average = sum(test_data) / len(test_data) data_sum = (sum(test_data)) Missing Parenthesis in your code. return(data_sum, data_average) This returns two values - sum and average. If you use "and" it would return the sum and not the average. test_data = [10, 23.4, 45.6, 98.7, 34.3] (data_sum, data_average) = sum_and_average(test_data) print("The sum of the data is {:.3f} and the average is {:.3f}".format( data_sum, data_average )) You have to note that the order of def and main does not matter in this particular case.

http://stackoverflow.com/comment/91970966
has text: To *what* else?
comment on: http://stackoverflow.com/q/52515594
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/52586108
score: 1
has comment: http://stackoverflow.com/comment/92107416
has comment: http://stackoverflow.com/comment/92107245
upvote count: 1
has body: I'm working on a project which requires me to find sum partitions of a certain value(required_reduction). I have to clear the total_parts list from sublists if any which has any value other than 2. index of combs's sublists. Example: required_reduction = 4 combs = [[2,1],[3,2]] total_parts = [[1,1,1,1],[1,1,2],[2,2],[1,3]] I can't use [1,3] because it has "3" in it which is not a value contained in 2.elemnt of "combs" sublists which are 1 and 2. "partition" function was taken from stackoverflow, I'm trying to construct rest. import numpy as np required_reduction = 16 combs = [[2,4],[3,5],[4,8],[5,13],[8,15],[10,18]] def partition(number): answer = set() answer.add((number, )) for x in range(1, number): for y in partition(number - x): answer.add(tuple(sorted((x, ) + y))) return answer total_parts = partition(required_reduction) total_parts = list(total_parts) def applicable_partitions(total_partitions, combinations): selections = [0] for _ in range(0, len(combinations) - 1): selections.append(combinations[_][1]) del selections[0] possible_partitions = np.array(np.zeros(1,int)) for i in range(0, len(total_partitions)-1): for j in range(0, len(total_partitions[i]) -1): for k in range(0, len(selections)-1): if total_partitions[i][j] == selections[k]: continue else: total_partitions.remove(total_partitions[i]) return total_partitions print(applicable_partitions(total_parts, combs)) I am getting this error : if total_partitions[i][j] == selections[k]: IndexError: tuple index out of range. Can someone see why ?
type: Question
tagged with: math
downvote count: 0
has title: How to fix this error while clearing subset sums?
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/comment/92115148
type: AnswerComment
comment on: http://stackoverflow.com/a/52586513
score: 0
type: Comment
has text: @Matthieu Because i using fiddler to catch post request. i think today is unfortunate day,i cannot get a cookies same as browser.

http://stackoverflow.com/comment/99114819
comment on: http://stackoverflow.com/a/52487800
type: Comment
has text: Rule of a thumb: expect generic types, return specific types. This gives users of your functions and classes the biggest flexibility and safety.
score: 90
type: AnswerComment

http://stackoverflow.com/q/52466479
has comment: http://stackoverflow.com/comment/91874648
has comment: http://stackoverflow.com/comment/91875048
has title: Is there a way to have a fair implementation of Brian Kernighan's algorithm for counting ones in Python?
tagged with: built-in
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91878110
has body: I was surprised by the big difference in performance of an implementation of Brian Kernighan's algorithm for counting ones in python when compared to a built in function for counting ones in a string. Converting to a String an then counting ones seemed to me like a bad idea. Now what seems like a bad idea is looping and not using built-in functions when looking for performance. import random x = random.randint(0,1&lt;&lt;1000000) def count_ones(number): c = 0 while(number !=0 ): number = number&amp;(number-1) c = c + 1 return c %timeit bin(x).count("1") %timeit count_ones(x) 5.09 ms ± 20 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 25 s ± 544 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
favorite count: 0
has comment: http://stackoverflow.com/comment/91875058
linked to: http://stackoverflow.com/q/9829578
has answer: http://stackoverflow.com/a/52472501
has comment: http://stackoverflow.com/comment/91877207
has comment: http://stackoverflow.com/comment/91875014
tagged with: python
has comment: http://stackoverflow.com/comment/91874823
score: 2
has comment: http://stackoverflow.com/comment/91874749
has comment: http://stackoverflow.com/comment/91875161
has comment: http://stackoverflow.com/comment/91874716
upvote count: 2
has comment: http://stackoverflow.com/comment/91874762
type: UnansweredQuestion
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/91874865
tagged with: performance
has comment: http://stackoverflow.com/comment/91874861
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91876801
has comment: http://stackoverflow.com/comment/91874960

http://stackoverflow.com/comment/91910867
type: QuestionComment
comment on: http://stackoverflow.com/q/52473158
has text: Verify that the role "Trust Relationships" includes lambda. It should show: `The identity provider(s) lambda.amazonaws.com`
score: 0
type: Comment

http://stackoverflow.com/q/52473178
has comment: http://stackoverflow.com/comment/91907595
has body: I am trying to find a way to compare two dictionaries without any library but the data is nested and keys are not ordered too.The data is dynamic in nature meaning the the keys in dictionary will change and nesting also. I am not able to parse the dictionary if the nesting is not fixed. Example data: source_data = { "name":"Kaleigh", "username":"Kaleigh60", "email":"Kaleigh6047@gmail.com", "address":{ "street":"MyahCourse","suite":"Apt.657","city":"Boyerberg","zipcode":"66413-8920", "geo":{"lat":"-44.6203","lng":"16.7454"} }, "website":"megane.biz", "friends":[ {"name":"Little-Reinger","catchPhrase":"Enhancedregionalemulation"}, {"name":"Big-Reinger","catchPhrase":"emulation"} ], "Numbers":[1,2,3,4] } destination_data = { "name":"Kaligh", "username": "Kaleigh60", "email": "Kaleigh6047@gmail.com", "address":{ "street":"GoldCourse", "suite":"Apt.657", "city":"Boyerberg", "zipcode":"66413-8920", "geo":{"lat":"-44.6203","lng":"16.7454"} }, "website":"megane.biz", "friends":[ {"name":"Reinger", "catchPhrase":"Enhancedregionalemulation"}, {"name":"Big-Reinger","catchPhrase":"emulation"} ], "Numbers":[4,2,1,5] } I am not able to understand how can I parse the and compare the dictionary? Expected Output: keys whose value is different and values as list [srcvalue,destvalue] e.g. { "friends[1].name": ["Big-Reinger", "Bigger-Reinger"], "name":["Kaleigh","Kaligh"], "Numbers[2]":[3,1], "Numbers[3]":[4,5], "friends[0].name":["Little-Reinger","Reinger"], "Numbers[0]":[1,4], "address.street":["MyahCourse","GoldCourse"] } Thanks in advance
has answer: http://stackoverflow.com/a/52473251
has comment: http://stackoverflow.com/comment/91888842
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91891162
linked to: http://stackoverflow.com/q/4527942
has title: Python3: How to compare data of two dictionaries which is nested and dynamic in nature?
score: 0
has comment: http://stackoverflow.com/comment/91888825
tagged with: nested
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91888111
has comment: http://stackoverflow.com/comment/91891182
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52473289
has comment: http://stackoverflow.com/comment/91888299
type: UnansweredQuestion

http://stackoverflow.com/q/52460724
type: Question
tagged with: dataframe
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52460828
downvote count: 0
has title: How to join two dataframes by more than one key?
favorite count: 0
has answer: http://stackoverflow.com/a/52460757
tagged with: python
has body: I need to join column 'rating' from dataframe df_original - by keys, 'userId' and 'movieId' - with dataframe df_workspace. > Dataframe df_workspace userId movieId cluster 0 1 2 2 1 1 29 2 2 1 260 2 3 1 589 2 4 1 653 2 5 1 919 2 6 1 1009 2 7 1 1196 2 8 1 1198 2 9 1 1200 2 10 1 1201 2 11 1 1291 2 12 1 1304 2 13 1 1374 2 14 1 1525 2 15 1 1750 2 16 1 1920 2 17 1 1967 2 18 1 2021 2 19 1 2138 2 20 1 2140 2 21 1 2143 2 22 1 2173 2 23 1 2193 2 24 1 2628 2 25 1 2761 2 26 1 2872 2 27 1 3000 2 28 1 3030 2 29 1 3037 2 > Dataframe df_original userId movieId title \ 0 1 2 Jumanji (1995) 1 1 29 City of Lost Children, The (CitÃ© des enfants ... 2 1 32 Twelve Monkeys (a.k.a. 12 Monkeys) (1995) 3 1 47 Seven (a.k.a. Se7en) (1995) 4 1 50 Usual Suspects, The (1995) 5 1 112 Rumble in the Bronx (Hont faan kui) (1995) 6 1 151 Rob Roy (1995) 7 1 223 Clerks (1994) 8 1 253 Interview with the Vampire: The Vampire Chroni... 9 1 260 Star Wars: Episode IV - A New Hope (1977) genres rating timestamp 0 Adventure|Children|Fantasy 3.5 2005-04-02 23:53:47.000 1 Adventure|Drama|Fantasy|Mystery|Sci-Fi 3.5 2005-04-02 23:31:16.000 2 Mystery|Sci-Fi|Thriller 3.5 2005-04-02 23:33:39.000 3 Mystery|Thriller 3.5 2005-04-02 23:32:07.000 4 Crime|Mystery|Thriller 3.5 2005-04-02 23:29:40.000 5 Action|Adventure|Comedy|Crime 3.5 2004-09-10 03:09:00.000 6 Action|Drama|Romance|War 4.0 2004-09-10 03:08:54.000 7 Comedy 4.0 2005-04-02 23:46:13.000 8 Drama|Horror 4.0 2005-04-02 23:35:40.000 9 Action|Adventure|Sci-Fi 4.0 2005-04-02 23:33:46.000 > OUTPUT EXAMPLE userId movieId cluster rating 0 1 2 2 3.5 1 1 29 2 4.0 2 1 260 2 3.5 3 1 589 2 2.0 4 1 653 2 5.0 5 1 919 2 4.5 I try to use join but i dont understand how to use more than one key.
possible better answer: http://stackoverflow.com/a/52460757
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52460828

http://stackoverflow.com/a/52451643
has comment: http://stackoverflow.com/comment/92313483
score: 0
has body: If lever of programming beginner, you will find useful to also look at these concepts, they ll be handy in your programmer future: map, lambda and generators. You could define simple functions using lambda functions. As: in_circle = lambda (x, y): True if Math.sqrt( Math.pow(x,2) + Math.pow(y,2) ) &lt; 1 else False # assuming circle has center 0, 0 and radius 1 2. and then map the function to a list of points: map( in_circle, your_list) Note that in lambda the syntax (x, y) is because you are passing a tuple as one argument, and your list is formed like: your_list = [(0,1),(0, 0.5), (0.3, 0.4) ...] 3. Instead of list, you can also use a generator, a structure very handy in iterations if you don't need to use again your list. syntax is similar (note the brakets ! ( VS [ ) your_point = [ (random.random(), random.random()) for i in range(n) ] # list comprehension your_point = ( (random.random(), random.random()) for i in range(n) ) # generator 4. So you could generate a list of N booleans like: n = 10000 your_point = ( (random.random(), random.random()) for i in range(n) ) bool_list = map( in_circle, your_list) For your curiosity in difference between lamdba and regular functions, see also: what is the difference for python between lambda and regular function? For your interest in generators VS lists comprehension: Generator Expressions vs. List Comprehension
answers question: http://stackoverflow.com/q/52451039
type: Answer

http://stackoverflow.com/comment/119700795
type: QuestionComment
score: 1
has text: worked here, should post it as the answer
comment on: http://stackoverflow.com/q/52466582
type: Comment

http://stackoverflow.com/a/52465636
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52465370
answers question: http://stackoverflow.com/q/52465370
type: AcceptedAnswer
downvote count: 0
score: 1
has body: i suggest use, df = df.values df now becomes the numpy ndarray: this will effectively remove the index column and the column names, so what you would do is as follows y_train=train'csMPa'.values x_train=train.drop(["csMPa"],axis=1).values now i am not saying that this will improve your accuracy, but as you asked it will remove the index column, this might help your situation and anyways passing the data this way is better NOTE: Accuracy as a metric for regression is not right, accuracy is better suited for classification, you shouldnt set the metric as accuracy, you may use something like MSAE, you may refer to https://medium.com/usf-msds/choosing-the-right-metric-for-machine-learning-models-part-1-a99d7d7414e4 Focus on minimizing the error, rather than maximizing the accuracy, you maximize accuracy in classification, not in regression

http://stackoverflow.com/comment/91989942
score: 0
type: Comment
has text: @zvone Hi, thanks for the answer, the important part of this, is that i have a video and a image of that video, and i need to know in what time that happen; like the image is in the second 10 of the video.
type: QuestionComment
comment on: http://stackoverflow.com/q/52524816

http://stackoverflow.com/a/72976251
has body: pip install geopandas==0.8.1 fixed this issue for me.
has comment: http://stackoverflow.com/comment/131346230
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52528889
answers question: http://stackoverflow.com/q/52528889
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/52512936
type: UnansweredQuestion
score: 1
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/57500661
has comment: http://stackoverflow.com/comment/91965976
has title: Python OpenCV VideoCapture read() cannot read a frame
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has body: I'm trying to capture image from usb camera, but cannot read a frame from an usb camera. when I run this code in python 3.6.5 cv2.VideoCapture(1).read() result [ WARN:0] videoio(MSMF): OnReadSample() is called with error status: -2147024809 [ WARN:0] videoio(MSMF): async ReadSample() call is failed with error status: -2147024809 [ WARN:1] videoio(MSMF): can't grab frame. Error: -2147024809 (False,None) I've also tried with other usb camera (device 0). It can read a frame. But device 1 cannot read a frame.
downvote count: 0

http://stackoverflow.com/comment/121360199
type: Comment
comment on: http://stackoverflow.com/a/61922605
score: 1
has text: This answer produces a string representation that uses much more digits than the IEEE standard requires (wasting space by more than a factor of 2). See my answer for a string representation that produces the **minimal** literal to represent a float.
type: AnswerComment

http://stackoverflow.com/a/52493234
type: AcceptedAnswer
upvote count: 3
has body: You can go through Pandas documentation for the details: "pandas.Timestamp" is a replacement for python datetime.datetime for Padas usage. Timestamp is the pandas equivalent of python’s Datetime and is interchangeable with it in most cases. It’s the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas. Notes There are essentially three calling conventions for the constructor. The primary form accepts four parameters. They can be passed by position or keyword. The other two forms mimic the parameters from datetime.datetime. They can be passed by either position or keyword, but not both mixed together. Timedeltas are differences in times, expressed in difference units, e.g. days, hours, minutes, seconds. They can be both positive and negative. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner, but allows compatibility with np.timedelta64 types as well as a host of custom representation, parsing, and attributes. I would say as pandas works better with Time Series data hence its been a kind of warper on the original built-in datetime module. The weaknesses of Python's datetime format inspired the NumPy team to add a set of native time series data type to NumPy. The datetime64 dtype encodes dates as 64-bit integers, and thus allows arrays of dates to be represented very compactly.
has comment: http://stackoverflow.com/comment/91932635
has comment: http://stackoverflow.com/comment/91931151
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91927357
score: 3
accepted answer of: http://stackoverflow.com/q/52492996
answers question: http://stackoverflow.com/q/52492996
has comment: http://stackoverflow.com/comment/91927093

http://stackoverflow.com/comment/91932434
comment on: http://stackoverflow.com/q/52495742
has text: Here I was trying to install a screenshot app by `sudo apt-get install gnome-screenshot` but it gave me this error. What's funny is that the app got installed and it functions properly but while installing I got this error.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92021892
has text: Please add some explanation to your answer. A code-only answer might be useful, but it is a lot more useful if you explain what it does and why it answers the OP's question. Thanks!
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52533202

http://stackoverflow.com/a/53477778
upvote count: 3
score: 3
has body: Had the same issue when going through the scikit-learn.org website: &gt;&gt;&gt; clf.set_params(kernel='rbf', gamma='scale').fit(X,y) Output (Shrinked): ... File "sklearn/svm/libsvm.pyx", line 58, in sklearn.svm.libsvm.fit TypeError: must be real number, not str Had to check the 'type' for gamma &gt;&gt;&gt; type(clf.gamma) &lt;class 'float'&gt; Passing a string ('scale') wouldn't have worked anyways. The best option is to pass it a float value (gamma=0.001)
downvote count: 0
answers question: http://stackoverflow.com/q/52582796
type: Answer

http://stackoverflow.com/a/52498899
has comment: http://stackoverflow.com/comment/122311774
has comment: http://stackoverflow.com/comment/91939119
has body: This is most likely a bug in pandas. See this question for suggested solution: No easy way out of this but to delete that row by reading the xlsx in again. Also there is a link into the GitHub issue, addressing this topic. So I made this workaround, it might be helpful for you: df = pd.read_excel('/home/teoretic/test.xlsx', index_col=0) df = df.drop(np.nan) # &lt;== dropping an empty row rename_dct = dict.fromkeys(df.loc[:,df.columns.str.contains('^Unnamed')], '') df = df.rename(columns=rename_dct) # &lt;== renaming 'Unnamed' columns to blank space writer = pd.ExcelWriter('/home/teoretic/test_new.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='test1') writer.close() This is an output file:
has comment: http://stackoverflow.com/comment/91941323
has comment: http://stackoverflow.com/comment/114605774
score: 5
has comment: http://stackoverflow.com/comment/97075108
type: AcceptedAnswer
upvote count: 6
answers question: http://stackoverflow.com/q/52497554
has comment: http://stackoverflow.com/comment/97062808
accepted answer of: http://stackoverflow.com/q/52497554
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91939362

http://stackoverflow.com/a/65091225
answers question: http://stackoverflow.com/q/52523419
type: Answer
score: 1
upvote count: 1
has body: from django.http import JsonResponse from csv import reader from django.contrib.auth.models import User def userdata(request): with open('templates/csv/your_file.csv', 'r') as csv_file: csvf = reader(csv_file) data = [] for username, password, *__ in csvf: user = User(username=username) user.set_password(password) data.append(user) User.objects.bulk_create(data) return JsonResponse('user csv is now working', safe=False) then in your urls.py path('userdata/', userdata, name='userdata') ##just redirect to the url and all the data will be pushed to the database
downvote count: 0

http://stackoverflow.com/comment/91868655
score: 1
type: AnswerComment
type: Comment
has text: Thanks @serv-inc. Yes, the python3 installation has NumPy installed. Most solutions out there seem to refer to /usr/bin/python but for mac it would be /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 etc, which caused me to second guess my path obtained by `which python3`. Thanks again for your help and pointing me to the document that indicates the need for a clean R session.
comment on: http://stackoverflow.com/a/52462957

http://stackoverflow.com/comment/92059916
has text: @stovfl I get back a 400 (bad request) with that accepted answer.. {"status":"FAILURE","error":[{"code":"5004","name":"General Error","severity":"3","message":"Error Occurred During the operation","details":{"5004":"General Error null"}}]} {'Connection': 'keep-alive', 'X-Powered-By': 'Undertow/1', 'Server': 'WildFly/9', 'Content-Length': '172', 'Content-Type': 'application/json;charset=UTF-8', 'X-Application-Context': 'application:9090', 'Date': 'Fri, 28 Sep 2018 17:57:57 GMT'}
comment on: http://stackoverflow.com/q/52560061
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52508653
upvote count: 1
type: AcceptedAnswer
has body: You can just use the axes to create a pygame.math.Vector2 instance and then call its as_polar method to get the angle (see https://en.wikipedia.org/wiki/Polar_coordinates). You can map the angle to 0-360 degrees in this way: How to map atan2() to degrees 0-360 import pygame as pg from pygame.math import Vector2 def main(): pg.init() screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() player_img = pg.Surface((42, 70), pg.SRCALPHA) pg.draw.polygon(player_img, pg.Color('dodgerblue1'), [(0, 70), (21, 2), (42, 70)]) player_rect = player_img.get_rect(center=screen.get_rect().center) joysticks = [pg.joystick.Joystick(x) for x in range(pg.joystick.get_count())] for joystick in joysticks: joystick.init() while True: for event in pg.event.get(): if event.type == pg.QUIT: return if len(joysticks) &gt; 0: # At least one joystick. # Use the stick axes to create a vector. vec = Vector2(joysticks[0].get_axis(0), joysticks[0].get_axis(1)) radius, angle = vec.as_polar() # angle is between -180 and 180. # Map the angle that as_polar returns to 0-360 with 0 pointing up. adjusted_angle = (angle+90) % 360 pg.display.set_caption( 'radius {:.2f} angle {:.2f} adjusted angle {:.2f}'.format( radius, angle, adjusted_angle)) # Rotate the image and get a new rect. player_rotated = pg.transform.rotozoom(player_img, -adjusted_angle, 1) player_rect = player_rotated.get_rect(center=player_rect.center) screen.fill((30, 30, 30)) screen.blit(player_rotated, player_rect) pg.display.flip() clock.tick(60) if __name__ == '__main__': main() pg.quit()
type: Answer
accepted answer of: http://stackoverflow.com/q/52504266
downvote count: 0
answers question: http://stackoverflow.com/q/52504266
score: 1

http://stackoverflow.com/comment/91902033
has text: https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python Check this link
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52480275

http://stackoverflow.com/q/52497570
has answer: http://stackoverflow.com/a/52498814
score: 0
has title: Creating a pandas.Series in the latest version of python pandas doesn't work in Matlab
tagged with: pandas
answer count: 1
tagged with: python
has body: I am calling several python libraries in Matlab and am now having trouble using the latest version of pandas (ver 0.23.x) https://pandas.pydata.org/ . Conversely, pandas 0.22.x works fine. Note that the problem doesn't exist in python. To reproduce: % set desired python environment pyversion(pypath) % try to create a pandas series py.pandas.Series(1) Error using py.pandas.Series Class 'py.pandas.core.series.Series' is not allowed to define a 'cat' method. Has anyone experienced this? I noticed that pandas has moved the CategoricalAccessor (which 'cat' refers to) from pandas.core.series.CategoricalAccessor to pandas.core.arrays.categorical.CategoricalAccessor. Maybe this is related? Any help on this would be appreciated.
tagged with: matlab
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/99933705
comment on: http://stackoverflow.com/q/52510620
type: Comment
has text: @jmh, I have added my vagrant file path as mentioned, but it is not showing in the add interpreter dropdown..
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92092855
score: 0
has text: Thanks for that - but why should I have to put in **anything** for the end of the line - why can't it just print out the file "as is" with the newline character being considered both part of and the end of a given line? Real pain about Python2/3 - the author **specifically** said that he was going to use 3!!!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52578818

http://stackoverflow.com/q/52447536
type: Question
has comment: http://stackoverflow.com/comment/91838416
has comment: http://stackoverflow.com/comment/91839643
has comment: http://stackoverflow.com/comment/91837990
has comment: http://stackoverflow.com/comment/91838491
has body: import re from docx import Document file1="" document = Document(filename) for p in document.paragraphs: file1=(file1 + p.text) print(file1) pattern=r"""B.*?A""" searchObj=re.search(pattern, file1, re.M|re.I) if searchObj: print("\n" + searchObj.group()) else: print("\n No match") File1 is essentially: ...B...A... A Word .DOCX file is read using docx. Its contents are stored in a string. Then an attempt is made to find a specific pattern inside this string. The attempt fails (no match) unless you copy and paste the exact string from the command window (e.g. if you type A into the Python script then no match, but if you copy and paste A from CMD into the Python script, then the match succeeds). Any help would be greatly appreciated. OS: Windows 10 pro Editor: Brackets 1.13 Python: 3.7.0 Docx: 0.8.7
has title: Python regex not matching unless string is copied and pasted
has comment: http://stackoverflow.com/comment/91838000
favorite count: 0
tagged with: http://stackoverflow.com/tag/docx
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91839064
tagged with: regex
has comment: http://stackoverflow.com/comment/91838657
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/91838101
has comment: http://stackoverflow.com/comment/91839389
has comment: http://stackoverflow.com/comment/91837986
has comment: http://stackoverflow.com/comment/91840123
downvote count: 1

http://stackoverflow.com/comment/92080010
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52519307
type: QuestionComment
has text: What is the code that creates session.graph? That's where the tensor in question is being created. Can you paste that code or relevant lines of that code.

http://stackoverflow.com/comment/92064634
has text: Sorry. Is that better? Just so I know for future reference.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52562991

http://stackoverflow.com/q/52526343
accepted answer: http://stackoverflow.com/a/52527362
has comment: http://stackoverflow.com/comment/91993941
type: AnsweredQuestion
has title: Why is my function returning error message: 'wordlist is not defined
has body: When running this program I get this error message: NameError: name 'wordList' is not defined. Can't figure out why. Thanks. import random def main(): def getRandomWord(wordList): wordIndex = random.randint(0, len(wordList) -1) return wordList[wordIndex] words = "Harry John Paul Jane Sue Frank Julie Tom Alice Sam".split() secretWord = getRandomWord(words) print("Welcome to You Bet Your Life with Groucho\n") print("Say the secret word and win a thousand dollars!") your_word = input("What is your guess for the secret word? ") if your_word == secretWord: print("Congratulations you are correct. The secrt word is", secretWord) print("and you win $1000 dollars !") else: print("Sorry, that is not the secret word.") playAgain = True wordList = secretWord playAgain = input("Do you want to play again? (yes or y) to continue") if playAgain == "Yes" or playAgain == "y": getRandomWord(wordList) else: print("Ok. Goodbye.") if name == 'main': main()
type: Question
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/91992901
has comment: http://stackoverflow.com/comment/91992595
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91992549
has answer: http://stackoverflow.com/a/52527362

http://stackoverflow.com/comment/91819378
type: Comment
score: 1
has text: thanks .. I will try it and inform you back
type: AnswerComment
comment on: http://stackoverflow.com/a/52437925

http://stackoverflow.com/a/52504535
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52504347
type: Answer
has body: I am not sure if this question is opinion based, but I have a feeling the general agreement would be this is a good idea, in general. You state the benefits yourself, not to mention the ability to generalize code etc. I would venture this is not common practice in Python as the language itself is not very restrictive. In addition, the variable is already called url - that is pretty self explanatory. You could argue you might have something called json_response or the like, and you expect it to be a url, and your method would certainly make it clear, but since Python encourages duck typing, the code usage often gives this hint anyway, and using type aliasing will be just extra safety for an inconsiderate user. It really goes down just to common practices, with no good "do that!" explanation. Final point - type aliasing, in a sense, is the most primitive version of object oriented programming. You are making it clear what properties you are expecting of this object, in this case the string should be a valid URL.

http://stackoverflow.com/q/52451441
has title: Drawing with a brush
accepted answer: http://stackoverflow.com/a/52452656
tagged with: draw
type: Question
score: -1
has answer: http://stackoverflow.com/a/52452656
tagged with: user-interface
answer count: 1
has body: I need help with the implementation of the brush on PyQt5 I already have some event code for the mouse: def mousePressEvent(self, event): if event.button() and event.button() == Qt.LeftButton: self.lastPoint = event.pos() self.scribbling = True def mouseMoveEvent(self, event): if (event.buttons() &amp; Qt.LeftButton) and self.scribbling: self.drawLineTo(event.pos()) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton and self.scribbling: self.drawLineTo(event.pos()) self.scribbling = False Inside of which the brush drawing function is declared: def drawLineTo(self, endPoint): painter = QPainter(self.image) painter.setPen(QPen(self.myPenColor, self.myPenWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(self.lastPoint, endPoint) self.modified = True rad = self.myPenWidth / 2 + 2 self.update(QRect(self.lastPoint, endPoint).normalized().adjusted(-rad, -rad, +rad, +rad)) self.lastPoint = QPoint(endPoint) But the main problem is that this function is declared in the events themselves. Therefore, drawing goes immediately, and I can not add other tools. Because together with them the "pencil" will constantly be drawn. But I need to somehow pull out the function from there and assign it to the corresponding button. To include only by clicking on this button. Let's say I have some toolbar: toolbar = self.addToolBar('Инструменты') toolbar.addAction(self.pen) For which there is an action: self.pen = QAction(QIcon('Image/pen.png'), 'Pencil', self) self.pen.triggered.connect(self. ) How would I do so in the "triggered.connect" assign the drawing function, and that it works only when the button is clicked. Maybe there are some bonds for this, like in tkinter, in the similarity: def draw_pen(self): self.parent.config(cursor="arrow") self.parent.unbind("&lt;Button-1&gt;") self.parent.unbind("&lt;Motion&gt;") self.parent.bind("&lt;ButtonPress-1&gt;", self.button_press) self.parent.bind('&lt;B1-Motion&gt;', self.draw_pencil_move) self.parent.bind('&l…
favorite count: 0
tagged with: python
downvote count: 1
tagged with: drawing
type: AnsweredQuestion
upvote count: 0
tagged with: pyqt5

http://stackoverflow.com/a/52460214
type: Answer
answers question: http://stackoverflow.com/q/52460145
has body: Many Modules (probably including opencv-contrib-python) are not yet updated to work with python3.7. so either downgrade or use an alternative library.
score: 0

http://stackoverflow.com/q/52527978
has comment: http://stackoverflow.com/comment/91995617
linked to: http://stackoverflow.com/q/31593201
upvote count: 1
has comment: http://stackoverflow.com/comment/91995887
has body: Why does the index seem to get appended to the first column of a .loc boolean selected row of a dataframe? Dataframe: date price 0 20180926 100 1 20180925 99 2 20180924 98 3 20180923 97 Code: import pandas as pd d = {'date': ['20180926', '20180925','20180924','20180923'], 'price': [100,99,98,97]} df = pd.DataFrame(d) a = df.loc[df['date'] == '20180924'] print(a['date']) Yields: 2 20180924 Name: date, dtype: object The "2" index seems to be automatically appended to the front of the 'date' field. Whereas: b=a.iloc[0]['date'] print(b) Yields: 20180924 I expected both methods to yield the same result as 'b'.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52528152
answer count: 2
has answer: http://stackoverflow.com/a/52528048
tagged with: pandas
has title: Pandas Dataframe .loc Boolean Attaching Index to First Column
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91995641
tagged with: python

http://stackoverflow.com/comment/92049932
type: AnswerComment
comment on: http://stackoverflow.com/a/52484156
type: Comment
has text: @fronsacqc Not sure if that is possible within the same repo: you would need a dedicated PR repo for that, where you accept your PR in a master branch and view them in the GitHub Pages associated to that dedicated repo. And then, upon review, merge that master branch of that dedicated repo to your actual target repo.
score: 0

http://stackoverflow.com/a/52501866
has comment: http://stackoverflow.com/comment/91945176
has comment: http://stackoverflow.com/comment/91945076
upvote count: 2
has body: In this particular case you are passing the variable in a wrong way. b64encode(b'credentails') means encode the bytes array [c, r, e, d, e, n, t, i, a, l, s]. Use it like that: credentials = b"username:password" userAndPass = b64encode(credentails).decode("ascii") EDIT: In case you would like to obtain the credentials differently: credentials = somehow_get_credentials_as_string() bytes_credentials = credentials.encode('utf-8') # or whatever the encoding is userAndPass = b64encode(bytes_credentials).decode("ascii")
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91945781
answers question: http://stackoverflow.com/q/52501609

http://stackoverflow.com/comment/91810153
score: 0
type: AnswerComment
has text: you sir are a genious! Works like a charm!
comment on: http://stackoverflow.com/a/52433075
type: Comment

http://stackoverflow.com/a/52521997
answers question: http://stackoverflow.com/q/52498042
downvote count: 1
type: Answer
has body: async_timeout module originally developed for aiohttp may be exact thing you need. It's traceback contains line which caused timeout. Installation: pip install async_timeout Usage: import asyncio from async_timeout import timeout async def main(): with timeout(1.5) as t: await asyncio.sleep(1) # first await asyncio.sleep(1) # second await asyncio.sleep(1) # third print('not timeout') if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) Output: Traceback (most recent call last): File "C:\Users\gmn\main.py", line 74, in main await asyncio.sleep(1) # second File "C:\Users\gmn\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py", line 564, in sleep return await future concurrent.futures._base.CancelledError During handling of the above exception, another exception occurred: ... Second and third lines here tell you place where timeout happened: File "C:\Users\gmn\main.py", line 74, in main await asyncio.sleep(1) # second
has comment: http://stackoverflow.com/comment/91984289
upvote count: 0
has comment: http://stackoverflow.com/comment/91985603
has comment: http://stackoverflow.com/comment/91986144
has comment: http://stackoverflow.com/comment/91987791
has comment: http://stackoverflow.com/comment/91984697
score: -1

http://stackoverflow.com/q/52496366
has body: I have an application whose backend is written using django and python. I want to implement auto logout feature in my applcation. For this , I used following django built-in features : SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 40 SESSION_SAVE_EVERY_REQUEST = True I have also used LOGOUT_REDIRECT_URL to redirect the page after logout. But this doesn't help. After 40 seconds, logout happens but it is not visible in frontend, login page comes only if the user refreshes the tab or makes any request in the tab. If I close the browser and open it again , the home page appears with no data as the data are user specific . and if refresh is done of tab is done , the tab is redirected to login page. I want to achieve 2 scenarios: If the auto log happens the user should be automatically redirected to login page. If the user closes the browser window and opens it again then user should be displayed the login page of the application. Any suggestions on how to achieve these scenarios ? Any help would be appreciated. Thank you.
tagged with: logout
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django auto logout and page redirection
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/69720716
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/52498148
has answer: http://stackoverflow.com/a/76815833
answer count: 3

http://stackoverflow.com/q/52486117
tagged with: django
type: AnsweredQuestion
has body: If I have some choices variable: In [1]: from model_utils import Choices In [2]: CHOICES = Choices( ...: (1, 'somekey', 'The long title'), ...: ) In [3]: CHOICES[1] Out[3]: 'The long title' How to retrieve somekey key from it? This answer doesn't work for me. In [10]: {v: k for k, v in dict(CHOICES).iteritems()} Out[10]: {'The long title': 1}
score: 3
type: Question
has answer: http://stackoverflow.com/a/52486292
downvote count: 0
answer count: 1
tagged with: django-model-utils
favorite count: 0
has title: How to get key from model_utils triple Choices?
tagged with: python
accepted answer: http://stackoverflow.com/a/52486292
linked to: http://stackoverflow.com/q/31782211
upvote count: 3

http://stackoverflow.com/q/52507755
has comment: http://stackoverflow.com/comment/91955948
has answer: http://stackoverflow.com/a/52507781
has comment: http://stackoverflow.com/comment/91956019
downvote count: 1
has body: I wanted to find all the six digit numbers with multiple delimited comma,Hyphen and space but not under score. For example: string = "OS 2.2.0_cvr_test_648052_02 &amp; v1.2.1_ab1_03, xyz-800239,test-434523,456345 902384" Required Output: [800239,434523,456345,902384]. The output should not include six digit number with "underscore". From the above string the number "648052" should not be printed. Could you please help me finding the better solution? I have re as re.findall('[-, ][0-9]{6}', string) But it prints the delimiters too.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52508357
upvote count: 0
favorite count: 0
score: -1
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python
has title: python regular expression to match six digit number from a string with multiple delimiters
tagged with: regex

http://stackoverflow.com/comment/91983755
type: QuestionComment
comment on: http://stackoverflow.com/q/52522057
score: 1
type: Comment
has text: You are comparing strings with numbers. `'Foo' != 1`, same for other conditions. That's why you get none. A UDF expects columns as arguments, while the `get_profile` has zero arguments.

http://stackoverflow.com/comment/92062171
comment on: http://stackoverflow.com/q/52557923
score: 0
type: Comment
type: QuestionComment
has text: also image: https://www.dropbox.com/s/8vdi78yfh6aqfzr/title%20app.PNG?dl=0

http://stackoverflow.com/a/52528111
downvote count: 0
has body: You will want to start by developing a python script that does any function you want it to do. In this case, it looks like you want it to download python and install it without user interaction and you want to be able to run this as an executable on windows. So your process would be as follows. your_script_name.py This contains all the code to download and install python non-interactive. Then to convert this into windows.exe install pyinstaller then run the following. pyinstaller --onefile &lt;your_script_name&gt;.py This will result in your_script_name.exe Note: You need to run pyinstaller on a windows system for it to produce an .exe
type: Answer
answers question: http://stackoverflow.com/q/52528035
score: 1
upvote count: 1

http://stackoverflow.com/comment/91947457
comment on: http://stackoverflow.com/q/52503228
has text: See https://github.com/Rapptz/discord.py/issues/969
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91838076
comment on: http://stackoverflow.com/q/52447128
has text: I must have been editing the post as you were commenting. That's possible with `FacetGrid`, but not `PairGrid`. As I understand it, passing `extent` for `PairGrid` will apply the same x-y extents for all `hexbin` plots. It's not variable specific.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91807487
score: 1
has text: You need to store your output in a new dictionary, so declare one at the top of your function. Then store the final value of `ave` in this new dictionary for each key. Finally return the dictionary with the averages.
comment on: http://stackoverflow.com/q/52431821
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52434752
tagged with: python
tagged with: list
score: 1
accepted answer: http://stackoverflow.com/a/52434798
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: if-statement
has body: While making a game of Connect Four, I encounter a strange problem in a function called make_move, when two equivalent return statements behaving differently. The only direct dependency function is put_piece(board, column, player), which puts a player's piece in the bottommost empty spot in the given column of the board. put_piece returns a tuple of two elements: the index of the row the piece ends up in (or -1 if the column is full) and the updated board. The put_piece function is implemented correctly. The make_move function is where the disagreement occurs. It successfully returns row (the index of the row the piece is placed in) and board (the updated board) if I implement using the usual if else return notation, as shown here: def make_move(board, max_rows, max_cols, col, player): """ Put player's piece in column COL of the board, if it is a valid move. Return a tuple of two values: 1. If the move is valid, make_move returns the index of the row the piece is placed in. Otherwise, it returns -1. 2. The updated board """ if 0 &lt;= col &lt; len(board[0]): return put_piece(board, max_rows, col, player) return -1, board This is how make_move should return: &gt;&gt;&gt; rows, columns = 2, 2 &gt;&gt;&gt; board = create_board(rows, columns) &gt;&gt;&gt; row, board = make_move(board, rows, columns, 0, 'X') &gt;&gt;&gt; row 1 &gt;&gt;&gt; board [['-', '-'], ['X', '-']] However, if I change make_move to def make_move(board, max_rows, max_cols, col, player): """ Put player's piece in column COL of the board, if it is a valid move. Return a tuple of two values: 1. If the move is valid, make_move returns the index of the row the piece is placed in. Otherwise, it returns -1. 2. The updated board """ return put_piece(board, max_rows, col, player) if 0 &lt;= col &lt; len(board[0]) else -1, board Both return values get assigned as a tuple to row, and board simply carries on the previous value. &gt;&gt;&gt; rows, columns = 2, 2 &gt;&gt;&gt; board = create_board(rows, columns) &g…
has answer: http://stackoverflow.com/a/52434798
answer count: 1
downvote count: 0
favorite count: 0
tagged with: tuples
tagged with: return
has title: Python different output for one-line if else return statement

http://stackoverflow.com/a/52531701
has body: this is functionnaly equivalent, but when this: 10 &lt; x &lt; 40 is nice to read, mixing different operators to use chained comparisons isn't the best choice. Is that really the same? let's disassemble to find out: def f1(x,y): if y &gt; x and x != -1: return 0 def f2(x,y): if y &gt; x != -1: return 0 import dis print("function 1") dis.dis(f1) print("function 2") dis.dis(f2) result: function 1 2 0 LOAD_FAST 1 (y) 3 LOAD_FAST 0 (x) 6 COMPARE_OP 4 (&gt;) 9 POP_JUMP_IF_FALSE 28 12 LOAD_FAST 0 (x) 15 LOAD_CONST 3 (-1) 18 COMPARE_OP 3 (!=) 21 POP_JUMP_IF_FALSE 28 3 24 LOAD_CONST 2 (0) 27 RETURN_VALUE &gt;&gt; 28 LOAD_CONST 0 (None) 31 RETURN_VALUE function 2 6 0 LOAD_FAST 1 (y) 3 LOAD_FAST 0 (x) 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 4 (&gt;) 11 JUMP_IF_FALSE_OR_POP 23 14 LOAD_CONST 3 (-1) 17 COMPARE_OP 3 (!=) 20 JUMP_FORWARD 2 (to 25) &gt;&gt; 23 ROT_TWO 24 POP_TOP &gt;&gt; 25 POP_JUMP_IF_FALSE 32 7 28 LOAD_CONST 2 (0) 31 RETURN_VALUE &gt;&gt; 32 LOAD_CONST 0 (None) 35 RETURN_VALUE &gt;&gt;&gt; Surprisingly they aren't the same, and the chained version has more instructions. Not sure what's going on here (some took some more time to explain it better: How do chained comparisons in Python actually work?), but really I'd stick to the and version which shortcuts and is so much readable (think of future maintainers too...). That said, one interesting thing about chained comparisons would be if the central argument is computed/takes a long time to compute/has a side effect in the computation and you don't want to store it in a variable: if y &gt; super_long_computation(x) != -1: In that case, the central argument is only evaluated once. In the case of and, you'd have to store it beforehand.
upvote count: 6
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52531569
downvote count: 0
answers question: http://stackoverflow.com/q/52531569
score: 6

http://stackoverflow.com/comment/92060511
type: Comment
has text: Also, you could use either `findAll` or `find_all`, they are the same method. It used to be just `findAll`, but I believe they added `find_all` due to PEP8.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52560938

http://stackoverflow.com/comment/92000095
has text: if you are talking about the for x in range(loops): then there is "break" statement at the end, which will for loop exit at the very first time. ie. irrespective of the value of loops variable(considering it to be atleast 1).
comment on: http://stackoverflow.com/q/52529735
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52453484
tagged with: python
has answer: http://stackoverflow.com/a/52453564
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: I have a measurement values in a manufacturing line like the following for example: import pandas as pd import random random.seed(2) df = pd.DataFrame() df['col1_date'] = pd.date_range('2018-09-01', periods=40, freq='D') df['col2_id'] = pd.DataFrame(list(['A', 'B', 'C', 'D'] *10)) df['MeasuredValues'] = np.random.choice(10, 40) df Basically the items, for example, ['A', 'B', 'C', 'D'] are getting measured for some parameter as it make progress in the line. I am trying to add a column in the table that gives me for each item in col2_id a sequence of measurement such as: when it is measured first I get 1st measurement, then for 2nd measurement I get 2nd measurement and so on. I can do it manually fo a small table of say 100 rows in excel by sorting col2_id and then by col1_date. Obviously for large number of rows in thousands it won't make much sense. Then I can compare the different measurements for all the items in col2_id. I am not having much clue how to do it in Pandas or Python. Can anyone give me some suggestions?
accepted answer: http://stackoverflow.com/a/52453564
has title: How to sequence repeated measurement values in data table?
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52453507
has answer: http://stackoverflow.com/a/52453507

http://stackoverflow.com/a/52511383
upvote count: 43
answers question: http://stackoverflow.com/q/52468956
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/106578557
has comment: http://stackoverflow.com/comment/129676093
downvote count: 1
has comment: http://stackoverflow.com/comment/107560624
has comment: http://stackoverflow.com/comment/107564873
score: 42
has body: The make_dot expects a variable (i.e., tensor with grad_fn), not the model itself. try: x = torch.zeros(1, 3, 224, 224, dtype=torch.float, requires_grad=False) out = resnet(x) make_dot(out) # plot graph of variable, not of a nn.Module
accepted answer of: http://stackoverflow.com/q/52468956

http://stackoverflow.com/comment/92035640
score: 0
has text: Ah sorry. Here it is: https://stackoverflow.com/questions/8053900/how-to-log-everything-that-occurs-in-a-python-interactive-shell-session
comment on: http://stackoverflow.com/q/52547688
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52480470
score: 2
answers question: http://stackoverflow.com/q/52480040
upvote count: 2
has body: if you want to bound your string in single quotes you can use this code. a = 'burja duba \'\'i
downvote count: 0
type: Answer

http://stackoverflow.com/a/52440159
type: Answer
has comment: http://stackoverflow.com/comment/91823285
has comment: http://stackoverflow.com/comment/91823481
has comment: http://stackoverflow.com/comment/91824276
has comment: http://stackoverflow.com/comment/91894702
has comment: http://stackoverflow.com/comment/91823238
has comment: http://stackoverflow.com/comment/91826134
has comment: http://stackoverflow.com/comment/91896675
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91823831
accepted answer of: http://stackoverflow.com/q/52439911
answers question: http://stackoverflow.com/q/52439911
has body: You should escape a backslash literal with a backslash: t.extract(member='autodiscovery\\report.json',path='outdir') or you can use a raw string: t.extract(member=r'autodiscovery\report.json',path='outdir') But then since you have this condition: if "autodiscovery/report" in member.name: you should use a forward slash instead for extraction: t.extract(member='autodiscovery/report.json',path='outdir') Also, os.mkdir does not return the directory name it made, so your outdir variable would be None. You should assign the path name to outdir directly: outdir="C:\\Users\\esrilka\\Documents\\Tar Files\\Untar Files3" os.mkdir(outdir) and then use it for os.mkdir and for extraction (note the lack of quotes around outdir): t.extract(member='autodiscovery/report.json',path=outdir) EDIT: Now that you mentioned that you want to extract report.json without the autodiscovery directory that is part of its path in the tar file, you would have to use the extractfile method instead and write the content to the desired location yourself: with open(os.path.join(outdir, 'report.json'), 'w') as f: f.write(t.extractfile('autodiscovery/report.json').read()) If you want to rename report.json to the name of the tar file you can simply open the file different name: with open(os.path.join(outdir, '3884b56e33d16dd68faa4f1f25c28200.json'), 'w') as f: and if you want that name to be the same as the tar file, use os.path.splitext twice to obtain it (since there are two extension names, .tar and .gz, for your tar file), so that in the beginning you should do this: archive = "C:\\Users\\esrilka\\Documents\\Tar Files\\3884b56e33d16dd68faa4f1f25c28200.tar.gz" basename = os.path.basename(os.path.splitext(os.path.splitext(archive)[0])[0]) t = tarfile.open(archive, 'r') and then when you open the json file for writing: with open(os.path.join(outdir, basename + '.json'), 'w') as f:

http://stackoverflow.com/a/52472512
downvote count: 0
type: Answer
upvote count: 1
has body: Use this XPath : //button[normalize-space()='Vote Now']
score: 1
answers question: http://stackoverflow.com/q/52471206

http://stackoverflow.com/comment/91822026
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52438356
has text: According to the value of `atomtype` I want to treat `atomdata` variable properly.
score: 0

http://stackoverflow.com/comment/92076237
score: 0
type: Comment
has text: Just a suggestion: Upgrade to Python 3 right now. A few things changed, in particular in the area of strings, and it's little use learning a language that's obsolete.
type: QuestionComment
comment on: http://stackoverflow.com/q/52569148

http://stackoverflow.com/a/52553724
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52543930
has body: If you want genuine interpolation, then contourf() is best, especially with more values as @ImportanceOfBeingErnest suggests. However, you could try a pcolormesh() instead, which samples each point instead of interpolating between them. I can't imagine it would be any better though; I'd go for more values so you get a smoother interpolation.
has comment: http://stackoverflow.com/comment/92056657
type: Answer

http://stackoverflow.com/comment/91809415
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52432408
has text: @krflol Apologize for what? He rushed a post then came back with a post that for the time being could have been more efficient, he should be using `enumerate` not range len
score: 0

http://stackoverflow.com/comment/92042748
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52551952
score: 1
has text: [shape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html)

http://stackoverflow.com/comment/92066437
type: Comment
comment on: http://stackoverflow.com/a/52559534
has text: @zaph That's nothing compared to the CBC padding oracle attacks that are likely to be possible :)
type: AnswerComment
score: 0

http://stackoverflow.com/a/52558194
type: Answer
has comment: http://stackoverflow.com/comment/92109628
answers question: http://stackoverflow.com/q/52556305
downvote count: 0
score: 1
has body: Here's one way to achieve your desired output: Add stat_boxplot(geom='errorbar', coef=1) to draw vertical ticks at exactly 1.0 times the IQR, i.e., at the 25th and 75th percentiles Pass nudge_x = 0.12 to geom_text New code: ggplot(aes(x='variable', y='value'), data=df.loc[ (df['L1'].isin(['controls','intercept']))]) + \ stat_summary(fun_y=np.mean, fun_ymin=np.min, fun_ymax=np.max) + \ stat_boxplot(geom='errorbar', coef=1) + \ coord_flip() + \ geom_text(aes(x='variable', y='value', label=round(df.loc[(df['L1'].isin(['controls','intercept']))].groupby( 'variable').mean().reset_index().value, 2), size=8 ), color='red', data=df.loc[(df['L1'].isin(['controls','intercept']))].groupby('variable').mean().reset_index(), position=position_dodge(width=0.8), nudge_x = 0.12) + \ ggtitle('Controls') Output:
upvote count: 1

http://stackoverflow.com/comment/91943430
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52488728
has text: Thank you for your suggestion @gittert. It's an option I will take into account. Do you know I can find a list of format() filters that can be used in jinja?

http://stackoverflow.com/comment/92075462
has text: I applied string formatting operator now the print function produces the exact result. But I also want that h value should be exactly 1.20,1.40. Because I have saved some files with these values when I try to load them it says that no such file or directory exists. and its reason is that h value is 1.2 and 1.4 instead of 1.20 and 1.40
comment on: http://stackoverflow.com/a/52569227
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52449858
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52449207
answers question: http://stackoverflow.com/q/52449207
has comment: http://stackoverflow.com/comment/91877598
has body: If features and features2 contain the features of the same batch of images, that is features[i] is the same image of features2[i] for each i, then it would make sense to group the features in a single array using the numpy function concatenate(): newArray = np.concatenate((features, features2), axis=3) Where 3 is the axis along which the arrays will be concatenated. In this case, you'll end up with a new array having dimension (14637, 10, 10, 103). However, if they refer to completely different batches of images and you would like to merge them on the first axis such that the 14637 images of features2 are placed after the first 14637 image, then, there no way you can end up with an array, since numpy array are structured as matrix, non as a list of objects. For instance, if you try to execute: &gt; a = np.array([[0, 1, 2]]) // shape = (1, 3) &gt; b = np.array([[0, 1]]) // shape = (1, 2) &gt; c = np.concatenate((a, b), axis=0) Then, you'll get: ValueError: all the input array dimensions except for the concatenation axis must match exactly since you are concatenating along axis = 0 but axis 1's dimensions differ.
type: Answer
has comment: http://stackoverflow.com/comment/91877447
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/52535214
answer count: 2
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/52535399
favorite count: 0
tagged with: python-3.x
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/52535294
has answer: http://stackoverflow.com/a/52535294
has answer: http://stackoverflow.com/a/52535399
type: Question
has title: Pandas comparing multiindex dataframes without looping
has body: I want to compare two multiindex dataframes and add another column to show the difference in values (if all index value match between the first dataframe and second dataframe) without using loops index_a = [1,2,2,3,3,3] index_b = [0,0,1,0,1,2] index_c = [1,2,2,4,4,4] index = pd.MultiIndex.from_arrays([index_a,index_b], names=('a','b')) index_1 = pd.MultiIndex.from_arrays([index_c,index_b], names=('a','b')) df1 = pd.DataFrame(np.random.rand(6,), index=index, columns=['p']) df2 = pd.DataFrame(np.random.rand(6,), index=index_1, columns=['q']) df1 p a b 1 0 .4655 2 0 .8600 1 .9010 3 0 .0652 1 .5686 2 .8965 df2 q a b 1 0 .6591 2 0 .5684 1 .5689 4 0 .9898 1 .3656 2 .6989 The resultant matrix (df1-df2) should look like p diff a b 1 0 .4655 -0.1936 2 0 .8600 .2916 1 .9010 .3321 3 0 .0652 No Match 1 .5686 No Match 2 .8965 No Match

http://stackoverflow.com/a/52501786
answers question: http://stackoverflow.com/q/52501647
has comment: http://stackoverflow.com/comment/92500213
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92503673
score: 1
upvote count: 1
has body: You can use a dictionary comprehension with enumerate: L = ['column1_label', 'column2_label', 1, 2, 3, 4, 5, 6] k, m = 2, 2 res = {f'row{i}': dict(zip(L[:k], row)) for i, row in \ enumerate(zip(L[k::m], L[k+1::m]), 1)} Result: {'row1': {'column1_label': 1, 'column2_label': 2}, 'row2': {'column1_label': 3, 'column2_label': 4}, 'row3': {'column1_label': 5, 'column2_label': 6}} Of course, due to the unstructured nature of your input list you will have to manually amend k, m as appropriate. But the same principle applies.

http://stackoverflow.com/comment/91838101
score: 0
comment on: http://stackoverflow.com/q/52447536
type: Comment
type: QuestionComment
has text: file1 type: <class 'str'>

http://stackoverflow.com/q/52503289
accepted answer: http://stackoverflow.com/a/52521085
has comment: http://stackoverflow.com/comment/91947327
answer count: 2
score: 2
has comment: http://stackoverflow.com/comment/91947467
downvote count: 0
has answer: http://stackoverflow.com/a/52504461
favorite count: 0
tagged with: braintree
linked to: http://stackoverflow.com/q/49074527
has title: Braintree subscription search
possible better answer: http://stackoverflow.com/a/52504461
has answer: http://stackoverflow.com/a/52521085
tagged with: python
has comment: http://stackoverflow.com/comment/91947518
has comment: http://stackoverflow.com/comment/91947490
type: AnsweredQuestion
has body: I am working on a Braintree subscription search in order to retrieve customer IDs and subscription prices tied to these IDs. In my code I am following the suggestions from this post. Here is an excerpt of my code: gateway = braintree.BraintreeGateway( braintree.Configuration( environment=braintree.Environment.Production, merchant_id= 'our_merchant_id', public_key='our_public_key', private_key='our_private_key' ) ) subscriptions = gateway.subscription.search( braintree.SubscriptionSearch.status.in_list( braintree.Subscription.Status.Active, braintree.Subscription.Status.PastDue, braintree.Subscription.Status.Pending ) ) result = {} for subscription in subscriptions.items: payment_method = gateway.payment_method.find(subscription.payment_method_token) result[payment_method.customer_id] = subscription.price """do something with result """ This approach works fine in the BT sandbox and on small queries around 100 records. However, whenever I try to query for more than about 120 subscriptions the BT server responds consistently with a 504 error. I would like to query for around 5000 subscriptions at a time in production. Any suggestions? Traceback: Traceback (most recent call last): File "BT_subscrAmount.py", line 22, in &lt;module&gt; for subscription in subscriptions.items: File "/home/karen/miniconda3/lib/python3.6/site- packages/braintree/resource_collection.py", line 38, in items for item in self.__method(self.__query, batch): File "/home/karen/miniconda3/lib/python3.6/site- packages/braintree/subscription_gateway.py", line 79, in __fetch response = self.config.http().post(self.config.base_merchant_path() + "/subscriptions/advanced_search", {"search": criteria}) File "/home/karen/miniconda3/lib/python3.6/site- packages/braintree/util/http.py", line 56, in post return self.__http_do("POST", path, Http.ContentType.Xml, params) File "/home/karen/miniconda3/lib/python3.6/site- packages/braintree/util/http.py", line 86, in __http_do Http.raise_exception_from_status(statu…
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/91947427

http://stackoverflow.com/comment/92093968
score: 1
has text: So did you add Flask just to use Flask_Cors? That isn't going to work. I'm not really too familiar with CORS and the headers required, but there are certainly packages which allow you to do that stuff with Django. Eg googling has given me this: https://github.com/ottoyiu/django-cors-headers/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52578922

http://stackoverflow.com/comment/92092675
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52572693
has text: I didn't really look into it, but one idea would be to calculate the "correlation" between the marker sound and the whole file. The correlation should have peaks at the times where the markers occur in the file.

http://stackoverflow.com/a/79200134
answers question: http://stackoverflow.com/q/52540121
has body: You can also set the variables on your terminal's settings to avoid doing it on each different project. In bash you can add these lines to~/bashrc (or ~/bash_profile): export PIPENV_VENV_IN_PROJECT=1 Or from terminal: echo 'export PIPENV_VENV_IN_PROJECT=1' &gt;&gt; ~/.bashrc source ~/.bashrc Of course this is different for zsh and other terminals but you can search for the same on them.
score: 0
type: Answer

http://stackoverflow.com/comment/91873063
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52465587
score: 0
has text: I update it @sobek . should i provide values of M?

dwt
type: Tag
tag name: dwt
tags question: http://stackoverflow.com/q/52496635

http://stackoverflow.com/comment/98445635
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52536132
has text: Did you ever figure this out @MRule? I'm encountering the same issue with the same setup as you.

http://stackoverflow.com/q/52463855
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91869926
type: Question
has title: how reverse relation works in django model while working with serializers?
score: 0
has answer: http://stackoverflow.com/a/52464158
has body: here is my models.py from __future__ import unicode_literals from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) owner = models.ForeignKey('User') class Meta: ordering = ('created',) def __str__(self): return self.title class User(models.Model): name = models.CharField(max_length=100, blank=True, default='') def __str__(self): return self.name here is my seralizers.py from rest_framework import routers, serializers, viewsets from .models import Snippet from django.contrib.auth.models import User from rest_framework import permissions class SnippetSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.user') permission_classes = (permissions.IsAuthenticatedOrReadOnly,) class Meta: model = Snippet fields = '__all__' class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) class Meta: model = User fields = '__all__' here is my view.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import * from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from re…
answer count: 1

http://stackoverflow.com/a/52731823
has body: There doesnt appear to be an obvious way to limit what happens under-the-covers when Reflecting a database object so I found that the best and most performant way around this is to simply define the mapped classes explicitly as described in the docs, only including the columns you require, as opposed to everything. Base = declarative_base() class Person(Base): __tablename__ = 'person' __table_args__ = {'schema': 'schema_name'} person_id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) And then the query can be executed using the same session.query() syntax that would be used with the database reflection but saves you the significant overhead of going to the database dictionary tables.
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52583845
answers question: http://stackoverflow.com/q/52583845
downvote count: 0
score: 1

http://stackoverflow.com/q/52434946
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52434997
type: Question
has body: I have a pandas DataFrame which looks like this: 0 2013-09-20 0 2013-09-21 1 2013-09-22 2 2013-09-23 3 2013-09-24 4 2013-09-25 5 2013-09-26 6 2013-09-27 7 2013-09-28 8 2013-09-29 9 ... and a list of lists in the following structure: [[0, 125.77, 126.28, 125.77, 126.16], [3, 126.06, 126.31, 125.84, 125.86], [4, 126.04, 126.93, 126.0, 126.93], [5, 126.51, 126.51, 126.0, 126.18], [6, 127.63, 128.04, 127.57, 128.04], [7, 127.58, 127.8, 126.42, 126.94], [10, 126.59, 126.77, 125.14, 125.51], [11, 125.38, 125.88, 125.38, 125.88], [12, 124.3, 124.3, 123.3, 123.81], [13, 123.38, 123.55, 123.09, 123.23], [14, 122.71, 122.85, 122.5, 122.79], [17, 121.19, 121.74, 121.0, 121.74], [18, 122.09, 122.09, 121.12, 121.13], [19, 123.31, 123.88, 123.17, 123.58], [20, 124.57, 125.83, 124.57, 125.83], ... I would like to add the last four values of each list to the DataFrame where the number of the DataFrame's column "0" equals the first value of the respective list in the collection of lists. E.g.: 0 1 2 3 4 2013-09-20 0 125.77 126.28 125.77 126.16 2013-09-21 1 nan 2013-09-22 2 nan 2013-09-23 3 126.06 126.31 125.84 125.86 ...
score: 1
accepted answer: http://stackoverflow.com/a/52434997
has title: Add values of a list to pandas DataFrame columns based on matching value per DataFrame row
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91813387
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/52467768
linked to: http://stackoverflow.com/q/3499791
has answer: http://stackoverflow.com/a/52490378
accepted answer: http://stackoverflow.com/a/52490378
has answer: http://stackoverflow.com/a/68770800
favorite count: 0
has title: IntegrityError: Problem installing fixture
downvote count: 1
tagged with: python
tagged with: django
possible better answer: http://stackoverflow.com/a/68770800
type: AnsweredQuestion
score: 1
has body: I upload my first Django-project into DigitalOcean. After command python manage.py loaddata initial_data.json, I have received this message: django.db.utils.IntegrityError: Problem installing fixture '/webapps/django_shop/shop/initial_data.json': Could not load contenttypes.ContentType(pk=3): duplicate key value violates unique constraint "django_content_type_app_label_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(auth, permission) already exists. How can I fix it?
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/q/52551356
answer count: 0
has body: I am parsing this XML file in python using ElementTree. <?xml version="1.0" encoding="UTF-8"?> <secured attributes="ROLE_USER" /> <evaluate expression="bookingService.createBooking(hotelId, currentUser.name)" result="flowScope.booking" /> <evaluate expression="bookingService.persistBooking(booking)" /> <end-state id="bookingConfirmed" /> <end-state id="bookingCancelled" /> I need the node immediately next to node, but that node has to be a Spring Webflow state node i.e, either a , <action-state> or <decision-state> etc. How can I do this using ElementTree?
type: Question
has title: How to get the next immediate xml node of the same level
has comment: http://stackoverflow.com/comment/92086765
score: 0
linked to: http://stackoverflow.com/q/51626950
has comment: http://stackoverflow.com/comment/92042023
tagged with: elementtree
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/q/52534212
tagged with: tensorflow
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/51430391
score: 3
favorite count: 0
has title: syntax error of matplotlib when training tensorflow/object-detection model on google cloud ml-engine
type: UnansweredQuestion
tagged with: python
tagged with: object-detection
tagged with: object-detection-api
answer count: 0
upvote count: 3
tagged with: matplotlib
has body: I'm trying to train a object detection model on tensorflow/object-detection and I'm following this github page. As I perform training, it seemes like training job is successfully performed but after looking at the log, I found it is stopped due to this error: { insertId: "1vzaw47f4on11p" logName: "projects/one-staging-e2903/logs/ml.googleapis.com%2Fobject_detection_09_27_2018_18_39_10" receiveTimestamp: "2018-09-27T09:43:32.946033224Z" resource: {…} severity: "ERROR" textPayload: "The replica ps 0 exited with a non-zero status of 1. Termination reason: Error. Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/root/.local/lib/python2.7/site-packages/object_detection/model_main.py", line 29, in &lt;module&gt; from object_detection import model_lib File "/root/.local/lib/python2.7/site-packages/object_detection/model_lib.py", line 27, in &lt;module&gt; from object_detection import eval_util File "/root/.local/lib/python2.7/site-packages/object_detection/eval_util.py", line 27, in &lt;module&gt; from object_detection.metrics import coco_evaluation File "/root/.local/lib/python2.7/site-packages/object_detection/metrics/coco_evaluation.py", line 20, in &lt;module&gt; from object_detection.metrics import coco_tools File "/root/.local/lib/python2.7/site-packages/object_detection/metrics/coco_tools.py", line 47, in &lt;module&gt; from pycocotools import coco File "/root/.local/lib/python2.7/site-packages/pycocotools/coco.py", line 49 import matplotlibnmatplotlib.use('Agg')nimport matplotlib.pyplot as plt ^ SyntaxError: invalid syntax The replica ps 1 exited with a non-zero status of 1. Termination reason: Error. Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in …

http://stackoverflow.com/q/52455077
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52455083
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: list
upvote count: 2
has comment: http://stackoverflow.com/comment/91852683
type: Question
possible better answer: http://stackoverflow.com/a/52455113
has body: I have the following list: my_list = ["shanya", 1.2, 1, False, "test", 2, 3.3, True, "3", "4.0"] But how do I access multiple elements in this list? I know how to access one specific element (e.g., my_list[1] gives me [1.2]) and a range (e.g., my_list[1:3] gives me [1.2, 1]) but how do I get the first and third to last element? ["shanya", 1, False, "test", 2, 3.3, True, "3", "4.0"]
has answer: http://stackoverflow.com/a/52455113
has answer: http://stackoverflow.com/a/52455083
has title: Python: access multiple elements in list
answer count: 2

http://stackoverflow.com/q/52474886
tagged with: python
type: AnsweredQuestion
tagged with: describe
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52551944
accepted answer: http://stackoverflow.com/a/52551944
score: 0
tagged with: pandas
has body: I am performing a topic in datacamp as follows: Exploring Your Data Now you'll perform some data exploration using the Python pandas module. To get a sense of the data, you'll output statistics such as mean, median, count, and percentiles. The DataFrame recent_grads is still in your workspace The objectives of the title hope are as follows: Print the .dtypes of your data so that you know what each column contains. Output basic summary statistics using a single pandas function. With the same function from before, summary statistics for all columns that aren't of type object. My code is as follows # Print .dtypes print(recent_grads.dtypes) # Output summary statistics print(recent_grads.describe()) # Exclude data of type object print(recent_grads.describe(exclude='object')) However, the error message that appears is as follows Make sure you correctly excluded object type variables in your second call of .describe() May I ask which part of the link is wrong, trouble assistance, thank you!
has title: Make sure you correctly excluded object type variables in your second call of .describe()

http://stackoverflow.com/comment/117062558
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/64166349
has text: Can you explain how this works? Where is this .value from?
score: 1

http://stackoverflow.com/comment/91891268
score: 0
comment on: http://stackoverflow.com/q/52474287
type: Comment
type: QuestionComment
has text: @bigbounty how?

http://stackoverflow.com/q/52463972
has comment: http://stackoverflow.com/comment/91869922
has comment: http://stackoverflow.com/comment/91870269
has comment: http://stackoverflow.com/comment/91870187
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52464135
upvote count: 9
has body: I'm using the following piece of code to create a banded matrix from a generator g: def banded(g, N): """Creates a `g` generated banded matrix with 'N' rows""" n=len(g) T = np.zeros((N,N+n-1)) for x in range(N): T[x][x:x+n]=g return T The usage is simple as: banded([1,2,3], 3) and it returns [1, 2, 3, 0, 0] [0, 1, 2, 3, 0] [0, 0, 1, 2, 3] It will used mostly to solve a finite difference model with a given stencil for example (-1, 1) Is there a better way to generate that stencil? I could not find any good NumPy Function for that. By better I mean, faster, using less memory, removing the loop from python and sending to Numpy stack. Any (or all) of those are improvements.
has title: Generating banded matrices using numpy
possible better answer: http://stackoverflow.com/a/52464057
type: Question
score: 9
tagged with: numpy
has answer: http://stackoverflow.com/a/52464057
tagged with: matrix
has comment: http://stackoverflow.com/comment/91870176
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/61349823
has comment: http://stackoverflow.com/comment/91869954
accepted answer: http://stackoverflow.com/a/52464135
answer count: 3
linked to: http://stackoverflow.com/q/51887316
has comment: http://stackoverflow.com/comment/91869930
tagged with: python

http://stackoverflow.com/a/52518967
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52518662
downvote count: 0
has body: You could try with leastsquares. Basically find values A and B so that the sum of residuals squared would be minimal. I have used scipy for that. Here is my code: import numpy as np from scipy.optimize import leastsq # -------------------------------- import matplotlib as mpl mpl.rcParams['font.size']=20 import matplotlib.pyplot as plt # ------------------------------------- points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)]) # get x and y vectors x = points[:,0] y = points[:,1] # calculate polynomial #z = np.polyfit(x, y, 4) &lt;---? #f = np.poly1d(z) &lt;---? # ---------------------------------------------- def poly(p,x): return p[0]*x**4+p[1]*x**2 def res(p,x,y): return y-poly(p,x) # ---------------------------------------------- p0=[1.,1.]; pars=leastsq(res,p0,(x,y)); print pars[0] # ----------------------------------------------- xi=np.linspace(np.min(x),np.max(x),100); fig = plt.figure(figsize=(6,6));ax=fig.add_subplot(111); ax.plot(x,y,ms=10,color='k',ls='none',marker='.'); ax.plot(xi,poly(pars[0],xi),color='0.8',lw=2.0); plt.savefig('fit_result.png'); plt.show();
score: 1

http://stackoverflow.com/a/52582670
upvote count: 1
answers question: http://stackoverflow.com/q/52582598
has comment: http://stackoverflow.com/comment/92100367
has comment: http://stackoverflow.com/comment/92100354
type: Answer
has body: You can use itertools.takewhile: from itertools import takewhile res = sum(takewhile(lambda x: x &lt; 4, [1, 2, 4, 0, 3, 2])) # 3 The docs for itertools.takewhile give the equivalent generator which can be used to implement the logic directly: def takewhile(predicate, iterable): # takewhile(lambda x: x &lt; 4, [1, 2, 4, 0, 3, 2]) --&gt; 1 2 for x in iterable: if predicate(x): yield x else: break
downvote count: 0
score: 1

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/52439325
tags question: http://stackoverflow.com/q/52505410
tags question: http://stackoverflow.com/q/52499323
type: Tag

http://stackoverflow.com/q/52570086
tagged with: seaborn
tagged with: machine-learning
score: 13
tagged with: python
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52570336
upvote count: 14
tagged with: matplotlib
has title: Plotting numpy array using Seaborn
type: Question
tagged with: numpy
answer count: 1
has comment: http://stackoverflow.com/comment/92076967
favorite count: 0
has body: I'm using python 2.7. I know this will be very basic, however I'm really confused and I would like to have a better understanding of seaborn. I have two numpy arrays X and y and I'd like to use Seaborn to plot them. Here is my X numpy array: [[ 1.82716998 -1.75449225] [ 0.09258069 0.16245259] [ 1.09240926 0.08617436]] And here is the y numpy array: [ 1. -1. 1. ] How can I successfully plot my data points taking into account the class label from the y array? Thank you,
has answer: http://stackoverflow.com/a/52570336
linked to: http://stackoverflow.com/q/29637150

http://stackoverflow.com/comment/92148689
comment on: http://stackoverflow.com/q/52579293
score: 0
has text: Not only it is *not* unreasonable, it is exactly the norm, and what functions like `GridSearchCV` do by default! That's why I am still puzzled why you are intermixing things here (i.e. CV with training/validation split)...
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52566756
type: Question
has answer: http://stackoverflow.com/a/52582002
type: AnsweredQuestion
answer count: 6
tagged with: graphviz
has answer: http://stackoverflow.com/a/74567405
has comment: http://stackoverflow.com/comment/92075032
downvote count: 0
accepted answer: http://stackoverflow.com/a/52582002
score: 28
favorite count: 0
possible better answer: http://stackoverflow.com/a/61846014
upvote count: 28
has comment: http://stackoverflow.com/comment/92071016
has answer: http://stackoverflow.com/a/61846014
has title: No module named 'graphviz' in Jupyter Notebook
tagged with: python
has comment: http://stackoverflow.com/comment/92071027
has body: I tried to draw a decision tree in Jupyter Notebook this way. mglearn.plots.plot_animal_tree() But I didn't make it in the right way and got the following error message. --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz So I downloaded Graphviz Windows Packages and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. pip install graphviz BUT it still doesn't work. Hope someone can help me, sincerely.
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/78201106
has comment: http://stackoverflow.com/comment/92070836
has answer: http://stackoverflow.com/a/52567078
has answer: http://stackoverflow.com/a/62942272

http://stackoverflow.com/q/52520638
answer count: 1
has title: How to extract information from html text with Python
tagged with: beautifulsoup
score: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/91981015
tagged with: python
has answer: http://stackoverflow.com/a/52520756
has comment: http://stackoverflow.com/comment/91980912
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91980940
has body: I might have a document with the following information: Some Text A person name Works somewhere, in some country Grab this text as well This block will basically repeat x amount of times. I need to extract this information. However, the number of tags will vary so could be 7 separate ones before the h1 tag appears again. I am using beautifulsoup as well to help with this. I can extract this data but cannot make a rule so that for every h1 tag extract the x number of tags after that until it is a h1 tag again. So every time a h1 tag appears this is a new record. Hope this makes sense thanks!
type: Question

http://stackoverflow.com/q/52573275
type: Question
accepted answer: http://stackoverflow.com/a/52573291
has comment: http://stackoverflow.com/comment/92082898
tagged with: python
has title: Get ALL items in a python list?
tagged with: list
has answer: http://stackoverflow.com/a/52573320
has comment: http://stackoverflow.com/comment/92082876
upvote count: 7
has comment: http://stackoverflow.com/comment/92082824
downvote count: 1
answer count: 4
has comment: http://stackoverflow.com/comment/92082832
has body: it's very easy to get the number of items in a list, len(list), but say I had a matrix like: [[1,2,3],[1,2,3]] Is there a pythonic way to return 6? Or do I have to iterate.
has answer: http://stackoverflow.com/a/52573291
score: 6
has comment: http://stackoverflow.com/comment/92082828
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66577718
possible better answer: http://stackoverflow.com/a/52573313
favorite count: 0
linked to: http://stackoverflow.com/q/2158395
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52573313

http://stackoverflow.com/comment/91901402
type: Comment
type: QuestionComment
has text: Check the line in your file after `Rio de Janeiro`. Most probably there is some error with `city_temp[2]`. There might be either a blank line or some formatting issues so that you have only 2 elements and hence `[2]` gives you an IndexError
comment on: http://stackoverflow.com/q/52480002
score: 0

http://stackoverflow.com/q/52441642
tagged with: while-loop
has comment: http://stackoverflow.com/comment/91826058
accepted answer: http://stackoverflow.com/a/52441722
has comment: http://stackoverflow.com/comment/91826052
tagged with: python
duplicate of: http://stackoverflow.com/q/15363138
has comment: http://stackoverflow.com/comment/91826051
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91826543
tagged with: loops
tagged with: primes
type: Question
has body: I am trying to find the nth prime number, without looking at other solutions I am building this function def Nth_Prime(Target): Primes = [2,3,5,7,11,13,17,19] Num = 20 N=8 Count=0 while(N&lt;Target): for i in Primes: if Num%i==0: Num+=1 i=2 else Num%i!=0: Count+=1 if Count==len(Primes): i=2 Primes.append(Num) N+=1 print(Primes) Num+=1 print(Count) Nth_Prime(10002) Now, while it may not be the most efficient, what I am trying to understand is why I can't reset my variable I to the beginning of the array for each loop? the function correctly finds 23 as the next prime number then it goes wrong help appreciated. EDIT: I got it! Thanks to all, time to clean it up a little and make it more aesthetic def Nth_Prime(Target): Primes = [2,3,5,7,11,13,17,19] Num = 20 N=8 Count=0 x=0 while(N&lt;Target): i = Primes[x] if Num%i==0: Num+=1 x = 0 elif Num%i!=0: Count+=1 x+=1 if Count==len(Primes): Primes.append(Num) N+=1 Num+=1 Count = 0 x=0 print(Primes[10000]) Nth_Prime(10002)
has comment: http://stackoverflow.com/comment/91826085
has comment: http://stackoverflow.com/comment/91826322
linked to: http://stackoverflow.com/q/15363138
upvote count: 4
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52441722
favorite count: 0
has title: Python find Nth prime
has comment: http://stackoverflow.com/comment/91826151

communication
tag name: communication
tags question: http://stackoverflow.com/q/52532124
type: Tag

http://stackoverflow.com/comment/91931886
comment on: http://stackoverflow.com/q/52495502
score: 0
has text: Ah I see that's fine, but then for the real problem it would be, `k` elements, `k^n` vector length and at least `n + 1` repetitions of each element, right?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52546624
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52546945
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I would like to split each row of a csv file into multiple blocks of text and save them as separate text files (it has only 1 column, each row contains a block of text). My items_split function works perfectly fine with a defined block of text but when applied to the csv file I got the error "File "untitled.py", line 25, in items_split idx = text_lines.index("ABC") + 1 ValueError: 'ABC' is not in list" The code I used is below: import re import uuid def items_split(file): data=file ## First, we want to remove all empty lines in the text files data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) data = re.sub(r'\n\s*\n','\n',data,re.MULTILINE) ## Then, we remove all lines up to ABC text_lines = data.split("\n") idx = text_lines.index("ABC") + 1 data = "\n".join(text_lines[idx:]) ## Last, we split the text files into multiple files, each with a news item current_file = None for line in data.split('\n'): # Set initial filename, if current_file == None and line != '': current_file = str(uuid.uuid4()) + '.txt' #this will assign a random file name #current_file = line + '.txt' # This is to handle the blank line after Brief if current_file == None: continue text_file = open(current_file, "a") text_file.write(line + "\n") text_file.close() # Reset filename if we have finished this section # which is idenfitied by: # starts with Demographics - ^Demographics # contains some random amount of text - .* # ends with ) - )$ if re.match(r'^Demographics:.*\)$', line) is not None: current_file = None import csv with open('Book1.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=',') for row in spamreader: items_split(row) For example, each row in the csv file would look like this: "M…
has comment: http://stackoverflow.com/comment/92064854
score: 4
has answer: http://stackoverflow.com/a/52547000
type: Question
has title: Split and save blocks of text from csv file with Python
upvote count: 4

http://stackoverflow.com/comment/91856712
type: Comment
type: QuestionComment
has text: Should the input array shape be N by N?
score: 0
comment on: http://stackoverflow.com/q/52457024

http://stackoverflow.com/comment/91873329
comment on: http://stackoverflow.com/q/52465771
has text: fixed. thanks for the comment
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52535324
type: AnsweredQuestion
has title: Closing a second Tkinter window doesn't work
tagged with: tkinter
has body: Imagine the following very simple example: from tkinter import * from tempFunctions import * startingWin = Tk() button = Button(startingWin, text="Open Other Win", command=lambda: openSecondWin()).grid(row=0, column=0, padx=30, pady=30) startingWin.mainloop() The output is simply as following: No if I click on the button, I open the second Win like: The second window has the following code in tempFunctions.py: from tkinter import * def openSecondWin(): secondWin = Tk() cancelButton = Button(secondWin, text="Cancel", command=secondWin.quit).grid(row=0, column=0, padx=30, pady=30) secondWin.mainloop() I expect that when I press cancel, the secondWin should close. That doesn't happen. What I get is that when I click cancel, the second Win doesn't close. However, if click twice both windows (startingWin and secondWin) close together. Why? Is there a logical explanation for this? Thanks! UPDATE: Trying with binding results in the same problem. Also making the second win as Toplevel doesn't help.
has comment: http://stackoverflow.com/comment/92011176
has answer: http://stackoverflow.com/a/52537988
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92014475
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/2307464
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92009949
accepted answer: http://stackoverflow.com/a/52537988
tagged with: python

http://stackoverflow.com/q/52461970
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52469494
score: 2
type: AnsweredQuestion
has title: Why is Python signal handler not getting triggered?
upvote count: 2
has body: In the code snippet below, I registered the signal handler with a call to signal.signal. However, though the process is killed after the timeout, the print or system statements inside the handler are not being executed. What am I doing wrong? I am running Python 2.7.15rc1 on Ubuntu 18.04, 64 bit. import signal import time import os import multiprocessing as mp def handler(signal, frame): print "Alarmed" os.system('echo Alarmed &gt;&gt; /tmp/log_alarm') def launch(): signal.signal(signal.SIGALRM, handler) signal.alarm(5) print "Process launched" os.execv('/bin/cat', ['cat']) print "You should not see this" p = mp.Process(target=launch) p.start() print "Process started" p.join()
type: Question
accepted answer: http://stackoverflow.com/a/52469494
has comment: http://stackoverflow.com/comment/91884290
tagged with: python-2.7
tagged with: signals

http://stackoverflow.com/comment/92007911
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52533844
has text: the class name is already an attribute of a class object, why bother to set again?

http://stackoverflow.com/q/52493921
has body: To duplicate the rows according to the value in column 'n', and reassign the value in column 'v' with the average (of v divided by n), like below: I am following the sample at Replicating rows in a pandas data frame by a column value. import pandas as pd import numpy as np df = pd.DataFrame(data={ 'id': ['A', 'B', 'C'], 'n' : [1, 2, 3], 'v' : [ 10, 13, 8] }) df2 = df.loc[np.repeat(df.index.values,df.n)] #pd.__version__ 0.20.3 #np.__version__ 1.15.0 But it returns me an error message: Traceback (most recent call last): File "C:\Python27\Working Scripts\pv.py", line 14, in &lt;module&gt; df2 = df.loc[np.repeat(df.index.values, df.n)] File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 445, in repeat return _wrapfunc(a, 'repeat', repeats, axis=axis) File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 61, in _wrapfunc return _wrapit(obj, method, *args, **kwds) File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 41, in _wrapit result = getattr(asarray(obj), method)(*args, **kwds) TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe' What goes wrong here and how can I correct it? Thank you. (Some others pandas and numpy scripts work all fine in the computer. )
has comment: http://stackoverflow.com/comment/91928957
tagged with: pandas
answer count: 1
has title: Python, Pandas to calculate average with replicated rows
has answer: http://stackoverflow.com/a/52494582
linked to: http://stackoverflow.com/q/20625582
has comment: http://stackoverflow.com/comment/91928710
has comment: http://stackoverflow.com/comment/91928932
linked to: http://stackoverflow.com/q/26777832
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91929239
score: 0
has comment: http://stackoverflow.com/comment/91928815
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91929198
accepted answer: http://stackoverflow.com/a/52494582
type: Question
tagged with: numpy

http://stackoverflow.com/q/52433525
tagged with: python
accepted answer: http://stackoverflow.com/a/52433678
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91810880
score: 1
has body: I am looking for something like TRIM() in python, but .strip() doesn't accomplish this. Here's an example: &gt;&gt;&gt; s.strip() 'Elvis Presley made his film debut in this tale of three brothers who, while serving in the Confederate Army, steal a Union Army payroll. \xc2\xa0' &gt;&gt;&gt; s2.strip() 'Elvis Presley made his film debut in this tale of three brothers who, while serving in the Confederate Army, steal a Union Army payroll.' &gt;&gt;&gt; s.strip()==s2.strip() False How would I accomplish the above -- to trim all whitespace characters at the edges of text -- where I could get s.trim() == s2.trim() (other than just doing a hackish s.strip('\xc2\xa0').strip()?
possible better answer: http://stackoverflow.com/a/52433594
has comment: http://stackoverflow.com/comment/91810901
has answer: http://stackoverflow.com/a/52433678
type: Question
linked to: http://stackoverflow.com/q/10993612
downvote count: 0
has title: TRIM in python for all whitespace characters
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/91810843
has answer: http://stackoverflow.com/a/52433594
favorite count: 0
has comment: http://stackoverflow.com/comment/91810948

http://stackoverflow.com/q/52504941
has comment: http://stackoverflow.com/comment/91983589
has answer: http://stackoverflow.com/a/71110674
has comment: http://stackoverflow.com/comment/91950731
tagged with: imaplib
has comment: http://stackoverflow.com/comment/91950363
has title: IMAPLIB "initial value must be str or none, not bytes" error
has comment: http://stackoverflow.com/comment/118341884
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91950499
has comment: http://stackoverflow.com/comment/91957011
has comment: http://stackoverflow.com/comment/91950421
tagged with: python
has comment: http://stackoverflow.com/comment/91950647
has body: so im working on a script that basically runs in the background and pulls the data from any email that gets received containing a specific word in the subject and from a specific person. However, i cannot get it to parse the subject when running it since it keeps giving me an error that says "initial value must be str or none, not bytes" and i am unsure what this means or how to go about fixing it. Here is what i have so far: import email import imaplib from bs4 import BeautifulSoup import time import sys username = 'asadrasdfasdi@asdfasdf.ca' password = 'asdfasdfasasdf' mail = imaplib.IMAP4_SSL('imap-mail.outlook.com') (retcode, capabilities) = mail.login(username, password) mail.list() n=0 while True: mail.select('inbox') (retcode, messages) = mail.search(None, 'UNSEEN', '(SUBJECT "XXXXX- ")', '(FROM "XXX.XXX@XXX.ca")') if retcode == 'OK': for num in messages[0].split(): n=n+1 print('Processing Email ' + str(n) + ': ') typ, data = mail.fetch(num, '(RFC822)') for response_part in data: if isinstance(response_part, tuple): original = email.message_from_string(response_part[1]) print("Subject: " + original['Subject']) typ, data = mail.store(num,'+FLAGS','\\Seen') time.sleep(120)
type: UnansweredQuestion

http://stackoverflow.com/q/52465567
answer count: 1
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52467024
has comment: http://stackoverflow.com/comment/91872885
has comment: http://stackoverflow.com/comment/91873618
linked to: http://stackoverflow.com/q/2536199
tagged with: mysql-workbench
has title: InternalError: (1366, u"Incorrect integer value: Select) Error
has comment: http://stackoverflow.com/comment/91873266
linked to: http://stackoverflow.com/q/42255754
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91873249
has body: Return user id from phone_number GET_USER_ID = "SELECT user_id FROM user WHERE phone_number = {};" I am trying to run the above query and got this error : InternalError: (1366, u"Incorrect integer value: 'SELECT user_id FROM user WHERE phone_number = 0400001122;' for column 'user_id' at row 1") When i run the query in the mysql workbench, it works fine and returns the correct user_id. I have been researching other posts as well, but most of them are insert problems and a null value for them would fix this in INSERT cases. However, I am doing a SELECT query. I have been struggling alot with this error, could anyhow help me out?
tagged with: mysql
has comment: http://stackoverflow.com/comment/91872937
has answer: http://stackoverflow.com/a/52467024
type: Question
has comment: http://stackoverflow.com/comment/91873279

http://stackoverflow.com/comment/92021294
has text: Because in theory, you could have 3 `0` values left to place towards the end? It's a random distribution so when you come to fill your last index, for example, what is the _guarantee_ that the second to last value is not the same as what you have left to place? Mine is failing occasionally on this.
type: Comment
comment on: http://stackoverflow.com/a/52540553
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92096195
comment on: http://stackoverflow.com/q/52580521
has text: That is the logical consequence of an *untrained* network. You should implement the *backward* and feed it with data.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/105041431
has text: @Kyle Morse why is none of that explained here: https://rally1.rallydev.com/slm/doc/webservice/authentication.jsp
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52536225
type: Comment

http://stackoverflow.com/comment/91867916
has text: @today edited !!
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52448552

http://stackoverflow.com/comment/91933985
has text: @martineau According to the regex of `test2` the OP apparently only considers positive integers.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52496390
type: Comment

http://stackoverflow.com/comment/92042236
score: 0
has text: But the *console output* is not in your question (the content the `print(..)` prints on the console).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52551210

http://stackoverflow.com/q/52528627
has comment: http://stackoverflow.com/comment/92022665
duplicate of: http://stackoverflow.com/q/26596730
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/92067059
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92077318
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92060604
has comment: http://stackoverflow.com/comment/92067026
has comment: http://stackoverflow.com/comment/92060409
tagged with: python
linked to: http://stackoverflow.com/q/26596730
has comment: http://stackoverflow.com/comment/92061380
has comment: http://stackoverflow.com/comment/92022697
answer count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/92061360
has comment: http://stackoverflow.com/comment/92061390
has comment: http://stackoverflow.com/comment/92060718
has title: Why does PyQt5 QtMultimedia gives an error?
type: Question
has body: Using OS: Linux Ubuntu 18.04 I'm trying to run different PyQt examples that contain QtMultimedia module. Unfortunately, they give me the same error: defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.mediaplayer" I've heard that many people, who use Unix-like OS, have faced with that problem but i still can't find any solution. Here's a code sample:` from PyQt5 import QtCore, QtWidgets, QtMultimedia import sys class MyWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent, flags= QtCore.Qt.Window | QtCore.Qt.MSWindowsFixedSizeDialogHint) self.setWindowTitle("Music PLayer") # Player self.mpPlayer = QtMultimedia.QMediaPlayer() self.mpPlayer.setVolume(50) self.mpPlayer.mediaStatusChanged.connect(self.initPlayer) self.mpPlayer.stateChanged.connect(self.setPlayerState) vbox = QtWidgets.QVBoxLayout() # File open button btnOpen = QtWidgets.QPushButton("File &amp;open") btnOpen.clicked.connect(self.openFile) vbox.addWidget(btnOpen) # Make components disable at start self.sldPosition = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.sldPosition.setMinimum(0) self.sldPosition.valueChanged.connect(self.mpPlayer.setPosition) self.mpPlayer.positionChanged.connect(self.sldPosition.setValue) self.sldPosition.setEnabled(False) vbox.addWidget(self.sldPosition) hbox = QtWidgets.QHBoxLayout() self.btnPlay = QtWidgets.QPushButton("&amp;Play") self.btnPlay.clicked.connect(self.mpPlayer.play) self.btnPlay.setEnabled(False) hbox.addWidget(self.btnPlay) self.btnPause = QtWidgets.QPushButton("P&amp;ause") self.btnPause.clicked.connect(self.mpPlayer.pause) self.btnPause.setEnabled(False) hbox.addWidget(self.btnPause) self.btnStop = QtWidgets.QPushButton("&amp;Stop") self.btnStop.clicked.connect(self.mpPlayer.stop) self.btnStop.setEnabled(False) hbox.addWidget(self.btnStop) vbox.addLayout(hbox) # Volume control hbox = QtWidgets.QHBoxLayout() lblVolume = QtWidgets.QLabel("&amp;Volume") hbox.addWidget(lblVolume) sldVolum…
has comment: http://stackoverflow.com/comment/91997699

http://stackoverflow.com/comment/92068573
comment on: http://stackoverflow.com/q/52564301
type: Comment
type: QuestionComment
score: 0
has text: The notation `sin(θ)(t)` is a bit ambiguous. Do you mean `Sin(θ(t))` (where `θ` is a function of `t`)?

http://stackoverflow.com/comment/91989037
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52520941
has text: My question is in which way the metrics' values represent the data. For example I could imagine the following schemes. The computation of metrics could be done via summation or via averaging. Then it could be done over over mini-batches or over the full data set. Within mini-batches, it could be summed or averaged. I would like to know what part of my data set is represented in which way by the metrics' values that are presented as part of the history. Also if this varies for the different metrics; for example accuracy clearly refers to a set of samples while MSE could be computed per sample.
score: 0

http://stackoverflow.com/a/52510568
has comment: http://stackoverflow.com/comment/91977909
has comment: http://stackoverflow.com/comment/91986916
type: AcceptedAnswer
downvote count: 0
has body: IIUC, this is what you're going for: For each row (which represents an ID), you want a total of num_samples Monte Carlo simulations of whether that row achieves its Revenue. The way you determine whether a given simulated instance achieves its Revenue is by comparing a randomly drawn value in [0,1] against the Odds for that row (in standard Monte Carlo fashion). You want to know the mean and standard deviation of the Revenue for each row, across all samples. If so, you can do this by leveraging the sampling function of the Binomial distribution, instead of drawing from a Uniform and then filtering based on Odds. I'll post a solution using this approach at the end of this answer. But since you've started out with the Uniform-draw approach: I'd recommend first making a sampling matrix s_draws of n_rows = len(df) by num_samples (aka n_draws in my code below). Then apply the Odds check against all of the samples in each row of s_draws. Then multiply by Revenue, and take the mean and sd for each row. Like this: First, draw the sampling matrix: np.random.seed(42) n_rows = len(df) n_draws = 5 s_draws = pd.DataFrame(np.random.rand(n_rows, n_draws)) # the matrix of random values between [0,1] # note: only showing the first 3 rows for brevity s_draws 0 1 2 3 4 0 0.374540 0.950714 0.731994 0.598658 0.156019 1 0.155995 0.058084 0.866176 0.601115 0.708073 2 0.020584 0.969910 0.832443 0.212339 0.181825 ... Now figure out which sampled instances "achieved" the target Revenue: s_rev = s_draws.apply(lambda col: col.lt(df.Odds) * df.Revenue) # the matrix of sampled revenue s_rev 0 1 2 3 4 0 1000 0 0 0 1000 1 1200 1200 0 0 0 2 1300 0 0 1300 1300 ... Finally, compute summary statistics for each row/ID: s_result = pd.DataFrame({"avg": s_rev.mean(axis=1), "sd": s_rev.std(axis=1)}) # the summary statistics of each row of samples s_result avg sd 0 400.0 547.722558 1 480.0 657.267069 2 780.0 712.039325 ... And here's the version using Binomial sampling: draws = pd.DataFrame( np.random.binom…
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52508956
type: Answer
answers question: http://stackoverflow.com/q/52508956
score: 2

http://stackoverflow.com/a/52859580
accepted answer of: http://stackoverflow.com/q/52452222
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52452222
score: 6
type: Answer
downvote count: 0
upvote count: 6
has body: Don't install qtconsole. With conda, do conda install notebook or conda install jupyterlab. Don't run conda install jupyter, as this will install qtconsole (look at the conda-forge recipe). With pip, do pip install notebook or pip install jupyterlab. Don't run pip install jupyter, as this will install qtconsole (look at the jupyter setup.py).

http://stackoverflow.com/q/52554285
downvote count: 0
favorite count: 0
tagged with: docker
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
has title: Python urllib.urlretrieve() error in Docker
has body: I recently developed a Python script to retrieve medical images from Open-I in Python. This script worked locally, but now that I have put this script in a Docker container the script errors when I try to retrieve the image. The output in the console only says: error. Can someone please explain to me what I am doing wrong? import urllib urllib.urlretrieve('https://openi.nlm.nih.gov/'+record['imgLarge'], path+str(filename)) Docker compose file: version: '3.2' services: zookeeper: image: wurstmeister/zookeeper ports: - "2181:2181" tty: true networks: - retriever kafka: image: wurstmeister/kafka:latest ports: - target: 9094 published: 9094 protocol: tcp mode: host environment: HOSTNAME_COMMAND: "docker info | grep ^Name: | cut -d' ' -f 2" KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_ADVERTISED_HOST_NAME: kafka KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT KAFKA_ADVERTISED_LISTENERS: INSIDE://:9092,OUTSIDE://_{HOSTNAME_COMMAND}:9094 KAFKA_LISTENERS: INSIDE://:9092,OUTSIDE://:9094 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_CREATE_TOPICS: "rontgen_images" volumes: - /var/run/docker.sock:/var/run/docker.sock networks: - retriever tty: true python: build: context: . dockerfile: DockerfilePython tty: true networks: - retriever networks: retriever: driver: bridge

http://stackoverflow.com/a/52431829
score: 0
answers question: http://stackoverflow.com/q/52431362
type: Answer
has comment: http://stackoverflow.com/comment/91836074
has body: Here you are posting the form data to /post_data and redirect it to /add so the edited function will not be able to access the request object containing the form data. So just change the form action to /add to make it work correctly.

http://stackoverflow.com/comment/92033726
has text: @juan , as soon as possible I will try opening the file with `encoding='utf16'`. Then, I comment here.
score: 0
comment on: http://stackoverflow.com/q/52545977
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92099921
comment on: http://stackoverflow.com/q/52582427
has text: Well, is this exactly what your browser does while logging you in? Are you using the exact same method (POST), passing the appropriate headers and the appropriate parameters?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52535703
has answer: http://stackoverflow.com/a/52537362
type: UnansweredQuestion
tagged with: python
has body: I'm building a very simple program in Python. All I want is to be able to input a text and get the translated text in another language. The program will be used on different computers, the API key can be stored in the code as I will be the only one using it. I can't figure out how to do it, I've searched for hours without any progress. What is the simplest way of getting it to work? EDIT: so far I have this: from google.cloud import translate key = "...." translate_client = translate.Client() service = translate.build(developerKey=key) service = build('translate', 'v2', developerKey=key) translation = service.translate(['Detta är ett test'], target_language = 'en') print(translation)
score: 1
tagged with: translate
type: Question
upvote count: 2
answer count: 2
tagged with: google-cloud-platform
tagged with: cloud
downvote count: 1
has answer: http://stackoverflow.com/a/58938250
favorite count: 0
has title: Having a hard time using the GCP translate API

http://stackoverflow.com/a/52553053
has body: Well, it's unclear tho, but... Try this: l=[2,5,8] print(tuple([1,2,3]+l)) You can concatenate by + Alternatively can do * (unpacking) in python 3: print((*l, 1,2,3)) Or can do chain from itertools: import itertools print(tuple(itertools.chain(l, [1,2,3]))) Or merge from heapq: from heapq import merge print(tuple(merge(l,[1,2,3]))) Or add form operator: import operator print(tuple(operator.add(l, [1,2,3])))
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52552994
upvote count: 2

http://stackoverflow.com/comment/92092546
has text: There is no `content` block in `catalog.html`. I also do not see where you add `'p'` to the context.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52578660
score: 1

http://stackoverflow.com/q/52471491
tagged with: python
score: 1
has body: Good Evening All, I have spent a couple of hours trying to figure this out. I tried everything but it seems not to work. I am launching a script via a windows batch file through python and a dialog box pops up with the "yes" already highlighted. All I want to do is press enter. I have seen subprocess and all but nothing happened. import openpyxl import os import subprocess import win32com.client import time from subprocess import Popen, PIPE print "Section Clear" launch = os.system('C:/Users/luis.durani/Desktop/login.bat') print "Section Clear"
has comment: http://stackoverflow.com/comment/91889015
type: Question
has title: Send Enter Key to dialog prompt with Python
has comment: http://stackoverflow.com/comment/91911532
upvote count: 1
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91895933
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52477335
type: Comment
has text: whats the other possible ways to import the module actually i used the same ethjsonrpc earlier

http://stackoverflow.com/q/52505583
has answer: http://stackoverflow.com/a/52505857
has answer: http://stackoverflow.com/a/52507877
tagged with: delimiter
has body: Working in Python 3.7. I'm currently pulling data from an API (Qualys's API, fetching a report) to be specific. It returns a string with all the report data in a CSV format with each new line designated with a '\r\n' escape. (i.e. 'foo,bar,stuff\r\n,more stuff,data,report\r\n,etc,etc,etc\r\n') The problem I'm having is writing this string properly to a CSV file. Every iteration of code I've tried writes the data cell by cell when viewed in Excel with the \r\n appended to where ever it was in the string all on one row, rather than on a new line. (i.e |foo|bar|stuff\r\n|more stuff|data|report\r\n|etc|etc|etc\r\n|) I'm just making the switch from 2 to 3 so I'm almost positive it's a syntactical error or an error with my understanding of how python 3 handles new line delimiters or something along those lines, but even after reviewing documentation, here and blog posts I just cant either cant get my head around it, or I'm consistently missing something. current code: def dl_report(id, title): data = {'action': 'fetch', 'id': id} res = a.request('/api/2.0/fo/report/', data=data) print(type(res)) #returns string #input('pause') f_csv = open(title,'w', newline='\r\n') f_csv.write(res) f_csv.close but i've also tried: with open(title, 'w', newline='\r\n') as f: writer = csv.writer(f,&lt;tried encoding here, no luck&gt;) writer.writerows(res) #anyone else looking at this, this didn't work because of the difference #between writerow() and writerows() and I've also tried various ways to declare newline, such as: newline='' newline='\n' etc... and various other iterations along these lines. Any suggestions or guidance or... anything at this point would be awesome. edit: Ok, I've continued to work on it, and this kinda works: def dl_report(id, title): data = {'action': 'fetch', 'id': id} res = a.request('/api/2.0/fo/report/', data=data) print(type(res)) #returns string reader = csv.reader(res.split(r'\r\n'), delimiter=',') with open(title, 'w') as outfile: writer = csv.writer(out…
has answer: http://stackoverflow.com/a/52505904
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/3305926
upvote count: 1
tagged with: python
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52508202
score: 1
possible better answer: http://stackoverflow.com/a/52505857
type: Question
has title: Writing a string to CSV using line escapes in python 3
has answer: http://stackoverflow.com/a/52508202
tagged with: newline
has comment: http://stackoverflow.com/comment/91956266
downvote count: 0
has comment: http://stackoverflow.com/comment/91956384
tagged with: http://stackoverflow.com/tag/csv

coin-flipping
tags question: http://stackoverflow.com/q/52514171
type: Tag
tag name: coin-flipping

http://stackoverflow.com/q/52454246
type: Question
upvote count: 2
downvote count: 2
answer count: 1
score: 0
tagged with: python
has title: Can I perform queries in django pre_save signals?
tagged with: django-signals
favorite count: 0
tagged with: django
has answer: http://stackoverflow.com/a/52454508
accepted answer: http://stackoverflow.com/a/52454508
has body: This is models.py class ledger1(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companys') Creation_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32,unique=True) Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2) Closing_balance = models.DecimalField(max_digits=10,decimal_places=2) class journal(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname') Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2,) Credit = models.DecimalField(max_digits=10,decimal_places=2) I want to make a mathamatical equation using django queries and the result of my equation will be displayed in the ledger1.Closing_Balance field So I have tried this: @receiver(pre_save, sender=ledger1) def update_user_closing_balance(sender,instance,*args,**kwargs): Closing_balance = ledger1.objects.annotate(debitsum=Sum('Debitledgers__Debit')) + instance.Opening_Balance - ledger1.objects.annotate(creditsum=Sum('Creditledgers__Credit')) instance.Closing_balance = Closing_balance Is it possible in django??? Because if I run this I am getting unsupported operand error... Is there any alternative code for this??? If anyone knows it...Plz help Thank you in advance
type: AnsweredQuestion
tagged with: django-models

http://stackoverflow.com/comment/92378328
type: Comment
has text: Your function is returning an iterator, use a for loop against the function and yield each result.
type: AnswerComment
comment on: http://stackoverflow.com/a/52724037
score: 0

http://stackoverflow.com/a/52569640
has body: You can probably iterate over your list of values, calling the required method from the library each time.
answers question: http://stackoverflow.com/q/52569622
type: Answer
has comment: http://stackoverflow.com/comment/92076233
has comment: http://stackoverflow.com/comment/92078616
score: 0

http://stackoverflow.com/a/52564845
has body: I found the answer: You should use json.dumps and attached_media as parameter: import json graph.put_object(parent_object="page_id", connection_name="feed", message="Message with multiple files!", attached_media=json.dumps([{'media_fbid': str(photo_id.get('id', ''))}]))
answers question: http://stackoverflow.com/q/52564590
upvote count: 4
score: 4
downvote count: 0
type: Answer

http://stackoverflow.com/a/64072196
downvote count: 1
answers question: http://stackoverflow.com/q/52497554
upvote count: 4
score: 3
has body: I have found the following workaround using the package openpyxl by reading the file with the empty line, deleting the line, and re-writing the file. The advantage I've found with this method is that it preserves the pretty merged cells in the MultiIndex columns and actually deletes the empty row from the Excel file. By actually deleting the empty row, if the rest of your data is numeric, this will allow you to use Excel's filtering capabilities in your spreadsheet out of the box without having to manually delete the empty row in the file. # Assuming df is your data frame with MultiIndex columns that you have already written to Excel # Load the file with the empty line and select the sheet you want to edit wb = openpyxl.load_workbook(filename = 'file_with_empty_line.xlsx') ws = wb['sheet_name_to_edit'] # The row number to delete is 1-indexed in Excel row_to_delete = df.columns.nlevels ws.delete_rows(row_to_delete) # If you want to write the name of the index into the empty cell above the index col # after deleting the row (assuming you are writing to the first column): ws['A'+str(row_to_delete)]=df.index.name # Save the modified workbook to file wb.save(filename = 'file_without_emtpy_line.xlsx') While its not ideal to have to import an entire package to handle this, my usage case required me to not simply hide the missing row. @lrnzcig's solution is much better if you can get away with only having to hide the empty row.
type: Answer

http://stackoverflow.com/comment/92043461
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52552185
has text: @trozen, working thanks
score: 0

http://stackoverflow.com/q/52553445
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92064761
answer count: 1
has answer: http://stackoverflow.com/a/52582980
tagged with: render
tagged with: jinja2
has body: There is a file api.yml containing a config for ansible: config/application.properties: server.port: 6081 system.default.lang: rus api.pdd.url: "http://{{ stage['PDD'] }}" api.policy.alias: "integration" api.order.url: "http://{{ stage['Order'] }} api.foo.url: "http://{{ stage['FOO'] }} There is a stage.yml containing the key and the stage values: default_node: Order: '172.16.100.40:8811' PDD: '172.16.100.41:8090' FOO: '10.100.0.11:3165 In fact, these files are larger and the 'stage' variables are also many. My task is to parse api.yml and turn it into properties-config. The problem is that I can not pull up the values ​​{{stage ['value']}} I'm trying to do it this way: stream = yaml.load(open('api.yml')) result={} result.update(stream['config/application.properties']) context= yaml.load(open('stage.yml')) stage={} stage.update(context['default_node']) text = '{% for items in result | dictsort(true)%} {{ items[0] }} = {{ items[1] }} {%endfor%}' template = Template(text) properti = (template.render(result=result, stage=stage)) At the output I get this: server.port = 6081 system.default.lang = rus api.pdd.url = http://{{ stage['PDD'] }} api.policy.alias = integration api.order.url = http://{{ stage['Order'] }} api.foo.url = http://{{ stage['FOO'] }} And you need to get this: server.port = 6081 system.default.lang = rus api.pdd.url = 172.16.100.41:8090 api.policy.alias = "integration" api.order.url = 172.16.100.40:8811 api.foo.url = 10.100.0.11:3165 Can I do it with jinja or ansible lib? Sorry for my bad english
has title: Render variables from a file
accepted answer: http://stackoverflow.com/a/52582980
tagged with: ansible
type: AnsweredQuestion
tagged with: yaml
downvote count: 0
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/52493112
has body: import math and use ceil import math decimals = 3 v = 1.234566789 print(math.ceil(v*pow(10,decimals))/pow(10,decimals)) # 1.234 or if you want an intger like "threshold" just use print(float(int(v))) # 1.0
has comment: http://stackoverflow.com/comment/91926963
score: 0
answers question: http://stackoverflow.com/q/52492966
type: Answer

http://stackoverflow.com/q/52460163
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91919173
tagged with: word-embedding
tagged with: word2vec
tagged with: python
tagged with: gensim
has comment: http://stackoverflow.com/comment/91906235
has comment: http://stackoverflow.com/comment/91923686
answer count: 0
score: 1
upvote count: 1
type: Question
has title: Which Pad token in Google-News Word2vec Pre-trained Model
has comment: http://stackoverflow.com/comment/91909748
has comment: http://stackoverflow.com/comment/91949573
downvote count: 0
favorite count: 0
has body: I'm using the pre-trained model from Google to do word embedding. What kind of string should I give to the model to receive and array full of zeros? I need to pad some sentences and I need an array of zeros to embed the padding. Maybe should I create the array of zeros instead of the model?

http://stackoverflow.com/comment/92085854
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52574780
type: Comment
has text: @Carpetfizz And to answer that query, `A(6:15, 6:15)` is the result that you're expecting; not `A(5:14, 5:14)`. Indexing starts from 1 in MATLAB, not zero. And with the colon operator, both boundaries are included in MATLAB. Please see the documentation before using the function. MATLAB and NumPy are not one-to-one compatible

http://stackoverflow.com/a/52513864
has comment: http://stackoverflow.com/comment/91969009
type: Answer
accepted answer of: http://stackoverflow.com/q/52513455
upvote count: 3
score: 3
has body: Use: df = df.set_index(['wk start','car']).unstack() df.columns = df.columns.map('_'.join) df = df.reset_index() df = df.loc[:, df.fillna(0).ne(0).any()] print (df) wk start rims_tesla model 3 rims_tesla model x color_tesla model 3 \ 0 2018-09-09 19.0 17.0 grey 1 2018-09-16 21.0 14.0 pink 2 2018-09-23 NaN 13.0 NaN color_tesla model x Autopilot$_tesla model x Sunroof$_tesla model 3 0 black 3000.0 2000.0 1 yellow 3000.0 2000.0 2 white 3000.0 NaN Explanation: Reshape by set_index with unstack Flatten MultiIndex in columns by map and join Index to column by DataFrame.reset_index Last remove only 0 columns by boolean indexing with loc EDIT: can you explain this line a bit df.loc[:, df.fillna(0).ne(0).any()] ? I can't figure out what it does? There aren't any nan values. If use unstack then is possible some missing values like in this sample: print (df) wk start rims_tesla model 3 rims_tesla model x color_tesla model 3 \ 0 2018-09-09 19.0 17.0 grey 1 2018-09-16 21.0 14.0 pink 2 2018-09-23 NaN 13.0 NaN color_tesla model x Autopilot$_tesla model 3 Autopilot$_tesla model x \ 0 black 0.0 3000.0 1 yellow 0.0 3000.0 2 white NaN 3000.0 Sunroof$_tesla model 3 Sunroof$_tesla model x 0 2000.0 0.0 1 2000.0 0.0 2 NaN 0.0 So need return True values for columns which not contains all zero or all zero with NaNs (what is reason for use fillna(0)): print (df.fillna(0).ne(0)) wk start rims_tesla model 3 rims_tesla model x color_tesla model 3 \ 0 True True True True 1 True True True True 2 True False True False color_tesla model x Autopilot$_tesla model 3 Autopilot$_tesla model x \ 0 True False True 1 True False True 2 True False True Sunroof$_tesla model 3 Sunroof$_tesla model x 0 True False 1 True False 2 False False Check if at least one True with any: print (df.fillna(0).ne(0).any()) wk start True rims_tesla model 3 True rims_tesla model x True color_tesla model 3 True color_tesla model x True Autopilot$_tesla model 3 False Autopilot$_tesla model x True Sunroof$_tesla model 3 True Sunro…
answers question: http://stackoverflow.com/q/52513455
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52434972
upvote count: 0
has body: I installed BeautifulSoup with my terminal, and when i got to Python 3.7.0 shell i cannot import using 'from bs4 import BeautifulSoup' like this: &gt; &gt;&gt; from bs4 import BeautifulSoup Traceback (most recent call last): File "&lt;pyshell#26&gt;", line 1, in &lt;module&gt; &gt; from bs4 import BeautifulSoup ModuleNotFoundError: No module named 'bs4' Please help!
type: Question
has answer: http://stackoverflow.com/a/52435402
score: -1
has comment: http://stackoverflow.com/comment/91813448
tagged with: python-3.7
downvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91813430
has title: BeautifulSoup problem using 'from bs4 import BeautifulSoup' not working on Python 3.7 with mac
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91813792

http://stackoverflow.com/q/52506099
has body: every key compares with value(you may say there is spelling check betwen key and value).If there are only 2 words mismatch then print the key input={"their":"thuor","diksha","dijmno"} output=["their"] def find_correct(words_dict): count=0 final_list=[] for key,value in words_dict.items(): for i in range(len(value)): # this may need adjusting for different length words if(value[i]!=key[i]): count+=1 if(count&lt;=2): final_list.append(key) return final_list print(find_correct({"their":"thuor","diksha":"dijmno"}))
has answer: http://stackoverflow.com/a/52506203
score: -1
has comment: http://stackoverflow.com/comment/91952734
type: Question
upvote count: 0
tagged with: key-value
has title: matches key with value in dictionary
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91952807
has comment: http://stackoverflow.com/comment/91952846
type: UnansweredQuestion
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/91938085
comment on: http://stackoverflow.com/a/52497848
has text: Exactly what I need !
type: Comment
score: 0
type: AnswerComment

keyboardinterrupt
tag name: keyboardinterrupt
tags question: http://stackoverflow.com/q/52475073
type: Tag

http://stackoverflow.com/a/62776703
has body: In addition to CristiFati-s solution, a better way to avoid magic numbers, would be using the winerror of the pywin32 module: import winerror try: os.mkdir(path) except WindowsError as e: if e.winerror == winerror.ERROR_PATH_NOT_FOUND: print("Handling WindowsError 3") elif e.winerror == winerror.ERROR_FILENAME_EXCED_RANGE: print("Handling WindowsError 206") else: print("Handling other WindowsError") except: print("Handling other exceptions")
answers question: http://stackoverflow.com/q/52541181
downvote count: 0
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/q/52486306
linked to: http://stackoverflow.com/q/22613272
tagged with: python
duplicate of: http://stackoverflow.com/q/22613272
favorite count: 0
has body: I'm using openPyXl library and I'd like to store a cell value, not its formula. In the cell that I want to read there's the formula =COUNTIF(C4:C21,"M") and it returns 0, but when I read it from python read=sheet['C28'].value it returns me again =COUNTIF(C4:C21,"M"). And if i try with simply read=sheet['C28'] It returns me &lt;Cell 'Sheet1'.C28&gt; How could I get 0? Thank you
tagged with: openpyxl
downvote count: 1
tagged with: excel
has answer: http://stackoverflow.com/a/52486356
type: AnsweredQuestion
score: -1
accepted answer: http://stackoverflow.com/a/52486356
type: Question
has title: I want to read a cell value, not its formula
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/91906850
type: Comment
comment on: http://stackoverflow.com/q/52469045
type: QuestionComment
has text: Back to my very first point that your process can certainly be improved without looping on empty df using proper pandas-style vectorized operations. Please post initial sample data, so we can run your code to produce your output.
score: 0

http://stackoverflow.com/q/52541841
has comment: http://stackoverflow.com/comment/92065808
has title: Why '__module__' class attribute can differ from actual module, where class was defined?
tagged with: python
has comment: http://stackoverflow.com/comment/92023723
has comment: http://stackoverflow.com/comment/92064427
answer count: 0
has comment: http://stackoverflow.com/comment/92024118
downvote count: 1
tagged with: numpy
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10113892
has body: I'm trying to understand modules concept in python, therefore I'm trying to make some experiments to understand details more deeper :) So, I see, that ndarray is defined in numpy.core.multiarray module initially. In my opinion, its __module__ attribute have to be numpy.core.multiarray, but actually it is numpy. Why does it happen? I'm using Python 3 and numpy 1.14.3. Code to reproduce is: &gt;&gt;&gt; import numpy &gt;&gt;&gt; numpy.ndarray.__module__ 'numpy' Thank you for your answers!
linked to: http://stackoverflow.com/q/49139674
tagged with: python-module
score: 1
tagged with: module
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/a/52570514
has comment: http://stackoverflow.com/comment/92077841
score: 5
upvote count: 5
downvote count: 0
has body: You have nearly done that. Just add square brackets around right side expression. It's called list comprehension: A, B, C = [tree[hash][i] for i in "xyz"]
has comment: http://stackoverflow.com/comment/92078267
type: Answer
answers question: http://stackoverflow.com/q/52570466

http://stackoverflow.com/a/52513947
has comment: http://stackoverflow.com/comment/91971659
has comment: http://stackoverflow.com/comment/91969912
score: 1
has comment: http://stackoverflow.com/comment/91973148
has comment: http://stackoverflow.com/comment/91973042
answers question: http://stackoverflow.com/q/52513801
has comment: http://stackoverflow.com/comment/91969888
has comment: http://stackoverflow.com/comment/91969024
accepted answer of: http://stackoverflow.com/q/52513801
has comment: http://stackoverflow.com/comment/91975158
type: AcceptedAnswer
downvote count: 0
has body: Use: d = {'ClaimId':'C', 'LenderId':'L','IsWorked':'W'} df = (A.rename(columns=d) .set_index(['ClaimantId',A.groupby('ClaimantId').cumcount()]) .unstack()) df.columns = [f'{i}{j+1}' for i, j in df.columns] print (df) C1 C2 C3 L1 L2 L3 W1 W2 W3 ClaimantId 1 1.0 2.0 3.0 1.0 4.0 3.0 1.0 0.0 1.0 2 6.0 NaN NaN 1.0 NaN NaN 1.0 NaN NaN df1 = B.join(df, on='ClaimantId') print (df1) ClaimantId Forename Surname C1 C2 C3 L1 L2 L3 W1 W2 \ 0 1 Bruce Wayne 1.0 2.0 3.0 1.0 4.0 3.0 1.0 0.0 1 2 Peter Parker 6.0 NaN NaN 1.0 NaN NaN 1.0 NaN W3 0 1.0 1 NaN Explanation: First rename columns by dict Then set_index by counter Series created by cumcount Reshape by unstack Flatten MultiIndex columns by list comprehension with f-strings Last join second DataFrame EDIT: If need same length all columns use reindex by new MultiIndex created by range: d = {'ClaimId':'C', 'LenderId':'L','IsWorked':'W'} df = (A.rename(columns=d) .set_index(['ClaimantId',A.groupby('ClaimantId').cumcount()]) .unstack()) mux = pd.MultiIndex.from_product([df.columns.get_level_values(0).unique(), range(5)]) df = df.reindex(columns=mux, fill_value=0) df.columns = [f'{i}{j+1}' for i, j in df.columns] print (df) C1 C2 C3 C4 C5 L1 L2 L3 L4 L5 W1 W2 W3 W4 \ ClaimantId 1 1.0 2.0 3.0 0 0 1.0 4.0 3.0 0 0 1.0 0.0 1.0 0 2 6.0 NaN NaN 0 0 1.0 NaN NaN 0 0 1.0 NaN NaN 0 W5 ClaimantId 1 0 2 0
has comment: http://stackoverflow.com/comment/91971828
type: Answer
has comment: http://stackoverflow.com/comment/91969836
has comment: http://stackoverflow.com/comment/91973493
has comment: http://stackoverflow.com/comment/91969642
upvote count: 1

http://stackoverflow.com/comment/92013588
has text: You don't know how to write a loop? BTW although your title says recursion I can't see why you would need to write anything recursive for this.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52536958

http://stackoverflow.com/comment/91956231
type: QuestionComment
comment on: http://stackoverflow.com/q/52507860
has text: @o11c According to https://stackoverflow.com/a/39980744/987358 there is just an array `dk_entries` of entries in order of insertion. No linked list. Deleted entries are replaced by a dummy and when adding new items, a resize of the array (with removing dummies) can happen.
type: Comment
score: 1

http://stackoverflow.com/comment/132792017
comment on: http://stackoverflow.com/a/52658294
type: AnswerComment
score: 0
type: Comment
has text: @jigz it depends on what sort of data you want to gather, the users click-speed, their browser footprint? I think you'd be better off with a framework designed for web.

http://stackoverflow.com/a/58815915
upvote count: 44
accepted answer of: http://stackoverflow.com/q/52578950
has body: This is a great concise explanation about what is "causal" padding: One thing that Conv1D does allow us to specify is padding="causal". This simply pads the layer's input with zeros in the front so that we can also predict the values of early time steps in the frame: Dilation just means skipping nodes. Unlike strides which tells you where to apply the kernel next, dilation tells you how to spread your kernel. In a sense, it is equivalent to a stride in the previous layer. In the image above, if the lower layer had a stride of 2, we would skip (2,3,4,5) and this would have given us the same results. Credit: Kilian Batzner, Convolutions in Autoregressive Neural Networks
answers question: http://stackoverflow.com/q/52578950
type: AcceptedAnswer
downvote count: 0
score: 44
type: Answer

http://stackoverflow.com/a/52458525
upvote count: 2
has body: You could make pingtest accept a device_name parameter and pass to ping.exe. So, you could fetch your list() first and then iterate over that and pass each of the device to pingtest in that loop. import subprocess import pyodbc data = {} def mylist(): conn = pyodbc.connect("Driver={SQL Server};" "Server=sqlserver;" "Database=database;" "Trusted_Connection=yes;") cursor = conn.cursor() cursor.execute(''' SELECT TOP 10 Names FROM sqldatabasetable ''') results = cursor.fetchall() conn.close() return [result.Names for result in results] def pingtest(device): response = subprocess.Popen(['ping.exe', device], stdout=subprocess.PIPE).communicate()[0] response = response.decode() if 'bytes=32' in response: status = 'Up' return status else: status = 'Down' return status devices = mylist() for device in devices: print(device) print(pingtest(device))
has comment: http://stackoverflow.com/comment/91859410
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52451830
has comment: http://stackoverflow.com/comment/91859444
has comment: http://stackoverflow.com/comment/91859397
answers question: http://stackoverflow.com/q/52451830
has comment: http://stackoverflow.com/comment/91859361
has comment: http://stackoverflow.com/comment/91859320
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52508956
upvote count: 1
tagged with: montecarlo
accepted answer: http://stackoverflow.com/a/52510568
type: Question
has body: I've been working to create a Monte Carlo simulation that will run through each ID of my dataframe and yield their respective Means and Standard Deviations. I've been able to write the code to get it for any one ID, but not to iterate through the entire list of IDs in my dataframe. So I could write each line individually, but I need the code to iterate through any mutable list of IDs. Here, I've tried to create a list of lists in which each set of Monte Carlo observations can be stored (and the mean and std could be taken from). I don't believe that will be the most efficient way of coding this, but it's what I know at this point. Is there anyway to run the Monte Carlo simulation on each of the IDs (without specifically calling each)? I need to be able to add and remove various IDs and corresponding data from the list. This is a follow up on: Utilizing Monte Carlo to Predict Revenue in Python import pandas as pd import matplotlib.pyplot as plt import numpy as np ID = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Revenue = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800, 1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800] odds = [0.5, 0.6, 0.33, 0.1, 0.9, 0.87, 0.37, 0.55, 0.97, 0.09, 0.5, 0.6, 0.33, 0.1, 0.9, 0.87, 0.37, 0.55, 0.97, 0.09] d = {'ID': ID, 'Revenue': Revenue, 'Odds': odds} df = pd.DataFrame(d) df['Expected Value'] = df['Revenue']*df['Odds'] print(df) num_samples = 100 df['Random Number'] = np.random.rand(len(df)) def monte_carlo_array(df): for _ in range(len(df)): yield [] mc_arrays = list(monte_carlo_array(df)) # Fill each list with 100 observations (no filtering necessary) id_1 = [] filter_1 = (df['ID'] == 5) for _ in range(num_samples): sample = df['Revenue'] * np.where(np.random.rand(len(df)) &lt; \ df['Odds'], 1, 0) for l in monte_carlo_array(df): for i in l: mc_arrays[i].append(sample.sum()) id_1.append(sample.loc[filter_1].sum()) # Plot simulation results. n_bins = 10 plt.hist([id_1], bins=n_bins, label=["ID: 1"]) p…
has title: Monte Carlo Simulation for Multiple Entries in Python
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52510568
tagged with: pandas
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
linked to: http://stackoverflow.com/q/52173863
score: 1

http://stackoverflow.com/q/52439325
tagged with: eclipse
type: Question
has title: WEBPY / Serving static files : 'StaticApp Object has no attribute 'directory'
has answer: http://stackoverflow.com/a/54991583
upvote count: 2
has answer: http://stackoverflow.com/a/52447838
has answer: http://stackoverflow.com/a/56149981
favorite count: 0
has answer: http://stackoverflow.com/a/56236415
type: UnansweredQuestion
has body: i've got some issues serving files on my web.py application : Python 3.7 web.py ver0.40_Dev1 Eclipse Photon Release (4.8.0) app.py : import web render = web.template.render('templates/') urls = ( '/', 'index',) class index: def GET(self): return render.index() if __name__ == "__main__": app = web.application(urls, globals()) app.run() templates/index.html : HELLO I manually created /templates and /static folders And I get the following error when displaying my index on localhost : > AttributeError("'StaticApp' object has no attribute 'directory'") > Traceback (most recent call last): File > "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/web/wsgiserver/wsgiserver3.py", > line 1089, in communicate > req.respond() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/web/wsgiserver/wsgiserver3.py", > line 877, in respond > self.server.gateway(self).respond() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/web/wsgiserver/wsgiserver3.py", > line 1982, in respond > for chunk in response: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/web/httpserver.py", > line 255, in __iter__ > path = self.translate_path(self.path) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/server.py", > line 820, in translate_path > path = self.directory AttributeError: 'StaticApp' object has no attribute 'directory' Trying : (with image at the root) returns casual 404 error (files are supposed to be served from /static right?) And reaching : localhost/static returns "not found" http://webpy.org/cookbook/staticfiles seems to tell me files serving from /static file is automatically handled by web.py ? (or i don't get it) Anyway : i can't serve any file in my app.py... any help ?
tagged with: python
tagged with: web.py
answer count: 4
score: 2
downvote count: 0

http://stackoverflow.com/comment/92176550
has text: can you please provide some detail how to use request module in scrapy
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52587141

http://stackoverflow.com/comment/92097836
type: QuestionComment
has text: Also note how you are supposed to replace the newline character with an empty string (`''`), but you try to replace with a space character (`' '`).
score: 0
comment on: http://stackoverflow.com/q/52581163
type: Comment

gstreamer
tags question: http://stackoverflow.com/q/52503964
tags question: http://stackoverflow.com/q/52488247
tag name: gstreamer
tags question: http://stackoverflow.com/q/52562499
type: Tag
tags question: http://stackoverflow.com/q/52543550
tags question: http://stackoverflow.com/q/52558617

line
tags question: http://stackoverflow.com/q/52520480
tags question: http://stackoverflow.com/q/52504218
tag name: line
tags question: http://stackoverflow.com/q/52491531
tags question: http://stackoverflow.com/q/52582885
type: Tag

http://stackoverflow.com/comment/92067067
comment on: http://stackoverflow.com/a/52563655
score: 0
type: AnswerComment
type: Comment
has text: Vaishali, you solution does not seem to be working as I get the error: "Could not operate 1 with block values must be str, not int"

http://stackoverflow.com/comment/91892958
has text: @caseWestern that concatenate isn't only for merging layers...?? I am doing early fusion kind thing. neb's answer perfectly works to me.thanks
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52449207

http://stackoverflow.com/q/52436197
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91821906
tagged with: null
downvote count: 0
has answer: http://stackoverflow.com/a/52439219
has body: I'm parsing my xml files and store them to a dictionary of list, where I will insert them into table at posgres using psycopg2. However, not all rows got inserted in the tables (it only inserted to the lowest number of values in the list). Here is the snippet of the dictionary of list: dict_songs = {'title' : ['Need You Now', 'GTFO'...], 'format': ['MP4', 'MP3'...], 'type' : ['Country Pop', 'R&amp;B Pop'..], 'year': [2010,2018..]} dict_movie = {'title' : ['Searching', 'Sidewalk of New York'...], 'format': ['DVD', 'Blue Ray'...], 'type' : ['Thriller', 'Romcom'..], 'year': [2018..] When I counted the length of each list in the dictionary it come up that not all the list has the same length, for example: for key, value in dict_songs.items(): #print value print(key, len([item for item in value if item])) # The result is: title 300000 format 189700 type 227294 year 227094 Title would be the primary key in the song table. When I inserted this dictionary to postgres it only shows 189700 records and not 300000. I want it to be 300000 and put Null for the null (none) values. The same goes to dict_movie This is the code I use to insert the dict list into table: keys = ['title', 'format', 'type','year'] insert_statement = 'insert into song_table (%s) values %s' for t in zip(*(dict_songs[key] for key in keys)): cur.execute(insert_statement3, (AsIs(','.join(keys)),t)) myConnection.commit() Any ideas why or how to go about this? Thank you!
tagged with: postgresql
has title: Psycopg2 - How to include 'Null' values in inserting dictionary of list to table in postgres?
answer count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/91830527
tagged with: insert-into

http://stackoverflow.com/a/52535460
type: Answer
has comment: http://stackoverflow.com/comment/92019974
score: 2
has comment: http://stackoverflow.com/comment/92010527
has comment: http://stackoverflow.com/comment/92010413
has body: You can do it like this: decoder_input = Input(shape=(coded_size,)) next_input = decoder_input # get the decoder layers and apply them consecutively for layer in autoencoder.layers[-2:]: next_input = layer(next_input) decoder = Model(inputs=decoder_input, outputs=next_input) As a side note, there is no h in your model. I think it must be replaced by coded.
accepted answer of: http://stackoverflow.com/q/52534717
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92019014
downvote count: 0
answers question: http://stackoverflow.com/q/52534717
upvote count: 2

http://stackoverflow.com/comment/92042264
comment on: http://stackoverflow.com/q/52551595
type: QuestionComment
type: Comment
score: 0
has text: Did you try the suggestions in https://stackoverflow.com/a/49991986/219640 ?

http://stackoverflow.com/a/52516587
accepted answer of: http://stackoverflow.com/q/52516549
answers question: http://stackoverflow.com/q/52516549
downvote count: 0
has comment: http://stackoverflow.com/comment/91972941
has body: Short answer: You assumption is wrong. If you evaluate the queryset, you will immediately fetch all the results in one query. So for the list(..), where you enumerate over the queryset, Django will first make a query, fetch all records with that query, and then deserialize all rows, and put it in a list. There is however linear behavior, since the size of the answer will scale with the number of records, and the amount of work to deserialize it, and put it in a list will also scale with the number of rows. If your query has prefetch_related calls, this will also result in some extra queries, but these (the number of queries) will typically scale linear with the number of prefeches, not in the number of records. If you plan to fetch a lot of foreign keys, for example: for obj in Model.objects.all(): print(obj.some_reversefk.all()) Then this will make a query per object to fetch the related object (the object to which the foreign key points). To avoid that, you can use .select_related(..) and .prefetch_related(..). The .prefetch_related(..) will make one or two extra queries, but will fetch all related objects, at once. So you can use: Model.objects.prefetch_related('some_m2m')
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/91972995

http://stackoverflow.com/a/52533563
has comment: http://stackoverflow.com/comment/92006699
accepted answer of: http://stackoverflow.com/q/52533429
type: Answer
has comment: http://stackoverflow.com/comment/92018681
answers question: http://stackoverflow.com/q/52533429
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92007952
has comment: http://stackoverflow.com/comment/92008387
has comment: http://stackoverflow.com/comment/92008047
has comment: http://stackoverflow.com/comment/92018777
has comment: http://stackoverflow.com/comment/92006641
has comment: http://stackoverflow.com/comment/92007160
upvote count: 2
has comment: http://stackoverflow.com/comment/92006666
has comment: http://stackoverflow.com/comment/92008918
type: AcceptedAnswer
has body: Use DataFrame.replace only and add whitespace to pattern: df = df.replace('[^a-zA-Z0-9 ]', '', regex=True) If one column - Series: df = pd.DataFrame({'col': ['creative-3', 'smart tech pte. ltd.', 'nutritive asia', "asia's first"], 'col2':range(4)}) print (df) col col2 0 creative-3 0 1 smart tech pte. ltd. 1 2 nutritive asia 2 3 asia's first 3 df['col'] = df['col'].replace('[^a-zA-Z0-9 ]', '', regex=True) print (df) col col2 0 creative3 0 1 smart tech pte ltd 1 2 nutritive asia 2 3 asias first 3 EDIT: If multiple columns is possible select only object, obviously string columns and if necessary cast to strings: cols = df.select_dtypes('object').columns print (cols) Index(['col'], dtype='object') df[cols] = df[cols].astype(str).replace('[^a-zA-Z0-9 ]', '', regex=True) print (df) col col2 0 creative3 0 1 smart tech pte ltd 1 2 nutritive asia 2 3 asias first 3

http://stackoverflow.com/a/52462388
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52462209
type: Answer
answers question: http://stackoverflow.com/q/52462209
downvote count: 0
score: 1
has body: If you have any object, even literal ones, it needs to use some space in memory. This memory needs to be mutated by the language runtime and it is the same if it's immutable or not. Thus mutable objects mutate memory when object gets created. Thus an immutable object is one that either is ensured not to be changed at compile time or protected by the runtime when the program runs. In python two immutable objects with the same value also have the same id, two references one value. I don't think this is guaranteed at all. Eg. x = (1,2,3) y = (1,2,3) x is y // =&gt; False When I run it in my repl. If it's anything like Common Lisp and Java it might happen that implementations are free to reuse memory locations of the same literals and thus any boolean result would be acceptable.

http://stackoverflow.com/comment/91867804
has text: trying it right now. your answer on my other thread was completely broken eh?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52462847
type: AnswerComment

http://stackoverflow.com/q/52484233
answer count: 1
downvote count: 1
tagged with: python
upvote count: 0
tagged with: classification
type: UnansweredQuestion
tagged with: machine-learning
has body: I am working on a classification problem. I have around 1000 features and target variable has 2 classes. All the 1000 features have values 1 or 0. I am trying to find feature importance but my feature importance values varies from 0.0 - 0.003. I am not sure if such low value is meaningful. Is there a way I can increase feature importance. # Variable importance rf = RandomForestClassifier(min_samples_split=10, random_state =1) rf.fit(X, Y) print ("Features sorted by their score:") a = (list(zip(map(lambda x: round(x, 3), rf.feature_importances_), X))) I would really appreciate any help! Thanks
score: -1
type: Question
has title: Increase feature importance
tagged with: random-forest
favorite count: 0
has answer: http://stackoverflow.com/a/52525480

http://stackoverflow.com/comment/92066308
comment on: http://stackoverflow.com/q/52526369
score: 0
type: Comment
type: QuestionComment
has text: @MarkRotteveel Even if I run chmod 777 on those ?

http://stackoverflow.com/comment/92034781
score: 1
has text: A link provided to where you found the code could be helpful.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52547688

http://stackoverflow.com/q/52546919
type: Question
tagged with: google-colaboratory
has comment: http://stackoverflow.com/comment/92055905
score: 0
has body: when I am trying to do Adaboosting in Colab for a kaggle competition, the project is here https://www.kaggle.com/c/competitive-data-science-predict-future-sales, it will definitely "runtime died, automatically restarting". Then, I googled some answers, one method is saying "you can type '!/opt/bin/nvidia-smi' before doing calculation. the output after doing it is: Fri Sep 28 00:48:45 2018 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 Tesla K80 Off | 00000000:00:04.0 Off | 0 | | N/A 36C P8 33W / 149W | 0MiB / 11439MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | No running processes found Thus I make sure I have all the memory, but no matter how I run my code: adb_reg = AdaBoostRegressor(base_estimator=None, n_estimators=20, learning_rate=1.0, loss='linear', random_state=None) adb_reg.fit(df[predictors],np.ravel(df[response]), sample_weight=None) I will get "runtime died...". After "enjoying" this kind of failure; can I say Colab is just a toy, and I need to find another way to do kaggle project? any suggestions?
has comment: http://stackoverflow.com/comment/92296700
answer count: 0
type: UnansweredQuestion
has title: colab runtime died, automatically restarting
tagged with: kaggle
tagged with: python

http://stackoverflow.com/q/52505501
tagged with: numpy
has title: Python – Pandas: Get max value of last 5 days
has comment: http://stackoverflow.com/comment/91953951
tagged with: pandas
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52505532
downvote count: 0
favorite count: 0
type: Question
has body: I have a csv file with two columns, date and price. I want to create a 3rd column with the max value of "Price" for the last 5 days. Not the last 5 rows or index, but 5 days. Content of "example.csv" Date Price 2018-07-23 124.44 2018-07-24 125.49 2018-07-25 123.26 2018-07-31 124.08 2018-08-01 125.10 2018-08-04 121.41 2018-08-05 119.17 2018-08-06 118.58 It should look like this: Date Price High5 2018-07-23 124.44 124.44 2018-07-24 125.49 125.49 2018-07-25 123.26 125.49 2018-07-31 124.08 124.08 2018-08-01 125.10 125.10 2018-08-04 121.41 125.10 2018-08-05 119.17 125.10 2018-08-06 118.58 121.41 With this code I get the max of the whole "Close" colum for every row. import pandas as pd df = pd.read_csv('example.csv', parse_dates=True, index_col=0) df['High5'] = df['Close'].max() print(df) With this code I get the max of the last 5 days ending with 2018-08-06 for all rows. import pandas as pd df = pd.read_csv('example.csv', parse_dates=True, index_col=0) rng = pd.date_range(end='2018-08-06', periods=5, freq='D') df['High5'] = df['Price'].loc[rng].max() print(df['High5']) I don't want the same value for all rows. And I know that it's wrong to work with a fix (ending) date. But I don't know the answer with my beginners knowledge.
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/91951737
accepted answer: http://stackoverflow.com/a/52505532
upvote count: 3
has comment: http://stackoverflow.com/comment/91951563

http://stackoverflow.com/comment/94690546
has text: https://stackoverflow.com/a/953097/941722 I think you should take a look at this answer, may be an good option.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52564639

http://stackoverflow.com/q/52535803
upvote count: 10
possible better answer: http://stackoverflow.com/a/52536583
has answer: http://stackoverflow.com/a/52536322
score: 9
type: Question
has answer: http://stackoverflow.com/a/52536212
has body: I have an OrderedDictionary that contains rate values. Each entry has a date for a key (each date happening to be the start of a yearly quarter), and the value is a number. Dates are inserted in order, from oldest to newest. { date(2017, 1, 1): 95, date(2018, 1, 1): 100, date(2018, 6, 1): 110, date(2018, 9, 1): 112, } My dictionary of rates is much larger than this, but this is the general idea. Given an arbitrary date, I want to find the value in the dictionary that precedes it. For example, looking up a date of date(2018, 8, 1) should return the value 110, since the entry date(2018, 6, 1) is the nearest key that precedes my date lookup. Similarly, a date of date(2017, 12, 1) should return 95, as the nearest preceding key happens to be date(2017, 1, 1). I could easily do this by walking the items in the dictionary: def find_nearest(lookup): nearest = None for d, value in rates.items(): if(d &gt; lookup): break nearest = value return nearest This feels inefficient to me, however, since in the worst case I have to scan the entire dictionary (which I mentioned before could be large). I will be doing tens of thousands of these kinds of lookups, so I want it to be performant. Another option to solve the performance issue would be to create a cache of what I've seen, which is also doable, though I wonder about the memory constraints (I'm not entirely sure how large the cache would grow). Are there any clever methods or Python core modules I can use here?
has title: Efficiently finding the previous key in an OrderedDictionary
favorite count: 0
accepted answer: http://stackoverflow.com/a/52536346
answer count: 5
has answer: http://stackoverflow.com/a/52536316
linked to: http://stackoverflow.com/q/52507860
tagged with: python-3.x
tagged with: python
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52536583
has comment: http://stackoverflow.com/comment/92011009
has answer: http://stackoverflow.com/a/52536346

http://stackoverflow.com/q/52463266
has body: This is the default code for Django pagination: {% load bootstrap4 %} {% with bpurl=bootstrap_pagination_url|default:"" %} &lt;ul class="{{ pagination_css_classes }}"&gt; &lt;li class="prev page-item{% if current_page == 1 %} disabled{% endif %}"&gt; &lt;a class="page-link" href="{% if current_page == 1 %}#{% else %}{% bootstrap_url_replace_param bpurl parameter_name 1 %}{% endif %}"&gt; &amp;laquo; &lt;/a&gt; &lt;/li&gt; {% if pages_back %} &lt;li class="page-item"&gt; &lt;a class="page-link" href="{% bootstrap_url_replace_param bpurl parameter_name pages_back %}"&gt;&amp;hellip;&lt;/a&gt; &lt;/li&gt; {% endif %} {% for p in pages_shown %} &lt;li class="page-item{% if current_page == p %} active{% endif %}"&gt; &lt;a class="page-link" href="{% if current_page == p %}#{% else %}{% bootstrap_url_replace_param bpurl parameter_name p %}{% endif %}"&gt; {{ p }} &lt;/a&gt; &lt;/li&gt; {% endfor %} {% if pages_forward %} &lt;li class="page-item"&gt; &lt;a class="page-link" href="{% bootstrap_url_replace_param bpurl parameter_name pages_forward %}"&gt;&amp;hellip;&lt;/a&gt; &lt;/li&gt; {% endif %} &lt;li class="last page-item{% if current_page == num_pages %} disabled{% endif %}"&gt; &lt;a class="page-link" href="{% if current_page == num_pages %}#{% else %}{% bootstrap_url_replace_param bpurl parameter_name num_pages %}{% endif %}"&gt; &amp;raquo; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; {% endwith %} So, where should I change the code to display less number of pages. The above code was retrieved from the default code of Django-bootstrap4 pagination Like displaying in this pattern :
has comment: http://stackoverflow.com/comment/91891731
answer count: 0
type: Question
has title: How to customize bootstrap pagination in Django?
score: 0
has comment: http://stackoverflow.com/comment/91869621
tagged with: bootstrap-4
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/52508705
downvote count: 0
score: 4
type: Answer
upvote count: 4
has body: Well in a dictionary keys can't repeat so we only have to deal with values. dict = {...} # get the values values = list(dict.values()) And then you can use a set() to check for duplicates: if len(values) == len(set(values)): print("no duplicates") else: print("duplicates)
answers question: http://stackoverflow.com/q/52508696

http://stackoverflow.com/comment/92065155
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52563315
has text: Converting dict.keys() to list gives compatibility with python3. I never searched why base functions like `sum` don't work anymore on arbitrary types in python3. `sum` over lists of strings was very convenient.
type: AnswerComment

http://stackoverflow.com/comment/92155234
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52597255
has text: Great to hear! Glad to help.

http://stackoverflow.com/comment/91979553
has text: I doubt you want a list of tuples of varying sizes; how do you know which field is actually missing if the tuple is shorter than usual.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52519848

http://stackoverflow.com/comment/92089390
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52453029
type: AnswerComment
has text: Thanks a lot for the detailed answer, an interesting approach.

http://stackoverflow.com/comment/91930336
type: QuestionComment
type: Comment
has text: I didn't start anything, that's why I am asking you, how will you do that
score: 0
comment on: http://stackoverflow.com/q/52494682

http://stackoverflow.com/a/52492307
has body: Try using flags=re.UNICODE Ex: import re s = """;00;RT @MeFixerr: شہباز شریف صاحب اس لگن سے جھوٹ پہ جھوٹ بول رہے ہیں جیسے اسمبلی پاکستان کی نہیں اسپین کی ہو جہاں کسی کو اردو نہیں آتی """ print(re.sub(r"[A-Za-z0-9@;:]", "", s, flags=re.UNICODE)) #Replaces English letters, numbers and symbols like @;:
answers question: http://stackoverflow.com/q/52490708
type: Answer
accepted answer of: http://stackoverflow.com/q/52490708
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/52523149
has answer: http://stackoverflow.com/a/52523223
favorite count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/91985987
has comment: http://stackoverflow.com/comment/91986020
tagged with: python
has answer: http://stackoverflow.com/a/52523593
has comment: http://stackoverflow.com/comment/91985935
has title: Python Summing characters from multiple lines of various lengths
has answer: http://stackoverflow.com/a/52523206
type: UnansweredQuestion
score: 0
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52523340
tagged with: recursion
has comment: http://stackoverflow.com/comment/91985865
has answer: http://stackoverflow.com/a/52523260
type: Question
has body: I want a function that iterates through each list item below and if the item does not being with a '>', I want the function to count the characters in each line then sum them all together''' ''' My first issue is I dont know how to use a startswith() type function with a list of strings My second issue is I don't know how to sum up all the lines together This function needs to work on lines with any number of characters. example list one_seq = ['&gt;JM_001 hypo pr\n', 'MQGNQST\n', 'HLR\n'] Recursive code I am trying to put together def get_seq_length(seq): if line in seq line.startswith('&gt;'): return sum(seq) else: length = get_seq_length(len(seq)) return length get_seq_length(one_seq)

http://stackoverflow.com/q/52582766
has answer: http://stackoverflow.com/a/52589762
has comment: http://stackoverflow.com/comment/92101171
has comment: http://stackoverflow.com/comment/92111303
type: Question
tagged with: pandas
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/52589762
score: 0
has title: Python sort out columns in DataFrame for OLS regression
answer count: 1
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/92111680
tagged with: dataframe
has body: I have a csv file with the following columns: Date|Mkt-RF|SMB|HML|RF|C|aig-RF|ford-RF|ibm-RF|xom-RF| I am trying to run a multiple OLS regression in python, regressing 'Mkt-RF', 'SMB' and 'HML' on 'aig-RF' for instance. It seems like i need to first sort out the DataFrame from the arrays but i cannot seem to understand how: # Regression x = df'Mkt-RF','SMB','HML' y = df['aig-RF'] df = pd.DataFrame({'x':x, 'y':y}) df['constant'] = 1 df.head() sm.OLS(y,df'constant','x').fit().summary() The full code is: import numpy as np import pandas as pd from pandas import DataFrame from sklearn import linear_model import statsmodels.api as sm def ReadFF(sIn): """ Purpose: Read the FF data Inputs: sIn string, name of input file Return value: df dataframe, data """ df= pd.read_csv(sIn, header=3, names=["Date","Mkt-RF","SMB","HML","RF"]) df= df.dropna(how='any') # Reformat the dates, as date-time, and place them as index vDate= pd.to_datetime(df["Date"].values,format='%Y%m%d') df.index= vDate # Add in a constant iN= len(vDate) df["C"]= np.ones(iN) print(df) return df def JoinStock(df, sStock, sPer): """ Purpose: Join the stock into the dataframe, as excess returns Inputs: df dataframe, data including RF sStock string, name of stock to read sPer string, extension indicating period Return value: df dataframe, enlarged """ df1= pd.read_csv(sStock+"_"+sPer+".csv", index_col="Date", usecols=["Date", "Adj Close"]) df1.columns= [sStock] # Add prices to original dataframe, to get correct dates df= df.join(df1, how="left") # Extract returns vR= 100*np.diff(np.log(df[sStock].values)) # Add a missing, as one observation was lost differencing vR= np.hstack([np.nan, vR]) # Add excess return to dataframe df[sStock + "-RF"]= vR - df["RF"] print(df) return df def SaveFF(df, asStock, sOut): """ Purpose: Save data for FF regressions Inputs: df dataframe, all data asStock list of strings, stocks sOut string, output file name Output: file written to disk """ df= df.dropna(how='any') asOut= ['Mk…

http://stackoverflow.com/a/52481818
downvote count: 0
upvote count: 3
has body: python supports percent as formatting option: a3 = 7 print(f"Assignment 3: {a3/25:.2%}") # 'Assignment 3: 28.00%' note that there is no need to divide by 100 when using % as format specifier. search form percent in the Format Specification Mini-Language. more information on formatting can be obtained here: https://pyformat.info/.
answers question: http://stackoverflow.com/q/52481711
type: Answer
score: 3

http://stackoverflow.com/a/52485814
answers question: http://stackoverflow.com/q/52485671
type: Answer
has comment: http://stackoverflow.com/comment/91913810
downvote count: 0
score: 1
has body: Once you have the count of the most common AA, you can loop over the counter and select the ones with the highest count: AA_count=Counter('GATTACAT') AA_most_common=AA_count.most_common(1) most_common = [AA for AA, ct in AA_count.items() if ct == AA_most_common[0][1]] print(most_common) &gt;&gt;&gt; ['A', 'T']
has comment: http://stackoverflow.com/comment/91914247
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52485671

http://stackoverflow.com/comment/91912578
type: Comment
type: QuestionComment
has text: Not sure what you mean by `get all data only if 25% is over given value`... maybe `if df['RaceRank'].quantile(.25) > 30: do_something_with_df`?
comment on: http://stackoverflow.com/q/52485496
score: 0

http://stackoverflow.com/comment/91877809
type: Comment
has text: Start by defining your `csv.writer()`, together with the header, outside of the `for row in reader:` loop.
comment on: http://stackoverflow.com/q/52467994
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91944060
has text: No, that's not what he meant because you can easily do `plt.legend(['a_4','','c'])`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52501559

http://stackoverflow.com/comment/91917681
comment on: http://stackoverflow.com/q/52430846
has text: How are you running Python? If it's through an IDE like Spyder or Pycharm then my guess is there is an option to control the window.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91884017
comment on: http://stackoverflow.com/q/52465868
type: Comment
score: 0
has text: That said, your error message is thrown because you try to use two variables in a for-loop over a simple list. But a simple list provides only one whatever per iteration, so this is wrong. Throw away the `, g` in the for loop.
type: QuestionComment

http://stackoverflow.com/comment/91956998
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52508305
score: 2
has text: This is an answer, if a bare bones one. If it wasn't a valid answer, you shouldn't be posting it to get around the reputation threshold for commenting, but in this case, it's fine, it could just use a little more detail (and removing the notes about comments).

http://stackoverflow.com/q/52477683
has answer: http://stackoverflow.com/a/69743708
has answer: http://stackoverflow.com/a/52479418
tagged with: django
has answer: http://stackoverflow.com/a/57879128
has answer: http://stackoverflow.com/a/52962384
has answer: http://stackoverflow.com/a/61928836
type: Question
answer count: 8
has body: I got this error while running the Django app file that I had downloaded from GitHub. How can I solve this problem?
has answer: http://stackoverflow.com/a/56897908
has answer: http://stackoverflow.com/a/61260929
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91896456
has answer: http://stackoverflow.com/a/52477805
score: 51
type: UnansweredQuestion
upvote count: 51
has title: ImportError: bad magic number in 'time': b'\x03\xf3\r\n' in Django
tagged with: python

http://stackoverflow.com/q/52513402
accepted answer: http://stackoverflow.com/a/52514868
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91997855
has comment: http://stackoverflow.com/comment/91967126
has answer: http://stackoverflow.com/a/52514868
tagged with: aggregate-functions
tagged with: python
has title: python pandas time series count number of previous matches
type: AnsweredQuestion
has body: Given: applications = pd.DataFrame({'application_id': [1, 2, 3, 4, 5], 'date': ['2015-01-05', '2015-01-06', '2015-01-07', '2015- 01-08', '2015-01-09'], 'client_employer': ['company A', 'company B', 'company C', 'company A', 'company B'], 'client_name': ['Bill', 'John', 'Steve', 'Bill', 'Alex']}) Table: date client_employer client_name 0 2015-01-05 company A John 1 2015-01-06 company B Bill 2 2015-01-07 company B Bill 3 2015-01-08 company A Sarah 4 2015-01-09 company B Alex 5 2015-01-10 company B Brian How many different people with the same employer do we have in past? NO LOOPS Desired output: date client_employer client_name employers_count 0 2015-01-05 company A John 0 1 2015-01-06 company B Bill 0 2 2015-01-07 company B Bill 0 3 2015-01-08 company A Sarah 1 4 2015-01-09 company B Alex 1 5 2015-01-10 company B Brian 2 Suggestion doesn't work correctly: applications = pd.DataFrame({'application_id': [1, 2, 3, 4, 5, 6], 'date': ['2015-01-05', '2015-01-06', '2015-01-07', '2015-01-08', '2015-01-09', '2015-01-10'], 'client_employer': ['company B', 'company B', 'company B', 'company B', 'company B', 'company B'], 'client_name': ['Bill', 'John', 'Steve', 'Bill', 'Alex', 'Bill'], 'cnt_desired': [0, 1, 2, 2, 3, 3]}) emp_count = applications.groupby(['client_employer'])['client_name'].transform(lambda x: x.map(dict(zip(x.unique(),np.arange(len(x.unique())))))) applications['cnt'] = emp_count application_id date client_employer client_name cnt_desired cnt 0 1 2015-01-05 company B Bill 0 0 1 2 2015-01-06 company B John 1 1 2 3 2015-01-07 company B Steve 2 2 3 4 2015-01-08 company B Bill 2 0 4 5 2015-01-09 company B Alex 3 3 5 6 2015-01-10 company B Bill 3 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/92047202
score: 0
type: Comment
type: QuestionComment
has text: yes.. i just droped the table. and created once. it is now working.
comment on: http://stackoverflow.com/q/52553680

http://stackoverflow.com/comment/91938536
score: 0
has text: check if the value contains only spaces then skip the value? It would be great to elaborate your question with the expected output. We all here are just guessing your expectation
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52498776

http://stackoverflow.com/q/52480756
answer count: 1
accepted answer: http://stackoverflow.com/a/52499807
tagged with: python
has answer: http://stackoverflow.com/a/52499807
type: AnsweredQuestion
has body: Given an existing figure of subplots of some dimension (e.g. 1 row x 9 col) how can I change it to a new dimension (subplots of 3 row x 3 col). This use case arises when using a plotting library which does not expose this control to the user (Nilearn.plotting.plot_prob_atlas for example). Initially creating the figure with the appropriate subplot dimensions, to my knowledge, is not possible.
has comment: http://stackoverflow.com/comment/91903377
has comment: http://stackoverflow.com/comment/91939187
type: Question
tagged with: matplotlib
has title: change subplot dimension of existing subplots in matplotlib
score: 0

http://stackoverflow.com/q/52564186
has answer: http://stackoverflow.com/a/52568196
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/52583677
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92067079
linked to: http://stackoverflow.com/q/13893227
tagged with: python
has title: Vectorized lookup another row + calculated field
possible better answer: http://stackoverflow.com/a/52568196
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52584757
accepted answer: http://stackoverflow.com/a/52584757
has comment: http://stackoverflow.com/comment/92067135
upvote count: 1
has comment: http://stackoverflow.com/comment/92066744
type: Question
has answer: http://stackoverflow.com/a/52564286
has body: I have this DataFrame "dfSummary" - exchangeBalances = [['ETHBTC','binance',10], ['LTCBTC','binance',10], ['XRPBTC','binance',10], ['ETHBTC','bitfinex',10], ['LTCBTC','bitfinex',10], ['XRPBTC','bitfinex',10]] bidOffers = [ ['ETHBTC','binance', 0.0035, 0.0351, datetime(2018, 9, 1, 8, 15)], ['LTCBTC','binance',0.009,0.092, datetime(2018, 9, 1, 8, 15)], ['XRPBTC','binance',0.000077, 0.000078, datetime(2018, 9, 1, 8, 15)], ['ETHBTC','bitfinex', 0.003522, 0.0353, datetime(2018, 9, 1, 8, 15)], ['LTCBTC','bitfinex',0.0093,0.095, datetime(2018, 9, 1, 8, 15)], ['XRPBTC','bitfinex',0.000083, 0.000085, datetime(2018, 9, 1, 8, 15)], ['ETHBTC','binance', 0.0035, 0.0351, datetime(2018, 9, 1, 8, 30)], ['LTCBTC','binance',0.009,0.092, datetime(2018, 9, 1, 8, 30)], ['XRPBTC','binance',0.000077, 0.000078, datetime(2018, 9, 1, 8, 30)], ['ETHBTC','bitfinex', 0.003522, 0.0353, datetime(2018, 9, 1, 8, 30)], ['LTCBTC','bitfinex',0.0093,0.095, datetime(2018, 9, 1, 8, 30)], ['XRPBTC','bitfinex',0.000083, 0.000085, datetime(2018, 9, 1, 8, 30)], ['ETHBTC','binance', 0.0035, 0.0351, datetime(2018, 9, 1, 8, 45)], ['LTCBTC','binance',0.009,0.092, datetime(2018, 9, 1, 8, 45)], ['XRPBTC','binance',0.000077, 0.000078, datetime(2018, 9, 1, 8, 45)], ['ETHBTC','bitfinex', 0.003522, 0.0353, datetime(2018, 9, 1, 8, 45)], ['LTCBTC','bitfinex',0.0093,0.095, datetime(2018, 9, 1, 8, 45)], ['XRPBTC','bitfinex',0.000083, 0.000085, datetime(2018, 9, 1, 8, 45)] ] dfExchangeBalances = pd.DataFrame(exchangeBalances, columns=['symbol','exchange','balance']) dfBidOffers = pd.DataFrame(bidOffers, columns=['symbol','exchange','bid', 'offer', 'created']) dfBidOffers["spread"] = dfBidOffers["bid"] - dfBidOffers["offer"] dfSummary = dfExchangeBalances.merge(dfBidOffers, how='left', on=['symbol','exchange']) What I need to accomplish is, add a computed field to "dfSummary": currentRow["Spread"] - someOtherRow["Spread"] "someOtherRow" is a look up based on "created" (For example last row with same {symbol, exchange} but "…
has comment: http://stackoverflow.com/comment/92066956

http://stackoverflow.com/comment/91862412
has text: `array[index % 3]`: no matter what (integer) `index` is, `index % 3` will be one of `0, 1, 2` (or more generally: `index % n` will be one of `0, 1, 2,..., n-1`).
comment on: http://stackoverflow.com/q/52460068
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92062132
has text: And why is there a loop in `rng()`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52561754
score: 0

http://stackoverflow.com/comment/93045162
has text: Hi @Elijah if you liked the answer or have any comments let me know. If you feel it is useful please accept the answer. Thanks
comment on: http://stackoverflow.com/a/52574544
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91954635
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52505906
has text: Why not simply use a histogram based approach?
score: 0

http://stackoverflow.com/comment/111439449
type: Comment
type: QuestionComment
has text: Your code works properly, entries are visible in the collection !
comment on: http://stackoverflow.com/q/52433109
score: 0

http://stackoverflow.com/comment/91972573
has text: also you can try. pip uninstall gTTs-token , which will uninstall gtts-token version==1.1.1. and thn again do pip install gTTs-token which will install new version of gTTs-token==1.1.2
comment on: http://stackoverflow.com/a/52516494
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52527545
has answer: http://stackoverflow.com/a/52537321
tagged with: python
upvote count: 2
type: Question
type: AnsweredQuestion
tagged with: aws-glue
accepted answer: http://stackoverflow.com/a/52537321
tagged with: pyspark
has body: I am new to spark. I have tried exploding a array inside of a struct. The JSON loop is a bit complex as below. { "id": 1, "firstfield": "abc", "secondfield": "zxc", "firststruct": { "secondstruct": { "firstarray": [{ "firstarrayfirstfield": "asd", "firstarraysecondfield": "dasd", "secondarray": [{ "score": " 7 " }] }] } } } I am trying to get access to score field under secondarray field to be able to calculate few metrics and come up with the average score of each id.
score: 2
has title: How to explode inner arrays in a struct inside a struct in pyspark/
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/93966717
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52490741
has text: ./toolchain.py pip install requests is what ended up doing it.
score: 2

http://stackoverflow.com/q/52549370
has answer: http://stackoverflow.com/a/52549647
type: Question
has answer: http://stackoverflow.com/a/52550011
upvote count: 5
has answer: http://stackoverflow.com/a/52550052
score: 5
answer count: 3
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92038189
has title: Why does running "setup.py test" run my console script?
has body: My very simple example project contains: addtest/ setup.py addtest/ __init__.py __main__.py app.py My app.py is just: def main(): raise SystemExit("Command line entry point called.") My __main__.py is just: from addtest.app import main main() My setup.py contains: from setuptools import setup, find_packages setup( name='AddTest', version='1.0', packages=find_packages(), entry_points={ 'console_scripts': ['addtest = addtest.app:main'] }, ) I would expect that running python setup.py test would do nothing, since no unit tests are written. However, running it in a clean virtualenv (Python 3.6.6 on Ubuntu 18.04.1) gives me: $ python setup.py test running test running egg_info writing AddTest.egg-info/PKG-INFO writing dependency_links to AddTest.egg-info/dependency_links.txt writing entry points to AddTest.egg-info/entry_points.txt writing top-level names to AddTest.egg-info/top_level.txt reading manifest file 'AddTest.egg-info/SOURCES.txt' writing manifest file 'AddTest.egg-info/SOURCES.txt' running build_ext Command line entry point called. Note the Command line entry point called. which means it's invoking the console script it generates from my __main__.py (or maybe just calling python -m addtest). Why is setup.py calling the console script when I want it to run tests? Further inspection of the script's execution shows that sys.argv is ['setup.py','test'] - why?
tagged with: setuptools

http://stackoverflow.com/comment/92009944
type: QuestionComment
has text: Is the script you're importing from the in same directory? If not, do you have a `__init__.py` script in the subdirectory where the variables are stored? Even a blank one will suffice
comment on: http://stackoverflow.com/q/52535263
score: 0
type: Comment

http://stackoverflow.com/comment/92048092
type: Comment
comment on: http://stackoverflow.com/a/52529132
has text: what is the purpose of ''.join(str_len_list)..why have you used it
type: AnswerComment
score: 0

http://stackoverflow.com/q/52574433
has comment: http://stackoverflow.com/comment/92085020
type: Question
has comment: http://stackoverflow.com/comment/92085095
has comment: http://stackoverflow.com/comment/92085036
has comment: http://stackoverflow.com/comment/92085109
tagged with: api
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/92085206
has comment: http://stackoverflow.com/comment/92085230
answer count: 1
has comment: http://stackoverflow.com/comment/92085279
has answer: http://stackoverflow.com/a/52658564
has comment: http://stackoverflow.com/comment/92084956
has body: In my application I have a Job class as defined/outlined below. Instance of this job class represents a particular Job run. Job can have multiple checkpoints and each checkpoint can have multiple commands. Job - JobName - [JobCheckpoint] - StartTime - EndTime - Status - ... JobCheckpoint - JobCheckpointName - [JobCommand] - StartTime - EndTime - Status - ... JobCommand - JobCommandName - [Command] - StartTime - EndTime - Status - ... At any given day there are like 100k different jobs that runs. Job information is persisted in File System. I want to design a user interface in Python for querying these job objects. For example users should be able to query All jobs that ran between x and y interval. All jobs that run command x. All jobs in failed state. All jobs in failed and terminated state. All checkpoints/commands of a particular job. And many more... To solve this, I was thinking of providing following method in user interface. get_jobs(Filter) I am not sure how can I design this Filter class in Python to support all such sort of queries on Job object. and to keep usage of API simple/intuitive for user. Leads here is really appreciated.
favorite count: 0
has comment: http://stackoverflow.com/comment/92084925
has comment: http://stackoverflow.com/comment/92085350
score: 5
has title: User Interface for filtering objects in Python
tagged with: python
tagged with: design-patterns
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52658564

http://stackoverflow.com/a/52489655
accepted answer of: http://stackoverflow.com/q/52489620
has body: While yes, you can use regular expressions for this problem, Python provides far simpler string functions for such tasks. Here is an example on the command line: &gt;&gt;&gt; my_string = 'There is a HeLLO_worLD in this string' &gt;&gt;&gt; 'hello_world' in my_string.lower() True
answers question: http://stackoverflow.com/q/52489620
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91920326
type: Answer
has comment: http://stackoverflow.com/comment/91920337
has comment: http://stackoverflow.com/comment/91920301

http://stackoverflow.com/comment/92132069
has text: Ok, I see what you mean, yeah that's right, my loops are totally screwed. I fixed it , but even if I use it, it works very slow, since there is a huge amount of data. Is there another method to map my labels to the array of data elements I was given?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52582899

http://stackoverflow.com/comment/91933999
has text: hmm, for remove first column use `dfnonreturnguidecount.to_csv('NonReturn_guideid_counts.csv', index=False)`
comment on: http://stackoverflow.com/a/52496083
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91877302
has text: I'm runnung it in interactive mode
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52467711

http://stackoverflow.com/comment/91955269
comment on: http://stackoverflow.com/q/52507359
has text: You can see the entire code file here https://github.com/LanceMcCarthy/MachineLearningFun/blob/master/PythonProjects/CognitiveServicesPlayground/CognitiveServicesPlayground/cognitive_services_playground.py
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52500802
has body: Here is one possible solution: You may use the fact that underscores do not produce legend entries. So setting all but the first label to "_" suppresses those to appear in the legend. import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.array([[0,1], [0,1], [0,1]]) y = np.array([[0,0], [1,1], [2,2]]) ax.plot([0,1],[0,2], label='foo', color='b') lines = ax.plot(x.T, y.T, label='bar', color='k') plt.setp(lines[1:], label="_") ax.legend() plt.show()
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52497476
upvote count: 8
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/52497476

http://stackoverflow.com/comment/91937932
has text: Do share some sample input and desired output?
type: QuestionComment
comment on: http://stackoverflow.com/q/52498449
score: 1
type: Comment

http://stackoverflow.com/comment/91991848
has text: @panktijk thanks so much...now it's work, I change the separator from comma to semicolon and now it's work very well
score: 0
comment on: http://stackoverflow.com/q/52525693
type: Comment
type: QuestionComment

search
tags question: http://stackoverflow.com/q/52533016
tags question: http://stackoverflow.com/q/52499239
type: Tag
tags question: http://stackoverflow.com/q/52543659
tags question: http://stackoverflow.com/q/52573393
tag name: search

http://stackoverflow.com/comment/91892066
has text: Thanks for your reply, I tried your code just now, the graph shows, but there are some problems with xaxis, there are lots of overlapped y-values, I think it's because the xaxis are seconds units, but there are lots of days in txt file, if the xaxis is not the 'date & time' unit, then is the graph not perfect. So I changed `x = [row.split()[-1]` for row in data] to `x = [row.split()[6]` for row in data], then the graph is better. Although I don'T know the difference between -1 and 6, but that works after all. Thank you a lot !
comment on: http://stackoverflow.com/a/52445577
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52575965
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52574857
downvote count: 0
has body: You missed to pass an id as argument. I mean it should be something like this def mutate(root, info, id=None, input=None): or def mutate(self, info, **args): you will have id and input inside args.
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/52574857

http://stackoverflow.com/comment/91918368
comment on: http://stackoverflow.com/a/52488525
type: AnswerComment
score: 0
type: Comment
has text: Thank you for your comment. I tried changing it to as you suggested. And i am trying to open the csv file in excel. The data in the file looks messed up. Is it because the encoded bytes are two big so that the excel is trying to compress it?

http://stackoverflow.com/q/52448562
accepted answer: http://stackoverflow.com/a/52449066
has comment: http://stackoverflow.com/comment/91840935
answer count: 1
downvote count: 0
favorite count: 0
has title: Replace a string with the middle section of that string in csv with Python
has answer: http://stackoverflow.com/a/52449066
tagged with: python
has comment: http://stackoverflow.com/comment/91840186
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91840287
has comment: http://stackoverflow.com/comment/91840097
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91840234
has body: I'm trying to replace a string in the first column of a csv and have been running into some issues, namely an 'AttributeError: NoneType object has no attribute group' error. When using code like this as a test things work fine. ``` import re array = [['aaa-bbb-ccc_dddL_eee_V00T00000-00_00000_V00T00000-00_00000_ACK_00000000.XML', '907 ', 'Sep 13 2018 18:07', ' '], ['V11T11111-11_11111_V11T11111-11_11111_ACK_11111111.XML', '875','Jan 31 2018 00:00',' ']] print(array, end='\n\n') for item in array: m = re.search(r'(\D\d+\D\d+\-\d+)', item[0]) print(m.group(),end='\n\n') item[0] = m.group() print(item,end='\n\n') ``` But when trying to implement this in a script that opens a csv that would have an array of a similar structure (just many more arrays in the array) I receive the NoneType error. ``` with open('./input.csv', 'r') as f: reader = csv.reader(f) for row in read`enter code here`er: m = re.search(r'(\D\d+\D\d+\-\d+)', row[0]) row[0] = m.group() ``` I not quite sure why things don't work with the second implementation since I am indeed getting matches in the csv. Any help would be greatly appreciated. Thanks.
type: Question

http://stackoverflow.com/comment/92057625
type: QuestionComment
comment on: http://stackoverflow.com/q/52559452
score: 0
type: Comment
has text: Within the 25th and 75th percentile of which column? And if its all the columns do you mean depth as well (since it has a different kind of label to all the other columns) I suspect you might mean keep the value of that column WHERE the others are within the limits but if those limits apply to all the other columns the then what is supposed to happen? Short version - what do you expect to see?

http://stackoverflow.com/q/52497739
tagged with: python-requests
type: Question
has body: I want to set requests 'user-agent' header globally. But I can't find any way to do it. Can anyone help me?
answer count: 2
has answer: http://stackoverflow.com/a/66661349
has answer: http://stackoverflow.com/a/52497819
upvote count: 7
downvote count: 1
has title: How to set requests 'user-agent' header globally
favorite count: 0
type: UnansweredQuestion
score: 6
tagged with: python
linked to: http://stackoverflow.com/q/10606133

http://stackoverflow.com/comment/91877504
has text: Are you getting any crash or error?? Please share that.
type: AnswerComment
comment on: http://stackoverflow.com/a/52467723
score: 0
type: Comment

http://stackoverflow.com/comment/92059113
score: 0
type: AnswerComment
type: Comment
has text: i am purposely trying to not use range(len(num_list) - 1). trying to be a little more pretty about it :) Thank you for your response
comment on: http://stackoverflow.com/a/52560244

http://stackoverflow.com/q/52541181
upvote count: 3
type: Question
has body: I am creating a new nested directory (data_dir = 'parent\child') in python: try: os.mkdir(data_dir) except WindowsError: pass If the parent directory 'parent' did not exists (yet, 'cause I might be setting later in the code), then the code caught that as a Windows Error 3 and moved on. However now what could also happen is Windows Error 206 which is when the filename or extension is too long. For which I would need to take a separate action. Is there a way to distinguish between Windows Error 3 and 206 (and others) so as to raise distinct Exceptions?
has answer: http://stackoverflow.com/a/52541414
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92029047
has comment: http://stackoverflow.com/comment/92029276
favorite count: 0
accepted answer: http://stackoverflow.com/a/52541414
has title: Catch a specific `Windows Error` number - python
tagged with: exception
score: 3
tagged with: windows
tagged with: python
possible better answer: http://stackoverflow.com/a/62776703
has answer: http://stackoverflow.com/a/62776703
type: AnsweredQuestion

http://stackoverflow.com/a/52471038
upvote count: 3
score: 1
downvote count: 2
has comment: http://stackoverflow.com/comment/91884051
answers question: http://stackoverflow.com/q/52471032
has body: You are missing a closing parenthesis ) in the two of your following lines. The correct line of code is num = (int(input("Enter an integer"))) Also, as sheepez mentioned below, your outer brackets are redundant. You can simply use num = int(input("Enter an integer"))
has comment: http://stackoverflow.com/comment/91918475
has comment: http://stackoverflow.com/comment/91884084
type: Answer

http://stackoverflow.com/comment/92037009
type: Comment
score: 1
has text: What do you mean by "input"? Is this the content of some ascii file? Do you want to import it? Or should that really be input manually number by number by a user in your nested loop...?
comment on: http://stackoverflow.com/q/52548928
type: QuestionComment

http://stackoverflow.com/q/52513271
type: Question
has answer: http://stackoverflow.com/a/52513552
has answer: http://stackoverflow.com/a/52513530
score: -2
has comment: http://stackoverflow.com/comment/91966458
has comment: http://stackoverflow.com/comment/91966463
has comment: http://stackoverflow.com/comment/91966234
answer count: 3
upvote count: 0
has body: I've currently got an issue where I need to read N lines from a text file, there is 50 lines total, but I want to give my user the choice of how many are picked. I don't know where to start.
favorite count: 0
has answer: http://stackoverflow.com/a/52513422
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91966261
has comment: http://stackoverflow.com/comment/91966402
tagged with: python
has title: Reading a few lines in Python
downvote count: 2
tagged with: file

http://stackoverflow.com/comment/92000349
comment on: http://stackoverflow.com/q/52530541
type: Comment
type: QuestionComment
has text: This is the wrong forum: read the text of your tag.
score: 0

http://stackoverflow.com/comment/92033518
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52460097
type: Comment
has text: Please accept my answer if you think it was of use to you.

http://stackoverflow.com/comment/91915692
type: Comment
has text: Happy it worked out. You can change the environment variables in `os.environ` for each key (PATH being the important one), or use it before your system calls. (`os.system(printenv + shellscript)`, with `printenv` being a string containing the terminal `printenv output`)
comment on: http://stackoverflow.com/a/52484664
score: 0
type: AnswerComment

http://stackoverflow.com/comment/93259731
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52575210
type: Comment
has text: I actually should have edited the question. I didn't want to use KFold actually at all. I wanted to get a logic which would randomly divide the data into 10 groups at once. Such a method is not available I guess in any of the module. I made my own logic. However, if there is some optimised solution I would be grateful.

http://stackoverflow.com/comment/91989918
comment on: http://stackoverflow.com/q/52524761
score: 0
type: Comment
type: QuestionComment
has text: @Divakar, unfortunately not

http://stackoverflow.com/q/52469050
type: Question
has title: send_push_message() missing 4 required positional arguments: 'token', 'title', 'message', and 'extra'
tagged with: python
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52470637
type: AnsweredQuestion
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/52470637
has body: I keep getting this error: send_push_message() missing 4 required positional arguments: 'token', 'title', 'message', and 'extra', what can i do? def receive_request(request, self): self.token = request.data['token'] self.title = request.data['title'] self.message = request.data['message'] self.extra = request.data['extra'] @api_view(["POST"]) @permission_classes((AllowAny, )) def send_push_message(self, token, title, message, extra): token = self.token title = self.title message = self.message extra = self.extra #it continues from here

http://stackoverflow.com/a/52550011
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52549370
type: Answer
has body: The test scanner in setuptools will look for tests in any *.py file found in your sub-directories, except for __init__.py. Yes, this includes __main__.py, it will call __import__() on it, causing its main suite to be executed. If you want to be able to run python -m addtest and have that run your __main__.py code, you may want to add the standard 'run only if this is really main' protection: if __name__ == "__main__": ... (then, if you do python -m the code will run, but it won't run if the file is loaded by setup.py test)
score: 2

image-processing
tags question: http://stackoverflow.com/q/52555016
tags question: http://stackoverflow.com/q/52479045
tags question: http://stackoverflow.com/q/52456871
tags question: http://stackoverflow.com/q/52436652
tags question: http://stackoverflow.com/q/52436030
tags question: http://stackoverflow.com/q/52566672
tags question: http://stackoverflow.com/q/52467592
tags question: http://stackoverflow.com/q/52443426
tags question: http://stackoverflow.com/q/52483836
tags question: http://stackoverflow.com/q/52508728
tags question: http://stackoverflow.com/q/52459794
tags question: http://stackoverflow.com/q/52587924
tags question: http://stackoverflow.com/q/52520031
tags question: http://stackoverflow.com/q/52578621
tags question: http://stackoverflow.com/q/52560845
tags question: http://stackoverflow.com/q/52449207
type: Tag
tags question: http://stackoverflow.com/q/52437002
tags question: http://stackoverflow.com/q/52505906
tags question: http://stackoverflow.com/q/52495105
tags question: http://stackoverflow.com/q/52572051
tags question: http://stackoverflow.com/q/52554457
tags question: http://stackoverflow.com/q/52471817
tags question: http://stackoverflow.com/q/52463149
tags question: http://stackoverflow.com/q/52459025
tags question: http://stackoverflow.com/q/52576498
tags question: http://stackoverflow.com/q/52496387
tag name: image-processing
tags question: http://stackoverflow.com/q/52473190
tags question: http://stackoverflow.com/q/52452155
tags question: http://stackoverflow.com/q/52445834

http://stackoverflow.com/comment/91929614
score: 0
type: Comment
type: QuestionComment
has text: I am still trying... I thought maybe someone here knows how to make it work.
comment on: http://stackoverflow.com/q/52493979

http://stackoverflow.com/comment/91811848
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52433940
type: Comment
has text: Great first post Terrel! I especially appreciate the fact that you liked directly to the relevant references.

http://stackoverflow.com/q/52493981
has answer: http://stackoverflow.com/a/52494006
accepted answer: http://stackoverflow.com/a/52494006
answer count: 3
tagged with: pandas
has body: Below is my dataframe: Id,ReturnCreated,ReturnTime,TS_startTime O108808972773560,Return Not Created,nan,2018-08-23 12:30:41 O100497888936380,Return Not Created,nan,2018-08-18 14:57:20 O109648374050370,Return Not Created,nan,2018-08-16 13:50:06 O112787613729150,Return Not Created,nan,2018-08-16 13:15:26 O110938305325240,Return Not Created,nan,2018-08-22 11:03:37 O110829757146060,Return Not Created,nan,2018-08-21 16:10:37 I want to replace the nan with Blanks. Tried the below code, but its not working. import pandas as pd import numpy as np df = pd.concat({k:pd.Series(v) for k, v in ordercreated.items()}).unstack().astype(str).sort_index() df.columns = 'ReturnCreated ReturnTime TS_startTime'.split() df1 = df.replace(np.nan,"", regex=True) df1.to_csv('OrderCreationdetails.csv') Kindly help me understand where i am going wrong and how can i fix the same.
downvote count: 0
has answer: http://stackoverflow.com/a/52494209
favorite count: 0
has answer: http://stackoverflow.com/a/52494099
tagged with: python
type: AnsweredQuestion
has title: Replacing nan with blanks in Python
has comment: http://stackoverflow.com/comment/91928757
upvote count: 10
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52494099
score: 10

http://stackoverflow.com/a/52483615
downvote count: 0
has comment: http://stackoverflow.com/comment/91911699
has body: There is three possibilities: Way 1 - hide the curve (but keep the data): import matplotlib.pyplot as plt list1=[1,2,3] list2=[4,5,6] fig1=plt.figure(1) plot_list1 = plt.plot(list1) plot_list2 = plt.plot(list2) plt.setp(plot_list2,"visible",False) #hide the list2 curve plt.show() Way 2 - Remove the data: import matplotlib.pyplot as plt list1=[1,2,3] list2=[4,5,6] fig1=plt.figure(1) plot_list1 = plt.plot(list1) plot_list2 = plt.plot(list2) plt.setp(plot_list2,"data",([],[])) #remove list2 data plt.show() Way 3 - Remove the curve: import matplotlib.pyplot as plt list1=[1,2,3] list2=[4,5,6] fig1=plt.figure(1) plot_list1 = plt.plot(list1) plot_list2 = plt.plot(list2) plot_list2[0].remove() plt.show()
type: AcceptedAnswer
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91910197
answers question: http://stackoverflow.com/q/52483327
accepted answer of: http://stackoverflow.com/q/52483327

http://stackoverflow.com/a/52546515
has comment: http://stackoverflow.com/comment/92069413
upvote count: 3
has comment: http://stackoverflow.com/comment/92034605
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92068725
has body: Read the datetime column as timestamp and localize to US/Eastern time and then apply tz_convert df['colA (EST)'] = pd.to_datetime(df['colA (EST)']).dt.tz_localize('US/Eastern') df['colC (timestamp in local tz) '] = df.apply(lambda x: x['colA (EST)']\ .tz_convert(x['colB (local tz)']), axis = 1) colA (EST) colB (local tz) colC (timestamp in local tz) 0 2016-09-19 01:29:13-04:00 US/Central 2016-09-19 00:29:13-05:00 1 2016-09-19 02:16:04-04:00 Etc/GMT+2 2016-09-19 04:16:04-02:00 2 2016-09-19 01:57:54-04:00 Europe/London 2016-09-19 06:57:54+01:00
type: Answer
has comment: http://stackoverflow.com/comment/92056109
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52546068
score: 3
answers question: http://stackoverflow.com/q/52546068

http://stackoverflow.com/comment/92086065
has text: I understand that part, but I am not entirely sure how I would go about pulling the proper api key, and then changing the cool down value under it. Is there a way to call a section and modify the values inside said section?
comment on: http://stackoverflow.com/q/52575212
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92098318
comment on: http://stackoverflow.com/a/52581471
has text: @Jean-FrançoisFabre nice catch, thanks! Edited that in to my answer (with the proper attribution, of course)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52558795
has comment: http://stackoverflow.com/comment/92056330
has answer: http://stackoverflow.com/a/52558948
type: Question
has answer: http://stackoverflow.com/a/52559007
linked to: http://stackoverflow.com/q/2257441
has title: How can I resolve maximum recursion depth error
has answer: http://stackoverflow.com/a/52559445
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/92056490
has body: I'm generating a random password with a desired length. I want it to have at least 2 uppercase letters, 2 lowercase letters, 2 digits and 2 special characters. I've tried multiple things, but every time I get this recursion depth error. Can anybody tell me what I've done wrong? list_lower =['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'] list_upper = ['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'] list_digit = [1,2,3,4,5,6,7,8,9,0] def generatePassword(desiredLength: int) -&gt; str: x = 0 password = "" for x in range (desiredLength): password = password + chr(random.randint(33,126)) list(password) list_password = list(password) times_lower = 0 times_upper = 0 times_digit = 0 times_special = 0 for character in list_password: if character in list_lower: times_lower += 1 elif character in list_upper: times_upper += 1 elif character in list_digit: times_digit += 1 else: times_special +=1 if times_lower &gt;= 2 and times_upper &gt;= 2 and times_digit &gt;= 2 and times_special &gt;= 2: return password else: return generatePassword(desiredLength) generatePassword(7) I get the error in line 30 which makes the function recursive.
has comment: http://stackoverflow.com/comment/92056265
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92056362
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92056335
has comment: http://stackoverflow.com/comment/92058411
tagged with: python
has comment: http://stackoverflow.com/comment/92056577
has comment: http://stackoverflow.com/comment/92056405
has comment: http://stackoverflow.com/comment/92056684

http://stackoverflow.com/a/52452126
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52451647
answers question: http://stackoverflow.com/q/52451647
has comment: http://stackoverflow.com/comment/91850842
upvote count: 2
has comment: http://stackoverflow.com/comment/91850833
has comment: http://stackoverflow.com/comment/91850965
has comment: http://stackoverflow.com/comment/91850911
type: AcceptedAnswer
has body: Seems like you need &gt;&gt;&gt; mannwhitneyu(k1, k2).pvalue 0.21078755520484055 &gt;&gt;&gt; mannwhitneyu(k1, k2).statistic 3201.5
type: Answer

http://stackoverflow.com/a/52443337
answers question: http://stackoverflow.com/q/52443126
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91836762
has comment: http://stackoverflow.com/comment/135851246
has comment: http://stackoverflow.com/comment/91829813
has body: Google does not offer an endpoint to do an unauthenticated search on a user by email address. If you have access to run a gmail users then you should ask the user for profile scope as well. then you can do GET https://www.googleapis.com/plus/v1/people/me The response will contain a link to the image of the user. If you are looking for pictures of random users then this is not something you can do.
type: Answer
has comment: http://stackoverflow.com/comment/91841366
has comment: http://stackoverflow.com/comment/91831397
upvote count: 2
has comment: http://stackoverflow.com/comment/135847776

http://stackoverflow.com/comment/92164504
comment on: http://stackoverflow.com/q/52463351
has text: See corresponding [PEP](https://www.python.org/dev/peps/pep-0484/)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/92421694
type: Comment
type: QuestionComment
has text: NB: depending on the task at hand, you may be (a lot) better off using a live Jupyter notebook, for which you can construct the environment (packages etc) yourself, if you use a "binder". See for example https://mybinder.org/ (note: universities and schools start using these binders quite a bit for teaching. Perhaps they'll take the hint ;-).
score: 0
comment on: http://stackoverflow.com/q/52535464

http://stackoverflow.com/comment/91996134
comment on: http://stackoverflow.com/q/52528287
has text: What do you want to happen when `line[i]` or `row[n]` is an empty string? It'd be great if you could post a simple [mcve] with expected output. That will help to clarify your question and also allow others to confirm their solutions match what you're looking for.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/92086587
comment on: http://stackoverflow.com/a/52575320
type: Comment
has text: Would this work for larger lists i.e when **len(list_of_ppl) > 10** and when len(list_of_ppl) is not divisible by 3?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52525332
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/92127694
has comment: http://stackoverflow.com/comment/92069118
tagged with: raspberry-pi3
score: 0
has body: I have a project that involves running 35 LCDs. I obviously cannot power this through my raspberry pi 3 so I have opted to run it from a separate power source. However, I am getting a "Remote I/O error" when I try to display my text to the LCDs. I am also using an i2c serial backpack with each LCD. Also, I hooked the SDA and SDL lines directly to a LCD to see if it was a wiring problem, but the sudo i2cdetect -y 1 command returned nothing. If taken off the alternative power source and plugged into the RPi's 5V and GND pins it gives an address of 0x3b. I thought that the 5V and GND pins were strictly for giving the LCD power. Is this not the case? Do they have to run off the same power source? Do the RPi pins have to be interfacing with the power source of the pins in some way? What else could be causing this error? Here is the error message: pi@raspberrypi:~ $ sudo python Hi1.py Traceback (most recent call last): File "Hi1.py", line 11, in &lt;module&gt; mylcd = I2C_LCD_driver2_3b.lcd() File "/home/pi/I2C_LCD_driver2_3b.py", line 122, in __init__ self.lcd_write(0x03) File "/home/pi/I2C_LCD_driver2_3b.py", line 147, in lcd_write self.lcd_write_four_bits(mode | (cmd &amp; 0xF0)) File "/home/pi/I2C_LCD_driver2_3b.py", line 142, in lcd_write_four_bits self.lcd_device.write_cmd(data | LCD_BACKLIGHT) File "/home/pi/I2C_LCD_driver2_3b.py", line 34, in write_cmd self.bus.write_byte(self.addr, cmd) IOError: [Errno 121] Remote I/O error Here is the Hi1.py script (essentially just a Hello_World.py) import I2C_LCD_driver2_3b from time import * f = open(r'C:\temp\output1.txt','r') data = f.read() line_1 = data[:14] line_2 = data[15:29] mylcd = I2C_LCD_driver2_3b.lcd() mylcd.lcd_display_string(line_1, 1) mylcd.lcd_display_string(line_2, 2) Here is the I2C_LCD_driver2_3b.py script # -*- coding: utf-8 -*- # Original code found at: # https://gist.github.com/DenisFromHR/cc863375a6e19dce359d """ Compiled, mashed and generally mutilated 2014-2015 by Denis Pleic Made available under GNU…
has title: Trouble Displaying to LCDs Powered from a Different Source
type: UnansweredQuestion
tagged with: python
tagged with: lcd

http://stackoverflow.com/comment/92020702
type: AnswerComment
has text: Yes, change the grouping columns, so that it's `df[mask].groupby(['Account', 'Date']).Value.transform('mean')`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52538907

http://stackoverflow.com/comment/91824331
score: 0
has text: Thanks a lot! This was very helpful.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52440611

http://stackoverflow.com/q/52447723
possible better answer: http://stackoverflow.com/a/52498330
accepted answer: http://stackoverflow.com/a/65028750
tagged with: python
upvote count: 6
tagged with: minimum-spanning-tree
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52451415
score: 6
tagged with: networkx
type: Question
tagged with: graph
has title: Networkx: Creating a complete graph for a given set of nodes
answer count: 3
has body: I have a list as c4_leaves = [56,78,90,112]. I'm trying to create a complete graph using these elements in c4_leaves as nodes. Here's what I've tried: V_ex = c4_leaves G_ex = nx.Graph() G_ex.add_nodes_from(V_ex) G_ex = nx.complete_graph(4) for u,v in G_ex.edges(): G_ex[u][v]['distance'] = distance(points33, u, v) And then the minimum spanning tree of the above graph as: T_ex = nx.minimum_spanning_tree(G_ex, weight='distance') F_ex = list(T_ex.edges()) When I draw G_ex, it gives me the correct graph, but when I print details of the minimum spanning tree, it shows that T_ex.nodes() = [0,1,2,3,56,78,90,112]. Can someone show me the mistake I'm making?
has answer: http://stackoverflow.com/a/52498330
downvote count: 0
has answer: http://stackoverflow.com/a/65028750
favorite count: 0

http://stackoverflow.com/a/60623211
answers question: http://stackoverflow.com/q/52443217
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: You can set up a shell script and run it with a configuration. For example, assuming a project structure like this... /project /src main.py /test test_something.py ...this shell script will run all the tests in the /test directory against the source files in the /src directory and open a browser with the HTML results: # contents of test_coverage.sh coverage erase coverage run --source=./src -m unittest discover ./test coverage report -m coverage html open ./htmlcov/index.html This script is written for Mac using unittest, but you can modify it for whatever OS and test runner you're using. Of course, you can also modify it to run whatever commands you want. For example, if you don't want to generate or open the HTML results, just remove the last two lines. If your project structure looks different, modify the --source=./src and ./test arguments for the coverage run command. This shell script should be run from the root /project folder. Make sure import statements in your test_*.py files are relative to that folder. This can easily be overlooked in PyCharm since source directories may be added to PYTHONPATH for you. Save the shell script as test_coverage.sh (or whatever you want to name it) and put it in the root /project folder. Then add a Shell Script run configuration in PyCharm with the script path to that file. PyCharm Run Configuration When you run the configuration in PyCharm, you should get a report in the terminal and your default browser should open the HTML report (assuming you use the commands above).

http://stackoverflow.com/q/52462641
has body: I have a simple Python/Selenium script that has to wait for 4 checks to happen. Each of these on a separated thread. On the first thread that returns information, the program should continue and the remaining threads killed (if possible). I have a program that is creating the threads just fine, but I have no idea on how to continue on the first that have executed. these are my function definitions: def wait_by(search_type, locator, timeout): WebDriverWait(driver, timeout).until(EC.presence_of_element_located((search_type, locator))) def multi_locator_verify_element(xpath_locator, css_locator, name_locator, id_locator, timeout): element = "" if xpath_locator != "": tx = Thread(target=wait_by, args=(By.XPATH, xpath_locator, timeout)) tx.start() if css_locator != "": tc = Thread(target=wait_by, args=(By.CSS, css_locator, timeout)) tc.start() if name_locator != "": tn = Thread(target=wait_by, args=(By.NAME, name_locator, timeout)) tn.start() if id_locator != "": ti = Thread(target=wait_by, args=(By.ID, id_locator, timeout)) ti.start() The multi_locator_verify_element function should finish after the first thread has been able to retrive the right element. Could someone please help me with that? Regards,
tagged with: python
has comment: http://stackoverflow.com/comment/92379585
favorite count: 0
answer count: 0
linked to: http://stackoverflow.com/q/26590638
type: UnansweredQuestion
has title: Waiting for any of a group of threads to finish Python
tagged with: multithreading
tagged with: selenium
upvote count: 1
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91923400
downvote count: 0

http://stackoverflow.com/q/52436090
score: -3
upvote count: 1
tagged with: python
has title: Why is it so in python?
has comment: http://stackoverflow.com/comment/91815451
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/91815469
has comment: http://stackoverflow.com/comment/91815423
answer count: 1
has answer: http://stackoverflow.com/a/52436184
has comment: http://stackoverflow.com/comment/91815441
has comment: http://stackoverflow.com/comment/91815403
favorite count: 0
has body: I'm swamped with this logic: n1=10 n2=3 n3=7 n1 = float(("1st")) n2 = float(("2nd")) n3 = float(("3rd")) if n1&gt;=n2 and n1&gt;=n3: h=n1 elif n2&gt;=n1 and n2&gt;=n3: h=n2 else: h=n3 print(h) I garner up with input as follows: n1 54.0 n2 3 n3 7 It compiled fine, but shows strange output: 1st54 2nd It don't even taking input for 2nd number, rather it shows "program terminated". Pls run it on your pc for better understanding.
type: UnansweredQuestion

http://stackoverflow.com/comment/92068987
type: Comment
type: QuestionComment
has text: Possible duplicate of https://stackoverflow.com/questions/6986986/bin-size-in-matplotlib-histogram
comment on: http://stackoverflow.com/q/52565666
score: 0

http://stackoverflow.com/a/52567221
downvote count: 0
answers question: http://stackoverflow.com/q/52567189
type: Answer
score: 2
has body: mystr1 = "1==1 or 1==2" mystr2 = "1==1 and 1==2" # will output True print(eval(mystr1)) # will output False print(eval(mystr2)) If you have a mathematical expression, there is a more elegant way using Pyparsing. Check out this post: from Stackoverflow
upvote count: 2

http://stackoverflow.com/comment/91982175
type: AnswerComment
type: Comment
has text: Can you please explain what "inherently nondifferentiable operation" means?
comment on: http://stackoverflow.com/a/52520428
score: 0

http://stackoverflow.com/comment/91828592
type: Comment
comment on: http://stackoverflow.com/a/52435847
score: 1
type: AnswerComment
has text: This seems to be the right path for an answer to my question but I get an error `TypeError: 'NoneType' object is not callable` on this part `cls.date.timetuple()`

http://stackoverflow.com/a/52481829
has body: I think use of objectpath is unnecessary. You can do it by really simple way thanks to json package. Content of data.json: {"status str":null,"id":563221, "filter":"low","text" : "Grass is green"} {"status str":null,"id":612835, "filter":"high","text" : "Textual blue"} code: import json file_name = "data.json" with open(file_name, 'r') as file_to_read: for line in file_to_read: json_object = json.loads(line) dictionary = {json_object["id"]: json_object["text"]} print(dictionary) Output: {563221: 'Grass is green'} {612835: 'Textual blue'}
score: 0
answers question: http://stackoverflow.com/q/52481557
type: Answer

http://stackoverflow.com/comment/91893099
score: 0
type: Comment
has text: Unrelated, but Python doesn't guarantee that `d.keys()` and `d.values()` will iterate in the same order. `dict(zip(d.keys(), d.values()))` is not necessarily equal to `d`.
type: QuestionComment
comment on: http://stackoverflow.com/q/52475378

http://stackoverflow.com/q/52441664
has comment: http://stackoverflow.com/comment/91826180
has body: I am trying to update an object named User with the properties username and fullname; my model is below. class User(models.Model): """docstring for User""" fullname = models.TextField() username = models.TextField() password = models.TextField() createdDate = models.DateTimeField(default=timezone.now) publishedDate = models.DateTimeField(blank=True, null=True) def publish(self): self.publishedDate = timezone.now self.save() def __str__(self): return str("\npk= " + self.pk + " | fullname= " + self.fullname + " | username= " + self.username + "\n") I have created an edit page and am able to get the values from that page in my view through request.POST["fullname"] and request.POST["username"]. My question is how do I update the entire object without having to specify a specific property in update or without getting the object and setting my new values and saving the object; my view is below. def editUserByID(request, userID): if (request.method == "POST"): if (request.POST["userID"] != '' and request.POST["fullname"] != '' and request.POST["username"] != ''): user1 = User( pk=request.POST["userID"], fullname=request.POST["fullname"], username=request.POST["username"] ) print(user1) # this only updates 1 property, so for multiple properties I would have to write multiple statements User.objects.filter(pk=user1.pk).update(fullname=user1.fullname) # is this possible? send the entire object and have it update the DB User.objects.filter(pk=user1.pk).update(user1) # this is how I was able to save it, but have to get the existing object again, assign the new values and then save updateUser = User.objects.get(pk=user1.pk) updateUser.fullname=user1.fullname updateUser.username=user1.username updateUser.save() else: user2 = User.objects.get(pk=userID) return render (request, 'helloworld/editUser.html', {'user': user2}) return redirect('listUsers') PS: I have been working with Java and .NET until now but am completely new to Python/Django so any help would be highly appreciated.
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/52442173
possible better answer: http://stackoverflow.com/a/52442362
has comment: http://stackoverflow.com/comment/91826392
type: Question
has answer: http://stackoverflow.com/a/52442362
type: AnsweredQuestion
has title: Django update an entire object (row)
has comment: http://stackoverflow.com/comment/91826918
answer count: 2
accepted answer: http://stackoverflow.com/a/52442173
downvote count: 0
score: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/91976189
type: AnswerComment
has text: @jezrael: 'really big' is actually not big at all. Vectorised string ops beat the list comp for 250 rows, for example. The ratio of NAs doesn't matter.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52516547

http://stackoverflow.com/a/52479326
score: 2
answers question: http://stackoverflow.com/q/52479017
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52479017
has body: You need to specify that you want sess to be your default session. You can do that in a couple of ways. One is as a context manager: filter = tf.random_normal(shape=[2,1,1], seed=123) sess = tf.Session() with sess.as_default(): print(sess.run(filter)) print(filter.eval()) The other option is to use tf.InteractiveSession, which is a regular session that registers itself as default on construction: filter = tf.random_normal(shape=[2,1,1], seed=123) sess = tf.InteractiveSession() print(sess.run(filter)) print(filter.eval()) As its name suggests, tf.InteractiveSession is recommended for interactive use. Full programs or modules should prefer the context manager (or just avoid .eval()) to avoid mistakes. EDIT: If you use the context manager, you can also use it to make sure that your session is closed too: filter = tf.random_normal(shape=[2,1,1], seed=123) with tf.Session() as sess, sess.as_default(): print(sess.run(filter)) print(filter.eval()) # sess will be closed after with block
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52575894
accepted answer of: http://stackoverflow.com/q/52575831
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52575831
has body: Try this: import re input_ = 'fafaf fadfa fafa fa-fa faf_afa@gs!' input_ = re.sub('[^0-9a-zA-Z]+', '', input_)
upvote count: 5
score: 5

http://stackoverflow.com/q/52501105
downvote count: 0
has comment: http://stackoverflow.com/comment/91963304
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/52518044
type: UnansweredQuestion
has body: I am trying to connect to MSSQL with help of django-pyodbc. I have installed all the required packages like FreeTDS, unixODBC and django-pyodbc. When I connect using tsql and isql I am able to connect:- &gt;tsql -S mssql -U ********* -P *********** locale is "en_US.UTF-8" locale charset is "UTF-8" using default charset "UTF-8" 1&gt; isql -v mssql ********* *********** +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | quit | | | +---------------------------------------+ SQL&gt; But, when I am trying to connect from python it does not work. I am getting below error:- &gt;python Python 2.7.14 (default, May 16 2018, 06:48:40) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pyodbc; &gt;&gt;&gt; print(pyodbc.connect("DSN=GB0015APP09.dir.dbs.com;UID=*********;PWD=*************").cursor().execute("select 1")); Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)') &gt;&gt;&gt; I have checked all other related answers but nothing is working. Not sure which data source name it is looking for. Below are all the related configurations:- /root&gt;cat .freetds.conf [mssql] host = my_server_name instance = MSSQL Port = 1433 tds version = /root&gt;cat /etc/odbc.ini [ServerDSN] Driver = FreeTDS Description = FreeTDS Trace = No Servername = mssql Server = my_server_name Port = 1433 Database = my_db_name /root&gt;cat /etc/odbcinst.ini [FreeTDS] Description = FreeTDS Driver = /usr/lib64/libtdsodbc.so Setup = /usr/lib64/libtdsS.so fileusage=1 dontdlclose=1 UsageCount=1 I have wasted couple of days trying to resolve this issue, but no luck. Please help me out. EDIT /root&gt;tsql -C Compile-time settings (established with the "configure" script) Version: freetds v0.95.81 freetd…
tagged with: django
tagged with: python
tagged with: pyodbc
has title: MSSQL django_pyodbc connectivity issues
score: 2
type: Question
tagged with: django-pyodbc
has answer: http://stackoverflow.com/a/52515289
has comment: http://stackoverflow.com/comment/91944086
answer count: 2

http://stackoverflow.com/comment/91816679
type: Comment
type: QuestionComment
has text: @Zapho: I don't think so because I am using raw string notation in python: `r" "`
comment on: http://stackoverflow.com/q/52436769
score: 0

http://stackoverflow.com/comment/91915783
type: Comment
type: QuestionComment
has text: The ideal way is to refactor your code *not* to require shared state. I would read through the [documentation](https://docs.python.org/3.7/library/multiprocessing.html#sharing-state-between-processes) to see what options you do have for sharing state.
comment on: http://stackoverflow.com/q/52486811
score: 0

http://stackoverflow.com/comment/91932165
type: Comment
comment on: http://stackoverflow.com/q/52494318
type: QuestionComment
score: 0
has text: @kristaps Yes, mysql is running. Often when this happens, some thing I am running will start showing the error but others will not.

http://stackoverflow.com/q/52498963
has comment: http://stackoverflow.com/comment/91938762
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/52499091
type: Question
score: -1
has comment: http://stackoverflow.com/comment/91938643
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91938674
favorite count: 0
has title: Django - pass URL as URL Parameter
has body: I have the following URL pattern: path('my_path/(?P&lt;url&gt;\w+)/$', views.my_view) where url is a url such as https:www.google.com It always says path not found. What is the right way to pass an url as url parameter?
tagged with: python
has comment: http://stackoverflow.com/comment/91939103
has comment: http://stackoverflow.com/comment/91938576
upvote count: 0

http://stackoverflow.com/comment/92056205
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52558051
type: Comment
has text: Thanks @BigGerman

http://stackoverflow.com/comment/91868269
score: 0
has text: @vash_the_stampede They are the parameters to `__setattr__()`.
comment on: http://stackoverflow.com/q/52463007
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52540273
accepted answer of: http://stackoverflow.com/q/52539749
has body: You are close, I think you are just confusing your variable X with the string 'X' within your loop. I also think you aren't calculating Y_i - Y_i-1, and are instead just regressing Y_i-1 against X_i-1. Here's how you would loop through the regressions. We'll also use a dictionary to store the regression results, with the keys as the column names. import pandas as pd import numpy as np import statsmodels.api as sm df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), columns=['Historic_Rate', 'Overnight', '1M', '3M', '6M']) fit_d = {} # This will hold all of the fit results and summaries for col in [x for x in df.columns if x != 'Historic_Rate']: Y = df['Historic_Rate'] - df['Historic_Rate'].shift(1) # Need to remove the NaN for fit Y = Y[Y.notnull()] X = df[col] - df[col].shift(1) X = X[X.notnull()] X = sm.add_constant(X) # Add a constant to the fit fit_d[col] = sm.OLS(Y,X).fit() Now if you wanted to make some predictions, say for your last model, you could just do: fit_d['6M'].predict(sm.add_constant(df['6M']-df['6M'].shift(1))) #0 NaN #1 0.5 #2 -2.0 #3 -1.0 #4 -0.5 #dtype: float64 And you can get the summaries: fit_d['6M'].summary() OLS Regression Results ============================================================================== Dep. Variable: Historic_Rate R-squared: 0.101 Model: OLS Adj. R-squared: -0.348 Method: Least Squares F-statistic: 0.2254 Date: Thu, 27 Sep 2018 Prob (F-statistic): 0.682 Time: 11:27:33 Log-Likelihood: -9.6826 No. Observations: 4 AIC: 23.37 Df Residuals: 2 BIC: 22.14 Df Model: 1 Covariance Type: nonrobust ============================================================================== coef std err t P&gt;|t| [0.025 0.975] ------------------------------------------------------------------------------ const -0.4332 1.931 -0.224 0.843 -8.740 7.873 6M -0.2674 0.563 -0.475 0.682 -2.691 2.156 ============================================================================== Omnibus: nan Durbin-Watson: 2.301 Prob(Omnibus): nan Jarque-Be…
has comment: http://stackoverflow.com/comment/92021124
type: Answer
has comment: http://stackoverflow.com/comment/92021227
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52539749
has comment: http://stackoverflow.com/comment/92020897
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52583174
score: 1
has body: There is no difference since after the application has initialized the result is exactly the same. When it is ready to receive requests there is literally zero difference. One could argue that during initialization the attribute access in the 2nd example is an instruction or two longer, but it makes no practical difference. As with all optimization questions, make sure it functions first and then perform some tests. Unless you re-initialize your app 100 times a second, you probably won't see any statistically significant differences even if you did test it.
accepted answer of: http://stackoverflow.com/q/52580807
upvote count: 1
answers question: http://stackoverflow.com/q/52580807
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52587927
answers question: http://stackoverflow.com/q/52587150
has body: It's working fine with that code!! try using scrapy runspider yourspiderfile.py instead of scrapy crawl quotes.There is no error in the code.
has comment: http://stackoverflow.com/comment/92111974
has comment: http://stackoverflow.com/comment/92112117
type: Answer
score: 0

http://stackoverflow.com/q/52472054
has title: How do you get Athena/Presto to recognize parquet index
has comment: http://stackoverflow.com/comment/91893744
tagged with: pandas
tagged with: amazon-athena
accepted answer: http://stackoverflow.com/a/52476582
tagged with: presto
favorite count: 0
tagged with: parquet
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have a 25k "row" parquet file (totaling 469.5kb) where each item in the parquet has a unique integer id. Knowing this i've put an index on this column, but it doesn't appear indexing the column actually affects performance when using Athena (AWS service) / Presto (underlying engine). I'm trying a simple select from where where I want to pull one of the rows by it's id- SELECT * FROM widgets w WHERE w.id = 1 The id column is indexed, so once Presto finds this match it shouldn't do any further scanning. The column is also ordered, so it should be able to do a binary search the resolve the location instead of a dumb scan. I can tell if the index is being used properly since Athena returns the number of bytes scanned in the operation. With and without the index, Athena returns the byte size of the file itself as the scan size, meaning it scanned the entire file. Just to be sure, ordering so that the id was the very first row also didn't have an affect. Is this not possible with the current version of Athena/Presto? I am using python, pandas, and pyarrow.
type: Question
has answer: http://stackoverflow.com/a/52476582
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/92082771
type: QuestionComment
has text: See https://stackoverflow.com/a/6822773/6779307
score: 0
comment on: http://stackoverflow.com/q/52573183
type: Comment

http://stackoverflow.com/q/52445630
upvote count: 2
has comment: http://stackoverflow.com/comment/91836418
has title: convolution that takes a function as kernel
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/52447826
has comment: http://stackoverflow.com/comment/91835935
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91834670
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91836799
has answer: http://stackoverflow.com/a/52447826
type: Question
favorite count: 0
has body: I need to experiment with convolution where the kernel is not constant, but dependents on the patch of the input (I'll call it filter to differentiate) and is calculated by a function f. So what I need is something like: conv2d :: R^(batch x height x width x in_channel) x f : R ^ (filter_height x filter_width x in_channels) -&gt; R ^ (filter_height x filter_width x in_channels x out_channels) -&gt; out What I don't want is to just evaluate f for every patch in the convolution. It's critical for my application that f just produces the filter for every patch of the input and then the filter gets applied to the patch. Is this somehow hackable with tf and if not, is there a reasonable way to extend tf to provide me with the needed functionality? I have never written CUDA, but I don't shy away from it.

http://stackoverflow.com/q/52516539
has comment: http://stackoverflow.com/comment/91975983
tagged with: excel
has body: I have been trying to take a sheet from an xls spreadsheet and add it to a sheet within another spreadsheet that contains multiple sheets without it overwriting the whole file and deleting the other sheets within it. For this I have imported the first sheet as a pandas dataframe and then ran it through the function, however it always shows the error: 'list' object has no attribute 'find' Here is the code that I have been using for this: import pandas as pd def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None, truncate_sheet=False, **to_excel_kwargs): """ Append a DataFrame [df] to existing Excel file [filename] into [sheet_name] Sheet. If [filename] doesn't exist, then this function will create it. Parameters: filename : File path or existing ExcelWriter (Example: '/path/to/file.xlsx') df : dataframe to save to workbook sheet_name : Name of sheet which will contain DataFrame. (default: 'Sheet1') startrow : upper left cell row to dump data frame. Per default (startrow=None) calculate the last row in the existing DF and write to the next row... truncate_sheet : truncate (remove and recreate) [sheet_name] before writing DataFrame to Excel file to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()` [can be dictionary] Returns: None """ from openpyxl import load_workbook # ignore [engine] parameter if it was passed if 'engine' in to_excel_kwargs: to_excel_kwargs.pop('engine') writer = pd.ExcelWriter(filename, engine='openpyxl') # Python 2.x: define [FileNotFoundError] exception if it doesn't exist try: FileNotFoundError except NameError: FileNotFoundError = IOError try: # try to open an existing workbook writer.book = load_workbook(filename) # get the last row in the existing Excel sheet # if it was not specified explicitly if startrow is None and sheet_name in writer.book.sheetnames: startrow = writer.book[sheet_name].max_row # truncate sheet if truncate_sheet and sheet_name in writer.book.sheetnames: # index of [sheet_name] sheet …
has title: When trying to save an excel spreadsheet in python I get this error: 'list' object has no attribute 'find'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91973953
tagged with: pandas
has comment: http://stackoverflow.com/comment/91974874
score: 2
answer count: 0
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
upvote count: 2

http://stackoverflow.com/a/52485629
has comment: http://stackoverflow.com/comment/91912904
has body: IIUC, you can do something like mask = df['RaceRank'].quantile(.25) &gt; 30 ones = np.ones(len(df), dtype=bool) df[mask &amp; ones]
type: Answer
has comment: http://stackoverflow.com/comment/91912888
answers question: http://stackoverflow.com/q/52485496
has comment: http://stackoverflow.com/comment/91912948
has comment: http://stackoverflow.com/comment/91912986
score: 0

http://stackoverflow.com/q/52551460
type: Question
accepted answer: http://stackoverflow.com/a/52551542
downvote count: 0
has comment: http://stackoverflow.com/comment/92041981
score: 6
tagged with: object-destruction
answer count: 3
favorite count: 0
possible better answer: http://stackoverflow.com/a/52551496
has body: Is it possible to delete an object form inside its class? class A(): def __init__(self): print("init") self.b="c" def __enter__(self): print("enter") return self def __exit__(self, type, value, traceback): print("exit") with A() as a: print(a.b) print(a.b) returns: init enter c exit c How comes I still have access to the a object after exiting the with ? Is there a way to auto-delete the object in __exit__?
has answer: http://stackoverflow.com/a/52551496
has answer: http://stackoverflow.com/a/52551542
tagged with: python
tagged with: with-statement
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52552017
has title: With statement, auto-delete object

http://stackoverflow.com/a/52514660
answers question: http://stackoverflow.com/q/52514442
upvote count: 3
has body: .xlsx is a ZIP rather than GZip archive. These are two completely different formats. While you can use the zipfile module to get its contents, you're still going to need some specialized package for Excel files to make sense of them.
type: Answer
has comment: http://stackoverflow.com/comment/91972362
score: 3
has comment: http://stackoverflow.com/comment/91971310
downvote count: 0

http://stackoverflow.com/comment/92083070
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52573403
has text: I would suggest to use the same variable names as the OP. That makes one to one correspondence easier
type: AnswerComment

http://stackoverflow.com/a/52531961
type: Answer
has body: O(n^2) is only the worst case time complexity, so the algorithm can run in less time than that on a random input and even on average (or even on almost all its inputs...). Also the complexity of Shellsort depends on the "gap sequence" you selected. Certain gap sequences result in a worst time case smaller than O(n^2), like O(n^1.5) for the gap sequence 1, 4, 13, 40, 121, ... or even O(nlog^2(n)) for 1, 2, 3, 4, 6, 8, 9, 12, ... (both due to Pratt, 1971). In other words: just trying on one input is not significant at all and the claim about O(n^2) may be false depending on the exact implementation of the algorithm.
has comment: http://stackoverflow.com/comment/92038776
score: 0
has comment: http://stackoverflow.com/comment/92021309
answers question: http://stackoverflow.com/q/52531864

http://stackoverflow.com/comment/92013647
comment on: http://stackoverflow.com/a/52534377
type: Comment
has text: if the `test.jpg` image does not show up in the browser in your example something fishy is going on. It's not CSS related, CSS just uses the address provided, and the problem is with the address. What happens if you make a new app using just the example I provided and nothing else?
score: 0
type: AnswerComment

tiff
tags question: http://stackoverflow.com/q/52530200
tag name: tiff
tags question: http://stackoverflow.com/q/52459913
type: Tag

http://stackoverflow.com/a/52442936
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52440341
accepted answer of: http://stackoverflow.com/q/52440341
has body: As you already mentioned both approaches are working fine since are the same thing. In the first approach you are overloading the class "Button" with initial values while instantiating the class at the same time. In your second approach you are instantiating the class "Button" without initial values (so the class default values will be used). After that you call the class and set the values of the class manually which leads to the same result as the first approach. PyCharm can do many things but I don't know of a command to do what you want, sorry.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91917080
type: AnswerComment
score: 0
type: Comment
has text: I could not get df['title1'] gives KEY ERROR.
comment on: http://stackoverflow.com/a/52487871

http://stackoverflow.com/comment/92028134
comment on: http://stackoverflow.com/q/52543824
has text: I would like A-B, C-D, E-F, G-H, ...etc all plotted on one graph. The data is a lot of spectrums, so the x-axis varies, but not so much that it would be difficult to visualize. However, when I'm doing this with my actual data, it will only plot A-B, C-D and then stop. One thing to note is because this is a CSV, some of my imported data comes as NaN, so I'm not sure if that is impacting it or not...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92089335
type: Comment
type: QuestionComment
has text: I don't believe hardcoding every state of that graph is a good idea. It would be much wiser to implement a `SlidingWindowGame` class which keeps record of a `3x3` board and has a `possible_moves` method which returns a set a future boards.
score: 0
comment on: http://stackoverflow.com/q/52576986

http://stackoverflow.com/comment/91877847
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52467670
has text: This code kind of works. I am facing with an issue when the customer id consists of a combination of alphabets, numbers and special characters. If the file name is say **'1d2017010123p+abc.xlsx'** where **'123p+abc'** is the customer id , then if I run the code, the folders are created properly but the resultant file name is **'123p'** with an unknown file type. Is there any way to avoid this problem?
type: AnswerComment

http://stackoverflow.com/q/52561244
answer count: 2
tagged with: python
tagged with: vectorization
has answer: http://stackoverflow.com/a/52706186
score: 4
has title: NLP in Python: Obtain word names from SelectKBest after vectorizing
upvote count: 4
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52706186
favorite count: 0
possible better answer: http://stackoverflow.com/a/52648406
type: Question
has answer: http://stackoverflow.com/a/52648406
tagged with: nlp
linked to: http://stackoverflow.com/q/51695769
has body: I can't seem to find an answer to my exact problem. Can anyone help? A simplified description of my dataframe ("df"): It has 2 columns: one is a bunch of text ("Notes"), and the other is a binary variable indicating if the resolution time was above average or not ("y"). I did bag-of-words on the text: from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(lowercase=True, stop_words="english") matrix = vectorizer.fit_transform(df["Notes"]) My matrix is 6290 x 4650. No problem getting the word names (i.e. feature names) : feature_names = vectorizer.get_feature_names() feature_names Next, I want to know which of these 4650 are most associated with above average resolution times; and reduce the matrix I may want to use in a predictive model. I do a chi-square test to find the top 20 most important words. from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 selector = SelectKBest(chi2, k=20) selector.fit(matrix, y) top_words = selector.get_support().nonzero() # Pick only the most informative columns in the data. chi_matrix = matrix[:,top_words[0]] Now I'm stuck. How do I get the words from this reduced matrix ("chi_matrix")? What are my feature names? I was trying this: chi_matrix.feature_names[selector.get_support(indices=True)].tolist() Or chi_matrix.feature_names[features.get_support()] These gives me an error: feature_names not found. What am I missing? A

http://stackoverflow.com/comment/91877387
has text: Hi @EricMyhre , is it related to count of sequence of occurances of A->B and B->A w.r.t users ?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52466810

faceted-search
tag name: faceted-search
type: Tag
tags question: http://stackoverflow.com/q/52464095

http://stackoverflow.com/a/52572012
has comment: http://stackoverflow.com/comment/92080604
has comment: http://stackoverflow.com/comment/92080559
type: Answer
has body: I'd split the string by &amp; to get a list of key-value strings, and then split each such string by : to get key-value pairs. Using dict and list comprehensions actually makes this quite elegant: result = {k:v for k, v in (part.split(':') for part in data.split('&amp;'))}
score: 1
answers question: http://stackoverflow.com/q/52571951
accepted answer of: http://stackoverflow.com/q/52571951
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91874724
has text: Would be dependent on the shape as there could be multiple spots that are all white (e.g. distance transform on a rectangle), though not enough info from OP to get anything better. BTW, check out the Python built-in `divmod()`.
type: Comment
comment on: http://stackoverflow.com/a/52462875
score: 0
type: AnswerComment

http://stackoverflow.com/q/52466293
has title: how to see if datetime is between start and end time of different dataframe in pandas
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52466367
has comment: http://stackoverflow.com/comment/91874303
score: 0
tagged with: pandas
has body: I have following two dataframes in pandas df code start_time end_time start end flag 0 2018-08-01 06:30:00 2018-08-01 06:40:00 123 145 0 1 2018-08-01 06:40:00 2018-08-01 06:50:00 145 150 0 2 2018-08-01 07:10:00 2018-08-01 07:20:00 155 160 1 df1 code occur_time Ack_time Alarm 0 2018-08-01 06:50:00 2018-08-01 08:00:00 437 1 2018-08-01 06:40:00 2018-08-01 07:10:00 430 2 2018-08-01 07:10:00 2018-08-01 07:20:00 456 The condition I want to check is,in df dataframe flag should be 1 then for that perticular row start_time should be between occur_time and Ack_time and Alarm should be 437 My desired dataframe would be df code start_time end_time start end flag manual 0 2018-08-01 06:30:00 2018-08-01 06:40:00 123 145 0 1 1 2018-08-01 06:40:00 2018-08-01 06:50:00 145 150 0 0 2 2018-08-01 07:10:00 2018-08-01 07:20:00 155 160 1 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91946685
has text: @FerMedina Correct
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52502807

http://stackoverflow.com/q/52534580
answer count: 1
has comment: http://stackoverflow.com/comment/92008618
has answer: http://stackoverflow.com/a/52535014
favorite count: 0
has comment: http://stackoverflow.com/comment/92009734
type: UnansweredQuestion
score: -3
tagged with: python
has body: Trying to update a A* implementation to include cost for different terrain. I understand I have to update my child.g to include the cost of the terrain instead of the current_node.g+1 for the non-terrain-cost implementation but I cant figure out how. # child.g = current_node.g + maze[child.g] All the costs are represented in my grid(maze[][]) as numbers. Trying with that last line only gives me an error. (Its not a maze anymore but was for the first few tasks). Appreciate all help on this. EDIT: Posting the entire code, it works well for non weighting boards. maze5 = [[50,50,50,50,50,10,10,10,10,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,10,10,10,50,50,50,50,50], [50,50,50,10,10,10,10,10,10,10,10,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,10,10,10,10,10,50,50,50,50], [50,50,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,1,10,10,10,10,10,10,50,50,50,50], [50,50,10,10,10,10,10,10,10,10,10,10,10,10,10,100,100,100,100,100,10,10,10,10,10,10,10,10,10,1,10,10,10,10,10,10,10,50,50,50], [50,10,10,10,10,10,10,10,10,10,10,10,10,10,100,100,100,100,100,100,100,10,10,10,10,10,10,10,10,1,10,10,10,10,10,10,50,50,50,50], [50,50,10,10,10,10,10,10,10,10,10,10,10,10,100,100,100,100,100,100,100,10,10,1,1,1,1,1,1,1,1,1,1,1,1,1,50,50,50,50], [50,50,50,10,10,10,10,10,10,10,10,10,10,10,10,100,100,100,100,100,10,10,10,10,10,10,10,10,10,10,10,10,1,10,10,10,10,50,50,50], [50,50,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,1,10,10,10,10,10,50,50], [50,50,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,50,50], [50,50,50,10,10,10,10,5,5,5,5,5,5,5,5,5,5,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,50,50]] class Node(): """A node class for A* Pathfinding""" def __init__(self, parent=None, position=None): self.parent = parent self.position = position self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position def astar(maze, start, end): """Returns a …
has comment: http://stackoverflow.com/comment/92045737
upvote count: 0
tagged with: a-star
has comment: http://stackoverflow.com/comment/92027881
type: Question
has comment: http://stackoverflow.com/comment/92046085
has title: Update A* to include terrain cost
downvote count: 3
has comment: http://stackoverflow.com/comment/92008261

http://stackoverflow.com/a/52449716
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91842817
has comment: http://stackoverflow.com/comment/91843963
answers question: http://stackoverflow.com/q/52449689
has comment: http://stackoverflow.com/comment/91842834
accepted answer of: http://stackoverflow.com/q/52449689
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91843012
upvote count: 2
has body: IIUC: df.groupby('ID').TEXT.apply(' '.join) ID 1 Start of document middle end of document 2 start of document 2 middle end of document 2 Name: TEXT, dtype: object

http://stackoverflow.com/comment/91895007
has text: I check the code in your previous comment, but the sum of values was greater than one, perhaps my question isn't clear enough, sorry about that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52475378
score: 0

http://stackoverflow.com/comment/134355905
type: Comment
has text: It doesn't appear to be working, yet it is displayed in the "Core options" with `fab2 --help`.
comment on: http://stackoverflow.com/a/52720758
score: 0
type: AnswerComment

http://stackoverflow.com/q/52433350
favorite count: 0
has title: How can I save several plot with different names coming from loop in python?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52433612
score: 1
tagged with: save
duplicate of: http://stackoverflow.com/q/35630748
has comment: http://stackoverflow.com/comment/91811020
linked to: http://stackoverflow.com/q/44959319
tagged with: loops
has comment: http://stackoverflow.com/comment/91810443
type: Question
tagged with: matplotlib
has body: I am new in python. I am doing a loop for plotting the same figure for many countries which belong to a list. When I tried to save the plot in a path I specified, the plot saved is just the last one. How can I save every single plot with different name which come from each interaction and change according to the plt.title? Figures are showed in the cell, but I can't save them. for c in countries_list: ax = emissions.loc[c].T.plot(kind='area', rot= 0, stacked=True) plt.title('Emissions of' + ' ' + c, fontsize='14', fontname="sans") plt.savefig('../plots/test.pdf', bbox_inches='tight')
upvote count: 2
linked to: http://stackoverflow.com/q/35630748
answer count: 2
has comment: http://stackoverflow.com/comment/91810464
has answer: http://stackoverflow.com/a/52433412
downvote count: 1

left-to-right
tags question: http://stackoverflow.com/q/52441715
tag name: left-to-right
type: Tag

http://stackoverflow.com/comment/92036512
comment on: http://stackoverflow.com/a/52548266
has text: also the Found Virus [TROJ_CVE201711882.UHAOBHAO] it trims the first parts but the second part didn't
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52565017
upvote count: 0
score: -2
answer count: 3
has answer: http://stackoverflow.com/a/52565043
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52565783
has body: i have searched on multiple forums and looks like others met similar issues but I haven't read a straightforward explanation yet. what I am trying to do is to simply open my python script by double clicking it. it used to work, but not anymore. my python scripts can still be opened via idle. and executable when it is opened and F5 pressed.
has answer: http://stackoverflow.com/a/52565672
downvote count: 2
has title: cannot open python script by double clicking
type: Question

http://stackoverflow.com/q/52467934
upvote count: 3
has title: python program to generate n*n matrix from user input
has answer: http://stackoverflow.com/a/52468146
accepted answer: http://stackoverflow.com/a/52467976
has answer: http://stackoverflow.com/a/52498796
answer count: 4
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/52467980
downvote count: 0
has answer: http://stackoverflow.com/a/52467980
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/52467976
has body: I want to generate a n*n matrix from user inputing the value of n and elements of the matrix. Following is the code: n=int(input("Enter the matrix size")) import numpy as np #initialise nxn matrix with zeroes mat=np.zeros((n,n)) #input each row at a time,with each element separated by a space for i in range(n): for j in range(n): mat[i][j]=input() print(mat) but I am getting output like this [[1. 2.] [3. 4.]] with a . (point) after the numbers which I don't want. Is there any way to get this with using loops and array only not NumPy?
tagged with: python

http://stackoverflow.com/comment/92081297
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52543336
has text: @Darkonaut I am using `multiprocessing.Pool`. The function is a recursive function, with a depth of 6 on average, and breadth of 10.

http://stackoverflow.com/q/52560765
has answer: http://stackoverflow.com/a/52561173
type: Question
tagged with: numpy
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52561258
has answer: http://stackoverflow.com/a/52570556
score: 1
answer count: 4
has answer: http://stackoverflow.com/a/52561219
has body: I am trying to mask an image where the masked values correspond to any one of several of values in a list. Consider the following "image" and "pixel values" import numpy img = numpy.arange(27).reshape(3,3,3) #something to represent an image pixels = [numpy.array([0,1,2]), numpy.array([9,10,11])] #arbitrarily selected "pixel" values I am trying to come up with some procedure that will output a 2d mask array where masked values correspond to pixel values in the list pixels Goal: In [93]: mask Out[93]: array([[1, 0, 0], [1, 0, 0], [0, 0, 0]]) Attempt 1 from this answer: mask = numpy.zeros( img.shape[:2], dtype = "uint8" ) mask[numpy.in1d(img, pixels).reshape(mask.shape)] = 1 This results in ValueError: cannot reshape array of size 27 into shape (3,3) I believe this answer assumes a 2d input as img Attempt 2: mask = numpy.zeros(img.shape[:2]) for x,y in [(x,y) for x in range(img.shape[0]) for y in range(img.shape[1])]: if img[x,y,:] in pixels: mask[x,y] = 1 This results in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(), but imagine there's a more concise approach than looping through each value.
accepted answer: http://stackoverflow.com/a/52561258
upvote count: 1
tagged with: python
has title: Mask an image where masked pixels exist in list of pixel values
linked to: http://stackoverflow.com/q/43098389
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52561173

http://stackoverflow.com/comment/91977586
type: Comment
has text: I also want to write cat_id|content into the textfile @Rakesh
comment on: http://stackoverflow.com/a/52515131
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91847319
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52451852
has text: Something like this for the output of 4 elements: `[ [a,b,c,d], [[a,b],c,d], [a,[b,c],d], [a,b,[c,d]], [[a,c],b,d]], [[a,d],b,c]], ... [[a,b,c],d], [a,[b,c,d]], [b,[a,c,d]]...]`
score: 0

class-variables
tag name: class-variables
tags question: http://stackoverflow.com/q/52530787
type: Tag

http://stackoverflow.com/q/52564152
tagged with: helper
has answer: http://stackoverflow.com/a/52564181
type: UnansweredQuestion
tagged with: python
score: 0
type: Question
has title: Problem with while loop in Python, repeating string
answer count: 2
tagged with: while-loop
has body: a = input('Enter your username...') while (a == 'SuperGiraffe007&amp;'): print('Welcome!') else: print("Try again...") a = input('Enter your username...') while (a == 'SuperGiraffe007&amp;'): print('Welcome!') The code functions correctly but when I input the correct username the string 'Welcome!' repeats forever which crashes my browser. How do I stop it from repeating and only print once?
has answer: http://stackoverflow.com/a/52564171

http://stackoverflow.com/q/52442311
has comment: http://stackoverflow.com/comment/91827806
tagged with: ajax
score: 0
has comment: http://stackoverflow.com/comment/91827952
tagged with: python
has body: I'm making an alarm system on raspberry pi. I have a python script, which detects motion, inserts data about it into mysql database and later displays it on website from database. I don't use frameworks like flask, django. I use html, php and also javascript from bootstrap framework to do responsive website. Now I would like to do a button (ON/OFF) on website, which will control python script, which I've described above. I'd like to do this in simple way, because I'm begginer in that. Is it possible to do this with php code, maybe with js, ajax not to refresh page, but without using frameworks like flask? Currently it will be localhost, but for example is it possible to host this website and remote control python script from mobile phone with php code? I've tried to do this with php code, but it is not working. &lt;?php if (isset($_POST['update'])) { exec('python /var/www/html/alarmV1.py'); } ?&gt; &lt;form name="update" method="post" &gt; &lt;input type="submit" value="Włącz" name="update" style="color:white; background-color: green; " &gt; &lt;/form&gt; Thanks for help.
answer count: 0
type: UnansweredQuestion
has title: How to execute python script with infinite loop from raspberry pi website by button click?
has comment: http://stackoverflow.com/comment/91828107
tagged with: php
has comment: http://stackoverflow.com/comment/91827457
type: Question
has comment: http://stackoverflow.com/comment/91827301
tagged with: raspberry-pi

http://stackoverflow.com/comment/92185490
comment on: http://stackoverflow.com/q/52588453
score: 0
type: Comment
has text: Otherwise, I would suggest that you raise an issue on their github. If that fails, `igraph` supports curved edges, IIRC (might have been just for the R interface though I don't think that likely).
type: QuestionComment

http://stackoverflow.com/comment/91925618
type: Comment
comment on: http://stackoverflow.com/a/52491496
has text: Still pretty fast under the constraints, going by the timings just added.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/103934203
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52462209
has text: All variables in Python are not really variable like in C, think of them are pointers. In your example,` {1, 2, 3}` create a new set object, then assign it to a label named `i`. Another `{1, 2, 3`} create another new set object, then assign it to a label named `j`. The line `i = j` copy the pointer value from `j` to `i`, so `j` is equal to `i` now. You can think the `id()` is the memory location of the object.

http://stackoverflow.com/q/52459952
has comment: http://stackoverflow.com/comment/91862042
has comment: http://stackoverflow.com/comment/91862094
has title: Using python to interpret results
has comment: http://stackoverflow.com/comment/91862158
has comment: http://stackoverflow.com/comment/91862033
has comment: http://stackoverflow.com/comment/91862123
tagged with: python
possible better answer: http://stackoverflow.com/a/52460789
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52460789
has body: I am trying to solve the following question. Here is my code I have produced import numpy as np import math sum = 4 while sum &lt;= 13: b = 10**(-sum) x = (math.sqrt(9+b)-3)/(b) print(x) sum +=1 which gives the following results 0.16666620370475727 0.1666666203714584 0.1666666618049817 0.1666666671340522 0.1666666804567285 0.1666666804567285 0.1666666804567285 0.1666666804567285 0.16653345369377348 0.16431300764452317 I am not sure if my code is correct or not. When I plug in 13 for n into the original equation in wolfram I am getting something different. I figured as it got closer to 13 it would approach 0.1666666. Also how would I make a graph from this? I guess this would be the best way to observe my results.
type: Question
tagged with: graph
has answer: http://stackoverflow.com/a/52460014
accepted answer: http://stackoverflow.com/a/52460014
score: 0
answer count: 2

http://stackoverflow.com/comment/91993567
type: Comment
type: QuestionComment
has text: @KennyOstrom I understand everything you said up until you said that the O(n) steps become O(1) steps. From what I understand, as the execution goes on, those O(n) steps start iterate from 1 char in the first pass through to n chars in the final pass through, making it scale by O(n). Can you elaborate? Also, yeah my space efficiency seems really bad. I am seeing that while looking through Narayana Pandita algorithm.
comment on: http://stackoverflow.com/q/52488523
score: 0

http://stackoverflow.com/comment/91873586
comment on: http://stackoverflow.com/q/52463652
type: Comment
has text: Guys in Bottle how do i reference to a static file? My images are withing './static/img'
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91951776
comment on: http://stackoverflow.com/a/52505493
score: 0
type: AnswerComment
has text: I forgot some parentheses in the second solution! One second, I will edit.
type: Comment

http://stackoverflow.com/q/52458708
score: 1
tagged with: django-forms
has title: How to check if a new file was selected in django admin using a pre_save signal?
accepted answer: http://stackoverflow.com/a/52572425
has body: I have a model that has an ImageField attribute. I update the model objects using the django admin and I needed something to delete the old image when a new image is uploaded while trying to update an object. So I created a pre_save signal that should delete the old image file from the server when the user attempts to update the model object. The problem is: When the user updates object's attributes other than the ImageField attribute, the signal still deletes the locally saved image file.. How can I change the signal to delete the file only if a new file was selected in django admin? In other words, I need to check if the user uploaded a file while trying to update the object in django admin. IMPORTANT NOTE: My signal works with many models.. and I need to keep it like that. Here is the signal code: @receiver(pre_save) def pre_save_image_delete(sender, instance, **kwargs): if not valid_model(sender.__name__): return # Get file path on the server path = get_photo_path(sender.__name__, instance.pk) # delete the file if it exists if path and file_exists(path): delete_file(path)
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: django-signals
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52572425
tagged with: django
upvote count: 1
type: Question
tagged with: django-admin

http://stackoverflow.com/a/52453758
has body: Here's an in-place solution: def dedupe(lol): seen = set() for lst in lol: for ii, val in enumerate(lst): while val in seen: val += 1 lst[ii] = val seen.add(val) And here's a generator which does not modify the input: def dedupe(lol): seen = set() for lst in lol: new = [] for val in lst: while val in seen: val += 1 new.append(val) seen.add(val) yield new You can use it like print(list(dedupe(l)).
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52453635
type: Answer

http://stackoverflow.com/q/52538143
score: 2
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: data-visualization
has body: For multiclass classification you would normally choose a confusion matrix to plot the error of predicted classes against the target classes. What is the best way to visualize errors of multilabel classifiers? As multiple classes are predicted at once a mapping of prediction against target is not always possible so confusion matrices are generelly not suitable. My first idea is to plot a bar chart where each class has a bar for missed and one for false predictions. But is there any standard for visualizing the errors which includes more information just like a confusion matrix for multiclass problems?
tagged with: python
tagged with: multilabel-classification
has title: How to visualize errors of multilabel classifiers
answer count: 0
upvote count: 2
tagged with: machine-learning
type: Question
tagged with: neural-network

http://stackoverflow.com/a/52504209
upvote count: 1
has body: Maybe you could use: pip freeze ? This would output all the installed packages for your given project, for reference. Hopefully that helps!
answers question: http://stackoverflow.com/q/52504092
downvote count: 0
has comment: http://stackoverflow.com/comment/91951395
type: Answer
has comment: http://stackoverflow.com/comment/91949856
score: 1

http://stackoverflow.com/a/52574910
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52572275
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92096684
answers question: http://stackoverflow.com/q/52572275
has body: This is pure slicing but I didn't know that syntax like arr1[0:,:][:,:2] actually works. It seems it does but not sure if it is better. This may be the wildcard slicing mechanism you are looking for. arr1 = tf.constant([[1,2,3,4,5,6],[1,2,3,4,5,7],[1,2,3,4,5,8]]) arr2 = tf.constant([[10, 11, 12], [10, 11, 12], [10, 11, 12]]) with tf.Session() as sess : sess.run( tf.global_variables_initializer() ) print(sess.run(tf.concat([arr1[0:,:][:,:2], arr2[0:,:] [:,:1], arr1[0:,:][:,2:4],arr2[0:, :][:, 1:2], arr1[0:,:][:,4:6],arr2[0:, :][:, 2:3]],axis=1))) Output is [[ 1 2 10 3 4 11 5 6 12] [ 1 2 10 3 4 11 5 7 12] [ 1 2 10 3 4 11 5 8 12]] So, for example, arr1[0:,:] returns [[1 2 3 4 5 6] [1 2 3 4 5 7] [1 2 3 4 5 8]] and arr1[0:,:][:,:2] returns the first two columns [[1 2] [1 2] [1 2]] axis is 1.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/91864325
type: Comment
has text: Your solution is very helpful. I'm just not sure about the syntax for saving the new Photo Image and saving the ID number
type: AnswerComment
comment on: http://stackoverflow.com/a/52460877
score: 0

http://stackoverflow.com/q/52465658
upvote count: 1
has comment: http://stackoverflow.com/comment/91873038
type: Question
score: -1
has comment: http://stackoverflow.com/comment/91873075
tagged with: class
has comment: http://stackoverflow.com/comment/91877306
answer count: 2
has answer: http://stackoverflow.com/a/52468269
tagged with: for-loop
has body: today I tried to create a class. I wrote this. from first_names_class import firstnames from last_names_class1 import lastnames from object_name_list import my_new_list class MyClass: """A Class with automatated full names.""" # Automatically create the instances of the class named user_indexfrom the rangeiterator def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name for i in range(0, 49): my_new_list[i] = MyClass(firstnames[i], lastnames[i]) print(user1.first_name) However, when I run it it says: Traceback (most recent call last): ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50'] File "/Users/myname/Documents/University/Programming for Quantitive Analysis/MyFirstClass.py", line 15, in print(user1.first_name) NameError: name 'user1' is not defined ['user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9', 'user10', 'user11', 'user12', 'user13', 'user14', 'user15', 'user16', 'user17', 'user18', 'user19', 'user20', 'user21', 'user22', 'user23', 'user24', 'user25', 'user26', 'user27', 'user28', 'user29', 'user30', 'user31', 'user32', 'user33', 'user34', 'user35', 'user36', 'user37', 'user38', 'user39', 'user40', 'user41', 'user42', 'user43', 'user44', 'user45', 'user46', 'user47', 'user48', 'user49', 'user50'] My thoughts on this: I don't know if I'm correct but I have read in another thread that the object/instance of the class should not be indented as it will be read "as content of the class". On the other hand, the for-loop requires me to have this text indented. How can I solve this problem, if that what I said is exactly the problem. If what I said, is wrong, how can I then solve this NameError. Maybe it has something to do with the list from which I take the…
favorite count: 0
has answer: http://stackoverflow.com/a/52465689
has comment: http://stackoverflow.com/comment/91877904
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91874084
has title: For loop vs. class-object... How can I solve it?
tagged with: python
has comment: http://stackoverflow.com/comment/91879214
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/91981243
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52517773
has text: And one more question: why do you use QTreeView when a typical QSqlQueryModel provides a table-type model using a QTableView?

http://stackoverflow.com/comment/92078566
has text: Thanks I installed lxml and it has returned the same output as you specified. Is there no way to only extract specific information? You see I want to apply this approach to a website which lists a series of Artists so I can use the data for a specific purpose (https://www.coachella.com/lineup/#/artists/alphabetical)
type: AnswerComment
comment on: http://stackoverflow.com/a/52570651
score: 0
type: Comment

http://stackoverflow.com/q/52495077
has answer: http://stackoverflow.com/a/52550815
answer count: 2
tagged with: 3d
has comment: http://stackoverflow.com/comment/91959003
has answer: http://stackoverflow.com/a/52563609
has comment: http://stackoverflow.com/comment/91931184
score: 0
has title: Best way to make 3D model out of CT scans with python?
type: UnansweredQuestion
tagged with: python
tagged with: blender
has body: I want to make a 3D model from the heart by using CT scans. I used Blender but it didn't work out well. This Python script is running too slow. Does someone know a better way to do this? import bpy import os import pydicom import numpy as np path = "./Desktop/EMC/" files = sorted(os.listdir(path + "/Data/Head/")) data = np.zeros((245, 512, 512)) for i in range(len(files)): layer = pydicom.dcmread(path + "/Data/Head/" + files[i]) # read dcm files data[i] = layer.pixel_array for yy in range(245): for xx in range(512): for zz in range(512): print("X: {}, Y: {}, Z: {}".format(xx, yy, zz)) c = data[yy, xx, zz] bpy.ops.mesh.primitive_cube_add(location=(xx / 500, zz / 500, yy / 500)) bpy.ops.transform.resize(value=(0.001, 0.001, 0.001)) activeObject = bpy.context.active_object # Select active object mat = bpy.data.materials.new(name="MaterialName") activeObject.data.materials.append(mat) #Add Material bpy.context.object.active_material.diffuse_color = (c, c, c) #change color if zz == 511: #Join objects and remove doubles item='MESH' bpy.ops.object.select_all(action='DESELECT') bpy.ops.object.select_by_type(type=item) bpy.ops.object.join() bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.remove_doubles() bpy.ops.object.mode_set(mode='OBJECT') print("DONE")
type: Question

http://stackoverflow.com/comment/91976371
comment on: http://stackoverflow.com/a/52518161
has text: Will do, but i want to understand the difference in all 3 occasions.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52513801
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has title: Pandas: Combine two dataframes and expand rows dynamically
tagged with: python
has answer: http://stackoverflow.com/a/52513947
type: AnsweredQuestion
upvote count: 1
has body: I've got the following dataframes setup A [ClaimantId], [ClaimId], [LenderId], [IsWorked] 1 1 1 1 1 2 4 0 1 3 3 1 2 6 1 1 B [ClaimantId], [Forename], [Surname] 1 Bruce Wayne 2 Peter Parker My Desired output would be [ClaimantId], [Forename], [Surname], [C1], [C2], [C3], [L1], [L2], [L3], [W1], [W2], [W3] 1 Bruce Wayne 1 2 3 1 4 3 1 0 1 2 Peter Parker 6 Nan Nan 1 Nan Nan 1 Nan Nan I'm not sure what i can apply to this, the number of C/L/W columns has an upper limit of 20 and won't ever be exceeded. I'd really appreciate any help. Thanks,
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52513947
tagged with: pandas

http://stackoverflow.com/comment/91987126
type: QuestionComment
has text: Just checking; this is a toy example, right? You're not storing passwords in a JSON for anything vaguely important?
comment on: http://stackoverflow.com/q/52523802
score: 3
type: Comment

http://stackoverflow.com/comment/92016348
score: 0
type: Comment
type: QuestionComment
has text: Which python version are you using?
comment on: http://stackoverflow.com/q/52538464

http://stackoverflow.com/a/52528049
has body: In [16]: np.matrix.transpose Out[16]: &lt;method 'transpose' of 'numpy.ndarray' objects&gt; This is the same as np.ndarray.transpose. In other words it's the transpose method that np.matrix subclass inherits from the parent np.ndarray (what we typically call numpy array). np.transpose is the function equivalent, which ends up calling the transpose method. It's different in that it can convert its input to an array first, e.g. if the input is a list. Lists, of course, don't have a transpose method. As for what it does - with a 2d array it does the usual mathematically defined transpose. What can confuse users from other languages, is that it generalized the concept to 1d, 3d, and higher. While you are at it make sure you understand the difference between a 1d and a 2d array. If you aren't clear about that, transpose will remain a puzzle. Transpose and its axes parameter has been explained in other SO question. I'd suggest reading the docs along side an interactive session in which you can play with arrays with various dimensions. In [23]: x = np.arange(24).reshape(2,3,4) In [24]: x.transpose().shape Out[24]: (4, 3, 2) In [25]: x.transpose(0,2,1).shape Out[25]: (2, 4, 3) Don't try to carry over MATLAB intuitions.
answers question: http://stackoverflow.com/q/52521358
score: 0
type: Answer

http://stackoverflow.com/a/52467901
type: AcceptedAnswer
downvote count: 0
has body: You can use shift() and compare to initial values to analyze when values change and then map into your list1 values. s = df.ne(df.shift()).sum(1).cumsum() df['col3'] = s.map(dict(zip(s.unique(), list1))) col1 col2 col3 0 1 1 5 1 1 1 5 2 1 2 9 3 1 2 9 4 3 9 3 5 3 9 3 6 3 9 3 7 10 5 12 Timings for small df: df = pd.concat([df]*100).reset_index(drop=True) %timeit s = df.ne(df.shift()).sum(1).cumsum(); df['col3'] = s.map(dict(zip(s.unique(), list1))) 2.81 ms ± 38.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit df.merge(df.drop_duplicates().assign(col3=list1)) 3.39 ms ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Timings for big df: df = pd.concat([df]*100000).reset_index(drop=True) %timeit s = df.ne(df.shift()).sum(1).cumsum(); df['col3_'] = s.map(dict(zip(s.unique(), list1))) 184 ms ± 1.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit df.merge(df.drop_duplicates().assign(col3=list1)) 87.6 ms ± 2.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In detail, df.ne(df.shift()).sum(1).cumsum() yields a series of values that are cumulatively unique 0 2 1 2 2 3 3 3 4 5 5 5 6 5 7 7 Then, you map these values into your list1 values, and assign back as a column.
has comment: http://stackoverflow.com/comment/91877845
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52467838
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52467838
has comment: http://stackoverflow.com/comment/91877723

http://stackoverflow.com/comment/92025990
has text: Since your function Manhattan_d returns a series, you can use Manhattan_d(a,b,c,d).idxmin() to get the index with minimum value
comment on: http://stackoverflow.com/q/52542976
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52547279
answers question: http://stackoverflow.com/q/52489967
has body: So, this was solved by turning userGateway() into a proper auth backend and implementing it like that. Explanation as to why: The sessionID in django stores a hash of the user's PK as well as the auth backend used to log in. Whenever a new request is sent, data needed is lazy-loaded from the DB using this hash. This is why login() was properly authenticating the user on the login page, because it was pretty much forced to. As soon as another request happened, though, it would be unable to load the user's data from the DB, and would flush the sessionid.
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52489967
type: Answer
has comment: http://stackoverflow.com/comment/127779779

http://stackoverflow.com/a/52491247
score: 0
answers question: http://stackoverflow.com/q/52490716
type: Answer
has body: In the examples in the multiprocessing docs, they suggest using Pool with a context manager, i.e., with Pool(processes=4) as pool: print(pool.map(f, range(10)) The's the most stand-out different I immediately see between your use and the docs. I don't see it spelled out, but I would infer based on your observation, that the framework is "reimporting" (so to speak) your module in each process that it spawned, and that's resulting in the behavior you report: namely, multiple browsers opening. To prevent that, I would recommend putting the initialization code within a function; if you want to share the final_list, you should probably do so with a queue or other data structure supported by multiprocess.
has comment: http://stackoverflow.com/comment/91927474

http://stackoverflow.com/q/52527186
linked to: http://stackoverflow.com/q/42128467
tagged with: python
tagged with: plot
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/42128467
upvote count: 1
accepted answer: http://stackoverflow.com/a/52527384
type: Question
has title: Pandas plot multiple columns on a single bar chart
has comment: http://stackoverflow.com/comment/91994374
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52527384
favorite count: 0
has body: I'm trying to plot multiple columns onto a single bar chart. First, I defined them: public_action_sum = df['Q17.4_1'].sum() testified_sum = df['Q17.4_4'].sum() met_el_sum = df['Q17.4_5'].sum() ... and then merged those sums into a single dataframe: actions_combined = [public_action_sum, testified_sum, met_el_sum, policy_sum, bill_sum] I'm trying to use pandas.DataFrame.plot.bar and have written: pd.DataFrame.plot.bar(x['Q17.4_1','Q17.4_4','Q17.4_5','Q17.4_6','Q17.4_7'],y=actions_combined,rot=0) but am getting the error "missing 1 required positional argument: 'self' I've spent the last hour and a half trying to figure this iout, and am not sure where I'm going wrong. Thoughts? THANKS!

http://stackoverflow.com/comment/91952222
type: AnswerComment
comment on: http://stackoverflow.com/a/52505741
type: Comment
score: 1
has text: CPython would reuse the same tuple even in the interactive case demonstrated in the question. The behavior in the question is specific to MicroPython (which I don't have installed and am not an expert in, so I can't say much more than that).

http://stackoverflow.com/q/52463761
answer count: 2
downvote count: 0
has body: I'm currently working on an large Django project (version 1.10.7) and am running into an error with a model field in a sub-application. Here's what the basic structure looks like: project/ app_one/ __init__.py apps.py models.py urls.py views.py app_two/ __init__.py apps.py models.py urls.py views.py The model and field in question looks like this (project/app_one/app_two/models.py): class SampleModel(model.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='members') When I run python manage.py makemigrations app_one.app_two in the root folder I get this error message: File .../django/db/models/utils.py", line 23, in make_model_tuple "must be of the form 'app_label.ModelName'." % model ValueError: Invalid model reference 'app_one.app_two.SampleModel'. String model references must be of the form 'app_label.ModelName'. Here is code from other files that are relevant: project/settings.py: INSTALLED_APPS = filter(None, ( ... 'app_one', 'app_one.app_two', ... ) project/app_one/app_two/apps.py: from __future__ import unicode_literals from django.apps import AppConfig class AppOneAppTwoConfig(AppConfig): name = 'app_one.app_two' label = 'app_one.app_two' project/app_one/app_two/__init__.py: default_app_config = 'app_one.app_two.apps.AppOneAppTwoConfig' I believe the error here is that Django is only looking for one . in the full model name (app_one.app_two.SampleModel) to separate the app label from the model name in django/db/models/utils.py, and since there are two in this case, it fails. My question is: This seems like a weird for Django not to account for...is there anyway to retain the dot notation of the app label and still have a self-referencing ForeignKey in a sub-application?
tagged with: python-2.7
tagged with: django-1.10
tagged with: python
accepted answer: http://stackoverflow.com/a/52473469
favorite count: 0
score: 4
has answer: http://stackoverflow.com/a/52483775
tagged with: django
possible better answer: http://stackoverflow.com/a/52483775
type: AnsweredQuestion
has title: ForeignKey to 'self' in sub-application throws error on makemigrations in Django project
tagged with: django-models
has answer: http://stackoverflow.com/a/52473469
type: Question
upvote count: 4

http://stackoverflow.com/comment/92106051
score: 3
comment on: http://stackoverflow.com/q/52585602
has text: sets are unordered. https://docs.python.org/2/library/sets.html https://docs.python.org/3.7/tutorial/datastructures.html?highlight=set#sets
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52484821
tagged with: python
accepted answer: http://stackoverflow.com/a/52506569
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91955544
has body: I am able to compress files into a single zip file, however when I open the zip file the contents always include a "parent folder" which has the same exact name as the zip file itslef. I'm simply trying to create a zip file that contains no folders at all. Current: abc.zip > abc (folder) > files Looking for: abc.zip > files def create_zip(file_name, file_dir): """ Function to create zip archive """ os.chdir(file_dir) zipfiles_list = ['csv', 'txt'] file_name_part = file_name zip_name = '{0}.zip'.format(file_name_part) with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zip_archive: for file_extension in zipfile_list: full_file_path = '{0}.{1}'.format(file_name_part, file_extension) zip_archive.write(full_file_path, basename(full_file_path)) Is this possible? I've seen that if I rename the zip file after it's created, it will still extract contents into a folder that matches the zip file name. Original zip extracts to abc folder Renamed same exact zip and contents extract to folder with new name
has comment: http://stackoverflow.com/comment/91912223
has comment: http://stackoverflow.com/comment/91954910
score: 1
has answer: http://stackoverflow.com/a/52506569
has title: Zipfile with no parent folder
type: Question
type: AnsweredQuestion
tagged with: python-zipfile
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91930345

http://stackoverflow.com/comment/115985320
score: 1
comment on: http://stackoverflow.com/q/52494572
type: QuestionComment
type: Comment
has text: This question is asked frequently (not always with regard to Python clients). Here's my most recent answer: https://stackoverflow.com/questions/65544007/is-that-possible-that-access-to-a-sql-table-with-question-mark/65544044#65544044

http://stackoverflow.com/a/52543161
type: AcceptedAnswer
score: 6
type: Answer
answers question: http://stackoverflow.com/q/52543124
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52543124
has comment: http://stackoverflow.com/comment/92027854
upvote count: 6
has body: Your question boils down to obtaining the StData object (or the values) for the record with the largest time column. So we do not need an aggregate, but obtain the smallest or largest row with respect to the time column. Obtaining the StData object with the maximum time You can just obtain the last() row when you order on 'time', like: stdata_max_time = qs.order_by('time').last() # will return a StData or alternatively: stdata_max_time = qs.order_by('-time').first() # will return a StData In case time is NULLable (not here), you can ensure that you will not retrieve a row with NULL by specifying that when ordering these should be placed as first/last elements respectively: from django.db.models import F # two alternatives stdata_max_time = qs.order_by(F('time', nulls_first=True)).last() stdata_max_time = qs.order_by(F('-time', nulls_last=True)).first() This is thus a StData object, and you can thus retrieve all relevant information you want from that object. Since it is a StData object, it will also behave like this (so extra properties, methods, etc. you defined, will work as well). Obtaining the values with the maximum time This is completely similar, except that we put a .values(..) call in the query: stdata_max_time = qs.order_by('time').values('exp_no', 'time', 'price').last() But unless there are some really good reasons, I would personally prefer to fetch the StData object, since that means "batteries included" (you get all the logic you wrote in the StData class with that object).

http://stackoverflow.com/q/52576000
favorite count: 0
has comment: http://stackoverflow.com/comment/92087340
has answer: http://stackoverflow.com/a/52576079
has comment: http://stackoverflow.com/comment/92087372
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52576065
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/52576065
has answer: http://stackoverflow.com/a/52576119
type: AnsweredQuestion
tagged with: if-statement
has comment: http://stackoverflow.com/comment/92087359
possible better answer: http://stackoverflow.com/a/52576079
has answer: http://stackoverflow.com/a/52576084
type: Question
has title: How to check if only one statement equals 0?
score: 0
upvote count: 1
downvote count: 1
has body: I got some trouble with finding the matching if-statement to check if only one entry equals 0 of 3. Here's the code: def thanx(self): if len(self.e.get()) == 0: messagebox.showerror("Error", "Please enter affordable infos") self.boo = False else: messagebox.showinfo("Submition done", "Thank you") self.boo = True It is only checking if my variable e equals 0, but i actually got 2 more entries. I know i could check every single one individually, however there has to be an easier way of doing this. Im using "tkinter" btw, but this shouldnt be too much important. I tried it with or but this isn't working or I'm doing it wrong. (Also tried to solve this with lambda, but again just errors...) Maybe someone can help me there... Edit: I might have explained this a bit confusing, I'll add the rest of the code here that you can understand this better: from tkinter import Tk, Label, Entry, Button, W from tkinter import messagebox class MyForm: def thanx(self): if len(self.e.get()) == 0: messagebox.showerror("Error", "Please enter affordable infos") self.boo = False else: messagebox.showinfo("Submition done", "Thank you") self.boo = True def callback(self): #print("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get())) if self.boo: f = open("PrivatData.txt", "w+") f.write("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get())) def __init__(self): self.root = Tk() self.root.title("Your privat details") Label(self.root, text="Your Name").grid(row = 0, padx = 12, pady=5) Label(self.root, text="Password").grid(row=1, padx=12, pady=5) Label(self.root, text="Email").grid(row=2, padx=12, pady=5) self.e = Entry(self.root) self.e2 = Entry(self.root) self.e3= Entry(self.root) self.e.grid(row=0,column=1,columnspan=2) self.e2.grid(row=1, column=1, columnspan=2) self.e3.grid(row=2, column=1, columnspan=2) self.e.focus_set() self.show= Button(self.root, text="Submit", command=lambda:[self.thanx(),self.callback()]) self.quit = Button(self.…

http://stackoverflow.com/comment/92230637
comment on: http://stackoverflow.com/q/52540693
type: Comment
type: QuestionComment
has text: We are using a private git repo thus source dists. I'll look into building wheels, but tbh it seemed like more work than I was willing to endure.
score: 0

http://stackoverflow.com/q/52463675
tagged with: python-pptx
has comment: http://stackoverflow.com/comment/91910633
tagged with: python
has title: Images getting corrupted after running python pptx code
answer count: 0
type: UnansweredQuestion
tagged with: powerpoint
has body: I am trying to insert some images on slides. But after I run the code, the the images are getting corrupted and a message would appear. I have pasted the message here.: The code which i am using is: pic1=prs.slides[1].shapes.add_picture(image_filepath,pre_left,top,width,height); prs.save(file_path)
has comment: http://stackoverflow.com/comment/91869318
type: Question
score: 0
tagged with: corrupt

http://stackoverflow.com/q/52453244
tagged with: go
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91849901
downvote count: 1
has comment: http://stackoverflow.com/comment/91849573
favorite count: 0
has title: Is there a blank identifier in Python as there is in Golang?
has body: For instance, I have a string that splits into 3 parts but I need just the first and third parts. one, two, three = '1 2 3'.split() After the above line, I would have to execute a "del" to remove it from variable list. del(two) Is there a way I can discard "two" immediately? Like" one, _, three = '1 2 3'.split() Additionally, this is not a question about language semantics which has been answered in the following question. What is the purpose of the single underscore &quot;_&quot; variable in Python? This is a question if Python runtime has that feature to remove the variable automatically.
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91849871
has comment: http://stackoverflow.com/comment/91849884
type: Question
linked to: http://stackoverflow.com/q/5893163
duplicate of: http://stackoverflow.com/q/5893163

http://stackoverflow.com/a/61858275
score: 1
downvote count: 0
has body: It turns out putting the call whithin a try/except block solved the problem for me try: langs = translator.detect(update.message.text) if langs.lang == 'en': foo(translator.translate(update.message.text,dest='zh-cn').text) else: bar(translator.translate(update.message.text,dest='en').text) except Exception as e: print(e)
type: Answer
answers question: http://stackoverflow.com/q/52455774
upvote count: 1

http://stackoverflow.com/comment/92056975
comment on: http://stackoverflow.com/q/52557522
type: QuestionComment
type: Comment
has text: The top 'xxx' folder is the project root and not a package.
score: 0

http://stackoverflow.com/q/52523339
type: Question
tagged with: performance
has answer: http://stackoverflow.com/a/52523379
has comment: http://stackoverflow.com/comment/91986642
tagged with: caching
tagged with: optimization
score: 0
has comment: http://stackoverflow.com/comment/91986243
has comment: http://stackoverflow.com/comment/91986453
answer count: 1
has comment: http://stackoverflow.com/comment/91986248
tagged with: python-3.x
has body: Unlike many cases of c++, Python apparently is not as smart to optimize redundant operations, even between constants. I did a simple benchmark to test math.cos in and out of a loop. In this first case, I do Python calculate cos (3) 10 million times: from datetime import * from math import * ini = datetime.now() for a in range(10000000): x = cos(0) fim = datetime.now() print(fim - ini) The result is about 0:00:01.360958. Now, just replacing x = cos(0) by x = 1 (or just putting cos(0) in a variable outside the loop), the time about 3 times faster: 0:00:00.429995 Now, if the cos (0) operation always generates a constant (1), why does Python not optimize execution with a cache, thus avoiding repeating the same cos operation constantly? One of Python's philosophies is to make easier the programmer's life. But in this case what is happening is just the opposite.
has title: Python not so 'smart' for redundant operations
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/28993557
tagged with: python
has comment: http://stackoverflow.com/comment/91986451
has comment: http://stackoverflow.com/comment/91988032
has comment: http://stackoverflow.com/comment/91986253

http://stackoverflow.com/comment/92230513
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52578838
has text: The zip has another zip in it, where do i extract that and do i need to add that to the path also?

http://stackoverflow.com/q/52576825
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: list
accepted answer: http://stackoverflow.com/a/52576872
upvote count: 3
has title: Highest and lowest value of nested lists using recursion
has answer: http://stackoverflow.com/a/52577011
type: Question
tagged with: recursion
possible better answer: http://stackoverflow.com/a/52577114
has answer: http://stackoverflow.com/a/52577114
answer count: 3
has answer: http://stackoverflow.com/a/52576872
downvote count: 0
has body: I want to take in a list with nested lists. Then print the highest value of index 0 or 2 in the list and the lowest value of index 0 or 2, through using recursion. This is what I got so far: lst = [1, 5, [7, 10, []]] def high_low(my_list): new_lst = [] if not my_list: print max(new_lst) print min(new_lst) elif isinstance(my_list[0], int): return new_lst.append(my_list[0]) + high_low(my_list[2:]) elif isinstance(my_list[0], list): return new_lst.append(max(my_list[0])) + high_low(my_list[2:]) This is where I get stuck, as I don't know how to get the highest and lowest value from a nested list and then append it to the new empty list. For example this is what I want the output to look like: &gt;&gt;&gt; print_tree(lst) 10 1
favorite count: 0
linked to: http://stackoverflow.com/q/2158395

http://stackoverflow.com/q/52540470
favorite count: 0
has answer: http://stackoverflow.com/a/52540621
tagged with: python
tagged with: regex
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92020790
upvote count: 2
has body: I'm using following regex to find first date in a each line. (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4} This is working but it is matching all the dates. But, I just need the first date "Feb 19 22:25:19 2018" in each line. Sample text file Mon Feb 19 22:25:19 2018 ABC.ls:9999: some text here, Mon Feb 19 22:25:19 2017\n Mon Feb 19 22:25:20 2018 ABC.ls:9999: some text here\n Mon Feb 19 22:25:20 2018 ABC.ls:9999: some text here, () with some more text\n TIA
accepted answer: http://stackoverflow.com/a/52540621
type: Question
has comment: http://stackoverflow.com/comment/92903441
has title: Extract first date from text in Python using regex
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92020849

http://stackoverflow.com/comment/91956077
type: Comment
has text: Oh. That explains a lot. That's what I get for not reading.
comment on: http://stackoverflow.com/q/52507696
score: 0
type: QuestionComment

http://stackoverflow.com/q/52529152
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52549710
tagged with: python-xarray
has answer: http://stackoverflow.com/a/52546155
tagged with: python
accepted answer: http://stackoverflow.com/a/52549710
possible better answer: http://stackoverflow.com/a/52546155
score: 0
tagged with: scipy
type: AnsweredQuestion
has title: Applying scipy.ndimage.convolve to tridimensional xarray DataArray
has body: I have a 3D xarray DataArray with dimensions x, y, z, and I'm trying to apply scipy.ndimage.convolve over each x-y plane while maintaining the output as a DataArray. Naturally I'm trying to use xr.apply_ufunc to do that. If I do it for only one plane it works perfectly: da=xr.DataArray(np.random.rand(5,5,5), dims=("x", "y", "z")) kernel=np.ones((3,3)) from scipy.ndimage import convolve conv1 = lambda x: convolve(x, kernel, mode="wrap") print(xr.apply_ufunc(conv1, da[:,:,0])) # works successfully I'm now trying to come up with a way to do the same for every x-y plane. What I thought was going to work was using np.apply_along_axis or np.apply_over_axes, but none of them work. I could iterate over the axis, put everything in a list, and concatenate, but I'm trying to use xr.apply_ufunc to avoid problems with the attributes. Is there a way to do that? Here's an example of something that I thought should work, but that doesn't: np.apply_over_axes(conv1, c, axes=(0,1)) but this fails with TypeError: &lt;lambda&gt;() takes 1 positional argument but 2 were given

http://stackoverflow.com/a/72928128
answers question: http://stackoverflow.com/q/52530293
type: Answer
score: 2
downvote count: 0
has body: There is no way to do this with PyPDF2 at the moment (I'm the maintainer of PyPDF2). See also: https://github.com/py-pdf/PyPDF2/issues/1071
upvote count: 2

http://stackoverflow.com/a/52548224
score: 3
type: Answer
has body: Python passes by object. In change_list1, you pass a mutable object, and mutate it. It's the same object (a list), just altered (content changed). mylist is a local parameter that refers to the object. The function returns the original object. You'll find that his_list is altered as well because it refers to the same object. In change_list2, you also pass a mutable object, but instead of mutating it, you assign a new object to the local parameter. The original object is unchanged. The function returns the new object. It's helpful to think of variables in Python as just names of objects. When you pass parameters to a function, the names of the parameters in the function are just new names for the original objects passed into the function. You can see this by printing the IDs of the object names passed into the function, and the IDs of the object names of the parameters: a = [1,2,3] # mutable object (content can be altered) b = 1 # immutable object (content can't be altered). print(f'id(a) = {id(a)}, id(b) = {id(b)}') def func(c,d): print('INSIDE func') print(f'id(c) = {id(c)}, id(d) = {id(d)}') c.append(4) # mutable object can be altered. d = 4 # local name 'd' assigned a new object. print('AFTER altering c &amp; d') print(f'id(c) = {id(c)}, id(d) = {id(d)}') return c,d e,f = func(a,b) print('AFTER func called') print(f'id(a) = {id(a)}, id(b) = {id(b)}') print(f'id(e) = {id(e)}, id(f) = {id(f)}') print(f'a = {a}, b = {b}') print(f'e = {e}, f = {f}') Output: id(a) = 2290226434440, id(b) = 1400925216 INSIDE func id(c) = 2290226434440, id(d) = 1400925216 AFTER altering c &amp; d id(c) = 2290226434440, id(d) = 1400925312 AFTER func called id(a) = 2290226434440, id(b) = 1400925216 id(e) = 2290226434440, id(f) = 1400925312 a = [1, 2, 3, 4], b = 1 e = [1, 2, 3, 4], f = 4 Note that the IDs of a and b coincide with parameter names c and d. The names refer to the same objects. c object gets mutated. a refers to the same object, so will show the same change. d object is immutab…
upvote count: 3
answers question: http://stackoverflow.com/q/52548178
downvote count: 0

http://stackoverflow.com/q/52433517
upvote count: 29
has comment: http://stackoverflow.com/comment/91833766
tagged with: conda
linked to: http://stackoverflow.com/q/53267063
answer count: 3
has answer: http://stackoverflow.com/a/55117851
has body: I installed Anaconda and created a new env ("dell_proj"). Then I created a new Project in Pycharm with my new environment. My expectation was that I would only be able to use packages in this project that I installed through Conda in that specific env, however, I am able to use all packages that were installed in the Base environment. Packages shown available in Conda for env Packages shown available in Pycharm for env Could somebody explain what I'm misunderstanding here?
favorite count: 0
linked to: http://stackoverflow.com/q/45329107
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91833667
tagged with: pycharm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140170680
score: 29
has answer: http://stackoverflow.com/a/52433651
tagged with: python
has title: Do newly created conda envs inherit all packages from the base env?
has comment: http://stackoverflow.com/comment/91833748
tagged with: anaconda
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/52433854

http://stackoverflow.com/q/52548787
tagged with: parse-server
tagged with: python
tagged with: python-3.x
has title: GET from back4app
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52608276
downvote count: 1
type: Question
tagged with: back4app
has body: I pretty much copy and pasted from the parse documentation to get server information: import json import http.client conn = http.client.HTTPSConnection('parseapi.back4app.com', 443) conn.connect() conn.request('GET', '/APP/users/ObjectID', '', { "X-Parse-Application-Id": 'AppID', "X-Parse-REST-API-Key": 'REST_API_kkey' }) result = json.loads(conn.getresponse().read()) print (result) but i keep getting this result: {'message': 'Not Found', 'error': {}}
score: -1
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52574859
has body: I'm new to Django. I'll be appreciate if anyone can help me. When I was trying to use the decorator @permission_required in a view in Django, it always told that my app name is not defined. I put this before a view in request/views.py: @permission_required(request.change_part_status) and got this error NameError: name 'request' is not defined Do I have to import something or is there something I missed?
type: Question
has title: Django decorator @permission_required
has comment: http://stackoverflow.com/comment/92089185
tagged with: decorator
tagged with: permissions
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/92085578
tagged with: django
tagged with: python

google-signin
tags question: http://stackoverflow.com/q/52584755
type: Tag
tag name: google-signin

http://stackoverflow.com/a/52449902
upvote count: 4
answers question: http://stackoverflow.com/q/52449810
accepted answer of: http://stackoverflow.com/q/52449810
score: 4
type: AcceptedAnswer
downvote count: 0
has body: I think you would want to use plt.show() at the end of your loop. %matplotlib inline import matplotlib.pyplot as plt import numpy as np for i in range(25): fig, ax_arr = plt.subplots(1,2) ax_arr[0].imshow(np.random.randn(10,10)) ax_arr[1].imshow(np.random.randn(10,10)) plt.show() There is then no need to close anything.
type: Answer

http://stackoverflow.com/comment/92060726
score: 0
comment on: http://stackoverflow.com/q/52554917
type: Comment
has text: Did you read [the documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html) before you posted? What did you learn from it? Why didn't it answer your question?
type: QuestionComment

http://stackoverflow.com/a/52537461
accepted answer of: http://stackoverflow.com/q/52537432
type: AcceptedAnswer
has body: Use m1 positive values and m2 negative value masks then stack and drop_duplicates as: m1 = (df.corr().gt(0.5)) &amp; (df.corr().ne(1)) m2 = (df.corr().lt(-0.5)) &amp; (df.corr().ne(-1)) df.corr()[m1|m2].stack().drop_duplicates().round(3).to_dict() OR d = df.corr() m = ((d&gt;0.5)&amp;(d!=1))|((d&lt;-0.5)&amp;(d!=-1)) d[m].stack().drop_duplicates().round(3).to_dict() Both produces output: {('CRIM', 'ZN'): -0.199, ('CRIM', 'INDUS'): 0.404, ('CRIM', 'NOX'): 0.418, ('CRIM', 'RM'): -0.22, ('CRIM', 'AGE'): 0.351, ('ZN', 'INDUS'): -0.534, ('ZN', 'NOX'): -0.517, ('ZN', 'RM'): 0.312, ('ZN', 'AGE'): -0.57, ('INDUS', 'NOX'): 0.764, ('INDUS', 'RM'): -0.392, ('INDUS', 'AGE'): 0.645, ('NOX', 'RM'): -0.302, ('NOX', 'AGE'): 0.731, ('RM', 'AGE'): -0.24}
score: 1
answers question: http://stackoverflow.com/q/52537432
has comment: http://stackoverflow.com/comment/92014724
has comment: http://stackoverflow.com/comment/92014804
type: Answer
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/52451154
has title: Flask app not using config file settings properly
has answer: http://stackoverflow.com/a/64762919
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91845674
has comment: http://stackoverflow.com/comment/91845807
has answer: http://stackoverflow.com/a/57128537
favorite count: 0
has body: I'm following the guide here trying to create a config.py file for my flask app's settings but it is not working. from flask import Flask # creates the application def create_app(): app = Flask(__name__) app.config.from_object('instance.config.DevelopmentConfig') # home @app.route('/') def home(): return str(app.config['DEBUG']) # displays 'False' # return str(app.config['SECRET_KEY']) -- displays 'dev' return app my instance/config.py file class DevelopmentConfig(object): ENV = 'development' DEBUG = True SECRET_KEY = 'dev' When I do flask run it runs the server in production with debug off. I'm not using export FLASK_ENV because I am under the impression that it isn't needed when you have a config.py file. Is my assumption wrong? Why is it correctly recording the app.config['SECRET_KEY'] but not the DEBUG mode?
type: Question
has answer: http://stackoverflow.com/a/58103736
has answer: http://stackoverflow.com/a/52456520
has comment: http://stackoverflow.com/comment/91845758
tagged with: python
accepted answer: http://stackoverflow.com/a/64762919
possible better answer: http://stackoverflow.com/a/58103736
downvote count: 1
has answer: http://stackoverflow.com/a/65646188
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/109517283
answer count: 5
has comment: http://stackoverflow.com/comment/91845623
tagged with: flask

http://stackoverflow.com/a/57241300
accepted answer of: http://stackoverflow.com/q/52495895
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52495895
has body: Just add the line: while True: data = client_sock.recv(1024) if len(data) == 0: break print("received [%s]" % data) I have tested is only with python 3.7
has comment: http://stackoverflow.com/comment/102126496

http://stackoverflow.com/q/52498463
has comment: http://stackoverflow.com/comment/91937412
type: Question
accepted answer: http://stackoverflow.com/a/52501474
has answer: http://stackoverflow.com/a/52498703
upvote count: 13
tagged with: amazon-web-services
favorite count: 0
possible better answer: http://stackoverflow.com/a/55962613
has answer: http://stackoverflow.com/a/52501474
has answer: http://stackoverflow.com/a/55962613
tagged with: python
downvote count: 0
has body: conn_string = "dbname='{}' port='{}' user='{}' password='{}' host='{}'"\ .format(dbname,port,user,password,host_url) sql="""UNLOAD ('select col1,col2 from %s.visitation_hourly_summary_us where col4= '2018-07-10' and col5= '1';') TO 's3://%s/%s/%s.csv' \ credentials 'aws_access_key_id=%s;aws_secret_access_key=%s' \ MANIFEST GZIP ALLOWOVERWRITE;Commit;""" \ % (schema_name,s3_bucket_name, schema,table,aws_access_key_id,\ aws_secret_access_key) con = psycopg2.connect(conn_string) cur = con.cursor() cur.execute(sql) I'm trying to execute the above script to read the table and then create a file in S3 Since my columns are string I'm not able to skip the single quotes and I'm getting error as syntax error near where Also, I've tried giving \ in where condition still it showing the same error. Any help would be highly appreciated. Thanks
answer count: 5
score: 13
has title: How to escape single quotes in Unload
has answer: http://stackoverflow.com/a/55960920
has answer: http://stackoverflow.com/a/54050482
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91937498
tagged with: amazon-s3
tagged with: amazon-redshift-spectrum

wsgi
type: Tag
tags question: http://stackoverflow.com/q/52473300
tag name: wsgi
tags question: http://stackoverflow.com/q/52448861

http://stackoverflow.com/comment/91970503
type: Comment
comment on: http://stackoverflow.com/a/52515228
score: 1
type: AnswerComment
has text: if it's massive data set, having two data frames can be tedious.

http://stackoverflow.com/comment/91942663
type: Comment
type: QuestionComment
has text: Then you should first try to solve the import problems by looking for answers on SO.
comment on: http://stackoverflow.com/q/52500736
score: 0

http://stackoverflow.com/comment/113378450
has text: I was about to head down the path of fixing all the places where someone else's code uses `pyspark.sql.functions.round` so I can use the built-in `round`, but had forgotten about the existence of the `builtins` module. On a deadline, and pressed for time, it is way easier to `import builtins` and later call `builtins.round`, so thank you for this answer!
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/64024182

http://stackoverflow.com/comment/91811283
comment on: http://stackoverflow.com/q/52433794
type: Comment
type: QuestionComment
has text: First you should not store passwords! Never!
score: 1

http://stackoverflow.com/a/52527695
downvote count: 0
type: Answer
score: 1
has body: You can use a regular expression replace: s = '1:CH,AG,ME,GS,AP,CH,HE,AC,AC,AG,CA,HE,AT,AT,AC,AT,OG,NE,AG,AC,CS,OD\n&amp;:TA,EB,PA,AC,BR,TH,PO,AC,2I,AC,TH,PE,TH,AZ,AZ,ZE,CS,OD,CH,EO,ZE,OG\n&amp;:TH,ZE,ZE,HE,HE,HP,HP,OG,HP,ZE\n2:ZE,FD,FD,AG,EO,OG,AG,NE,RU,GS,HP,ZE,ZE,HM,HM,PC,PC,AS,AS,TY,TY,AG\n&amp;:AG,GS,NO,EU,ZF,HE,AT,AT,OD,OD,EB,OD,GS,TR,OD,AC,TR,GS,OD,TR,OD,AT,GS\n&amp;:CA,GS,NE,GS,AG,PS,HL,AG,NE,ID,AJ,AX,DI,OD,ME,AT,GS,MU,HO,PB,LT,9Z,PT,9Y\n&amp;:9W,9X,AR,9V,9U,9T,AX,9S,9R,AT,AJ,DI,ST,EA,AG,ME,NE,MU,9Q,9P,9O,9N,9M,9L\n&amp;:9K,ID,MG,OD,FY,AU,AU,HR,HR,9J,TL,9I,9H,9G,9F,AC,BR,AC,9E,9D,9C,9B,99\n' s = re.sub(r"(\n\d*?:)|(\n&amp;:)", ",", s).strip() # replaces the middle bits with commas and strips trailing \n s = re.sub(r"^(\d*?:)|(&amp;:)", "", s) # removes the initial 1: or similar
answers question: http://stackoverflow.com/q/52527435
upvote count: 1

http://stackoverflow.com/comment/91953520
comment on: http://stackoverflow.com/a/52506422
score: 0
type: Comment
has text: Thank You Solved it ;-)
type: AnswerComment

http://stackoverflow.com/comment/104895376
has text: You may need `lsof | grep "foldername"`
type: Comment
comment on: http://stackoverflow.com/a/52564444
score: 0
type: AnswerComment

http://stackoverflow.com/q/52501358
has body: We have a model order. This is having a reference to different table fulfillment. I need to fetch details from both table for indexing. I achieved the get part of index by overriding get_raw_record() function. but I am not able to figure out that how update will work. ie wherever there is change in fulfillment then , then Order Index should update. # from index.py file @register(Order) class OrderIndex(AlgoliaIndex): custom_objectID = 'id' index_name = 'orders' fields = ( 'name', 'created_at', 'total_price', 'fulfillment_status', 'email', 'tags', 'item_names') def get_raw_record(self, instance, update_fields=None): algolia_dict = instance.algolia_fields res_dict = super(OrderIndex, self).get_raw_record(instance, update_fields) return merge_two_dicts(res_dict, algolia_dict) # Order and Fulfillment models: class Order(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) oid = models.BigIntegerField() email = models.CharField(max_length=100) closed_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField() updated_at = models.DateTimeField() no = models.CharField(max_length=100) test = models.BooleanField(default=False) total_price = models.FloatField(blank=True, null=True) currency = models.CharField(max_length=10, blank=True, null=True) name = models.CharField(max_length=50) fulfillment_status = models.CharField(max_length=20, blank=True, null=True) tags = models.CharField(max_length=200, blank=True, null=True) shipping_address = JSONField(default=dict) customer_info = JSONField() @property def algolia_fields(self): fulfillmemt_ids = [item.id for item in self.order_fulfillments.all()] return {'customer_info': { 'first_name': self.customer.first_name, 'last_name': self.customer.last_name, 'email': self.customer.email, 'phone': self.customer.phone }, 'created_date': arrow.ge…
score: 0
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9160263
has answer: http://stackoverflow.com/a/52648094
type: Question
tagged with: algolia
has title: How to update an algolia index that is mix of multiple data models
answer count: 1

http://stackoverflow.com/a/52536258
accepted answer of: http://stackoverflow.com/q/52535690
type: Answer
score: 3
upvote count: 3
has body: Looking under the References section on this page, as of today there's no Python SDK available for creating an index in an Azure Search account. You would need to consume REST API directly in your code. You can read the REST API documentation for creating an index here: https://learn.microsoft.com/en-us/rest/api/searchservice/create-index.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52535690

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/52548500
tags question: http://stackoverflow.com/q/52459179
tags question: http://stackoverflow.com/q/52542201
tags question: http://stackoverflow.com/q/52544571