http://stackoverflow.com/a/50792612
downvote count: 0
has comment: http://stackoverflow.com/comment/88741342
answers question: http://stackoverflow.com/q/50792565
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88624581
has body: Use Regex: Ex: import re data = """Sett S=1 Stage Tmsec; NP=81 NC1=3 Sett S=2 Stage Tmsec; NP=82 NC1=4 Sett S=3 Stage Tmsec; NP=83 NC1=5""" Sett_S = re.findall("Sett S=(.*)", data) NP = re.findall("NP=(.*)", data) NC1 = re.findall("NC1=(.*)", data) for i in zip( Sett_S, NP, NC1 ): print(i) Output: ('1', '81', '3') ('2', '82', '4') ('3', '83', '5')
score: 1
has comment: http://stackoverflow.com/comment/88740221

http://stackoverflow.com/q/50779695
favorite count: 0
tagged with: python-3.x
has body: I want to do an statistical study of an strategy called Martingala. For now I want to practice it many times, adding the results to a list. The problem is that despite being random, it returns me always the same result. I suspect it is because of the random module not being truly random. How can I solve it? Many thanks. import random print("ANÁLISIS ESTADÍSTICO DE LA MARTINGALA") print() print("La apuesta mínima es 1€") dinero = int(input("Con cuanto dinero empiezas? ")) muestra = int(input("Tamaño de la muestra: ")) dinero_apostado=1 tiradas=0 datos=list() while muestra&gt;0: while dinero &gt;= dinero_apostado: casilla=random.choices([0,1,2],[1,18,18]) casilla=casilla.pop() if casilla == 1: dinero = dinero + dinero_apostado dinero_apostado = 1 elif casilla != 1: dinero = dinero - dinero_apostado dinero_apostado = dinero_apostado * 2 tiradas+=1 datos.append(tiradas) muestra-=1 print(datos)
type: Question
has comment: http://stackoverflow.com/comment/88566279
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/88566264
has answer: http://stackoverflow.com/a/50779785
has comment: http://stackoverflow.com/comment/88566519
has title: How to make random.choices truly random (I cannot find it in secrets module)
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/50779785
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88605624

http://stackoverflow.com/comment/88413463
comment on: http://stackoverflow.com/q/50702058
score: 0
type: Comment
type: QuestionComment
has text: Because you're comparing a class object to a string? This isn't javascript, where `typeof` returns a string.

http://stackoverflow.com/q/50797009
has comment: http://stackoverflow.com/comment/88600323
score: 0
has comment: http://stackoverflow.com/comment/88600359
answer count: 1
has comment: http://stackoverflow.com/comment/88599923
has comment: http://stackoverflow.com/comment/90438066
has answer: http://stackoverflow.com/a/50798597
has body: I am still not satisfied with django foreignkey relationship. below are two classess . from django.db import models from django.utils.text import slugify from django_countries.fields import CountryField from django.conf import settings # Create your models here. class PhotoGallery(models.Model): title = models.CharField(max_length=255,unique=True) picture_choices = models.CharField(max_length=255,choices=PICTURE_CHOICES,default=NTR) description = models.TextField(default='') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='image_uploader') date_posted = models.DateTimeField(auto_now=True) views = models.PositiveIntegerField() likes = models.PositiveIntegerField() country = CountryField(blank_label='(select country)') slug = models.SlugField(allow_unicode=True,unique=True) def __str__(self): return self.title from django.contrib import admin from gallery.models import PhotoGallery class PhotoGalleryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} And below is class Imagesmodel that has a foreignkey .Calling the PhotoGallery class from class Imagesmodel is not a problem .MY big problem is doing the reverse class ImagesModel(models.Model): gala_obj = models.ForeignKey(PhotoGallery, related_name='picture_gallery',on_delete=models.CASCADE) post_image = models.ImageField(upload_to='gallery_pics', verbose_name='Image') def __str__(self): return self.gala_obj.title and below is my views.py file `def detailViewPage(request,slug): #here i wanted to get one image with the given slug from `ImagesModel` a = get_object_or_404(PhotoGallery, slug=slug) selected_pic = a.picture_gallery.all() #here i wanted to get all images excluding one with the given slug object_2 = ImagesModel.objects.exclude(id=selected_pic.id) .order_by('-id')[:15] return render(request,'gallery/photogallery_detail.html',{ 'selected_pic':selected_pic, 'object_2':object_2, })` below is the error i get
has comment: http://stackoverflow.com/comment/88600044
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88599959
type: Question
has comment: http://stackoverflow.com/comment/88600243
has comment: http://stackoverflow.com/comment/88600393
has comment: http://stackoverflow.com/comment/88600022
has title: django foreignkey not working

http://stackoverflow.com/a/50804102
answers question: http://stackoverflow.com/q/50803988
type: Answer
upvote count: 1
has body: You could create an iterator as a class member. Initialize at None at start, and if None, use iter on random.sample on your whole list. When called, return the next element. On StopIteration exception (normal when you reach the end of the list), create another randomly shuffled list wrapped in a new iterable : import random class Foo: messages = [ 'Nice cat', 'What a lovely cat', 'Wow, great picture', 'Amaizing, I am in love &lt;3', 'Beautiful', 'I have same cat :)' ] def __init__(self): self.__msgiter = None def randomComments(self): if self.__msgiter: try: return next(self.__msgiter) except StopIteration: pass self.__msgiter = iter(random.sample(self.messages,len(self.messages))) return next(self.__msgiter) f = Foo() for _ in range(10): print(f.randomComments()) one output: What a lovely cat Wow, great picture I have same cat :) Amaizing, I am in love &lt;3 Nice cat Beautiful Nice cat What a lovely cat Beautiful I have same cat :)
accepted answer of: http://stackoverflow.com/q/50803988
has comment: http://stackoverflow.com/comment/88615829
score: 1
has comment: http://stackoverflow.com/comment/88615948
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50714458
tagged with: python
linked to: http://stackoverflow.com/q/39659180
tagged with: pycharm
has comment: http://stackoverflow.com/comment/88448320
tagged with: pip
has title: Can not update pip. Or install pip. windows 10 pycharm
type: Question
score: 0
has body: Can not update or any commands with pip is not working. Shows this exceptions while updating: Exception: Traceback (most recent call last): File "c:\program files (x86)\python36-32\lib\shutil.py", line 544, in move os.rename(src, real_dst) PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\lib\\site-packages\\pip-9.0.3.dist-info\\description.rs t' -&gt; 'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-lpjr52z1-uninstall\\program files (x86)\\python36-32\\lib\\site-packages\\pip-9.0.3.dist-inf o\\description.rst' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 778, in install requirement.uninstall(auto_confirm=True) File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 754, in uninstall paths_to_remove.remove(auto_confirm) File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_uninstall.py", line 115, in remove renames(path, new_path) File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 267, in renames shutil.move(old, new) File "c:\program files (x86)\python36-32\lib\shutil.py", line 559, in move os.unlink(src) PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\lib\\site-packages\\pip-9.0.3.dist-info\\description.rs t'
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50717605
type: UnansweredQuestion

http://stackoverflow.com/a/50793599
type: Answer
downvote count: 1
has body: So i have been doing some testing and found out the following about this problem. As i have been trying to reuse my created model i had to use the tf.global_variables_initializer(). By doing so it has overwritten my imported graph and all the values were random, which explains different network outputs. This still left me with a problem to solve: how do i load my network? The workaround i am currently using is not optimal by far but it at least allows me to use my saved model. Tensor flow allows one to give unique names to the functions and tensors used. By doing so i could access them through the graph: with tf.Session() as sess: saver = tf.train.import_meta_graph('path to .meta') saver.restore(sess, tf.train.latest_checkpoint('path to checkpoints')) graph = tf.get_default_graph() graph.get_tensor_by_name('name:0') Using this method i could access all my saved values, but they were separated! It means that i had 1x weight and 1x bias per operation used, which led to a bunch of new variables. If you do not know the names, use following: print(graph.get_all_collection_keys()) This prints the collection names (our variables are stored in collections) print(graph.get_collection('name')) This allows us to access the collection as see what are the names/keys for our variables. This led to another problem. I could no longer use my model as global variables initializer had everything overwritten. By thus i had to redefine the whole model manually with weight and biases that i got previously. Unfortunately, this is the only thing i could come up with. If anyone has a better idea, please let me know. The whole thing with mistake looked like this: imports... placeholders for data... def my_network(data): ## network definition with tf functions ## return output def train_my_net(): prediction = my_network(data) cost function optimizer with tf.Session() as sess: for i in how many epochs i want: training routine save def use_my_net(): prediction = my_network(data) with tf.Session…
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/50706680

recursion
tags question: http://stackoverflow.com/q/50730315
type: Tag
tags question: http://stackoverflow.com/q/50774975
tag name: recursion
tags question: http://stackoverflow.com/q/50749527
tags question: http://stackoverflow.com/q/50793016
tags question: http://stackoverflow.com/q/50844692
tags question: http://stackoverflow.com/q/50839112
tags question: http://stackoverflow.com/q/50718514
tags question: http://stackoverflow.com/q/50821728
tags question: http://stackoverflow.com/q/50853849
tags question: http://stackoverflow.com/q/50744669
tags question: http://stackoverflow.com/q/50730359
tags question: http://stackoverflow.com/q/50747181
tags question: http://stackoverflow.com/q/50841777

tensorflow
tags question: http://stackoverflow.com/q/50770467
tags question: http://stackoverflow.com/q/50723072
tags question: http://stackoverflow.com/q/50786034
tags question: http://stackoverflow.com/q/50751484
tags question: http://stackoverflow.com/q/50796984
tags question: http://stackoverflow.com/q/50737973
tags question: http://stackoverflow.com/q/50742686
tags question: http://stackoverflow.com/q/50792130
tags question: http://stackoverflow.com/q/50713528
tags question: http://stackoverflow.com/q/50744565
tags question: http://stackoverflow.com/q/50801949
tags question: http://stackoverflow.com/q/50786427
tags question: http://stackoverflow.com/q/50854342
tags question: http://stackoverflow.com/q/50789709
tags question: http://stackoverflow.com/q/50849823
tags question: http://stackoverflow.com/q/50703942
tags question: http://stackoverflow.com/q/50727045
tags question: http://stackoverflow.com/q/50706967
tags question: http://stackoverflow.com/q/50784875
tags question: http://stackoverflow.com/q/50828699
tags question: http://stackoverflow.com/q/50769500
tags question: http://stackoverflow.com/q/50781253
tags question: http://stackoverflow.com/q/50707717
tags question: http://stackoverflow.com/q/50782516
tags question: http://stackoverflow.com/q/50752787
tags question: http://stackoverflow.com/q/50825248
tags question: http://stackoverflow.com/q/50820639
tags question: http://stackoverflow.com/q/50836434
tags question: http://stackoverflow.com/q/50715928
tags question: http://stackoverflow.com/q/50849877
tags question: http://stackoverflow.com/q/50724495
tags question: http://stackoverflow.com/q/50817851
tags question: http://stackoverflow.com/q/50719510
tags question: http://stackoverflow.com/q/50784337
tags question: http://stackoverflow.com/q/50778593
tags question: http://stackoverflow.com/q/50815325
tags question: http://stackoverflow.com/q/50700481
tags question: http://stackoverflow.com/q/50780561
tags question: http://stackoverflow.com/q/50779554
tags question: http://stackoverflow.com/q/50701410
tags question: http://stackoverflow.com/q/50809155
tags question: http://stackoverflow.com/q/50812641
tags question: http://stackoverflow.com/q/50740219
tags question: http://stackoverflow.com/q/50706431
tags question: http://stackoverflow.com/q/50729148
tags question: http://stackoverflow.com/q/50745868
tags question: http://stackoverflow.com/q/50712246
tags question: http://stackoverflow.com/q/50794383
tags question: http://stackoverflow.com/q/50756586
tags question: http://stackoverflow.com/q/50782881
tags question: http://stackoverflow.com/q/50768538
tags question: http://stackoverflow.com/q/50755544
tags question: http://stackoverflow.com/q/50742245
tags question: http://stackoverflow.com/q/50839892
tags question: http://stackoverflow.com/q/50747981
tags question: http://stackoverflow.com/q/50819035
tags question: http://stackoverflow.com/q/50823794
tags question: http://stackoverflow.com/q/50843487
tags question: http://stackoverflow.com/q/50706992
tags question: http://stackoverflow.com/q/50756732
tags question: http://stackoverflow.com/q/50770655
tag name: tensorflow
tags question: http://stackoverflow.com/q/50733342
tags question: http://stackoverflow.com/q/50746530
tags question: http://stackoverflow.com/q/50843524
tags question: http://stackoverflow.com/q/50805634
tags question: http://stackoverflow.com/q/50732229
tags question: http://stackoverflow.com/q/50829631
tags question: http://stackoverflow.com/q/50700841
tags question: http://stackoverflow.com/q/50779773
tags question: http://stackoverflow.com/q/50853708
tags question: http://stackoverflow.com/q/50720041
tags question: http://stackoverflow.com/q/50824643
tags question: http://stackoverflow.com/q/50765892
tags question: http://stackoverflow.com/q/50807504
tags question: http://stackoverflow.com/q/50778953
tags question: http://stackoverflow.com/q/50707653
tags question: http://stackoverflow.com/q/50814751
tags question: http://stackoverflow.com/q/50744453
tags question: http://stackoverflow.com/q/50783854

http://stackoverflow.com/q/50823252
has answer: http://stackoverflow.com/a/50824894
has answer: http://stackoverflow.com/a/50880245
tagged with: python
has body: I'm trying to get following: Get all EC2 instances that either: are Tagged with tag Owner and value Unknown or unknown are missing tag Owner I'm able to accomplish 1) but no idea how to get 2) import boto3 import collections import datetime import time import sys ec = boto3.client('ec2', 'eu-west-1') ec2 = boto3.resource('ec2', 'eu-west-1') def lambda_handler(event, context): instance_ids = [] reservations = ec.describe_instances( Filters=[ {'Name': 'tag:Owner', 'Values': ['Unknown', 'unknown']}, ] ).get('Reservations', []) for reservation in reservations: instances = reservation['Instances'] for instance in instances: instance_ids.append(instance['InstanceId']) print("Stopping instances: {}".format(','.join(instance_ids)))
score: 2
type: AnsweredQuestion
type: Question
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/50880245
downvote count: 0
tagged with: amazon-ec2
tagged with: amazon-web-services
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/88653071
favorite count: 0
accepted answer: http://stackoverflow.com/a/50824894
has title: Lambda function to check if specific tag do NOT exists-python
has comment: http://stackoverflow.com/comment/88653031

http://stackoverflow.com/q/50725888
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/78723796
has answer: http://stackoverflow.com/a/59502223
has answer: http://stackoverflow.com/a/50726888
score: 76
has body: April 2024 UPDATE, Please read: It appears the answer since late 2023 is the newly accepted answer provided by Mircea, this question is old so older, now incorrect answers, have more upvotes but please scroll down for that answer. original question: I'm using the May 2018 Python extension (released June 2018) for VS Code 1.23.1 on Windows, python 3.6 via Anaconda, conda installing black from conda-forge into my conda environment. In my user settings.json I have the below: "python.formatting.blackArgs": [ "--line-length 80" ], which I'd think would be the correct way to structure this to pass arguments to black in VS Code Python formatting. However, in my python Output pane I get the below: Formatting with black failed. Error: Error: no such option: --line-length 80 If I edit my settings.json to be no args, such as: "python.formatting.blackArgs": [], black works as expected. Does anyone know how to pass arguments correctly to the new (as of June 2018) black formatter?
has answer: http://stackoverflow.com/a/78269768
answer count: 7
possible better answer: http://stackoverflow.com/a/58048911
has answer: http://stackoverflow.com/a/77141211
favorite count: 0
has answer: http://stackoverflow.com/a/58048911
has title: VS Code Python + Black formatter arguments - python.formatting.blackArgs
tagged with: python-black
has answer: http://stackoverflow.com/a/57342416
tagged with: python
type: AnsweredQuestion
upvote count: 77
has comment: http://stackoverflow.com/comment/120743568
accepted answer: http://stackoverflow.com/a/77141211
has comment: http://stackoverflow.com/comment/137989053
downvote count: 1
has comment: http://stackoverflow.com/comment/120662309
type: Question

http://stackoverflow.com/a/50726779
downvote count: 0
score: 1
upvote count: 1
has body: I agree with @maverick's index fix but don't see any need for the index in the first place. Instead of: for x in range (0,int(size)): ... leo.forward(bheight[x]) which really should be: for x in range(size): ... leo.forward(bheight[x]) why not simply do: for height in bheight: ... leo.forward(height) The reworked code with this and various other style fixes: from turtle import Turtle, Screen def Water(): leo.penup() leo.setx(-200) leo.fillcolor('midnightblue') leo.begin_fill() for _ in range(2): leo.forward(400) leo.right(90) leo.forward(150) leo.right(90) leo.end_fill() leo.pendown() def Building(): leo.fillcolor('darkslategrey') for height in bheight: leo.begin_fill() leo.left(90) leo.forward(height) leo.right(90) leo.forward(20) leo.right(90) leo.forward(height) leo.left(90) leo.end_fill() blist = input('Please enter building heights e.g. "50 30 60": ') bsplit = blist.split() bheight = list(map(int, bsplit)) screen = Screen() screen.bgcolor("orange") leo = Turtle() Water() Building() screen.mainloop()
type: Answer
answers question: http://stackoverflow.com/q/50711550

http://stackoverflow.com/comment/88578194
has text: Hmm, with Windows in mind I'd also look at standalone installers built with `pyinstaller`/`cxFreeze` etc, however, I have very little experience with those. The best Windows option in my opinion would be writing a standalone installer with NSIS. In the installation script, you can create a fresh virtual environment, install the package along its dependencies in the env and adjust `PATH` so the installed executables are available. Unfortunately, the standard packaging tools (`distutils`/`setuptools`) are simply not powerful enough for that.
type: Comment
comment on: http://stackoverflow.com/q/50785230
score: 0
type: QuestionComment

http://stackoverflow.com/q/50724024
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: Writing a simple regex to find dates and times within strings. There's a small issue with identifying time-items when there's specific dates in the sting. Here's the regex: TIME_REGEX = "([0-1][0-9]|2[0-3])[:\-\_]?([0-5][0-9])[:\-\_]?([0-5][0-9])" The issue is that I need to accept time-values without anything between the numbers, hence the two "[:-_]?" parts. However, the regex matches even if the two are different from each other. So this will also match the date "2011-07-30" as being the time 20:11:07. Can I change the regex so both items inbetween the numbers are the same, so it matches "201107" and "20-11-07", but not "2011-07" or "20:11-07"?
type: Question
has title: Regex: (date/time) same item between each part
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50724732
favorite count: 0
has comment: http://stackoverflow.com/comment/88456501
tagged with: regex
score: 1
has answer: http://stackoverflow.com/a/50724767

http://stackoverflow.com/q/50749378
has title: Why does my Python program close after running the first loop?
score: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50749503
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88506526
has comment: http://stackoverflow.com/comment/88508351
has body: I'm new to Python and scraping. I'm trying to run two loops. One goes and scrapes ids from one page. Then, using those ids, I call another API to get more info/properties. But when I run this program, it just runs the first bit fine (gets the IDs), but then it closes and doesn't run the 2nd part. I feel I'm missing something really basic about control flow in Python here. Why does Python close after the first loop when I run it in Terminal? import requests import csv import time import json from bs4 import BeautifulSoup, Tag file = open('parcelids.csv','w') writer = csv.writer(file) writer.writerow(['parcelId']) for x in range(1,10): time.sleep(1) # slowing it down url = 'http://apixyz/Parcel.aspx?Pid=' + str(x) source = requests.get(url) response = source.content soup = BeautifulSoup(response, 'html.parser') parcelId = soup.find("span", id="MainContent_lblMblu").text.strip() writer.writerow([parcelId]) out = open('mapdata.csv','w') with open('parcelIds.csv', 'r') as in1: reader = csv.reader(in1) writer = csv.writer(out) next(reader, None) # skip header for row in reader: row = ''.join(row[0].split())[:-2].upper().replace('/','-') #formatting url="https://api.io/api/properties/" url1=url+row time.sleep(1) # slowing it down response = requests.get(url1) resp_json_payload = response.json() address = resp_json_payload['property']['address'] writer.writerow([address])
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50749503
type: Question

http://stackoverflow.com/comment/88653824
comment on: http://stackoverflow.com/a/50823733
type: Comment
score: 0
type: AnswerComment
has text: @zwer Will do. I have to wait 90 minutes to make another post so it will be up shortly.

http://stackoverflow.com/q/50751413
tagged with: google-cloud-storage
has body: I have two projects. I store data in project_A and build tables in project_B. I have created a service_account.json for both of them, but I don't know how to use both files at the same time when I need to load the data from project_A and build the tables in project_B. The data is stored in URI: gs://project_A//* The table will live in project_B table name huge_table from google import storage, bigquery proj_a_client = storage.Client.from_service_account_json(service_acct_A.json) proj_b_client = bigquery.Client.from_service_account_json(service_acct_B.json) dest_table = proj_b_client.dataset('DS_B').table('huge_table') uri = 'gs://project_A//*' job_config = bigquery.LoadJobConfig() load_job = proj_b_client.load_table_from_uri(uri, dest_table, job_config=job_config) But I get the error: google.api_core.exceptions.Forbidden: 403 Access Denied: File gs://project_A/: Access Denied
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50769127
has title: How to load data from one project's bucket into another project's table in python?
upvote count: 2
has comment: http://stackoverflow.com/comment/88533001
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50769127
tagged with: google-bigquery

http://stackoverflow.com/a/50800488
type: Answer
has body: IIUC, transform + set df2.groupby(level=0).avail.transform(lambda x : sum(set(x))) Out[220]: 2020 11 2020 11 2020 11 2020 11 2020 11 2021 29 2021 29 2021 29 Name: avail, dtype: int64
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50800409

http://stackoverflow.com/comment/88527443
has text: For `spark.master` settings.
comment on: http://stackoverflow.com/q/50758115
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50746992
upvote count: 2
linked to: http://stackoverflow.com/q/38013778
downvote count: 2
has comment: http://stackoverflow.com/comment/88501585
type: Question
duplicate of: http://stackoverflow.com/q/38985053
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88503148
has body: I have a 2d numpy array with repeated values in first column. The repeated values can have any corresponding value in second column. Its easy to find the cumsum using numpy, but, I have to find the cumsum for all the repeated values. How can we do this effectively using numpy or pandas? Here, I have solved the problem using ineffective for-loop. I was wondering if there is a more elegant solution. Question How can we get the same result in more effective fashion? Help will be appreciated. #!python # -*- coding: utf-8 -*-# # # Imports import pandas as pd import numpy as np np.random.seed(42) # make results reproducible aa = np.random.randint(1, 20, size=10).astype(float) bb = np.arange(10)*0.1 unq = np.unique(aa) ans = np.zeros(len(unq)) print(aa) print(bb) print(unq) for i, u in enumerate(unq): for j, a in enumerate(aa): if a == u: print(a, u) ans[i] += bb[j] print(ans) """ # given data idx col0 col1 0 7. 0.0 1 15. 0.1 2 11. 0.2 3 8. 0.3 4 7. 0.4 5 19. 0.5 6 11. 0.6 7 11. 0.7 8 4. 0.8 9 8. 0.9 # sorted data 4. 0.8 7. 0.0 7. 0.4 8. 0.9 8. 0.3 11. 0.6 11. 0.7 11. 0.2 15. 0.1 19. 0.5 # cumulative sum for repeated serial 4. 0.8 7. 0.0 + 0.4 8. 0.9 + 0.3 11. 0.6 + 0.7 + 0.2 15. 0.1 19. 0.5 # Required answer 4. 0.8 7. 0.4 8. 1.2 11. 1.5 15. 0.1 19. 0.5 """
tagged with: data-manipulation
has answer: http://stackoverflow.com/a/50747045
tagged with: numpy
tagged with: numpy-ndarray
answer count: 2
has title: Python: effective way to find the cumulative sum of repeated index (numpy method)
possible better answer: http://stackoverflow.com/a/50747200
favorite count: 0
duplicate of: http://stackoverflow.com/q/32751229
has answer: http://stackoverflow.com/a/50747200
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50747045
tagged with: python

http://stackoverflow.com/a/50749023
has comment: http://stackoverflow.com/comment/88506277
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50748857
downvote count: 0
has body: Provided you are using a fairly modern CPU, multiprocessing.cpu_count() won't give you the number of physical cores your machine has, but the number of hyper-threads. In a nutshell, hyper-threading allows a single physical core to have n (most commonly, two) pipelines, which fools your OS into thinking you've got n times the number of cores you really have. This is helpful, when you are doing some stuff that might starve a core with data (most notably, IO or RAM lookups caused by cache-misses), but your workload is purely arithmetic and it is not likely to starve your CPU, resulting in little to no gains from hyper-threading. And the little gains you might get will be overshadowed by multiprocessing overhead, which is quite significant. P.S. I usually post this sort of things as comments, but I've exceeded the comment size limitation. By the way, if you've chosen the Fibonacci series for something more that just an example, you might want to consider a faster algorithm: Fast Fibonacci computation
accepted answer of: http://stackoverflow.com/q/50748857
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/88507775

http://stackoverflow.com/a/77644831
answers question: http://stackoverflow.com/q/50777849
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: I find a simple way to work, you need to change the common command conda list -e > requirements.txt to conda list -F'=| ' '{print $1"=="$2}' > requirements.txt. As a result, you can obtain the file that the content format is 'package==version', which will work with pip install -r requirements.txt.

http://stackoverflow.com/q/50848050
has answer: http://stackoverflow.com/a/50848359
score: 0
has body: I am trying to do loops to convert a column of timestamp in a dataframe into ISO 8601 format. However, it keeps going back to the 1970 data with weird hour:minute:second. But if I just choose one timestamp and run the middle code "tz=... iso.format())", it works fine. df= pd.read_csv('file.csv') for i in range(len(df)): timestamp=df.loc[i,'timestamp'] # print(timestamp) #forloops to print ISO 8601 format res=[] def ISOformat(): tz = pytz.timezone('America/Los_Angeles') print(datetime.fromtimestamp(i, tz).isoformat()) for i in range(len(df)): res.append(ISOformat()) #make a dataframe of the ISO 8601 iso_8601_test= pd.DataFrame({'ISO_8601_time':res}) I like my output to be like this: 2011-12-31T16:05:00-08:00 not the 1970 time. Example of my timestamp: timestamp 1325376300 1325376600 1325376900 1325377200 1325377500 1325377800 1325378100 1325378400 1325378700 1325379000 1325379300 1325379600 1325379900
accepted answer: http://stackoverflow.com/a/50848359
tagged with: timestamp
type: Question
has title: Python convert Timestamp to ISO 8601 revert to 1970 in loops
tagged with: iso8601
answer count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50802257
answers question: http://stackoverflow.com/q/50798172
upvote count: 5
score: 5
type: AcceptedAnswer
has body: You can wrap the class DatasetFolder (or ImageFolder) in another class to limit the dataset: class LimitDataset(data.Dataset): def __init__(self, dataset, n): self.dataset = dataset self.n = n def __len__(self): return self.n def __getitem__(self, i): return self.dataset[i] You can also define some mapping between the index in LimitDataset and the index in the original dataset to define more complex behavior (such as random subsets). If you want to limit the batches per epoch instead of the dataset size: from itertools import islice for data in islice(dataloader, 0, batches_per_epoch): ... Note that if you use this shuffle, the dataset size will be the same, but the data that each epoch will see will be limited. If you don't shuffle the dataset this will also limit the dataset size.
downvote count: 0
has comment: http://stackoverflow.com/comment/88679453
has comment: http://stackoverflow.com/comment/88678773
type: Answer
accepted answer of: http://stackoverflow.com/q/50798172
has comment: http://stackoverflow.com/comment/88627051

http://stackoverflow.com/q/50809564
score: 1
has comment: http://stackoverflow.com/comment/88624914
type: Question
linked to: http://stackoverflow.com/q/4383571
has answer: http://stackoverflow.com/a/50809634
downvote count: 0
has comment: http://stackoverflow.com/comment/88645800
has comment: http://stackoverflow.com/comment/88628805
answer count: 1
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/88624818
accepted answer: http://stackoverflow.com/a/50809634
has title: Using a .py file inside a .py file
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88624707
has comment: http://stackoverflow.com/comment/88624717
has body: I'm fairly new to python and I've been exclusively using Jupyter Notebooks. When I need to run a .py file I have saved somewhere in my computer what I normally do is just use the magic command %run %run '/home/cody/.../Chapter 3/efld.py' %run '/home/cody/.../Chapter 5/tan_vec.py' Then in the next cell I can run efld.py without a problem. But tan_vec.py uses efld.py and looks like this, def tan_vec(r): import numpy as np #Finds the tangent vector to the electric field at point 'r' e = efld(r) e = np.array(e) #Turn 'e' into a numpy array so I can do math with it a little easier. emag = np.sqrt(sum(e**2)) #Magnitude of the return e / emag when I try to run that I get the error; "NameError: name 'efld' is not defined." I tried most of the things here but none of them seamed to work. Am I going about running py files in the notebook wrong? Is there a better way to run/call py files in a notebook? How do make it so that I can run one py file inside another py file? EDIT Thank you everyone for your help! I just wanted to add the final code that worked in case anyone comes across this later and wants to see what i did. def tan_vec(r): #import sys #sys.path.insert(0, '/home/cody/Physics 331/Textbook Programs/Chapter 3') from efld import efld import numpy as np #Finds the tangent vector to the electric field at point 'r' e = efld(r) e = np.array(e) #Turn 'e' into a numpy array so I can do math with it a little easier. emag = np.sqrt(sum(e**2)) #Magnitude of the return e / emag The first two lines are commented out because they were only needed if efld.py and tan_vec.py are saved in different folders. I just added a copy of efld to the same folder and tan_vec and I didn't need them any more. Thank you again for all the help!

http://stackoverflow.com/comment/88467142
type: AnswerComment
has text: Thanks, it works. However do you know how to do it, using existing structure (with group.by.rolling.apply)? In other words, is possible to create a function which could be nested in apply()? Thanks
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50729629

http://stackoverflow.com/comment/88564334
comment on: http://stackoverflow.com/a/50778544
type: AnswerComment
score: 0
type: Comment
has text: perfect!!!! I'm try to understand how it work lol but defintly got the job done would you happen to know how to write this data for all the urls for the site https://howlongtobeat.com/game.php?id= (from 0 to 30870)

http://stackoverflow.com/comment/88423837
comment on: http://stackoverflow.com/a/50706822
type: AnswerComment
has text: Changing the title of the question to pretend OP said 'n' is a bit disingenuous. The post only mentions "top 3" and if that is the case, your answer seems very inefficient. EDIT: Looks like you even modified the question text to pretend your answer is more applicable.
score: 0
type: Comment

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

lstm
tags question: http://stackoverflow.com/q/50785592
tags question: http://stackoverflow.com/q/50784540
tags question: http://stackoverflow.com/q/50780152
tags question: http://stackoverflow.com/q/50707501
tags question: http://stackoverflow.com/q/50810593
tags question: http://stackoverflow.com/q/50768538
tags question: http://stackoverflow.com/q/50785198
tags question: http://stackoverflow.com/q/50742559
tags question: http://stackoverflow.com/q/50782030
tag name: lstm
tags question: http://stackoverflow.com/q/50805147
tags question: http://stackoverflow.com/q/50826625
type: Tag

http://stackoverflow.com/comment/88533438
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50760254
type: QuestionComment
has text: Why is the program aborted? Is due to a python error inside the loop or something external? In the former case a try-except clause could help. Also if the frames are actually written to the file maybe there is repair tool for mp4 files available somewhere?

http://stackoverflow.com/a/50787459
has body: There are two issues: FixedlenFeature has to have the size defined. So change to: feature_set = { 'A': tf.FixedLenFeature([3], tf.int64), 'C': tf.FixedLenFeature([3], tf.float32)} You need to start the queues for reading the inputs, so your code should look like: with tf.Session() as sess: # for the queues init_op = tf.local_variables_initializer() sess.run(init_op) # Create a coordinator, launch the queue runner threads. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) try: for _ in range(1): print(sess.run([A,C])) except tf.errors.OutOfRangeError: # When done, ask the threads to stop. print('') finally: coord.request_stop() # Wait for threads to finish. coord.join(threads)
answers question: http://stackoverflow.com/q/50777324
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88616491
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50777324

http://stackoverflow.com/q/50818864
has answer: http://stackoverflow.com/a/51987804
tagged with: pandas
score: 2
answer count: 1
downvote count: 0
tagged with: tqdm
has body: I'm using tqdm combined with Pandas on Jupyter notebooks. I have a Pandas dataframe df. When i use df.progress_apply, new lines are printed instead of updating only one. This is what I currently do : tqdm.pandas(desc="Computing MONTH...") df["MONTH"] = df.progress_apply(compute_month, axis=1) My question is not a duplicate of this question : tqdm in Jupyter Notebook because they said to use tqdm_notebook instead of tqdm. I can't use tqdm_notebook as I need to implement df.progress_apply. I can't reproduce this issue on a minimal example because my code is too heavy. Here is an issue in Github related of this problem but couldn't help me : https://github.com/tqdm/tqdm/issues/375
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
has title: Newline created after each iteration
upvote count: 2
linked to: http://stackoverflow.com/q/42212810
type: Question

http://stackoverflow.com/q/50765633
has title: How to get a user's Reddit fullname?
score: 0
tagged with: api
tagged with: reddit
answer count: 1
type: UnansweredQuestion
has body: I've been playing around the the Reddit API and I've come across this endpoint: GET /api/user_data_by_account_ids According the the documentation, the query parameter for this endpoint is a comma separated list of fullnames. Reddit defines a fullname as: "a combination of a thing's type (e.g. Link) and its unique ID which forms a compact encoding of a globally unique ID on reddit. Fullnames start with the type prefix for the object's type, followed by the thing's unique ID in base 36. For example, t3_15bfi0." So I'm wondering how I can determine a user's fullname? Is it listed somewhere in their profile? Or is there another endpoint in Reddit's api for getting a user's fullname?
tagged with: python
has answer: http://stackoverflow.com/a/50937843
type: Question

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/50782258
tags question: http://stackoverflow.com/q/50802451
tags question: http://stackoverflow.com/q/50837943
tags question: http://stackoverflow.com/q/50701738
tags question: http://stackoverflow.com/q/50765946
tags question: http://stackoverflow.com/q/50711204
tags question: http://stackoverflow.com/q/50813567
tags question: http://stackoverflow.com/q/50707161
tags question: http://stackoverflow.com/q/50821649
tags question: http://stackoverflow.com/q/50767861
tags question: http://stackoverflow.com/q/50806927
type: Tag
tags question: http://stackoverflow.com/q/50771539
tags question: http://stackoverflow.com/q/50819578
tags question: http://stackoverflow.com/q/50707133
tags question: http://stackoverflow.com/q/50707948
tags question: http://stackoverflow.com/q/50799470
tags question: http://stackoverflow.com/q/50778767
tags question: http://stackoverflow.com/q/50772550
tags question: http://stackoverflow.com/q/50710718
tags question: http://stackoverflow.com/q/50820465
tags question: http://stackoverflow.com/q/50746183
tags question: http://stackoverflow.com/q/50817695
tags question: http://stackoverflow.com/q/50808053
tags question: http://stackoverflow.com/q/50713091
tags question: http://stackoverflow.com/q/50793994
tags question: http://stackoverflow.com/q/50834900
tags question: http://stackoverflow.com/q/50839911
tags question: http://stackoverflow.com/q/50757953
tags question: http://stackoverflow.com/q/50752296
tags question: http://stackoverflow.com/q/50716302
tags question: http://stackoverflow.com/q/50792494
tags question: http://stackoverflow.com/q/50731311
tags question: http://stackoverflow.com/q/50742749
tags question: http://stackoverflow.com/q/50755040
tags question: http://stackoverflow.com/q/50702922
tags question: http://stackoverflow.com/q/50737813
tags question: http://stackoverflow.com/q/50765072
tags question: http://stackoverflow.com/q/50784595
tags question: http://stackoverflow.com/q/50784955
tags question: http://stackoverflow.com/q/50769943
tags question: http://stackoverflow.com/q/50848879
tags question: http://stackoverflow.com/q/50798848
tags question: http://stackoverflow.com/q/50842951
tags question: http://stackoverflow.com/q/50799885

http://stackoverflow.com/a/50841812
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88688290
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50841713
has body: This is the read() function: def read(self,cmd): cmd_str = self.build_cmd_str(cmd,'') try: self.sp.write(cmd_str.encode()) self.sp.flush() except Exception: return None return self.sp.readline().decode('UTF-8').replace("\r\n", "") One of the things it can return is None as you can see in the return None line. If that happens, then your line: float(self.read('T1')) will fail, because it will try to convert None into a float, and that gives the error you're getting.
has comment: http://stackoverflow.com/comment/88689618
answers question: http://stackoverflow.com/q/50841713
score: 4
has comment: http://stackoverflow.com/comment/88689633
has comment: http://stackoverflow.com/comment/88687353
has comment: http://stackoverflow.com/comment/88688145
has comment: http://stackoverflow.com/comment/88695316

http://stackoverflow.com/a/50719143
type: AcceptedAnswer
has body: I think need one parameter index_col for convert first column to index with filter columns by usecols with join by default left join: df1 = pd.read_csv("field1.csv", index_col=[0], usecols=["ID","NAME","ACC"]) df2 = pd.read_csv("field2.csv", index_col=[0], usecols=["ID","SCORE","TEAM"]) finaldf = df1.join(df2) print (finaldf) NAME ACC SCORE TEAM ID 123 TRR OOP 87.0 BCC 124 DEE OOP NaN NaN 125 EWR PLO NaN NaN Another possible solution is filter columns before join by subsets: df1 = pd.read_csv("field1.csv", index_col=[0]) df2 = pd.read_csv("field2.csv", index_col=[0]) finaldf = df1"NAME","ACC".join(df2"SCORE","TEAM") Last write to file with omit index: finaldf.to_csv('final.csv', index=False)
has comment: http://stackoverflow.com/comment/88451415
type: Answer
has comment: http://stackoverflow.com/comment/88451360
accepted answer of: http://stackoverflow.com/q/50719059
answers question: http://stackoverflow.com/q/50719059
has comment: http://stackoverflow.com/comment/88446935
score: 0

http://stackoverflow.com/a/50775441
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88564054
has comment: http://stackoverflow.com/comment/88559610
upvote count: 1
has comment: http://stackoverflow.com/comment/88558242
has body: Consider the following triangle. 1 1 2 9 1 1 9 1 1 1 For this triangle, what would your algorithm think is the maximal path? You are going to need to find a different approach to solving this, but that's half the fun of Project Euler problems.
type: Answer
has comment: http://stackoverflow.com/comment/88557829
answers question: http://stackoverflow.com/q/50775378
has comment: http://stackoverflow.com/comment/88559072

http://stackoverflow.com/q/50795241
favorite count: 0
linked to: http://stackoverflow.com/q/3121979
tagged with: tuples
accepted answer: http://stackoverflow.com/a/50795278
has answer: http://stackoverflow.com/a/50795332
duplicate of: http://stackoverflow.com/q/3121979
tagged with: python
has body: I want to show the list from the large age to the small age. Here is my list: player = [("Dmitry", 15), ("Dima", 11), ("Sergey", 14), ("Andrey", 12), ("Nikita", 13)] I can sort list using name element by player.sort and get this list: [('Andrey',12),('Dima',11),('Dmitry',15),('Nikita',13),('Sergey',14)] But I want this list, where ages are large age to small age: [('Dmitry',15),('Sergey',14),('Nikita',13),('Andrey',12),('Dima',11)] How I can do this?
answer count: 4
possible better answer: http://stackoverflow.com/a/50795277
upvote count: 2
has answer: http://stackoverflow.com/a/50795277
score: 1
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50795278
tagged with: sorting
has title: Sort list of tuples by element two of all tuples
has answer: http://stackoverflow.com/a/50795283

http://stackoverflow.com/a/50787723
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50787607
has body: Assuming you want spyder2 for Python 2.7: You need to install spyder for the Python version you want: python -m pip install spyder Then you just need to run it for that version. So: python -m spyder
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88581783

http://stackoverflow.com/q/50728743
has comment: http://stackoverflow.com/comment/88467881
has comment: http://stackoverflow.com/comment/88466271
type: Question
has comment: http://stackoverflow.com/comment/88465781
has comment: http://stackoverflow.com/comment/88466154
score: 0
has title: gap between QListWidget items/icons
has body: I would like to remove the gap between my QListWidget items in my textureIconChart QListWidget. It is populated with items set with pixmap icons. I am using QListWidget set to a QHBoxLayout, which is set to a QVBoxLayout. import maya.cmds as cmds import os import maya.OpenMayaUI as mui from PySide2 import QtWidgets,QtCore,QtGui import shiboken2 class texture_replacer(): def texture_linker_UI(self): windowName = "name" if cmds.window(windowName,exists = True): cmds.deleteUI(windowName, wnd = True) pointer = mui.MQtUtil.mainWindow() parent = shiboken2.wrapInstance(long(pointer),QtWidgets.QWidget) window = QtWidgets.QMainWindow(parent) window.setObjectName(windowName) window.setWindowTitle(windowName) window.setMinimumSize(450,650) window.setMaximumSize(600,400) mainWidget = QtWidgets.QWidget() window.setCentralWidget(mainWidget) verticalLayout = QtWidgets.QVBoxLayout(mainWidget) self.textureIconChartLayout = QtWidgets.QVBoxLayout() textureIconsLayout = QtWidgets.QHBoxLayout() self.textureIconChartLayout.addLayout(textureIconsLayout) verticalLayout.addLayout(self.textureIconChartLayout) self.textureIconChart = QtWidgets.QListWidget() self.textureIconChart.setViewMode(QtWidgets.QListWidget.IconMode) self.textureIconChart.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.textureIconChart.setDragEnabled(0) self.textureIconChart.setMaximumWidth(290) self.populateListWidget() textureIconsLayout.addWidget(self.textureIconChart) textureIconsLayout.setSpacing(0) textureIconsLayout.setContentsMargins(0,0,0,0) tr = texture_replacer() tr.texture_linker_UI()
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: pyside2
has comment: http://stackoverflow.com/comment/88466341
has comment: http://stackoverflow.com/comment/88466927

http://stackoverflow.com/comment/88474480
has text: Well.. it isn't in a function. it is close to it -- I don't really know what your linked list looks like. It is a guess
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50733196

http://stackoverflow.com/q/50702625
has comment: http://stackoverflow.com/comment/88414738
has body: I want to extract the number of (outer) items inside the parentheses associated with a. For example for the following examples: a(b(c d) f) a has two items b(c d) and f therefore output is 2. e(a(h f)) a has two items h and f therefore output is 2. b(c a(d(f) h(i j) l(2 k z))) a has three items d(f) and h(i j) and l(2 k z) therefore output is 3. Not sure how solve this but first I try to convert the strings to where they start with a( m=re.search("a\((.*)\)\)", string) print m.group() What's the best approach to solve this?
duplicate of: http://stackoverflow.com/q/4284991
accepted answer: http://stackoverflow.com/a/50702847
has comment: http://stackoverflow.com/comment/88414562
answer count: 1
has comment: http://stackoverflow.com/comment/88414710
tagged with: string
favorite count: 0
tagged with: python
has title: extracts the number of (outer) items inside the parentheses
tagged with: regex
linked to: http://stackoverflow.com/q/4284991
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50702847
upvote count: 2
has comment: http://stackoverflow.com/comment/88414716
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88415258
tagged with: algorithm

pandas
tags question: http://stackoverflow.com/q/50819579
tags question: http://stackoverflow.com/q/50850325
tags question: http://stackoverflow.com/q/50711786
tags question: http://stackoverflow.com/q/50778877
tags question: http://stackoverflow.com/q/50794631
tags question: http://stackoverflow.com/q/50704041
tags question: http://stackoverflow.com/q/50845835
tags question: http://stackoverflow.com/q/50815015
tags question: http://stackoverflow.com/q/50773388
tags question: http://stackoverflow.com/q/50707913
tags question: http://stackoverflow.com/q/50789880
tags question: http://stackoverflow.com/q/50701460
tags question: http://stackoverflow.com/q/50796039
tags question: http://stackoverflow.com/q/50778334
tags question: http://stackoverflow.com/q/50733987
tags question: http://stackoverflow.com/q/50844505
tags question: http://stackoverflow.com/q/50770021
tags question: http://stackoverflow.com/q/50750918
tags question: http://stackoverflow.com/q/50829206
tags question: http://stackoverflow.com/q/50837180
tags question: http://stackoverflow.com/q/50842419
tags question: http://stackoverflow.com/q/50840416
tags question: http://stackoverflow.com/q/50778103
tags question: http://stackoverflow.com/q/50782934
tags question: http://stackoverflow.com/q/50741330
tags question: http://stackoverflow.com/q/50702503
tags question: http://stackoverflow.com/q/50740250
tags question: http://stackoverflow.com/q/50740148
tags question: http://stackoverflow.com/q/50795928
tags question: http://stackoverflow.com/q/50730408
tags question: http://stackoverflow.com/q/50854155
tags question: http://stackoverflow.com/q/50725652
tags question: http://stackoverflow.com/q/50788585
tags question: http://stackoverflow.com/q/50724489
tags question: http://stackoverflow.com/q/50829995
tags question: http://stackoverflow.com/q/50851137
tags question: http://stackoverflow.com/q/50759970
tags question: http://stackoverflow.com/q/50731253
tags question: http://stackoverflow.com/q/50729885
tags question: http://stackoverflow.com/q/50797827
tags question: http://stackoverflow.com/q/50830683
tags question: http://stackoverflow.com/q/50727342
tags question: http://stackoverflow.com/q/50702150
tags question: http://stackoverflow.com/q/50848454
tags question: http://stackoverflow.com/q/50751520
tags question: http://stackoverflow.com/q/50764194
tags question: http://stackoverflow.com/q/50798855
tags question: http://stackoverflow.com/q/50732157
tags question: http://stackoverflow.com/q/50750030
tags question: http://stackoverflow.com/q/50730831
tags question: http://stackoverflow.com/q/50746653
tags question: http://stackoverflow.com/q/50847436
tags question: http://stackoverflow.com/q/50767799
tags question: http://stackoverflow.com/q/50761987
tags question: http://stackoverflow.com/q/50725788
tags question: http://stackoverflow.com/q/50775923
tags question: http://stackoverflow.com/q/50782766
tags question: http://stackoverflow.com/q/50820659
tags question: http://stackoverflow.com/q/50757929
tags question: http://stackoverflow.com/q/50751177
tags question: http://stackoverflow.com/q/50824644
tags question: http://stackoverflow.com/q/50767648
tags question: http://stackoverflow.com/q/50735669
tags question: http://stackoverflow.com/q/50832601
tags question: http://stackoverflow.com/q/50717904
tags question: http://stackoverflow.com/q/50798811
tags question: http://stackoverflow.com/q/50748971
tags question: http://stackoverflow.com/q/50751259
tags question: http://stackoverflow.com/q/50777758
tags question: http://stackoverflow.com/q/50797503
tags question: http://stackoverflow.com/q/50831217
tags question: http://stackoverflow.com/q/50852303
tags question: http://stackoverflow.com/q/50756169
tags question: http://stackoverflow.com/q/50798853
tags question: http://stackoverflow.com/q/50702709
tags question: http://stackoverflow.com/q/50811070
tags question: http://stackoverflow.com/q/50732915
tags question: http://stackoverflow.com/q/50704571
tags question: http://stackoverflow.com/q/50841644
tags question: http://stackoverflow.com/q/50777214

http://stackoverflow.com/q/50708852
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50709669
has answer: http://stackoverflow.com/a/50708916
has title: Design my own Error in Python
has answer: http://stackoverflow.com/a/50709669
has comment: http://stackoverflow.com/comment/88426821
downvote count: 1
type: Question
upvote count: 0
score: -1
answer count: 2
accepted answer: http://stackoverflow.com/a/50708916
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I want to design an error in python. Here is my code class TwitchException(Exception): def __init__(self, value): self.value = value def __str__(self): return "The input ", self.value ," is not a valid reaction." valid_reactions = ["Poggers", "4Head","SMOrc", "TheIlluminati"] def react(reaction): """ &gt;&gt;&gt; react("Poggers") Poggers &gt;&gt;&gt; react("Hello") Traceback (most recent call last): ... TwitchException: The input Hello is not a valid reaction. &gt;&gt;&gt; react("SMOrc") SMOrc """ try: if reaction in valid_reactions: print(reaction) except TwitchException: raise TwitchException(reaction) Help!!! I am not sure how to fulfill the second doctest.

pyqt
type: Tag
tags question: http://stackoverflow.com/q/50804943
tags question: http://stackoverflow.com/q/50738264
tags question: http://stackoverflow.com/q/50833627
tags question: http://stackoverflow.com/q/50720719
tags question: http://stackoverflow.com/q/50712783
tags question: http://stackoverflow.com/q/50724271
tags question: http://stackoverflow.com/q/50820042
tags question: http://stackoverflow.com/q/50759423
tags question: http://stackoverflow.com/q/50775036
tags question: http://stackoverflow.com/q/50755702
tags question: http://stackoverflow.com/q/50744783
tags question: http://stackoverflow.com/q/50763897
tags question: http://stackoverflow.com/q/50737170
tags question: http://stackoverflow.com/q/50789605
tags question: http://stackoverflow.com/q/50833107
tags question: http://stackoverflow.com/q/50783666
tags question: http://stackoverflow.com/q/50747402
tags question: http://stackoverflow.com/q/50725166
tags question: http://stackoverflow.com/q/50711763
tags question: http://stackoverflow.com/q/50769024
tags question: http://stackoverflow.com/q/50726510
tags question: http://stackoverflow.com/q/50849549
tags question: http://stackoverflow.com/q/50786186
tags question: http://stackoverflow.com/q/50838371
tags question: http://stackoverflow.com/q/50768366
tags question: http://stackoverflow.com/q/50851966
tags question: http://stackoverflow.com/q/50735744
tags question: http://stackoverflow.com/q/50769689
tags question: http://stackoverflow.com/q/50704447
tags question: http://stackoverflow.com/q/50795993
tags question: http://stackoverflow.com/q/50745153
tags question: http://stackoverflow.com/q/50846037
tags question: http://stackoverflow.com/q/50851350
tags question: http://stackoverflow.com/q/50749343
tags question: http://stackoverflow.com/q/50804987
tags question: http://stackoverflow.com/q/50724389
tags question: http://stackoverflow.com/q/50709638
tags question: http://stackoverflow.com/q/50821529
tags question: http://stackoverflow.com/q/50715822
tags question: http://stackoverflow.com/q/50767240
tags question: http://stackoverflow.com/q/50718438
tags question: http://stackoverflow.com/q/50753808
tags question: http://stackoverflow.com/q/50720945
tags question: http://stackoverflow.com/q/50756044
tag name: pyqt
tags question: http://stackoverflow.com/q/50716794
tags question: http://stackoverflow.com/q/50782747
tags question: http://stackoverflow.com/q/50705536
tags question: http://stackoverflow.com/q/50794761

http://stackoverflow.com/comment/88557887
score: 0
type: Comment
type: QuestionComment
has text: yes I can share them with you. Where can I provide the data?
comment on: http://stackoverflow.com/q/50775312

http://stackoverflow.com/comment/88500776
type: QuestionComment
has text: I tried doing "lxterminal -x" but it didn't work
comment on: http://stackoverflow.com/q/50722690
score: 0
type: Comment

http://stackoverflow.com/q/50840526
has body: I am trying to read this excel sheet: https://1drv.ms/x/s!AkiO0urKs8OwgSDHRD2IoE4LPBtt with pandas(python) #!/usr/bin/python # -*- coding: latin-1 -*- import os, sys import urllib2 from collections import Counter import json from pprint import pprint import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile import numpy as np import pandas as pd import matplotlib.pyplot as plt file_name = "test.xlsx" df = pd.read_excel(file_name, sheetname='Resultados 1 fase') print df I am trying to get the match results by index, for example: 1 - 1 x 0 2 - 2 x 2 3 - 0 x 2 4 - 4 x 0 ... But when I see the result of the code above many column headers are NaN and I don't know how to extract the information I need from. Can anyone help me with this? Thanks
tagged with: python
tagged with: excel
type: AnsweredQuestion
downvote count: 0
score: 1
has title: reading excel files in pandas - columns with NaN header
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/50840873
answer count: 1
accepted answer: http://stackoverflow.com/a/50840873
favorite count: 0

http://stackoverflow.com/comment/88686874
score: 0
comment on: http://stackoverflow.com/a/50833844
type: AnswerComment
type: Comment
has text: Sorry I have no experience with the pyqtgraph module. But I got the values (x, y) from the module `mouseMoved (evt)`. Some errors are commented out. I think that further you will succeed. See the updated code.

http://stackoverflow.com/comment/88602683
type: AnswerComment
has text: I did this : `sound = AudioSegment.from_mp3('/home/nikhil/Documents/test.mp3')` . But still getting the error.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50798358

http://stackoverflow.com/comment/88648504
score: 0
type: QuestionComment
type: Comment
has text: Please provide your Dockerfile. I'm guessing that you used a template Dockerfile and didn't create the necessary files.
comment on: http://stackoverflow.com/q/50821693

http://stackoverflow.com/q/50719840
tagged with: django
accepted answer: http://stackoverflow.com/a/50719917
type: Question
possible better answer: http://stackoverflow.com/a/50721035
has title: How to get a file from a network windows directory and move to my Python Django project directory?
has answer: http://stackoverflow.com/a/50721035
answer count: 2
downvote count: 0
favorite count: 0
tagged with: windows
tagged with: python
tagged with: macos
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50719917
upvote count: 2
has body: I'm programming in a MacOS and using Python + Django. I must to get some files in our private network (Windows network) and move them to our server. There, Python/Django will read these files and save the data in a database. How can I do that? What I have tried source_path = "smb://server-name/GRUPOS/TECNOLOGIA_INFORMACAO/Dashboard Diretoria/" dest_path = "./static/reports/". # This is my static folder where I want to move the file file_name = "general_reports.csv" shutil.copyfile(source_path + file_name, dest_path + file_name) It gives the follow error: [Errno 2] No such file or directory: 'smb://server-name/GRUPOS/TECNOLOGIA_INFORMACAO/Dashboard Diretoria/general_reports.csv' This path (source_path) I just copied and past from the Finder, so... I think that it's correct. I have already searched at StackOverflow and I have tried other methods like put "r" before the path... Nothing.... Technologies used Python 3.6; Django 3.0.5; Mac OSX; Windows Network. Thank you for your help and patience.

http://stackoverflow.com/comment/88475693
has text: I am unable to find any such working samples in https://github.com/pdfminer/pdfminer.six . Can you please tell me where it is?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50698913

http://stackoverflow.com/a/50785900
has comment: http://stackoverflow.com/comment/88579186
answers question: http://stackoverflow.com/q/50785851
upvote count: 1
score: 1
has body: Maybe this way: URL_list = [i for i in data.split('"') if 'http' in i] It doesn't use regex, but in this code I don't see a need for regex.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50785851

http://stackoverflow.com/a/50851654
upvote count: 2
has body: You can write as below:- $form_data = $("#idofform").serialize(); And then in ajax data : $form_data+'&amp;key=value',
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50790223
downvote count: 0

http://stackoverflow.com/q/50848163
has comment: http://stackoverflow.com/comment/88725432
score: 9
has comment: http://stackoverflow.com/comment/88725308
answer count: 3
has answer: http://stackoverflow.com/a/78074528
has body: How can I obtain the AUC value having fpr and tpr? Fpr and tpr are just 2 floats obtained from these formulas: my_fpr = fp / (fp + tn) my_tpr = tp / (tp + fn) my_roc_auc = auc(my_fpr, my_tpr) I know this can't pe possible, because fpr and tpr are just some floats and they need to be arrays, but I can't figure it out how to do that so. I also know that I can compute AUC this way: y_predict_proba = model.predict_proba(X_test) probabilities = np.array(y_predict_proba)[:, 1] fpr, tpr, _ = roc_curve(y_test, probabilities) roc_auc = auc(fpr, tpr) but I want to avoid using predict_proba for some reasons. So my question is: how can I obtain AUC having fp, tp, fn, tn, fpr, tpr? In other words, is it possible to obtain AUC without roc_curve?
has comment: http://stackoverflow.com/comment/88703283
downvote count: 0
favorite count: 0
tagged with: roc
tagged with: false-positive
has answer: http://stackoverflow.com/a/50892759
tagged with: python
has title: Manually calculate AUC
possible better answer: http://stackoverflow.com/a/56335842
tagged with: predict
has answer: http://stackoverflow.com/a/56335842
type: Question
type: AnsweredQuestion
tagged with: auc
upvote count: 9
accepted answer: http://stackoverflow.com/a/50892759

http://stackoverflow.com/comment/88668761
type: Comment
has text: Dont user `item in dict.keys()` for lookup, it's O(N), use `item in dict` which is O(1) (and highly optimised).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50832310

http://stackoverflow.com/comment/88465629
type: QuestionComment
has text: arg parser takes command line arguments, so when you invoke your module, you need to pass values in order python new.py *radius int* *height int*
comment on: http://stackoverflow.com/q/50728714
score: 0
type: Comment

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

http://stackoverflow.com/a/50711977
downvote count: 0
has comment: http://stackoverflow.com/comment/88437961
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88582104
answers question: http://stackoverflow.com/q/50709813
upvote count: 1
has comment: http://stackoverflow.com/comment/88581831
accepted answer of: http://stackoverflow.com/q/50709813
has body: If you prefer to not wrap the text in anything, you can choose to insert a line break tag because by default it takes p tag for wrapping. config.enterMode = CKEDITOR.ENTER_P; You need to add below line in config.js file for CKEditor: CKEDITOR.editorConfig = function (config) { config.enterMode = CKEDITOR.ENTER_BR; ... }; or else if you want to wrap in div tag then, config.enterMode = CKEDITOR.ENTER_DIV;
has comment: http://stackoverflow.com/comment/88436678
type: AcceptedAnswer

http://stackoverflow.com/q/50819033
type: Question
tagged with: qlabel
has answer: http://stackoverflow.com/a/50821539
score: 4
downvote count: 1
answer count: 1
favorite count: 0
tagged with: qpixmap
upvote count: 5
has body: I want to display image with round shape in PyQt5/PySide2 application. Below is the code i tried. self.statusWidget = QLabel() img = QImage(":/image.jpg").scaled(49, 49, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self.statusWidget.setPixmap(QPixmap.fromImage(img)) self.statusWidget.setStyleSheet("border-radius:20px") I got below output. And I want Qlabel like below.
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50821539
tagged with: pyside2
tagged with: pyqt5
has title: QLabel with image in round shape

http://stackoverflow.com/comment/88880112
has text: Well, since I'm a total newbie in VS Code and python, I was suggesting that it highly possible that I made a mistake, and I would like to know how to check that everything is well configured.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50845016
type: Comment

http://stackoverflow.com/a/50719027
downvote count: 0
has body: You can try python -m ipykernel install --user in cmd. Then relaunch jupyter.
score: 2
accepted answer of: http://stackoverflow.com/q/50717492
upvote count: 2
answers question: http://stackoverflow.com/q/50717492
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/50752761
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50729248
has body: Pandas is designed to let you apply operations to entire columns rather than use a for-loop like you're describing. One method you might be looking for is str.split() with expand=True: &gt;&gt;&gt; df.name1.str.split('-', expand=True) 0 1 0 Braund None 1 Cummings Johnson 2 Heikkinen Smith Notice that names without a hyphen will be given None for the second element. You could also filter down to only hyphenated last names first: &gt;&gt;&gt; df.loc[df.name1.str.contains('-'), 'name1'].str.split('-', expand=True) 0 1 1 Cummings Johnson 2 Heikkinen Smith To rename the columns: df.loc[df.name1.str.contains('-'), 'name1']\ .str.split('-', expand=True)\ .rename(columns={0: 'name2', 1: 'name3'}) Lastly, if you really need to mimic exactly your example, you could use ffill(): &gt;&gt;&gt; df.name1.str.split('-', expand=True).ffill(axis=1) 0 1 0 Braund Braund 1 Cummings Johnson 2 Heikkinen Smith

http://stackoverflow.com/q/50765465
has answer: http://stackoverflow.com/a/50765958
has body: pathlib import Path def saveJSONget(site, code): r = requests.get(site) json_str = r.text if r.status_code != code: Path("PATH").write_text(r.text+"\n") I'm trying to save json to file .txt. Do I need to save information about Request Headers, Response Headers and in POST method - Request payload? Which function used to save this information?
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50765958
tagged with: python
has title: Save data to file .txt - Request Headers , Response Headers and in POST method - Request payload
type: AnsweredQuestion
tagged with: python-requests
type: Question

http://stackoverflow.com/a/51572844
has body: This is indeed possible but took a bit of experimenting. I had to open the Kudu console from a VM which is inside the same VNet as the App Service Environment. From there on, it's a cake walk. You can also configure Web Jobs from the VM which is otherwise not possible from the portal.
answers question: http://stackoverflow.com/q/50816456
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50816456

http://stackoverflow.com/q/50757101
answer count: 1
tagged with: hyperlink
favorite count: 0
has body: My issue is, how can I translate label, where is link, inside the label. I am trying but I get only translate for msgid not for msgid. site.html {% blocktrans %}Lorem Lorem ipsum lorem ipsum test test {% endblocktrans %} django.po file #: templates/pages/templates/contact.html:72 msgid "" "Text Text " "TextTextTextTextText" msgstr "" "Text Text Text Text " "TextTextText TextText"
type: UnansweredQuestion
has title: How can I put link into translation label in django
tagged with: translation
tagged with: django
tagged with: python
tagged with: href
has answer: http://stackoverflow.com/a/50757703
upvote count: 5
type: Question
score: 5
downvote count: 0

http://stackoverflow.com/q/50738140
has body: class Vector: def __init__(self, vector): self.vector = vector def __eq__(self, other): return self.vector==other.vector #above must not be changed. Below is my work. #def __str__(self): # return self.vector ---Not sure how to use __str__ on a list--- def __add__(self,other): vector = Vector(self.vector+other.vector) return vector I know this is a wrong method but I have no clue how to work with a list. I just want to know how to work with a list in a class. Also, the following statement should work: x=Vector([2,4,6]) #This is a list right? This is where I get stuck. y=Vector([7,8,9]) print(x+y==Vector([9.12.15])) I don't want the answer to all the operations just the add is enough. I just don't understand how to output lists in classes without the statement "a.vector" which clearly was not used the commands given above when creating objects for classes. Also please specify if any clarification is required. Any help is appreciated! I am new to programming and just learnt classes in Python. Thanks a lot on advance
has title: I have to perform addition on a 3d vector. The variable vector is a list
type: Question
tagged with: vector
has answer: http://stackoverflow.com/a/50738208
tagged with: function
tagged with: class
score: 0
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88484049
accepted answer: http://stackoverflow.com/a/50738208
has comment: http://stackoverflow.com/comment/88483911
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88601224
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50797616
has text: "content"? What is that? How to do this with a concrete string (say "aaa")?

http://stackoverflow.com/comment/88421574
comment on: http://stackoverflow.com/q/50706092
has text: @user2357112 because when I used sympy I got np.array([np.exp(x)*x]) Traceback (most recent call last): File "<ipython-input-99-1572dbe878a4>", line 1, in <module> np.array([np.exp(x)*x]) AttributeError: 'Symbol' object has no attribute 'exp'
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50742361
answer count: 2
has comment: http://stackoverflow.com/comment/88492550
has body: I have a problem that following code causes a encoding error: This problem happens when pass a japanese including string to strftime. This is caused on python repl on cmd.exe. Is this problem a bug of python? import datetime d = datetime.datetime.now() d.strftime("%y年") Error message: UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence Python 3.6.5 Windows10 1803
has answer: http://stackoverflow.com/a/50742462
upvote count: 1
tagged with: windows
has answer: http://stackoverflow.com/a/50742628
favorite count: 0
tagged with: python-3.x
has title: python datetime.strftime does not support japanese?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88492324
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/q/50825816
has body: I am trying to parallelize a function that takes in an object in Python: In using Pathos, the map function automatically dills the object before distributing it among the processors. However, it takes ~1 min to dill the object each time, and I need run this function up to 100 times. All in all, it is taking nearly 2 hours to just serialize the object before even running it. Is there a way to just serialize it once, and use it multiple times? Thanks very much
type: UnansweredQuestion
type: Question
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/50825883
has comment: http://stackoverflow.com/comment/88656525
answer count: 1
has comment: http://stackoverflow.com/comment/88656541
score: 0
tagged with: python
tagged with: pathos
has comment: http://stackoverflow.com/comment/88656789
has title: Serializing objects for multiprocessing is slow -- is there a way to serialize just once?

http://stackoverflow.com/q/50747606
linked to: http://stackoverflow.com/q/4117530
score: 0
tagged with: argv
duplicate of: http://stackoverflow.com/q/4117530
has body: I am trying to run this script that grabs rss feeds on the environment "Thonny" but I just keep receiving this error of "IndexError: List index out of range" Traceback (most recent call last): File "C:\Users\uri\rssfeedfour.py", line 11, in &lt;module&gt; url = sys.argv[1] IndexError: list index out of range How do I resolve this to keep from getting this error over and over again. Im not sure how to solve this as I am a beginner. Do I need to define it, if so how? or could I take it out and go a different direction? Here is the code. import feedparser import time from subprocess import check_output import sys #feed_name = 'TRIBUNE' #url = 'http://chicagotribune.feedsportal.com/c/34253/f/622872/index.rss' feed_name = sys.argv[1] url = sys.argv[2] db = 'http://feeds.feedburner.com/TheHackersNews' limit = 12 * 3600 * 1000 current_time_millis = lambda: int(round(time.time() * 1000)) current_timestamp = current_time_millis() def post_is_in_db(title): with open(db, 'r') as database: for line in database: if title in line: return True return False def post_is_in_db_with_old_timestamp(title): with open(db, 'r') as database: for line in database: if title in line: ts_as_string = line.split('|', 1)[1] ts = long(ts_as_string) if current_timestamp - ts &gt; limit: return True return False # # get the feed data from the url # feed = feedparser.parse(url) # # figure out which posts to print # posts_to_print = [] posts_to_skip = [] for post in feed.entries: # if post is already in the database, skip it # TODO check the time title = post.title if post_is_in_db_with_old_timestamp(title): posts_to_skip.append(title) else: posts_to_print.append(title) # # add all the posts we're going to print to the database with the current timestamp # (but only if they're not already in there) # f = open(db, 'a') for title in posts_to_print: if not post_is_in_db(title): f.write(title + "|" + str(current_timestamp) + "\n") f.close # # output all of the new posts # count = 1 blockcount = 1 for title…
has comment: http://stackoverflow.com/comment/88505934
favorite count: 0
linked to: http://stackoverflow.com/q/15121717
tagged with: rss
type: UnansweredQuestion
tagged with: sys
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88504121
has title: sys.argv list index out of range error
has comment: http://stackoverflow.com/comment/88504095
downvote count: 1
type: Question
tagged with: feedparser
has answer: http://stackoverflow.com/a/50749235
answer count: 1
has comment: http://stackoverflow.com/comment/88502839

http://stackoverflow.com/comment/88445791
type: Comment
has text: Edit: It was not the final code, sorry, the actual code has *leng =* instead of *return leng +*,
score: 0
comment on: http://stackoverflow.com/q/50718514
type: QuestionComment

http://stackoverflow.com/q/50775100
possible better answer: http://stackoverflow.com/a/50775231
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/50775817
has body: Writing a script to check if a product is loaded onto a website. import requests import time from bs4 import BeautifulSoup r = requests.get('https://www.off---white.com/en/GB/section/new-arrivals.js') soup = BeautifulSoup(r.text, 'html.parser') text = '3.0' while text not in soup: print('not found') r = requests.get('https://www.off---white.com/en/GB/section/new-arrivals.js') soup = BeautifulSoup(r.text, 'html.parser') time.sleep(5) When I print soup I can see that '3.0' is in there. But when I run the script it does not recognize that '3.0' is there. What am I doing wrong?
has title: while text not in soup: - not picking up that text is in soup even though it exists
answer count: 2
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50775231
has answer: http://stackoverflow.com/a/50775817
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50709783
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50705731
accepted answer of: http://stackoverflow.com/q/50705731
has body: I tried something and it worked well. import dns.resolver, smtplib MyEmail = "X@hotmail.com" MyPassword = "XXX" EmailToValidate = "X@Y.com" record = dns.resolver.query(str.split(EmailToValidate, "@")[1], "MX") mx = str(record[0].exchange) server = smtplib.SMTP("smtp.live.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(MyEmail, MyPassword) server.helo("live.com") server.connect(mx) server.mail(MyEmail) code, msg = server.rcpt(EmailToValidate) print("Code: ", str(code), " message: ", msg) the (code, message) pair will be (250, OK) if the email exists, and (550, Address Rejected) if the email does not exists. I wrote this on hurry, so there might be some unnecessary steps.
type: AcceptedAnswer

http://stackoverflow.com/comment/88495910
has text: If i sum up my arguments in a list and replace with shell=false ,i get the following error. ./createvmattend.1.py usage: virt-install --name NAME --memory MB STORAGE INSTALL [options] virt-install: error: unrecognized arguments: --name bob --vcpus 1 --memory 2048 --cdrom /var/lib/libvirt/images/Centos.iso --disk size 80 --os-variant centos7.0 --os-type linux --network bridge virbr0
type: Comment
comment on: http://stackoverflow.com/q/50708912
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88530940
has text: Edit: This works if I convert the blank strings which were in '' form into None which does solve my problem. Thanks. Although I am curious if there is a solution to if there are '' instead of None
type: AnswerComment
comment on: http://stackoverflow.com/a/50761482
score: 0
type: Comment

http://stackoverflow.com/a/50799053
type: AcceptedAnswer
downvote count: 0
has body: '-'.join(lst).split('-') seems quite a bit faster: &gt;&gt;&gt; timeit("'-'.join(lst).split('-')", globals=globals(), number=10) 1.0838123590219766 &gt;&gt;&gt; timeit("[x for xs in lst for x in xs.split('-')]", globals=globals(), number=10) 3.1370303670410067
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50798432
answers question: http://stackoverflow.com/q/50798432

http://stackoverflow.com/comment/88499144
comment on: http://stackoverflow.com/a/50745359
type: Comment
has text: @DataWiz, Sure, but note that `pd.Series.map` can be used with *another series* directly. You probably don't need a dictionary at all.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50708959
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/50709029
has answer: http://stackoverflow.com/a/50709012
has answer: http://stackoverflow.com/a/50709068
has body: I'm having a csv file that I did manipulations on it, I merged two different files using pandas.merge. But now, I have some columns that are called for example column_x and column_y. So I want to merge these two columns to obtain one column. By knowing that the two columns can be represented like this: Column_x Column_y 2 2.1 3 4.322 4 5 And then obtain either one of these two results: Column 2 3 4.322 5 Or: Column 2.1 3 4 5 Either of these two results will satisfy me
answer count: 4
possible better answer: http://stackoverflow.com/a/50709033
has answer: http://stackoverflow.com/a/50709033
accepted answer: http://stackoverflow.com/a/50709029
has title: How to merge two columns from a dataframe
tagged with: pandas
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/103499586
type: Comment
comment on: http://stackoverflow.com/a/58411594
score: 1
has text: Something similar happened to me; not adding, but slicing.
type: AnswerComment

http://stackoverflow.com/comment/88619739
has text: @bananagurlz `x0` and `xn` are basically the same thing: first one is initial approximation to the solution while `xn` is the n-th approximation to the solution of the same system of equations. What I am saying is that you are solving the equation `function=A*x == 0`. I can tell you right away that if `det(A)!=0` the solution is `x=[0,0]`. You do not need Newton method at all - the solution is bvious.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50806050
type: Comment

http://stackoverflow.com/comment/88502622
comment on: http://stackoverflow.com/q/50747481
score: 0
has text: Shouldn't `xadrez` only score 18 points?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88537690
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/50761146
has text: `pytest --html=report.html`?

http://stackoverflow.com/a/51987281
has comment: http://stackoverflow.com/comment/91065428
accepted answer of: http://stackoverflow.com/q/50764572
has comment: http://stackoverflow.com/comment/91065298
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91055710
type: Answer
score: 34
has body: You may use TensorFlow Lite Python interpreter to test your tflite model. It allows you to feed input data in python shell and read the output directly like you are just using a normal tensorflow model. I have answered this question here. And you can read this TensorFlow lite official guide for detailed information. You can also use Netron to visualize your model. It allows you to load your .tflite file directly and inspect your model architecture and model weights.
upvote count: 34
answers question: http://stackoverflow.com/q/50764572

http://stackoverflow.com/comment/88479474
type: Comment
type: QuestionComment
has text: I found it and sorry but it is obscure that I would never have know it was due to a file called numbers.py in my folder where I put my python files I renamed it and reinstalled matplotlib and it works now. I found it in here by doing a google search of the error and it found a similar issue on stackoverflow schoolboy error thanks for all the help.
score: 0
comment on: http://stackoverflow.com/q/50717721

http://stackoverflow.com/q/50808120
has title: AttributeError: 'NoneType' object has no attribute writing guessing game
linked to: http://stackoverflow.com/q/8949252
favorite count: 0
has comment: http://stackoverflow.com/comment/88621915
has body: UPDATED CODE , got it working but im repeating lines above and below my while loop. any friendly advice to solve this error, just looking for some guidance . import pyperclip import random x=random.randint(1,10) pyperclip.copy(x) print(str(int(pyperclip.paste()))) def guessingGame(answer): if(casting==x): print("correct") return True elif(casting&lt;x): print("higher") return False else: print("lower") return False userAnswer=input() casting=int(userAnswer) guessingGame(casting) while(guessingGame!=True): userAnswer=input() casting=int(userAnswer) guessingGame(casting) I am trying to create a simple guessing game, and am running into an AttributeError. Here is an input that causes the error: lets play a guessing game, can you get our number? type in your guess 2 Traceback (most recent call last): File "E:/guessing.py", line 25, in &lt;module&gt; while(guess(userAnswer)==False): File "E:/guessing.py", line 9, in guess print(str(int(copying.paste()))+" higher") AttributeError: 'NoneType' object has no attribute 'paste' Here is my code: import pyperclip import random x=random.randint(1,10) def guess(value): copying=pyperclip.copy(int(value)) if(value&lt;x): print(str(int(copying.paste()))+" higher") return False elif(value&gt;x): copying=pyperclip.copy(value) print(str(int(copying.paste()))+" lower") return False else: printcopying=pyperclip.copy(value) print(str(int(copying.paste()))+" correct guess our number was "+ str(int(value))) return True print("lets play a guessing game, can you get our number? type in your guess") userAnswer=int(input()) while(guess(userAnswer)==False): print("lets play a guessing game, can you get our number? type in your guess") userAnswer guess(userAnswer)
duplicate of: http://stackoverflow.com/q/8949252
has comment: http://stackoverflow.com/comment/88622239
tagged with: python
has comment: http://stackoverflow.com/comment/88621973
has comment: http://stackoverflow.com/comment/88621926
answer count: 0
has comment: http://stackoverflow.com/comment/88622023
has comment: http://stackoverflow.com/comment/88621947
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88622232
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88622039
has comment: http://stackoverflow.com/comment/88621924
score: 0

http://stackoverflow.com/comment/88503473
type: QuestionComment
comment on: http://stackoverflow.com/q/50747043
has text: Does the HTML really contain the `"` characters around the text you want, or is that just how it's being displayed in the browser console? Use `View Source` to see the actual HTML.
score: 0
type: Comment

http://stackoverflow.com/q/50701021
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
has body: After following these instructions I ended up with a working script that generates a pdf as I desire. Unfortunately, the text is only visible upon clicking the filled fields! (this only happens when using adobe reader, not when viewing the page through web browsers) Seeing as users of the module aren't experiencing this issue I'm fairly certain it has something to do with the example script. If I reassign the black text color in the generated pdf the text shows up as I want. So I'm assuming the issue has something to do with the textColor of the filled fields. Any ideas how to solve this? (Can I assign field text color through pdfrw as a workaround?)
type: Question
tagged with: python
tagged with: pdfrw
answer count: 0
has title: TextColor set to invisible in python generated pdf after filling fields from a pdf template with pdfrw
upvote count: 1

http://stackoverflow.com/comment/88535333
score: 0
type: AnswerComment
has text: Thanks. I tried this and get another error, which I have updated the question with. When I do that, i get the error `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position 0: ordinal not in range(128)`
comment on: http://stackoverflow.com/a/50763709
type: Comment

http://stackoverflow.com/comment/88579625
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50786018
type: AnswerComment
has text: Thank you. Your first suggestion using `replace` works. Sadly the encoding idea hasn't worked yet.

http://stackoverflow.com/comment/88697940
has text: Does the file contains spaces? Or new lines?
comment on: http://stackoverflow.com/q/50847245
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50762999
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50763142
score: 0
has comment: http://stackoverflow.com/comment/88533871
has comment: http://stackoverflow.com/comment/88533958
type: Question
has comment: http://stackoverflow.com/comment/88533795
has title: Dealing with one KeyError best practice
has answer: http://stackoverflow.com/a/50763142
answer count: 1
tagged with: keyerror
has comment: http://stackoverflow.com/comment/88533573
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88533746
has body: I have shortend the script and the start date of pendulum to reproduce this error more quickly. When the start date was 2016, 4, 2 I got through around 47,661 returned results before this KeyError occurred. To my knowledge I could use a try: except to pass up the KeyError. However I would not know any other KeyErrors that may come up after that point and that seems like I am just (for lack of a better word) "swallowing" my errors. What is best practice for this 1 in 50,000 (so far) occurrance. import csv import requests import datetime from pprint import pprint import pendulum gamepks = set() start = pendulum.datetime(2016, 5, 18) end = pendulum.datetime(2016, 10, 2) period = pendulum.period(start, end) for dt in period.range('days'): day = dt.format('DD') month = dt.format('MM') year = dt.format('YYYY') the_date = str(month) + "/" + str(day) + "/" + str(year) try: req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') # get_gameIds = req.json()['data']['games']['game'] for gameId in get_gameIds: gamepk = gameId['game_pk'] gamepks.add(gamepk) except(KeyError,TypeError): pass for new_pk in sorted(gamepks): req = requests.get('https://statsapi.mlb.com/api/v1.1/game/' + str(new_pk) + '/feed/live?language=en') # ' + str(gamepk) + ' 530302 at_bat_log = req.json()['liveData']['plays']['allPlays'] # Get Game date game_data = req.json()['gameData'] gamedate = game_data['datetime']['originalDate'] # GET PARK &amp; TEAMS teams = game_data['teams'] home_team = teams['home'] park = home_team['abbreviation'] away = teams['away']['abbreviation'] home = home_team['abbreviation'] batter_team = (away,home) pitcher_team = (home,away) for keys in at_bat_log: result = keys['result'] res_type = result['type'] res_event = result['event'] des = result['description'] rbi = result['rbi'] about = keys['about'] topbot = about['halfInning'] if topbot == "bottom": topbot = "B" if topbot == "top": topbo…

http://stackoverflow.com/q/50824252
answer count: 1
score: 0
tagged with: python
has body: My setup is nginx proxy + uwsgi server + flask python app. Without nginx I was getting in console traceback from program and than I was able to debug and fix whats wrong. With nginx I'm getting Segmentation Fault everytime with error, exception in code. Nothing usefull to debug. How to setup to get some real code traceback in console? api | !!! uWSGI process 19 got Segmentation Fault !!! api | *** backtrace of 19 *** api | /usr/local/bin/uwsgi(uwsgi_backtrace+0x30) [0x463ef0] api | /usr/local/bin/uwsgi(uwsgi_segfault+0x21) [0x464291] api | /lib/x86_64-linux-gnu/libc.so.6(+0x350e0) [0x7fd5fb52f0e0] api | /usr/local/lib/libpython3.6m.so.1.0(_PyUnicode_AsUTF8String+0x8) [0x7fd5fbbee878] api | /usr/local/bin/uwsgi(uwsgi_python_backtrace+0x158) [0x4794c8] api | /usr/local/bin/uwsgi(uwsgi_exceptions_catch+0x322) [0x446e92] api | /usr/local/bin/uwsgi(uwsgi_manage_exception+0x1fe) [0x4471fe] api | /usr/local/bin/uwsgi(python_call+0x2e) [0x479aae] api | /usr/local/bin/uwsgi(uwsgi_request_wsgi+0x104) [0x47bba4] api | /usr/local/bin/uwsgi(wsgi_req_recv+0xa2) [0x41e4c2] etc
type: AnsweredQuestion
tagged with: nginx
type: Question
has answer: http://stackoverflow.com/a/50840756
accepted answer: http://stackoverflow.com/a/50840756
has title: Segmentation fault instead of traceback python nginx wsgi

http://stackoverflow.com/q/50724495
answer count: 2
downvote count: 0
tagged with: neural-network
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Train and validate using tensorflow estimator
has answer: http://stackoverflow.com/a/52138053
has answer: http://stackoverflow.com/a/50756280
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question
has body: I have created a shallow NN using tf.estimator API. I would like to something similar to the hyperparameter search explained in here https://www.youtube.com/watch?time_continue=948&amp;v=eBbEDRsCmv4 at TensorFlow Dev Summit. I could not find any updated documentation about how can you do this. I have the following code (I will try to simplify as much as possible): # Define nn architecture def neural_net(features): input_layer = tf.cast(features['x'], tf.float32) hidden_layer = nn_layer(input_layer, 10, 'hidden_layer', act=tf.nn.relu) out_layer = nn_layer(hidden_layer, 2, 'out_layer', act=tf.nn.relu) return out_layer # Define model function def model_fn(features, labels, mode): # Build the neural network logits = neural_net(features&lt;9 with tf.name_scope('loss'): # Define loss and optimizer loss = tf.losses.sparse_softmax_cross_entropy(logits=logits, labels=labels) # Configure the Training if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001) train_op = optimizer.minimize( loss=loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) nn_classifier = tf.estimator.Estimator(model_fn=model_fn) train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": train_data}, y=train_labels, batch_size=100, num_epochs=None, shuffle=True) nn_classifier.train( input_fn=train_input_fn, steps=20000 ) Executing this code I can obtain the summary for the loss and observe it in Tensorboard. But imagine I want to obtain different curves. Let's say that I want to see how the loss evolves with the number of samples, so I would train two models with different sample size. Or two models with a different architecture... whatever. How can I get these two curves in Tensorboard?

http://stackoverflow.com/q/50796178
tagged with: printing
has comment: http://stackoverflow.com/comment/88598145
answer count: 1
accepted answer: http://stackoverflow.com/a/50796229
linked to: http://stackoverflow.com/q/8384737
tagged with: glob
has body: I'm trying to print out the filename of files in my folder but unfortunately when I print it out it comes out as - Image is ././Image_crop 4.jpg - how do I get rid of the ././ in front of the file? I'm new to python so please help! for filename in glob.glob(os.path.join(".", '*.jpg')): y = os.path.join(".", filename) print "Image is ", y
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88599464
tagged with: filenames
has title: Removing /. spaces when printing a filename
has answer: http://stackoverflow.com/a/50796229
type: Question
tagged with: os.path
has comment: http://stackoverflow.com/comment/88598177
score: 0

http://stackoverflow.com/a/50707802
downvote count: 0
has body: A variation of Patrick answer, using collections.Counter and just update since sub-dicts are already in the proper format: from collections import Counter x = { '1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4} } total = Counter() for d in x.values(): total.update(d) print(total) result: Counter({'b': 7, 'a': 3}) (update works differently for Counter, it doesn't overwrite the keys but adds to the current value, that's one of the subtle differences with defaultdict(int))
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50707632

http://stackoverflow.com/a/50724462
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50723662
has body: Yes i answered it myself, very easy my brain must of just been having a moment lol, for anyone else who is wondering how to do this, username.entry1.get() and password.entry2.get() you send that over in socket like you normally would a variable basically :) host = 'xxx.xxx.xx.x' port = 5000 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((host,port)) def dialog1(): username=entry1.get() password = entry2.get() if (username == 'admin' and password == 'secret'): box.showinfo('info','Correct Login') s.send(bytes(username,'utf8')) s.send(bytes(password, 'utf8')) else: box.showinfo('info','Invalid Login')

http://stackoverflow.com/a/50750479
accepted answer of: http://stackoverflow.com/q/50750332
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50750332
has body: You can create the dictionary and then add the appropriate entries to it. result = { 'prc': response.xpath(prc_path).extract_first() } if sqf_path: result['sqf'] = response.xpath(sqf_path).extract_first() if loc_path: result['loc'] = response.xpath(loc_path).extract_first() yield result You could also factor out the extract_path bit with a dict comprehension. result = { 'prc': prc_path, 'sqf': sqf_path, 'loc': loc_path } yield { key : response.xpath(value).extract_first() for (key, value) in result.items() if value } In earlier versions of Python, this would be: result = { 'prc': prc_path, 'sqf': sqf_path, 'loc': loc_path } yield dict((key, response.xpath(value).extract_first()) for (key, value) in result.items() if value)
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88508955
has comment: http://stackoverflow.com/comment/88509074
has comment: http://stackoverflow.com/comment/88508802

http://stackoverflow.com/a/50760599
upvote count: 2
has body: I have elaborated my comment. In the code provided by you, the contours are found using cv2.RETR_LIST which every possible contour in the image including those present within contours. I have used cv2.RETR_EXTERNAL which ignores those contours within other contours. image = cv2.imread(r'C:\Users\Desktop\g.png') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) retval, thresh_gray = cv2.threshold(gray, thresh=100, maxval=255, \ type=cv2.THRESH_BINARY_INV) cv2.imshow('thresh_gray.png', thresh_gray) image, contours, hierarchy = cv2.findContours(thresh_gray,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for i, c in enumerate(contours): if cv2.contourArea(c) &gt; 10000: x, y, w, h = cv2.boundingRect(c) roi = image[y :y + h, x : x + w ] cv2.imshow('Region_{}.jpg'.format(i), roi) cv2.waitKey(0) cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/88595367
score: 2
accepted answer of: http://stackoverflow.com/q/50759678
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88594428
answers question: http://stackoverflow.com/q/50759678
has comment: http://stackoverflow.com/comment/88555908
has comment: http://stackoverflow.com/comment/88531683
type: Answer
has comment: http://stackoverflow.com/comment/88531941
has comment: http://stackoverflow.com/comment/88561287
has comment: http://stackoverflow.com/comment/88594921

http://stackoverflow.com/q/50729226
possible better answer: http://stackoverflow.com/a/50729373
favorite count: 0
tagged with: pandas-groupby
type: Question
tagged with: pandas
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/50729299
accepted answer: http://stackoverflow.com/a/50729299
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/50729461
has title: How to use groupby in pandas dataframe to get mean for the following data?
has answer: http://stackoverflow.com/a/50729373
has body: I have my data as follows, the values in the dataframe are the quantities, while 'red','yellow', 'green' are the categories items place red green yellow a VA 1 7 9 b VA 3 0 19 c VA 5 1 0 d VA 11 3 4 e VA 2 2 1 a NJ 0 0 3 b NJ 3 0 9 c NJ 2 4 0 d NJ 0 5 6 e NJ 2 7 1 a MO 0 0 5 b MO 1 0 4 c MO 1 4 0 d MO 0 0 5 e MO 1 7 1 For each place-category combination, I would like to compute the mean of these quantities across all 5 items (a,b,c,d,e), category place Avg_quantity red VA .. green VA . .. yellow VA .. red NJ .. green NJ .. yellow NJ .. red MO .. green MO .. yellow MO ..
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/50854443
has answer: http://stackoverflow.com/a/50856351
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
accepted answer: http://stackoverflow.com/a/50856351
tagged with: tensorflow
type: Question
has body: I would like to intuitively understand the tf.nn.conv2d() function in tensorflow. Reason i post this since when the inputs are single dimensional array the convolution is tricky to interpret. Here is an example. Say i have a [1x5] input feature vector. d = [x for x in range(1,6)] print('Inputs:', d) Now reshape and flatten into the tensor. d = tf.reshape(d, shape=[-1,1,5,1]) print ("New shape : ",d.get_shape().as_list()) New shape : [1, 1, 5, 1] # convert inputs to float32 d = tf.cast(d,tf.float32) Applying filters with size [2x2] and then convolve with strides as 1. w1 = np.random.randint(5, size=(2,2)) w1 = tf.reshape(w1, shape=[2,2,1,1]) w1 = tf.cast(w1, tf.float32) # Apply conv layer d_conv = tf.nn.conv2d(d, w1, strides=[1,1,1,1], padding='SAME') # run session with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('\nFilter: ', w1.eval()) print('\nShape after convolution:',d_conv.eval().shape) print('\nConv output:',d_conv.eval()) Outputs. Inputs: [1, 2, 3, 4, 5] Filter: [[[[ 3.]] [[ 1.]]] [[[ 2.]] [[ 3.]]]] Shape after convolution: (1, 1, 5, 1) Conv output: [[[[ 5.] [ 9.] [ 13.] [ 17.] [ 15.]]]] Analysis The output is a result of convolving filter [[[ 3.]] [[ 1.]]]] with the input d with stride 1 and the last element after 5 is zero padded. Looks like the filter elements [[[ 2.]] [[ 3.]]]] where never applied. Would be nice if someone can explain what is going on. Best would be to increase the filter size w1 and figure out, ie, w1 = np.random.randint(10, size=(3,3)), w1 = tf.reshape(w1, shape=[3,3,1,1]) but i still get weird outputs. Thanks a lot.
score: 0
answer count: 1
has title: Computing outputs from conv2d in tensorflow

http://stackoverflow.com/comment/88536322
comment on: http://stackoverflow.com/a/50762951
has text: Am trying something new...do you have an idea on how to display `dupllcate` on a treeview....I've tried creating an array of strings(dup_data) and use a loop statement to go trough `duplicate` and add items(paths) to the array...then `self.model = QStandardItemModel() self.addItems(self.model, dup_data) self.treeView.setModel(self.model)`
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88574866
has text: The problem is that there may be multiple such keys. What do you want to do in that case? And anyway, it's going to be relatively slow, dictionaries are designed to do the opposite.
comment on: http://stackoverflow.com/q/50784201
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88608045
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50801041
type: QuestionComment
has text: What version of python do you use: 2.x or 3.x?

http://stackoverflow.com/comment/88565856
type: QuestionComment
has text: Done, Edited the question
comment on: http://stackoverflow.com/q/50779426
score: 0
type: Comment

http://stackoverflow.com/a/50730295
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50727450
downvote count: 0
has body: The other answer is surely suboptimal. What you need in order to customize the levels of the colorbar of a contour or contourf plot is to use its levels argument. E.g. to have 10 levels with 0.1 spacing between 0 and 1, you create a linspace np.linspace(0,1,11) and supply it to the levels argument. Note that the levels denote the bin edges, such that we take one edge more than bins. import numpy as np import matplotlib.pyplot as plt x = np.linspace(1,10, 100) z = np.random.uniform(0, 1, 100**2).reshape((100, 100)) levels = np.linspace(0,1,11) plt.contourf(x, x, z, levels=levels, cmap=plt.cm.coolwarm, vmin=0., vmax=1.) cbar = plt.colorbar() plt.show()

pyqt5
tags question: http://stackoverflow.com/q/50846037
tags question: http://stackoverflow.com/q/50851350
type: Tag
tags question: http://stackoverflow.com/q/50776545
tags question: http://stackoverflow.com/q/50825126
tags question: http://stackoverflow.com/q/50720719
tags question: http://stackoverflow.com/q/50705536
tags question: http://stackoverflow.com/q/50759423
tags question: http://stackoverflow.com/q/50775036
tags question: http://stackoverflow.com/q/50804943
tags question: http://stackoverflow.com/q/50789605
tags question: http://stackoverflow.com/q/50738264
tags question: http://stackoverflow.com/q/50712783
tags question: http://stackoverflow.com/q/50702903
tags question: http://stackoverflow.com/q/50724271
tags question: http://stackoverflow.com/q/50820042
tags question: http://stackoverflow.com/q/50709534
tags question: http://stackoverflow.com/q/50821563
tags question: http://stackoverflow.com/q/50819033
tags question: http://stackoverflow.com/q/50711763
tags question: http://stackoverflow.com/q/50699300
tags question: http://stackoverflow.com/q/50769024
tags question: http://stackoverflow.com/q/50849549
tags question: http://stackoverflow.com/q/50722734
tags question: http://stackoverflow.com/q/50768366
tags question: http://stackoverflow.com/q/50769689
tags question: http://stackoverflow.com/q/50778388
tags question: http://stackoverflow.com/q/50804987
tags question: http://stackoverflow.com/q/50802721
tag name: pyqt5
tags question: http://stackoverflow.com/q/50718438
tags question: http://stackoverflow.com/q/50758950
tags question: http://stackoverflow.com/q/50753808
tags question: http://stackoverflow.com/q/50726510
tags question: http://stackoverflow.com/q/50786186
tags question: http://stackoverflow.com/q/50756044
tags question: http://stackoverflow.com/q/50851966
tags question: http://stackoverflow.com/q/50782747
tags question: http://stackoverflow.com/q/50735744
tags question: http://stackoverflow.com/q/50771171
tags question: http://stackoverflow.com/q/50782670
tags question: http://stackoverflow.com/q/50745153

http://stackoverflow.com/comment/88619804
type: QuestionComment
comment on: http://stackoverflow.com/q/50806462
has text: Is there a reason this need to be a one-liner? Why not just `nv = container.find('span', attrs= {'name':'nv'})` then `if nv: votes = nv['data-value']`? (I'm guessing about where the error happens and why, but it should be obvious how to change it if I've guessed wrong.)
score: 0
type: Comment

vector
tags question: http://stackoverflow.com/q/50772176
type: Tag
tags question: http://stackoverflow.com/q/50773233
tag name: vector
tags question: http://stackoverflow.com/q/50727961
tags question: http://stackoverflow.com/q/50706947
tags question: http://stackoverflow.com/q/50738140
tags question: http://stackoverflow.com/q/50717951

http://stackoverflow.com/a/50760279
has comment: http://stackoverflow.com/comment/88587577
has body: I think you want to use pickle. import pickle very_long_list = [1,2,3] file_name = "/tmp/very_long_list.pickle" pickle.dump(very_long_list, open(file_name, "wb")) del very_long_list very_long_list = pickle.load(open(file_name, "rb")) print(very_long_list) # prints [1,2,3], we did it!
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50760163
type: Answer
has comment: http://stackoverflow.com/comment/88528558
has comment: http://stackoverflow.com/comment/88528228
upvote count: 2
has comment: http://stackoverflow.com/comment/88592748
has comment: http://stackoverflow.com/comment/88589934
has comment: http://stackoverflow.com/comment/88591127

http://stackoverflow.com/q/50791275
score: 3
has title: Convert array of JSON String to array of object in Python
has comment: http://stackoverflow.com/comment/88588476
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/50791778
has comment: http://stackoverflow.com/comment/88588593
has answer: http://stackoverflow.com/a/50791778
has comment: http://stackoverflow.com/comment/88592720
has comment: http://stackoverflow.com/comment/88616386
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88588739
has comment: http://stackoverflow.com/comment/88598600
has comment: http://stackoverflow.com/comment/88588904
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/50791489
has comment: http://stackoverflow.com/comment/88589760
tagged with: deserialization
has body: I having array of JSON string, I need to convert it as array of object (i.e., convert the JSON to respective object) without a for loop. Source Code: (Input data) data = ['[1,2,3]', '[4,5,6]', '[7,8,9]'] Required Output: [[1,2,3], [4,5,6], [7,8,9]] I already using the following solution import json data = ['[1,2,3]', '[4,5,6]', '[7,8,9]'] output = [] for item in data: output.append(json.loads(item)) Currently I'm having a very large number of JSON strings (approx 100K records) and moreover each JSON String array internally contains the record approx 50K. While on execution it takes more than 3GB of RAM for processing. Note: Implicitly the output is a 2-dim array [][]. 1st dimension is approx 100K records 2nd dimension contains approx 50K records. Totally 100K * 50K items. While on conversion it takes more time to convert the JSON (for the above approach). Kindly assist me the idea to convert the JSON string without a for loop.
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/88590187
has comment: http://stackoverflow.com/comment/88598684
accepted answer: http://stackoverflow.com/a/50791489
type: AnsweredQuestion

http://stackoverflow.com/comment/88601700
score: 0
type: Comment
type: QuestionComment
has text: @XaBla Remove the co-variance matrix. You do not need that for this particular task. See my answer
comment on: http://stackoverflow.com/q/50794966

http://stackoverflow.com/comment/88595296
type: Comment
type: QuestionComment
has text: @KavehVahedipour I printed the `img_name` inside the for loop, and there didn't seem to be any difference, eyeballing the console with my eyes, in the rate at which the image names were displayed in the console.
score: 0
comment on: http://stackoverflow.com/q/50791452

heap
tags question: http://stackoverflow.com/q/50727159
type: Tag
tag name: heap

http://stackoverflow.com/q/50790056
has title: failed building wheel for pocketsphinx
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/90776784
downvote count: 1
type: Question
tagged with: swig
tagged with: pocketsphinx
has answer: http://stackoverflow.com/a/63849054
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: (Macosx) I've been trying to install textract using pip install textract, but I get the below error message. I've installed pocketsphinx and swig already. I also don't know what the message about requests 2.18.4 has requirement chardet&lt;3.1.0,&gt;=3.0.2, but you'll have chardet 2.3.0 which is incompatabile I'd really appreciate if someone could walk me through what this means and how I can move on to install textract. relatively new to python so the simpler the language the better. Here's what I thought to be the relevant error message: Failed building wheel for pocketsphinx Running setup.py clean for pocketsphinx Failed to build pocketsphinx requests 2.18.4 has requirement chardet&lt;3.1.0,&gt;=3.0.2, but you'll have chardet 2.3.0 which is incompatible. Installing collected packages: pocketsphinx, textract Found existing installation: pocketsphinx 0.1.15 Uninstalling pocketsphinx-0.1.15: Successfully uninstalled pocketsphinx-0.1.15 Running setup.py install for pocketsphinx ... error Complete output from command /anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/d8/hyzy1y7s4sd46jxz4chrhfcc0000gn/T/pip-install-dn569xpj/pocketsphinx/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/d8/hyzy1y7s4sd46jxz4chrhfcc0000gn/T/pip-record-j1sxbma0/install-record.txt --single-version-externally-managed --compile: running install running build_ext building 'sphinxbase._ad' extension swigging swig/sphinxbase/ad.i to swig/sphinxbase/ad_wrap.c swig -python -modern -Ideps/sphinxbase/include -Ideps/sphinxbase/include/sphinxbase -I/System/Library/Frameworks/OpenAL.framework/Versions/A/Headers -Ideps/sphinxbase/include/android -Ideps/sphinxbase/swig -outdir sphinxbase -o swig/sphinxbase/ad_wrap.c swig/sphinxbase/ad.i dyld: Library not loaded: @rpath/libpcre.1.dylib Referenced from: /usr/local/bin/swig Reason: image not found…
tagged with: macos

http://stackoverflow.com/comment/88702655
score: 0
type: AnswerComment
type: Comment
has text: Sorry for the typos and not including writeCSVfile. That did solve the issue, thank you very much. I have also corrected other things that were wrong with my code.
comment on: http://stackoverflow.com/a/50849130

python
tags question: http://stackoverflow.com/q/50711026
tags question: http://stackoverflow.com/q/50829690
tags question: http://stackoverflow.com/q/50708768
tags question: http://stackoverflow.com/q/50790043
tags question: http://stackoverflow.com/q/50702508
tags question: http://stackoverflow.com/q/50837180
tags question: http://stackoverflow.com/q/50790766
tags question: http://stackoverflow.com/q/50762877
tags question: http://stackoverflow.com/q/50784136
tags question: http://stackoverflow.com/q/50703090
tags question: http://stackoverflow.com/q/50700725
tags question: http://stackoverflow.com/q/50838199
tags question: http://stackoverflow.com/q/50751820
tags question: http://stackoverflow.com/q/50761252
tags question: http://stackoverflow.com/q/50790300
tags question: http://stackoverflow.com/q/50818999
tags question: http://stackoverflow.com/q/50720245
tags question: http://stackoverflow.com/q/50724040
tags question: http://stackoverflow.com/q/50793063
tags question: http://stackoverflow.com/q/50820844
tags question: http://stackoverflow.com/q/50804656
tags question: http://stackoverflow.com/q/50724788
tags question: http://stackoverflow.com/q/50842419
tags question: http://stackoverflow.com/q/50704849
tags question: http://stackoverflow.com/q/50711796
tags question: http://stackoverflow.com/q/50734672
tags question: http://stackoverflow.com/q/50774996
tags question: http://stackoverflow.com/q/50706901
tags question: http://stackoverflow.com/q/50794276
tags question: http://stackoverflow.com/q/50766326
tags question: http://stackoverflow.com/q/50850258
tags question: http://stackoverflow.com/q/50714720
tags question: http://stackoverflow.com/q/50795543
tags question: http://stackoverflow.com/q/50704080
tags question: http://stackoverflow.com/q/50825093
tags question: http://stackoverflow.com/q/50844558
tags question: http://stackoverflow.com/q/50757464
tags question: http://stackoverflow.com/q/50756032
tags question: http://stackoverflow.com/q/50833256
tags question: http://stackoverflow.com/q/50713455
tags question: http://stackoverflow.com/q/50735626
tags question: http://stackoverflow.com/q/50731058
tags question: http://stackoverflow.com/q/50729869
tags question: http://stackoverflow.com/q/50846131
tags question: http://stackoverflow.com/q/50818965
tags question: http://stackoverflow.com/q/50837766
tags question: http://stackoverflow.com/q/50766762
tags question: http://stackoverflow.com/q/50804126
tags question: http://stackoverflow.com/q/50808495
tags question: http://stackoverflow.com/q/50789505
tags question: http://stackoverflow.com/q/50853900
tags question: http://stackoverflow.com/q/50705083
tags question: http://stackoverflow.com/q/50714185
tags question: http://stackoverflow.com/q/50841608
tags question: http://stackoverflow.com/q/50834258
tags question: http://stackoverflow.com/q/50797275
tags question: http://stackoverflow.com/q/50841048
tags question: http://stackoverflow.com/q/50710203
tags question: http://stackoverflow.com/q/50787334
tags question: http://stackoverflow.com/q/50728186
tags question: http://stackoverflow.com/q/50822822
tags question: http://stackoverflow.com/q/50778481
tags question: http://stackoverflow.com/q/50772362
tags question: http://stackoverflow.com/q/50839847
tags question: http://stackoverflow.com/q/50844331
tags question: http://stackoverflow.com/q/50734957
tags question: http://stackoverflow.com/q/50698975
tags question: http://stackoverflow.com/q/50774928
tags question: http://stackoverflow.com/q/50812469
tags question: http://stackoverflow.com/q/50811377
tags question: http://stackoverflow.com/q/50838633
tags question: http://stackoverflow.com/q/50783151
tags question: http://stackoverflow.com/q/50797289
tags question: http://stackoverflow.com/q/50803526
tags question: http://stackoverflow.com/q/50816723
tags question: http://stackoverflow.com/q/50703077
tags question: http://stackoverflow.com/q/50846477
tags question: http://stackoverflow.com/q/50784367
tags question: http://stackoverflow.com/q/50719510
tags question: http://stackoverflow.com/q/50729897

http://stackoverflow.com/q/50763920
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88535969
has comment: http://stackoverflow.com/comment/88536007
score: 0
has comment: http://stackoverflow.com/comment/88536295
has body: I'm using PIL and numpy to combine two images while one is a .jpg and the other image is represented by a numpy array, which defines a mask that I want to put on top of the original image (basically just a matrix with one and zero entries and the same size as the .jpg). PIL’s composite function works just fine for that but for some reason, after saving the composite image, the file size shrinks to approximately 1/3 of the original image size. Can someone explain this behavior to me? Here's a code snippet: import numpy as np import PIL from PIL import Image from PIL import ImageColor rgb = ImageColor.getrgb('black') # Read image and write into numpy array image = Image.open('test_image.jpg') (im_width, im_height) = image.size # Create empty mask mask = np.zeros((im_width, im_height)) # Composite image and mask solid_color = np.expand_dims(np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3]) pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA') pil_mask = Image.fromarray(np.uint8(255.*mask)).convert('L') image = Image.composite(pil_solid_color, image, pil_mask) # save image image.save('test_image_with_mask.jpg') Code was inspired by tnesorflow's object detection api. Thanks in advance.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88535670
tagged with: python
has title: Quality loss after combining two images with PIL and numpy
tagged with: python-imaging-library

http://stackoverflow.com/q/50750189
answer count: 2
has answer: http://stackoverflow.com/a/50753435
tagged with: pandas
has answer: http://stackoverflow.com/a/50781117
downvote count: 0
favorite count: 0
has body: I want to insert 2 columns into a dataframe. Original Dataframe card auth month order_number Amex A 2017-11 1234 Visa A 2017-12 2345 Amex D 2017-12 3456 I want to break down auth_status by month. I used the following code: bin_month_df = monthly_df.pivot_table(index='card', columns=['month', 'auth'],values='order_number', aggfunc='count') Dataframe by Month month 2017-11 2017-12 auth A D A D card mastercard 10 11 11 10 amex 19 20 10 11 visa 50 30 50 1 Target Outcome I want to add columns for subtotal and auth_rate month 2017-11 2017-12 auth A D total pct A D total pct card mastercard 10 11 21 .47 11 10 21 .52 amex 19 20 39 .49 10 11 21 .47 visa 50 30 80 .63 50 1 51 .98 I'm having trouble creating these columns.This link shows subtotals by rows, but it's not translating for me into columns or calculated columns. Any help is appreciated!
tagged with: python
accepted answer: http://stackoverflow.com/a/50753435
score: 2
type: AnsweredQuestion
has title: Calculated Columns in Multiindex
upvote count: 2
type: Question
linked to: http://stackoverflow.com/q/15570099
possible better answer: http://stackoverflow.com/a/50781117

http://stackoverflow.com/comment/88604009
type: Comment
comment on: http://stackoverflow.com/a/50799012
score: 0
type: AnswerComment
has text: @SergeBallesta OP seems to wan't to call it with `1` indexed and this does the job.

http://stackoverflow.com/comment/88671256
has text: @DeepakM - add them to `dictionary`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50833718

http://stackoverflow.com/comment/88621329
type: AnswerComment
score: 0
type: Comment
has text: Thank you Joy, I tried the last piece, and from what I could tell, it breaks down the groups and does each group individually: then does the quantile over the entire set and selects the last two results. It gets the right answer, but I believe doesn't address the idea of not calculating the entire expanding windows.
comment on: http://stackoverflow.com/a/50752906

http://stackoverflow.com/comment/88546259
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50768396
has text: @ShabbirKhan I figured it out, thanks! worked very well
score: 0

http://stackoverflow.com/comment/88694669
comment on: http://stackoverflow.com/a/50844957
has text: Can you try with this vector gAAAAABbIXmNE6v5uaUYNxbQIFuHLokphd7OzAg-dekcC3-XlllcwWly3HJvUlPAMBWsgCLWiKBMGVReeRtXLFoMS-ZVLPwAlw==
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50767472
has comment: http://stackoverflow.com/comment/88542600
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88552776
has title: Higher model accuracy for TensorFlow on Google Colab GPUs
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88569997
has body: When i run my simple Neural Network model on MNIST dataset, on my Macbook, the accuracy is about %0.85. but when i copy the same code (everything's the same, like epoch numbers etc) on Google Colab, with their decent GPUs, i get an accuracy of about %0.95, is there any rationale around it ? Regards
tagged with: neural-network
score: 0
tagged with: gpu
tagged with: python

http://stackoverflow.com/q/50834762
has comment: http://stackoverflow.com/comment/88704594
has comment: http://stackoverflow.com/comment/88707431
type: AnsweredQuestion
tagged with: django-views
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88704523
has comment: http://stackoverflow.com/comment/88738954
has comment: http://stackoverflow.com/comment/88739464
has comment: http://stackoverflow.com/comment/88848476
has comment: http://stackoverflow.com/comment/88848444
has body: This problem is related to a gaming arcade parlor where people go in the parlor and play a game. As a person plays, there is a new entry created in the database. My model is like this: class gaming_machine(models.Model): machine_no = models.Integer() score = models.Integer() created = models.DateTimeField(auto_now_add=True) My view is like this: today = datetime.now().date() # i am querying the db for getting the gaming_machine objects where score = 192 or 100 and the count of these objects separately for gaming_machines object which have 192 score and gaming_machine objects which have score as 100 gaming_machine.objects.filter(Q(points=100) | Q(points=192),created__startswith=today).values_list('machine_no','points').annotate(Count('machine_no')) # this returns a list of tuples -&gt; (machine_no, points, count) &lt;QuerySet [(330, 192,2), (330, 100,4), (331, 192,7),(331,192,8)]&gt; Can i change the returned queryset format to something like this: {(330, 192):2, (330, 100) :4, (331, 192):7,(331,192):8} # that is a dictionary with a key as a tuple consisting (machine_no,score) and value as count of such machine_nos I am aware that i can change the format of this queryset in the python side using something like dictionary comprehension, but i can't do that as it takes around 1.4 seconds of time to do that because django querysets are lazy.
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50925250
accepted answer: http://stackoverflow.com/a/50925250
has comment: http://stackoverflow.com/comment/88847803
has comment: http://stackoverflow.com/comment/88673561
has comment: http://stackoverflow.com/comment/88674856
favorite count: 0
has comment: http://stackoverflow.com/comment/88673526
has title: Django queryset : how to change the returned datastructure
has comment: http://stackoverflow.com/comment/88713813
linked to: http://stackoverflow.com/q/782915
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88673453

http://stackoverflow.com/comment/88687766
comment on: http://stackoverflow.com/a/50842041
type: Comment
has text: No I really do want the whole string in `idx` , not just the country name, i.e I want to be able to distinguish points one step more than what can be simply done with legends.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50737109
has comment: http://stackoverflow.com/comment/88481887
has comment: http://stackoverflow.com/comment/88481897
has comment: http://stackoverflow.com/comment/88482288
has comment: http://stackoverflow.com/comment/88481889
tagged with: if-statement
score: 0
has title: http.server if statement os.path.isfile() doesn't work
has comment: http://stackoverflow.com/comment/88482640
type: Question
has body: So this is my code: from http.server import BaseHTTPRequestHandler, HTTPServer import requests, json, os PORT = 1337 class getHandler(BaseHTTPRequestHandler): def handleJSON(self, provider, data): if provider == "provider_1": json_data = json.loads(data) sl_token = json_data["access_token"] return sl_token elif provider == "provider_2": json_data = json.loads(data) pb_token = json_data["access_token"] return pb_token def do_GET(self): data = self.requestline self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(b'You may close the tab now') print("Raw Data: " + data) if not os.path.isfile("PbToken.txt") and os.path.isfile("SlToken.txt"): if "GET /?code=" and "&amp;state=" in data: # Provider_1 print("Provider_1 Data:", data) pb_code = data[data.find("/?code=") + len("/?code="):data.find("&amp;state=")] with open("PbToken.txt", "w") as file: file.write(pb_code) file.close() elif "GET /?code=" in data: # Provider_2 print("Provider_2 Data:", data) sl_code = data.strip() sl_code = sl_code[sl_code.rindex("/?code=") + len("/?code="):sl_code.rindex(" ")] with open("SlToken.txt", "w") as file: file.write(sl_code) file.close() else: raise SystemExit server = HTTPServer(('localhost', PORT), getHandler) print("Started server on port", PORT) server.serve_forever() So from the class getHandler in the function do_GET(self) it never makes it past the if not os.path.isfile("PbToken.txt") and os.path.isfile("SlToken.txt"): statement (I've of course made sure the files aren't actually there). I want it to check if both of the files exist, if they don't do what's written below. If the files exist they should go straight to the else statement where it uses raise SystemExit. What am I doing wrong?
linked to: http://stackoverflow.com/q/17893542
answer count: 1
has answer: http://stackoverflow.com/a/50740460
has comment: http://stackoverflow.com/comment/88481891
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88482119
tagged with: python

http://stackoverflow.com/q/50768224
has body: I'm trying to use shelve to save/load some data to/from a file. I have a list of dictionaries: inv = [slot0, slot1, slot2, slot3, slot4, slot5, slot6] And each of the 7 dictionaries look like this, but with slight variation in the values: slot0 = {"item_pos": [hud_x + 592, hud_y + 4], "text_pos": [hud_x + 612, hud_y + 25], "item": None, "amount": 0} In order to save/load the dictionaries, I use the "shelve" module, and here is the code for saving: with shelve.open((os.path.join(saves_path, "inventory", "inventory")), "c") as f: f["slot0_item"] = slot0["item"] f["slot0_amount"] = slot0["amount"] f["slot1_item"] = slot1["item"] f["slot1_amount"] = slot1["amount"] f["slot2_item"] = slot2["item"] f["slot2_amount"] = slot2["amount"] f["slot3_item"] = slot3["item"] f["slot3_amount"] = slot3["amount"] f["slot4_item"] = slot4["item"] f["slot4_amount"] = slot4["amount"] f["slot5_item"] = slot5["item"] f["slot5_amount"] = slot5["amount"] f["slot6_item"] = slot6["item"] f["slot6_amount"] = slot6["amount"] Here is the code for loading: with shelve.open((os.path.join(saves_path, "inventory", "inventory")), "c") as f: slot0["item"] = f["slot0_item"] slot0["amount"] = f["slot0_amount"] slot1["item"] = f["slot1_item"] slot1["amount"] = f["slot1_amount"] slot2["item"] = f["slot2_item"] slot2["amount"] = f["slot2_amount"] slot3["item"] = f["slot3_item"] slot3["amount"] = f["slot3_amount"] slot4["item"] = f["slot4_item"] slot4["amount"] = f["slot4_amount"] slot5["item"] = f["slot5_item"] slot5["amount"] = f["slot5_amount"] slot6["item"] = f["slot6_item"] slot6["amount"] = f["slot6_amount"] While this code works fine, it's very long and inefficient. I tried to use a "for" loop to save the data like this: for slot in inv: f["slot_item"] = slot["item"] f["slot_amount"] = slot["amount"] ...And load the data like this: for slot in inv: slot["item"] = f["slot_item"] slot["amount"] = f["slot_amount"] However, when I use this method, the dictionaries don't save/load their changes when restart…
has title: How to save/load data with shelve using a "for" loop?
tagged with: python
has comment: http://stackoverflow.com/comment/88544199
has comment: http://stackoverflow.com/comment/88544722
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50779506
tagged with: save
tagged with: shelve
type: Question
possible better answer: http://stackoverflow.com/a/50772649
has answer: http://stackoverflow.com/a/50772649
has comment: http://stackoverflow.com/comment/88544179
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50779506

http://stackoverflow.com/comment/88441543
has text: That's expected as spyder is not present in the env anymore. Install it via `conda install spyder` and try starting it again.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50715679

http://stackoverflow.com/q/50728117
tagged with: performance
tagged with: set
has answer: http://stackoverflow.com/a/50728352
type: Question
accepted answer: http://stackoverflow.com/a/50728352
score: 5
answer count: 1
upvote count: 6
linked to: http://stackoverflow.com/q/27674289
downvote count: 1
has body: why this question ? I was trying to answer this question: Check if All Values Exist as Keys in Dictionary with something better than a generator comprehension fed to all (python loops, even in comprehensions, slow down execution compared to implicit loops that some functions perform): all(i in bar for i in foo) where bar is a dictionary and foo is a list by using set.issubset (with a conversion to set of foo to be able to use foo.issubset(bar)), and didn't succeed to beat the times of the all solution (unless both containers are converted to sets). my question: From the documentation of set: Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') &amp; 'cbs' in favor of the more readable set('abc').intersection('cbs'). Okay but the performance really depends on the type of argument, even if the complexity does not (The complextiy of Python issubset()): import timeit foo = {i for i in range(1, 10000, 2)} bar = foo - {400} n=10000 x = timeit.timeit(setup="foo = {str(i) for i in range(1, 10000, 2)};bar = foo - {'400'}",stmt="bar.issubset(foo)",number=n) print("issubset(set)",x) x = timeit.timeit(setup="foo = {str(i) for i in range(1, 10000, 2)};bar = foo - {'400'};foo=list(foo)",stmt="bar.issubset(foo)",number=n) print("issubset(list)",x) x = timeit.timeit(setup="foo = {str(i):i for i in range(1, 10000, 2)};bar = set(foo) - {'400'}",stmt="bar.issubset(foo)",number=n) print("issubset(dict)",x) x = timeit.timeit(setup="foo = {str(i):i for i in range(1, 10000, 2)}.keys();bar = set(foo) - {'400'}",stmt="bar.issubset(foo)",number=n) print("issubset(dict_keys)",x) my results (Python 3.4): issubset(set) 1.6141405847648826 issubset(list) 3.698748032058883 issubset(dict) 3.6300025109004244 issubset(dict_keys) 4.2242996…
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/50724875
has title: set issubset performance difference depending on the argument type
type: AnsweredQuestion

http://stackoverflow.com/comment/88540042
score: 1
comment on: http://stackoverflow.com/q/50766229
type: Comment
type: QuestionComment
has text: which version of python ?

http://stackoverflow.com/q/50725646
upvote count: 1
tagged with: python
tagged with: c++
type: AnsweredQuestion
score: 1
tagged with: boost
linked to: http://stackoverflow.com/q/36049533
type: Question
has comment: http://stackoverflow.com/comment/88459620
answer count: 1
has comment: http://stackoverflow.com/comment/88459900
has answer: http://stackoverflow.com/a/50776056
has title: Convert Python function to C++, via Boost Python, for use as a callback
tagged with: boost-python
accepted answer: http://stackoverflow.com/a/50776056
downvote count: 0
linked to: http://stackoverflow.com/q/21451863
favorite count: 0
has body: In general what is the recommended way to pass a Python function through Boost-Python for use later in C++ code (i.e. as a callback in a C++ object)? More specifically, I have a C++ class FooCPP that I've successfully exposed to Python via Boost-Python; the user interacts with the Python class Foo that runs the C++ counterpart under the hood. Contrived example: # Foo.py from foo_base import FooBase class Foo(FooBase): ... def callback(val=42.): return val foo = Foo() foo.run(callback) And the Boost Python bindings: // foo_bindings.cpp #include "foo.hpp" #include &lt;boost/python.hpp&gt; namespace bp = boost::python; FooPython::Run(const bp::object&amp; py_callback) // TODO: Do something with the python callback to make it a C++ function! std::function&lt;double(double)&gt; cpp_callback; FooCPP::Run(cpp_callback); ) BOOST_PYTHON_MODULE(foo_base){ bp::class_&lt;FooPython&gt;("FooBase") .def("run", &amp;FooPython::Run) ; } So how can I address the TODO comment in foo_bindings.cpp? I've gone through a number of related SO questions -- e.g. pass python function to boost c and sending py function as boost function arg -- and I'm familiar with the Boost-Python docs, but have not found a good solution/explanation. Thanks in advance! Notes: C++11, boost v1.58.0, ubuntu 16.04 Update I may have just found a solution, where I can implement a functor in foo_bindings.cpp, e.g., struct PythonCallback { public: PythonCallback(bp::object cb_func) : cb_func_(cb_func) {} double operator() (const double&amp; val) { // Call the callback function in python return cb_func_(val); } private: bp::object cb_func_; }; But then what should the FooCPP::Run signature be? I.e. what type is defined for the cpp_callback passed in? And does the BOOST_PYTHON_MODULE code need to change for this callback functor?

http://stackoverflow.com/comment/88531644
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50744038
has text: My suspicion is that Python handles the two expressions very differently and the $input PyObject must be processed differently. But I do not know how to get from a managedbuffer Type to a callable function.
score: 0

http://stackoverflow.com/q/50703051
score: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88415556
upvote count: 1
tagged with: python
answer count: 1
tagged with: mplcursors
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88415879
has answer: http://stackoverflow.com/a/50744657
has title: Display one label per bubble in tooltips in a scatter plot (Matplotlib)
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88430565
favorite count: 0
has body: I have an animated scatter plot which shows GDP per capita x life expectancy per country through the years. I want to add a tooltip that will appear when someone hovers the mouse over a bubble, and I want it to display the name of the country that bubble is equivalent to. I attempted to use mplcursors to do so, but had trouble figuring out how to display the name of the country, since it's a different one in each bubble. Here's the plot: ax.scatter(y = data['lifeExpec'], x = data['gdp'], s = data['population']/40000, c = data['region'].astype('category').cat.codes, cmap = cm.viridis, edgecolors = 'none', alpha = 0.5) c1 = mplcursors.cursor(ax, hover=True) @c1.connect("add") def _(sel): sel.annotation.set_text(&lt;????&gt;) sel.annotation.set(position=(-15,15), fontsize=8, ha='center', va='center') Here's a sample of my dataframe: country, gdp, lifeExpec, year, population, region USA, 20000, 70, 2005, 100000, America USA, 21000, 72, 2007, 104000, America Canada, 20500, 71, 2005, 50000, America Canada, 23000, 74, 2007, 53000, America
type: Question
linked to: http://stackoverflow.com/q/7908636
accepted answer: http://stackoverflow.com/a/50744657

http://stackoverflow.com/comment/88647088
type: Comment
type: AnswerComment
has text: Yup that was the issue, feel a little slow but thanks for the quick response !
score: 0
comment on: http://stackoverflow.com/a/50820651

http://stackoverflow.com/comment/88689625
has text: `lst = [func1(centroids[i], value) for i in range(n + 1)]`
comment on: http://stackoverflow.com/q/50843032
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88501623
type: Comment
type: QuestionComment
has text: How do you open the form to create the child record? Could you show an screenshot?
score: 0
comment on: http://stackoverflow.com/q/50743569

http://stackoverflow.com/comment/88557543
type: AnswerComment
comment on: http://stackoverflow.com/a/50755018
has text: It seems that post.pk is None, but we need the full stack trace to be sure. You shuld paste here the full page with errors and variables values.
score: 0
type: Comment

http://stackoverflow.com/comment/89545010
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50755103
has text: Note `np.in1d` is used by `pd.Series.isin` for sufficiently large arrays ([source](http://github.com/pandas-dev/pandas/blob/v0.23.1/pandas/core/series.py#L3532-L3590)). So there may be benefits to leaving the decision-making to `pd.Series.isin`.

http://stackoverflow.com/q/50754601
answer count: 3
possible better answer: http://stackoverflow.com/a/50755676
tagged with: python
has answer: http://stackoverflow.com/a/50755676
has body: So I have a function defined that works great at doing merge sort on a linear array if it is implemented by its lonesome, but if I put it into a class it bugs out. I think it's a great example of what I don't quite understand about how classes work; possibly in regards to namespace management(?). See below: def sort(array): print('Splitting', array) if len(array) &gt; 1: m = len(array)//2 left = array[:m] right = array[m:] sort(left) sort(right) i = 0 j = 0 k = 0 while i &lt; len(left) and j &lt; len(right): if left[i] &lt; right[j]: array[k] = left[i] i += 1 else: array[k] = right[j] j += 1 k += 1 while i &lt; len(left): array[k] = left[i] i += 1 k += 1 while j &lt; len(right): array[k] = right[j] j += 1 k += 1 print('Merging', array) arr = [1,6,5,2,10,8,7,4,3,9] sort(arr) Produces the expected correct output: Splitting [1, 6, 5, 2, 10, 8, 7, 4, 3, 9] Splitting [1, 6, 5, 2, 10] Splitting [1, 6] Splitting [1] Merging [1] Splitting [6] Merging [6] Merging [1, 6] Splitting [5, 2, 10] Splitting [5] Merging [5] Splitting [2, 10] Splitting [2] Merging [2] Splitting [10] Merging [10] Merging [2, 10] Merging [2, 5, 10] Merging [1, 2, 5, 6, 10] Splitting [8, 7, 4, 3, 9] Splitting [8, 7] Splitting [8] Merging [8] Splitting [7] Merging [7] Merging [7, 8] Splitting [4, 3, 9] Splitting [4] Merging [4] Splitting [3, 9] Splitting [3] Merging [3] Splitting [9] Merging [9] Merging [3, 9] Merging [3, 4, 9] Merging [3, 4, 7, 8, 9] Merging [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] However, I get an error when I attempt to use this function in a class; something to do with namespace managment, I think. See below: class MergeSort(object): def __init__(self, array): self.array = array def sort(self): print('Splitting', self.array) if len(self.array) &gt; 1: m = len(self.array)//2 left = self.array[:m] right = self.array[m:] sort(left) sort(right) i = 0 j = 0 k = 0 while i &lt; len(left) and j &lt; len(right): if left[i] &lt; right[j]: self.array[k] = left[i] i += 1 …
has answer: http://stackoverflow.com/a/50754696
linked to: http://stackoverflow.com/q/50774975
has comment: http://stackoverflow.com/comment/88517151
tagged with: namespaces
has answer: http://stackoverflow.com/a/50754703
has comment: http://stackoverflow.com/comment/88517352
type: AnsweredQuestion
tagged with: algorithm
tagged with: class
type: Question
accepted answer: http://stackoverflow.com/a/50754696
has title: Implementing merge sort function in python class, errors
score: 0
tagged with: mergesort
has comment: http://stackoverflow.com/comment/88517146
has comment: http://stackoverflow.com/comment/88517046

http://stackoverflow.com/a/50862282
type: Answer
upvote count: 11
accepted answer of: http://stackoverflow.com/q/50779424
has comment: http://stackoverflow.com/comment/118529564
answers question: http://stackoverflow.com/q/50779424
has body: Pardon the almost blog post. I am posting this because while you can find partial answers in various places, I haven't run across a complete post anywhere, which would have saved me a ton of time. The problem is you need both sides to the story in order to verify either. So I want to send a request using Postman to a Python/Flask web service. It has to have an image along with some metadata. Here are the settings for Postman (URL, Headers): And Body: Now on to the web service. Here is a bare bones service which will take the request, print the metadata and save the file: from flask import Flask, request app = Flask(__name__) # POST - just get the image and metadata @app.route('/RequestImageWithMetadata', methods=['POST']) def post(): request_data = request.form['some_text'] print(request_data) imagefile = request.files.get('imagefile', '') imagefile.save('D:/temp/test_image.jpg') return "OK", 200 app.run(port=5000) Enjoy!
type: AcceptedAnswer
downvote count: 0
score: 11

http://stackoverflow.com/a/50753408
type: AcceptedAnswer
has body: According to Scrapy Document, the method parse , as well as any other Request callback, must return an iterable of Request and/or dicts or Item objects. Also according to the code example below that link, import scrapy from myproject.items import MyItem class MySpider(scrapy.Spider): name = 'example.com' allowed_domains = ['example.com'] def start_requests(self): yield scrapy.Request('http://www.example.com/1.html', self.parse) yield scrapy.Request('http://www.example.com/2.html', self.parse) yield scrapy.Request('http://www.example.com/3.html', self.parse) def parse(self, response): for h3 in response.xpath('//h3').extract(): yield MyItem(title=h3) for url in response.xpath('//a/@href').extract(): yield scrapy.Request(url, callback=self.parse) We can see we have to use yield to acquire proper results from parse function. tl;dr: replace return in your last line with yield.
accepted answer of: http://stackoverflow.com/q/50736550
answers question: http://stackoverflow.com/q/50736550
type: Answer
score: 0

http://stackoverflow.com/q/50827777
tagged with: postgresql
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50828010
tagged with: bulk-load
has title: Bulk loading with special characters using Python
type: Question
has answer: http://stackoverflow.com/a/50828010
score: 0
answer count: 1
has body: I am currently using "copy_from" to do bulk load, but it seems to give error due to the presence of double quotes in the data. engineor = create_engine('oracle+cx_oracle://xxxx:xxxx@xxxxx:xxxx/?service_name=xxxxx') sql = "select * from xxxxxx WHERE ROWNUM &lt;= 10" df = pd.read_sql(sql, engineor) enginegp = create_engine('xxxxx@xxxxx:xxxx/xxxx') connection = enginegp.raw_connection() output = io.StringIO() df.to_csv(output, sep='\t', header=False, index=False) output.seek(0) output.getvalue() cur = connection.cursor() cur.copy_from(output, 'test', null="") connection.commit() cur.close() The error I am getting is "DataError: missing data for column" with some column name. I tried removing comma from the data using replace, I still get the error with a different column name.
tagged with: greenplum

http://stackoverflow.com/a/50846293
has comment: http://stackoverflow.com/comment/88696350
answers question: http://stackoverflow.com/q/50845998
has comment: http://stackoverflow.com/comment/88696121
has comment: http://stackoverflow.com/comment/88696136
has comment: http://stackoverflow.com/comment/88696300
upvote count: 3
has comment: http://stackoverflow.com/comment/88696336
downvote count: 1
has comment: http://stackoverflow.com/comment/88696230
has body: You can use np.bincount to count the months first and then plot it: import matplotlib.pyplot as plt import numpy as np # create an example months array months = np.random.randint(1, 13, size=30) plt.bar(np.arange(1, 13), np.bincount(months, minlength=13)[1:])
has comment: http://stackoverflow.com/comment/88696183
type: Answer
score: 2

http://stackoverflow.com/a/50867437
upvote count: 2
type: Answer
score: 2
has body: If your goal is to remove "outlier" spikes in derivative series, I would try "rolling median" first instead of "rolling mean" since median in general is more insensitive to outliers. For example: smotDeriv = derivative.rolling(window=10, min_periods=3, center=True).median() And then, if you further want to smooth it out, one of possible options is to apply rolling_mean(). Note: Since I don't have your data at hand to play around, I'm not sure about optimal values for window and min_periods. It depends on how far you want to smooth it out. Also, it seems to me that smoothing derivative is becoming more like smoothing the original time series, so if there is a known way to smooth your original time series, that may be more straight forward. Hope this helps.
downvote count: 0
answers question: http://stackoverflow.com/q/50766061

http://stackoverflow.com/comment/88660817
has text: Thanks for you kind formatting, it's quit pretty now~ I'll pay attention to that the next time~
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50808754

http://stackoverflow.com/comment/124669231
has text: In the current version it seems you need to use `get_variable` to get a string variable rather than `get_object`
comment on: http://stackoverflow.com/a/55248730
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50727776
upvote count: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50727891
favorite count: 0
possible better answer: http://stackoverflow.com/a/50729596
tagged with: python
tagged with: regex
tagged with: nlp
score: 2
has title: How to extract text until it reaches a capital word? Python
has body: This is my complete text: RETENTION Liability in excess of the Retention The Retention shall be borne by the Named Insured and the Insurer shall only be liable for Loss once the Retention has been fully eroded. The Retention shall apply until such time as it has been fully eroded after which no Retention shall apply. Erosion of the Retention The Retention shall be eroded by Loss for which the Insurer would be liable under this Policy but for the Retention. I want to extract the whole RETENTION paragraph. This was my code to extract the sentences which have a specific word (here: Retention). abc3=([sentence + '.' for sentence in txt_trim_string.split('.') if 'RETENTION' in sentence]) But this gave the output as: RETENTION Liability in excess of the Retention The Retention shall be borne by the Named Insured and the Insurer shall only be liable for Loss once the Retention has been fully eroded. I also want to include: Erosion of the Retention The Retention shall be eroded by Loss for which the Insurer would be liable under this Policy but for the Retention. How can I do that?
has answer: http://stackoverflow.com/a/50729596
has comment: http://stackoverflow.com/comment/88464209
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50727891
type: Question

http://stackoverflow.com/q/50844558
tagged with: widget
has answer: http://stackoverflow.com/a/52412805
upvote count: 1
tagged with: databricks
answer count: 1
type: UnansweredQuestion
has title: Databricks widgets
downvote count: 0
score: 1
favorite count: 0
has body: My question is about widgets to pass parameters in databricks. I am using widgets in one notebook to set parameters. Then, I am running this initial notebook from other notebooks. I want the chosen parameters to be pulled in. For example, in Notebook 1 I have: dbutils.widgets.dropdown("start_year", "2011", [str(x) for x in range(2008, 2021)], "Earliest year") start_year=dbutils.widgets.get("start_year") print("The start_year is " + dbutils.widgets.get("start_year")) The print statement correctly prints whatever year the user has selected. In Notebook 2, which runs Notebook 1 using %run, it will only print the default year, in this case 2011, no matter what is selected. What am I doing wrong? Thanks!
type: Question
tagged with: python

http://stackoverflow.com/comment/88709647
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50853397
has text: i have attached the images of the error i came through. Please see it ones

http://stackoverflow.com/a/50812967
has comment: http://stackoverflow.com/comment/88631659
has comment: http://stackoverflow.com/comment/88632106
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: One each way to handle this is simply to group together all of the types you want to match. isinstance will take a tuple of types as well as a single type: &gt;&gt;&gt; CollectionTypes = list, dict, set &gt;&gt;&gt; isinstance("", CollectionTypes) False &gt;&gt;&gt; isinstance({}, CollectionTypes) True &gt;&gt;&gt; If you do find a predefined type that matches exactly those three types and doesn't match str then you've locked yourself in and when later on you decide you also need tuple or some other types to be included in the match you are back to square one. That's why it is better here to be explicit about the types you are matching.
answers question: http://stackoverflow.com/q/50812799
accepted answer of: http://stackoverflow.com/q/50812799
has comment: http://stackoverflow.com/comment/88634168
score: 5
upvote count: 5

http://stackoverflow.com/q/50708607
type: UnansweredQuestion
tagged with: python
has body: I'm seeing some unexpected behavior when using lxml to parse the following HTML. Here's my Python 3 code: from lxml import etree, html s = """ ABC"<" and ">" """ doc = etree.ElementTree(html.fromstring(s)) print(etree.tostring(doc, pretty_print=True, encoding="unicode")) Here's the output I get: ABC"" Is there something I'm missing or doing wrong? Or is this a bug in lxml?
has title: Seeing unexpected behavior when using lxml to parse HTML
has comment: http://stackoverflow.com/comment/88455831
has comment: http://stackoverflow.com/comment/88426473
upvote count: 1
downvote count: 1
type: Question
score: 0
tagged with: lxml
answer count: 1
has answer: http://stackoverflow.com/a/50744563
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88446455

http://stackoverflow.com/a/50787970
downvote count: 0
has body: Although a Python solution is likely to give you a bit more flexibility with regards to formatting etc, the out-of-the-box keywords in Robot are sufficient to create the desired logic. See below for the code example and the output: *** Settings *** Library Collections *** Variables *** @{a} red blue green @{b} head eyes nose &amp;{DIC} a=${a} b=${b} *** Test Cases *** TC Log Structure ${DIC} *** Keywords *** Log Structure [Arguments] ${structure} Log To Console \n Log To Console ------------------------------ # For Loops only work on Lists, so get all the keys from the Dictionary ${keys} Get Dictionary Keys ${structure} :FOR ${item} IN @{keys} \ Log Many To Console ${item} ${structure["${item}"]} Log Many To Console [Arguments] ${name} ${list} Log To Console ${name} Log To Console ------------------------------ :FOR ${item} IN @{list} \ Log To Console ${item} Log To Console ------------------------------ This then results in the following console output: ============================================================================== ConsoleLog.ConsoleLog ============================================================================== TC ------------------------------ a ------------------------------ red blue green ------------------------------ b ------------------------------ head eyes nose ------------------------------ | PASS | ------------------------------------------------------------------------------ ConsoleLog.ConsoleLog | PASS | 1 critical test, 1 passed, 0 failed 1 test total, 1 passed, 0 failed
answers question: http://stackoverflow.com/q/50764478
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/88580921
has text: Thank you for the answer. Would you mind explaining why "The np.arange function does not fit to this scenario"? Thanks
type: Comment
comment on: http://stackoverflow.com/a/50787280
score: 0
type: AnswerComment

http://stackoverflow.com/q/50764572
possible better answer: http://stackoverflow.com/a/50767869
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/51987281
has answer: http://stackoverflow.com/a/50769835
type: AnsweredQuestion
has body: I have generated a .tflite model based on a trained model, I would like to test that the tfilte model gives the same results as the original model. Giving both the same test data and obtaining the same result.
tagged with: tensorflow-lite
has answer: http://stackoverflow.com/a/78508135
type: Question
has title: How can I test a .tflite model to prove that it behaves as the original model using the same Test Data?
linked to: http://stackoverflow.com/q/51267129
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51987281
linked to: http://stackoverflow.com/q/50443411
tagged with: python
upvote count: 32
has answer: http://stackoverflow.com/a/50767869
answer count: 4
linked to: http://stackoverflow.com/q/52057552
score: 32

http://stackoverflow.com/comment/88563107
comment on: http://stackoverflow.com/q/50777849
score: 2
type: Comment
type: QuestionComment
has text: Nope, none if it is working. I find it so strange that this can't be done. Yeah maybe its uncommon for people to switch between environment managers, but still ... the need _is_ conceivable.

http://stackoverflow.com/q/50789880
tagged with: pandas
has answer: http://stackoverflow.com/a/50789941
favorite count: 0
has answer: http://stackoverflow.com/a/50790250
has answer: http://stackoverflow.com/a/50790009
answer count: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/50789920
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50789941
linked to: http://stackoverflow.com/q/48333661
has answer: http://stackoverflow.com/a/50789920
has body: I have a dataframe, df: id_0 id_1 id_2 0 1 0 1 1 1 0 0 2 0 1 0 3 1 1 0 4 0 0 1 5 0 0 0 I want to get the column name for each row if there is 1. How to do that? Thank you. Result: result 0 id_0, id_2 1 id_0 2 id_1 3 id_0, id_1 4 id_2 5 NaN
duplicate of: http://stackoverflow.com/q/48333661
type: Question
upvote count: 4
has title: How to get the column name in pandas based on row values?
downvote count: 0
has answer: http://stackoverflow.com/a/50790061
tagged with: dataframe
score: 4

http://stackoverflow.com/comment/88705525
comment on: http://stackoverflow.com/q/50851359
score: 7
has text: Which version of Python are you on? if on Python 2 then you should inherit your class from `object`, `property` only works from new-style classes.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50878443
upvote count: 1
answers question: http://stackoverflow.com/q/50800885
score: 1
downvote count: 0
has body: You may use pycrypto: #!/usr/bin/env python # -*- coding: UTF-8 -*- import hashlib import base64 from Crypto import Random from Crypto.Cipher import AES BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s : s[0:-ord(s[-1])] class AESCipher: def __init__( self, key ): self.key = hashlib.sha256(key.encode('utf-8')).digest() def encrypt( self, raw ): raw = pad(raw) iv = Random.new().read( AES.block_size ) cipher = AES.new( self.key, AES.MODE_CBC, iv ) return base64.b64encode( iv + cipher.encrypt( raw ) ) def decrypt( self, enc ): enc = base64.b64decode(enc) iv = enc[:16] cipher = AES.new(self.key, AES.MODE_CBC, iv ) return unpad(cipher.decrypt( enc[16:] )) #password password="mypassword" #content global_report="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." #generate cipher cipher = AESCipher(bytes(password)) #encrypt encrypted = cipher.encrypt(bytes(global_report)) #show encrypted print encrypted #decrypt decrypted = cipher.decrypt(encrypted) #show decrypted print decrypted Which return: [binary] Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letras…
type: Answer

http://stackoverflow.com/a/50783981
downvote count: 0
answers question: http://stackoverflow.com/q/50783925
has comment: http://stackoverflow.com/comment/88574466
type: Answer
has comment: http://stackoverflow.com/comment/88574618
has comment: http://stackoverflow.com/comment/88574431
upvote count: 1
has comment: http://stackoverflow.com/comment/88574570
has comment: http://stackoverflow.com/comment/88574399
has comment: http://stackoverflow.com/comment/88578655
score: 1
has body: There is a rule of allocating threads when ever you are doing computational intensive work the number of threads should always be less then the no of cores in the machine.If the thread count is increased there will be race condition and your algo will take more time to give back result NoOfThreads &lt; NoOfCores you can use this code to check the number of cores import multiprocessing multiprocessing.cpu_count()
has comment: http://stackoverflow.com/comment/88574448
accepted answer of: http://stackoverflow.com/q/50783925
type: AcceptedAnswer

http://stackoverflow.com/comment/88836879
type: Comment
has text: Don't try to persuade OP which solution he sholud go for @demouser123. It's not a good practice. Let him decide what to do. Thanks.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50915048

python-2.7
tags question: http://stackoverflow.com/q/50814889
tags question: http://stackoverflow.com/q/50759980
tags question: http://stackoverflow.com/q/50730946
tags question: http://stackoverflow.com/q/50795324
tags question: http://stackoverflow.com/q/50837180
tags question: http://stackoverflow.com/q/50820844
tags question: http://stackoverflow.com/q/50731058
tags question: http://stackoverflow.com/q/50844331
tags question: http://stackoverflow.com/q/50824723
tags question: http://stackoverflow.com/q/50763147
tags question: http://stackoverflow.com/q/50783666
tags question: http://stackoverflow.com/q/50733329
tags question: http://stackoverflow.com/q/50752674
tags question: http://stackoverflow.com/q/50751520
tags question: http://stackoverflow.com/q/50757873
tags question: http://stackoverflow.com/q/50713316
tags question: http://stackoverflow.com/q/50817371
tags question: http://stackoverflow.com/q/50806693
tags question: http://stackoverflow.com/q/50802957
tags question: http://stackoverflow.com/q/50770394
tags question: http://stackoverflow.com/q/50752601
tags question: http://stackoverflow.com/q/50836997
tags question: http://stackoverflow.com/q/50787783
tags question: http://stackoverflow.com/q/50827300
tags question: http://stackoverflow.com/q/50747113
tags question: http://stackoverflow.com/q/50729090
tags question: http://stackoverflow.com/q/50783925
tags question: http://stackoverflow.com/q/50771322
tags question: http://stackoverflow.com/q/50838797
tags question: http://stackoverflow.com/q/50726520
tags question: http://stackoverflow.com/q/50805164
tags question: http://stackoverflow.com/q/50805588
tags question: http://stackoverflow.com/q/50724142
tags question: http://stackoverflow.com/q/50751819
tags question: http://stackoverflow.com/q/50785017
tags question: http://stackoverflow.com/q/50775969
tags question: http://stackoverflow.com/q/50725166
tags question: http://stackoverflow.com/q/50714025
tags question: http://stackoverflow.com/q/50806947
tags question: http://stackoverflow.com/q/50766229
tags question: http://stackoverflow.com/q/50732381
tags question: http://stackoverflow.com/q/50818539
tags question: http://stackoverflow.com/q/50749782
tags question: http://stackoverflow.com/q/50825906
tags question: http://stackoverflow.com/q/50761847
tags question: http://stackoverflow.com/q/50822383
tags question: http://stackoverflow.com/q/50844345
tags question: http://stackoverflow.com/q/50848191
tags question: http://stackoverflow.com/q/50787171
tags question: http://stackoverflow.com/q/50789288
tags question: http://stackoverflow.com/q/50767506
tags question: http://stackoverflow.com/q/50732765
tags question: http://stackoverflow.com/q/50779165
tags question: http://stackoverflow.com/q/50705660
tags question: http://stackoverflow.com/q/50841643
tags question: http://stackoverflow.com/q/50700158
tags question: http://stackoverflow.com/q/50767260
tags question: http://stackoverflow.com/q/50745486
tags question: http://stackoverflow.com/q/50751820
tags question: http://stackoverflow.com/q/50754517
tags question: http://stackoverflow.com/q/50808495
tags question: http://stackoverflow.com/q/50850840
tags question: http://stackoverflow.com/q/50753395
tags question: http://stackoverflow.com/q/50758637
tags question: http://stackoverflow.com/q/50795204
tags question: http://stackoverflow.com/q/50752283
tags question: http://stackoverflow.com/q/50737719
tags question: http://stackoverflow.com/q/50743261
tags question: http://stackoverflow.com/q/50712106
tags question: http://stackoverflow.com/q/50805485
tags question: http://stackoverflow.com/q/50728444
tags question: http://stackoverflow.com/q/50767714
tags question: http://stackoverflow.com/q/50723233
tags question: http://stackoverflow.com/q/50780461
tags question: http://stackoverflow.com/q/50709740
tags question: http://stackoverflow.com/q/50828295
tags question: http://stackoverflow.com/q/50748748
tags question: http://stackoverflow.com/q/50735972
tags question: http://stackoverflow.com/q/50801277
tags question: http://stackoverflow.com/q/50810879

http://stackoverflow.com/a/53407580
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50799238
downvote count: 0
has body: @cwurtz is right! To set order of the tasks you can use priority_weight task's parameter The pool parameter can be used in conjunction with priority_weight to define priorities in the queue, and which tasks get executed first as slots open up in the pool. (Read more)
type: Answer

http://stackoverflow.com/q/50828946
has comment: http://stackoverflow.com/comment/88662900
answer count: 1
favorite count: 0
tagged with: python-3.x
score: 0
has title: Issue with def function
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50829378
downvote count: 1
type: AnsweredQuestion
has body: I'm trying to create Exponential Moving average. However, the error code 'Series' object is not callable' appeared. This is my code. Can someone help? def CalculateEMA(window): sma = Close.rolling(window, min_periods=window).mean()[:window] rest = Close[window:] EMA_window=pd.concat([sma, rest]).ewm(span=window, adjust=False).mean() return EMA_window() CalculateEMA(60)
type: Question
has answer: http://stackoverflow.com/a/50829378
has comment: http://stackoverflow.com/comment/88662205
tagged with: pandas

http://stackoverflow.com/comment/88554958
comment on: http://stackoverflow.com/q/50773936
type: Comment
type: QuestionComment
has text: what is not workin as expected and what do you expect?
score: 1

http://stackoverflow.com/a/50767560
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50766148
has body: Answering my own question. Yes, the issue was in improper usage of Entropy parameter. To sign the message you need to generate a key, it consists of two parts (client entropy and server's entropy). They get combined with P_SHA1 algorithm into a key. To anyone who find this post in the future: for Python have a look on signxml library and section 4 of ws-trust spec.
accepted answer of: http://stackoverflow.com/q/50766148

http://stackoverflow.com/comment/88507796
type: QuestionComment
score: 1
has text: @ThomasMcDonald please correct all typos first. there is no j declared, there is no k declared yet you use them in the function. You should be seeing these errors when trying to run the code
comment on: http://stackoverflow.com/q/50749481
type: Comment

http://stackoverflow.com/comment/88438928
type: QuestionComment
comment on: http://stackoverflow.com/q/50714877
score: 0
has text: So if I want to control a program like Java then I should create a module as my Main class (say "main"). Then I shall import other modules and functions inside this main module. And I shall run python main.py. Am I right?
type: Comment

http://stackoverflow.com/q/50778174
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50778370
favorite count: 0
tagged with: pandas
tagged with: python
has body: After scraping a website, I ended up with a list which looks like this: data = ['\xa0header1', 'element1', 'element2', 'element3', '\xa0header2', 'element4', 'element5'] and so on. I want to create a panda dataframe with the data I scraped that looks like this: A B 0 element1 header1 1 element2 header1 2 element3 header1 3 element4 header2 4 element5 header2 So, basically, I want to show in the next column the header which is above a group of elements of the initial list. How can it be done, considering the special character in front of the headers makes it easy to look them up in the list?
has title: Pull headers from a list and create a DataFrame with headers side-by-side to list elements
upvote count: 2
score: 2
possible better answer: http://stackoverflow.com/a/50778885
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50778885
tagged with: dataframe
has answer: http://stackoverflow.com/a/50778370
type: Question

http://stackoverflow.com/q/50854924
has answer: http://stackoverflow.com/a/50855942
tagged with: git
has title: Push to remote repository
score: 2
tagged with: gitpython
type: AnsweredQuestion
has body: I have two repositories on github, using gitpython I'm trying to push a file from one repository to another remote repository. I've managed to do it using git but struggling with the gitpython code. git remote add remote_to_push git@bitbucket... git fetch remote_to_push git checkout remote_to_push/master git add file_to_push git commit -m "pushing file" git push remote_to_push HEAD:master I've managed to create a repo object of the remote I think with the following from git import Repo repo = Repo('path/to/other/git/repo') remote = repo.remotes.origin I can't figure out how to add something to then push, if i call remote.add("file_to_push") Then I get errors about the create() function TypeError: create() takes exactly 4 arguments (2 given) Trying to follow what they have done in How to push to remote repo with GitPython with remote.push(refspec='{}:{}'.format(local_branch, remote_branch)) I assume it should work with using master and master as the remote branches as they both must exist but it's giving me the error stderr: 'error: src refspec master does not match any.' Thanks
accepted answer: http://stackoverflow.com/a/50855942
linked to: http://stackoverflow.com/q/1456269
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/41836988
linked to: http://stackoverflow.com/q/41429525
upvote count: 2

http://stackoverflow.com/q/50820438
duplicate of: http://stackoverflow.com/q/45621722
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88646179
has answer: http://stackoverflow.com/a/50820478
possible better answer: http://stackoverflow.com/a/50820510
has answer: http://stackoverflow.com/a/50820510
downvote count: 1
type: Question
score: -1
has title: IndentationError: expected an indented block, what should I do?
accepted answer: http://stackoverflow.com/a/50820478
answer count: 2
has body: I'm currently writing some code in Python and whenever I try to run the program I get this error. Here is the code; if month == time.strftime("%m") and day == time.strftime("%d"): continue elif hour == time.strftime("%H") and minute != time.strftime("%M"): channelD["just_sent"] = False with open("data.json", "w") as write_file: json.dump(data, write_file) elif hour == time.strftime("%H") and minute == time.strftime("%M"): if just_sent = channelD["just_sent"]: continue else: channel = bot.get_channel(i) await bot.send_message(channel, content=channelD["message"]) print("24h message sent!")
upvote count: 0
favorite count: 0

http://stackoverflow.com/q/50767758
has title: How can I scrape this data? [BeautifulSoup4 with Python]
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/50769042
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50769042
has comment: http://stackoverflow.com/comment/88545728
type: Question
has comment: http://stackoverflow.com/comment/88546863
score: 0
has body: I've found a way to scrape other websites, but for this code it requires a special "browser" to access the html variables, thing is after I do this, the program doesn't crash, but no longer works. Variables I want: rank, name, code, points (https://i.sstatic.net/POMEz.jpg) This is the code that I made but it doesn't work on this website: [Runs but nothing reads/saves] from urllib.request import urlopen as uReq from urllib.request import Request from bs4 import BeautifulSoup as soup myUrl = "https://mee6.xyz/levels/159962941502783488" req = Request( myUrl, data=None, headers={ 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36' } ) uClient = uReq(req) pageHtml = uClient.read() uClient.close() page_soup = soup(pageHtml, "html.parser") containers = page_soup.findAll("div",{"class":"Player"}) print(containers) The code I used that did work was from a youtube tutorial, when changing the url it wont work with the mee6 leaderboard because it refuses the browser: [Crashes for the mee6 url] from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import csv my_url = "https://www.newegg.ca/Product/ProductList.aspx?Submit=ENE&amp;N=100007708%20601210955%20601203901%20601294835%20601295933%20601194948&amp;IsNodeId=1&amp;bop=And&amp;Order=BESTSELLING&amp;PageSize=96" uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") containers = page_soup.findAll("div",{"class":"item-container"}) filename = "GPU Prices.csv" header = ['Price', 'Product Brand', 'Product Name', 'Shipping Cost'] with open(filename, 'w', newline='') as f_output: csv_output = csv.writer(f_output) csv_output.writerow(header) for container in containers: price_container = container.findAll("li", {"class":"price-current"}) price = price_container[0].text.replace('\xa0', ' ').strip(' –\r\n|') brand = container.div.div.a.img["title"] title_container = container.findAll("a",…
answer count: 1
tagged with: beautifulsoup

http://stackoverflow.com/comment/88676374
has text: That has no effect at all.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50823133
type: Comment

http://stackoverflow.com/comment/88436673
comment on: http://stackoverflow.com/q/50713595
score: 1
type: QuestionComment
has text: Hard to know without see completely data, but maybe character problem of `DataetimeIndex` - `groupby` need create many small `5s` groups.
type: Comment

http://stackoverflow.com/comment/88715422
comment on: http://stackoverflow.com/q/50853900
score: 0
type: Comment
type: QuestionComment
has text: I'm not a python expert, but from what i tried, i get the same result for both version. I suspect the problem comes from encoding: in your login and password, are there any special chars that could mess it up?

google-app-engine
tags question: http://stackoverflow.com/q/50785764
tag name: google-app-engine
tags question: http://stackoverflow.com/q/50723498
type: Tag
tags question: http://stackoverflow.com/q/50849380
tags question: http://stackoverflow.com/q/50721890
tags question: http://stackoverflow.com/q/50752367
tags question: http://stackoverflow.com/q/50768023
tags question: http://stackoverflow.com/q/50738536
tags question: http://stackoverflow.com/q/50752283
tags question: http://stackoverflow.com/q/50707888
tags question: http://stackoverflow.com/q/50729516
tags question: http://stackoverflow.com/q/50736310

http://stackoverflow.com/comment/88522612
has text: `y_labeled = [elt.flatten() for elt in y_labeled]` should probably work? Or `for x in sublist.flatten()`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50757085

http://stackoverflow.com/q/50763971
type: AnsweredQuestion
has body: I'm currently working on a learner project for webscraping I've picked my site: https://www.game.co.uk/en/m/games/best-selling-games/best-selling-xbox-one-games/?merchname=MobileTopNav-_-XboxOne_Games-_-BestSellers#Page0 On this page, there is a button on the bottom that displays the list of the next 10 products there without this button being clicked it does not display the next batch of products however the URL does not change when the button is clicked. I wanted to ask how I will solve this dilemma using requests module. My code is below: import requests from bs4 import BeautifulSoup r = requests.get("https://www.game.co.uk/en/m/games/best-selling-games/best-selling-xbox-one-games/?merchname=MobileTopNav-_-XboxOne_Games-_-BestSellers") c = r.content soup = BeautifulSoup(c,"html.parser") all=soup.find_all("div",{"class":"product"}) for item in all: print(item.find({"h2": "productInfo"}).text.replace('\h2','').replace(" ", "")) print(item.find("span",{"class": "condition"}).text + " " + item.find("span",{"class": "value"}).text ) try: print(item.find_all("span",{"class": "condition"})[1].text + " " + item.find_all("span",{"class": "value"})[1].text ) except: print("No Preowned") print(" ")
has answer: http://stackoverflow.com/a/50764086
type: Question
has answer: http://stackoverflow.com/a/50764493
answer count: 2
possible better answer: http://stackoverflow.com/a/50764086
score: 0
accepted answer: http://stackoverflow.com/a/50764493
has title: Python Request Module - Displaying More Results
tagged with: web-scraping
tagged with: python
tagged with: python-requests

http://stackoverflow.com/a/50752272
has body: Actually The problem with the code is that python is getting confused with request flask has a module named request you are declaring a variable named request request = Requests.query.get(request_id) and using it over here job = Jobs.query.get(request.job_id) python is getting confused which request to use the variable you declared or the flask request module. simply change the variable name to something else
score: 2
answers question: http://stackoverflow.com/q/50752137
accepted answer of: http://stackoverflow.com/q/50752137
downvote count: 0
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88422028
has text: Are you rotating the rows or shifting zeros in?
comment on: http://stackoverflow.com/q/50706431
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88457740
score: 0
type: Comment
type: AnswerComment
has text: Is there any way to enable/disable that config right in the middle of the code? And how can I change the color of the logged queries? I tried using a formatter but it doesn't seem to help.
comment on: http://stackoverflow.com/a/50721074

http://stackoverflow.com/comment/88600780
type: QuestionComment
comment on: http://stackoverflow.com/q/50797275
has text: You should probably be using [`zip`](https://docs.python.org/3/library/functions.html#zip)
score: 0
type: Comment

http://stackoverflow.com/a/50845248
score: 0
has body: Lets imagine that your output is stored in variable x: &gt;&gt;&gt; print("\n".join([y.strip() for y in x])) 1.27 1.81 4.90 2.07 2.12 Would this help? Or you need a list in which case: &gt;&gt;&gt; print([y.strip() for y in x]) ['1.27', '1.81', '4.90', '2.07', '2.12'] [UPDATE] As for the Is data a list ? How to determine a Python variable&#39;s type?
type: Answer
answers question: http://stackoverflow.com/q/50845165

regex
tags question: http://stackoverflow.com/q/50807156
tags question: http://stackoverflow.com/q/50754474
tags question: http://stackoverflow.com/q/50813915
tags question: http://stackoverflow.com/q/50809409
tags question: http://stackoverflow.com/q/50849119
tags question: http://stackoverflow.com/q/50846719
tags question: http://stackoverflow.com/q/50777729
tags question: http://stackoverflow.com/q/50728614
tags question: http://stackoverflow.com/q/50820577
tags question: http://stackoverflow.com/q/50757504
tags question: http://stackoverflow.com/q/50792821
tag name: regex
tags question: http://stackoverflow.com/q/50790824
tags question: http://stackoverflow.com/q/50723581
tags question: http://stackoverflow.com/q/50743216
tags question: http://stackoverflow.com/q/50736281
tags question: http://stackoverflow.com/q/50794420
tags question: http://stackoverflow.com/q/50832864
tags question: http://stackoverflow.com/q/50710057
tags question: http://stackoverflow.com/q/50702625
tags question: http://stackoverflow.com/q/50806403
tags question: http://stackoverflow.com/q/50775629
tags question: http://stackoverflow.com/q/50764286
tags question: http://stackoverflow.com/q/50830909
tags question: http://stackoverflow.com/q/50839375
tags question: http://stackoverflow.com/q/50798431
tags question: http://stackoverflow.com/q/50803526
tags question: http://stackoverflow.com/q/50703077
tags question: http://stackoverflow.com/q/50734530
tags question: http://stackoverflow.com/q/50801118
tags question: http://stackoverflow.com/q/50808598
tags question: http://stackoverflow.com/q/50728444
tags question: http://stackoverflow.com/q/50721670
tags question: http://stackoverflow.com/q/50761538
tags question: http://stackoverflow.com/q/50756299
tags question: http://stackoverflow.com/q/50731359
tags question: http://stackoverflow.com/q/50813683
tags question: http://stackoverflow.com/q/50715769
tags question: http://stackoverflow.com/q/50799964
tags question: http://stackoverflow.com/q/50760826
tags question: http://stackoverflow.com/q/50786841
tags question: http://stackoverflow.com/q/50841210
tags question: http://stackoverflow.com/q/50755084
tags question: http://stackoverflow.com/q/50727776
tags question: http://stackoverflow.com/q/50718433
tags question: http://stackoverflow.com/q/50804656
tags question: http://stackoverflow.com/q/50782554
tags question: http://stackoverflow.com/q/50849547
tags question: http://stackoverflow.com/q/50775470
tags question: http://stackoverflow.com/q/50702947
tags question: http://stackoverflow.com/q/50715667
tags question: http://stackoverflow.com/q/50726973
tags question: http://stackoverflow.com/q/50835345
tags question: http://stackoverflow.com/q/50787621
tags question: http://stackoverflow.com/q/50825516
tags question: http://stackoverflow.com/q/50743106
tags question: http://stackoverflow.com/q/50753925
tags question: http://stackoverflow.com/q/50714289
tags question: http://stackoverflow.com/q/50714130
tags question: http://stackoverflow.com/q/50704350
tags question: http://stackoverflow.com/q/50728105
tags question: http://stackoverflow.com/q/50802059
tags question: http://stackoverflow.com/q/50699752
tags question: http://stackoverflow.com/q/50820087
tags question: http://stackoverflow.com/q/50793945
tags question: http://stackoverflow.com/q/50847976
tags question: http://stackoverflow.com/q/50833013
tags question: http://stackoverflow.com/q/50841724
tags question: http://stackoverflow.com/q/50724024
tags question: http://stackoverflow.com/q/50776079
tags question: http://stackoverflow.com/q/50751339
tags question: http://stackoverflow.com/q/50761951
tags question: http://stackoverflow.com/q/50730070
tags question: http://stackoverflow.com/q/50753804
tags question: http://stackoverflow.com/q/50722530
type: Tag
tags question: http://stackoverflow.com/q/50810846
tags question: http://stackoverflow.com/q/50785851

http://stackoverflow.com/a/50764896
type: Answer
answers question: http://stackoverflow.com/q/50760319
accepted answer of: http://stackoverflow.com/q/50760319
has body: First, your function should not take chr and ord as arguments. Instead, input your string and the amount by which you want to shift. A common way to implement a ciper is to use str.translate. from string import ascii_lowercase, ascii_uppercase, ascii_letters def cipher(text, shift): translation = str.maketrans( ascii_letters, ascii_lowercase[shift:] + ascii_lowercase[:shift] +\ ascii_uppercase[shift:] + ascii_uppercase[:shift] ) return text.translate(translation) secret_msg = cipher('Python is cool!', 1) # 'Qzuipo jt dppm!' Finally, since ciphering shifts characters by k, the inverse operation is simply to cipher by -k. msg = cipher('Qzuipo jt dppm!', -1) # Python is cool!
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50816513
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50814751
type: Answer
has body: You are specifying a whole op, but since ops can have more than one output you have to tell exactly which output you want. Try this: def encode(self, X): return self.sess.run(self.encoded, feed_dict={self.input.outputs[0]: X}) Alternatively, you can do: self.input = self.sess.graph.get_tensor_by_name("x:0")
accepted answer of: http://stackoverflow.com/q/50814751

http://stackoverflow.com/comment/88577058
type: QuestionComment
has text: How are you getting that pattern of `2nd element, 1st element, 1st element & 3rd element`? Or is it given as a separate indexing variable?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50785226

http://stackoverflow.com/comment/88519755
comment on: http://stackoverflow.com/a/50755547
score: 0
type: AnswerComment
type: Comment
has text: In the case of the question int is the appropriate. float won't work with // and the operator / will result in a float value instead of the desired int.

http://stackoverflow.com/comment/88666751
type: QuestionComment
has text: Judging from the picture you posted, there are no missing data. If you interpolate between two values that are both 0, the result will still be 0. As a general hint, make it easy for us to help you: it would be great to have the data sample in a form we can copy and paste to reproduce your error. Also, show the result you expected. Since nobody has your csv files, the code for data preparation is mostly meaningless for others. Maybe take a look at [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/50819549
score: 0
type: Comment

http://stackoverflow.com/comment/88636994
has text: You cannot change a value by reassigning a name (that points to that value) to another value. The best you can do is to create a _special_ object to act as a value and provide it an update method.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50816015

http://stackoverflow.com/comment/88530811
score: 0
type: Comment
has text: @Chris_Rands: I do not understand what you mean by an XY problem, but I can think of a few cases where this abstraction might come in handy. As a simplified context, consider a progress bar which for each iteration overwrites the last line (not using ncurses). When the loop is finished you want to write an \n, regardless of how it finished, such that the next time something is printed it appears on a new line.
type: QuestionComment
comment on: http://stackoverflow.com/q/50759630

http://stackoverflow.com/q/50786376
type: UnansweredQuestion
tagged with: opencv
has comment: http://stackoverflow.com/comment/88579510
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/88580386
has comment: http://stackoverflow.com/comment/88580900
score: 0
tagged with: python
has title: OpenCV2: Calculate gradient for color images
answer count: 0
has body: I am using the following Python code to apply Sobel derivatives to an image: image = scipy.ndimage.imread(FILE_NAME, True) image = image.astype('float64') gradx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3) grady = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3) The code works when I pass True to imread to convert to grayscale. When I decide to apply Sobel to each image component, I pass False and the array returned in empty. Is there a way to get gradient computed for each color component?

http://stackoverflow.com/comment/88623516
comment on: http://stackoverflow.com/q/50808799
score: 0
type: QuestionComment
type: Comment
has text: I want to have a single method or property that calls the underlying mixin methods or properties depending on which mixins are used. I don't know which mixins will be used ahead of time.

http://stackoverflow.com/comment/88581831
has text: yep, but it looks a little bit different to django CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Basic', 'enterMode': 2, }
comment on: http://stackoverflow.com/a/50711977
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50706313
type: Answer
answers question: http://stackoverflow.com/q/50705975
has comment: http://stackoverflow.com/comment/88421888
score: 0
has body: I would modify a select-sort to capture (n) as MAX instead of just one. and instead of running n2, just go thru the list once. so [9,1,2,11,8] you'd initialize with a MAX list [0,0,0] then loop thru your list plucking things that are bigger than MAX [9,0,0] [9,1,0] [9,1,2] [9,11,2] [9,11,8] the trickiest part is step 4 where you need to decide to keep 9, and 2 and replace 1 with 11.
has comment: http://stackoverflow.com/comment/88421834
has comment: http://stackoverflow.com/comment/88421759

http://stackoverflow.com/comment/88583668
score: 0
type: Comment
has text: The result df is not what I have, but is what my desired output is
type: QuestionComment
comment on: http://stackoverflow.com/q/50788167

http://stackoverflow.com/comment/88639882
type: QuestionComment
comment on: http://stackoverflow.com/q/50815597
score: 0
has text: I try read json files only: self.level_words = json.load(open("levels/level_"+str(self.level_number)+".json", 'r', encoding='utf8')) i add main.py and main.kv files in question.
type: Comment

http://stackoverflow.com/q/50806124
answer count: 2
downvote count: 0
has title: Selenium can't find element even after explicit waiting in an Ajax Page
favorite count: 0
tagged with: ajax
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88629896
tagged with: python
has answer: http://stackoverflow.com/a/50806304
tagged with: selenium-webdriver
score: 2
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/50806280
has body: I'm trying to automate updating fields in a web application. Thus the url does not change after logging in Here is my code so far from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC path_to_chromedriver = "C:/chromedriver" browser = webdriver.Chrome(executable_path=path_to_chromedriver) """Login Page""" login_url = "url" browser.get(login_url) username = browser.find_element_by_id("username") password = browser.find_element_by_id("password") username.send_keys("username") password.send_keys("password") browser.find_element_by_name("submit").click() """Application front page""" searchBar = browser.find_element_by_id("searchBar") searchBar.send_keys("item to be searched") button = browser.find_element_by_id("searchButton") button.click() """Click on item on search results""" #starting here, everything doesn't work wait = WebDriverWait(browser,10) item = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#item'))) item.click()#this never works as it just times out This site is a web application. I've printed out the page source after each click and it doesn't change after the homepage however in the Chrome browser it does change. Explicit and Implicit waits both do not work. Any suggestions? Thanks in advance --edit-- I'm a bit hesitant to post the html because it's a custom web app. However, the class of the body is "dhtmlx_winviewport" and the part of the web app that did change starts out with something like == $0 The thing I want to click on is a cell in a table title The error I am getting is Traceback (most recent call last): File "C:\script.py", line 45, in item = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'css'))) File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until rai…
has comment: http://stackoverflow.com/comment/88625602
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/88618294

http://stackoverflow.com/comment/88564213
type: QuestionComment
has text: @Ruthless Using one list to avoid looping will probably actually make it more difficult in the long run, since the semantics of parsing and iterating through 3 in a row in a noughts and crosses board are better oriented towards 2 dimensions.
comment on: http://stackoverflow.com/q/50778615
score: 0
type: Comment

http://stackoverflow.com/comment/88601544
type: Comment
comment on: http://stackoverflow.com/a/50784323
score: 0
type: AnswerComment
has text: Usually, using this search API, you do the same search to get new tweets, so yes you can get duplicates. So the best way should be to save in memory the last tweet you got, then use it in the next search with the "since_id" parameter. See : https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html

http://stackoverflow.com/a/51941728
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/90861751
answers question: http://stackoverflow.com/q/50708063
type: Answer
has body: Try to use user agent in chrome_options ua = UserAgent() userAgent = ua.random print(userAgent) chrome_options.add_argument('user-agent={userAgent}')
downvote count: 1

http://stackoverflow.com/comment/88438511
type: Comment
type: QuestionComment
has text: i am expecting the same. it works as above. thanks
comment on: http://stackoverflow.com/q/50713093
score: 0

http://stackoverflow.com/comment/88437599
has text: pass a file-object opened in append (`'a'`) mode. Better yet, ditch pandas (which is really over-kill here) and just use the `csv` module (which will still involve a file in append mode).
comment on: http://stackoverflow.com/q/50714181
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88572370
score: 0
comment on: http://stackoverflow.com/a/50782667
type: Comment
has text: It does not work, please don't answer if you are not sure.
type: AnswerComment

http://stackoverflow.com/comment/88696127
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50830065
has text: Thanks. Yes that makes sense. But I honestly don't know how to edit the definition for idxs in order to save the resulting boxes instead of just deleting some boxes. I'm not as good with python and I'm not exactly sure how to handlle those lists etc. Can you give me a hint how I need to edit that function? Also, I edited the definition of overlap to "max((w * h) / area[idxs[:last]], (w * h) / area[i]), so the overlap is compared to both the bigger and the smaller box. It doesn't make sense to me to just compare it to one of the boxes.
type: AnswerComment

http://stackoverflow.com/a/50798439
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50797819
answers question: http://stackoverflow.com/q/50797819
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/88628681
score: 1
has body: One approach is to set Unicode on your path. Ex: import os for i in os.listdir(u"C:\\Your\\Path\\Folder"): #I have used 'u' before the path print i Output: 26-देहजरी-P.txt

http://stackoverflow.com/a/50831083
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50831007
has body: You can also use regex. Ex: import pandas as pd df = pd.DataFrame({"Debit/Credit": ["-£7.50", "-£5.79", "-£28.50", "-£3.99", "-£17.99"]}) df["Debit/Credit"] = df["Debit/Credit"].str.extract("(\d*\.\d+)", expand=True).apply(pd.to_numeric) print(df) Output: Debit/Credit 0 7.50 1 5.79 2 28.50 3 3.99 4 17.99

http://stackoverflow.com/q/50824528
has body: I want groups based on three columns, but keep the original columns in the output(6 column). this link Actually did not help me. it just had three columns and grouped based on those three columns. this is a sample of my original data frame : Clinic Number Question Text Answer Text Answer Date year month dayofyear 1 1 bathing No 2006/7/1 2006 1 7 2 1 dressing No 2006/7/1 2006 1 7 3 1 feeding NO 2006/7/1 2006 1 7 4 1 housekeeping No 2006/7/1 2006 1 7 5 1 medications No 2006/7/1 2006 1 7 6 2 bathing No 2006/1/1 2006 1 1 7 2 dressing Yes 2006/1/1 2006 1 1 8 2 feeding Yes 2006/1/1 2006 1 1 9 2 housekeeping Yes 2006/1/1 2006 1 1 10 2 medications No 2006/1/1 2006 1 1 I want to group by [clinicNumber,Answer Text, Year,month], but I need other columns like Answer Date and question Text, yearOfday column, because later I want to do some calculation on them. What I did: this is the group by I am using on this dataframe to reach my goal. the problem is that there is no Answer date ,yearofyear ... in the output. grouped = data.groupby(['Clinic Number','year','month','Answer Text']).size().reset_index(name='counts') the output of this group by is like this: Clinic Number year month Answer Text counts 0 1 1999 5 No 6 1 1 2000 10 No 6 2 1 2000 2 No 6 3 1 2001 9 Yes 6 4 1 2002 2 Yes 8 5 1 2003 2 No 8 6 1 2004 4 No 8 7 1 2014 6 No 2 8 1 2015 10 No 2 5 2 2003 2 No 8 6 2 2004 4 No 8 7 2 2014 6 No 2 8 2 2015 10 No 2 Any help is appreciated :)
has title: How to GroupBy a Dataframe in Pandas and keep whole fields in the output
tagged with: data-analysis
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50824727
linked to: http://stackoverflow.com/q/31569549
type: Question
has answer: http://stackoverflow.com/a/50824727
tagged with: group-by
tagged with: dataframe
upvote count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/50862198
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50771552
type: AnsweredQuestion
type: Question
upvote count: 0
tagged with: qr-code
has body: This is png image: When I open it with Notepad++ I found that this is a QR code How to recover it, if python have any lib for this problem?
has title: How can I get a QR code from an encrypted image?
has answer: http://stackoverflow.com/a/50771788
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88550547
downvote count: 2
has comment: http://stackoverflow.com/comment/88554970
tagged with: python
score: -2
linked to: http://stackoverflow.com/q/27233351
accepted answer: http://stackoverflow.com/a/50771788
has comment: http://stackoverflow.com/comment/88550620

http://stackoverflow.com/a/50714837
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88438747
type: Answer
has body: >>> soup = BeautifulSoup(' \u20b9 1,990 ', 'lxml') >>> list(soup.div.strings) ['₹', '1,990']
has comment: http://stackoverflow.com/comment/88439478
accepted answer of: http://stackoverflow.com/q/50714663
answers question: http://stackoverflow.com/q/50714663

http://stackoverflow.com/comment/88422099
type: Comment
type: QuestionComment
has text: A link to the page would be very helpful. When you say scroll down, do you mean scroll down the page or are you referring to switching to another page/panel with more table data? e.g. when you scroll down, does the original table data remain or is it replaced with the new data?
comment on: http://stackoverflow.com/q/50703723
score: 0

http://stackoverflow.com/q/50701736
favorite count: 0
possible better answer: http://stackoverflow.com/a/61542941
linked to: http://stackoverflow.com/q/46528343
has comment: http://stackoverflow.com/comment/88517108
has answer: http://stackoverflow.com/a/61542941
has comment: http://stackoverflow.com/comment/88455816
has comment: http://stackoverflow.com/comment/88637050
has answer: http://stackoverflow.com/a/50832174
accepted answer: http://stackoverflow.com/a/50832174
tagged with: apache-beam
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88494834
has title: Start CloudSQL Proxy on Python Dataflow / Apache Beam
tagged with: cloud-sql-proxy
downvote count: 0
has body: I am currently working on a ETL Dataflow job (using the Apache Beam Python SDK) which queries data from CloudSQL (with psycopg2 and a custom ParDo) and writes it to BigQuery. My goal is to create a Dataflow template which I can start from a AppEngine using a Cron job. I have a version which works locally using the DirectRunner. For that I use the CloudSQL (Postgres) proxy client so that I can connect to the database on 127.0.0.1 . When using the DataflowRunner with custom commands to start the proxy within a setup.py script, the job won't execute. It stucks with repeating this log-message: Setting node annotation to enable volume controller attach/detach A part of my setup.py looks the following: CUSTOM_COMMANDS = [ ['echo', 'Custom command worked!'], ['wget', 'https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64', '-O', 'cloud_sql_proxy'], ['echo', 'Proxy downloaded'], ['chmod', '+x', 'cloud_sql_proxy']] class CustomCommands(setuptools.Command): """A setuptools Command class able to run arbitrary commands.""" def initialize_options(self): pass def finalize_options(self): pass def RunCustomCommand(self, command_list): print('Running command: %s' % command_list) logging.info("Running custom commands") p = subprocess.Popen( command_list, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # Can use communicate(input='y\n'.encode()) if the command run requires # some confirmation. stdout_data, _ = p.communicate() print('Command output: %s' % stdout_data) if p.returncode != 0: raise RuntimeError( 'Command %s failed: exit code: %s' % (command_list, p.returncode)) def run(self): for command in CUSTOM_COMMANDS: self.RunCustomCommand(command) subprocess.Popen(['./cloud_sql_proxy', '-instances=bi-test-1:europe-west1:test-animal=tcp:5432']) I added the last line as separate subprocess.Popen() within run() after reading this issue on Github from sthomp and this discussion on Stackoverflo. I also tried to play around with some parameters of subprocess…
has comment: http://stackoverflow.com/comment/88646820
score: 10
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/88526982
type: Question
has comment: http://stackoverflow.com/comment/88521440
has comment: http://stackoverflow.com/comment/88518387
has comment: http://stackoverflow.com/comment/88527311
linked to: http://stackoverflow.com/q/1196074
tagged with: google-cloud-sql
has answer: http://stackoverflow.com/a/71094782
has comment: http://stackoverflow.com/comment/88498855
answer count: 3
upvote count: 10
tagged with: python
has comment: http://stackoverflow.com/comment/88598699

http://stackoverflow.com/comment/88579918
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50786765
has text: This only produces indices, and presumes a sequence as the input (with a set length). You'd have to use `sequence[i]` to get to the actual `n`-th value of the input sequence.
score: 0

http://stackoverflow.com/a/50851923
answers question: http://stackoverflow.com/q/50851658
type: Answer
has body: image top right corner is origin X increase downwards Y increase from left to right top left corner is x1,y1 bottom left corner is x2,y2 so image[y1:y2,x1:x2] should give you the selected area of interest Image ROI
score: 0

http://stackoverflow.com/comment/88432289
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50711699
has text: @StephenRauch No it won't, certainly not as flexible as option 1!
type: Comment

http://stackoverflow.com/q/50712202
tagged with: performance
has title: Creating a new tuple vs indexing and assigning to an array
has body: Given the two data structures, Array and tuple, which is more complex, creating a new tuple or indexing and assigning a number to a particular index in an array. For example, given the tuple/array containing x, y. (0,0),[0,0] If you want to change the two x, y values, is it quicker to create a new tuple or to index and assign to the array? (0,1), [0, 1] does the most efficient data structure change with the length?
linked to: http://stackoverflow.com/q/626759
has comment: http://stackoverflow.com/comment/88433228
has comment: http://stackoverflow.com/comment/88433222
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: data-structures
favorite count: 0
type: Question
tagged with: time-complexity
score: 1
has comment: http://stackoverflow.com/comment/88433274
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88445056
has text: I use self.show()
score: 0
comment on: http://stackoverflow.com/q/50716794
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50826245
upvote count: 0
accepted answer: http://stackoverflow.com/a/50834418
favorite count: 0
has comment: http://stackoverflow.com/comment/88658046
has answer: http://stackoverflow.com/a/50834418
score: -3
tagged with: python
has title: Code exiting issue in Python 2.7
has comment: http://stackoverflow.com/comment/88657704
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50826998
downvote count: 3
has body: I am working on ROS and I have written a code in Python 2.7 and in the menu I am asking the user to select either option 1 or 2. After the task is accomplished, when I press Ctrl+c, instead of exiting the code, it displays the menu again, instead of exiting. Here again if I choose between 1 or 2, it keeps printing the menu again and again. What changes in the code would be suggested in order to exit the code as soon as I press Ctrl+c instead of displaying the menu again and again? The code and the screen shot of the problem are below: if __name__=='__main__': while(True): try: print "***********" print "1. Continuous" print "2. Single Step" print "***********" try: choice = int(raw_input('Choose a number between 1 &amp; 2: ')) number = choice move_group_python_interface() except ValueError: print "ERROR! Choose a number between 1 and 2" except rospy.ROSInterruptException: break
type: Question
tagged with: exit
has comment: http://stackoverflow.com/comment/88657705
tagged with: python-2.7
tagged with: rospy
answer count: 2
has answer: http://stackoverflow.com/a/50826998
tagged with: ros

http://stackoverflow.com/a/50852021
type: Answer
has comment: http://stackoverflow.com/comment/88707350
has comment: http://stackoverflow.com/comment/88707099
has comment: http://stackoverflow.com/comment/88707602
answers question: http://stackoverflow.com/q/50850724
has comment: http://stackoverflow.com/comment/88707528
has comment: http://stackoverflow.com/comment/88706840
has comment: http://stackoverflow.com/comment/88707394
has comment: http://stackoverflow.com/comment/88706707
has comment: http://stackoverflow.com/comment/88706890
has body: Pandas tries to detect the data type of a column, but sometimes fails as you noticed. You can force the data type of a column in read_csv like this: dataset = pd.read_csv('new_dataset.csv', dtype={'CLASS': str})
has comment: http://stackoverflow.com/comment/88707430
score: 0

http://stackoverflow.com/comment/88580900
type: Comment
comment on: http://stackoverflow.com/q/50786376
type: QuestionComment
has text: yes I did it both on a `jpeg` and a `png` image
score: 0

http://stackoverflow.com/comment/88552740
has text: OS? Python version?
comment on: http://stackoverflow.com/q/50772342
score: 0
type: Comment
type: QuestionComment

merge
tags question: http://stackoverflow.com/q/50777012
tags question: http://stackoverflow.com/q/50767717
tags question: http://stackoverflow.com/q/50849102
tags question: http://stackoverflow.com/q/50844688
tags question: http://stackoverflow.com/q/50744612
tags question: http://stackoverflow.com/q/50849178
tags question: http://stackoverflow.com/q/50706125
tags question: http://stackoverflow.com/q/50734036
tags question: http://stackoverflow.com/q/50847122
tags question: http://stackoverflow.com/q/50755238
tags question: http://stackoverflow.com/q/50750999
type: Tag
tags question: http://stackoverflow.com/q/50811084
tags question: http://stackoverflow.com/q/50718109
tag name: merge
tags question: http://stackoverflow.com/q/50793753
tags question: http://stackoverflow.com/q/50713109
tags question: http://stackoverflow.com/q/50749224
tags question: http://stackoverflow.com/q/50731253
tags question: http://stackoverflow.com/q/50794251

http://stackoverflow.com/a/50785754
downvote count: 0
has body: If you want to send information from Python to QML you must create a class that inherits from QObject and have a q-property to store that value, then export an object of that class to QML with setContextProperty(), and on the QML side it performs a binding as shown to continuation: main.py import sys from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, QUrl from PyQt5.QtGui import QGuiApplication from PyQt5.QtQml import QQmlApplicationEngine class Helper(QObject): textChanged = pyqtSignal() def __init__(self, parent=None): QObject.__init__(self, parent) self._text = "" @pyqtProperty(str, notify=textChanged) def text(self): return self._text @text.setter def text(self, v): if self._text == v: return self._text = v self.textChanged.emit() def send_file(self, file_content): self.text = file_content if __name__ == "__main__": app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() helper = Helper() engine.rootContext().setContextProperty("helper", helper) engine.load(QUrl.fromLocalFile('main.qml')) if not engine.rootObjects(): sys.exit(-1) helper.send_file("Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ornare magna felis. Nulla justo ipsum, finibus eu nibh quis, iaculis malesuada lorem. Phasellus et lacus malesuada, aliquam enim condimentum, efficitur sapien. Sed ultricies egestas massa, nec sodales neque mattis et. Praesent euismod pretium hendrerit. Maecenas non porttitor velit, non scelerisque quam. Phasellus at diam vel enim venenatis vulputate sed a nisl. Sed erat nunc, maximus varius justo vitae, vehicula porttitor enim. Maecenas vitae sem odio. Nunc interdum sapien vitae magna tempus, nec laoreet elit placerat. Nullam cursus metus facilisis pulvinar auctor.") sys.exit(app.exec_()) main.qml import QtQuick 2.10 import QtQuick.Window 2.2 import QtQuick.Controls 1.4 Window { id: mainWindow visible: true TextArea{ id: textArea anchors.fill: parent text: helper.text } }
score: 1
accepted answer of: http://stackoverflow.com/q/50782747
has comment: http://stackoverflow.com/comment/88828304
answers question: http://stackoverflow.com/q/50782747
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88613132

http://stackoverflow.com/q/50699944
tagged with: hungarian-algorithm
downvote count: 1
has body: This is the scenario : B1, B2, B3, B4, B5, B6 are blocks S1, S2, S3 are slots Each block can be put into specific slots. ie, B1 = ["S1","S2", "S3"] . Means B1 can be put in to these 3 slots. B2 = [S1, S2] B3 = [S3] You can make a product by taking one block from each slot - ie, the recipe for the product is (1 from S1) + (1 from S2 )+ (1 from S3) Need a function/algorithm to put these blocks in each slot to make maximum number of products. In the given example - B3 will be in S3 because B3 is allowed to put in only that slot. However, although B1 can be put in any 3 slots we should put in S1 because to make device we need S1 + S2 + S3 and B3 Can only be in S3. So the best way to distribute blocks among slots will be : B1-> S1, B2 -> S2, B3 -> S3 So we can make one product as per recipe ie, (1 from S1 + 1 from S2 +1 from S3 ) Example Input ============ block_slots = { "BLOCK1" : ["SLOT - 1","SLOT - 3", "SLOT - 2"], "BLOCK2" : ["SLOT - 1","SLOT - 3"], "BLOCK3" : ["SLOT - 1","SLOT - 3", "SLOT - 2"], "BLOCK4" : ["SLOT - 1","SLOT - 2"], "BLOCK5" : ["SLOT - 3", "SLOT - 2"], "BLOCK6" : ["SLOT - 1","SLOT - 3", "SLOT - 2"], "BLOCK7" : ["SLOT - 1","SLOT - 3", "SLOT - 2"], "BLOCK8" : ["SLOT - 1","SLOT - 3", "SLOT - 2"], "BLOCK9" : ["SLOT - 3", "SLOT - 2"], "BLOCK10" : ["SLOT - 3", "SLOT - 2"], "BLOCK11" : ["SLOT - 1"], "BLOCK12" : ["SLOT - 2"], } Output ========== { "BLOCK8": "SLOT - 1", "BLOCK9": "SLOT - 3", "BLOCK2": "SLOT - 1", "BLOCK3": "SLOT - 2", "BLOCK1": "SLOT - 3", "BLOCK6": "SLOT - 2", "BLOCK7": "SLOT - 1", "BLOCK4": "SLOT - 2", "BLOCK5": "SLOT - 3", "BLOCK10": "SLOT - 3", "BLOCK11": "SLOT - 1", "BLOCK12": "SLOT - 2" } &gt; 4 Blocks in each slot. 4 Products can be made from 12 blocks which is &gt; maximum yield. I tried the following code : blocks = { "B1" : ["S1","S3", "S2"], "B2" : ["S1","S3"], "B3" : ["S1","S3", "S2"], "B4" : ["S1","S2"], "B5" : ["S3", "S2"], "B6" : ["S1","S3", "S2"], "B7" : ["S1","S3", "S2"], "B8" : ["S1","S3", "S2"], "B9" : ["S3", "S2"] } slot_c…
tagged with: algorithm
has comment: http://stackoverflow.com/comment/88419231
has comment: http://stackoverflow.com/comment/88417943
has comment: http://stackoverflow.com/comment/88410544
has answer: http://stackoverflow.com/a/50700769
type: Question
has comment: http://stackoverflow.com/comment/88409529
answer count: 2
has title: Algorithm to get maximum yield
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88410610
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50700787
upvote count: 1

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

http://stackoverflow.com/comment/88567528
has text: I'm trying to do some thing like this https://www.youtube.com/watch?v=gCpCGkwwy8I&t=5s. I think before the program start, I will have it to send a serial data (a character B) over to arduino to initiate a scan. when the scan complete the arduino will response with a serial data (a character E) for the program to stop reading. The B and E above, I just add for simple value extract from each line, not to start or stop the reading/writing process. And yes, I haven't figure out how to start and stop reading value from serial port.
type: Comment
comment on: http://stackoverflow.com/q/50780220
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88535582
has text: Sorry, misinterpreted that part. What results do you want from grouping by dates?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50763898
type: AnswerComment

http://stackoverflow.com/comment/88560003
has text: I need help on this very badly... I'd really appreciate any kind of support
score: 0
comment on: http://stackoverflow.com/q/50766976
type: Comment
type: QuestionComment

http://stackoverflow.com/a/59605945
downvote count: 2
upvote count: 13
has comment: http://stackoverflow.com/comment/106251485
type: Answer
answers question: http://stackoverflow.com/q/50714469
has body: Use list comprehensions: (1) [f.name for f in p.glob("**/*")] # or (2) [f.name for f in p.rglob("*")] You can add if f.is_file() or if f.is_dir() to (1) or (2) if you want to target files only or directories only, respectively. Or replace "*" with some pattern like "*.txt" if you want to target .txt files only. See this quick guide.
has comment: http://stackoverflow.com/comment/127255884
score: 11
has comment: http://stackoverflow.com/comment/108991567

http://stackoverflow.com/q/50709020
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88429834
has comment: http://stackoverflow.com/comment/88437504
tagged with: python
answer count: 1
upvote count: 3
tagged with: dataframe
has answer: http://stackoverflow.com/a/51534964
downvote count: 0
has body: I am having a following DataFrame schema: | str_A | str_B | co_A | co_B | ... | co_X | where co_A and co_B stand for custom objects Those objects inherit object and have defined rich comparison methods FWIW: __hash__ method is also overriden and calls super().__hash__() What I want to do is to sort by the two custom columns and here is where the confusion comes. The following code works as expected: df.sort_values(by=['str_A', 'str_B']) The following code works as well: df.sort_values(by=['co_A']) but what doesn't work is: df.sort_values(by=['co_A', 'co_B']) which throws ValueError: Categorical categories must be unique And it turns out that some combinations of co_x and str_x do work, others do not. I thought it might be cause of mixed types and so I dropped the string values and left only the custom objects, the error persists. I am clueless here and I would appreciate any help. EDIT: I am using pandas version 0.23.0 To generate a simple data which I can reproduce the issue with, the following sample code can be used def feed(): return type('Feed', (), { attr: names.get_first_name() if attr.startswith('substr') else names.get_last_name() for attr in CPE_VERSION_ATTRIBUTE_LIST }) feed = [feed() for i in range(100)] EDIT2: I am using jupyter notebook, the CustomObject class is imported from a lib. What I did is I created another simple class directly in the jupyter with the similar methods as the original one to check whether there is something wrong with the data... and it worked. Which is even more confusing. There must be something wrong with the CustomObject class (I did not write the class, however, I can not find anything that could cause the issue). The class is supposed to handle version comparisons -- the specification can be found in the gist https://gist.github.com/CermakM/011f17e91ffe9efbe35f29738fb23ec2 EDIT3: Found the root cause of the issue, don't know how to solve it, yet Having implemented CustomObject like class CustomObject: def __init__(self, st…
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88427311
has title: pandas sort_values throws ValueError: Categorical categories must be unique
tagged with: pandas
score: 3
favorite count: 0

http://stackoverflow.com/a/50765181
score: 1
has body: First of all do not use str, it is a reserved word in Python and its use is considered bad programming practice. On the other hand in the case of QListView this is based on the MVC pattern, where the model has the information, the view shows it and the controller handles when and what information is displayed. In this case the model must be a class that inherits from QAbstractListModel, the easiest class to handle is QStandardItemModel, we create an object of that class and we establish it to QListView, after the information is added to the model, the model will internally notify the view causing it to update. class MainWindow(QMainWindow): ... def setupUi(self, Form): Form.setObjectName("Form") Form.resize(400, 300) self.listView = QtWidgets.QListView(Form) self.listView.setGeometry(QtCore.QRect(40, 40, 256, 192)) self.listView.setObjectName("listView") self.model = QtGui.QStandardItemModel() # &lt;---- self.listView.setModel(self.model) # &lt;---- self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) ... def updateReceivedDataDisplay(self, text): if text: it = QtGui.QStandardItem(text) self.model.appendRow(it)
upvote count: 1
has comment: http://stackoverflow.com/comment/88592776
answers question: http://stackoverflow.com/q/50759423
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50759423
type: Answer

dataframe
tags question: http://stackoverflow.com/q/50716573
tags question: http://stackoverflow.com/q/50747359
tags question: http://stackoverflow.com/q/50844688
tags question: http://stackoverflow.com/q/50749224
tags question: http://stackoverflow.com/q/50827227
tags question: http://stackoverflow.com/q/50782385
tags question: http://stackoverflow.com/q/50827164
tags question: http://stackoverflow.com/q/50824938
tags question: http://stackoverflow.com/q/50755079
tags question: http://stackoverflow.com/q/50837829
tags question: http://stackoverflow.com/q/50778190
tags question: http://stackoverflow.com/q/50705612
tags question: http://stackoverflow.com/q/50782047
tags question: http://stackoverflow.com/q/50720532
tags question: http://stackoverflow.com/q/50847246
tags question: http://stackoverflow.com/q/50839103
tags question: http://stackoverflow.com/q/50808943
tags question: http://stackoverflow.com/q/50811228
tags question: http://stackoverflow.com/q/50762963
tags question: http://stackoverflow.com/q/50833671
tags question: http://stackoverflow.com/q/50819486
tags question: http://stackoverflow.com/q/50836427
tags question: http://stackoverflow.com/q/50786266
tags question: http://stackoverflow.com/q/50768765
tags question: http://stackoverflow.com/q/50785197
tags question: http://stackoverflow.com/q/50847041
tags question: http://stackoverflow.com/q/50829764
tags question: http://stackoverflow.com/q/50772944
tags question: http://stackoverflow.com/q/50785729
tags question: http://stackoverflow.com/q/50809594
tags question: http://stackoverflow.com/q/50832334
tags question: http://stackoverflow.com/q/50827506
tags question: http://stackoverflow.com/q/50745224
tags question: http://stackoverflow.com/q/50800884
tags question: http://stackoverflow.com/q/50721324
tags question: http://stackoverflow.com/q/50748511
tags question: http://stackoverflow.com/q/50702033
tags question: http://stackoverflow.com/q/50767883
tags question: http://stackoverflow.com/q/50839992
tags question: http://stackoverflow.com/q/50774222
tags question: http://stackoverflow.com/q/50711432
tags question: http://stackoverflow.com/q/50798277
tags question: http://stackoverflow.com/q/50783863
tags question: http://stackoverflow.com/q/50781533
tags question: http://stackoverflow.com/q/50767452
tags question: http://stackoverflow.com/q/50718634
tags question: http://stackoverflow.com/q/50843370
tags question: http://stackoverflow.com/q/50822213
tags question: http://stackoverflow.com/q/50812299
tags question: http://stackoverflow.com/q/50723226
tags question: http://stackoverflow.com/q/50824528
tags question: http://stackoverflow.com/q/50709020
tags question: http://stackoverflow.com/q/50710987
tags question: http://stackoverflow.com/q/50756894
tags question: http://stackoverflow.com/q/50756563
tags question: http://stackoverflow.com/q/50807744
tags question: http://stackoverflow.com/q/50844535
tags question: http://stackoverflow.com/q/50740435
tags question: http://stackoverflow.com/q/50827039
tags question: http://stackoverflow.com/q/50789655
tags question: http://stackoverflow.com/q/50778174
tags question: http://stackoverflow.com/q/50838369
tags question: http://stackoverflow.com/q/50746726
tags question: http://stackoverflow.com/q/50747136
tags question: http://stackoverflow.com/q/50831061
tags question: http://stackoverflow.com/q/50748340
tags question: http://stackoverflow.com/q/50814482
tags question: http://stackoverflow.com/q/50776692
tags question: http://stackoverflow.com/q/50714449
tags question: http://stackoverflow.com/q/50826007
tags question: http://stackoverflow.com/q/50740176
tags question: http://stackoverflow.com/q/50719857
tags question: http://stackoverflow.com/q/50764548
tags question: http://stackoverflow.com/q/50805426
tags question: http://stackoverflow.com/q/50849087
tags question: http://stackoverflow.com/q/50750999
tags question: http://stackoverflow.com/q/50820254
tags question: http://stackoverflow.com/q/50842385
tags question: http://stackoverflow.com/q/50764576
tags question: http://stackoverflow.com/q/50709769

http://stackoverflow.com/comment/88588954
has text: Here's what I have so far, sorry I'm pretty new to python. https://pastebin.com/LRrfCkuB
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50786313

http://stackoverflow.com/q/50776081
upvote count: 1
score: 1
has body: I'm building an interface in Gtk3/Python3, using Glade, showing data from a ListStore in a TreeView, and letting the user edit the values in one of the columns. As said, I'm using glade, and in the glade file it's written which ListStore column serves what data for each GtkCellRenderer. The first funny thing is that I do not know how to get to this information, and I'm introducing redundancy in order to keep things working. Next more interesting trouble: when an edited cell loses focus, but focus stays in the TreeView, my callback for the edited signal is invoked and I can store the edited value in the ListStore. When an edited cell loses focus, and focus goes to a different widget (like in the further useless Button in the example), the registered callback is not invoked. Also if the window loses focus, the previous value is restored. This last one is particularly unpractical in the case 'focus-follows-mouse'. How can I synchronize the Gtk.TreeView with its ListStore? import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gdk class TestWindow: def __init__(self, builder): import os.path path, name = os.path.split(__file__) builder.add_from_file(os.path.join(path, "treeedit.glade")) builder.connect_signals(self) self.window = builder.get_object("window1") self.window.connect("destroy", Gtk.main_quit) self.notes_list = builder.get_object("notes_list") self.notes_list.append(('a',)) self.notes_list.append(('b',)) self.notes_list.append(('c',)) self.notes_list.append(('d',)) def on_cell_edited(self, widget, path, text): self.notes_list[path][0] = text def show_all(self): self.window.show_all() builder = Gtk.Builder() win = TestWindow(builder) win.show_all() Gtk.main() and this is the glade file: <?xml version="1.0" encoding="UTF-8"?> <requires lib="gtk+" version="3.20"/> <column type="gchararray"/> False dialog vertical 2 button True True False 12 True True True True notes_list False True value True <signal name="edited" hand…
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50776660
tagged with: glade
favorite count: 0
tagged with: python
tagged with: gtk
has title: Synchronize editable Gtk.TreeView with its ListStore
type: UnansweredQuestion

http://stackoverflow.com/a/50739932
has comment: http://stackoverflow.com/comment/88488667
accepted answer of: http://stackoverflow.com/q/50739402
answers question: http://stackoverflow.com/q/50739402
has comment: http://stackoverflow.com/comment/88488069
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/88487992
score: 1
has body: If I understand correctly, you want to compare each coordinate in the original dataframe with each target coordinate and get a dataframe of indicators true if the respective distance is under 2 km. Here is one approach. The key ingredient is scipy.spatial.distance.cdist that can compute pairwise distances. import pandas as pd import numpy as np from scipy.spatial.distance import cdist from haversine import haversine df = pd.read_csv( pd.compat.StringIO( """ID Time Latitude Longitude 1 2:00 60.092033 20.765083 1 3:00 60.097300 20.672767 1 4:00 60.125550 20.593650 1 5:00 60.115233 20.505367 1 6:00 60.103800 20.425850 1 7:00 60.113750 20.335717 1 8:00 60.115683 20.303683 1 9:00 60.114817 20.305500 1 10:00 60.077983 20.316917 1 11:00 60.034500 20.305317""" ), sep=r" +", ) targets = pd.DataFrame( [[60.103900, 20.415850], [60.403900, 20.715850]], columns=["Latitude", "Longitude"] ) res_data = ( cdist( df"Latitude", "Longitude", targets"Latitude", "Longitude", metric=haversine, ) &lt; 2 ) res_df = pd.DataFrame( res_data, index=df"Latitude", "Longitude".round(3).apply(tuple, axis=1), columns=targets"Latitude", "Longitude".round(3).apply(tuple, axis=1), ) Result: (60.104, 20.416) (60.404, 20.716) (60.092, 20.765) False False (60.097, 20.673) False False (60.126, 20.594) False False (60.115, 20.505) False False (60.104, 20.426) True False (60.114, 20.336) False False (60.116, 20.304) False False (60.115, 20.306) False False (60.078, 20.317) False False (60.034, 20.305) False False
has comment: http://stackoverflow.com/comment/88488300

http://stackoverflow.com/q/50787196
has answer: http://stackoverflow.com/a/50787778
answer count: 2
has comment: http://stackoverflow.com/comment/88581448
has answer: http://stackoverflow.com/a/50787787
has body: I want to merge this two data frames (with no common columns) one next to each other. The two dataframes look like this: df1: 10.74,5.71,5.41 11.44,6.1,5.87 df2: 10.17,6.58,5.23 9.99,5.75,5.13 11.21,6.35,5.72 10.3,5.86,5.12 I am trying with: df_total=pd.concat([df1,df2],axis=1) But the result looks something like this: Access grade global,Grade_global,Regression_global,Access grade,Grade,Regression ,,,10.74,5.71,5.41 ,,,11.44,6.1,5.87 10.17,6.58,5.23,,, 9.99,5.75,5.13,,, 11.21,6.35,5.72,,, 10.3,5.86,5.12,,, And I what to have something like this: 10.17,6.58,5.23,10.74,5.71,5.41 9.99,5.75,5.13,11.44,6.1,5.87 11.21,6.35,5.72 10.3,5.86,5.12 The two things I want to know how to do are: 1- How can I merge the 2 data frames so that the values are next to each other (the number of rows should, therefore, be the maximum number of rows between the two dataframes; 4 in this case). 2- How to avoid having NaN (you can see that in the end there are multiple commas). (I want to avoid this because afterwards in the scatter plot I use, all the Nan are plotted as 0 (so I have a line of dots in y=0)). The Nan values are generating zeros. Please see the result: The html snipped is: The lines that best approximate the expected grades according to the access grade to University and comparing all students with {{user.hsname}}' students are: All the chart: With grades_acess_hs.csv: Access grade global,Grade_global,Regression_global,Access grade,Grade,Regression ,,,10.74,5.71,5.41 ,,,11.44,6.1,5.87 ,,,11.21,6.35,5.72 ,,,10.3,5.86,5.12 10.17,6.58,5.23,,, 9.99,5.75,5.13,,, 10.96,5.84,5.71,,, 9.93,6.12,5.09,,, 9.93,6.0,5.09,,, 11.21,6.22,5.86,,, 11.28,6.1,5.9,,, ,,,10.93,6.08,5.54 Thanks in advance!
has comment: http://stackoverflow.com/comment/88581218
tagged with: c3.js
has comment: http://stackoverflow.com/comment/88580757
tagged with: pandas
has title: Uniting two data frames
tagged with: python
linked to: http://stackoverflow.com/q/49620538
tagged with: d3.js
type: UnansweredQuestion
type: Question
tagged with: charts
has comment: http://stackoverflow.com/comment/88581021
score: 0

http://stackoverflow.com/comment/88550154
type: QuestionComment
has text: Thanks, @101, this concept is new to me. I will have a look at it.
comment on: http://stackoverflow.com/q/50771171
score: 0
type: Comment

http://stackoverflow.com/comment/88517453
score: 1
type: AnswerComment
type: Comment
has text: Calling `self.sort()` will just restart sorting the same list you're in the middle of sorting, which will just lead to infinite recursion. It won't sort the left half, which is what the OP is trying to do. I agree that the `print` is not a great design, but it is useful for debugging purposes, so maybe that's why he did it? But `print(sort(x))` is not good either. In Python, functions that mutate objects in-place usually don't return those objects. Just like `list.sort()` doesn't return the sorted `self`, it's idiomatic for `MergeSort.sort()` to not return _its_ sorted `self.array`.
comment on: http://stackoverflow.com/a/50754703

http://stackoverflow.com/comment/88674854
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50835478
has text: Why would you want to do this? Maybe a dictionary with the desired position as the index is more appropriate for your problem.
type: Comment

http://stackoverflow.com/a/50793352
type: Answer
score: 5
upvote count: 5
has body: [item['code'] for item in jsonData] will return list of codes.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50793321
answers question: http://stackoverflow.com/q/50793321

http://stackoverflow.com/a/50822355
type: Answer
has comment: http://stackoverflow.com/comment/88650916
upvote count: 6
has body: You were almost there but you need the .values as the list of array and then provide the column names. pd.DataFrame(pd.DataFrame({ k : df.loc[df['A'] == k, 'B'].values for k in df['A'].unique() }), columns=df['A'].unique()) Output: a b 0 6 8 1 7 9
has comment: http://stackoverflow.com/comment/88650068
has comment: http://stackoverflow.com/comment/88650100
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50822213
answers question: http://stackoverflow.com/q/50822213
score: 6

http://stackoverflow.com/comment/88699721
comment on: http://stackoverflow.com/q/50848109
type: QuestionComment
has text: [How to apply a function to each sublist of a list in python?](https://stackoverflow.com/a/43357135/1248974)
type: Comment
score: 1

http://stackoverflow.com/comment/88413602
type: Comment
type: QuestionComment
has text: Are you properly shuffling your training data? Something like this can happen if the data is not shuffled: Your model will only see inputs of a certain class and get used to those (getting better, reducing loss), and at some point training reaches the point in the data where it switches to the other class, which will heavily reduce performance (since the model is biased towards the other class at that point).
comment on: http://stackoverflow.com/q/50700481
score: 0

http://stackoverflow.com/q/50707709
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88425627
tagged with: ttk
score: 0
has body: I designed a chatbot interface but the entry row looks very narrow, so I want to make it widen (2 rows) . I tried with rowspan=2 but it's the same. Below is my code. self.usr_input = ttk.Entry(self, width=100, state='normal') self.usr_input.grid(column=0, row=10, rowspan=2, sticky='nwsw', padx=3, pady=3)
tagged with: tkinter-entry
tagged with: python-3.x
has title: Entry widget row expansion in tkinter
has comment: http://stackoverflow.com/comment/88424635

screen-scraping
tags question: http://stackoverflow.com/q/50782619
tags question: http://stackoverflow.com/q/50790248
type: Tag
tags question: http://stackoverflow.com/q/50830491
tag name: screen-scraping
tags question: http://stackoverflow.com/q/50746909

http://stackoverflow.com/comment/88709527
has text: It's good point. There's many ppl that thinking like you - they only use `View` for writing CBV. I can understand that way - more intuitive way. But as you know, python-django is for more effective. Also, RESTful way is one of standard way for web. (I guess you still have CRUD way in your single page) So django provide that way for more efficiency I guess. If you write ListView on your own way, it has lot more lines for simple `ListView` in CBV.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50851789

http://stackoverflow.com/a/50747144
has body: average = np.average(px1 + px2 + px3 + px4 + px5 + px6 + px7 + px8 + px9) is acutally summing over the values not averaging those, average = (px1 + px2 + px3 + px4 + px5 + px6 + px7 + px8 + px9)/9 should give you what you want. Also for doing such task, scipy.signal.convolve2d is the best tool. See doc and example below. https://www.google.com/search?q=scipy.signal.convolve2d&amp;oq=scipy.signal.convolve2d&amp;aqs=chrome..69i57j69i60&amp;sourceid=chrome&amp;ie=UTF-8
answers question: http://stackoverflow.com/q/50747064
has comment: http://stackoverflow.com/comment/88502944
has comment: http://stackoverflow.com/comment/88501990
score: 2
has comment: http://stackoverflow.com/comment/88502869
has comment: http://stackoverflow.com/comment/88502709
type: Answer
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/88502656
has comment: http://stackoverflow.com/comment/88502796
has comment: http://stackoverflow.com/comment/88502915

http://stackoverflow.com/a/50714069
has comment: http://stackoverflow.com/comment/88477142
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88477131
has body: I think need simply loop, especially if want avoid apply and many columns: cols = ['start_d','end_d'] for c in cols: df[c] = pd.to_datetime(df[c],errors='coerce').dt.strftime('%Y-%b-%d') If need list comprehension is necessary concat because result is list of Series: comp = [pd.to_datetime(df[c],errors='coerce').dt.strftime('%Y-%b-%d') for c in cols] df = pd.concat(comp, axis=1) But still here is possible solution with apply: df[cols]=df[cols].apply(lambda x: pd.to_datetime(x ,errors='coerce')).dt.strftime('%Y-%b-%d')
accepted answer of: http://stackoverflow.com/q/50713833
has comment: http://stackoverflow.com/comment/88477013
type: Answer
answers question: http://stackoverflow.com/q/50713833

http://stackoverflow.com/q/50827458
tagged with: url
linked to: http://stackoverflow.com/q/3813735
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50833180
has comment: http://stackoverflow.com/comment/88659500
has title: looping url's with 'for' loop and string vs integer problems
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88659449
tagged with: web-scraping
type: Question
has body: trying to figure out how to loop urls with a "for" loop (or any other loop for that matter) I'm data scraping Howlongtobeat.com the url's are structured like this: https://howlongtobeat.com/game.php?id=38050 where only the number at the end of "id=" changes, how do I get the end of the string to change numbers?? page_number = range (38040, 38060) url = 'https://howlongtobeat.com/game.php?id={page_number}' this isn't working because I'm not adding to the string and url = 'https://howlongtobeat.com/game.php?id=' + page_number isn't working because I'm getting this errror TypeError: must be str, not range FYI using beautifulsoup and csv writer to scrap the data and write it to a csv I'm a beginner at this stuff so start from the top Thanks!!!!!!!
score: 0
answer count: 1

http://stackoverflow.com/comment/88581325
has text: I modified your question a bit using info from your comment [over here](https://stackoverflow.com/questions/50775083/python-vectorized-difference-of-dates-in-1-million-row-table/50776287?noredirect=1#comment88576707_50776287). Please check that I haven't changed the intended meaning of your question.
type: Comment
comment on: http://stackoverflow.com/q/50786484
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88620442
comment on: http://stackoverflow.com/q/50807175
score: 0
has text: My mistake, that was left over from actual code, I've edited to make it consistent within the example.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88603466
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50798045
has text: It goes through that for loop 2 times because there's two layers ! len(parameters) = 4 and I divide it by 2. The values of "grads" are the gradients of each parameters, so that this for loop updates each parameters
score: 0

http://stackoverflow.com/q/50732046
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17703239
tagged with: python
has body: Is it possible to build a SQLAlchemy relationship that will accept any instance that inherits from the same Base? Ideally, it maintains one foreign key for the instance's ID and a second foreign key for the instance's type. As an example, this Variable class has a relationship applies_to between itself and the Car class. # some overhead, for completeness from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, Session from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:') session = Session(bind=engine) Base = declarative_base() # defining my classes class Variable(Base): __tablename__ = 'variables' id = Column(Integer, primary_key=True) name = Column(String) value = Column(Integer) applies_to_id = Column(Integer, ForeignKey('cars.id')) applies_to = relationship('Car') class Car(Base): __tablename__ = 'cars' id = Column(Integer, primary_key=True) class Truck(Base): __tablename__ = 'trucks' id = Column(Integer, primary_key=True) Base.metadata.create_all(engine) With it, I can make a Car and a Variable for that car and commit to the database. car = Car() var1 = Variable(name="speed", value=50, applies_to=car) session.add(car) session.add(var1) session.commit() But I cannot do a similar thing with Truck and Variable. truck = Truck() var2 = Variable(name="speed", value=50, applies_to=truck) session.add(truck) session.add(var2) session.commit() AssertionError: Attribute 'applies_to' on class '&lt;class '__main__.Variable'&gt;' doesn't handle objects of type '&lt;class '__main__.Truck'&gt;' I would like to edit the Variable class to support Truck and any other classes that inherit from Base through the applies_to relationship. EDIT: Similar to sqlalchemy generic foreign key (like in django ORM), but that solution requires all classes to inherit from the HasAddresses mixin and handles a backref via addresses on those classes. Is there a solution that…
answer count: 0
score: 1
upvote count: 1
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/88473926
has title: SQLAlchemy relationship to any class
has comment: http://stackoverflow.com/comment/88500798
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88473897

http://stackoverflow.com/comment/88654670
type: Comment
has text: Actually, to be properly portable, the first line should be `#!/bin/bash` if you want to use Bash-only features like the `source` synonym to the POSIX portable command `.` (dot).
comment on: http://stackoverflow.com/a/50823791
type: AnswerComment
score: 1

http://stackoverflow.com/comment/88680043
comment on: http://stackoverflow.com/a/50835985
type: Comment
has text: Don't rush in posting solutions till not sure they work.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50733662
has body: Lets say I have 2 lines of code like this: a = [1 , 2 , 3 , 4] print (a) Now I want to add something to this code to give the user 2 options: 1: press "Enter" to continue. In this case the code should print "a" 2: press "Esc" to exit the program. In this case the program should be stopped (e.g. exit the code). I need to mention that I only want to use these 2 keys (Enter&amp;Esc) NOT any key I have been palying with raw_input and sys.exit but it did not work. Any idea how I can do it in this example? Thanks!
has title: How to "continue" OR "exit" the program by pressing keys
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50733869
tagged with: python
tagged with: user-input
score: 4
tagged with: sys
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50733869
tagged with: user-controls
has comment: http://stackoverflow.com/comment/88475063
upvote count: 4

http://stackoverflow.com/a/50885498
accepted answer of: http://stackoverflow.com/q/50844709
type: Answer
upvote count: 1
has body: I made a series of changes which resulted in the build compiling and running correctly. First, pyinstaller is missing a 'hook' file for pandas, so one must be manually created. For me the hook folder was located here: "C:\Users\natha\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\PyInstaller\hooks" Inside that folder I created a file named hook-pandas.py and the only contents of that file was one line: hiddenimports = ['pandas._libs.tslibs.timedeltas'] I did install the Windows 10 SDK, but I'm not sure if that was just part of the problem, or what it affected if anything. My program was made up of multiple modules, because I like to separate different types of processes in different files. However, to simplify things I combined all my code to one .py file and had just one other file that contained my PyQt5/Qt Designer auto-generated GUI code. I removed all imports that read like from x.y import z I received errors in a few builds where it seemed like pyinstaller didn't recognize those things. So I kept things very straight-forward, like import PyQt5 Lastly, when I went to compile the build, using the -p command, I added two file paths; one pointed to the root location of my program, which is where the other module(the PyQt5 module) was saved and the second path was to "C:\Users\natha\AppData\Local\Programs\Python\Python36-32\Lib\site-packages". Once these things are in place, compile completed normally and the build runs perfectly. So in summary, the keys to success here are: -Ensure there is a hook-pandas.py file IF pandas is being used in your script -Ensure the hook-pandas.py file contains this line: hiddenimports = ['pandas._libs.tslibs.timedeltas'] -And be sure -p command is used to direct pyinstaller to where your custom modules and any python packages are saved. My -p command read like this: -p C:\Users\natha\Desktop\Python_Projects\CompEval\code:C:\Users\natha\AppData\Local\Programs\Python\Python36-32\Lib\site-packages Notice the colon separatin…
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50844709

http://stackoverflow.com/q/50763704
has comment: http://stackoverflow.com/comment/88535805
answer count: 1
has body: models.py class Product(models.Model): product_name = models.CharField(max_length=32) quantity = models.IntegerField() remarks = models.TextField(blank=True) class Vendor(models.Model): vendor_name = models.CharField(max_length=50) address = models.CharField(max_length=100) bill_no = models.CharField(max_length=8) product = models.ManyToManyField(Product) serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class VendorSerializer(serializers.ModelSerializer): product = ProductSerializer(many=True, read_only=False) class Meta: model = Vendor fields = '__all__' views.py from rest_framework import viewsets class VendorViewset(viewsets.ModelViewSet): serializer_class = VendorSerializer queryset = Vendor.objects.all() How do I override writable create() method on VendorSerializer to add products details to vendors where products are from the related to Vendor?
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: writable create() method in drf serializers
type: Question
has comment: http://stackoverflow.com/comment/88535701
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/50764750
has comment: http://stackoverflow.com/comment/88536120
score: 0

mysql
tags question: http://stackoverflow.com/q/50790682
tags question: http://stackoverflow.com/q/50708061
tags question: http://stackoverflow.com/q/50751820
tags question: http://stackoverflow.com/q/50807129
tags question: http://stackoverflow.com/q/50833873
tags question: http://stackoverflow.com/q/50818766
tags question: http://stackoverflow.com/q/50798353
tag name: mysql
tags question: http://stackoverflow.com/q/50759886
tags question: http://stackoverflow.com/q/50810204
tags question: http://stackoverflow.com/q/50748753
tags question: http://stackoverflow.com/q/50782134
tags question: http://stackoverflow.com/q/50722535
tags question: http://stackoverflow.com/q/50850655
tags question: http://stackoverflow.com/q/50815217
tags question: http://stackoverflow.com/q/50751990
tags question: http://stackoverflow.com/q/50850868
tags question: http://stackoverflow.com/q/50756389
tags question: http://stackoverflow.com/q/50815562
tags question: http://stackoverflow.com/q/50854898
tags question: http://stackoverflow.com/q/50709916
tags question: http://stackoverflow.com/q/50784439
tags question: http://stackoverflow.com/q/50699737
tags question: http://stackoverflow.com/q/50817695
tags question: http://stackoverflow.com/q/50733466
tags question: http://stackoverflow.com/q/50751008
tags question: http://stackoverflow.com/q/50840869
tags question: http://stackoverflow.com/q/50740392
type: Tag
tags question: http://stackoverflow.com/q/50807088
tags question: http://stackoverflow.com/q/50743230
tags question: http://stackoverflow.com/q/50719532
tags question: http://stackoverflow.com/q/50730264
tags question: http://stackoverflow.com/q/50738955
tags question: http://stackoverflow.com/q/50836908
tags question: http://stackoverflow.com/q/50805061
tags question: http://stackoverflow.com/q/50789262
tags question: http://stackoverflow.com/q/50817496
tags question: http://stackoverflow.com/q/50778983
tags question: http://stackoverflow.com/q/50810495
tags question: http://stackoverflow.com/q/50745794
tags question: http://stackoverflow.com/q/50800487
tags question: http://stackoverflow.com/q/50728615
tags question: http://stackoverflow.com/q/50754100
tags question: http://stackoverflow.com/q/50703550

http://stackoverflow.com/a/50782994
downvote count: 0
has body: Sounds like you are looking for a[:, 0:3]: In [4]: a[:, 0:3] Out[4]: array([[ 1, 2, 3], [ 6, 7, 8], [11, 12, 13]])
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50782980
answers question: http://stackoverflow.com/q/50782980
type: Answer
has comment: http://stackoverflow.com/comment/88572566
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88573052

http://stackoverflow.com/comment/88620981
comment on: http://stackoverflow.com/a/50807614
score: 0
type: AnswerComment
has text: isn't a simple `while True` + `break` at the and of the `try` block doing exactly that (instead of manually dealing with a `fail` bool)?
type: Comment

http://stackoverflow.com/a/50774140
has comment: http://stackoverflow.com/comment/88555239
accepted answer of: http://stackoverflow.com/q/50774055
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50774055
has body: Create DatetimeIndex of removed values first with date_range and union, then select only difference with original index: idx = pd.date_range('2018-01-04','2018-01-08').union(['2018-01-12']) df = HAO_10.loc[HAO_10.index.difference(idx)] #another similar solutions #df = HAO_10.drop(idx, errors='ignore') #df = HAO_10[~HAO_10.index.isin(idx)] If want working with dates only and index contains also times floor is your friend: df = HAO_10.loc[HAO_10.index.floor('d').difference(idx)] #another similar solutions #df = HAO_10[~HAO_10.index.floor('d').isin(idx)] print (df) Price 2018-01-02 30.240000 2018-01-03 30.629999 2018-01-09 31.309999 2018-01-10 31.400000 2018-01-11 31.580000 2018-01-16 31.200001 Your solution should be simlify: df = HAO_10[((HAO_10.index &lt; '2018-01-04') | ((HAO_10.index &gt; '2018-01-08') &amp; (HAO_10.index != '2018-01-12')))]
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/50844379
accepted answer: http://stackoverflow.com/a/50844560
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88692345
downvote count: 0
possible better answer: http://stackoverflow.com/a/50844537
type: Question
has answer: http://stackoverflow.com/a/50844560
tagged with: split
favorite count: 0
has answer: http://stackoverflow.com/a/50844893
has answer: http://stackoverflow.com/a/50844458
upvote count: 3
tagged with: pandas
has body: I have a column "Nome_propriedade" with complete addresses, such as establishment name, streets, neighborhood, city and state It always ends with the name of the city and state. With this pattern: Nome_propriedade "Rod. BR 386, bairro Olarias/Conventos, Lajeado/RS" "Fazenda da Várzea - zona rural, Serro/MG" "Cidade do Rock - Jacarepaguá, Rio de Janeiro/RJ" "Área de extração de carnaúba - Povoado Areal, zona rural, Santa Cruz do Piauí/PI" "Pastelaria - Av. Vicente de Carvalho, 995, Loja Q, Vila da Penha, Rio de Janeiro/RJ" I want to create two new columns, "city" and "state", and fill them with the last values found in column "Nome_propriedade". I also want to stip those away from Nome_propiedade. Nome_propriedade City State Rod. BR 386, bairro Olarias/Conventos Lajeado RS Fazenda da Várzea - zona rural Serro MG Cidade do Rock - Jacarepaguá... Rio de Janeiro RJ Área de extração de carnaúba - Povoado A... Santa Cruz do Piauí PI Pastelaria - Av. Vicente de Carvalho, 99... Rio de Janeiro RJ Please anyone know how I can create these two columns? I can not do a general split because I just want to separate the city and state information. Other information may remain unchanged.
tagged with: python
has title: Split a column in pandas twice to multiple columns
answer count: 4
has answer: http://stackoverflow.com/a/50844537
has comment: http://stackoverflow.com/comment/88692265
has comment: http://stackoverflow.com/comment/88694011

http://stackoverflow.com/a/50767814
has body: You've got a few different things going on. For the dtypes issue, in the read_csv documentation there are a few examples about specifying types. You'll want to use dtype as the argument name, not what you have (i.e. df7.dtypes). For the attribute error, it's because you're assigning a string to that variable. Namely, df9 = 'PL.csv' means that df9 is now a string. Try printing it and you'll see that df9 prints PL.csv. The NoneType errors are because Python never got to df8 and df9. (NoneType generally means that something went wrong and the variable doesn't exist yet.)
has comment: http://stackoverflow.com/comment/88619869
score: 0
answers question: http://stackoverflow.com/q/50766016
type: Answer

http://stackoverflow.com/a/50765522
type: Answer
has body: You can use re.findall: import re with open('tree_file.txt') as f, open('word_list.txt', 'a') as f1: f1.write('\n'.join(set(re.findall("[a-zA-Z\-\.'/]+", f.read())))) When running the code above on the text, the output is: make not gorgeously the Conan than so huge and co-writer/director Peter st is can Schwarzenegger expanded even trilogy Middle-earth Segal continuation column vision 's he '' Damme adequately that greater Steven Rock Jackson Rings a Tolkien Van be words going to new Jean-Claud or elaborate of splash Lord The Arnold describe destined J.R.R. Century
accepted answer of: http://stackoverflow.com/q/50765499
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50765499
has comment: http://stackoverflow.com/comment/88538935
has comment: http://stackoverflow.com/comment/88539081
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88538691

http://stackoverflow.com/q/50808053
score: 0
tagged with: django-queryset
answer count: 1
has comment: http://stackoverflow.com/comment/88641399
has answer: http://stackoverflow.com/a/50821555
tagged with: python
accepted answer: http://stackoverflow.com/a/50821555
has title: How to show user only available field of model?
type: AnsweredQuestion
tagged with: django-views
has comment: http://stackoverflow.com/comment/88622226
has comment: http://stackoverflow.com/comment/88642555
has comment: http://stackoverflow.com/comment/88641470
tagged with: django-forms
has comment: http://stackoverflow.com/comment/88623164
type: Question
has body: I have two models car and booking. A car is ForeignKey field in booking model if car is booked then in car list its still showing available . I have is_available_car model field in car model default=True. If car is booked then it will not show till it's unbooked. i am haviing booking form in car is foreign key and after user booked the car its still showing the car . Help me please. Thank you. Model class Booking(models.Model): booking_name = models.CharField(max_length=240, null=False) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' ) book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car') booking_start_date = models.DateTimeField(auto_now_add=True, blank=False) booking_end_date = models.DateTimeField(blank=True, null=True) rental_price = models.IntegerField(blank=False, null=False) times_pick = models.TimeField(blank=True) is_approved = models.BooleanField(default=False) def __str__(self): return self.booking_name def get_absolute_url(self): return reverse("buggy_app:detail",kwargs={'pk':self.pk}) Views .py class BookingView(FormView): template_name = 'buggy_app/booking.html' form_class = BookingForm models = Booking def form_valid(self, form): form.save() return super(BookingView, self).form_valid(form) success_url = reverse_lazy('index') def get_context_data(self, **kwargs): # kwargs['car'] is the car booking now! try: kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', '')) except (Car.DoesNotExist, ValueError): kwargs['car'] = None return super(BookingView, self).get_context_data(**kwargs) def get_initial(self): initial = super(BookingView, self).get_initial() if 'car' in self.request.GET: try: initial['book_car'] = Car.objects.get(id=self.request.GET['car']) except (Car.DoesNotExist, ValueError): pass return initial class CarListView(ListView): context_object_name = 'cars' model = models.Car def get_queryset(self): qs = super(CarListView, self).get_queryset() qs = qs.f…
tagged with: django-models
has comment: http://stackoverflow.com/comment/88641337

http://stackoverflow.com/comment/125496453
type: Comment
has text: This is a noobie question. What does it mean for a method to be generated at runtime?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50765010

http://stackoverflow.com/a/50772314
has comment: http://stackoverflow.com/comment/88552085
downvote count: 0
answers question: http://stackoverflow.com/q/50772282
has body: Generaly your new code is imposible convert to DataFrame, because: pd.unique(dataAll'Frequency', 'Period', 'Date'.values.ravel('K')) create one big 1d numpy array, so after remove duplicates is impossible recreate rows. E.g. if there are 2 unique values 3 and 1 is impossible find which datetimes are for 3 and for 1. But if there is only one unique value for Frequency and for each Period is possible find Date like in sample, solution is possible. EDIT: One possible alternative is use dask.dataframe.DataFrame.drop_duplicates.
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88552098
has comment: http://stackoverflow.com/comment/88552127
has comment: http://stackoverflow.com/comment/88552401
upvote count: 1

http://stackoverflow.com/comment/88733763
has text: Yes but I already know how many PCs I have to keep. The problem still to find the important features for PCA(n_components = 2), maybe I didn't get your point. Suppose I keep 3 PCs, do I have to look at the 3rd raw of "pca.componets_" to have the relevance of each original feature for those PCs I want to keep?
comment on: http://stackoverflow.com/a/50845697
type: AnswerComment
score: 2
type: Comment

http://stackoverflow.com/q/50793753
has body: I'm trying to implement merge sort in Python that sorts either in ascending or in descending order depending on the parameter you give it. I got it working with 2 separate functions but I can't get it to work in one function. def mergeSort(L, ascending = True): print('Mergesort, Parameter L:') print(L) result = [] if len(L) == 1: return L mid = len(L) // 2 teilliste1 = mergeSort(L[:mid], ascending) teilliste2 = mergeSort(L[mid:], ascending) x, y = 0, 0 while x &lt; len(teilliste1) and y &lt; len(teilliste2): if ascending: if teilliste1[x] &gt; teilliste2[y]: result.append(teilliste2[y]) y = y + 1 else: result.append(teilliste1[x]) x = x + 1 else: if teilliste1[x] &lt; teilliste2[y]: result.append(teilliste2[y]) y = y + 1 else: result.append(teilliste1[x]) x = x + 1 result = result + teilliste1[x:] result = result + teilliste2[y:] return result mergeSort(list, True) # sort in ascending order mergeSort(list, False) # sort in descending order Just flipping the > in the if-statement will make it descending but if I try doing both in one function, it always messes up my result. Any suggestions?
has comment: http://stackoverflow.com/comment/88595116
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88594019
tagged with: python
tagged with: merge
has title: Python: Merge Sort in ascending and descending order
score: 0
has comment: http://stackoverflow.com/comment/88593824
type: Question
has answer: http://stackoverflow.com/a/50796823
tagged with: mergesort
tagged with: sorting
has comment: http://stackoverflow.com/comment/88594398
has comment: http://stackoverflow.com/comment/88594152
has comment: http://stackoverflow.com/comment/88593950
answer count: 1

http://stackoverflow.com/q/50703496
tagged with: beautifulsoup
tagged with: python
has body: I'm trying to extract the text inside from the following html structure: Text to extract I have the following Beautiful Soup code to do it: from bs4 import BeautifulSoup as bs soup = bs(html, "lxml") div = soup.find("div", {"class": "account-age"}) span = div.children[1].children[0].children[0] text = span.get_text() Unfortunately, Beautiful Soup is throwing the error: 'list_iterator' object is not subscriptable. How can I fix this to extract the text I need?
possible better answer: http://stackoverflow.com/a/50703677
has answer: http://stackoverflow.com/a/50703672
answer count: 4
has answer: http://stackoverflow.com/a/50703677
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50703757
downvote count: 0
has title: Python BeautifulSoup: 'list_iterator' object is not subscriptable
type: Question
score: 3
has answer: http://stackoverflow.com/a/50703641
accepted answer: http://stackoverflow.com/a/50703641
upvote count: 3
favorite count: 0

global
type: Tag
tags question: http://stackoverflow.com/q/50784959
tag name: global
tags question: http://stackoverflow.com/q/50801277
tags question: http://stackoverflow.com/q/50747181

http://stackoverflow.com/comment/88467754
type: Comment
has text: `player_position` is a function which does not return anything. You need to keep track of the position with a variable and update it each time you change direction.
type: QuestionComment
comment on: http://stackoverflow.com/q/50729916
score: 0

http://stackoverflow.com/a/50847936
downvote count: 0
has body: Actually, pip should be installed by default. In case something special happens, try to download get-pip.py Then run the following (which may require administrator access): python get-pip.py in terminal (To have administrator access rights, simply type sudo su in terminal, and enter your password) Please reference: https://askubuntu.com/questions/597906/how-to-install-pip-and-a-python-package-for-self-installed-python
answers question: http://stackoverflow.com/q/50847721
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/q/50853136
score: 28
favorite count: 0
accepted answer: http://stackoverflow.com/a/59163225
tagged with: python
has comment: http://stackoverflow.com/comment/88717494
type: AnsweredQuestion
tagged with: pca
has title: R internal handling of sparse matrices
type: Question
has comment: http://stackoverflow.com/comment/89572779
has comment: http://stackoverflow.com/comment/88768368
answer count: 1
downvote count: 0
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/59163225
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/88742346
tagged with: http://stackoverflow.com/tag/r
upvote count: 28
has comment: http://stackoverflow.com/comment/89564982
has body: I have been comparing the performance of several PCA implementations from both Python and R, and noticed an interesting behavior: While it seems impossible to compute the PCA of a sparse matrix in Python (the only approach would be scikit-learn's TruncatedSVD, yet it does not support the mean-centering required to be equivalent to a covariance solution for PCA. Their argumentation is, that it would destroy the sparsity property of the matrix. Other implementations like Facebook's PCA algorithm or the PCA/randomPCA method in scikit learn do not support sparse matrices for similar reasons. While all of that makes sense to me, several R packages, like irlba, rsvd, etc., are able to handle sparse matrices (e.g. generated with rsparsematrix), and even allow for specific center=True arguments. My question is, how R handles this internally, as it seems to be vastly more efficient than the comparable Python implementation. Does R still maintain the sparsity by doing Absolute Scaling instead (which would theoretically falsify the results, but at least maintain sparsity)? Or is there any way in which the mean can be stored explicitly for the zero values, and is only stored once (instead of for every value separately)? To get put off hold: How does R internally store matrices with mean-centering without exploding RAM usage. Hope that is concise enough....

http://stackoverflow.com/q/50843263
downvote count: 2
has body: I tried to use pandas.DataFrame.replace() to fill empty strings in a frame via the code below. main_datasets = [train_data, test_data, alt_data1, alt_data2] for data in main_datasets: for x in data: if type(x) == 'int': x.fillna(x.median(), inplace = True) elif type(x) == 'float': x.fillna(x.median(), inplace = True) else: x.replace(to_replace = None, value = 'N/A', inplace = True) However, I continue to receive the following exception, despite using characters or numbers for the keyword value and removing the keyword name: TypeError: replace() takes no keyword arguments Why is this error raised from "value = 'N/A?'" Here is an ad hoc sample of some fields (separated by commas): 12123423, 0, M, Y, 120432.5 12654423, 1, F, N, 80432.5 12123423, 0, M, Y, 120432.5 12123423, 0, M, Y, 120432.5
has comment: http://stackoverflow.com/comment/88690098
has answer: http://stackoverflow.com/a/50843573
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50843478
tagged with: pandas
favorite count: 0
has title: How to use the replace() method with keyword arguments to replace empty strings
has comment: http://stackoverflow.com/comment/88690334
tagged with: python
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88539106
score: 0
type: Comment
type: QuestionComment
has text: I looked over that article, and it was helpful! It wasn't quite what I was asking but it definitely helped with my understanding of how the input function works. Thanks!
comment on: http://stackoverflow.com/q/50765431

http://stackoverflow.com/a/50745106
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88499282
has body: Initialise T as a placeholder. T = tf.placeholder(tf.float32, [2, 2]) When starting your session, compute T and pass it in through a feed_dict: with tf.Session() as sess: a, b = .3, .4 inp = np.array([[1 - a, b], [a, 1 - b]]) sess.run(optimizer, feed_dict={T : inp}) Where optimizer is the node that minimizes your cost function.
upvote count: 1
answers question: http://stackoverflow.com/q/50744841
type: Answer

http://stackoverflow.com/comment/88582031
has text: Yes except in your link spyder is 3.2.8
type: AnswerComment
comment on: http://stackoverflow.com/a/50787763
type: Comment
score: 0

http://stackoverflow.com/a/50717723
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50716971
type: Answer
upvote count: 1
has body: A simple way would that the special method __repr__ delegates the actual processing to a recursive method. To avoir clutterin the interface, that method could have a name starting with an underscore (_). Code could be: class Node(object): def __init__(self, data): self.data = data self.parent = None self.children = [] def add_child(self, obj): self.children.append(obj) obj.parent = self.data def __repr__(self): return self._do_repr(0) def _do_repr(self, indent_increase): indent = " " print_data = (indent * indent_increase) + "Node " + str(self.data) if self.children: print_data += " ↴" + "\n" for child in self.children: print_data += child._do_repr(indent_increase + 1) else: print_data += '\n' return print_data This gives as expected: Node 1 ↴ Node 2 Node 3 ↴ Node 4 Node 5

http://stackoverflow.com/comment/88410561
comment on: http://stackoverflow.com/a/50699471
type: Comment
has text: Probably, but is it actually an issue? None of these edge cases break the intuitive comparison operators. If you need to check that it fits a float, then do a `float(a)` and catch the exception.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/125214765
score: 0
type: Comment
has text: PyCharm (JetBrains) which is a very popular, very good IDE. It could be something in my environment to do with recently installing anaconda and messing up my PATHs etc... But I don't have any issues with any other packages and I code a lot on many different projects daily.. (and purged Anaconda from PATH)
type: AnswerComment
comment on: http://stackoverflow.com/a/50851671

http://stackoverflow.com/comment/88648468
type: QuestionComment
comment on: http://stackoverflow.com/q/50820029
score: 0
type: Comment
has text: [reading-binary-file-and-looping-over-each-byte](https://stackoverflow.com/questions/1035340/reading-binary-file-and-looping-over-each-byte)

http://stackoverflow.com/comment/88565950
comment on: http://stackoverflow.com/q/50778953
score: 0
type: Comment
type: QuestionComment
has text: Can you fathom how much code you've dumped here? I'm _not_ going to go through it, there's just too much. Provide a [mcve] that demonstrates just the problem you're trying to solve, and nothing more.

http://stackoverflow.com/a/50782065
has comment: http://stackoverflow.com/comment/88572785
has comment: http://stackoverflow.com/comment/88572997
downvote count: 0
has body: Well, you have some problems in creating elements. I will first provide the fixed code and then explain: from tkinter import * def part_search(): # The sole purpose of this function is to update elements, not creating them. mtext = ment.get() print(mtext) mlabel2.config(text=mtext) msearch = open(r"Parts.txt") print('again') for line in msearch: if mtext in line: listbox.insert(END, str(line)) listbox.config(yscrollcommand=scrollbar.set,width=0, justify=LEFT) scrollbar.config(command=listbox.yview) msearch.close() return # This code is your original code for creating the first elements mGui = Tk() mGui.configure(bg="orange") ment = StringVar() mGui.geometry ("1000x500+200+300") mGui.title ("Parts Finder") mlabel1 = Label(mGui, text="Type in search term", font="Times 20", bg="orange") mlabel1.pack() mentry = Entry(textvariable=ment, font="Times 20", width = 50, bg="orange") mentry.pack() mentry.focus() mlabel3 = Label(mGui, text="Now click GO", font="Times 20", bg="orange") mlabel3.pack() mbutton = Button(mGui, text ="Go", font="Times 20", command = part_search, bg="grey") mbutton.pack() # here is the moved code from the function Finder = () scrollbar = Scrollbar(mGui) scrollbar.pack(side=RIGHT, fill=Y) listbox = Listbox(mGui) listbox.pack(fill=BOTH, expand=1) listbox.configure(justify=CENTER, bg="orange", font="Times 16") mlabel2 = Label(mGui) mlabel2.pack() while True: # ball.draw() mGui.update_idletasks() mGui.update() What happened? In your code, inside the part_search function, you've created elements and displayed them inside the UI. Then, each call, you create those elements again and stack them in your layout. They have just disappeared and were below you listbox. Another thing is that you've set a full height listbox which pushed your Label below the bottom of the window. You should use the Tk layout schemes (Stacking, griding, etc.). See official documentation here How can I avoid this type of errors? You should separate the code that creates the UI and the…
type: Answer
answers question: http://stackoverflow.com/q/50781833
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88572971

http://stackoverflow.com/a/50799383
has body: The problem is not that complicated if you are familiar with SQL :) The following code should do the trick : #Given your dataframe : df TripID time Latitude SectorID sector_leave_time 0 42.0 7.0 52.5 5.0 8.0 1 42.0 8.0 52.6 5.0 8.0 2 42.0 9.0 52.7 6.0 10.0 3 42.0 10.0 52.8 6.0 10.0 4 5.0 9.0 50.1 2.0 10.0 5 5.0 10.0 50.0 2.0 10.0 6 5.0 11.0 49.9 1.0 12.0 7 5.0 12.0 49.8 1.0 12.0 # Get the Latitude corresponding to time = sector_leave_time df_max_lat = df.loc[df_merged.time==df.sector_leave_time, ['TripID', 'Latitude', 'SectorID']] # Then you have : TripID Latitude SectorID 1 42.0 52.6 5.0 3 42.0 52.8 6.0 5 5.0 50.0 2.0 7 5.0 49.8 1.0 # Add the max latitude to original dataframe applying a left join pd.merge(df, df_max_lat, on=['TripID', 'SectorID'], how='left', suffixes=('','_sector_leave')) # You're getting : TripID time Latitude SectorID sector_leave_time Latitude_sector_leave 0 42.0 7.0 52.5 5.0 8.0 52.6 1 42.0 8.0 52.6 5.0 8.0 52.6 2 42.0 9.0 52.7 6.0 10.0 52.8 3 42.0 10.0 52.8 6.0 10.0 52.8 4 5.0 9.0 50.1 2.0 10.0 50.0 5 5.0 10.0 50.0 2.0 10.0 50.0 6 5.0 11.0 49.9 1.0 12.0 49.8 7 5.0 12.0 49.8 1.0 12.0 49.8 There you go :)
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50798446
type: Answer

http://stackoverflow.com/comment/88523550
type: AnswerComment
comment on: http://stackoverflow.com/a/50754826
score: 0
type: Comment
has text: Thanks for your help @Roushan. I understood it now.

http://stackoverflow.com/comment/88627606
type: QuestionComment
comment on: http://stackoverflow.com/q/50811084
has text: Can you explain why the last two entries of your dictionary aren't combined? Seems to break your pattern
score: 0
type: Comment

http://stackoverflow.com/q/50751672
tagged with: foursquare
tagged with: checkin
tagged with: python
linked to: http://stackoverflow.com/q/22390776
has body: I use the following code to get details of a venue (with venue ID: 412d2800f964a520df0c1fe3) in my local PyCharm Edu: import json, requests url = 'https://api.foursquare.com/v2/venues/' CLIENT_ID = 'XYZ' # I replace "XYZ" using my real CLIENT ID CLIENT_SECRET = 'XYZ' # I replace "XYZ" using my real CLIENT SECRET id='412d2800f964a520df0c1fe3' params = dict( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, v='20180323' ) resp = requests.get(url=url+id, params=params) data = json.loads(resp.text) with open('resp_detail.json', 'a') as the_file: dumped=json.dumps(data) the_file.write("%s\n" % dumped) The returned checkin statistics are: "stats": { "tipCount": 1672, "usersCount": 0, "checkinsCount": 0, "visitsCount": 0}. However, when I use the online trial interface (https://foursquare.com/developers/explore#req=venues%2F49eeaf08f964a52078681fe3%3F) to get details of a venue for the same venue ID, the return results are: "stats": { "tipCount": 389 "usersCount": 16762 "checkinsCount": 25938 "visitsCount": 32866 } The online results should be correct since this venue is Central Park, New York and it should get lots of checkins. I don't know what is wrong with my code. Foursquare even didn't post a sample code for "get details of a venue". Could anyone help to correct my code? Thank you so much!!
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50753067
score: 0
has answer: http://stackoverflow.com/a/50753067
answer count: 2
possible better answer: http://stackoverflow.com/a/53924999
has title: Foursquare API returns zero checkinsCount check-in counts in Python, but returns non-zero value in online trial interface
has answer: http://stackoverflow.com/a/53924999

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

http://stackoverflow.com/q/50702186
type: UnansweredQuestion
has title: Finding exact hsv values for colors with green and purple in opencv
tagged with: python
tagged with: opencv
score: 1
linked to: http://stackoverflow.com/q/31460267
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/88414279
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88415968
answer count: 0
has body: I am tring to detect the plant with the colors of green and purple using opencv color detection. I have done it for the green color, but I am unable to get the exact lower range and upper range of the color green + purple. The values I have used would detect all the colors in the image. Values: lower_purple = np.array([[80, 10, 10]]) upper_purple = np.array([120, 255, 255]) How can I get the exact hsv range of the values for each color.
duplicate of: http://stackoverflow.com/q/31460267

http://stackoverflow.com/comment/88477382
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50734157
has text: I have edited the answer, I have troubles with mergeasof

http://stackoverflow.com/comment/88458208
has text: @DanielRoseman that field same on my models called foo bar
score: 0
comment on: http://stackoverflow.com/q/50724655
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88654293
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50824532
has text: I have a dataframe of Tweets. If a Tweet was geocoded, I have marked that Tweet with a True (if it has been geocoded) or False (If it has not been geocoded). What I'm trying to do is check if the column is True, print out that row. Else if that row is False, then send it into my for loop to be geocoded. I will edit the original post for an input.
score: 0

http://stackoverflow.com/a/50803126
score: 0
answers question: http://stackoverflow.com/q/50802824
has body: @Petpan, you can use list comprehension to fulfill your need. You should not use list comprehension for this. Try it online at http://rextester.com/QBQDO38144. list_1 = ['rwww corp\pan 2323 2018-23-23 0% c:\program files\pa.txt', 'rwww corp\pand 2323 2018-23-23 0% c:\program files\monkey.txt', 'c:\program files\pa.txt', 'c:\program files\pex2.txt', 'c:\program files\pex5.txt', 'c:\program files\pex4.txt', ] list_2 = ['c:\program files\pa.txt', 'c:\program files\pex2.txt', 'c:\program files\pex3.txt',] # You should not use list comprehension for this purpose # It will print items in list_1 if it also exists in list_2 [print(e, 'exists in list_1') for e in list_2 if e in list_1] &raquo; Output c:\program files\pa.txt exists in list_1 c:\program files\pex2.txt exists in list_1
type: Answer

http://stackoverflow.com/a/50849748
has body: I would expand out the index into multiple columns when first creating the DataFrame. You can try to look at the code here for inspiration: https://github.com/gseastream/pyomo/blob/fa9b8f20a0f9afafa7cbd4607baa8b4963a96f42/pyomo/repn/plugins/excel_writer.py Grant was working on an interface to Excel, but development priorities shifted elsewhere. Also, a quick note: you can use model.component_objects(Var) instead of what you have with list(set(block_vars)).
answers question: http://stackoverflow.com/q/50841644
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50841644
type: Answer

http://stackoverflow.com/comment/88566674
comment on: http://stackoverflow.com/a/50772253
type: AnswerComment
score: 0
type: Comment
has text: are these angles relative to the origin (0, 0, 0)? I am trying to translate the idea to using 3D points.

http://stackoverflow.com/q/50720165
has body: when we use curl or urlopen with facet to execute queries, we get a nested dictionary with 3 elements 1. responseHeader 2. response 3. facet_counts I want to show the facet_counts while using Pysolr search. It just shows the 'response' value of the query output. I'm trying the following code, please help. import pysolr conn = pysolr.Solr('http://localhost:8983/solr/') result = conn.search('enron', **{ 'fl' : 'body', 'facet' : 'on' }) for r in result: print r
has comment: http://stackoverflow.com/comment/88449224
accepted answer: http://stackoverflow.com/a/50720925
has comment: http://stackoverflow.com/comment/88449084
answer count: 1
has answer: http://stackoverflow.com/a/50720925
score: 0
has title: How to do facet search with Pysolr
tagged with: python
tagged with: solr
tagged with: pysolr
has comment: http://stackoverflow.com/comment/88449332
has comment: http://stackoverflow.com/comment/88449611
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/50763627
downvote count: 0
accepted answer: http://stackoverflow.com/a/50764432
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88535776
score: 5
possible better answer: http://stackoverflow.com/a/50763898
tagged with: django
has comment: http://stackoverflow.com/comment/88535686
has answer: http://stackoverflow.com/a/50763898
has comment: http://stackoverflow.com/comment/88536501
type: AnsweredQuestion
upvote count: 5
type: Question
has body: I am trying to perform a grouping on my model which looks like this: class Restaurant(models.Model): pass class Order(models.Model): created = models.DateTimeField(auto_now_add=True) restaurant = models.ForeignKey('Restaurant') Now I want to know how many orders were created each day. This means I need to get date from DateTime field and then a count. If it's relevant, I'm getting Order queryset in this way: restaurant = Restaurant.objects.get(id=request.data['restaurant_id']) orders = restaurant.order_set.filter(created__lte=some_date) Now, how can I get what I want from orders? I have tried things like: orders.values('created').annotate(Count('created')) Using TruncDate and so on. I am using Python 2 and Django 1.11. EDIT To better express my intentions. I want something that I would achieve in pure python with something like this: orders_by_date = {} for order in orders: if orders_by_date.get(datetime.date(orders[0].created.year, orders[0].created.month, orders[0].created.day): orders_by_date[datetime.date(orders[0].created.year, orders[0].created.month, orders[0].created.day)] += 1 else: orders_by_date[datetime.date(orders[0].created.year, orders[0].created.month, orders[0].created.day)] = 1 EDIT2 I was able to successfully display count for a single date: orders.filter(created__date=datetime.date(2018, 6, 8)).aggregate(Count('id')) Gave me {'id__count': 3}. Now It would be perfect to group by all dates, not just this single one.
answer count: 2
has title: Django group by and count
has answer: http://stackoverflow.com/a/50764432

http://stackoverflow.com/q/50702623
answer count: 2
tagged with: curve-fitting
tagged with: python
has answer: http://stackoverflow.com/a/50706586
score: 0
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50715732
has title: curve fitting equations python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88436278
has body: I am trying to fit data with an admittance equation for an rlc circuit having 6 components. I am following an example given he[fit]1re and inserted my equation. The equation is the real part of admittance for the 6 component circuit simplified using Mathcad. In the figure attached the x axis is omega (w=2*pi*f) and y is admittance in milli Siemens. The program runs but it doesn't do the fitting despite a good trial function. I appreciate any help why the fit is a straight line. I attached also a Gaussian fitting example. this is what i get when I try to fit with the equation. The data is the one with a smaller peak on the left and the trial function is the dotted line. the fit is a straight line from numpy import sqrt, pi, exp, linspace, loadtxt from lmfit import Model import matplotlib.pyplot as plt data = loadtxt("C:/Users/susu/circuit_eq_real5.dat") x = data[:, 0] y = data[:, 1] def circuit(x,C0,Cm,Lm,Rm,R0,Rs): return ((C0**2*Cm**2*Lm**2*R0*x**4)+(Rs*C0**2*Cm**2*Lm**2*x**4)+(C0**2*Cm**2*R0**2*Rm*x**2)+(Rs*C0**2*Cm**2*R0**2*x**2)+(C0**2*Cm**2*R0*Rm**2*x**2)+(2*Rs*C0**2*Cm**2*R0*Rm*x**2)+(Rs*C0**2*Cm**2*Rm**2*x**2)-(2*C0**2*Cm*Lm*R0*x**2)-(2*Rs*C0**2*Cm*Lm*x**2)+(C0**2*R0)+(Rs*C0**2)-(2*Rs*C0*Cm**2*Lm*x**2)+(2*Rs*C0*Cm)+(Cm**2*Rm)+(Rs*Cm**2))/((C0**2*Cm**2*Lm**2*x**4)+(C0**2*Cm**2*R0**2*x**2)+(2*C0**2*Cm**2*R0*Rm*x**2)+(C0**2*Cm**2*Rm**2*x**2)-(2*C0**2*Cm*Lm*x**2)+(C0**2)-(2*C0*Cm**2*Lm*x**2)+(2*C0*Cm)+(Cm**2)) gmodel = Model(circuit) result = gmodel.fit(y, x=x, C0=1.0408*10**(-12), Cm=5.953*10**(-14), Lm=1.475*10**(-7), Rm=1.571, R0=2.44088, Rs=0.42) print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.init_fit, 'k--') plt.plot(x, result.best_fit, 'r-') plt.show() Below is the Fit Report Fit Statistics # fitting method = leastsq # function evals = 14005 # data points = 237 # variables = 6 chi-square = 32134074.5 reduced chi-square = 139108.548 Akaike info crit = 2812.71607 Bayesian info crit = 2833.52443 Variables C0: -7.5344e-15 +/- 6.3081e…
favorite count: 0
has comment: http://stackoverflow.com/comment/88414737
type: Question
tagged with: circuit-diagram
tagged with: lmfit

http://stackoverflow.com/a/50796981
accepted answer of: http://stackoverflow.com/q/50793624
has body: When used with Flask, Nginx is acting as a proxy server, which means there's no need to restart it when you want to reload your Flask app. It's the uWSGI that you need to take care of, since uWSGI is sitting in the middle between Flask app and Nginx and is responsible for forwarding all requests towards your app, and, well, running it. Solution 1 One of the common approaches is to add following into uwsgi_conf.ini: py-autoreload = 1 This will tell uWSGI that it needs to monitor file timestamps every second and reload the app once triggered. Solution 2 Send graceful reload command to uWSGI Master FIFO: Add following to your uwsgi_conf.ini: master-fifo = /var/run/flask_uwsgi_fifo And then reload uWSGI once you're done with your Flask source file changes: $ echo r &gt; /var/run/flask_uwsgi_fifo Solution 3 Similar to solution 2, but via touch-reload. Add following to your uwsgi_conf.ini: touch-reload = /var/run/flask_touch And then reload your app via: $ touch /var/run/flask_touch Solution 4 Send SIGHUP to uWSGI pid file. Add following to your uwsgi_conf.ini: safe-pidfile = /tmp/flask.pid And then reload your app via: $ kill -HUP `cat /tmp/flask.pid` or $ uwsgi --reload /tmp/flask.pid
answers question: http://stackoverflow.com/q/50793624
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88600297
type: AcceptedAnswer
downvote count: 0

yaml
tags question: http://stackoverflow.com/q/50846431
tags question: http://stackoverflow.com/q/50734530
tags question: http://stackoverflow.com/q/50720614
tags question: http://stackoverflow.com/q/50761829
tag name: yaml
type: Tag

http://stackoverflow.com/comment/88515206
comment on: http://stackoverflow.com/q/50753610
type: Comment
type: QuestionComment
score: 1
has text: In other words, you're trampling over the Flask `redirect` method by choosing to call one of your strings `redirect`

http://stackoverflow.com/q/50796984
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50800622
tagged with: tensorflow
tagged with: matrix-multiplication
type: Question
has title: How to do matrix-scalar multiplication in TensorFlow with batch?
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50800622
has body: At the beginning, I will describe formula, what I am trying to compute: Math formula on google chat api (I can't post image directly.) where I is identity matrix with shape (M,M), N_i is the vector (C) and T is the matrix (C*F,M), T_c are submatrices with shape (F,M). My code for tensorflow to enumerate this look like that: N_p = tf.placeholder(floatX, shape=[C], name='N_p') I = tf.Variable(np.eye(M),dtype=tf.float32, name="I") T = tf.Variable(np.random.rand(C*F,M),dtype=tf.float32, name="T") L = I for i,T_c in enumerate([T[i:i+F,:] for i in xrange(0,F*C,F)]): L=tf.add(L,tf.scalar_mul(N_p[i],tf.matmul(tf.transpose(T_c),T_c))) This works fine, unfortunately, I need expand this into batch processing, here N_p will be: N_p = tf.placeholder(floatX, shape=[None,C], name='N_p') Unfortunately, I don't know hor change my tensorflow formula. Problem is in scalar_mul. L=tf.add(L,tf.scalar_mul(N_p[:,i],tf.matmul(tf.transpose(T_c),T_c))) what is obvious why, but how to rewrite it? Thanks a lot for any advice.
tagged with: python

http://stackoverflow.com/q/50839398
linked to: http://stackoverflow.com/q/32868717
type: Question
has comment: http://stackoverflow.com/comment/88685058
linked to: http://stackoverflow.com/q/16392288
downvote count: 0
has comment: http://stackoverflow.com/comment/88682575
has title: ORA-01036: illegal variable name/number - Python insert query
favorite count: 0
tagged with: oracle-database
has comment: http://stackoverflow.com/comment/88682718
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
has body: I am executing following code in python(in eclipse) using oracle 11.g database. I am getting error: cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number. Please help addressid=input("Enter address id:") addressLine=input("Enter Address line:") city=input("Enter city:") zipcode=input("enter zipcode:") state=input("ENTER state") cur.execute("""INSERT INTO INFYCAMPUSCONNECT.Address(ADDRESSID,ADDRESSLINE,CITY,ZIPCODE,STATE) VALUES(?,?,?,?,?)""", (addressid,addressLine,city,zipcode,state))
score: 1

http://stackoverflow.com/q/50702570
upvote count: 1
accepted answer: http://stackoverflow.com/a/50702704
type: Question
has body: i am using pandas.Timestamp.now(tz='America/New_York') to get the current time. and using pandas.Timestamp.now(tz='America/New_York').date() to get current date But I wanted to add 9hr 30min to the current date pandas.Timestamp.now(tz='America/New_York').date() + pandas.Timedelta('570 minutes') the following code is just giving date without the 9 hrs 30 minutes . Where should I improve ?
has title: Add a specific amount of time to a datetime column
tagged with: pandas
downvote count: 0
answer count: 1
tagged with: timedelta
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50702704
tagged with: datetime
tagged with: python
type: AnsweredQuestion

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

http://stackoverflow.com/a/50704485
has body: You should be able to build a list to write as an entire row: for product in products: row = [product['price'],product['vendor_code']] # [price,vendor_code] row.extend(product['characteristics']) # [price,vendor_code,characteristic1,characteristic2,...] writer.writerow(row) # writes each value in the list as a new column
score: 0
has comment: http://stackoverflow.com/comment/88418696
has comment: http://stackoverflow.com/comment/88418621
type: Answer
has comment: http://stackoverflow.com/comment/88418976
answers question: http://stackoverflow.com/q/50704236

http://stackoverflow.com/comment/88634986
comment on: http://stackoverflow.com/q/50815005
type: Comment
type: QuestionComment
has text: @user1034937 yes. should I add that to the post?
score: 0

http://stackoverflow.com/a/50796530
has comment: http://stackoverflow.com/comment/88598949
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50796361
answers question: http://stackoverflow.com/q/50796361
has comment: http://stackoverflow.com/comment/88599302
type: Answer
has comment: http://stackoverflow.com/comment/88601577
has comment: http://stackoverflow.com/comment/88601367
has body: You can use the library googletrans import pandas as pd from googletrans import Translator d = {"City_trad_chinese":["香港特别行政区", "澳门特别行政区", "北京市", "上海市"]} df = pd.DataFrame(data=d) translator = Translator() df["City_English"] = df["City_trad_chinese"].map(lambda x: translator.translate(x, src="zh-TW", dest="en").text) print(df["City_English"]) 0 Hong Kong Special Administrative Region 1 Macao Special Administrative Region 2 Beijing City 3 Shanghai City Note: The Google Translate API has a 15k character limit. You can circumnavigate this by translating each row individually: df["City_English"] = "" for index, row in df.iterrows(): translator = Translator() eng_text = translator.translate(row["City_trad_chinese"], src="zh-TW", dest="en").text row["City_English"] = eng_text
has comment: http://stackoverflow.com/comment/91222397
has comment: http://stackoverflow.com/comment/88600483
has comment: http://stackoverflow.com/comment/88600252
has comment: http://stackoverflow.com/comment/88601333
score: 4
upvote count: 4

http://stackoverflow.com/comment/88575987
score: 0
has text: But why you want to execute a function on the change of code. Once the application is developed it has no use.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50784722

http://stackoverflow.com/comment/88568538
type: Comment
comment on: http://stackoverflow.com/q/50780461
score: 0
has text: I spun my wheels for a bit trying to get Tkinter set up in Python2 before just doing it in Python3. Should be the same but let me know.
type: QuestionComment

http://stackoverflow.com/q/50828297
downvote count: 0
tagged with: win32com
score: 1
type: Question
upvote count: 1
answer count: 1
has title: Python win32com insert word object into Excel file
favorite count: 0
has answer: http://stackoverflow.com/a/50836993
accepted answer: http://stackoverflow.com/a/50836993
has body: Excel error: "Document not saved" when trying to insert multiple objects into excel file. Works for zip and .mpp file extensions, but not working with .doc and .docx file types. Once inserted, the object shows a white unknown file image and simply says EMBED("Document",""). However, when I insert manually these docs I have no problems and they display as Word doc icon. Any Suggestions? import win32com.client as win32 xl = win32.gencache.EnsureDispatch('Excel.Application') xl.Visible = 1 wb = xl.Workbooks.Open('BlankTemplate.xlsx') #New Excel file that is blank xl.DisplayAlerts = False ws = wb.Worksheets('Sheet1') dest_cell = ws.Range('C5') obj = ws.OLEObjects() obj.Add(ClassType=None,Filename='Approval.zip',Link=False,DisplayAsIcon=False,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) obj.Add(ClassType=None,Filename='Final.docx',Link=False,DisplayAsIcon=True,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) obj.Add(ClassType=None,Filename='Release.doc',Link=False,DisplayAsIcon=True,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) obj.Add(ClassType=None,Filename='Platform.mpp',Link=False,DisplayAsIcon=False,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) wb.SaveAs('ProjectDetailsAttachments.xlsx') xl.DisplayAlerts = True xl.Application.Quit() xl.Visible = 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88660044
type: Comment
score: 0
has text: I was thinking about using the .pop but it removes the element as well. :(
type: AnswerComment
comment on: http://stackoverflow.com/a/50827758

http://stackoverflow.com/comment/88610346
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50802059
score: 0
has text: @Aran-Fey Doing re.search i successfully done by making a for loop, just trying to understand how to use re.findall.

http://stackoverflow.com/q/50800085
score: 0
has comment: http://stackoverflow.com/comment/88644389
has comment: http://stackoverflow.com/comment/88634000
has comment: http://stackoverflow.com/comment/88618710
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88644220
favorite count: 0
has body: I'm a beginner in machine learning and I'm trying to apply a Bayes multiclasses classification algorithm and then do the accurancy score. The first part works, the second part of the calculation does not work but I would like to be able to calculate the degree of precision and recall of the program in its classifications. import sklearn import numpy as np from sklearn import svm from pprint import pprint from sklearn.pipeline import Pipeline from sklearn.datasets import load_files from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import precision_recall_fscore_support as score from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import accuracy_score labels = ["price", "personal", "delivery", "store", "product"] # Download data docs_to_train = load_files('train') train_X, test_X, train_y, test_y = train_test_split(docs_to_train.data, docs_to_train.target,test_size = 3) count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(docs_to_train.data) tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts) X_train_tf = tf_transformer.transform(X_train_counts) X_train_tf.shape tfidf_transformer = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) X_train_tfidf.shape # Train Bayes classifier clf = MultinomialNB().fit(X_train_tfidf, docs_to_train.target) docs_test = ["the shop is beautiful", "the price is expensive", "they are nice the staff", "I loved the shop", "there are not many products", "choose the products on the site", "more choice in the store", "the packaging is beautiful", "the packaging is very ugly", "lack of products", "there are problems on the site", "the shop is very beautiful", "the botique is very beautiful", "I love this store", "…
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88614048
has comment: http://stackoverflow.com/comment/88642254
has comment: http://stackoverflow.com/comment/88633617
has comment: http://stackoverflow.com/comment/88645150
tagged with: bayesian
has comment: http://stackoverflow.com/comment/88643032
has title: Score precision and recall in the multiclass Bayes classifier

http://stackoverflow.com/comment/88603949
type: Comment
type: QuestionComment
has text: Related: https://stackoverflow.com/questions/1239035/asynchronous-method-call-in-python
comment on: http://stackoverflow.com/q/50798858
score: 0

http://stackoverflow.com/comment/88567639
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50780402
type: Comment
has text: it's giving me [6,10], I'm missing 14 the output [6,10,14].

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

http://stackoverflow.com/comment/88675174
type: Comment
type: QuestionComment
has text: It's ok `n` is number of students.Can you please explain, each students has how many subjects?
score: 0
comment on: http://stackoverflow.com/q/50834506

http://stackoverflow.com/comment/88626025
comment on: http://stackoverflow.com/q/50810190
type: Comment
type: QuestionComment
has text: Can you share what file.json looks like? I'm not sure what you mean by 'object by object', files are always read line by line, so the recombination of objects across lines will have to be done in python after reading in the file.
score: 0

http://stackoverflow.com/comment/88509950
has text: @abarnert. gfortran never contained any part of f2c.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50750872
type: Comment

http://stackoverflow.com/q/50792344
has comment: http://stackoverflow.com/comment/88590814
has comment: http://stackoverflow.com/comment/88595772
possible better answer: http://stackoverflow.com/a/50792546
accepted answer: http://stackoverflow.com/a/50792414
favorite count: 0
has answer: http://stackoverflow.com/a/50792461
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/88590819
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50792548
downvote count: 3
has comment: http://stackoverflow.com/comment/88590749
has answer: http://stackoverflow.com/a/50792414
has answer: http://stackoverflow.com/a/50792441
type: Question
has body: Is there any Pythonic way to know if the for loop is interrupted? I have a very large list, with 100 000 records. I want to loop through all list items but I want to know if there for some reason (for example: if the power is gone, if the battery is empty of for any other reason) the loop is interrupted and didn't come to the end of the list. Thus for example if I have list as follows: some_list = ["item1", "item2", "item3", "item4", "item5"] for item in some_list: # If it came to item3 and it's interrupted. How can I know that? print(item)
has comment: http://stackoverflow.com/comment/88590752
has answer: http://stackoverflow.com/a/50792395
upvote count: 5
has answer: http://stackoverflow.com/a/50792546
answer count: 6
has title: How to check if the for loop is interrupted in Python

http://stackoverflow.com/q/50850337
has comment: http://stackoverflow.com/comment/88703425
tagged with: pandas
has title: Pandas: How to concatenate dataframes in the following manner?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88703526
has body: I want to concatenate multiple dataframes into one dataframe. The manner I want the concatenation to happen is illustrated in the following example: Input tables: A B C D 0 x p 2 4 1 y q 3 5 A B E F 0 x p 6 8 1 y q 9 10 Output table: A B C D E F 0 x p 2 4 6 8 1 y q 3 5 9 10 I want to know if this can be done using the pandas.concat command. I know this can be done through the pd.merge command. Thanks.
tagged with: python
linked to: http://stackoverflow.com/q/41815079
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/88703456
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50850423
accepted answer: http://stackoverflow.com/a/50850423
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88703382
tagged with: concatenation

http://stackoverflow.com/comment/88651293
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50823011
score: 0
has text: Can we get the whole class?

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

http://stackoverflow.com/a/50753919
type: Answer
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50753321
has body: Works perfectly in python 2.7. name1 = raw_input("enter first string: ") name2 = raw_input("enter second string: ") name3 = raw_input("enter third string: ") average = (len(name1) + len(name2) + len(name3)) / 3 print("the average length is: " + str(average)) Hope it helps.

http://stackoverflow.com/comment/88616316
type: QuestionComment
comment on: http://stackoverflow.com/q/50805099
has text: Norrius , I tried @app.route('localhost:3000/new', methods=['POST']) But it said url has to start with "/". How can I listen to localhost:3000/new when flask run in port 5000
score: 0
type: Comment

http://stackoverflow.com/a/50730121
upvote count: 2
score: 1
downvote count: 1
has body: While continuing to debug, as a test I deleted the word RedisError from the except line. But the error message still contained RedisError. That was my clue that the app.py I thought was being executed was not being executed. I had to execute docker build ./ -t friendlyhello again before I could docker run.
type: Answer
answers question: http://stackoverflow.com/q/50727619

http://stackoverflow.com/q/50706513
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88422266
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50706684
score: 0
has title: python - csvfile replace column values by NaN when other column equal certain values
has comment: http://stackoverflow.com/comment/88422370
type: Question
accepted answer: http://stackoverflow.com/a/50706684
answer count: 1
has body: Sorry if the title is somehow long and weird... I have the following csv file: Date,Value1,Value2 01-01-01,01,01 02-01-01,02,00 03-01-01,03,01 04-01-01,04,01 In this dataset I would like to replace the data of Value1 column by a NaN when the data of Value2 column equal 00. So the output dataset should look like this: Date,Value1,Value2 01-01-01,01,01 02-01-01,NaN,00 03-01-01,03,01 04-01-01,04,01 I tried with the following codes but I am missing some of the conditions and it obviously does not work: data = pd.read_csv("test.csv") data['Value1'][data.Value2 == 00] = np.NaN Does anyone knows how to achieve that?
tagged with: nan

http://stackoverflow.com/a/50805555
has comment: http://stackoverflow.com/comment/103988524
upvote count: 10
accepted answer of: http://stackoverflow.com/q/50804826
score: 10
answers question: http://stackoverflow.com/q/50804826
has body: Ok, to go over this in painful detail: class Singleton: implicitly inherits from Object because in python everything is an Object. instance = None is only read at module load time, and sets the class level variable instance to be None one time but it can be over written by individual instances of the class Singleton. def __new__(cls): if cls.instance is None: cls.instance = super().__new__(cls) return cls.instance (First off, I think that it's weird that they put "cls" in there, I know why they did it, because it's referring to the class overall and not a specific instance of that class. But, it can be confusing so someone who doesn't know what they're looking at. Anyway...) __new__ is a magic function that is called before __init__, that is roughly analogous to allocating the space for the new instance of the class. Here, cls.instance was set to None on module load, and so every time a new Singleton is being created this test is done. Since cls.instance is set the first time a Singleton is created, the super().__new__(cls) is also only called once. The super class of Singleton is Object. So the behavior of the super().__new__(cls) is exactly what you'd expect it to be for any other class you create. If, you are creating a second(, or third/fourth/fifth...) instance of Singleton then this super().__new__(cls) will not be called. Instead the class level variable instance is returned, meaning that no new instances of Singleton can be created. When you print the instances of Singleton then you can see the memory address of 0x10dbc0f60 is the same for both "instances" because cls.instance is returned at __new__ time, which you can think of as memory allocation time, before __init__ is called. This is a good way to do a Singleton pattern because in order to create a singleton class, now, all you have to do is inherit from Singleton and the heavy lifting is already done. You go ahead and use __init__ like you normally would, and don't worry about it. Every time you go to …
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/50782317
type: Question
has comment: http://stackoverflow.com/comment/88572127
has answer: http://stackoverflow.com/a/50881734
has body: Say you want to optimize a (byte) string compare intensive algorithm implemented in Python. Since a central code path contains this sequence of statements if s &lt; t: # less than ... elif t &lt; s: # greater than ... else: # equal ... it would be great to optimize it to something like r = bytes_compare(s, t) if r &lt; 0: # less than ... elif r &gt; 0: # greater than ... else: # equal ... where (the hypothetical) bytes_compare() ideally would just call the three-way comparison C function memcmp() which is usually quite well optimized. This would reduce the number of string comparisons by half. A very feasible optimization unless the strings are ultra short. But how to get there with Python 3? PS: Python 3 has removed the three way comparison global function cmp() and the magic method __cmp__(). And even with Python 2, the bytes class doesn't had a __cmp__() member. With the ctypes package it's straight forward to call memcmp() but the foreign function call overhead with ctypes is prohibitively high.
has comment: http://stackoverflow.com/comment/88571636
answer count: 1
has comment: http://stackoverflow.com/comment/88572043
tagged with: string
favorite count: 0
score: 8
tagged with: python-3.x
has title: Three-way comparing strings in Python 3
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88572497
has comment: http://stackoverflow.com/comment/88572062
accepted answer: http://stackoverflow.com/a/50881734
upvote count: 8

http://stackoverflow.com/q/50705190
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50705399
downvote count: 0
score: 7
type: Question
has body: I have looked quite extensively on stackoverflow and elsewhere and I can't seem to find an answer to the problem below. I am trying to modify a parameter of a function that is itself a parameter inside the GridSearchCV function of sklearn. More specifically, I want to change parameters (here preserve_case = False) inside the casual_tokenize function that is passed to the parameter tokenizer of the function CountVectorizer. Here's the specific code : from sklearn.datasets import fetch_20newsgroups from sklearn.pipeline import Pipeline from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import GridSearchCV from nltk import casual_tokenize Generating dummy data from 20newsgroup categories = ['alt.atheism', 'comp.graphics', 'sci.med', 'soc.religion.christian'] twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42) Creating classification pipeline. Note that the tokenizer can be modified using lambda. I am wondering if there's another way to do it since it is not working with GridSearchCV . text_clf = Pipeline([('vect', CountVectorizer(tokenizer=lambda text: casual_tokenize(text, preserve_case=False))), ('tfidf', TfidfTransformer()), ('clf', MultinomialNB()), ]) text_clf.fit(twenty_train.data, twenty_train.target) # this works fine I then want to compare the default tokenizer of CountVectorizer with the one in nltk. Note that I am asking the question because I would like to compare more than one tokenizer that each have specific parameters that needs to be specified. parameters = {'vect':[CountVectorizer(), CountVectorizer(tokenizer=lambda text: casual_tokenize(text, preserve_case=False))]} gs_clf = GridSearchCV(text_clf, parameters, n_jobs=-1, cv=5) gs_clf = gs_clf.fit(twenty_train.data[:100], twenty_train.target[:100]) gs_clf.fit gives the following error : PicklingError: Can't p…
tagged with: grid-search
has title: GridsearchCV: can't pickle function error when trying to pass lambda in parameter
upvote count: 7
answer count: 1
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/50705399

http://stackoverflow.com/comment/88667925
comment on: http://stackoverflow.com/q/50831530
has text: ok. Thanks. It is like this: /home/"username"/PycharmProjects/2DHistogram/2DHistogram.py
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50829631
downvote count: 0
favorite count: 0
has body: I have just begin to learn tensorflow,and write a model for exercising on MNIST.Thus I am following a book,but there is still porblem,could you please help me about this? Following is my code with problem description in it,thank you very much! x = tf.placeholder(tf.float32,[None,INPUT_NODE],name='input') y_ = tf.placeholder(tf.float32,[None,OUTPUT_NODE],name='output') weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE,LAYER1_NODE],stddev=0.1)) biases1 = tf.Variable(tf.constant(0.1,shape=[LAYER1_NODE])) weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE,OUTPUT_NODE],stddev=0.1)) biases2 = tf.Variable(tf.constant(0.1,shape=[OUTPUT_NODE])) the next y = ()...define forward propagating without using moving average model. y = inference(x,None,weights1,biases1,weights2,biases2) global_step = tf.Variable(0,trainable=False) variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step) variables_averages_op = variable_averages.apply(tf.trainable_variables()) the next average_y =()...define forward propagating using moving average model. average_y = inference(x,variable_averages,weights1,biases1,weights2,biases2) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=tf.arg_max(y_,1)) cross_entropy_mean = tf.reduce_mean(cross_entropy) regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE) regularization = regularizer(variable_averages.average(weights1)) +\ regularizer(variable_averages.average(weights2)) loss = cross_entropy_mean + regularization learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, mnist.train.num_examples / BATCH_SIZE, LEARNING_RATE_DECAY ) train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step) train_op = tf.group(train_step,variables_averages_op) the problem is when I use average_y to calculate the accuracy,it seems like training doesn't help improving at all: After 0 training steps, acc in validatation is 0.0742 After…
type: UnansweredQuestion
has title: Tensorflow:Training doesn't improve accuracy
tagged with: python
has answer: http://stackoverflow.com/a/50832761
score: 1
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question
answer count: 1

http://stackoverflow.com/comment/88576476
has text: If you want to modify the existing tables, as is implied by your statement that "no changes were reflected in the tables," then you need to use either an UPDATE or an INSERT query.
comment on: http://stackoverflow.com/q/50783729
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88540890
has text: I'm using Bokeh to visualize the graphs so the some_plot() function returns an HTML div and JS script generated by Bokeh.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50766521

http://stackoverflow.com/a/50768873
score: 0
accepted answer of: http://stackoverflow.com/q/50768511
type: Answer
has comment: http://stackoverflow.com/comment/88545531
answers question: http://stackoverflow.com/q/50768511
has body: Looking at the traceback, the problem seems to occur when you call the predict method: next_price = model.predict(self.current_price) You need to make sure that self.current_price has the right shape --- shape=(whatever, 3)
type: AcceptedAnswer

data-structures
tags question: http://stackoverflow.com/q/50712202
tags question: http://stackoverflow.com/q/50785187
tag name: data-structures
tags question: http://stackoverflow.com/q/50780127
tags question: http://stackoverflow.com/q/50829546
tags question: http://stackoverflow.com/q/50728738
tags question: http://stackoverflow.com/q/50833671
tags question: http://stackoverflow.com/q/50832334
tags question: http://stackoverflow.com/q/50788042
tags question: http://stackoverflow.com/q/50786352
tags question: http://stackoverflow.com/q/50721813
tags question: http://stackoverflow.com/q/50842580
tags question: http://stackoverflow.com/q/50779565
type: Tag

http://stackoverflow.com/a/50769523
score: 2
downvote count: 0
has body: The two examples are not the same. The problem with the Python example is that the input doc does not have a context. The processor first expands the data and will result in unknown terms that are dropped. You can see the problem if you print out the expanded data: expanded = jsonld.expand(doc) print(json.dumps(expanded, indent=2)) [] If you add in the context, then expand, you will see the correct data: from pyld import jsonld import json context = { "url": "@id", "a": "@type", "name": "http://schema.org/name", "schema" : "http://schema.org/" } doc = { "@context": context, "url": "http://example.com/about#gregg", "a": "schema:Person", "name": "Gregg Kellogg" } expanded = jsonld.expand(doc) print(json.dumps(expanded, indent=2)) [ { "@type": [ "http://schema.org/Person" ], "http://schema.org/name": [ { "@value": "Gregg Kellogg" } ], "@id": "http://example.com/about#gregg" } ] To match your compaction playground example, you would want to add in the context as above and compact with the schema.org context: ... compacted = jsonld.compact(doc, {"@context": "http://schema.org/"}) # or use the shortcut: # compacted = jsonld.compact(doc, "http://schema.org/") print(json.dumps(compacted, indent=2)) { "@context": "http://schema.org/", "id": "http://example.com/about#gregg", "type": "Person", "name": "Gregg Kellogg" }
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50709437
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50709437
type: Answer
has comment: http://stackoverflow.com/comment/88565815

http://stackoverflow.com/comment/88457961
type: QuestionComment
has text: Actually scratch my last comment, I just tried some operations with `datetime.date` and they work fine with comparison and arithmetic operations which is news to me
score: 1
comment on: http://stackoverflow.com/q/50724489
type: Comment

http://stackoverflow.com/comment/88500078
has text: @jonrsharpe Thanks!
comment on: http://stackoverflow.com/q/50746022
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88576526
has text: Possible duplicate of [web scraping dynamic content with python](https://stackoverflow.com/questions/17608572/web-scraping-dynamic-content-with-python)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50784900

http://stackoverflow.com/q/50729951
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88468360
has body: This could be caused by me not understanding how pandas.melt works but I get strange behaviour when plotting "melted" dataframes using plotnine. Both frames has been converted from wide to long format. One frame with a column containing string values (df_slow) and another with only numerical values (df_fast). The following code gives different behaviour. Plotting df_slow is slow and gives a strange looking y-axis. Plotting df_fast looks ok and is fast. My guess is that pandas melt is doing something strange with the data which causes this behaviour. See example plots. import matplotlib.pyplot as plt import numpy as np import pandas as pd import plotnine as p9 SIZE = 200 value = np.random.rand(SIZE, 1) # Create test data, one with a column containing strings, one with only numeric values df_slow = pd.DataFrame({'value': value.flatten(), 'string_column': ['A']*SIZE}) df_fast = pd.DataFrame({'value': value.flatten()}) # Set index df_slow = df_slow.reset_index() df_fast = df_fast.reset_index() # Convert 'df_slow', 'df_fast' to long format df_slow = pd.melt(df_slow, id_vars='index') df_fast = pd.melt(df_fast, id_vars='index') print(df_slow.head()) print(df_fast.head()) df_slow = df_slow[df_slow.variable == 'value'] # This is slow and has many breaks on y-axis p = (p9.ggplot(df_slow, p9.aes(x='index', y='value')) + p9.geom_point()) p.draw() # This is much faster and y-axis looks good p = (p9.ggplot(df_fast, p9.aes(x='index', y='value')) + p9.geom_point()) p.draw() slow and strange plot fast and good looking plot Possible fix Changing the type of the "value" column in df_slow makes it behave like df_fast when plotting. # This makes df_slow behave like df_fast when plotting df_slow['value'] = df_slow.value.astype(np.float64) Question Is this a bug in plotnine (or pandas) or am I doing something wrong? Answer When pivoting two columns with different data types, in this case string and float, I guess it makes sense that the resulting column containing both strings and floats …
tagged with: pandas
has title: Plotting pandas dataframe after doing pandas melt is slow and creates strange y-axis
downvote count: 0
has comment: http://stackoverflow.com/comment/88467982
has comment: http://stackoverflow.com/comment/88468026
favorite count: 0
tagged with: plotnine
answer count: 0

http://stackoverflow.com/q/50752605
has comment: http://stackoverflow.com/comment/88513835
has answer: http://stackoverflow.com/a/50755606
has body: I want to compute the expanding window of just the last few elements in a group... df = pd.DataFrame({'B': [np.nan, np.nan, 1, 1, 2, 2, 1,1], 'A': [1, 2, 1, 2, 1, 2,1,2]}) df.groupby("A")["B"].expanding().quantile(0.5) this gives: 1 0 NaN 2 1.0 4 1.5 6 1.0 2 1 NaN 3 1.0 5 1.5 7 1.0 I only really want the last two rows for each group though. the result should be: 1 4 1.5 6 1.0 2 5 1.5 7 1.0 I can easily calculate it all and then just get the sections I want. but this is very slow if my dataframe is 1000s of elements long and I dont want to roll across the whole window... just the last two "rolls" EDIT: I have ammended the title; A lot of people are correctly answering part of the question, but ignoring what is IMO the important part (I should have been more clear) The issue here is the time it takes. I could just "tail" the answer to get the last two; but then it involves calculating the first two "expanding windows" and then throwing away those results. If my dataframe was instead 1000s of rows long and I just needed the answer for the last few entries, much of this calculation would be wasting time. This is the main problem I have. As I stated: "I can easily calculate it all and then just get the sections I want" => through using tail. Sorry for the confusion. Also potentially using tail doesnt involve calculating the lot, but it still seems like it does from the timings that I have done... maybe this is not correct, it is an assumption I have made. EDIT2: The other Option I have tried was using the min_windows in rolling to force it to not calculate the initial sections of the group, but this has many pitfalls such as: -if the array includes NaNs this doesnt work, -if the groupbys are not the same length. EDIT3: As a simpler problem and reasoning: Its a limitation of the expanding/or rolling window I think... say we had an array [1,2,3,4,5] the expanding windows are [1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5], and if we run the max over that we get: 1,2,3,4,5 (the…
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50755606
favorite count: 0
possible better answer: http://stackoverflow.com/a/50752906
has answer: http://stackoverflow.com/a/50752906
type: Question
tagged with: python
has title: In pandas is there a way to compute a subsection of a expanding window; without calculating the entire array and "tail-ing" the result
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88621058
downvote count: 1

http://stackoverflow.com/a/50851256
has comment: http://stackoverflow.com/comment/88738084
has body: I see your connection ID is M_1 and your connection type is S3 so you can load this inside a PythonOperator (or a python script called from BashOperator) with: from airflow.hooks.s3_hook import S3Hook def py_op_callable: hook = S3Hook('M_1') botocore_credentials = hook.get_credentials() botocore_credentials.access_key botocore_credentials.secret_key botocore_credentials.token On v1.9.0 it seems get_credentials is not yet there. There's only the private _get_credentials() on AwsHook which S3Hook inherits. If you're sure you put them into the extra parameters the direct approach is: from airflow.hooks.base_hook import BaseHook def py_op_callable: hook = BaseHook('M_1') extra = hook.get_connection().extra_dejson key_id = extra.get('aws_access_key_id') secret_key = extra.get('aws_secret_access_key') default_region = extra.get('region_name') return key_id,secret_key,default_region
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50811352
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88711507

http://stackoverflow.com/a/50833644
accepted answer of: http://stackoverflow.com/q/50832667
answers question: http://stackoverflow.com/q/50832667
type: Answer
score: 0
has body: The problem with [int(x) for x in data.split('\r\n')] is that the result will contain an empty string '' at the end, after the final \r\n. You could use a filter condition to remove it... &gt;&gt;&gt; [int(x) for x in data.split('\r\n') if x] [25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25] ... or just use data.split() without parameter: &gt;&gt;&gt; [int(x) for x in data.split()] [25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25] From the documentation (emphasis mine): S.split(sep=None, maxsplit=-1) -&gt; list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
type: AcceptedAnswer

http://stackoverflow.com/q/50848879
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: In my Django project, I want to create slug field from the title. For example: title = Arduino UNO slug = arduino-uno And if the slug field exists into my DB then I want to append a digit For example: arduino-uno2 Here is title to slug generator logic: def create_slug(title): qs = IndividualProduct.objects.filter(slug=title) if qs.exists(): title = title + str(qs.last().id) create_slug(title) else: return title def slug_generator_for_image_folder(sender, instance, *args, **kwargs): if instance.slug == None: title = slugify(instance.title) instance.slug = create_slug(title) instance.save() else: pass pre_save.connect(slug_generator_for_image_folder, sender=IndividualProduct) But this code is exceeding maximum recursion limit if I want to add a digit. If I make the change of the code from if qs.exists(): ..... else: return title to if qs.exists(): ..... return title Then it is working perfectly. I have tried both the code into python shell and it is working perfectly. I am not understanding why it is not working into my Django models.
tagged with: django
tagged with: python
tagged with: slug
answer count: 0
has title: Slug field RecursionError
has comment: http://stackoverflow.com/comment/88701819
has comment: http://stackoverflow.com/comment/88701571
type: Question
tagged with: django-models
score: 0
has comment: http://stackoverflow.com/comment/88701762
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88713497

http://stackoverflow.com/comment/88503156
type: Comment
type: QuestionComment
has text: So you're asking how to use a package that no longer exists? The answer to that is easy: either you have to fork it and take over building and maintaining it yourself (which is going to be a major project, and almost certainly not something you want to do as your first foray into Python), or you just can't use it. Which means your book is out of date and useless, which sucks, but there's nothing anyone can do about that.
comment on: http://stackoverflow.com/q/50747653
score: 1

http://stackoverflow.com/q/50801103
has comment: http://stackoverflow.com/comment/88616785
type: Question
has comment: http://stackoverflow.com/comment/88608232
has comment: http://stackoverflow.com/comment/88608149
has comment: http://stackoverflow.com/comment/88608497
has comment: http://stackoverflow.com/comment/88608560
has comment: http://stackoverflow.com/comment/88614342
score: 0
tagged with: python
tagged with: dictionary
tagged with: performance
has body: I'm writing some code to go through the vigenere cipher with different possibilities, and then making it only add the list to the possible options that result in a word when decrypted (that way I don't get thousands of print outs, I only get told with the most likely possibilities). Here's the code so far def vigenere(input): print("VIGENERE") key = "" keyList = [] textList = [] for word in englishDictionary: key = re.sub('[\W_]+', '', word) if key[:len(input)] not in keyList: while len(key) &lt; len(input): key = key + key keyLetters = list(key.upper()) keyNumbers = [] for x in keyLetters: keyNumbers.append(alphaNum.get(x)) vigenereOutput = "" for z in list(input): try: keyNum = int(keyNumbers[0]) except IndexError: pass keyNum = keyNum - 1 inbetween = int(alphaNum.get(z)) - keyNum del keyNumbers[0] if inbetween &lt; 1: inbetween = 26 + inbetween vigenereOutput = vigenereOutput + numAlpha.get(str(inbetween)) if vigenereOutput in englishDictionary: keyList.append(key[:len(input)]) textList.append(vigenereOutput) if len(keyList) &gt; 0: for keyEntry in len(keyList): print("Key:", keyList[keyEntry]) print("Text:", textList[keyEntry]) print() The englishDictionary is a list of all the words in my dictionary text file (fairly big file, but using a small one would ruin the point of this decoder) Right now however it takes over 20 minutes to go through the entire dictionary... how can I speed this process up?
has comment: http://stackoverflow.com/comment/88609853
has title: Make python code for searching through dictionary more efficent (vigenere cipher)
has comment: http://stackoverflow.com/comment/88608471
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50728719
type: Question
tagged with: gurobi
has comment: http://stackoverflow.com/comment/88468027
score: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Gurobi/Python crashes with "A heap has been corrupted" error message
has body: I am running an optimization in Gurobi which crashes whenever I add a quadratic constraint to the problem that I generate thru the following lines of code: expression = gurobipy.QuadExpr() for course_key in hostings: for kitchen_key in hostings[course_key]: if not hostings[course_key][kitchen_key].large_gathering: expression.add(x[kitchen_key,course_key,team_key1]*x[kitchen_key,course_key,team_key2]) mod.addQConstr(expression,gurobipy.GRB.LESS_EQUAL,1,"1MeetingPerPair_"+team_key1+"_"+team_key2) The optimization always crashes after three iterations: cmd output with the following error message: Unhandled exception at 0x00007FFC596CE6FC (ntdll.dll) in python.exe: 0xC0000374: A heap has been corrupted (parameters: 0x00007FF8FF82C6E0). Does anyone have any clue as to how this problem could be solved? I am rather clueless as to what the error message even wants to tell me. I tried constructing the constraint in different ways (e. g. using .add instead of .addTerms) but that didn't change anything. Appreciate any help!
answer count: 0
has comment: http://stackoverflow.com/comment/88465588
has comment: http://stackoverflow.com/comment/88466369

http://stackoverflow.com/q/50821406
tagged with: rose-plot
linked to: http://stackoverflow.com/q/48192743
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88659541
favorite count: 0
has comment: http://stackoverflow.com/comment/88654172
tagged with: polar-coordinates
has body: I am trying to compare wind roses in python, but it is difficult because I cannot figure out how to make the same scale across all of the plots. Someone else asked the same question here Custom percentage scale used by windrose.py but it was not answered . Example code: from windrose import WindroseAxes import numpy as np import matplotlib.pyplot as plt wind_dir = np.array([30,45,90,43,180]) wind_sd = np.arange(1,wind_dir.shape[0]+1) bins_range = np.arange(1,6,1) # this sets the legend scale fig,ax = plt.subplots() ax = WindroseAxes.from_ax() bin_range below sets scale of bars, but I need to change the y-axis frequency scale so it can be compared to other wind roses with different data. ax.bar(wind_dir,wind_sd,normed=True,bins=bins_range) this set_ylim does seem to work, but the yaxis ticks do not change ax.set_ylim(0,50) this set_ticks line below does not do anything and I do not know why ax.yaxis.set_ticks(np.arange(0,50,10)) ax.set_legend() plt.show()
accepted answer: http://stackoverflow.com/a/50827533
tagged with: python
type: AnsweredQuestion
score: 7
upvote count: 7
type: Question
has title: custom scaling of a wind rose plot
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50827533
has comment: http://stackoverflow.com/comment/88651679
tagged with: windrose

http://stackoverflow.com/q/50838181
has comment: http://stackoverflow.com/comment/88680239
tagged with: python
has comment: http://stackoverflow.com/comment/88680193
has comment: http://stackoverflow.com/comment/88680294
possible better answer: http://stackoverflow.com/a/50838318
has answer: http://stackoverflow.com/a/50838318
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50838367
has comment: http://stackoverflow.com/comment/88680257
has title: About a simple recursive function in python
accepted answer: http://stackoverflow.com/a/50838367
type: AnsweredQuestion
has body: I need to do a recursive function that works like this: input: 'word' output: ['word','ord', 'rd', 'd'] Now, the best way to do it its like this: func(string): if not string: return [] return [string] + func(string[1:]) But i'd like to do it in this way: func(string, recursivelist): if len(string) == 0: return [] recursivelist += [string] recursivelist += func(string[1:],recursivelist) return recursivelist I know this is a bad way to do a recursive function, and i'm trying slowly to get the first approach, but just out of curiosity, why this code is not working? The output is like this: ['word', 'ord', 'rd', 'd', 'word', 'ord', 'rd', 'd', 'word', 'ord', 'rd', 'd', 'word', 'ord', 'rd', 'd', 'word', 'ord', 'rd', 'd', 'word', 'ord', 'rd', 'd', 'word', 'ord', 'rd', 'd', 'word', 'ord', 'rd', 'd']
type: Question

http://stackoverflow.com/q/50806104
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50806842
tagged with: web-scraping
upvote count: 1
has answer: http://stackoverflow.com/a/50806341
has comment: http://stackoverflow.com/comment/88618375
type: Question
has title: Beautiful Soup 4 Python 3.6.5 web scraping for real time currency conversion from GBP to USD
answer count: 2
possible better answer: http://stackoverflow.com/a/50806341
accepted answer: http://stackoverflow.com/a/50806842
has body: I'm trying to scrape a web page for the conversion rate of GBP to USD from this site https://www.x-rates.com/calculator/?from=GBP&to=USD&amount=1. I've identified the class for the conversion rate in the HTML of the link above as "ccOutputRslt" however when printing what is scraped what is returned to me reads: 1.338241 USD How does one go about removing the tags from the code, as well as removing the string "USD" contained in class="ccOutputCode" so that what's printed will be the float "1.338241", so the conversion can take place. here is the python code for my file: import requests from bs4 import BeautifulSoup page = requests.get('https://www.x-rates.com/calculator/?from=GBP&to=USD&amount=1') soup = BeautifulSoup(page.text, 'html.parser') price_box = soup.find(class_="ccOutputRslt") rate = price_box print(rate) #checking the output def gbp_to_usd(rate,gbp): dollars=gpb*rate return dollars gbp = input("Enter GBP amount: ") finalamt = gbp_to_usd(float(rate),float(gbp)) print(str(gbp)+" GBP is equvalent to "+"$"+str(finalamt)+" USD") I'm still very new to python and coding in general, any help would be greatly appreciated. Regards, Chris
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has comment: http://stackoverflow.com/comment/88618293
has comment: http://stackoverflow.com/comment/88618182
has comment: http://stackoverflow.com/comment/88618400

http://stackoverflow.com/comment/88560613
has text: "I tried something and it did not work" is a little too broad of an error description as a starting point.
comment on: http://stackoverflow.com/q/50776671
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/88687619
type: Comment
type: QuestionComment
has text: maybe not in detail as a Pro should but i fairly understand the concept
score: 0
comment on: http://stackoverflow.com/q/50841713

http://stackoverflow.com/comment/88578267
score: 0
has text: Plus, `data` is a list, how are you using `.find()` on it? You should be getting an exception.
type: QuestionComment
comment on: http://stackoverflow.com/q/50785851
type: Comment

http://stackoverflow.com/a/50708274
has body: First, I would probably structure this differently, as a dict, i.e. something like d = {500: {'lal': ttk.Label ... 'ent': ttk.Entry ... ... } Then I'd create it with a comprehension or loop, something like this: for n in 1,2,5,10,20,50, ...: d[n] = {'lal': ttk.label.... text='$'+str(n), 'ent': ttk. ... } With out knowing more about what self.int500 &amp;c. are, it's hard to fill in the blanks completely. If it's a regular pattern, you could also iterate through a list comprehension: for n in [i*f for f in [1,10,100] for i in [1,2,5]]: ... Fundamentally, though, I think all the repetition in your code comes from using a bunch of individual variables rather than a structured data structure like a list or dict.
downvote count: 1
answers question: http://stackoverflow.com/q/50708062
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/88425703
type: Answer

http://stackoverflow.com/q/50785588
has comment: http://stackoverflow.com/comment/88577956
has comment: http://stackoverflow.com/comment/88577765
linked to: http://stackoverflow.com/q/31841096
accepted answer: http://stackoverflow.com/a/50786133
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50786074
has answer: http://stackoverflow.com/a/50786133
has comment: http://stackoverflow.com/comment/88577816
tagged with: python
has body: I'm trying to detect system suspend using the following algorithm: while True: lastchecked = now() if now() - lastchecked &gt; 1s: print "suspend detected!" But I ran into a problem: If suspend happens between 2nd and 3rd line, then the loop catches it. But if suspend happens between 1st and 2nd line, then the algorithm fails. Is there some commonly used method for this type of situation? Preferably OS-independent please, I don't want to hook into OS events and suchlike.
has title: Detecting system suspend in a loop
linked to: http://stackoverflow.com/q/694475
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/26774186
has answer: http://stackoverflow.com/a/50786074
linked to: http://stackoverflow.com/q/8067768
type: Question
tagged with: algorithm

http://stackoverflow.com/comment/88679910
type: Comment
type: QuestionComment
has text: Thank you @YSelf. Actually your comment helped more in solving the issue than the explanation on the duplicate question.(solved by commenting out app.run)
score: 0
comment on: http://stackoverflow.com/q/50833759

http://stackoverflow.com/a/50758448
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50758200
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50758200
type: Answer
upvote count: 1
has body: There are 2 possible different solutions - resampling by 15Min and aggregate columns by mean and first value: df = df.resample('15T', on='reporttime').agg({'w':'mean', 'buildingid':'first'}) Or groupbing by column buildingid with Grouper for resampling: df = df.groupby(['buildingid', pd.Grouper(key='reporttime',freq='15T')])['w'].mean() Sample: rng = pd.date_range('2017-04-03 18:09:04', periods=10, freq='7T') df = pd.DataFrame({'reporttime': rng, 'w': range(10), 'buildingid':[39] * 5 + [40] * 5}) print (df) reporttime w buildingid 0 2017-04-03 18:09:04 0 39 1 2017-04-03 18:16:04 1 39 2 2017-04-03 18:23:04 2 39 3 2017-04-03 18:30:04 3 39 4 2017-04-03 18:37:04 4 39 5 2017-04-03 18:44:04 5 40 6 2017-04-03 18:51:04 6 40 7 2017-04-03 18:58:04 7 40 8 2017-04-03 19:05:04 8 40 9 2017-04-03 19:12:04 9 40 df1 = df.resample('15T', on='reporttime').agg({'w':'mean', 'buildingid':'first'}).reset_index() print (df1) reporttime w buildingid 0 2017-04-03 18:00:00 0.0 39 1 2017-04-03 18:15:00 1.5 39 2 2017-04-03 18:30:00 4.0 39 3 2017-04-03 18:45:00 6.5 40 4 2017-04-03 19:00:00 8.5 40 df2 = df.groupby(['buildingid', pd.Grouper(key='reporttime',freq='15T')])['w'].mean().reset_index() print (df2) buildingid reporttime w 0 39 2017-04-03 18:00:00 0.0 1 39 2017-04-03 18:15:00 1.5 2 39 2017-04-03 18:30:00 3.5 3 40 2017-04-03 18:30:00 5.0 4 40 2017-04-03 18:45:00 6.5 5 40 2017-04-03 19:00:00 8.5

http://stackoverflow.com/a/50757085
score: 1
accepted answer of: http://stackoverflow.com/q/50756288
upvote count: 1
has comment: http://stackoverflow.com/comment/88522797
answers question: http://stackoverflow.com/q/50756288
has comment: http://stackoverflow.com/comment/88522612
type: AcceptedAnswer
downvote count: 0
has body: Using nested list comprehensions: &gt;&gt;&gt; y_labeled = [[1,2,2,4,4,1,1], [2,1,1,4,4,0,0], [2,2,2,2,0,0,0]] &gt;&gt;&gt; weights_dict = {1:5, 2:6, 4:19} &gt;&gt;&gt; [[weights_dict.get(x, 0) for x in sublist] for sublist in y_labeled] [[5, 6, 6, 19, 19, 5, 5], [6, 5, 5, 19, 19, 0, 0], [6, 6, 6, 6, 0, 0, 0]]
has comment: http://stackoverflow.com/comment/88522435
type: Answer

http://stackoverflow.com/comment/88473271
comment on: http://stackoverflow.com/q/50732028
has text: Ok I deleted the ad_pictures directory and this time just used "media" as the folder my images will go to, and I took out the "upload_to=" argument in an attempt to simplify things and unfortunately it's still rendering a broken image.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50714673
accepted answer of: http://stackoverflow.com/q/50714467
upvote count: 6
has comment: http://stackoverflow.com/comment/88441479
has comment: http://stackoverflow.com/comment/88438285
has comment: http://stackoverflow.com/comment/88438419
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88438737
has comment: http://stackoverflow.com/comment/88438218
has comment: http://stackoverflow.com/comment/88438858
type: Answer
has comment: http://stackoverflow.com/comment/88438789
score: 6
answers question: http://stackoverflow.com/q/50714467
has comment: http://stackoverflow.com/comment/88438939
has body: Python zipfile package can unzip files having password. def unzip_folder(zip_folder, destination, pwd): """ Args: zip_folder (string): zip folder to be unzipped destination (string): path of destination folder pwd(string): zip folder password """ with zipfile.ZipFile(zip_folder) as zf: zf.extractall( destination, pwd=pwd.encode()) In your case, import zipfile zip_folder = 'E:\\Shared\\DOWNLOADED\\c.zip' destination = 'E:\\Shared\\DOWNLOADED' pwd = '&lt;YOUR_PASSWORD&gt;' with zipfile.ZipFile(zip_folder) as zf: zf.extractall( destination, pwd=pwd.encode())
has comment: http://stackoverflow.com/comment/88438405
has comment: http://stackoverflow.com/comment/88438652

http://stackoverflow.com/comment/88688306
type: AnswerComment
comment on: http://stackoverflow.com/a/50842041
has text: I see... I'm no expert with `mpldatacursor` but as `matplotlib` scatter creates a collection, with a single label (for use in legends), you'd need to do a separate plot per point (added an example above) so each has its own label (or keep a separate list in the same order as your plotted data, which strikes me as potentially problematic).
score: 0
type: Comment

http://stackoverflow.com/q/50748203
tagged with: asynchronous
has body: I have a django project having a web interface where you can upload files and after the upload is successful it calls the cli version of the software to process it and returns the result after it's successful execution Here, is a bit of snippet I use in my views.py from cliproject.main import clirunner # Some code for file upload and saving clirunner() This will run the command line python script main.py which is present inside cliproject/ directory and it will do some stuff and saves the output The problem is, this whole process is Synchronous at this moment. Hence, the user page loads after they upload the file from the UI and until it gets processed by Python CLI script behind the scenes. The flow is as Django UI | (User upload files) views.py gets request and saves it somewhere | (views run clirunner() to give python cli program control) cliproject runs | (After doing the stuff which is intended, it saves the output file) views.py resumes | (Reads the output file) Django UI displays the output file So, we can see the problem here that I am calling a different CLI program from views.py to do the stuff which I want. But it happens synchronously. What I need is to make the process Asynchronous and I want to show something as a Loading Bar to notify them that the cli program is executing at the back-side and it's status. After CLI program is done executing then loading bar will reach 100% and asynchronously django UI will display the output I tried Celery. But I could not figure out how to make this loading bar work based on the python cli script. Any ideas?
type: UnansweredQuestion
tagged with: django
tagged with: celery
tagged with: django-views
has title: Calling Python CLI program from django views and displaying the results back asynchronously?
type: Question
score: 0
has answer: http://stackoverflow.com/a/50748637
answer count: 1
tagged with: python

http://stackoverflow.com/a/50726335
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/88493029
answers question: http://stackoverflow.com/q/50725454
has body: Here you go: import requests from bs4 import BeautifulSoup name = 'Flow' namec = 'Flow' url = 'http://warframe.wikia.com/wiki/' + name r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') main_text = soup.find('div', id='mw-content-text').find_all('div', class_='pi-data-value pi-font') for d in main_text: if d.find_next(string=True) == 'Missions:': snippets = str(d).split("&lt;br/&gt;") for snippet in snippets: snippet_soup = BeautifulSoup(snippet, 'html.parser') print(snippet_soup.text)

http://stackoverflow.com/comment/88625602
has text: How much wait are you giving? if it is less, you can try to increase.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50806124

http://stackoverflow.com/comment/88548551
comment on: http://stackoverflow.com/q/50770438
score: 0
type: Comment
type: QuestionComment
has text: Can you provide us with `reddit_urls`?

http://stackoverflow.com/comment/88811577
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50905415
has text: thanks ,is there a command for linux terminal to find number of thread?or i shoud use that only in python code?
score: 0

http://stackoverflow.com/comment/88600109
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50797048
has text: so "*/1 * * * * cd ~/Downloads/guichets && python newRdvChecker.py -G3 -S40" becomes "*/1 * * * * cd ~/Downloads/guichets && path/to/python newRdvChecker.py -G3 -S40"?

keras
tags question: http://stackoverflow.com/q/50831434
tags question: http://stackoverflow.com/q/50850477
tags question: http://stackoverflow.com/q/50806566
tags question: http://stackoverflow.com/q/50784021
tags question: http://stackoverflow.com/q/50778471
tags question: http://stackoverflow.com/q/50711764
tags question: http://stackoverflow.com/q/50819081
tags question: http://stackoverflow.com/q/50826625
tags question: http://stackoverflow.com/q/50784067
tags question: http://stackoverflow.com/q/50818972
tags question: http://stackoverflow.com/q/50741765
tags question: http://stackoverflow.com/q/50806953
tags question: http://stackoverflow.com/q/50806075
tags question: http://stackoverflow.com/q/50797135
tags question: http://stackoverflow.com/q/50811349
tags question: http://stackoverflow.com/q/50834510
tags question: http://stackoverflow.com/q/50823233
tags question: http://stackoverflow.com/q/50816800
tags question: http://stackoverflow.com/q/50853699
tags question: http://stackoverflow.com/q/50742559
tags question: http://stackoverflow.com/q/50700307
tags question: http://stackoverflow.com/q/50715679
tags question: http://stackoverflow.com/q/50831870
tags question: http://stackoverflow.com/q/50814880
tags question: http://stackoverflow.com/q/50786427
tags question: http://stackoverflow.com/q/50801878
tags question: http://stackoverflow.com/q/50834933
tags question: http://stackoverflow.com/q/50842356
tags question: http://stackoverflow.com/q/50745516
tags question: http://stackoverflow.com/q/50703942
tags question: http://stackoverflow.com/q/50767146
tags question: http://stackoverflow.com/q/50849198
tags question: http://stackoverflow.com/q/50723287
tags question: http://stackoverflow.com/q/50717846
tags question: http://stackoverflow.com/q/50709557
tags question: http://stackoverflow.com/q/50820639
tags question: http://stackoverflow.com/q/50836434
tags question: http://stackoverflow.com/q/50734672
tags question: http://stackoverflow.com/q/50841048
tags question: http://stackoverflow.com/q/50719510
tags question: http://stackoverflow.com/q/50701786
tags question: http://stackoverflow.com/q/50815325
tags question: http://stackoverflow.com/q/50779261
tags question: http://stackoverflow.com/q/50745868
tags question: http://stackoverflow.com/q/50794383
tags question: http://stackoverflow.com/q/50755544
tags question: http://stackoverflow.com/q/50742245
tags question: http://stackoverflow.com/q/50701913
tags question: http://stackoverflow.com/q/50843487
tags question: http://stackoverflow.com/q/50706992
tags question: http://stackoverflow.com/q/50703359
tags question: http://stackoverflow.com/q/50782726
tags question: http://stackoverflow.com/q/50785592
tags question: http://stackoverflow.com/q/50788098
tags question: http://stackoverflow.com/q/50709249
tags question: http://stackoverflow.com/q/50787834
tags question: http://stackoverflow.com/q/50737792
tags question: http://stackoverflow.com/q/50705899
tags question: http://stackoverflow.com/q/50822774
tags question: http://stackoverflow.com/q/50779773
tags question: http://stackoverflow.com/q/50853708
tags question: http://stackoverflow.com/q/50828699
tags question: http://stackoverflow.com/q/50825936
tags question: http://stackoverflow.com/q/50787555
tags question: http://stackoverflow.com/q/50825248
tags question: http://stackoverflow.com/q/50724762
tags question: http://stackoverflow.com/q/50823687
tags question: http://stackoverflow.com/q/50780152
tags question: http://stackoverflow.com/q/50715928
tags question: http://stackoverflow.com/q/50720828
tags question: http://stackoverflow.com/q/50849877
tags question: http://stackoverflow.com/q/50718447
tags question: http://stackoverflow.com/q/50809155
tags question: http://stackoverflow.com/q/50805980
tags question: http://stackoverflow.com/q/50729148
tags question: http://stackoverflow.com/q/50811990
tags question: http://stackoverflow.com/q/50824417
tags question: http://stackoverflow.com/q/50768538
tags question: http://stackoverflow.com/q/50737814
tags question: http://stackoverflow.com/q/50837728

http://stackoverflow.com/comment/88619736
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50806917
type: QuestionComment
has text: No idea whether this is your problem, because it's too much of a mass code dump, but from a quick glance, the C++ code is including `i` in the inner loops, but your Python code is excluding `col` in the equivalent inner loops. You really should be rewriting this stuff in idiomatic Python (e.g., `maxRight = max(height[col:])`), so off-by-one errors don't even arise in the first place. (This would also be a better answer in C++, by the way…) But if you really want to do things at the same level as the C++ code, make sure you're doing exactly the same. Print the loop variables to compare, etc.

http://stackoverflow.com/q/50846992
answer count: 1
score: 0
has title: NLTK wordnet does not contain vocabulary term - Python
has answer: http://stackoverflow.com/a/50847304
has body: A function in my program finds the definitions of certain vocabulary words, which will be useful for other parts of my program. However, it seems that not every vocabulary word is present in wordnet. I find the definitions as follows: y = wn.synset(w + '.n.01').definition() where 'w' is one of the many vocabulary words being fed from a list (did not include rest of the program because it has too much irrelevant code). When the list reaches the term 'ligase', however, the following error comes up: line 1298, in synset raise WordNetError(message % (lemma, pos)) nltk.corpus.reader.wordnet.WordNetError: no lemma 'ligase' with part of speech 'n' Is there anyway to bypass this or a different way to find the definition of these terms not in wordnet? My program is going through various scientific terms, so this may occur more often as I add more words to the list.
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50847304
tagged with: wordnet
type: Question
tagged with: nltk

http://stackoverflow.com/comment/88511775
score: 0
has text: `b = [list(map(float, x.split())) for x in a]`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50751902

http://stackoverflow.com/q/50774598
has body: I reference to the information on the Internet. I would like to painting my data. id time w 5630 39 2018-03-01 841.704067 5631 39 2018-03-02 605.119444 5632 39 2018-03-03 651.337735 5633 39 2018-03-04 595.974252 5634 39 2018-03-05 656.031315 5635 39 2018-03-06 972.101045 5636 39 2018-03-07 660.659986 5637 39 2018-03-08 1225.648122 . . 5685 39 2018-04-25 699.347653 5686 39 2018-04-26 516.267288 5687 39 2018-04-27 621.807574 5688 39 2018-04-28 488.903030 5689 39 2018-04-29 790.637525 5690 39 2018-04-30 457.569811 5691 40 2018-03-01 157.636364 5692 40 2018-03-02 138.759563 5693 40 2018-03-03 209.213996 5694 40 2018-03-04 177.255571 5695 40 2018-03-05 155.696106 . . 5748 40 2018-04-27 133.512968 5749 40 2018-04-28 157.630623 5750 40 2018-04-29 210.996613 5751 40 2018-04-30 120.643963 My reference URL I execute this: fig, ax = plt.subplots(figsize=(15,7)) df2.groupby(['time','id']).count()['w'].unstack().plot(ax=ax) But my result is strange. I would like to painting like this: I just cut out my sample, but I want to draw it all at once. Overlap or alone. How to achieve similar results below. I really need your help.Many thanks.
linked to: http://stackoverflow.com/q/29975835
has answer: http://stackoverflow.com/a/50774626
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/50774626
has title: How does using python Pandas unstack in plt?
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/50797503
has answer: http://stackoverflow.com/a/53374535
downvote count: 0
has body: I have a simple impyla code, and I would like to create a pandas dataFrame from my cursor. My code is running but my dataframe is always an empty dataframe. If I run my query directly on impala, the result is not empty. This is how my code looks like: from impala.dbapi import connect from impala.util import as_pandas conn = connect(host='impala_server', port=21051, user='user' , password='pass', use_ssl=True, auth_mechanism='PLAIN') cursor = conn.cursor() cursor.execute("SELECT * FROM TABLE") results = cursor.fetchall() df = as_pandas(cursor) print(df.head()) Help me please, what am I doing wrong?
tagged with: pandas
tagged with: impyla
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/63010669
type: UnansweredQuestion
tagged with: python
score: 2
has title: impyla - as_pandas - empty dataframe
type: Question
answer count: 2

http://stackoverflow.com/comment/88501845
has text: Strip, lstrip, and rstrip let you specify which characters will be stripped: https://docs.python.org/2/library/string.html#string.strip
comment on: http://stackoverflow.com/q/50747043
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88717642
has text: Rather than encoding the strings it might be worth doing some NLP with them instead. Something like tf-idf might be a good place to start.
comment on: http://stackoverflow.com/q/50852700
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50801454
favorite count: 0
has body: What's the difference between the following: a = np.array([2,3,4]) b = np.array([2,7,8]) if a.any() == b.all(): print('yes') and a = np.array([2,3,4]) b = np.array([2,7,8]) if a.any() == b.any(): print('yes') In both situations, 'yes' is printed.
has answer: http://stackoverflow.com/a/50801865
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: conditional-statements
upvote count: 3
has answer: http://stackoverflow.com/a/77453834
has comment: http://stackoverflow.com/comment/88609695
has comment: http://stackoverflow.com/comment/88608767
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50801871
accepted answer: http://stackoverflow.com/a/50801865
has answer: http://stackoverflow.com/a/50801871
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/88609657
tagged with: logic
has title: Understanding the use of any() and all() in numpy arrays
has comment: http://stackoverflow.com/comment/88618092
answer count: 3

http://stackoverflow.com/comment/136837246
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50725771
has text: Provide example where "(a + b) + c is not the same as a + (b + c)"

http://stackoverflow.com/q/50821484
has comment: http://stackoverflow.com/comment/88648385
type: Question
has comment: http://stackoverflow.com/comment/88648340
has comment: http://stackoverflow.com/comment/88648344
has answer: http://stackoverflow.com/a/50824069
has body: day = ([ 1 , 2 , 5 , 6 , 7 , 8 , 9]) rain = ([0.6 , 0.8 , 1 , 6 , 6.5 ,7 , 4]) snow = ([ 1 , 2 , 0.5 , 7 , 8 , 9 , 10]) if I want to plot day on x axis and rain and snow on y axis, and for example have a dotted line joining for the days that are missing information how do I do this? plt.figure() plt.plot(day,rain, marker='o') plt.plot(day, snow, marker='o') plt.show()
upvote count: 3
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: plot
score: 2
has title: Python plotting missing data
has comment: http://stackoverflow.com/comment/88648213
tagged with: matplotlib

http://stackoverflow.com/comment/88545208
comment on: http://stackoverflow.com/a/50753082
score: 0
type: Comment
has text: @Bijoy PERFECT. Really i don't undertand completely how it works but the functions do what is supossed to. Thank you so much!
type: AnswerComment

http://stackoverflow.com/comment/88695906
type: QuestionComment
has text: How am i supposed to change the certain integer values without calling the function with extra brackets under command? Like `mybutton = tk.Button(parent, text='Whatever', command=myclick(a,b,c))`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50845828

http://stackoverflow.com/q/50700671
type: UnansweredQuestion
has body: This is my first project using Python. I'm encountering a problem while displaying the values ​​in my table. AttributeError: type object 'Client' has no attribute 'query' from flask import Flask, render_template, request, url_for, redirect import os from sqlalchemy import * from sqlalchemy import create_engine, ForeignKey from sqlalchemy import Column, Date, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref,sessionmaker engine = create_engine('sqlite:///banco.db', echo=True) db = declarative_base() class Cliente(db): __tablename__ = 'cliente' _idCliente = Column(Integer, primary_key =True, autoincrement = True) nmCliente = Column (String) def __init__ (self, nmCliente): self.nmCliente = nmCliente db.metadata.create_all(engine) app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route("/cadastros/cliente") def cadastroCliente(): return render_template ("cadastroCliente.html") @app.route("/cadastrar/cliente", methods=['GET','POST']) def cadastrarCliente(): if request.method == "POST": nmCliente = request.form.get("nmCliente") if nmCliente: c = Cliente(nmCliente) db.session.add(c) db.session.commit() return redirect(url_for("cadastroCliente")) @app.route("/consulta/cliente") def consulta(): cliente = Cliente.query.all() return render_template("consultaClientes.html", cliente = cliente) if __name__ == '__main__': app.run(debug=True) Python 2.7, what should i change? I followed some tutorials and it worked
downvote count: 1
type: Question
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/50700991
answer count: 1
score: 1
tagged with: flask
favorite count: 0
has title: AttributeError: type object 'Cliente' has no attribute 'query'
tagged with: python
upvote count: 2

automation
tags question: http://stackoverflow.com/q/50843636
tags question: http://stackoverflow.com/q/50818782
tag name: automation
tags question: http://stackoverflow.com/q/50705645
tags question: http://stackoverflow.com/q/50790266
tags question: http://stackoverflow.com/q/50817078
tags question: http://stackoverflow.com/q/50822230
tags question: http://stackoverflow.com/q/50752200
type: Tag
tags question: http://stackoverflow.com/q/50730539
tags question: http://stackoverflow.com/q/50816879
tags question: http://stackoverflow.com/q/50773103
tags question: http://stackoverflow.com/q/50698948
tags question: http://stackoverflow.com/q/50796675
tags question: http://stackoverflow.com/q/50757275
tags question: http://stackoverflow.com/q/50806165
tags question: http://stackoverflow.com/q/50807664
tags question: http://stackoverflow.com/q/50842653

http://stackoverflow.com/q/50748569
has body: I am working on my first project and I am using Pygal to visualize some data from a database. I am using the latest version of Python (3.6.5), Flask, Pygal and my IDE is Pycharm The project is a simple budget application in which one enters the planned budget for a monthly expenditure and then the actual amounts for that expense/item (e.g. monthly car expenses, like gas). I use Pygal to show 2 bar charts. The first one (which works as intended) shows a total planned amounts vs total actual amounts: The second chart shows the planned vs actual per expense/item (e.g. monthly car expenses, like gas) The issue I am facing is that the chart mixes up the labels and amounts. They show up in the chart based on the order they are entered, not on the item type. For example: In the above image, the are 3 items: Masina (car), Salariu (salary) and Economii (savings). The amount represented by the blue column (the actual amount) should show up under the label Economii, not under Masina and it should not matter that I have entered it as the first actual in the database. Also, adding more actual amounts for the same expenses item (Economii in our case) in the database simply adds more columns and it does not sum it up on the same column: This is the database query function I am using: def GraphData(): BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, 'budget_db.db') with sqlite3.connect(db_path) as db: c = db.cursor() d = db.cursor() c.execute('SELECT title, category, name, planned_amount_month FROM Post') d.execute('SELECT title_actual, category_actual, actual_amount_name, actual_amount FROM ActualPost') data_planned = c.fetchall() data_actual = d.fetchall() return data_planned, data_actual Below is the route I have created for both of the charts. The labels are pulled from the title_planned list and I have a feeling that the issue I am facing is because I am creating lists and I am appending them. I think I should create dictionaries, but I ha…
has title: Python Pygal chart pulling data from database not matching values to labels
tagged with: pygal
type: AnsweredQuestion
tagged with: charts
tagged with: database
has answer: http://stackoverflow.com/a/50783680
type: Question
accepted answer: http://stackoverflow.com/a/50783680
answer count: 1
score: 0
tagged with: python

http://stackoverflow.com/q/50700897
has body: I want transfer page_number to url with name='onePart' from part_list.html. In my code page_number=1, but I want change it to current page of paginator depends on page. How I can do this? P.S. sorry for my english:) views.py: def PartyNumView(request, page_number = 1): all_parties = Part.objects.all() current_page = Paginator(all_parties, 1) try: context = current_page.page(page_number) except PageNotAnInteger: context = current_page.page(1) except EmptyPage: context = current_page.page(current_page.num_pages) return render_to_response('part_list.html', {'PartyNum': context}) def forOne(request, pk): onePart = get_object_or_404(Part, pk=pk) return render_to_response('SinglePart.html', {'onePart': onePart}) **urls.py:** urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^parties/(\d+)/$', PartyNumView), url(r'^parties', PartyNumView), url(r'parties/(?P&lt;page_number&gt;[\d]+)/(?P&lt;pk&gt;[\d]+)$', forOne, name='onePart'), url(r'^main/', TemplateView.as_view(template_name='main.html')), #static html url(r'^measures/', TemplateView.as_view(template_name='IcDesc.html')), #static html ] A little bit of HTML code part_list.html: {% for object in PartyNum %} &lt;tr&gt; &lt;td&gt;{{ forloop.counter }}&lt;/td&gt; &lt;td&gt;&lt;a href="{% url 'onePart' pk=object.pk page_number=1%}"&gt; {{ object.Party_number }}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{ object.Film }}&lt;/td&gt; &lt;td&gt;{{ object.Thick }}&lt;/td&gt; &lt;td&gt;{{ object.Critical_temperature }}&lt;/td&gt; &lt;td&gt;{{ object.R_s }}&lt;/td&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; &lt;/table&gt; &lt;div class="row" style="margin:auto"&gt; &lt;div class="large-3 large-offset-5 columns"&gt; &lt;ul class="pagination"&gt; {% if PartyNum.has_previous %} &lt;li class="arrow"&gt;&lt;a href="/parties/{{ PartyNum.previous_page_number }}/"&gt;&amp;laquo;&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class="arrow disabled"&gt;&lt;a href=""&gt;&amp;laquo;&lt;/a&gt;&lt;/li&gt; {% endif %} {% for page in PartyNum.paginator.page…
has title: How to transfer page_number to urls.py
has comment: http://stackoverflow.com/comment/88411189
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50701548
downvote count: 1
has comment: http://stackoverflow.com/comment/88414409
type: Question
has comment: http://stackoverflow.com/comment/88412376
has comment: http://stackoverflow.com/comment/88413865
has comment: http://stackoverflow.com/comment/88412258
has comment: http://stackoverflow.com/comment/88414838
score: 0
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50831205
downvote count: 0
answer count: 1
has body: I've taken over a project that uses python and flask (and I'm new to python/flask too!). I'd like to add Sentry to it to capture any errors/exceptions that happen. To add to the complexity the project is split into multiple docker containers that link to each other. I'm trying at first to get the main "frontend" container to start logging errors to Sentry. I've read the documentation but it's only served to confuse me even more. For example (from the frontend.py file): app = WebServer(logger, environment) sentry = Sentry(app, logging=True, level=logging.INFO) This is in the frontend part of the app. From what I understand this should allow Sentry to capture any exceptions and send it off, but nothing happens (I did a simple division by zero to force an exception). I'm sure I'm probably missing something but I'm just confused by the documentation. For example, in the logging option (I've been considering maybe using this option instead), it talks about setting up a client manually. What client is it talking about? I've set up Sentry to work in a PHP Laravel app before with no problems at all, and it was very very easy to do. This python way is confusing the hell out of me.
has comment: http://stackoverflow.com/comment/88702256
has comment: http://stackoverflow.com/comment/88667444
favorite count: 0
has comment: http://stackoverflow.com/comment/88702571
tagged with: python
has comment: http://stackoverflow.com/comment/88667057
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/88703692
has comment: http://stackoverflow.com/comment/88698838
type: Question
tagged with: flask
has answer: http://stackoverflow.com/a/50902954
accepted answer: http://stackoverflow.com/a/50902954
tagged with: sentry
has title: Setting up Sentry not working - nothing sent to Sentry

http://stackoverflow.com/q/50849700
type: Question
has title: Python how to open any file without explicit application call
duplicate of: http://stackoverflow.com/q/434597
score: 1
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/434597
has body: I was wondering if there was a way to open a file and have the OS/Python handle what applications to use to open it like how the OS typically does. For example if I have the path of a pdf file, it would automatically open the pdf file with the default pdf reader like adobe. If it is a mp4 file, it would use default video player like VLC. Or if it is a text file it would use notepad. Do I have to explicitly handle each file extension or is there an easier way?

http://stackoverflow.com/comment/88531346
type: QuestionComment
has text: Thank you so much! @Jean-FrançoisFabre
comment on: http://stackoverflow.com/q/50761749
score: 0
type: Comment

http://stackoverflow.com/q/50716344
tagged with: cloud9
has title: BOOTSTRAP // not working despite adding cdn links and reference style link // PYTHON
answer count: 2
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
favorite count: 0
tagged with: twitter-bootstrap
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm currently in the middle of building this Django app and after I got the main parts that I wanted which were the login page and the homepage working, I decided on updating the look of my page because it was VERY basic. I've used bootstrap a ton before and I'm in love with it. However, this problem to me is a first. As you will see down below I have linked bootstrap via CDN (TWICE) and also via reference stylesheet link. Despite all these different ways of getting bootstrap my page still looks like this . Here is my base_generic.html {% load staticfiles %} {% block title %} Local Library {% endblock %} {% load static %} {% include "header.html" %} {% block content %}{% endblock %} {% include "pagination.html" %} And here is my header.html file that has my navbar {% load staticfiles %} Navbar Home (current) Link Disabled Dropdown Action Another action Something else here Search Heres what my file structure looks like Any input or feedback would be helpful really. I'm really stuck here.
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/65324909
has answer: http://stackoverflow.com/a/53300693
type: Question

http://stackoverflow.com/comment/88599566
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50796522
type: AnswerComment
has text: While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

http://stackoverflow.com/a/50723894
has body: You can use the io module: import io FILES = {} f = io.BytesIO() FILES{'file'] = ("dummy.txt", f) response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES) Here is the convert_base64_to_file function: import base64 import io def convert_base64_to_file(data): return io.BytesIO(base64.b64decode(data))
type: Answer
accepted answer of: http://stackoverflow.com/q/50723795
has comment: http://stackoverflow.com/comment/88457089
answers question: http://stackoverflow.com/q/50723795
upvote count: 1
has comment: http://stackoverflow.com/comment/88457825
has comment: http://stackoverflow.com/comment/88457327
has comment: http://stackoverflow.com/comment/88456098
has comment: http://stackoverflow.com/comment/88456959
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88456306

http://stackoverflow.com/q/50758785
score: 0
has comment: http://stackoverflow.com/comment/88526158
upvote count: 1
has comment: http://stackoverflow.com/comment/88525022
downvote count: 1
tagged with: awk
has title: Extract words from tree
favorite count: 0
tagged with: grep
tagged with: python
has comment: http://stackoverflow.com/comment/88525623
has comment: http://stackoverflow.com/comment/88526021
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88536298
has body: I am working with Recursive Neural Networks and have to use pre-trained GLOVE word embeddings. As my dataset is small I don't want to use all embeddings, only the ones in my dataset. The glove text file looks like: throughout 0.099415 0.063893 -0.65517 -0.31035 -0.54867 -0.31378 -0.75248 0.11362 0.029626 -0.23832 0.054125 -0.6937 0.019753 -0.25373 0.12972 -0.16954 -0.40668 -0.25018 -0.36012 -0.32704 0.15759 0.041711 0.39897 0.53711 0.058105 -0.8139 -0.39827 0.077777 0.2354 0.27001 3.6635 0.35466 0.81482 -1.1884 -0.29611 0.5244 -0.45087 0.13699 -0.93812 0.4332 -0.45985 0.13347 -0.069847 0.097409 -0.073005 0.55471 -0.13301 -0.47559 -1.057 -0.60987 established 0.083877 0.14873 -0.80328 -0.24779 -0.10944 -0.11647 -0.87871 -0.43654 0.015808 -0.61117 0.83698 0.39583 -0.1244 -0.36991 -0.43331 0.23538 0.14534 0.2862 0.00098344 0.74532 0.7003 -0.34758 -0.29388 0.17333 -0.51236 -1.2029 -0.35278 -1.1695 -0.61088 0.18471 3.0157 -0.67365 -0.45001 -1.0056 0.034002 -0.026611 0.0097914 0.55304 -0.19343 0.44712 -0.33502 -0.91209 0.19758 -0.035535 -0.77284 0.28167 -0.6852 -0.62592 -0.36489 -0.22197 mission 1.9144 0.40923 -0.31422 -0.6443 0.55513 -0.81588 -0.766 0.18716 0.94453 -1.0715 0.52092 0.20347 -0.36264 0.5649 -0.30487 -0.13143 0.080574 0.16483 -0.25986 0.45458 -0.40467 0.7947 -0.66128 -0.49532 0.31973 -1.1424 0.097268 -0.48496 -0.17357 0.29176 2.7318 -0.073546 -1.7509 -0.86062 -0.0093403 0.021347 -0.006449 -0.18159 -0.27718 0.10547 -0.30741 -0.48023 0.40922 -1.2402 -0.476 0.30602 0.32634 0.62645 -0.91152 0.42901 associated 0.23032 1.0919 -0.029497 0.749 -0.17768 0.22918 -0.38591 -0.15044 0.25437 -0.35935 0.42707 0.056076 -0.3842 -0.35789 0.35419 0.45716 -0.15932 -1.0055 0.25288 0.0078635 -0.031715 0.16926 0.90977 0.36871 0.04203 -0.81182 -0.81018 -0.40931 -0.2312 0.50252 2.6289 -0.57009 0.87378 -1.6698 -0.13101 0.28056 0.040286 -0.12814 0.23653 1.2403 0.29779 0.94279 -0.057406 -0.17155 0.96692 -0.055877 -0.48754 0.25528 0.12889 0.10638 The input data (text file) is in the form…
type: Question

http://stackoverflow.com/comment/88691429
has text: you can also refer this [post](https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python) to redirect stdout to a file.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50843876

http://stackoverflow.com/a/50733845
type: Answer
answers question: http://stackoverflow.com/q/50722486
score: 0
has body: here is my code according to changes. from pad4pi import rpi_gpio import time # Setup Keypad KEYPAD = [ ["1","2","3","A"], ["4","5","6","B"], ["7","8","9","C"], ["*","0","#","D"] ] # same as calling: factory.create_4_by_4_keypad, still we put here fyi: ROW_PINS = [16, 20, 21, 5] # BCM numbering; Board numbering is: 7,8,10,11 (see pinout.xyz/) COL_PINS = [6, 13, 19, 26] # BCM numbering; Board numbering is: 12,13,15,16 (see pinout.xyz/) factory = rpi_gpio.KeypadFactory() # Try keypad = factory.create_4_by_3_keypad() or # Try keypad = factory.create_4_by_4_keypad() #for reasonable defaults # or define your own: keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS) class KeyStore: def __init__(self): #list to store them self.pressed_keys ='' #function to clear string def clear_keys(self): self.pressed_keys = self.pressed_keys.replace(self.pressed_keys,'') def store_key(self,key): if key=='#': #printing the sequence of keys. print(self.pressed_keys) self.clear_keys() else: self.pressed_keys += key keys = KeyStore() # store_key will be called each time a keypad button is pressed keypad.registerKeyPressHandler(keys.store_key) try: while(True): time.sleep(0.2) except: keypad.cleanup()

http://stackoverflow.com/q/50763717
has title: Jupyter Notebook bad HTML export
tagged with: python
tagged with: jupyter-notebook
has body: I have changed the theme in my Jupyter Notebook to chesterish: pip install jupyterthemes jt -t chesterish The Notebook itself is displayed in a nice way, however, when downloading it as an HTML file (File &gt; Download as &gt; HTML (.html)), the font colors of the original default white theme are used while keeping the background of the chesterish theme, which makes it look ugly and mostly unreadable. Is it possible to export a Notebook to HTML using the chesterish native font colors? Jupyter notebook with chesterish theme: Generated HTML: Used code: # Notebook for i in range(5): print "Hello world!"
answer count: 0
upvote count: 3
type: UnansweredQuestion
type: Question
score: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50723528
answers question: http://stackoverflow.com/q/50723416
upvote count: 1
type: Answer
has body: This is one approach. Using a simple iteration. Demo: res = [] with open(filename, "r") as infile: for line in infile: if not line.strip(): break else: res.append(line) print( "".join(res) )
has comment: http://stackoverflow.com/comment/88455502
downvote count: 0
score: 1

http://stackoverflow.com/comment/88668321
score: 1
type: Comment
has text: If you have sample images of every type of input that you'll get then your best bet would be to train a neural network. For inspiration look at [this video](https://redd.it/8p9car).
type: QuestionComment
comment on: http://stackoverflow.com/q/50829874

http://stackoverflow.com/q/50737192
has title: tf.data.Dataset: how to get the dataset size (number of elements in an epoch)?
score: 73
has answer: http://stackoverflow.com/a/68557100
has body: Let's say I have defined a dataset in this way: filename_dataset = tf.data.Dataset.list_files("{}/*.png".format(dataset)) how can I get the number of elements that are inside the dataset (hence, the number of single elements that compose an epoch)? I know that tf.data.Dataset already knows the dimension of the dataset, because the repeat() method allows repeating the input pipeline for a specified number of epochs. So it must be a way to get this information.
has comment: http://stackoverflow.com/comment/88483618
has answer: http://stackoverflow.com/a/65280883
has answer: http://stackoverflow.com/a/61019377
has comment: http://stackoverflow.com/comment/88482520
has answer: http://stackoverflow.com/a/66380817
has answer: http://stackoverflow.com/a/69026327
has answer: http://stackoverflow.com/a/57264695
downvote count: 0
has answer: http://stackoverflow.com/a/61485424
has answer: http://stackoverflow.com/a/56368864
has comment: http://stackoverflow.com/comment/111461394
tagged with: tensorflow-datasets
favorite count: 0
answer count: 19
has answer: http://stackoverflow.com/a/64909950
accepted answer: http://stackoverflow.com/a/50737863
tagged with: python-3.x
has answer: http://stackoverflow.com/a/58792474
has answer: http://stackoverflow.com/a/63487037
has answer: http://stackoverflow.com/a/66198006
has answer: http://stackoverflow.com/a/62260393
has comment: http://stackoverflow.com/comment/88482572
has comment: http://stackoverflow.com/comment/88484345
has answer: http://stackoverflow.com/a/61745078
tagged with: python
has answer: http://stackoverflow.com/a/50737863
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88483579
has answer: http://stackoverflow.com/a/76742492
has comment: http://stackoverflow.com/comment/88484282
has answer: http://stackoverflow.com/a/57868119
upvote count: 73
has answer: http://stackoverflow.com/a/71770496
has comment: http://stackoverflow.com/comment/88482875
has comment: http://stackoverflow.com/comment/88483307
possible better answer: http://stackoverflow.com/a/56368864
tagged with: tensorflow
has answer: http://stackoverflow.com/a/66486699
type: Question

http://stackoverflow.com/comment/88701541
comment on: http://stackoverflow.com/q/50849097
has text: u can try `CLASS[DURATION>0]`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50815763
accepted answer of: http://stackoverflow.com/q/50721746
type: AcceptedAnswer
has body: When I run test_trace() I see no mention of any str calls in any of the profiled events. That's because str() is a type object defined entirely in C. Only function calls are traced, not type calls, so no c_call event is issued. You could work around this by replacing the str built-in; you can alter Python's builtins via the builtins module: import builtins orig_str = builtins.str def traceable_str(*args): return orig_str(*args) builtins.str = traceable_str You can now see traceable_str calls be passed to the profiling function. However, note that only calls from Python code to str() will be traced! Anything implemented in C, like the print() function, doesn't even call the str() builtin, it just uses the C API to achieve the same results.
downvote count: 0
answers question: http://stackoverflow.com/q/50721746
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/88486715
score: 0
comment on: http://stackoverflow.com/a/50739630
type: AnswerComment
type: Comment
has text: yeah but the thing is that I want to keep the breaks on the strings, I jus want them with the breaks next to each other (string1 with breaks + string2 + breaks next to each other)

http://stackoverflow.com/q/50758950
score: 0
has answer: http://stackoverflow.com/a/50760150
tagged with: pyqt5
type: Question
has body: I made two ui with QT designer, and I called these ui with uic.loadUi(). I want to make a shortcut to exit code with keyPressEvent because all my GUI run as fullscreen. code will run in raspberry pi. I found a code with keyPressEvent, but it works only on self.show() window. I don't use that window, but the event do not works on my ui window. How can I run keyPressEvent in my ui window that made with QTdesigner?(self.ui and self.goodsUi) class Form(QtWidgets.QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) I want to use this two windows self.ui = uic.loadUi("ui/a.ui") self.goodsUi = uic.loadUi("ui/goods.ui") self.ui.showFullScreen() self.goodsUi.showFullScreen() I Want to remove this window/I don't use it self.showFullScreen() self.resize(10, 10) this is keypressevent that works only in self.show()window def keyPressEvent(self, event): if event.key() == Qt.Key_D: sys.exit(1) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = Form() sys.exit(app.exec())
tagged with: keypress
answer count: 1
tagged with: user-interface
has comment: http://stackoverflow.com/comment/88525908
tagged with: python
has title: pyqt5: Can't run keyPressedEvent at GUI Window that made in QTdesigner
type: UnansweredQuestion

http://stackoverflow.com/q/50812578
type: Question
accepted answer: http://stackoverflow.com/a/50812820
downvote count: 0
tagged with: iso8601
has answer: http://stackoverflow.com/a/50812820
tagged with: datetime
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88630445
has title: How to compare ISO-8601 dates in python
tagged with: python
has comment: http://stackoverflow.com/comment/88630719
has body: I have a date in ISO-8601 format date="2018-03-13T17:22:20.065Z" I want to find the current UTC time in iso9621 format. I found some code snippet like datetime.datetime.utcnow().isoformat() which gives us the following result 2018-06-12T08:19:28.954375 I want to find if the provided date is older than 30 days or not. I tried to solve it as shown in this question import datetime import dateutil.parser insertion_date = dateutil.parser.parse('2018-03-13T17:22:20.065Z') diffretiation=datetime.datetime.utcnow().isoformat() - insertion_date print diffretiation print insertion_date if diffretiation.days&gt;30: print "The insertion date is older than 30 days" else: print "The insertion date is not older than 30 days" I found the following error here Traceback (most recent call last): File "test2.py", line 5, in &lt;module&gt; right_now_30_days_ago=datetime.datetime.utcnow().isoformat() - insertion_date TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime' Any help would be great here
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88630750
linked to: http://stackoverflow.com/q/46046136

http://stackoverflow.com/comment/88490858
has text: This is the desired output. Yet, in my question I used the sum as a simple example. In actuality what I need is a multiplication of the 1st,2nd and 3rd item (0.299*A + 0.587*B+ 0.114*C). Where `A,B,C` are the 1st,2nd,3rd number per element. I'll update my question.
type: Comment
comment on: http://stackoverflow.com/a/50741489
score: 0
type: AnswerComment

http://stackoverflow.com/a/50746609
type: AcceptedAnswer
score: 0
has body: I have not found any solve of this problem by native in django. I used dal select2 form. I define Select2QuerySetView for every Profile field and filter queryset in it + filter by search.
type: Answer
accepted answer of: http://stackoverflow.com/q/50741687
answers question: http://stackoverflow.com/q/50741687

http://stackoverflow.com/q/50817991
upvote count: 1
tagged with: python-requests
downvote count: 1
type: Question
score: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has title: Web Scraping loop structure issues
tagged with: python
has answer: http://stackoverflow.com/a/50818605
has body: I'm currently writing some code to web scrape from AutoTrader as a practice project. I'm having trouble printing the results I need. The desired output should be: Car 1 Specs Car 1 Instead, it's Car 1 Specs Car 1 Specs Car 2 Specs Car X car 2 Where in my looping structure am I going wrong? from bs4 import BeautifulSoup import requests page_link = ("https://www.autotrader.co.uk/car-search?sort=price-asc&amp;radius=1500&amp;postcode=lu15jq&amp;onesearchad=Used&amp;onesearchad=Nearly%20New&amp;onesearchad=New&amp;make=AUDI&amp;model=A5&amp;price-to=8500&amp;year-from=2008&amp;maximum-mileage=90000&amp;transmission=Automatic&amp;exclude-writeoff-categories=on") LN = 0 r = requests.get(page_link) c = r.content soup = BeautifulSoup(c,"html.parser") all = soup.find_all("h2",{"class":"listing-title title-wrap"}) all2 = soup.find_all('ul',{"class" :'listing-key-specs '}) The above block of code is fine. The below block prints the outputs. LN = -1 ListTotal = len(all) for item in all: if LN &lt;= ListTotal: LN += 1 print(item.find("a", {"class": "js-click-handler listing-fpa-link"}).text) for carspecs in all2: print (carspecs.text) else: break Thanks
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50818605
tagged with: web-scraping

http://stackoverflow.com/a/50757926
score: 1
type: Answer
has body: Your regex solution does not work - you need to get the original file names to exclude them, based on a given lock-file-name. You are only excluding the lockfiles from all xlsx files in your dir. This could be a first step into the correct direction - carefully review the last problematic one though - you would have to fix that somehow: # exel/word/powerpoint create a lock-file with by prepending ~$ to a filename that you open. # the complete lock-file name is different for different lengths of original file lengths. # Depending on the original name you get # ~$name.xlsx from name.xlsx # ~$1name.xlsx from 1name.xlsx # ~$12name.xlsx from 12name.xlsx # ~$23name.xlsx from 123name.xlsx # ~$34name.xlsx from 1234name.xlsx import re # file lists all *.xlsx NOT starting with ~$ file = ["test.xlsx", "1test.xlsx", "12test.xlsx", "123test.xlsx", "1234test.xlsx"] # these are only the lockfiles starting with ~$ lock = ["~$1test.xlsx", "~$12test.xlsx", "~$23test.xlsx", "~$34test.xlsx","~$test.xlsx"] for lockFile in lock: lockBase = lockFile[2:] # remove the ~$ nonOpen = [x for x in file if not (x == lockBase or x.endswith(lockBase))] isOpen = [x for x in file if x.endswith(lockBase)] print("Locfile:", lockFile) print("Is open:", isOpen) print("Non open", nonOpen) Output: Locfile: ~$1test.xlsx Is open: ['1test.xlsx'] Non open ['test.xlsx', '12test.xlsx', '123test.xlsx', '1234test.xlsx'] Locfile: ~$12test.xlsx Is open: ['12test.xlsx'] Non open ['test.xlsx', '1test.xlsx', '123test.xlsx', '1234test.xlsx'] Locfile: ~$23test.xlsx Is open: ['123test.xlsx'] Non open ['test.xlsx', '1test.xlsx', '12test.xlsx', '1234test.xlsx'] Locfile: ~$34test.xlsx Is open: ['1234test.xlsx'] Non open ['test.xlsx', '1test.xlsx', '12test.xlsx', '123test.xlsx'] # problematic - all other files end on this pattern, you would have # to smarten the testing quite a bit to avoid this: Locfile: ~$test.xlsx Is open: ['test.xlsx', '1test.xlsx', '12test.xlsx', '123test.xlsx', '1234test.xlsx'] Non open [] # all end on …
upvote count: 1
answers question: http://stackoverflow.com/q/50757504
downvote count: 0

http://stackoverflow.com/comment/88679137
type: QuestionComment
has text: Yes, first I fit the model using X,y and then save it. But, when I reload the model it cannot predict anything and gives the error.
comment on: http://stackoverflow.com/q/50826359
score: 0
type: Comment

http://stackoverflow.com/q/50755400
tagged with: python
has title: Write Python dataframe to Oracle
linked to: http://stackoverflow.com/q/28461229
type: UnansweredQuestion
has body: I have a dataframe testdata like this: Here are the variables' types in Python: detectorid:int64 starttime:str volume:float64 speed:float64 occupancy:float64 Now I want to creat a datatable in oracle and insert this dataframe into it, here is what I tried: import pandas as pd import cx_Oracle host = "192.168.1.100" port = "1521" sid = "orcl" dsn = cx_Oracle.makedsn(host, port, sid) conn = cx_Oracle.connect("scott", "tiger", dsn) cursor = conn.cursor() #creat datatable： sql_creat = "create table portland(detectorid number(32), starttime varchar(32), volume number(32), speed number(32), occupancy number(32))" cursor.execute(sql_creat) query = "insert into portland (detectorid,starttime,volume,speed,occupancy) VALUES (%d,'%s',%f,%f,%f)" #insert by rows： for i in range(len(testdata)): detectorid= testdata.ix[i,0] starttime= testdata.ix[i,1] volume= testdata.ix[i,2] speed= testdata.ix[i,3] occupancy= testdata.ix[i,4] cursor.execute(query % (detectorid,starttime,volume,speed,occupancy)) conn.commit() cursor.close() conn.close() However it gives me DatabaseError: ORA-00984:column not allowed here. I think there are something wrong about the columns' types in my sql statement but I don't know how to solve it. Could somebody give me some instructions? Thank you for your attention!
has answer: http://stackoverflow.com/a/50759433
score: 1
has comment: http://stackoverflow.com/comment/88523321
has comment: http://stackoverflow.com/comment/88525401
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/88518954
has comment: http://stackoverflow.com/comment/88526176
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88522495
favorite count: 0
has comment: http://stackoverflow.com/comment/88518911
tagged with: oracle-database

http://stackoverflow.com/q/50797087
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88600353
has answer: http://stackoverflow.com/a/50797174
has comment: http://stackoverflow.com/comment/88601188
tagged with: python
has comment: http://stackoverflow.com/comment/88669700
has comment: http://stackoverflow.com/comment/88600485
downvote count: 1
type: Question
has body: I have multiple files in a directory : 00- filename1 01- filename2 02- filename3 03- filename4 etc. I am trying to replace 00 in the file name with 01, and 01 ==> 02 Using Python. which would result in the following: 01- filename1 02- filename2 03- filename3 04- filename4
has title: how to rename multiple files at once using python
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88600106
score: -1
favorite count: 0
linked to: http://stackoverflow.com/q/17748228

http://stackoverflow.com/comment/88559919
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50776137
has text: @Ben.T worked like a charm

http://stackoverflow.com/comment/88493998
type: AnswerComment
comment on: http://stackoverflow.com/a/50742150
type: Comment
has text: @ViniciusMorais I changed my answer. Have a look.
score: 0

http://stackoverflow.com/a/50907886
has body: You can take a look at my TFClassify-Unity example. It uses trained model from official Tensorflow repo, but you can try your own by renaming its extension from '.pb' to '.bytes' and replacing default one with it.
answers question: http://stackoverflow.com/q/50831358
type: Answer
has comment: http://stackoverflow.com/comment/96003929
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/96040752
downvote count: 0

http://stackoverflow.com/q/50716573
tagged with: dataframe
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/50717801
downvote count: 0
has comment: http://stackoverflow.com/comment/88446659
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: How to compare cell values of two different DataFrames in Python?
has comment: http://stackoverflow.com/comment/88482422
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50717801
has body: I have two DataFrames: Person_df Name Emplid Country 0 DK 123 India 1 JS 456 India 2 RM 789 China 3 MS 111 China 4 SR 222 China Target_df Country Category Target 0 India Marketing Reduce spend by $xy. 1 India R&amp;D Increase spend by $dd. 2 India Infra Reduce spend by $kn. 3 China Marketing Increase spend by $eg. 4 China R&amp;D Increase spend by $cb. 5 China Infra Reduce spend by $mn. My aim is to create a third DataFrame based on the country of each person, which would look like this: Individual_df TargetID Category Target DK12301 Marketing Reduce spend by $xy. DK12302 R&amp;D Increase spend by $dd. DK12303 Infra Reduce spend by $kn. JS45601 Marketing Reduce spend by $xy. JS45602 R&amp;D Increase spend by $dd. JS45603 Infra Reduce spend by $kn. RM78901 Marketing Increase spend by $eg. RM78902 R&amp;D Increase spend by $cb. RM78903 Infra Reduce spend by $mn. MS11101 Marketing Increase spend by $eg. MS11102 R&amp;D Increase spend by $cb. MS11103 Infra Reduce spend by $mn. SR22201 Marketing Increase spend by $eg. SR22202 R&amp;D Increase spend by $cb. SR22203 Infra Reduce spend by $mn. Basically I have to take a person from Person_df, match his/her country with country mentioned in Target_df and then assign each of this target to this person(and store in Individual_df). Problem is, I am new to python and can't really figure out how to carry out this comparison of country. I wrote the code below: for index, row in Person_df.iterrows(): for index1, row1 in Goals_df.iterrows(): If Person_df['country'] == Person_df['country'] : #I know this is incorrect data = [] #populate data[] with selected values for one person. #append data[] to Individual_df I need help on couple of points here: 1) How really I can perform the comparison here for country of each person. 2) Even if I know how to compare, the code I wrote is not at efficient as I am doing loads of unnecessary iterations here. Any pointers how can I improve this? Thanks!
type: Question

http://stackoverflow.com/a/71094782
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50701736
downvote count: 0
has body: The easy and right thing to do in 2022 is to use the cloud sql connector which will work with postgres, sqlserver, and mysql running on gcloud sql. https://cloud.google.com/sql/docs/mysql/connect-connectors#python_1 https://pypi.org/project/cloud-sql-python-connector/ No need to white list IPs, manually load certificates, or leave your database wide open. You use this format for the host: "project:region:instance" and connect as usual.
type: Answer

http://stackoverflow.com/q/50767146
has comment: http://stackoverflow.com/comment/88558943
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88543365
tagged with: python
has comment: http://stackoverflow.com/comment/88565440
has title: Sqlite Images into Keras training
has comment: http://stackoverflow.com/comment/88558912
answer count: 0
type: Question
has body: I have the data for my Keras model stored in a sqlite database. Using the sqlite3 python module I extract the image data into an array. Also in that database is my feature data. I have tried 100 different ways to extract the data and put it into a model that has my images as input and features as output. Is there a guide or something that isn't the wonderfully in depth keras documentation to do so?
has comment: http://stackoverflow.com/comment/88559156
score: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/88559098

http://stackoverflow.com/a/50822509
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50812512
has comment: http://stackoverflow.com/comment/88705872
answers question: http://stackoverflow.com/q/50812512
type: Answer
has body: NetCDF4 doesn't seem to have such a "pretty print" option, at best you can open a NetCDF file and simply print the object; that provides some info on the variables, dimensions, etc.: import netCDF4 as nc4 test = nc4.Dataset('rico.default.0000000.nc') print(test) As an alternative, xarray does have the option for "pretty printing" information about the variables, dimensions, attributes: import xarray as xr test = xr.open_dataset('rico.default.0000000.nc') print(test.info()) This returns pretty much the same output as ncdump -h, for example (small portion of the full output): xarray.Dataset { dimensions: t = 7 ; z = 100 ; zh = 101 ; variables: int32 iter(t) ; iter:units = - ; iter:long_name = Iteration number ; float64 t(t) ; t:units = s ; t:long_name = Time ; float32 z(z) ; z:units = m ; z:long_name = Full level height ; float32 zh(zh) ; zh:units = m ; zh:long_name = Half level height ; ............ At the end it also prints the global attributes (which this specific NetCDF file does not have).
score: 2
downvote count: 0

http://stackoverflow.com/comment/134574740
has text: In the grouped version of this (hue="species"), can I choose a different color for each regression line per group?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/65509804

http://stackoverflow.com/comment/88656253
comment on: http://stackoverflow.com/a/50825690
has text: @Barmar whoops, i misread the last part of the question
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50707658
tagged with: python
favorite count: 0
upvote count: 11
has answer: http://stackoverflow.com/a/50709069
tagged with: pip
has comment: http://stackoverflow.com/comment/88425652
score: 11
tagged with: tensorflow
has title: requirements.txt - How to mark alternative packages
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50709069
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/69028315
downvote count: 0
has body: I am writing a project that relies on tensorflow, but that can be provided by either of two pip packages: tensorflow or tensorflow-gpu. My project works fine with either, but I don't want people running it on a machine without gpu support to have to install the extra overhead, but I still want people running on machines with gpu support to be able to leverage that. Is there a way to mark in my requirements.txt file that I require either tensorflow or tensorflow-gpu but not both? EDIT: In this specific case I should note that from the programmer's point of view, both tensorflow and tensorflow-gpu are identical, as they both provide a module tensorflow which has the same functions/classes/methods etc., and only differ in that tensorflow-gpu benefits from GPU acceleration. The problem that I am having is that if I put tensorflow in requirements.txt then in order to run with GPU acceleration, users would have to do pip install -r requirements.txt &amp;&amp; pip uninstall tensorflow &amp;&amp; pip install tensorflow-gpu which is not ideal, and if I instead put tensorflow-gpu in requirements.txt, then it will require a bunch of unnecessary system libraries (CUDNN etc) and wont work out-of-the-box for non-gpu users. EDIT AGAIN As a work-around, I've decided to provide two different requirement files, requirements.txt and requirements-gpu.txt, both of which include a shared -r .requirements-core.txt and add their respective version of tensorflow. That way people who want GPU support can pip install -r requirements-gpu.txt but the standard pip install -r requirements.txt will still work out-of-the box for everyone.
possible better answer: http://stackoverflow.com/a/69028315

http://stackoverflow.com/comment/88598283
score: 0
type: AnswerComment
has text: The packet will exit the OUTPUT chain, enter the NFQUEUE then it will be re-injected after the OUTPUT chain, so no loop. Of course, any matching packet will be injected **once** in the nfqueue, you need to define in the code which packets need mangling and which packet doesn't.
type: Comment
comment on: http://stackoverflow.com/a/50766805

http://stackoverflow.com/a/50764166
has body: Disclaimer: the other answer is correct and you should use it. However, your actual problem stems from the fact that you are overriding r here: r = requests.get(url) x = r.json() During the next iteration r will still be that value and not the one you initialized it with in the first place. You could simply rename it to result to avoid that problem. Better let the requests library do the work though.
answers question: http://stackoverflow.com/q/50764002
score: 0
type: Answer

http://stackoverflow.com/a/50826081
answers question: http://stackoverflow.com/q/50825918
has comment: http://stackoverflow.com/comment/88659590
type: Answer
has comment: http://stackoverflow.com/comment/88658812
has body: This is a scoping issue. Your variable gameExit is only defined inside the functions that use it. The easiest way to fix this would be to declare it to False at the start of the program and put global gameExit at the top of all of your functions that set it, thus making sure they access the global version of it and don't just re-define it. For you're purposes, I'm sure this is fine, but you might want to check out the top answer on this question.
has comment: http://stackoverflow.com/comment/88658998
score: 0
has comment: http://stackoverflow.com/comment/88658446

http://stackoverflow.com/q/50800454
type: UnansweredQuestion
tagged with: pandas-datareader
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51554226
has answer: http://stackoverflow.com/a/57409624
type: Question
has title: How can I download stock price data with Python?
upvote count: 12
tagged with: stock
has answer: http://stackoverflow.com/a/60259398
score: 12
has answer: http://stackoverflow.com/a/56772026
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I have installed pandas-datareader but I'm wondering if there are alternatives. So far, I'm using this: import pandas_datareader.data as web start_date = '2018-01-01' end_date = '2018-06-08' panel_data = web.DataReader('SPY', 'yahoo', start_date, end_date)

http://stackoverflow.com/q/50782813
tagged with: tkinter
has title: How do i open a webcam frame in OpenCV and a tkinter window at the same time without using any threading in Python?
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: opencv
downvote count: 0
has comment: http://stackoverflow.com/comment/126747750
favorite count: 0
has body: Someone from here gave me this code that uses threading. This code works fine but what i want is to open the webcam frame and the tkinter at the same time without using threading. import cv2 import tkinter as tk import threading ui = Tk() ui.state('zoomed') def video_stream(): video = cv2.VideoCapture(0) while True: check, frame = video.read() cv2.imshow('Video', frame) key = cv2.waitKey(1) if key == 27: break video.release() cv2.destroyAllWindows th= threading.Thread(target=video_stream) #initialise the thread th.setDaemon(True) th.start() #start the thread ui.mainloop() #Run your UI
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88574111
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88574157
has comment: http://stackoverflow.com/comment/88574215

http://stackoverflow.com/comment/88557365
comment on: http://stackoverflow.com/q/50775125
score: 0
has text: and if you're using something like pycharm, add xlrd to your project/environment
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88687390
comment on: http://stackoverflow.com/a/50840266
type: Comment
has text: You'll want to copy and paste it from airflow's models.py taking the part you need to create a Fernet object
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88674641
comment on: http://stackoverflow.com/q/50835382
has text: dict[key] = item is the syntax you're looking for
type: QuestionComment
type: Comment
score: 4

http://stackoverflow.com/q/50837818
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50838045
has answer: http://stackoverflow.com/a/50838004
upvote count: 1
accepted answer: http://stackoverflow.com/a/50838004
downvote count: 1
has body: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ('headline',) I found this one-to-many relationship example in the Django docs. How would I go about doing another class called Magazine. In the class magazine, it would contain many articles written by many reporters. Would I still use a many-to-one relationship, or would I need a one-to-one relationship?
type: Question
has comment: http://stackoverflow.com/comment/88681170
tagged with: database
possible better answer: http://stackoverflow.com/a/50837892
score: 0
answer count: 3
tagged with: sqlite
has title: What type of database relationship should I use?
has comment: http://stackoverflow.com/comment/88679317
favorite count: 0
has answer: http://stackoverflow.com/a/50837892
tagged with: django

http://stackoverflow.com/q/50730049
type: Question
tagged with: sonarqube
has answer: http://stackoverflow.com/a/50745519
accepted answer: http://stackoverflow.com/a/50745519
tagged with: abstract-syntax-tree
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I am trying to add a new rule for my Python project, so according to this source (Adding Coding Rules using XPath), I was trying to run sslr-python-toolkit-1.9.1.2080.jar from command line to view AST of a given piece of code but it exited with the following error: Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.NoClassDefFoundError: org/sonar/sslr/toolkit/ConfigurationModel at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) at java.lang.Class.privateGetMethodRecursive(Class.java:3048) at java.lang.Class.getMethod0(Class.java:3018) at java.lang.Class.getMethod(Class.java:1784) at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526) Caused by: java.lang.ClassNotFoundException: org.sonar.sslr.toolkit.ConfigurationModel at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 7 more Am I missing something? How could I make it work? I'm quite new in SonarQube arena, so please excuse my naivety and help me to solve the issue. Thanks!
has title: Error running Sonar SSLR Toolkit

http://stackoverflow.com/comment/88520575
type: QuestionComment
score: 1
has text: Four digit pattern is `[0-9]{4}` (ERE and NFAs) or `[0-9]\{4\}` (BRE). I have no idea what you are going to use. Treat it as a hint.
comment on: http://stackoverflow.com/q/50756299
type: Comment

http://stackoverflow.com/comment/88567256
type: Comment
has text: @user2357112 , it won't be. Thank you. Made the correction.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50780161

http://stackoverflow.com/comment/88522909
score: 0
type: Comment
type: QuestionComment
has text: exel/word/pp use `~$` for a tempfile - the rest of the tempfiles name is based on it's original length, it might be somehting like `~$` plus either the full filename or `filename[1:]` or `filename[2:]` (shorter files are used completely, longers get reduced by 1st or 1st/2nd char. You need to find all`~$...` and discard all matching real filenames that possibly would create this tempfile.
comment on: http://stackoverflow.com/q/50757504

http://stackoverflow.com/a/50808844
has comment: http://stackoverflow.com/comment/88623470
has body: Here's a readable format of the code: rprod = {0: [2,1,1], 1: [3,1,2]} clst = {"comp": [8, 3, 5], "prod": [2, 2]} lst = [] for i, prod_demand in enumerate(clst["prod"]): sub_list = [] for j, comp_demand in enumerate(clst["comp"]): sub_list.append([1]*comp_demand+[rprod[i][j]*(-1)]) for k in range(prod_demand): lst.append(sub_list) But if you want to condense it, you can just write: rprod = {0: [2,1,1], 1: [3,1,2]} clst = {"comp": [8, 3, 5], "prod": [2, 2]} lst = [] for i, p in enumerate(clst["prod"]): lst += [[[1]*c+[rprod[i][j]*(-1)] for j, c in enumerate(clst["comp"])]]*p
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88623457
score: 1
has comment: http://stackoverflow.com/comment/88623573
has comment: http://stackoverflow.com/comment/88623441
answers question: http://stackoverflow.com/q/50808650
accepted answer of: http://stackoverflow.com/q/50808650
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88623547
has comment: http://stackoverflow.com/comment/88623565

http://stackoverflow.com/q/50849823
tagged with: tensorflow
score: 3
type: Question
has title: Cannot find libcublas.so.9.0 when running TensorBoard as sudo
downvote count: 0
favorite count: 0
tagged with: tensorboard
tagged with: python
has body: I can run TensorBoard as non-root user successfully. For some reason I have to use a port number with need root permission. So I need to run TensorBoard using sudo command. Then the error message comes out: cannot find libcublas.so.9.0. I am sure libcublas.so.9.0 is there under /usr/local/cuda/lib64. If I run sudo echo $LD_LIBRARY_PATH the first library path will just be /usr/local/cuda/lib64, so I do not know what to do. I am using CUDA 9.0, TensorFlow 1.7, Python 2.7 with Anaconda.
answer count: 0
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/50699111
upvote count: 2
answer count: 3
tagged with: loops
possible better answer: http://stackoverflow.com/a/50699313
has body: I am looking for a solution to order my loop selection. My problem is that when is select the rows, these aren't sorted. So I want to find the all matching lines and process them after that find the next matching lines based on the next key word. An other aspect I want firtly I want to find the all matching lines first and after that the all matching line based n the next key word. Finally I would like to note that I do not want to append the result in different variables because I have many key word. Here is a simple example of my problem: key_word=['one', 'two'] list=['one1', 'one2', 'two1', 'two2', 'two3', 'one3'] for i in list: for word in key_word: if (word in i): print (i) My output: one1 one2 two1 two2 two3 one3 My desired output: one1 one2 one3 two1 two2 two3
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50699215
downvote count: 0
has title: Select lines in order with Python
tagged with: sorting
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50699313
has answer: http://stackoverflow.com/a/50798859
accepted answer: http://stackoverflow.com/a/50699215

http://stackoverflow.com/q/50854803
score: 3
upvote count: 3
has body: In SymPy, what is the difference between eye(5) and Identity(5)? If I have a matrix X, I see that X + eye(5) and X + Identity(5) give different results (the latter is not a matrix).
tagged with: identity
type: Question
has title: Difference between eye and Identity in SymPy
answer count: 2
tagged with: sympy
accepted answer: http://stackoverflow.com/a/50873951
downvote count: 0
tagged with: matrix
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88724459
possible better answer: http://stackoverflow.com/a/50862749
has answer: http://stackoverflow.com/a/50873951
has answer: http://stackoverflow.com/a/50862749
type: AnsweredQuestion

http://stackoverflow.com/q/50744963
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88497996
downvote count: 3
accepted answer: http://stackoverflow.com/a/50745202
type: Question
answer count: 2
has title: plot more graphs from excel file and Pandas ( python)
upvote count: 0
has body: I have a .xlsx file structured as follows Now, I know how to manipulate the data in my table by pandas function. However, I am (unsuccessfully, I should say) looking for a way to plot in the same graph area the three curves labelled by the flags A, B, C in column 2 using col 3 as x-axis and col 9 as y-axis. I copy here the table in a "copy-&amp;-paste" suitable form Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 1 FlagA 5743 bla bla 0.02% 13-Apr-18 DS Y 17229 2 FlagA 654 bla bla -0.89% 13-Apr-18 DS Y 1962 3 FlagA 543 bla bla -0.74% 13-Apr-18 DS Y 1629 4 FlagA 321 bla bla -0.56% 13-Apr-18 DS Y 963 5 FlagA 8765 bla bla -0.37% 13-Apr-18 DS Y 26295 6 FlagA 98769 bla bla 3.75% 13-Apr-18 DS Y 296307 7 FlagA 943 bla bla 4.01% 13-Apr-18 DS Y 2829 8 FlagA 7986 bla bla 4.04% 13-Apr-18 DS Y 23958 9 FlagA 54343 bla bla 3.27% 13-Apr-18 DS Y 163029 10 FlagB 876856 bla bla 4.16% 13-Apr-18 DS Y 2630568 11 FlagB 36854 bla bla 3.36% 13-Apr-18 DS Y 110562 12 FlagB 3644 bla bla 4.21% 13-Apr-18 DS Y 10932 13 FlagC 68 bla bla 3.51% 13-Apr-18 DS Y 204 14 FlagC 354 bla bla 3.70% 13-Apr-18 DS Y 1062 15 FlagC 568748 bla bla 1.66% 13-Apr-18 DS Y 1706244 16 FlagC 64 bla bla 2.00% 13-Apr-18 DS Y 192
tagged with: pandas
linked to: http://stackoverflow.com/q/21654635
tagged with: python
has answer: http://stackoverflow.com/a/50745202
favorite count: 0
possible better answer: http://stackoverflow.com/a/50745228
has answer: http://stackoverflow.com/a/50745228
score: -3
tagged with: plot
tagged with: excel

http://stackoverflow.com/q/50739516
tagged with: amqp
score: 0
answer count: 1
tagged with: python
tagged with: kombu
has title: Is it possible to use kombu as client library for activeMQ?
type: UnansweredQuestion
has body: Trying to switch from rabbitMQ to activeMQ keeping kombu library but my script just hang on. Does kombu supports activeMQ?
has answer: http://stackoverflow.com/a/50742888
tagged with: activemq-classic
type: Question

http://stackoverflow.com/comment/111461394
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50737192
has text: From what I can see in official `tf` tutorials - they count *files* before creating a dataset, not number of elements in a dataset.
score: 0

text-analysis
tags question: http://stackoverflow.com/q/50775975
tags question: http://stackoverflow.com/q/50818999
tags question: http://stackoverflow.com/q/50801434
type: Tag
tag name: text-analysis
tags question: http://stackoverflow.com/q/50810846
tags question: http://stackoverflow.com/q/50720712

http://stackoverflow.com/comment/88688857
comment on: http://stackoverflow.com/q/50842628
type: QuestionComment
has text: That's basically an alternate way to write `./processInput.py -f "$FILE" | ./processInput.py -f - >"$FILE"`, which doesn't work for the same reasons (even if your program recognizes the conventional meaning of `-` referring to stdin/stdout as positionally appropriate).
score: 0
type: Comment

http://stackoverflow.com/comment/88654318
type: Comment
comment on: http://stackoverflow.com/a/50823590
has text: Sadly.. It won't work :( It always gives me an error message of please enter the right # in range.. I made sure I did casting of int(vlan_id)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88627509
has text: What's the logic behind your expected output? Also, please add your code that you've tried so far. SO is not a homework solving service. People here can help you when they know that you've already tried to solve your problem by yourself and for any reason you couldn't.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50811084

http://stackoverflow.com/a/50811892
has body: Not familiar with COCO but I see there's a annToMask function that should generate a binary mask for each annotation. So in untested pseudoish code, assuming non overlapping masks, you should have something like: annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) mask = np.zeros_like(img) for i, ann in enumerate(annIds): mask += coco.annToMask(ann) * i
answers question: http://stackoverflow.com/q/50805634
type: Answer
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/q/50821447
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88648624
score: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88648179
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88648748
upvote count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/88648985
has title: Set FPS in opencv 3.x
has comment: http://stackoverflow.com/comment/88648929
type: Question
has body: How can i set framerate to 60 fps in opencv3 When i start my program it has only 30fps (i get framerate from this function cv.get(cv2.CAP_PROP_FPS)) My code : cv = cv2.VideoCapture(0) While True: frame = cv.read #something here
has answer: http://stackoverflow.com/a/54444044

http://stackoverflow.com/comment/88508880
type: QuestionComment
comment on: http://stackoverflow.com/q/50750335
has text: Didn't even think about the migration files. This led to my fix, I just deleted the migration files concerned with that field - Django had two listed in the migrations folder that were throwing the error. Thank you!
score: 0
type: Comment

http://stackoverflow.com/q/50789829
score: 0
has body: From https://www.tutorialspoint.com/python/python_database_access.htm The Python standard for database interfaces is the Python DB-API. MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API. Is MySQLdb a module or an interface? What does "an interface implements a standard for interfaces" mean? I can understand that a module implements an interface. Thanks.
tagged with: mysql-python
tagged with: python
has comment: http://stackoverflow.com/comment/88585856
answer count: 0
type: UnansweredQuestion
has title: Is MySQLdb a module or an interface?
type: Question
tagged with: database
has comment: http://stackoverflow.com/comment/88585767

http://stackoverflow.com/comment/88427528
has text: @Ry- did'T look for the dupe, my bad.
comment on: http://stackoverflow.com/q/50708912
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88629559
type: Comment
comment on: http://stackoverflow.com/a/50811791
has text: It can capture a space at the end where it shouldn't.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50704445
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/88418459
tagged with: pandas
tagged with: python
has body: I'm trying to remove the commas from the numbers I extracted with the following code: with requests.Session() as s: url = 'https://www.zoopla.co.uk/for-sale/property/london/paddington/?q=Paddington%2C%20London&amp;results_sort=newest_listings&amp;search_source=home' r = s.get(url, headers=req_headers) soup = BeautifulSoup(r.content, 'lxml') prices = [] for price in soup.find_all('a', {"class":"listing-results-price text-price"}): prices.append(price.text) if price is None: print('none') df['price'] = prices df['price'] = df['price'].str.extract('(\d+([\d,]?\d)*(\.\d+)?)', expand=True) #remove extract numbers with commas df['price'] = df['price'].replace(',','', inplace = True) This returns a column in which all the values are None. Is there anyway to remove this NoneType error? Before I run the final line the dataframe is as follows: price 0 NaN 1 1,875,000 2 4,950,000 3 500,000 4 675,000 5 980,000 6 475,000 7 849,950 8 1,050,000 9 1,050,000 10 650,000 11 1,100,000 12 1,300,000 13 895,000 14 1,000,000 15 26,800,000 16 1,600,000 17 695,000 18 2,100,000 19 510,000 20 1,200,000 21 3,000,000 22 599,000 23 26,800,000 24 1,550,000 25 750,000 26 1,600,000 27 1,025,000
accepted answer: http://stackoverflow.com/a/50704678
has comment: http://stackoverflow.com/comment/88418529
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/50704719
tagged with: nonetype
has comment: http://stackoverflow.com/comment/88418286
has answer: http://stackoverflow.com/a/50704719
has comment: http://stackoverflow.com/comment/88418116
has comment: http://stackoverflow.com/comment/88418466
score: 0
has answer: http://stackoverflow.com/a/50704678
answer count: 2
has title: Remove NoneType from BeautifulSoup

http://stackoverflow.com/comment/88501742
comment on: http://stackoverflow.com/q/50747043
has text: First, if you want to get rid of just trailing whitespace, not both leading and trailing, use `rstrip`, not `strip`. Bur meanwhile, if you want us to debug your problem, you need to give us a [mcve] that demonstrates the problem and can be debugged. It's hard to believe that the whole `text = … [0]` returned a string full of non-whitespace characters but adding `.strip()` to the end emptied it out, but if that really _is_ happening, we definitely need to be able to repro it to find the bug.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/129329693
comment on: http://stackoverflow.com/a/53420574
score: 1
type: AnswerComment
has text: what is `start` supposed to be in the line: `print(f'Time: {time.time() - start:.2f}')`?
type: Comment

http://stackoverflow.com/q/50791248
type: Question
score: 4
tagged with: telegram-bot
upvote count: 4
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51111187
tagged with: python-3.x
tagged with: python-telegram-bot
tagged with: telegram
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51111187
has title: How can I make a unit test for python telegram bot?
has body: I'm currently using python-telegram-bot for create telegram bot. But every change I made, I have to do feature test by my hands. How can I create a unit test for a telegram bot using a tool such as pytest or unittest? Is there a way to generate the same traffic without telegram or control telegram in a terminal environment for test my telegram bot? Using python3, the latest version of python-telegram-bot

http://stackoverflow.com/q/50789659
type: Question
has answer: http://stackoverflow.com/a/50792385
downvote count: 0
answer count: 1
favorite count: 0
has title: Is Python DB-API 2.0 for relational database only?
upvote count: 2
type: UnansweredQuestion
has body: Is Python DB-API 2.0 for relational database only, or also for some nonrelational databases? https://wiki.python.org/moin/DatabaseInterfaces seems to imply no. https://wiki.python.org/moin/DatabaseProgramming seems to imply yes. Thanks.
tagged with: python
tagged with: python-db-api
score: 2
tagged with: database

http://stackoverflow.com/a/50774180
score: 0
has comment: http://stackoverflow.com/comment/88561369
type: Answer
answers question: http://stackoverflow.com/q/50772362
has body: For the vast majority of the scikit-image functions the internal representation is float. Especially, where some kind of smoothing/anti-alisaing/etc is required. Only this way we can guarantee that the output is as precise and informative as possible. To answer your questions: [Question]: is there a way to tweek transform.resize in order to stick to ints constraint the range of number after the , (say, 3 decimals) "negative" to both bullet points :). You should manually cast the output to whatever dtype you want by using, e.g., {resize_output}.astype(np.uint8, casting='unsafe') or numpy.around({resize_output}, decimals=3). I'm curious to know, however, the details of your benchmark. 23GB is a lot. If you could prepare a minimal example of your code that shows the high memory usage, please, post it on our GitHub bugtracker (https://github.com/scikit-image/scikit-image/issues).
has comment: http://stackoverflow.com/comment/88556800
has comment: http://stackoverflow.com/comment/88556835

http://stackoverflow.com/a/75302568
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50735075
has body: This is probably what you're looking for: https://cloud.google.com/bigquery/docs/reference/standard-sql/other-statements#export_data_statement The EXPORT DATA statement exports the results of a query to an external storage location. The storage location must be Cloud Storage.

scrapy
tags question: http://stackoverflow.com/q/50750332
tags question: http://stackoverflow.com/q/50775373
tags question: http://stackoverflow.com/q/50830491
tags question: http://stackoverflow.com/q/50826299
tags question: http://stackoverflow.com/q/50841317
tags question: http://stackoverflow.com/q/50761939
tags question: http://stackoverflow.com/q/50736550
tags question: http://stackoverflow.com/q/50734845
tags question: http://stackoverflow.com/q/50780420
tags question: http://stackoverflow.com/q/50845799
tags question: http://stackoverflow.com/q/50729897
tags question: http://stackoverflow.com/q/50845189
tags question: http://stackoverflow.com/q/50707253
tags question: http://stackoverflow.com/q/50765651
tags question: http://stackoverflow.com/q/50788131
tags question: http://stackoverflow.com/q/50779567
tags question: http://stackoverflow.com/q/50701035
tags question: http://stackoverflow.com/q/50821046
tags question: http://stackoverflow.com/q/50757380
tags question: http://stackoverflow.com/q/50714354
tags question: http://stackoverflow.com/q/50828125
tags question: http://stackoverflow.com/q/50736824
tags question: http://stackoverflow.com/q/50758256
tags question: http://stackoverflow.com/q/50812610
tags question: http://stackoverflow.com/q/50715822
tags question: http://stackoverflow.com/q/50712607
tags question: http://stackoverflow.com/q/50773194
tag name: scrapy
tags question: http://stackoverflow.com/q/50820912
tags question: http://stackoverflow.com/q/50770170
tags question: http://stackoverflow.com/q/50797349
tags question: http://stackoverflow.com/q/50789473
tags question: http://stackoverflow.com/q/50761567
tags question: http://stackoverflow.com/q/50699601
tags question: http://stackoverflow.com/q/50791031
tags question: http://stackoverflow.com/q/50773587
tags question: http://stackoverflow.com/q/50700540
tags question: http://stackoverflow.com/q/50711963
type: Tag
tags question: http://stackoverflow.com/q/50775354
tags question: http://stackoverflow.com/q/50772794
tags question: http://stackoverflow.com/q/50777226
tags question: http://stackoverflow.com/q/50763286
tags question: http://stackoverflow.com/q/50751281
tags question: http://stackoverflow.com/q/50815686
tags question: http://stackoverflow.com/q/50805355

ibm-cloud-functions
tag name: ibm-cloud-functions
type: Tag
tags question: http://stackoverflow.com/q/50843136

http://stackoverflow.com/q/50811101
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88627909
has title: convert list of class objects into json in python or django
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50811405
type: Question
has comment: http://stackoverflow.com/comment/88627580
answer count: 2
has answer: http://stackoverflow.com/a/50811405
possible better answer: http://stackoverflow.com/a/50811564
downvote count: 0
has answer: http://stackoverflow.com/a/50811564
has comment: http://stackoverflow.com/comment/88627768
has body: my_objects = [] my_objects.append(Needed("bye",9)) my_objects.append(Needed("tata",8)) my_objects.append(Needed("hi",10)) i have list of object(example 5 objects in list) like this class Needed: def __init__(self, name, number): self.name = name self.number = number and i need to convert this into json order by count like below { "results":[ { "name":"hi", "number":"10" }, { "name":"bye", "number":"9" }, { "name":"tata", "number":"8" }, ........... ........... ] } so how to achieve this in django

http://stackoverflow.com/comment/88652089
comment on: http://stackoverflow.com/q/50823134
type: QuestionComment
score: 1
has text: When you get f from allFiles, it includes the path, you should use `path, filename = os.path.split(path/to/file/foobar.txt)` to just get the filename without the path
type: Comment

http://stackoverflow.com/comment/88567568
type: QuestionComment
has text: def matVec(matrix,vector): for i in range(len(matrix)): result = [] total = 0 for j in range(len(vector)): total += matrix[i][j] * vector[j] result.append(total) return result matrix_0 = [[1, 2, 3],[2, 3, 4]] vector_0 = [2, 2] print(matVec(matrix_0,vector_0))
comment on: http://stackoverflow.com/q/50780402
score: 0
type: Comment

http://stackoverflow.com/a/50751926
type: AcceptedAnswer
has body: The problem It's almost surely related to a version incompatibility between Eve and Eve-SQLAlchemy. Eve-SQLAlchemy 0.5 only supports Eve 0.6 and there is currently no version available supporting newer Eve versions. This also matches the TypeError you see: find_one() is a method in the data layer, which Eve-SQLAlchemy provides. Probably the interface changed in Eve 0.7 or 0.8. Where to go from here If you're using pip then pip check should report an error with your installation, as Eve-SQLAlchemy declares it depends on Eve&gt;=0.6,&lt;0.7 (see https://github.com/pyeve/eve-sqlalchemy/blob/586cec403daabaeab8f7cbe133275d5fcc4e4bf3/setup.py#L35). To fix this, either remove any pinning of Eve to an incompatible version in your setup.py and/or requirements.txt, or if that does not change anything add Eve&lt;0.7. Unfortunately pip is not always able to determine a set of non-contradicting versions for all your dependencies itself, so it sometimes needs guidance to do so.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50722792
answers question: http://stackoverflow.com/q/50722792
has comment: http://stackoverflow.com/comment/88525405

http://stackoverflow.com/q/50726510
favorite count: 0
has comment: http://stackoverflow.com/comment/88470195
has answer: http://stackoverflow.com/a/77041328
tagged with: python
has answer: http://stackoverflow.com/a/50731575
possible better answer: http://stackoverflow.com/a/77041328
has comment: http://stackoverflow.com/comment/104821048
tagged with: pyqt5
has body: When you use Qt_Designer or Qt_Creator to design a form, objectName for any given widget is always set to something. But if you create a widget in code AND you need the objectName later, you have to assign it explicitly. So then the widget assignment takes at least two lines of code. This seems very inelegant. Example: button1 = QPushButton('button caption') # at this point objectName is some kind of empty string button1.setObjectName('button1') If you need to find the widget later (i.e. with findChild), you must have objectName set, otherwise you're out of luck. Is there some way to automatically set objectName without extra lines of code? I looked at the PyQt5 Reference Guide and could not find such a feature. A similar question was asked on Code Review, but got no answers. Two lines of code isn't the end of the world, but it seems redundant. Somehow I'm required to assign this name twice once for Python (first line) and again for Qt.
has title: PyQt: is there an better way to set objectName in code?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/104820757
has comment: http://stackoverflow.com/comment/88470257
score: 7
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/88462650
answer count: 2
has comment: http://stackoverflow.com/comment/88464231
tagged with: pyqt
downvote count: 1
accepted answer: http://stackoverflow.com/a/50731575

http://stackoverflow.com/comment/88687362
has text: I've extended the answer, maybe now its not only *working*, but is also clear what is going on!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50840972

http://stackoverflow.com/q/50728718
tagged with: global-variables
tagged with: multiprocessing
type: Question
answer count: 1
tagged with: keras
has title: Trouble mutliprocessing when the function has global state in imported libraries
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50729403
has body: This is being done on a machine learning example but I don't believe the problem or solution is specifically related to it using keras/tensorflow. __init__.py file with some gobal state I can't get around... ## Silly module with some odd state variables global __STATE __STATE = 3 def add(x): if __STATE == 3: return x + __STATE else: return 0 def finish(): global __STATE __STATE = None del __STATE return Multiprocessing code I want to get working def doSomethingComplicated(x): # x = x + y # import some libraries import stateFullStuff # create some of its own processes and run them x = stateFullStuff.add(x) print (x) stateFullStuff.finish() # print ("finished") return x from multiprocessing import Pool if __name__ == '__main__': x_ = range(100) pool = Pool(3) results = pool.map(doSomethingComplicated,x_) print ("results: ", results) Now this works okay if the number of workers for the pool is equal to or greatert than len(x_) but that is unmaintainable. For anyone's interest, the global state that is causing problems in my real code is the loaded tensorflow backend in Keras. I believe the session is closed when the task is done but the next task for some worker still sees the old session...
score: 0

http://stackoverflow.com/comment/88578635
comment on: http://stackoverflow.com/q/50785955
score: 0
type: Comment
type: QuestionComment
has text: @Lemayzeur If printed 'Called post_delete' when call HogeFileModel.objects.get(pk=~~).delete()

http://stackoverflow.com/a/50742638
type: Answer
answers question: http://stackoverflow.com/q/50742036
score: 2
upvote count: 2
has body: You need to upgrade your matplotlib to version 2.2.0 or higher. (Current version is 2.2.2) This will solve your problem automatically because it respects the order of the input.
accepted answer of: http://stackoverflow.com/q/50742036
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88601580
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50786590
has text: I just want to say, once a word was recognised as a token, this word is highlighted in a different word. For example if program can recognise `"a"` as Token.Literal.String.Double so this chars are highlighted. But not only this string literal but also all a's in the Text widget. Here you can see on the screenshots. https://forum.yazbel.com/uploads/default/original/1X/09f8af59804472fe8f6bd891d0c6aefc4e58af73.png https://forum.yazbel.com/uploads/default/original/1X/ae2374523e84f5c80e6ba6c3784cf8534a94efa5.png
score: 0

http://stackoverflow.com/comment/88439085
score: 0
has text: Add `print(message)` inside your loop and you would then see which items are available.
type: QuestionComment
comment on: http://stackoverflow.com/q/50709874
type: Comment

http://stackoverflow.com/comment/88459969
score: 0
comment on: http://stackoverflow.com/q/50723906
has text: Do you have `tk.Tk()` in more than one place in your code? Please show us a [mcve]. the code you posted isn't complete.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88608065
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50801041
has text: 3.6, just as I mentioned in my question.
type: QuestionComment

http://stackoverflow.com/a/50773521
answers question: http://stackoverflow.com/q/50773410
has body: This kind of operation (splitting into groups) is handled by the .groupby method in pandas. If we take care to set the index to time, it also handles giving us the right output with a time index back. Here's an example which does basically the same as your code: df = pandas.DataFrame( [[1, 'A', 1], [2, 'A', 2], [3, 'A', 3], [1, 'B', 4], [2, 'B', 5], [3, 'B', 6], [1, 'C', 7], [2, 'C', 8], [3, 'C', 9]], columns=['t', 'group', 'val']) df = df.set_index('t') moving_avg = df.groupby('group').rolling(2).mean() moving_avg is now a new dataframe. Note that because I set the index to be t in the first part, it's handled correctly in the grouping and rolling averages: val group t A 1 NaN 2 1.5 3 2.5 B 1 NaN 2 4.5 3 5.5 C 1 NaN 2 7.5 3 8.5
score: 5
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/88557530
accepted answer of: http://stackoverflow.com/q/50773410
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88556415
has comment: http://stackoverflow.com/comment/88554807
type: Answer
has comment: http://stackoverflow.com/comment/88556754

http://stackoverflow.com/a/50756387
score: 1
has comment: http://stackoverflow.com/comment/88625316
has body: You can filter your data in a very easy and convenient way via pandas. I do not have access to your online data storage, so I made some sample data on my own, if that's ok... import pandas as pd x = np.linspace(0,25000,1000) y = np.sin(np.linspace(0,25*np.pi,1000))*(1.2+np.cos(np.arange(-200,800)/45/4/2))+np.random.random(1000) df = pd.DataFrame({'y': y}, index=x) plt.plot(df) plt.plot(df, label='raw data') plt.plot(df.rolling(10, Center=True).mean(), label='filtered by rolling mean size 10') plt.legend()
has comment: http://stackoverflow.com/comment/88591190
has comment: http://stackoverflow.com/comment/88625365
has comment: http://stackoverflow.com/comment/88590929
upvote count: 1
answers question: http://stackoverflow.com/q/50750146
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89090276
type: QuestionComment
comment on: http://stackoverflow.com/q/50826232
has text: This has been rectified: See: https://github.com/HIPS/autograd/issues/407
score: 0
type: Comment

http://stackoverflow.com/comment/88691412
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50843495
type: Comment
has text: Agreed - and for the correct order one could use the key `sorted(spool_list, key=lambda x: 10**2*ord(x[0]) + int(x[1:]))`

http://stackoverflow.com/comment/120163946
type: AnswerComment
has text: Avoid posting answers like these or else add a meaningful description as to why your answer is more relevant and useful to the question.
type: Comment
comment on: http://stackoverflow.com/a/67981887
score: 0

http://stackoverflow.com/q/50801259
type: UnansweredQuestion
tagged with: python
has body: I tried running the following program: for i in range(5): print(i, end=' ') However, it waits for me to write some string in the next line and gives the output like: 0 1 2 3 4 'Hi' where 'Hi' is what I input. I'm using the latest version 3.6.5 and can't seem to understand the reason behind this error. Can anyone help?
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50801291
score: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: The end=' ' option in print function in python
linked to: http://stackoverflow.com/q/2456148

http://stackoverflow.com/q/50729672
has comment: http://stackoverflow.com/comment/88467219
has title: Python replace apostrophes in dictionary
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/88467322
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88469051
linked to: http://stackoverflow.com/q/10472907
has answer: http://stackoverflow.com/a/50747256
has comment: http://stackoverflow.com/comment/88467594
type: UnansweredQuestion
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/88494715
linked to: http://stackoverflow.com/q/18283725
tagged with: replace
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88467577
has comment: http://stackoverflow.com/comment/88467156
has body: I have a dictionary that has apostrophes for the value and key in every entry. For instance one entry would look like this: {'lat': '38.683959', 'lon': '-90.265198', 'accuracy': '3'} I need to get rid of these apostrophes so I can write them into SQL. The single quotes cause an error when I try to write them. What is the best way to get rid of all of the apostrophes? Thanks for your help!
favorite count: 0

http://stackoverflow.com/a/50730875
answers question: http://stackoverflow.com/q/50711159
has body: (Spyder maintainer here) The problem is that kernel restarts are asynchronous calls, i.e. they are executed in an external process and there's no way to tell from code when that call finished and when a new kernel is available. That's because code is run in the kernel that's going to be killed. So, as far as I can tell, it's not possible to do what you want (but I'm no expert in the Jupyter architecture).
type: Answer
score: 0

http://stackoverflow.com/q/50745439
type: Question
has body: i want to pass a dictionary object as parameter to a function. i read some post, the people recommend to use **kwargs as parameter, but when i use this keyword, it make a new dictionary instead of passing my dictionary to the function. can you help me with a solution to pass my entire dictionary object as variable. this is a sample code that i tried to use it my_dic={test:list1[], train:list2[]} def prt(**kwargs): for txt in kwargs[test]: print(txt) prt(my_dic) thank you
accepted answer: http://stackoverflow.com/a/50745543
has answer: http://stackoverflow.com/a/50745766
downvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/89906544
possible better answer: http://stackoverflow.com/a/50745830
favorite count: 0
has answer: http://stackoverflow.com/a/50745830
has comment: http://stackoverflow.com/comment/88499022
score: -3
has title: how to pass a dictionary object as parameter for a function in python
has comment: http://stackoverflow.com/comment/88498604
tagged with: python
tagged with: dictionary
tagged with: parameters
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88498608
has answer: http://stackoverflow.com/a/50745543
upvote count: 1

http://stackoverflow.com/comment/88550813
type: AnswerComment
comment on: http://stackoverflow.com/a/50771646
has text: Thank you for your kindness..!! But I still have small problems that it printed on the page '1101 나연(student name)--<bound method Student.atclub of <Student: 1101 (student name)>>', Not a name of club..
type: Comment
score: 0

http://stackoverflow.com/comment/88618425
has text: Can you explain why I would do this one more time? Sorry I am still confused. Where does the second matrix come from? Is this a problem in the functional computation of the Jacobian or the actual function itself? if it is the function, that specific code for the function worked for other iterative methods, so what is different now?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50806050
score: 0

http://stackoverflow.com/q/50727556
has title: How to give methods package-private visibility in Ruby or Python
favorite count: 0
tagged with: ruby
has comment: http://stackoverflow.com/comment/88463385
has body: Java has a visibility named package-private, which means that something can only be accessed inside the package it is defined in, and not outside. I'm wondering if there is any way to add this feature to Ruby (with modules) or Python. Here is an example of what I'm looking for: module Foo class FooClass def print_message_package # Some line to test that the last caller is in module Foo puts 'Hello' end def print_message_public print_message_package end end end test = Foo::FooClass.new # I would like that following line raises an error, because it is not called inside module Foo test.print_message_package # This line should not raise an error: test.print_message_public
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88475152
linked to: http://stackoverflow.com/q/10535319
tagged with: python
has answer: http://stackoverflow.com/a/50744284
has comment: http://stackoverflow.com/comment/88466444
has comment: http://stackoverflow.com/comment/88466201
upvote count: 1
has comment: http://stackoverflow.com/comment/88464613
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88463527
has comment: http://stackoverflow.com/comment/88471484
has comment: http://stackoverflow.com/comment/88463510
score: 0
has comment: http://stackoverflow.com/comment/88463481
tagged with: visibility
answer count: 1

http://stackoverflow.com/q/50794064
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50797895
answer count: 3
tagged with: python
has body: I have a generic shell script used in all of the modules. All of the modules install a common pip called common. The script is something like this common utils scripts build generic_build.sh I've saw there is a way to install python script by adding to setup.py using the scripts or the console_scripts arguments. but sh files seems to be ignored. meaning they don't end up in the installed package. Any ideas?
has title: How to package a shell script in a pip package
has comment: http://stackoverflow.com/comment/88600038
has comment: http://stackoverflow.com/comment/88597767
type: UnansweredQuestion
upvote count: 21
tagged with: pip
score: 21
type: Question
has answer: http://stackoverflow.com/a/78722092
has answer: http://stackoverflow.com/a/50794413

http://stackoverflow.com/comment/88693709
score: 0
type: AnswerComment
has text: You're not copying the object here. Check out the edit above. Hope that helps!
type: Comment
comment on: http://stackoverflow.com/a/50845055

http://stackoverflow.com/a/50769778
has body: Forget about your two functions, since they're both correct, and look at your top-level code: import random as rand def ... def ... print(cards_dealt(5, 3, deck)) Where does deck come from? Nowhere. Hence the exception. It's pretty obvious where you intended it to come from—you have a create function that ends with a return deck. You just aren't calling it anywhere. So you want: import random as rand def ... def ... deck = create() print(cards_dealt(5, 3, deck)) … or, if you want to make it clearer that the global variable is unrelated to the two locals: import random as rand def ... def ... mydeck = create() print(cards_dealt(5, 3, mydeck)) … or, if you want to make things more concise: import random as rand def ... def ... print(cards_dealt(5, 3, create())) Beyond this problem, cards_dealt doesn't have a return, so it just returns None. When your function is complete, there might be something worth printing out, but for now, while you're debugging what you have so far, it's not very useful. Meanwhile, if you want to print the shuffled deck, which could be useful, you'd do something like this: import random as rand def ... def ... mydeck = create() cards_dealt(5, 3, mydeck) print(mydeck) When you later finish the function so it returns, say, a tuple of 3 lists of 5 cards, you'll probably want to store those return values for later as well as printing them, so it might go something like this: import random as rand def ... def ... mydeck = create() hands = cards_dealt(5, 3, mydeck) for hand in hands: print(hand)
has comment: http://stackoverflow.com/comment/88547031
has comment: http://stackoverflow.com/comment/88546999
answers question: http://stackoverflow.com/q/50769728
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88547226
has comment: http://stackoverflow.com/comment/88547108

shell
tags question: http://stackoverflow.com/q/50708912
tags question: http://stackoverflow.com/q/50779165
tags question: http://stackoverflow.com/q/50756299
tag name: shell
tags question: http://stackoverflow.com/q/50793587
tags question: http://stackoverflow.com/q/50722088
tags question: http://stackoverflow.com/q/50829364
tags question: http://stackoverflow.com/q/50759877
tags question: http://stackoverflow.com/q/50777423
tags question: http://stackoverflow.com/q/50723662
tags question: http://stackoverflow.com/q/50774143
tags question: http://stackoverflow.com/q/50745369
tags question: http://stackoverflow.com/q/50749840
tags question: http://stackoverflow.com/q/50801671
type: Tag
tags question: http://stackoverflow.com/q/50701563
tags question: http://stackoverflow.com/q/50762627
tags question: http://stackoverflow.com/q/50747849
tags question: http://stackoverflow.com/q/50829798
tags question: http://stackoverflow.com/q/50841425

http://stackoverflow.com/q/50817926
has title: python - numpy - many matrices multiplying many vectors
score: 0
has comment: http://stackoverflow.com/comment/88641018
downvote count: 1
has comment: http://stackoverflow.com/comment/88648175
possible better answer: http://stackoverflow.com/a/50818738
tagged with: matrix-multiplication
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50818738
accepted answer: http://stackoverflow.com/a/50818447
answer count: 2
has comment: http://stackoverflow.com/comment/88646702
favorite count: 0
has body: I have a set of many matrices each corresponding to a vector. I want to multiply each matrix by its vector smartly. I know I can putt all the matrices in a big block diagonal form, and multiply it by a big combined vector. I want to know if there is a way to use numpy.dot to multiply all of them in an efficient way. I have tried to use numpy.stack and the numpy.dot, but I can't get only the wanted vectors. To be more specific. My matrices look like: R_stack = np.stack((R, R2, R3)) which is array([[[-0.60653066, 1.64872127], [ 0.60653066, -1.64872127]], [[-0.36787944, 2.71828183], [ 0.36787944, -2.71828183]], [[-0.22313016, 4.48168907], [ 0.22313016, -4.48168907]]]) and my vectors look like: p_stack = np.stack((p0, p0_2, p0_3)) which is array([[[0.73105858], [0.26894142]], [[0.88079708], [0.11920292]], [[0.95257413], [0.04742587]]]) I want to multiply the following: R*p0, R2*p0_2, R3*p0_3. When I do the dot : np.dot(R_stack, p_stack)[:,:,:,0] I get array([[[ 0. , -0.33769804, -0.49957337], [ 0. , 0.33769804, 0.49957337]], [[ 0.46211716, 0. , -0.22151555], [-0.46211716, 0. , 0.22151555]], [[ 1.04219061, 0.33769804, 0. ], [-1.04219061, -0.33769804, 0. ]]]) The 3 vectors I'm interested in are the 3 [0,0] vectors on the diagonal. How can I get them?
has comment: http://stackoverflow.com/comment/88641169
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50818447
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88641023

http://stackoverflow.com/comment/88578999
type: QuestionComment
has text: After working with Atom for about an hour, playing with F5 and Script, I quit and closed Atom still unsure why F5 didn't always work. I was doing something else which required me to open a terminal window. When I did this, the window went crazy opening tabs and plot windows all related to my Atom testing. There must have been 50 or more tabs and plots. I closed them all down and reopened Terminal to ensure I got them all. After doing that I reopened Atom and F5 and F6 worked fine. So try opening a terminal window to be sure you don't have a similar problem.
score: 0
comment on: http://stackoverflow.com/q/50699962
type: Comment

http://stackoverflow.com/q/50754517
tagged with: pyspark
type: UnansweredQuestion
has body: I am running a huge text file using PyCharm and PySpark. This is what I am trying to do: spark_home = os.environ.get('SPARK_HOME', None) os.environ["SPARK_HOME"] = "C:\spark-2.3.0-bin-hadoop2.7" import pyspark from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession conf = SparkConf() sc = SparkContext(conf=conf) spark = SparkSession.builder.config(conf=conf).getOrCreate() import pandas as pd ip = spark.read.format("csv").option("inferSchema","true").option("header","true").load(r"some other file.csv") kw = pd.read_csv(r"some file.csv",encoding='ISO-8859-1',index_col=False,error_bad_lines=False) for i in range(len(kw)): rx = '(?i)'+kw.Keywords[i] ip = ip.where(~ip['Content'].rlike(rx)) op = ip.toPandas() op.to_csv(r'something.csv',encoding='utf-8') However, PyCharm is throwing me this error: To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). 2018-06-08 11:31:52 WARN Utils:66 - Truncated the string representation of a plan since it was too large. This behavior can be adjusted by setting 'spark.debug.maxToStringFields' in SparkEnv.conf. Traceback (most recent call last): File "C:/Users/mainak.paul/PycharmProjects/Concept_Building_SIP/ThemeSparkUncoveredGames.py", line 17, in &lt;module&gt; op = ip.toPandas() File "C:\Python27\lib\site-packages\pyspark\sql\dataframe.py", line 1966, in toPandas pdf = pd.DataFrame.from_records(self.collect(), columns=self.columns) File "C:\Python27\lib\site-packages\pyspark\sql\dataframe.py", line 466, in collect port = self._jdf.collectToPython() File "C:\Python27\lib\site-packages\py4j\java_gateway.py", line 1160, in __call__ answer, self.gateway_client, self.target_id, self.name) File "C:\Python27\lib\site-packages\pyspark\sql\utils.py", line 63, in deco return f(*a, **kw) File "C:\Python27\lib\site-packages\py4j\protocol.py", line 320, in get_return_value format(target_id, ".", name), value) py4j.protocol.Py4JJavaError: An error occurred while calling o30.collectToPyth…
tagged with: python-2.7
tagged with: apache-spark
downvote count: 0
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/50794028
favorite count: 0
type: Question
tagged with: python
upvote count: 1
has title: DF.topandas() - Failed to locate the winutils binary in the hadoop binary path
tagged with: apache-spark-sql

http://stackoverflow.com/comment/88477230
type: Comment
has text: What type is kp1 ? Check if it is an array. If not convert it to one
score: 0
comment on: http://stackoverflow.com/q/50733604
type: QuestionComment

http://stackoverflow.com/comment/94673286
score: 0
has text: That code that his shown in the screen shot doesn't look obfuscated, but then it is also nowhere complete, nor is the bytecode shown around the offset that is reported to be where the problem is. However to have this considered for fixing in uncompyle6 you'll have to read the instructions on how to report a bug and follow them.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50795021

http://stackoverflow.com/q/50846621
tagged with: matplotlib
has title: How to adjust branch lengths of dendrogram in matplotlib (like in astrodendro)? [Python]
tagged with: hierarchical-clustering
score: 20
tagged with: dendrogram
answer count: 1
has body: Here is my resulting plot below but I would like it to look like the truncated dendrograms in astrodendro such as this: There is also a really cool looking dendrogram from this paper that I would like to recreate in matplotlib. Below is the code for generating an iris data set with noise variables and plotting the dendrogram in matplotlib. Does anyone know how to either: (1) truncate the branches like in the example figures; and/or (2) to use astrodendro with a custom linkage matrix and labels? import pandas as pd import numpy as np from sklearn.datasets import load_iris import astrodendro from scipy.cluster.hierarchy import dendrogram, linkage from scipy.spatial import distance def iris_data(noise=None, palette="hls", desat=1): # Iris dataset X = pd.DataFrame(load_iris().data, index = [*map(lambda x:f"iris_{x}", range(150))], columns = [*map(lambda x: x.split(" (cm)")[0].replace(" ","_"), load_iris().feature_names)]) y = pd.Series(load_iris().target, index = X.index, name = "Species") c = map_colors(y, mode=1, palette=palette, desat=desat)#y.map(lambda x:{0:"red",1:"green",2:"blue"}[x]) if noise is not None: X_noise = pd.DataFrame( np.random.RandomState(0).normal(size=(X.shape[0], noise)), index=X_iris.index, columns=[*map(lambda x:f"noise_{x}", range(noise))] ) X = pd.concat([X, X_noise], axis=1) return (X, y, c) def dism2linkage(DF_dism, method="ward"): """ Input: A (m x m) dissimalrity Pandas DataFrame object where the diagonal is 0 Output: Hierarchical clustering encoded as a linkage matrix Further reading: http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.hierarchy.linkage.html https://pypi.python.org/pypi/fastcluster """ #Linkage Matrix Ar_dist = distance.squareform(DF_dism.as_matrix()) return linkage(Ar_dist,method=method) # Get data X_iris_with_noise, y_iris, c_iris = iris_data(50) # Get distance matrix df_dism = 1- X_iris_with_noise.corr().abs() # Get linkage matrix Z = dism2linkage(df_dism) #Create dendrogram with plt.style.context(…
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88907659
has answer: http://stackoverflow.com/a/52435026
upvote count: 20
has comment: http://stackoverflow.com/comment/88907699
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88949643
tagged with: plot
type: Question

http://stackoverflow.com/a/50843371
has comment: http://stackoverflow.com/comment/88726116
downvote count: 0
has comment: http://stackoverflow.com/comment/88699124
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50838525
upvote count: 1
has comment: http://stackoverflow.com/comment/88703934
has comment: http://stackoverflow.com/comment/88703618
has body: Edited: Federico Bertola is correct on the solution and the temporary table that is written to by BigQuery see this link. I did not get an error with my sample code querying from a public table last time, but I can reproduce the error today, so it is possible this symptom can appear intermittent. I can confirm the error is resolved with Federico’s suggestion. You can get the “super(QueryJob, self).result(timeout=timeout)” error when the query string lacks quotes around the parameters in the query. It seems you have made a similar mistake with the parameter format_strings in your query. You can fix this problem by ensuring there is quotes escaped around the parameter: (" + myparam + ") , should be written as (\"" + myparam + "\") You should examine your query string where you use parameters, and start with a simpler query such as select productId, eventType, count(*) as count from `xyz:xyz.abc` , and grow your query as you go. For the record, here is what worked for me: from google.cloud import bigquery client = bigquery.Client() job_config = bigquery.QueryJobConfig() def get_data_from_bq(myparam): query = "SELECT word, SUM(word_count) as count FROM `publicdata.samples.shakespeare` WHERE word IN (\""+myparam+"\") GROUP BY word;" query_job = client.query(query, job_config=job_config) return query_job.result() mypar = "raisin" x = 1 while (x&lt;9): iterator = get_data_from_bq(mypar) print "==%d iteration==" % x x += 1

http://stackoverflow.com/comment/88686453
score: 0
has text: @AzatIbrakov Ill have a look at it later, thanks for the response!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50782326

http://stackoverflow.com/comment/88722040
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50850489
has text: Regarding your *"The link for the javascript library I provided produces the following hash for the text 'MyPassword'" : 5e618e009fe35ea092150ad1f2c24e3181b4cf6693dc7bbd9a09ea9c8144720d* I don't know how you used your library, but the correct SHA256 hash of MyPassword string is the same as you showed for Python, you can check on this site : https://passwordsgenerator.net/sha256-hash-generator/ . You are missing an [mcve] so we can reproduce the discrepancy and help you.

http://stackoverflow.com/q/50737066
type: Question
has answer: http://stackoverflow.com/a/50737120
tagged with: python
score: -1
upvote count: 2
downvote count: 3
has body: I am coding a database and while doing so I got stuck into an infinite loop. #!/bin/usr/python3 import os, sys import math try: project_file = open('work_good.txt', 'w+') text = project_file.read() except FileNotFoundError as error: text = ('File not found') print (text) project_file.close() with open('work_good.txt', 'r') as f: my_names = [] my_names = f.readlines() def Zone(): #Introduction to the database print ('WELCOME TO THE DATABASE', file=project_file) print (23*'=', file=project_file) def Username(): #Ask for users username usr_name = input ('What do you want your current username to be?: ').strip().capitalize() print ('Your username is: {}'.format(usr_name), file=project_file) return usr_name def Change_Username(): #Information for the user to change their username change_usr = input ('Would you like to change your username? (y/n): ').strip().lower() if change_usr == 'y': status = input ('Enter your new username: ').strip() print ('Username is changing...', file=project_file) print ('Your new username is: {}'.format(status), file=project_file) elif change_usr == 'n': pass else: print ('No such command was given!', file=project_file) def Password(): set_password = input ('What will be your password?: ').strip() password = ('Your password is: {}'.format(set_password)) print (password, file=project_file) def Password_Change(): change_password = input('Do you want to change your password? (y/n): ').strip().lower() if change_password == 'y': password1 = input ('What will your new passsword be: ') password2 = ('Your new password is: {}'.format(password1)) print (password2, file=project_file) elif change_password == 'n': print ('Your password remains the same'.upper(), file=project_file) else: print ('No such command has been given!', file=project_file) Zone() counter = 0 while counter &lt;= 3: usr_name = [] usr_name = Username() my_names.append(usr_name) print (usr_name, file=project_file) Change_Username() Password() Password_Change() I think at the final line …
answer count: 1
has title: I'm stuck in an infinite loop
tagged with: database
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88481594
has comment: http://stackoverflow.com/comment/88481598
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50773119
tagged with: macos
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: agent
type: Question
has body: Problem is when i try to open app converted from my Python script into Mac app with pyinstaller, it closes in a second. I'm using pyinstaller with flags -w -F like this sudo pyinstaller client.py -w -F so I've got 2 files in a dist folder client which is exec file. And client.app so when i try to run exec file - everything is ok, but when I clicked client.app I've seen icon in dock for a second and then it disappeared. But if I go into client.app/Contents/MacOS/ and run client it runs ok again. I thought problem could be in Info.plist file but i'm not shure <?xml version="1.0" encoding="UTF-8"?> CFBundleDisplayName client CFBundleName client CFBundleIdentifier client CFBundleExecutable MacOS/client CFBundleIconFile icon-windowed.icns CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType APPL CFBundleShortVersionString 0.0.0 LSBackgroundOnly 0 client - is console program. So how can i fix the problem with client.app?
upvote count: 1
downvote count: 0
favorite count: 0
has title: app closes after pyinstaller Mac Os
tagged with: pyinstaller

http://stackoverflow.com/q/50785510
upvote count: 4
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50805186
favorite count: 0
linked to: http://stackoverflow.com/q/7591656
tagged with: python
type: AnsweredQuestion
tagged with: libreoffice-calc
has body: I am writing custom functions in LibreOffice Calc. Such functions must be called in Calc as if they were native functions, e.g. as EDATE(), DAYS() etc. Upto now what I am doing for each custom function is: Define a Python function Define a StarBasic function which invokes its Python correspondant Call StarBasic function from Calc. It works, but it is quite impractical to write each function in two languages. My question is: is it possible to write such kind of functions directly in Python ? Do you have any reference to share ?
tagged with: custom-function
type: Question
has answer: http://stackoverflow.com/a/50805186
has title: Define a LibreOffice Calc custom function in Python
score: 4

http://stackoverflow.com/q/50718634
has title: Can't recognize dtype int as int in computation
favorite count: 0
has comment: http://stackoverflow.com/comment/88447059
type: Question
tagged with: pandas
has body: I have two columns (serverTs, FTs) in DataFrame which are timestamps in the format of Unix Time. In my code I need to subtract one from another. When i did so I received an error saying I can't subtract strings. So I added types for serverTs and FTs as integers. file = r'S:\Работа с клиентами\Клиенты\BigTV Rating\fts_check.csv' col_names = ["Day", "vcId", "FTs", "serverTs", "locHost", "tnsTmsec", "Hits", "Uniqs"] df_empty = pd.DataFrame() with open(file) as fl: chunk_iter = pd.read_csv(fl, sep='\t', names=col_names, dtype={'serverTs': np.int32, 'FTs': np.int32}, chunksize = 100000) for chunk in chunk_iter: chunk['diff'] = np.array(chunk['serverTs'])-np.array(chunk['FTs']) chunk = chunk[chunk['diff'] &gt; 180] df_empty = pd.concat([df_empty,chunk]) But the program gives me an error: TypeError Traceback (most recent call last) pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens() TypeError: Cannot cast array from dtype('O') to dtype('int32') according to the rule 'safe' During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) in () 6 #dtype={'serverTs': np.int32, 'FTs': np.int32}, 7 #chunk_iter = chunk_iter.astype({'serverTs': np.int32, 'FTs': np.int32}) ----> 8 for chunk in chunk_iter: 9 #print(chunk[chunk['FTs'] == 'NaN']) 10 #chunk'serverTs','FTs' = chunk'serverTs','FTs'.astype('int32') C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py in next(self) 1040 def next(self): 1041 try: -> 1042 return self.get_chunk() 1043 except StopIteration: 1044 self.close() C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py in get_chunk(self, size) 1104 raise StopIteration 1105 size = min(size, self.nrows - self._currow) -> 1106 return self.read(nrows=size) 1107 1108 C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows) 1067 raise ValueError('skipfooter not supported for iteration') 1068 -> 1069 ret = self._engine.read(nrows) 1070 1071 if s…
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50718857
upvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/50718857
has comment: http://stackoverflow.com/comment/88445980
tagged with: dataframe
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/88695885
comment on: http://stackoverflow.com/q/50845990
has text: @ritlew Yes, I've added that and for some reason it still gives me the same error
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50762489
has title: Python Goole Drive API Disable Link Sharing & "Advanced Permissions"
type: Question
has answer: http://stackoverflow.com/a/50763185
has body: Can someone please tell me if it is possible to do the following, and if so, point me in the right direction please: TLDR: When I share the folder to a specific "user" as a "reader" I don't want link sharing to be turned on but it is. "Anyone at My_Org who has the link can view" I have dug through the docs and posts and cannot find how to do it. Code Below. I am creating folders with: def createFolder(name,sharewith): file_metadata = { 'name': name, 'parents': ['----------------------------------------'], 'mimeType': 'application/vnd.google-apps.folder' } file = service.files().create(body=file_metadata, fields='id').execute() fid = file.get('id') return fid Then Sharing the folder with a specific individual: def insert_permission(service, file_id, emailAddress, perm_type, role, notif): new_permission = { 'emailAddress': emailAddress, 'type': perm_type, 'role': role } try: return service.permissions().create( fileId=file_id, body=new_permission,sendNotificationEmail=notif).execute() except errors.HttpError as error: print('An error occurred: %s' % error) return None Edit: I see this - newPermission.setType("anyone"); in Set file sharing level to 'Anyone with the link' through Google Drive API I want to do the opposite but can't find the acceptable parameters for setType()
tagged with: linkshare
answer count: 1
linked to: http://stackoverflow.com/q/11155441
score: 0
tagged with: python
tagged with: permissions
tagged with: google-drive-api
type: UnansweredQuestion

http://stackoverflow.com/a/50762847
type: Answer
has body: why don't u just load the script ? and name your file .js var loader will be accessible in the main scope.
score: 0
answers question: http://stackoverflow.com/q/50761646

http://stackoverflow.com/a/50712682
has body: This might work from table import user user.User()
score: 0
has comment: http://stackoverflow.com/comment/88434410
type: Answer
answers question: http://stackoverflow.com/q/50712174

http://stackoverflow.com/q/50752438
has comment: http://stackoverflow.com/comment/88525914
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50752577
tagged with: performance
has answer: http://stackoverflow.com/a/50752577
has answer: http://stackoverflow.com/a/50752492
has comment: http://stackoverflow.com/comment/88512944
score: 0
has comment: http://stackoverflow.com/comment/88525704
answer count: 2
has title: Improve code to find prime numbers
has comment: http://stackoverflow.com/comment/88512940
linked to: http://stackoverflow.com/q/1801391
has comment: http://stackoverflow.com/comment/88520517
favorite count: 0
linked to: http://stackoverflow.com/q/2068372
accepted answer: http://stackoverflow.com/a/50752492
tagged with: python
tagged with: primes
has comment: http://stackoverflow.com/comment/88512936
type: AnsweredQuestion
upvote count: 1
has body: I wrote this python code about 3 days ago, and I am stuck here, I think it could be better, but I don't know how to improve it. Can you guys please help me? # Function def is_prime(n): if n == 2 or n == 3: return True for d in range(3, int(n**0.5), 2): if n % d == 0: return False return True

http://stackoverflow.com/comment/88878316
score: 1
comment on: http://stackoverflow.com/q/50807744
has text: Create a string `" "` and append it to the string given by `df.to_html()`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50787834
type: UnansweredQuestion
tagged with: classification
tagged with: python
has comment: http://stackoverflow.com/comment/88588912
answer count: 0
score: 1
has title: Best way to use an autoencoder with any classifier in keras
upvote count: 1
type: Question
has body: I built and trained a autoencoder in Keras, removed the decoder part and add a flatten layer in order to produce a feature vector. Now I wish to train a classifier (SVM for example) but, as preprocess step I need to apply the encoder to get the feature vector which will be used in the classifier. The problem is, the whole dataset does not fit into the memory! To overcome this during the training of the autoencoder I created a generator and used the fit_generator(..) function of the Model. Thus, I'm stuck in the same situation to train the SVM. I read about Pipelines in sk-learn, but I'm not sure if it will work for my situation, since I have the batch situation. I also read about the scaling stategies recommended in sk-learn doc page but again, run partial fit is not a problem, the real problem is the preprocess step which have to run in batches as well. I would like to know which are the strategies that I can used in this situation?
tagged with: batch-processing
downvote count: 0
tagged with: scikit-learn
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/88599399

http://stackoverflow.com/a/50844544
has body: pickle enables you to save your python object to your disk. Without running your first program, you can just load this pickle file and use it in another program by just calling the load function.
answers question: http://stackoverflow.com/q/50844344
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/50789526
tagged with: subdirectory
type: Question
score: 0
has title: Python output number of files in each sub directory for a specific file (*.doc) to a csv file
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88585444
has comment: http://stackoverflow.com/comment/88797181
has body: I would like to know if it is possible to count a specific files in folder and subfolders( per example all ".doc" files in folders) with the precedent script of @Mark Tolonen post on Python output number of files in each sub directory to a csv file ( a sort of try and count specific file )? import os import csv # Open the csv and write headers. with open("Subject_Task_Count.csv",'wb') as out: outwriter = csv.writer(out) outwriter.writerow(['Directory','FilesInDir','FilesIncludingSubdirs']) # Track total number of files in each subdirectory by absolute path totals = {} # topdown=False iterates lowest level (leaf) subdirectories first. # This way I can collect grand totals of files per subdirectory. for path,dirs,files in os.walk('.',topdown=False): files_in_current_directory = len(files) # Start with the files in the current directory and compute a # total for all subdirectories, which will be in the `totals` # dictionary already due to topdown=False. files_including_subdirs = files_in_current_directory for d in dirs: fullpath = os.path.abspath(os.path.join(path,d)) # On my Windows system, Junctions weren't included in os.walk, # but would show up in the subdirectory list. this try skips # them because they won't be in the totals dictionary. try: files_including_subdirs += totals[fullpath] except KeyError as e: print 'KeyError: {} may be symlink/junction'.format(e) totals[os.path.abspath(path)] = files_including_subdirs outwriter.writerow([path,files_in_current_directory,files_including_subdirs])
has comment: http://stackoverflow.com/comment/88797278

http://stackoverflow.com/comment/88700959
comment on: http://stackoverflow.com/q/50847827
has text: @rayryeng I put the x and y coordinates of the contours into a gist here: https://gist.github.com/sdoken/173fae1f9d8673ffff5b481b3872a69d Referring to a 512 by 512 numpy array, these coordinates tell you the location of the contour points.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88508256
comment on: http://stackoverflow.com/a/50750005
score: 0
has text: You got it -- it was actually adding `source='match_set'` that made it work. Bravo!
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50714467
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50714673
tagged with: file
type: Question
upvote count: 4
answer count: 2
score: 4
downvote count: 0
has title: extract zip files using python
possible better answer: http://stackoverflow.com/a/50714517
has answer: http://stackoverflow.com/a/50714673
has answer: http://stackoverflow.com/a/50714517
favorite count: 0
tagged with: http://stackoverflow.com/tag/zip
tagged with: extract
has body: import zipfile fantasy_zip = zipfile.ZipFile('E:\\Shared\\DOWNLOADED\\c.zip') fantasy_zip.extractall('E:\\Shared\\DOWNLOADED\\extract) fantasy_zip.close() my password is "hello" how can I include password to extract?

http://stackoverflow.com/q/50754368
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50755018
has title: NoReverseMatch at /post/new/ Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found
tagged with: blogs
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: Please, click the link to see the picture to see the error. base.html {% if user.is_authenticated %} New post Drafts Log out <a >Welcome: {{ user.username }} {% else %} Sign up post_detail.html {% extends 'blog/base.html'%} {% block content %} {{ post.title }} {% if post.published_date %} {{ post.published_date }} {% else %} Publish {% endif %} {% if user.is_authenticated %} {% endif %} {% if user.is_authenticated %} Comment {% else %} Comment {% endif %} {% for comment in post.comments.all %} {% if user.is_authenticated or comments.approved_comments %} {{ comment.created_date }} {% if not comment.approved_comments %} {% else %} {% endif %} Posted by: {{ comment.author }} {% endif %} {% empty %} No comments {% endfor %} {% endblock %} post_form.html % extends 'blog/base.html'%} {% load bootstrap3 %} {% block content %} New post {% csrf_token %} {{ form.as_p }} Save {% endblock %} urls.py from django.conf.urls import url from blog import views urlpatterns = [ url(r'^about/$', views.AboutView.as_view(), name = 'about'), url(r'^$', views.PostListView.as_view(),name = 'post_list' ), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name = 'post_detail'), url(r'^post/new/$', views.CreatePostView.as_view(), name = 'post_new'), url(r'^post/(?P<pk>\d+)/edit/$', views.PostUpdateView.as_view(), name = 'post_edit'), url(r'^post/(?P<pk>\d+)/remove/$', views.PostDeleteView.as_view(), name = 'post_remove'), url(r'^drafts/$', views.DraftListView.as_view(),name = 'post_draft_list' ), url(r'^post/(?P<pk>\d+)/Comment/$', views.add_comment_to_post, name = 'add_comment_to_post'), url(r'^comment/(?P<pk>\d+)/approve/$',views.comment_approve, name = 'comment_approve'), url(r'^comment/(?P<pk>\d+)/remove/$',views.comment_remove, name = 'comment_remove'), url(r'^signup/$', views.SignUp.as_view(), name ='signup'), url(r'^comment/(?P<pk>\d+)/Comment/$', views.comment_red, name = 'comment_redirect'), url(r'^post/(?P<pk…
downvote count: 1
score: -1

http://stackoverflow.com/comment/88535325
comment on: http://stackoverflow.com/q/50763584
score: 0
type: QuestionComment
has text: Thanks everyone. @TomDalton I updated the question to show what happens when I implement changing `r` to `rb`
type: Comment

http://stackoverflow.com/comment/88523257
type: Comment
has text: Nitpick: the ternary operator doesn't "only allow" expressions, it *is* an expression, called the [conditional expression](https://docs.python.org/3/reference/expressions.html#conditional-expressions). It can be used in other expressions and statements.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50757651

http://stackoverflow.com/q/50782337
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50782428
has body: I'd like to separate numerical values in the form with a comma in my Django project. Then I found the documentation below: https://docs.djangoproject.com/en/2.0/ref/contrib/humanize/ I thought that I can use 'intcomma' for my purpose. So I added "django.contrib.humanize" to my INSTALLED_APPS setting. And put {% load humanize %} in a template. When I use 'intcomma' like below, it worked. {{ 999999|intcomma }} # 999,999 But It did not work for integer form like below: # did not work. A code was displayed to html instead of numbers like this: &lt;input type="number" name="int_sample" value="100000" id="id_int_sample" My Django version is 2.0.1.
score: 3
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: django
has title: How can I use Django intcomma in integerfield
upvote count: 3
type: Question

http://stackoverflow.com/a/50820128
answers question: http://stackoverflow.com/q/50820087
type: AcceptedAnswer
score: 0
has body: Try: import re str = '999.33 This is an example g= 9.81 with numbers 32 in bewteen 5555' print( re.sub(r'(?&lt;=\=)(\s+\d+\.?\d+)', '10', str) ) #Lookbehind Output: 999.33 This is an example g=10 with numbers 32 in bewteen 5555
type: Answer
accepted answer of: http://stackoverflow.com/q/50820087

http://stackoverflow.com/a/50731449
upvote count: 4
has comment: http://stackoverflow.com/comment/107431559
has comment: http://stackoverflow.com/comment/88482639
accepted answer of: http://stackoverflow.com/q/50714395
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/107431046
has body: Your X should not be a matrix, but an array of 2D elements: X = np.array([[1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.], [1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.],[1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.]]) # rest of your code as is gp.fit(X, y) # result: GaussianProcessRegressor(alpha=1e-10, copy_X_train=True, kernel=RBF(length_scale=[1, 2]) * Matern(length_scale=[3, 4], nu=1.5), n_restarts_optimizer=0, normalize_y=False, optimizer='fmin_l_bfgs_b', random_state=None) That said, your kernel definition will not do what you want to do; most probably you have to change it to kernel = R([1,0]) * M([0,1]) but I am not quite sure about that - be sure to check the documentation for the correct arguments of the RBF and Matern kernels...
score: 4
answers question: http://stackoverflow.com/q/50714395
has comment: http://stackoverflow.com/comment/88533443
has comment: http://stackoverflow.com/comment/95696554
type: Answer
has comment: http://stackoverflow.com/comment/88510717
has comment: http://stackoverflow.com/comment/107432408
has comment: http://stackoverflow.com/comment/88510863
has comment: http://stackoverflow.com/comment/88470837
has comment: http://stackoverflow.com/comment/88471188

http://stackoverflow.com/q/50731702
favorite count: 0
tagged with: series
has body: If I have a dataframe like this: id str 01 abc_d(a) 02 ab_d(a) 03 abcd_e(a) 04 a_b(a) How can i get a dataframe as following ? Sorry i makeup this dataframe to represent my real issues. Thanks. id str 01 d 02 d 03 e 04 b
has answer: http://stackoverflow.com/a/50731749
tagged with: python
has title: Remove partial string from dataframe with Pandas
answer count: 4
has answer: http://stackoverflow.com/a/50731750
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88481979
upvote count: 3
has answer: http://stackoverflow.com/a/50731816
type: Question
possible better answer: http://stackoverflow.com/a/50731727
has answer: http://stackoverflow.com/a/50731727
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50731816
tagged with: string

http://stackoverflow.com/q/50737973
has body: I am using tensorflow to build a multilayer_perceptron network, based on the example given by Google The point is to train images to recognize specific patterns I am using images that are 1440*900 with coordinates that point these patterns (that might not be the best way but it is just a test really). When running my code I have the following error : #python multilayer_perceptron.py WARNING:tensorflow:From multilayer_perceptron.py:119: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version. Instructions for updating: Future major versions of TensorFlow will allow gradients to flow into the labels input on backprop by default. See @{tf.nn.softmax_cross_entropy_with_logits_v2}. 2018-06-07 11:29:14.144489: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA current batch : [195330 195330 195330 ... 155252 155252 155252] [ 90.5 312.5] Traceback (most recent call last): File "multilayer_perceptron.py", line 141, in &lt;module&gt; Y: batch_y}) File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 900, in run run_metadata_ptr) File "/usr/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1111, in _run str(subfeed_t.get_shape()))) ValueError: Cannot feed value of shape (1296000,) for Tensor 'Placeholder:0', which has shape '(?, 1296000)' Here is how I created the perceptrons: # Network Parameters n_hidden_1 = 10 #256 # 1st layer number of neurons n_hidden_2 = 10 #256 # 2nd layer number of neurons #each image has been flattened and converted to a 1-D numpy array of 1440*900 n_input = INPUT_SIZE # img size n_classes = 2 # coordinates of where to click # tf Graph input X = tf.placeholder("float", [None, n_input]) #n_input is size of input which is 784 pixels Y = tf.placeholder("float", [None, n_classes]) # n_classes is size of output which is 10 digits here so why float…
tagged with: python
has title: tensorflow : Analysing images gives Cannot feed value of shape (1296000,) for Tensor 'Placeholder:0', which has shape '(?, 1296000)'
type: AnsweredQuestion
score: 0
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50738290
type: Question
has comment: http://stackoverflow.com/comment/88483468
answer count: 1
has comment: http://stackoverflow.com/comment/88483546
accepted answer: http://stackoverflow.com/a/50738290

http://stackoverflow.com/a/56132715
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50743227
has body: Try this: # conversion can access other values from the same row table = etl.convert(table, 'Price List', lambda row: 100 * (1 + row.IRR), pass_row=True)

http://stackoverflow.com/q/50849458
has answer: http://stackoverflow.com/a/50849624
type: Question
tagged with: function
tagged with: class
has body: In my code, I'm using a JSON file to decide what the values are to be used to initialize an object. In my config.json: { "ClassA": { "p1": 3, "p2"; 4 } } My ClassA: class ClassA: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 Then I'm instantiating ClassA via: with open("config.json", "r") as f: config = json.load(f) a = ClassA(**config["ClassA"]) Now the problem arises when either the keys associated with the value changes (e.g. "p1" changes to "p3") in the JSON; or the name of the parameters in ClassA changes. As any change would mean that using the instantiation method above fails. In an attempt to decouple the configuration with my code, I've defined another class to map the configuration parameters names to my class parameter names and vice-versa. class IInitializable(ABC): _parameter_name_lookup = dict() @classmethod def parameter_name_lookup(cls, mode): if mode == "ConfigurationToClass": return {y: x for x, y in cls._parameter_name_lookup.items()} elif mode == "ClassToConfiguration": return cls._parameter_name_lookup else: raise NameError("No such mode") Now say I change my config.json to: { "ClassA": { "p1": 3, "p9"; 4 } } And my ClassA to: class ClassA: def __init__(self, p1, p4): self.p1 = p1 self.p2 = p4 I would let ClassA inherit from IInitializeable and define the mapping: class ClassA(IInitializable): _parameter_name_lookup = {"p4": "p9"} def __init__(self, p1, p4): self.p1 = p1 self.p2 = p4 Then I could initialize my ClassA with the new config.json by: with open("config.json", "r") as f: config = json.load(f) config_to_class_lookup = ClassA.parameter_name_lookup("ConfigurationToClass") new_parameters_for_a = dict() for config_parameter_name, value in config.items(): class_parameter_name = config_to_class_lookup.get(config_parameter_name, config_parameter_name) new_parameters_for_a[class_parameter_name] = value a = ClassA(**new_parameters_for_a) Though, I'm sure that there is a more elegant way to approach this problem. I've read up my metaclass…
score: 0
has comment: http://stackoverflow.com/comment/88701812
linked to: http://stackoverflow.com/q/45420138
answer count: 1
has title: How can I decouple the parameter names in my code from the configuration file?
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/50705195
has comment: http://stackoverflow.com/comment/88420943
has comment: http://stackoverflow.com/comment/88420656
has body: I am just trying to do this really simple thing where I want to play two different sound files depending on a touch sensor. The problem that I currently have is that I cannot even play one of them without anything else, because 'the files cannot be opened'. import pygame pygame.mixer.pre_init(44100, -16, 12, 512) pygame.init slowbeat = pygame.mixer.Sound('/home/pi/gpio-music-box/samples/slowbeat.wav') slowbeat.set_volume(.4); fastbeat = pygame.mixer.Sound('/home/pi/gpio-music-box/samples/fastbeat.wav') fastbeat.set_volume(.4); slowbeat.play() The traceback: Traceback (most recent call last): File "/home/pi/a.py", line 11, in slowbeat = pygame.mixer.Sound('slowbeat.wav') pygame.error: Unable to open file 'slowbeat.wav'
has comment: http://stackoverflow.com/comment/88420396
type: Question
has answer: http://stackoverflow.com/a/50705635
has comment: http://stackoverflow.com/comment/88420278
has comment: http://stackoverflow.com/comment/88420569
has comment: http://stackoverflow.com/comment/88420275
has comment: http://stackoverflow.com/comment/88420991
tagged with: raspberry-pi
upvote count: 1
answer count: 1
has title: Sounds with pygame can't be opened
has comment: http://stackoverflow.com/comment/88420552
has comment: http://stackoverflow.com/comment/88419885
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: pygame
tagged with: audio
downvote count: 0
type: UnansweredQuestion
score: 1

http://stackoverflow.com/a/50811902
has comment: http://stackoverflow.com/comment/100200068
downvote count: 0
score: 22
has body: I wonder if you have seen this page? Either way, let me explain a few things for you. The number of documents you use is small for the method (it works much better when trained on a data source of the size of Wikipedia). Therefore the results will be rather crude and you have to be aware of that. This is why you should not aim for a large number of topics (you chose 10 which could maybe go sensibly up to 20 in your case). As for the other parameters: random_state - this serves as a seed (in case you wanted to repeat exactly the training process) chunksize - number of documents to consider at once (affects the memory consumption) update_every - update the model every update_every chunksize chunks (essentially, this is for memory consumption optimization) passes - how many times the algorithm is supposed to pass over the whole corpus alpha - to cite the documentation: can be set to an explicit array = prior of your choice. It also support special values of `‘asymmetric’ and ‘auto’: the former uses a fixed normalized asymmetric 1.0/topicno prior, the latter learns an asymmetric prior directly from your data. per_word_topics - setting this to True allows for extraction of the most likely topics given a word. The training process is set in such a way that every word will be assigned to a topic. Otherwise, words that are not indicative are going to be omitted. phi_value is another parameter that steers this process - it is a threshold for a word treated as indicative or not. Optimal training process parameters are described particularly well in M. Hoffman et al., Online Learning for Latent Dirichlet Allocation. For memory optimization of the training process or the model see this blog post.
has comment: http://stackoverflow.com/comment/129285564
has comment: http://stackoverflow.com/comment/128918600
type: Answer
has comment: http://stackoverflow.com/comment/88642019
has comment: http://stackoverflow.com/comment/115114451
accepted answer of: http://stackoverflow.com/q/50805556
has comment: http://stackoverflow.com/comment/88644339
answers question: http://stackoverflow.com/q/50805556
has comment: http://stackoverflow.com/comment/100200093
upvote count: 22
type: AcceptedAnswer

http://stackoverflow.com/comment/88577905
has text: Do you know whether the trackers support udp announces? Have you compared with a working bittorrent client? Try comparing a working and your own announce with wireshark.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50781349

http://stackoverflow.com/comment/88629850
has text: Yes, pretty nice. One question: don't you need to initialize d[k] to [] before adding to it?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50812235

http://stackoverflow.com/q/50699300
tagged with: python
has comment: http://stackoverflow.com/comment/88408835
has comment: http://stackoverflow.com/comment/88409707
score: 1
tagged with: multithreading
tagged with: pyqt5
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50700411
answer count: 2
linked to: http://stackoverflow.com/q/16879971
downvote count: 0
has body: I'm trying to write a PyQt application for some image processing algorithms that I have written. The problem is, these take some time and make the app freezes (until it finishes but the user might be compelled to close the app in the mean time). I'm trying to understand how to implement multi-threading but I just can't seem to make it work. This example just loads a large image on a different thread, but it still makes the whole app freeze. I'm sure I'm making a mistake somewhere. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class App(QWidget): def __init__(self): super().__init__() self._unit_ui() def _unit_ui(self): label = QLabel(self) label.resize(700, 700) button = QPushButton(self) self.th = Thread(self) self.th.change_pixmap.connect(label.setPixmap) button.pressed.connect(self.th.start) self.show() class Thread(QThread): change_pixmap = pyqtSignal(QPixmap) def __init__(self, parent=None): QThread.__init__(self, parent=parent) self.isRunning = True def run(self): pixmap = QPixmap('gridscan.jpg') self.change_pixmap.emit(pixmap) app = QApplication(sys.argv) m = App() sys.exit(app.exec_())
favorite count: 0
has title: PyQt5 multithreading still freezes. How to improve performance?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50699688

http://stackoverflow.com/comment/88588285
score: 0
comment on: http://stackoverflow.com/q/50791076
has text: you're creating many tables, you should move the `for loop` just around the ` ` blocks.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50821145
has answer: http://stackoverflow.com/a/50849383
accepted answer: http://stackoverflow.com/a/50849383
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88647653
answer count: 1
upvote count: 6
favorite count: 0
linked to: http://stackoverflow.com/q/31883432
tagged with: python
tagged with: rncryptor
downvote count: 0
has comment: http://stackoverflow.com/comment/88647834
score: 6
has body: Is there a method to convert an image, that is loaded as a binary string, into a numpy array of size (im_height, im_width, 3)? Something like this: # read image as binary string with open(img_path, "rb") as image_file: image_string = image_file.read() # convert image string to numpy image_np = convert_binary_string_to_numpy(image_string) How would that conversion function look like? I'm working with decryption, thus I need to work with binary strings. Thanks!
tagged with: opencv
type: AnsweredQuestion
tagged with: python-imaging-library
has title: Convert image loaded as binary string into numpy array

http://stackoverflow.com/a/50770952
has body: You need a client to punch text into the web browser, which is not a PHP problem. Typically a barcode scanner will act as a HID, so it appears to type out the number and press enter wherever you scan something. You can either plug in an alernate RFID reader that acts as a HID, or simulate keyboard events from python. Sort out permissions or pass around the data so that you can get the RFID input without sudo: To create the keyboard events, you should be running under your graphical session, as yourself. Call the something like xte from python, which is part of the Debian xautomation package.
upvote count: 1
answers question: http://stackoverflow.com/q/50770703
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/95059499
has text: I tried so hard to make pygmo work, but as you say, the community is very small. I hardly find my questions answered and keep finding similar documentation whatever I search for. Generally speaking, I still don't know why would someone prefer scipy over pygmo or visa versa. Do you have any thoughts? I was able to simply parallelize my DE in scipy, but after 2 weeks i am still tweaking my pygmo code to get something out of it, no success yet. It seems much complicated compared to scipy, as you need to explicitly define classes and deeply understand which one does what.
comment on: http://stackoverflow.com/a/50872377
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/74764162
score: 8
answers question: http://stackoverflow.com/q/50849789
has comment: http://stackoverflow.com/comment/132786186
has comment: http://stackoverflow.com/comment/132591311
downvote count: 0
has comment: http://stackoverflow.com/comment/139219864
has body: I am not a mathematician but here is my layman's explanation of “norm”: A vector describes the location of a point in space relative to the origin. Here’s an example in 2D space for the point [3 2]: The norm is the distance from the origin to the point. In the 2D case it’s easy to visualize the point as the diametrically opposed point of a right triangle and see that the norm is the same thing as the hypotenuse. However, In higher dimensions it’s no longer a shape we describe in average-person language, but the distance from the origin to the point is still called the norm. Here's an example in 3D space: I don’t know why the norm is used in K-means clustering. You stated that it was part of determing the distance between the old and new centroid in each step. Not sure why one would use the norm for this since you can get the distance between two points in any dimensionality* using an extension of the from used in 2D algebra: You just add a term for each addtional dimension, for example here is a 3D version: *where the dimensions are positive integers
upvote count: 8
type: Answer

http://stackoverflow.com/comment/117282905
has text: [This answer](https://stackoverflow.com/a/66271987/2313889) might be also helpful. Check it out.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/54958813

http://stackoverflow.com/comment/88611255
score: 0
type: Comment
type: QuestionComment
has text: Yeah, I'll try this
comment on: http://stackoverflow.com/q/50802475

http://stackoverflow.com/comment/88715205
type: QuestionComment
has text: The high numbers usually occur when zero is the input value. When calculating the SSE, I can do without this comparison at zero, and then get normal values for SSE.
score: 0
comment on: http://stackoverflow.com/q/50761849
type: Comment

http://stackoverflow.com/comment/88573178
has text: check which version of pip you have installed and pointing for pip3 ls -l `which pip3`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50782767

http://stackoverflow.com/comment/88423123
type: Comment
type: QuestionComment
has text: I don't think the equation you are using has the same shape as your data - make a scatterplot of the data only and you can see this. The Stirling equation is a much better fit to your data, try the equation "y = a * (exp(bx) - 1.0) / b" with fitted parameters a = 1.8641552758230268E-01 and b = -2.8402723064116495E-02
comment on: http://stackoverflow.com/q/50706092
score: 0

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

http://stackoverflow.com/q/50730811
favorite count: 0
tagged with: python
has body: So, I'm interested in communicating between a C program and a Python program so that I can neatly send tasks and data between the two. I figured I'd go ahead and start with this guide. In this guide I have a C file with contents outlined in the example in the link right above the "Building and Installing Extensions" title and the python code from right under it. After I run the python setup.py install command I try to import the created module through &gt;&gt;&gt;import helloworld ImportError: DLL load failed: %1 is not a valid Win32 application. So I suppose the issue is that the extension is 32-bit while my Python installation is 64-bit? The python I'm using is Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)] on win32 All help appreciated!
has title: Extending Python with C on Windows - ImportError: DLL load failed: %1 is not a valid Win32 application
score: 2
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python-extensions
type: Question
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/88469725
downvote count: 0

http://stackoverflow.com/q/50810019
upvote count: 1
tagged with: psycopg2
accepted answer: http://stackoverflow.com/a/50810057
type: AnsweredQuestion
type: Question
answer count: 1
downvote count: 0
score: 1
tagged with: string
tagged with: postgresql
has title: select specific columns for each query in union in postgresql from python
tagged with: python
has body: I have different tables of same columns across monthly time periods. I want to pull only specific columns from each table and then do a UNION as shown below. col_list = ['income', 'urban2', 'marital_stat', 'ethnic_group'] data_sample = str(""" SELECT {} FROM dbo.gold_nov17 where drform in ('NON') """.format(', '.join(col_list))) This query on a single table works just fine. However when I try to do a union as below: data_sample = str(""" SELECT {} FROM dbo.gold_nov17 where drform in ('NON') ----------- union all ----------- SELECT {} FROM dbo.gold_nov17 where drform in ('NON') """.format(', '.join(col_list))) It throws error: """.format(', '.join(col_list))) IndexError: tuple index out of range I am essentially wanting to select specific columns(based on col_list) for each of the tables for UNION.
favorite count: 0
has answer: http://stackoverflow.com/a/50810057
tagged with: string-formatting

http://stackoverflow.com/comment/88626370
type: Comment
type: QuestionComment
has text: you cant expect data to be magically preserved between different runs of the script, after all python interprets the file every time you try to run it
comment on: http://stackoverflow.com/q/50810442
score: 1

http://stackoverflow.com/a/50800121
type: Answer
accepted answer of: http://stackoverflow.com/q/50789031
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50789031
has body: I keep getting 2 errors: "runtimeError: Event loop is running." or "asyncio > Task was destroyed but it is pending!" As you discovered, asyncio event loops do not nest. To remove the nesting, you should define send_to_peers as a coroutine using async def. Inside it loop.run_until_complete(coro) should be changed to await coro. Once send_to_peers is a coroutine, you can call it: from blocking code such as infinite using loop.run_until_complete(send_to_peers(...)) from async code such as infinite_loop using await send_to_peers(...). In case of infinite_loop, you can implement the timeout using asyncio.wait_for: try: await asyncio.wait_for(send_to_peers(str(index)), 10) except asyncio.TimeoutError: # ... timeout ...
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88693715

http://stackoverflow.com/comment/88512340
score: 0
comment on: http://stackoverflow.com/q/50752067
type: Comment
type: QuestionComment
has text: Take a look at: [Generate a custom formated string with python](https://stackoverflow.com/q/45670876/2063361)

http://stackoverflow.com/q/50844505
accepted answer: http://stackoverflow.com/a/50845039
type: Question
tagged with: python
score: 0
answer count: 2
has title: Using Pandas Getdummies or isin to create Bool Features from feature that contains lists
has answer: http://stackoverflow.com/a/50845406
possible better answer: http://stackoverflow.com/a/50845406
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50845039
has body: I have a pandas dataframe with one column containing a list of unique strings for each instance: obj_movies['unique_genres'].head() 0 [Action, Fantasy, Adventure, Science Fiction] 1 [Action, Fantasy, Adventure] 2 [Action, Adventure, Crime] 3 [Action, Drama, Thriller, Crime] 4 [Action, Science Fiction, Adventure] Name: unique_genres, dtype: object I would like to use pandas get_dummies() to create boolean features (to add on to the same dataframe) based on values in the list. For example, feature 'Action_Movie' would be True (or have value 1) for all first five instances. To complete this task, I created a set of unique values from all the lists contained in the feature. With a for loop, for each movie tag feature (i.e. unique value in the set) I then used a boolean conversion method I created separately to create a list of 1's or a 0's based on the method outcomes. Finally, I simply appended as new pandas series. However, I am thinking there must be a faster way! What about pandas df.isin() method for example? I also looked into that but it doesn't seem to work when you pass it a series of lists What would be the best way to go about doing this? Can anyone recommend a good pandas advanced data manipulation tutorial online?

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

http://stackoverflow.com/comment/88674656
type: Comment
type: QuestionComment
score: 1
has text: Incase it can't decode the JSON data, as stated I am working with a finicky host.
comment on: http://stackoverflow.com/q/50834924

http://stackoverflow.com/a/50805751
type: Answer
has body: Since it looks like they are already integers, forget about all of the string formatting. df['year'] = df.date//10**4 df['month'] = df.date//100%100 df['day'] = df.date%100
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50805591

http://stackoverflow.com/comment/88440343
score: 1
has text: [`str.split()`](https://docs.python.org/3/library/stdtypes.html#str.split) should be more than enough for this.
comment on: http://stackoverflow.com/q/50715769
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50725015
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50724762
accepted answer of: http://stackoverflow.com/q/50724762
has body: Using K.stack(): import keras import keras.backend as K input = K.constant([3.14, 0., 0, 3.14]) dX, dY, dZ = K.constant(1.), K.constant(2.), K.constant(3.) c, s = K.cos(input[3]), K.sin(input[3]) T = K.stack([[ c, -s, 0., dX], [ s, c, 0., dY], [0., 0., 1., dZ], [0., 0., 0., 1.]], axis=0 ) sess = K.get_session() res = sess.run(T) print(res) # [[ -9.99998748e-01 -1.59254798e-03 0.00000000e+00 1.00000000e+00] # [ 1.59254798e-03 -9.99998748e-01 0.00000000e+00 2.00000000e+00] # [ 0.00000000e+00 0.00000000e+00 1.00000000e+00 3.00000000e+00] # [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.00000000e+00]] How to use with Lambda: Keras layers are expecting/dealing with batched data. Keras would for instance assume that the input (angs) of your Lambda(FK_Keras) layer is of shape (batch_size, 5). Your FK_Keras() thus need to be adapted to deal with such inputs. A rather straightforward way to do so, requiring only minor edits to your T_matrix_K() is to use K.map_fn() to loop over every list of angles in the batch and apply the proper T_matrix_K() function to each. Other minor changes to deal with batches: Using K.batch_dot() instead of K.dot() Broadcasting accordindly your constant tensors e.g. self.base_pos_K Taking into account the additional 1st dimension to batched tensors, e.g. replacing end_effector_T[1,0] by end_effector_T[:, 1,0] Find below a shortened working code (extending to all joints is left to you): import keras import keras.backend as K from keras.layers import Lambda, Dense from keras.models import Model, Sequential import numpy as np def trig_K( angle): r = angle*np.pi/180.0 return K.cos(r), K.sin(r) def T_matrix_K_z(x): rotation, translation = x[0], x[1] c, s = trig_K(rotation) T = K.stack( [[c, -s, 0., translation[0]], [s, c, 0., translation[1]], [0., 0., 1., translation[2]], [0., 0., 0., 1.]], axis=0) # We have 2 inputs, so have to return 2 outputs for `K.map_fn()`: return T, 0. def T_matrix_K_y(x): rotation, translation = x[0], x[1] c, s = trig_K(rotati…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88574551

http://stackoverflow.com/comment/88490288
comment on: http://stackoverflow.com/a/50729633
score: 0
type: Comment
has text: That is exactly what I am looking for! (and probably more efficient than a method I would have devised)
type: AnswerComment

http://stackoverflow.com/a/50850532
accepted answer of: http://stackoverflow.com/q/50850325
upvote count: 1
has comment: http://stackoverflow.com/comment/88704797
has comment: http://stackoverflow.com/comment/88704760
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88704746
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88704818
has comment: http://stackoverflow.com/comment/88704038
has comment: http://stackoverflow.com/comment/88703988
type: Answer
answers question: http://stackoverflow.com/q/50850325
has comment: http://stackoverflow.com/comment/88704462
has body: First reshape DataFrame by set_index and unstack: df = t.set_index(['ReturnType','Payment']).unstack() print (df) Hour value Label Payment Card Cash Card Cash Card Cash ReturnType Return With Proof Of Purchase 16 14 17 67 17.0--16 67.0--14 Return With Receipt 16 12 37 26 37.0--16 26.0--12 ReturnWithoutReceipt 11 12 1 3 1.0--11 3.0--12 Select each DataFrame by xs (because MultiIndex in columns) df1 = df.xs('value', axis=1, level=0) lab = df.xs('Label', axis=1, level=0) print (df1) Payment Card Cash ReturnType Return With Proof Of Purchase 17 67 Return With Receipt 37 26 ReturnWithoutReceipt 1 3 print (lab) Payment Card Cash ReturnType Return With Proof Of Purchase 17.0--16 67.0--14 Return With Receipt 37.0--16 26.0--12 ReturnWithoutReceipt 1.0--11 3.0--12 And last pass second DataFrame to parameter annot, idea for show labels is from this answer: ax = sns.heatmap(df1, annot=lab, fmt="")
has comment: http://stackoverflow.com/comment/88704115
has comment: http://stackoverflow.com/comment/88704786
has comment: http://stackoverflow.com/comment/88704179

http://stackoverflow.com/q/50776071
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/88560471
upvote count: 2
tagged with: regression
tagged with: selenium
tagged with: web-scraping
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50776223
has comment: http://stackoverflow.com/comment/88560381
has title: How to write a python program that 'scrapes' the results from a website for all possible combinations chosen from the given drop down menus?
type: AnsweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88559079
has answer: http://stackoverflow.com/a/50776223
type: Question
has comment: http://stackoverflow.com/comment/88560527
linked to: http://stackoverflow.com/q/25747294
has comment: http://stackoverflow.com/comment/88560162
tagged with: python
has body: There is a website that claims to predict the approximate salary of an individual on the basis of the following criteria presented in the form of individual drop-down Age : 5 options Education : 3 Options Sex : 3 Options Work Experience : 4 Options Nationality: 12 Options On clicking the Submit button, the website gives a bunch of text as output on a new page with an estimate of the salary in numerals. So, there are technically 5*3*3*4*12 = 2160 data points. I want to get that and arrange it in an excel sheet. Then I would run a regression algorithm to guess the function this website has used. This is what I am looking forward to achieve through this exercise. This is entirely for learning purposes since I'm keen on learning these tools. But I don't know how to go about it? Any relevant tutorial, documentation, guide would help! I am programming in python and I'd love to use it to achieve this task! Thanks!

http://stackoverflow.com/q/50792424
score: 4
upvote count: 4
accepted answer: http://stackoverflow.com/a/50810091
answer count: 1
downvote count: 0
tagged with: imagefilter
has body: Using PIL in Python, I am superimposing a PNG image on top of another, larger image. The smaller image is semi-transparent. I would like for the area behind the smaller image to be blurred on the larger image. The following code blurs a rectangular area: box = (3270, 1150, 4030, 2250) # (x1, y1, x2, y2) ic = outputImage.crop(box) ic = ic.filter(ImageFilter.BoxBlur(20)) outputImage.paste(ic, box) However, I need to blur a rectangular area that has rounded corners. This is what the superimposed image looks like: So, is it possible to define a custom shape for a cropped area in PIL? If not, is it possible to at least crop circle-shaped areas? (For full coverage and without any overhang, my area would have to broken down into 6 sub-areas: 4 circles and 2 rectangles. Doing all this will slow down my code, but I will take whatever solution I can get.) I understand that this can be done with Numpy, but I would prefer to use PIL because everything else in this script is already coded with PIL.
favorite count: 0
tagged with: python
has title: How to blur non-rectangular or circular area of image with Python PIL?
linked to: http://stackoverflow.com/q/7787375
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3707567
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/50810091

http://stackoverflow.com/comment/88624547
comment on: http://stackoverflow.com/q/50809409
has text: I advice you to use dictinaries
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88518620
has text: show, please, how do you get data from postgres
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50755291
score: 1

http://stackoverflow.com/comment/88476035
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50733181
has text: Ooh thats great just tried it thanks! Btw dude, in this code >>> div.find('h2').text: div.find('span', {'class': 'amount'}).text.strip() for div in divs <<< Why is the for loop placed after the line and not before like normal for loop conventions?
score: 0

http://stackoverflow.com/comment/88676811
comment on: http://stackoverflow.com/q/50835979
type: Comment
type: QuestionComment
has text: @ChesuCR When using the plotting API there is a warning about duplicate tools but using multiple `HoverTool`s otherwise seems to work all right (there is even an individual icon in the toolbar for each `HoverTool` that allows enabling/disabling it individually).
score: 0

http://stackoverflow.com/a/50721880
score: 0
has body: I don't think it is workable for now as the intermediate float cast is unavoidable (see this issue for details). While float type cannot preserve the precision of such a long-digit decimal (check the float representation for details). One way to work around is "override" the numpy.longdouble function: class Custom(object): def __init__(self, int_, nano_): self._int = int_ self._nano = nano_ def __float__(self): return self._int + self._nano * 1e-9 def longdouble(self): return numpy.longdouble(a._int) + numpy.longdouble(a._nano * 1e-9) def __int__(self): return self._int a = Custom(1234567890, 123456789) print(a.longdouble())
type: Answer
answers question: http://stackoverflow.com/q/50718474

http://stackoverflow.com/q/50790043
score: 0
has comment: http://stackoverflow.com/comment/88586268
answer count: 1
has comment: http://stackoverflow.com/comment/88586276
has title: There are too many data that dotted line seem to be straight line in Matplotlib
accepted answer: http://stackoverflow.com/a/50793609
has comment: http://stackoverflow.com/comment/88586117
tagged with: python
has body: As the picture below In the subplot (2,1,1), the linestyle is '--'， but seems like a straight line. In the subplot (2,1,2), the linestyle is ':', it seems better but also have the same problem. How can I get a concise dotted line? plt.subplot(2, 1, 1) plt.plot(df['START_DATETIME'],df['RESULT_DESC'],'o') plt.plot(df['START_DATETIME'],(xbar,) * num) plt.plot(df['START_DATETIME'],((UCL,) * num),'--') plt.plot(df['START_DATETIME'],((LCL,) * num),'--') plt.subplot(2, 1, 2) plt.plot(df['START_DATETIME'],df['range'],'o') plt.plot(df['START_DATETIME'],(rbar,) * num) plt.plot(df['START_DATETIME'],((UCLR,) * num),':') plt.axhline(y=UCLR, xmin=starttime, xmax=stoptime) plt.plot(df['START_DATETIME'],((0,)*num),':')
has comment: http://stackoverflow.com/comment/88586104
has comment: http://stackoverflow.com/comment/88587223
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50793609
tagged with: matplotlib

http://stackoverflow.com/comment/88592075
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50783853
score: 0
has text: Yes , i have used for other codes and they are working fine

http://stackoverflow.com/q/50804741
has title: Pandas Shift columns but add new rows where non-shifted columns are null
answer count: 1
has comment: http://stackoverflow.com/comment/88615805
tagged with: python
has answer: http://stackoverflow.com/a/50804831
accepted answer: http://stackoverflow.com/a/50804831
type: AnsweredQuestion
type: Question
has body: Say I have a dataframe: x y 0 1 5 1 2 4 2 3 3 3 4 2 4 5 1 I want to run something like df.y.shift(3) and it will not only shift y down 3 rows but also create three new rows for x that are null so that the dataframe becomes x y 0 1 N 1 2 N 2 3 N 3 4 5 4 5 4 5 N 3 6 N 2 7 N 1 Where N=NaN The shift operator only seems to shift a column down n rows but will also "knock" n items from your list. I want to keep those n item on my new dataframe.
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88615780

http://stackoverflow.com/comment/113279319
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50790965
has text: I had the same problem and it was related to the scheduler and how I set up that.

http://stackoverflow.com/comment/88633710
type: Comment
has text: That is because when you append the first time, `soup_append.a` becomes `None`. Check this value after the first append.
type: AnswerComment
comment on: http://stackoverflow.com/a/50814029
score: 0

http://stackoverflow.com/q/50819717
answer count: 1
tagged with: python
tagged with: directory
favorite count: 0
has comment: http://stackoverflow.com/comment/88644662
type: UnansweredQuestion
score: -3
tagged with: file
downvote count: 4
has answer: http://stackoverflow.com/a/50820085
has comment: http://stackoverflow.com/comment/88644655
has title: Python error. FileNotFoundError: [Errno 2] No such file or directory:
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/88645762
has comment: http://stackoverflow.com/comment/88644721
has body: Running a python code but getting a weird error in regards to finding the working directory and file to run the script. FileNotFoundError: [Errno 2] No such file or directory: Please let me know if you have any suggestions or know how I may be able to fix the error.

http://stackoverflow.com/a/50849492
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50849380
has body: We needed to Create a service account key in GCP console. More details are here: https://cloud.google.com/storage/docs/reference/libraries Then in the python code we added: os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/SERVICE_KEY.json" After that I can access my endpoint API without authentication.
accepted answer of: http://stackoverflow.com/q/50849380

http://stackoverflow.com/a/50831048
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50830909
answers question: http://stackoverflow.com/q/50830909
type: AcceptedAnswer
downvote count: 0
has body: Try using raw string instead. Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it. https://www.tutorialspoint.com/python/python_strings.htm
type: Answer
score: 1

http://stackoverflow.com/q/50842580
score: 2
has comment: http://stackoverflow.com/comment/88688712
has answer: http://stackoverflow.com/a/50842689
upvote count: 2
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88688768
tagged with: data-structures
has comment: http://stackoverflow.com/comment/88688686
accepted answer: http://stackoverflow.com/a/50842689
tagged with: pandas
has title: Creating a new column in a data frame by mapping the values from a dictionary to an existing column
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: dictionary
has body: I have a dictionary like this: dictionary = {100:[1, 2], 110:[3, 4], 120:[5, 6, 7], 130:[8, 9], 140:[10, 11, 12, 13], 150:[14, 15]} I already have an existing column 'A' and would like to create a new column 'B' and map the values back to each key but display this in a data frame format. Here is the output I wish to receive: #Column A is the existing column. Column B is the new one to be created A B 4 110 8 130 15 150 7 120 7 120 4 110 9 130 1 100 2 100 How can this be done? Help would be appreciated. Thanks in advance!

http://stackoverflow.com/a/50820933
answers question: http://stackoverflow.com/q/50820707
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88647656
has comment: http://stackoverflow.com/comment/88647509
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88647266
has body: This can be done (assuming that args are all hashable) class MyClass: instances = {} def __new__(cls, *args): if args in cls.instances: return cls.instances[args] self = super().__new__(cls) cls.instances[args] = self return self a = MyClass('hello') b = MyClass('hello') c = MyClass('world') a is b and a == b and a is not c and a != c # True is is the python operator that shows two objects are the same instance. == falls back to is on objects where it is not overidden. As pointed out in the comments, this can be a bit troubling if you have an __init__ with side effects. Here's an implementation that avoids that: class Coord: num_unique_instances = 0 _instances = {} def __new__(cls, x, y): if (x, y) in cls._instances: return cls._instances[x, y] self = super().__new__(cls) # __init__ logic goes here -- will only run once self.x = x self.y = y cls.num_unique_instances += 1 # __init__ logic ends here cls._instances[x, y] = self return self # no __init__ method
has comment: http://stackoverflow.com/comment/88647355

http://stackoverflow.com/comment/88600001
comment on: http://stackoverflow.com/a/50794028
score: 0
type: Comment
has text: The Stacktrace shows that Spark is unable to find the winutils.exe file. This is required when running spark on a local windows machine. It actually makes spark think that it is interacting/running alongside a hadoop installation
type: AnswerComment

http://stackoverflow.com/a/50778445
downvote count: 1
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/88573339
answers question: http://stackoverflow.com/q/50777423
has comment: http://stackoverflow.com/comment/91544434
has body: @ Daniel, Nice code, has written some thing similar for the same question, But since your code was better didn't post mine, hadn't thought of using enumerate, was looping through them. Will now go back and rethink a lot of my code to include the freedom of enumerate.
score: -1
has comment: http://stackoverflow.com/comment/88563759
has comment: http://stackoverflow.com/comment/91545497

http://stackoverflow.com/a/50732049
answers question: http://stackoverflow.com/q/50731944
type: Answer
score: 1
upvote count: 1
has body: Well first youll want to add those score variables at the begging of your code. computer_score=0 user_score=0 then you want to have a while statement that also encloses the user input Rock_paper_scissors = ['rock', 'paper', 'scissors'] while True: user_choice = input("select one of "rock, paper, scissors. ") computer_choice = Rock_paper_scissors[random.randint(0,2)] #Your if/elif statements go here And at the end and an if statement to check if someone has a score of 3 or more if user_score &gt;= 3: print('You win') break
downvote count: 0

win32gui
type: Tag
tags question: http://stackoverflow.com/q/50825336
tag name: win32gui
tags question: http://stackoverflow.com/q/50796382

http://stackoverflow.com/a/50933085
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50803382
downvote count: 0
has body: Welcome to SO! I solved it by using Docker-Compose for running a separate CouchDB Container and a separate Python Container. The relevant part of the configuration file docker-compose.yml looks like this: # This help to avoid routing conflict within virtual machines: networks: default: ipam: driver: default config: - subnet: 192.168.112.0/24 # The CouchDB data is kept in docker volume: volumes: couchdb_data: services: # The container couchServer uses Dockerfile from the subdirectory CouchDB-DIR # and it has the hostname 'couchServer': couchServer: build: context: . dockerfile: CouchDB-DIR/Dockerfile ports: - "5984:5984" volumes: - type: volume source: couchdb_data target: /opt/couchdb/data read_only: False - type: volume source: ${DOCKER_VOLUMES_BASEPATH}/couchdb_log target: /var/log/couchdb read_only: False tty: true environment: - COUCHDB_PASSWORD=__secret__ - COUCHDB_USER=admin python_app: build: context: . dockerfile: ./Python_DIR/Dockerfile ... In the Docker subnet, the CouchDB can be accessed by http://couchServer:5984 from the Python container. To ensure that the CouchDB is not lost when restarting the container, it is kept in a separate Docker volume couchdb_data. Use the enviroment-variable DOCKER_VOLUMES_BASEPATH to determine in which directory CouchDB logs. It can be defined in a .env-file. The network section is only necessary if you have routing problems.
has comment: http://stackoverflow.com/comment/88874298
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50803382

http://stackoverflow.com/comment/88609412
type: QuestionComment
has text: This is a very nonspecific question and it is difficult to understand what you mean. Can you come with example input and ideal output as well?
comment on: http://stackoverflow.com/q/50801553
score: 0
type: Comment

http://stackoverflow.com/q/50801910
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50804640
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: aiohttp
score: 1
has body: I want to have additional attributes of request to be logged in access log of aiohttp server. For example I have middleware, that adds user attribute to each request, and I want to store this value inside extra attribute for access log records. Documentation suggests to overwrite aiohttp.helpers.AccessLogger which indeed seems to be a good starts, but what do I do next, where do I put instance of my custom logger? I looked through the code and it looks like that is not possible on application creation stage, but rather on application run. But I'm running application using different approaches, so this it's not that convenient to modify startup in several places (for example locally I'm using aiohttp-devtools runserver and gunicorn for deployment). So what should be correct approach here? (Also I'd like to do the same for error log, but that seems even more complex, so for now I'm just using another middleware that catches errors and creates log records I need).
type: Question
has title: Custom access log in aiohttp
tagged with: python-asyncio
answer count: 1

http://stackoverflow.com/comment/88515665
comment on: http://stackoverflow.com/a/50752065
type: AnswerComment
has text: you should change the code by your situation.Instead of waiting for someone to change it for you
score: 0
type: Comment

http://stackoverflow.com/comment/91663240
comment on: http://stackoverflow.com/a/50713370
has text: @ahmedabdelqader There's always a way for C#.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/50776350
has comment: http://stackoverflow.com/comment/88583285
score: 2
tagged with: pypdf
has body: I've been extracting text from PDFs using PyPDF2. However it seems to be inputting erroneous white space in between words. Does anyone know of way to avoid this, or clean it after the fact? Here is an example: 'IN THE MATTER OF an application submitted by 1113 York Avenue Realty Company, L.L.C. and 60th Street Devel opment LLC pursuant to Sections 197-c and 201 of the New York City Charter for an amendment of th e Zoning Map, Section Nos. 8c and 8d:' Here "development" is spelt "devel opment" and "the" is the spelt "th e". I'd like to correct this. Here is PDF. The example text is from list item number 1, on the first page.
has comment: http://stackoverflow.com/comment/88580391
type: Question
has title: Cleaning Up (or Avoiding) Extra Whitespace with PyPDF2
tagged with: nltk
has comment: http://stackoverflow.com/comment/88581573
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88583575
tagged with: python
has answer: http://stackoverflow.com/a/75571946
tagged with: nlp

http://stackoverflow.com/comment/88557494
score: 0
type: AnswerComment
type: Comment
has text: I would appreciate if the downvoter can explain what I'm missing. The question was left open for quite a while so I assumed the consensus was that it should be answered. It's possible I made a mistake in my answer.
comment on: http://stackoverflow.com/a/50775271

http://stackoverflow.com/q/50851651
type: UnansweredQuestion
tagged with: web-applications
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88713970
has comment: http://stackoverflow.com/comment/88712907
tagged with: heroku
has comment: http://stackoverflow.com/comment/88710870
has comment: http://stackoverflow.com/comment/88706117
has title: Heroku Application Error when deploying Dash app
has answer: http://stackoverflow.com/a/77407856
type: Question
has answer: http://stackoverflow.com/a/68391452
tagged with: plotly-dash
downvote count: 0
has body: I am attempting to deploy a web app on Heroku with the app made with Dash. I have successfully deployed several example apps on Heroku, and I have successfully deployed my app on my local server. The problem arises when I try to deploy my own app on Heroku. I have tried several different approaches to deploying on Heroku, but I continue getting “Application Error” despite a successful build. I have included my logs, but could use help understanding them. I am still quite new to this so any insight would be appreciated. 2018-06-14T06:16:06.479983+00:00 app[web.1]: self.reap_workers() 2018-06-14T06:16:06.479989+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2018-06-14T06:16:06.480336+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2018-06-14T06:16:06.480369+00:00 app[web.1]: gunicorn.errors.HaltServer: &lt;HaltServer 'Worker failed to boot.' 3&gt; 2018-06-14T06:16:06.571040+00:00 heroku[web.1]: State changed from up to crashed 2018-06-14T06:16:06.555492+00:00 heroku[web.1]: Process exited with status 1 2018-06-14T06:20:34.738228+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=builddlrapp.herokuapp.com request_id=75e9c068-72cb-41e3-8bbd-c6790c722f8e fwd="137.158.71.91" dyno= connect= service= status=503 bytes= protocol=https 2018-06-14T06:20:38.238293+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=builddlrapp.herokuapp.com request_id=c0905560-3e86-4059-918a-3c795824325c fwd="137.158.71.91" dyno= connect= service= status=503 bytes= protocol=https 2018-06-14T06:31:25.832995+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=builddlrapp.herokuapp.com request_id=3d771909-ec4e-4312-9567-6653b443ef6f fwd="137.158.71.91" dyno= connect= service= status=503 bytes= protocol=https 2018-06-14T06:31:26.464840+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GE…
has answer: http://stackoverflow.com/a/71804995
has comment: http://stackoverflow.com/comment/88741279
has answer: http://stackoverflow.com/a/51644995
score: 1
answer count: 4
favorite count: 0

http://stackoverflow.com/comment/88571807
score: 0
has text: Ok I got it. Thank you for the explication !
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50782046

http://stackoverflow.com/comment/88549666
type: Comment
score: 4
has text: Please show your code, instead of just describing it. See [mcve]. (also example input/output if necessary)
comment on: http://stackoverflow.com/q/50771084
type: QuestionComment

http://stackoverflow.com/a/50850805
type: Answer
answers question: http://stackoverflow.com/q/50833107
upvote count: 4
downvote count: 0
has body: It is not necessary to use a QTimer to perform this task and to create a method called update() since QMainWindow has a similar method and could be interfering with the correct operation. The sigMouseMoved signal is emitted every time you move the mouse, so in general it is not necessary to use the SignalProxy. The signal sigMouseMoved returns the coordinates in pixels with respect to the PlotWidget, not in the coordinates of the plot, so a conversion must be done using the mapSceneToView method of the ViewBox--> PlotItem --> PlotWidget. Finally, it is not necessary to use GraphicsWindow(), this creates another window, just a QWidget is enough. import sys from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg import random class TestClass(QtGui.QMainWindow): ##################################################### def __init__(self): super(TestClass, self).__init__() self.initUI() #################################################### # GUI construction def initUI(self): self.setWindowTitle("Mouse Point, x &amp; y") win = QtGui.QWidget() # creates plot self.plot = pg.PlotWidget() self.plot.setLabel('left', "B", units='T') self.plot.setLabel('bottom', "t", units='s') self.plot.showGrid(x=1, y=1, alpha=None) self.setCentralWidget(win) self.setGeometry(600, 600, 600, 600) self.setWindowTitle('Mouse Point, x&amp; y GUI') # Create some widgets to be placed inside btnRandon = QtGui.QPushButton('Random Function') # Create a grid layout to manage the widgets size and position layout = QtGui.QGridLayout(win) # Add widgets to the layout in their proper positions layout.addWidget(btnRandon, 0, 0) # button to show or hide the OldB layout.addWidget(self.plot, 1, 0) mypen = pg.mkPen('y', width=1) self.curve = self.plot.plot(x=[], y=[], pen=mypen) # Plot self.t_plot_max = 30 self.fe = 10e3 self.t = np.arange(-1 * self.t_plot_max, 0, 1.0 / self.fe) self.len_signal = len(self.t) self.signal = np.zeros(self.len_signal, dtype=np.double) btnRandon.clicked.connect(s…
score: 4
has comment: http://stackoverflow.com/comment/88723515

http://stackoverflow.com/q/50765423
favorite count: 0
linked to: http://stackoverflow.com/q/50747453
score: 3
tagged with: python
tagged with: airflow-scheduler
has comment: http://stackoverflow.com/comment/88561163
has comment: http://stackoverflow.com/comment/88559292
answer count: 0
has body: I'm trying to cluster my Airflow setup and I'm using this article to do so. I just configured my airflow.cfg file to use the CeleryExecutor, I pointed my sql_alchemy_conn to my postgresql database that's running on the same master node, I've set the broker_url to use AWS SQS (I didn't set the access_key_id or secret_key since it's running on an EC2-Instance it doesn't need those), and I've set the celery_result_backend to my postgresql server too. I saved my new airflow.cfg changes, I ran airflow initdb, and then I ran airflow scheduler which worked. I went to the UI and turned on one of my testing DAGs and it went into the queued gray status, In order to test my setup more easily I'm just doing everything on one server for now and once I get that server working I'm going to add the other nodes to the cluster. So I went to start an airflow worker using airflow worker and I got an error saying I didn't have pycurl installed. So I install pycurl using, sudo yum install libcurl-devel export PYCURL_SSL_LIBRARY=openssl note: other options include [nss|openssl|ssl|gnutls] sudo pip-3.6 install pycurl sudo yum install -y openssl-devel I then reran the command airflow worker and I'm getting this error, [ec2-user@ip-10-185-150-32 ~]$ airflow worker [2018-06-08 15:36:28,653] {configuration.py:206} WARNING - section/key [celery/celery_ssl_active] not found in config [2018-06-08 15:36:28,653] {default_celery.py:41} WARNING - Celery Executor will run without SSL [2018-06-08 15:36:28,654] {__init__.py:45} INFO - Using executor CeleryExecutor -------------- celery@ip-10-185-150-32 v4.1.1 (latentcall) ---- **** ----- --- * *** * -- Linux-4.9.76-3.78.amzn1.x86_64-x86_64-with-glibc2.3.4 2018-06-08 15:36:28 -- * - **** --- - ** ---------- [config] - ** ---------- .&gt; app: airflow.executors.celery_executor:0x7f1d528c39b0 - ** ---------- .&gt; transport: sqs://localhost// - ** ---------- .&gt; results: postgresql://postgres:**@localhost/datalake_airflow_cluster_v1_master1_database_1 - …
upvote count: 3
type: UnansweredQuestion
tagged with: celery
type: Question
tagged with: airflow
tagged with: amazon-sqs
downvote count: 0
has title: Airflow + Cluster + Celery + SQS - Airflow Worker: 'Hub' object has no attribute '_current_http_client'

http://stackoverflow.com/comment/88568353
score: 1
type: Comment
type: QuestionComment
has text: Your JSON is malformed. I have no idea how to help you. If the file was JSON lines, you could've salvaged something, but this is the absolute worst. Please give a kick to whoever you got this crappy data from.
comment on: http://stackoverflow.com/q/50780606

http://stackoverflow.com/a/53732684
answers question: http://stackoverflow.com/q/50842653
score: 0
type: Answer
has body: If a default approach (switch_to.alert.accept()) desn't work, you may try mobile gestures: driver.execute_script('mobile: alert', {'action': 'accept', 'buttonLabel': &lt;your button label here&gt;});

http://stackoverflow.com/a/50837221
has body: This is a known issue: The problem is that we don't support the datetime64[s] type on pandas objects, even though it's a valid type for NumPy arrays. A possible workaround is converting directly to float, as in the comment on this question: Pandas DataFrame - 'cannot astype a datetimelike from [datetime64[ns]] to [float64]' when using ols/linear regression
accepted answer of: http://stackoverflow.com/q/50835689
answers question: http://stackoverflow.com/q/50835689
type: Answer
upvote count: 1
downvote count: 0
type: AcceptedAnswer
score: 1

http://stackoverflow.com/q/50708359
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88425918
upvote count: 2
accepted answer: http://stackoverflow.com/a/50708703
answer count: 1
downvote count: 1
has body: I have dates list with missing dates like ['2018-06-01', '2018-06-02', '2018-06-03', '2018-06-06'] And corresponding values list like [3,5,3,7] How can I add missing dates in sorted list and add 0 for corresponding index in values Above values I parsed from below data data = defaultdict(Counter) defaultdict(&lt;class 'collections.Counter'&gt;, {'2018-06-01': Counter({u'Values': 1}), '2018-06-03': Counter({u'Values': 2})} If I can add missing dates in defaultdict that will work as well. It's not duplicate I don't just want to create dates I have to updates corresponding values list.
has comment: http://stackoverflow.com/comment/88425844
has title: python add missing dates and update corresponding list
tagged with: python-2.7
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/993358
score: 1
has answer: http://stackoverflow.com/a/50708703
favorite count: 0
tagged with: defaultdict
has comment: http://stackoverflow.com/comment/88425961

http://stackoverflow.com/comment/88636532
type: Comment
has text: It does the job @T. Ray. +1 for this. However, I'm still sanguine to have any pure selenium solution.
comment on: http://stackoverflow.com/a/50807252
type: AnswerComment
score: 0

http://stackoverflow.com/q/50730489
tagged with: oop
has comment: http://stackoverflow.com/comment/88468639
has comment: http://stackoverflow.com/comment/88472286
type: Question
downvote count: 0
has body: I'd like to have a class decorator that adds properties to a class based on a class attribute _arg_names, as in this minimal example: def add_properties(cls): for name in cls._arg_names: setattr(cls, name, property(lambda self: getattr(self, '_' + name))) return cls @add_properties # .a-&gt;._a, .b-&gt;._b class A(): _arg_names = ('a', 'b') def __init__(self): self._a = 1 self._b = 2 However, when I run this, I find that all properties point to the last argument name: &gt;&gt;&gt; x = A() &gt;&gt;&gt; x.a 2 &gt;&gt;&gt; x.b 2 Any ideas why the closure inside property isn't working as expected? Are there any other solutions for this problem? I need the properties to be read-only, and they should show up in the class documentation.
has comment: http://stackoverflow.com/comment/88468638
has comment: http://stackoverflow.com/comment/88474853
has comment: http://stackoverflow.com/comment/88511074
has comment: http://stackoverflow.com/comment/88511086
has comment: http://stackoverflow.com/comment/88474907
has comment: http://stackoverflow.com/comment/88472980
score: 1
tagged with: python-decorators
favorite count: 0
linked to: http://stackoverflow.com/q/3431676
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88472315
has title: Setting properties dynamically in class decorator
upvote count: 1
has comment: http://stackoverflow.com/comment/88468707
tagged with: python
duplicate of: http://stackoverflow.com/q/3431676
tagged with: properties
has comment: http://stackoverflow.com/comment/88468716

http://stackoverflow.com/comment/88424223
type: AnswerComment
has text: in that case, you have to use `re.MULTILINE` as an option or work line by line.
type: Comment
comment on: http://stackoverflow.com/a/50707466
score: 0

http://stackoverflow.com/comment/88607485
type: Comment
has text: Could you show `print repr(value)` when value comes from the database? Because the backslashes (`\ `) are ignored in your code...
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50800333

http://stackoverflow.com/a/50809944
score: 0
has body: This should help. even_list = [] odd_list = [] with open(filename) as infile: for index, line in enumerate(infile): if index % 2 != 0: even_list.append(line.strip()) #even_list.append(int(line.strip())) else: odd_list.append(line.strip()) print( even_list ) print( odd_list ) Output: ['1', '2', '3', '4'] ['aaa', 'bbb', 'ccc', 'ddd']
type: Answer
accepted answer of: http://stackoverflow.com/q/50809838
answers question: http://stackoverflow.com/q/50809838
type: AcceptedAnswer

matplotlib
tags question: http://stackoverflow.com/q/50742036
tags question: http://stackoverflow.com/q/50820010
tags question: http://stackoverflow.com/q/50821406
tags question: http://stackoverflow.com/q/50701005
tags question: http://stackoverflow.com/q/50731146
tags question: http://stackoverflow.com/q/50727450
tags question: http://stackoverflow.com/q/50788421
tags question: http://stackoverflow.com/q/50761807
tags question: http://stackoverflow.com/q/50757879
tags question: http://stackoverflow.com/q/50731785
tags question: http://stackoverflow.com/q/50850325
tags question: http://stackoverflow.com/q/50711382
tags question: http://stackoverflow.com/q/50845835
tags question: http://stackoverflow.com/q/50826068
tags question: http://stackoverflow.com/q/50814953
tags question: http://stackoverflow.com/q/50722972
tags question: http://stackoverflow.com/q/50744314
tags question: http://stackoverflow.com/q/50783978
tags question: http://stackoverflow.com/q/50825707
tags question: http://stackoverflow.com/q/50844830
tags question: http://stackoverflow.com/q/50704472
tags question: http://stackoverflow.com/q/50702150
tags question: http://stackoverflow.com/q/50802475
tags question: http://stackoverflow.com/q/50848127
tags question: http://stackoverflow.com/q/50730831
tags question: http://stackoverflow.com/q/50821171
tags question: http://stackoverflow.com/q/50853632
tags question: http://stackoverflow.com/q/50746271
tag name: matplotlib
tags question: http://stackoverflow.com/q/50846666
tags question: http://stackoverflow.com/q/50842160
tags question: http://stackoverflow.com/q/50772954
tags question: http://stackoverflow.com/q/50766073
tags question: http://stackoverflow.com/q/50742269
tags question: http://stackoverflow.com/q/50750146
tags question: http://stackoverflow.com/q/50846441
tags question: http://stackoverflow.com/q/50704593
tags question: http://stackoverflow.com/q/50725416
tags question: http://stackoverflow.com/q/50847566
tags question: http://stackoverflow.com/q/50704932
tags question: http://stackoverflow.com/q/50846694
tags question: http://stackoverflow.com/q/50769456
tags question: http://stackoverflow.com/q/50777982
tags question: http://stackoverflow.com/q/50832204
tags question: http://stackoverflow.com/q/50756776
tags question: http://stackoverflow.com/q/50773148
tags question: http://stackoverflow.com/q/50710858
tags question: http://stackoverflow.com/q/50816945
tags question: http://stackoverflow.com/q/50845646
tags question: http://stackoverflow.com/q/50794631
tags question: http://stackoverflow.com/q/50787698
tags question: http://stackoverflow.com/q/50717073
tags question: http://stackoverflow.com/q/50732789
tags question: http://stackoverflow.com/q/50835720
tags question: http://stackoverflow.com/q/50842419
tags question: http://stackoverflow.com/q/50706901
tags question: http://stackoverflow.com/q/50766326
tags question: http://stackoverflow.com/q/50778410
tags question: http://stackoverflow.com/q/50700325
tags question: http://stackoverflow.com/q/50751520
tags question: http://stackoverflow.com/q/50700763
tags question: http://stackoverflow.com/q/50748833
tags question: http://stackoverflow.com/q/50835690
tags question: http://stackoverflow.com/q/50779508
tags question: http://stackoverflow.com/q/50846621
tags question: http://stackoverflow.com/q/50711904
tags question: http://stackoverflow.com/q/50848895
tags question: http://stackoverflow.com/q/50721310
tags question: http://stackoverflow.com/q/50711725
tags question: http://stackoverflow.com/q/50840879
tags question: http://stackoverflow.com/q/50830680
tags question: http://stackoverflow.com/q/50768430
tags question: http://stackoverflow.com/q/50841200
tags question: http://stackoverflow.com/q/50760792
tags question: http://stackoverflow.com/q/50812810
tags question: http://stackoverflow.com/q/50730911
tags question: http://stackoverflow.com/q/50849549
tags question: http://stackoverflow.com/q/50799903
tags question: http://stackoverflow.com/q/50818539
tags question: http://stackoverflow.com/q/50789490

http://stackoverflow.com/comment/88463866
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50726804
has text: I think I understood your logic and it is indeed interesting. First issue: `a = (float(random.random())+1)**0.5` doesn't generate uniform numbers. It has a bias towards larger numbers. But even if you use `random.uniform(1, 2**0.5)` the issue doesn't resolve. As I understand you select a point on the edges of the square and then select another random number that's on the line that connects the center and the point you've previously chosen. The issue is here the conditional probability. That may be causing problems with uniformity again.
type: Comment

http://stackoverflow.com/q/50735066
answer count: 0
downvote count: 0
has title: Using python for decoding url content
type: Question
score: 5
has comment: http://stackoverflow.com/comment/137834172
has comment: http://stackoverflow.com/comment/137834079
favorite count: 0
upvote count: 5
has body: There is a site which contains bible translations in Greek and Hebrew in Russian. Here is python2 code for getting url content: # -*- coding: utf-8 -*- import io, urllib f1 = io.open('url.txt','w',encoding='utf8') #link = "http://manuscript-bible.ru/OT/Gen1.htm" link = "http://manuscript-bible.ru/S/H/psa117.htm" f2 = urllib.urlopen(link) myfile = f2.read().decode("utf-8") f1.write(myfile) f1.close() Thus,for Hebrew and Russian using f2.read().decode("utf-8") it is possible to get the url from http://manuscript-bible.ru/S/H/psa117.htm e.g.: >1 הַֽלְלוּ אֶת for Russian as well it is possible to get the content using myfile = f2.read().decode('cp1251') from http://manuscript-bible.ru/RSV/22_116.htm here one sentence of the content .htm 1 Хвалите <01984> Господа <03068>, все народы <01471>, прославляйте <07623> Его, все племена <0523>; The problem is with this url http://manuscript-bible.ru/OT/Ps116.htm which is not possible to decode: by inspection from the source of .htm it seems that there is two Gen1.htm with the same extension .htm and one of them contain something like: anot=0;bn=22;cn=116;variants="";cr=new Array();parsing="";a=new Array("","","","","","",""," ","","",""," ","","",""," ","CALMOI","calmoi","6163","ПСАЛМЫ","Глава 116","","","","","",""," ","","",""," ","","","","","1","","","","Allhlouia.","allhlouia","6C61","Аллилуйя.","AЮneЭte","aЮneЭte","6961","Хвали&#769те","tтn","tсn","6F74","-","kжrion,","kжrion","756B","Го&#769спода," it seems that is utf-16 coding because when inserted in https://www.branah.com/unicode-converter we get: anot=0;bn=22;cn=116;variants="";cr=new Array();parsing="";a=new Array("","","","","","",""," ","","",""," ","","",""," ","CALMOI","calmoi","6163","ПСАЛМЫ","Глава 116","","","","","",""," ","","",""," ","","","","","1","","","","Allhlouia.","allhlouia","6C61","Аллилуйя.","AЮneЭte","aЮneЭte","6961","Хвали&#769те","tтn","tсn","6F74","-","kжrion,","kжrion","756B","Го&#769спода," The question is, how to get the decoded content of…
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50828588
has comment: http://stackoverflow.com/comment/88661674
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/588004
has body: Run these two commands in Python: print(int(822981260158260520/2)) print(int(822981260158260520//2)) The second one prints a correct answer but the first one does not. The difference is as big as 20. How did this happen? Is it a Python bug?
type: Question
has title: Why / has a wrong answer but // has a correct answer in python?
has comment: http://stackoverflow.com/comment/88662333
linked to: http://stackoverflow.com/q/588004
score: 0

http://stackoverflow.com/comment/88422933
has text: @Ruthless: The inner set of parenthesis indicates a [tuple](https://www.programiz.com/python-programming/tuple), which in this case represents an interval.
comment on: http://stackoverflow.com/a/50706754
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50733027
tagged with: python
has body: I have several long lists that I would like to parse and grab the data of interest. Specifically I am looking for data between 2 patterns in one list and grab the data across all the lists using the same index. I have the following dictionary with a lot of data in each list (showing only a few in this example): LA = { 'A':['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'], 'B':[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 'C':[ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32], 'D':[ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42], 'E':[..........................................................], 'F':[..........................................................] } for j in itertools.zip_longest(LA['A'], LA['B'], LA['C'], LA['D']): if (j[0] =='d'): grab_data = 1 else: if not (j[0] == 'j'): grab_data = 1 else: if (grab_data ==1): print ("My required Data", j) This will print the following: My required Data ('e', 4, 25, 35) My required Data ('f', 5, 26, 36) My required Data ('g', 6, 27, 37) My required Data ('h', 7, 28, 38) My required Data ('i', 8, 29, 39) This is right but is there a more efficient and concise way to do this?. The lists are long and there is lot of data.
downvote count: 1
score: 1
has title: How to iterate efficiently using itertools.zip_longest to grab data between 2 markers
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50733882
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/88614586
has answer: http://stackoverflow.com/a/50804870
favorite count: 0
upvote count: 2
type: UnansweredQuestion

filter
tags question: http://stackoverflow.com/q/50705083
tags question: http://stackoverflow.com/q/50710203
tags question: http://stackoverflow.com/q/50755079
tags question: http://stackoverflow.com/q/50772799
tag name: filter
tags question: http://stackoverflow.com/q/50832667
tags question: http://stackoverflow.com/q/50853179
tags question: http://stackoverflow.com/q/50819051
type: Tag
tags question: http://stackoverflow.com/q/50833129
tags question: http://stackoverflow.com/q/50754730
tags question: http://stackoverflow.com/q/50812323
tags question: http://stackoverflow.com/q/50759213

http://stackoverflow.com/q/50818851
score: 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71806595
tagged with: matplotlib
tagged with: treemap
has title: Python + Matplotlib: multi-level treemap plot?
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/95276734
has body: I recently saw this treemap chart from https://www.kaggle.com/philippsp/exploratory-analysis-instacart (two levels of hierarchy, colored, squarified treemap). It is made with R ggplot2::treemap, by: treemap(tmp,index=c("department","aisle"),vSize="n",title="", palette="Set3",border.col="#FFFFFF") I want to know how can I make this plot in Python? I searched a bit, but didn't find any multi-level treemap example. https://gist.github.com/gVallverdu/0b446d0061a785c808dbe79262a37eea https://python-graph-gallery.com/200-basic-treemap-with-python/
upvote count: 8
tagged with: visualization
tagged with: python
has answer: http://stackoverflow.com/a/62479982

http://stackoverflow.com/q/50751828
has body: This code is meant to scrape data variables from a website and plot the values down. I am trying to use this so that I can graph the prices of graphics cards over time. I am using beautifulsoup and everything is working, except I can't get the price to properly print. from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = "https://www.newegg.ca/Product/ProductList.aspx?Submit=ENE&amp;N=100007708%20601210955%20601203901%20601294835%20601295933%20601194948&amp;IsNodeId=1&amp;bop=And&amp;Order=BESTSELLING&amp;PageSize=96" uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") containers = page_soup.findAll("div",{"class":"item-container"}) filename = "GPU Prices.csv" f = open(filename, "w") header = "Price,Product Brand,Product Name,Shipping Cost\n" f.write(header) for container in containers: price_container = container.findAll("li", {"class":"price-current"}) price = price_container[0].text.strip() brand = container.div.div.a.img["title"] title_container = container.findAll("a", {"class":"item-title"}) product_name = title_container[0].text shipping_container = container.findAll("li", {"class":"price-ship"}) shipping = shipping_container[0].text.strip() price f.write(price.replace(",", "") + "," + brand.replace(",", ".") + "," + product_name.replace(",", " |") + "," + shipping + "\n") f.close() After running this, the csv file looks like this:
score: 1
tagged with: web-scraping
type: Question
has title: Trouble Grabbing HTML variable using python scraping
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88520145
has comment: http://stackoverflow.com/comment/88514346
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50756654

http://stackoverflow.com/a/50746298
score: 3
has body: They are added as instance attributes. The instance, though, is the class, as an instance of the metaclass. You aren't defining a __init__ method for E; you are defining the method that type uses to initialize E itself. If you just want attributes added to the instance of E, you're working at the wrong level; you should define a mixin and use multiple inheritance for that.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50746194
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/50746194

http://stackoverflow.com/a/50721405
accepted answer of: http://stackoverflow.com/q/50721324
downvote count: 0
answers question: http://stackoverflow.com/q/50721324
has body: Use str.len() only: a.str.len() And for columns of DataFrame: df['col'].str.len() But if no NaNs values apply(len) working more efficient: a.apply(len) df['col'].apply(len) List comprehension solutions: pd.Series([len(x) for x in a], index=a.index) pd.Series([len(x) for x in df['col']], index=df.index)
score: 5
type: AcceptedAnswer
upvote count: 5
has comment: http://stackoverflow.com/comment/117195570
type: Answer

http://stackoverflow.com/q/50789288
tagged with: inheritance
has comment: http://stackoverflow.com/comment/88584852
linked to: http://stackoverflow.com/q/50658942
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88584839
has body: I read all kinds of super usage for inheritance in Python. But I also get the following code work in Python 2.7.5 class A: def f3(self): print('a f3') class B(A): def f1(self): self.f3() b = B() b.f1() # 'a f3' Is this actually correct in production? Can we use self instead of super(...)? Thanks!
has comment: http://stackoverflow.com/comment/88584836
type: UnansweredQuestion
tagged with: python
has title: When can I call base class method using self in Python
duplicate of: http://stackoverflow.com/q/50658942
answer count: 0
has comment: http://stackoverflow.com/comment/88584842
has comment: http://stackoverflow.com/comment/88585069
type: Question
has comment: http://stackoverflow.com/comment/88585418
has comment: http://stackoverflow.com/comment/88584979

http://stackoverflow.com/q/50742621
has comment: http://stackoverflow.com/comment/88493501
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88496548
upvote count: 2
has comment: http://stackoverflow.com/comment/88493075
downvote count: 2
accepted answer: http://stackoverflow.com/a/50830758
has comment: http://stackoverflow.com/comment/88493360
answer count: 1
has title: Transfer a JSON string between programs without saving a file
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/88496497
has answer: http://stackoverflow.com/a/50830758
tagged with: python
has comment: http://stackoverflow.com/comment/88493136
has comment: http://stackoverflow.com/comment/88493564
tagged with: transfer
has body: Let's assume I have two Python modules, first.py and second.py. first.py generates a JSON string; second.py takes a JSON string and does subsequent processes. To simplify them, consider the example written below: # first.py import json fruit = input("Name a fruit: ") material_str = json.dumps({"fruit": fruit}) print(material_str) # second.py import json material = json.loads(material_str) def blender(material): serving = material["fruit"] + " juice" return serving print(blender(material)) Now my problem is: how to transfer material_str from first.py to second.py? Is there a way to make material_str somehow cached in the memory and then taken by second.py (or even more general, by programs in other languages which can load JSON strings)? Because it seems unlikely that the printed string can be transferred like this. I know I can json.dump the dictionary into a file in first.py, and json.load it in second.py. However, these codes will be executed thousands of times a day and the JSON strings are useful only during the execution, so I don't want to save them. Combining first.py and second.py is not feasible either because in fact they are two big projects developed by different people. In fact, consider first.py as a script doing OCR and second.py as a script of one iOS app. Now the results of OCR need to be transferred to the app script so that they can be presented. I have read some documentation about sys.stdout but it looks like no luck. Any help is appreciated.
has comment: http://stackoverflow.com/comment/88493728
has comment: http://stackoverflow.com/comment/88493322
has comment: http://stackoverflow.com/comment/88493158
has comment: http://stackoverflow.com/comment/88492894
has comment: http://stackoverflow.com/comment/88493856
type: Question

http://stackoverflow.com/comment/88573129
type: Comment
has text: I Got a little Problem there cause my readlines() retrieves a list, and i cant split lists.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50783300

http://stackoverflow.com/a/50733423
has comment: http://stackoverflow.com/comment/88474581
has body: You can understand it simply, As every image in MNIST data is 28x28px, so when we convert our image into 1D matrix, its size becomes 28x28=784. MNIST image size is 28 × 28 pixel, so it is represented as 784 1-d array. each value in the matrix represents the value between 0 to 255.
answers question: http://stackoverflow.com/q/50733342
has comment: http://stackoverflow.com/comment/88474622
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50733342
downvote count: 0

http://stackoverflow.com/q/50755803
tagged with: elementtree
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
answer count: 0
downvote count: 0
score: 1
type: Question
has title: Extract an XML file (TED Europe) to a pandas dataframe
tagged with: xml-parsing
tagged with: pandas
upvote count: 1
has body: I have an XML from TED Europe (like this:TED Europa XML Files (Login required)) Within the XML Files are public procurement contracts. My question is now how can I parse the XML File to a pandas dataframe. So far I tried to achieve this using the ElementTree package. However since I am still a beginner habe trouble extracting the information since the relevant text is marked with only "p" tags. How can I extract this information for the english translation so that for example "TI_MARK" is the column header and the information within "TXT_MARK" and the "p" tags are the rows? The other rows are later filled with information from other public procurement XML Files. <FORM_SECTION> <OTH_NOT LG="DA" VERSION="R2.0.8.S03.E01" CATEGORY="TRANSLATION"> <OTH_NOT LG="DE" VERSION="R2.0.8.S03.E01" CATEGORY="TRANSLATION"> <OTH_NOT LG="EN" VERSION="R2.0.8.S03.E01" CATEGORY="ORIGINAL"> <FD_OTH_NOT> <TI_DOC> BE-Brussels: IPA - Improved implementation of animal health, food safety and phytosanitary legislation and corresponding information systems </TI_DOC> <STI_DOC> Location — The former Yugoslav Republic of Macedonia </STI_DOC> <STI_DOC> SERVICE CONTRACT NOTICE </STI_DOC> <CONTENTS> <GR_SEQ> <TI_GRSEQ> <BLK_BTX/> </TI_GRSEQ> <BLK_BTX_SEQ> <MARK_LIST> <MLI_OCCUR NO_SEQ="001"> <NO_MARK>1.</NO_MARK> <TI_MARK>Publication reference</TI_MARK> <TXT_MARK> EuropeAid/139253/DH/SER/MK </TXT_MARK> </MLI_OCCUR> <MLI_OCCUR NO_SEQ="002"> <NO_MARK>2.</NO_MARK> <TI_MARK>Procedure</TI_MARK> <TXT_MARK> Restricted </TXT_MARK> </MLI_OCCUR> So far my code is: import xml.etree.cElementTree as ET tree = ET.parse('196658_2018.xml') #Print Tree print(tree) #tree=ET.ElementTree(file='196658_2018.xml') root = tree.getroot() #Print root print(root) for element in root.findall('{ted/R2.0.8.S03/publication}FORM_SECTION/{ted/R2.0.8.S03/publication}OTH_NOT/{ted/R2.0.8.S03/publication}FD_OTH_NOT/{ted/R2.0.8.S03/publication}TI_DOC/{ted/R2.0.8.S03/publication}P'): print(element.text) Strangely the extraction only works…

http://stackoverflow.com/comment/88721767
type: QuestionComment
comment on: http://stackoverflow.com/q/50852700
score: 0
has text: @ncfirth i'll be checking that out, thank you!
type: Comment

http://stackoverflow.com/comment/88519352
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50755795
has text: While this will work, why would you bring in numpy for something that isn't going to benefit from it? And why loop over `i in range(len(mylist))` when you're only going to use `mylist[i]` instead of just looping over `mylist`?
type: AnswerComment

http://stackoverflow.com/a/51878585
score: 2
downvote count: 0
has body: Since you provided the actual vectors, you presumably know how to map ids to vectors. Most Faiss indexes in do not store the vectors, because they need to be compressed to fit in RAM.
upvote count: 2
answers question: http://stackoverflow.com/q/50798515
has comment: http://stackoverflow.com/comment/90780137
has comment: http://stackoverflow.com/comment/92766758
type: Answer

http://stackoverflow.com/q/50841542
score: 1
has title: How to read data nicely using np.fromregex?
has answer: http://stackoverflow.com/a/50841652
has comment: http://stackoverflow.com/comment/88689534
has comment: http://stackoverflow.com/comment/88689338
has comment: http://stackoverflow.com/comment/88689113
type: Question
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/88689273
has answer: http://stackoverflow.com/a/50843222
accepted answer: http://stackoverflow.com/a/50841652
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/88687557
has comment: http://stackoverflow.com/comment/88689217
possible better answer: http://stackoverflow.com/a/50842192
has body: I am little bit familiar with np.fromregex. I read the tutorials and tried to implement it to read a data file. When the file is read using simple python list comprehension, it gives the desired result: [400, 401, 405, 408, 412, 414, 420, 423, 433]. But, when np.fromregex is is gives another format answer: [(400,) (401,) (405,) (408,) (412,) (414,) (420,) (423,) (433,)]. How can the code be changed so that the answer from regex becomes same as the simple python for loop. Thanks. P.S. I know this is a simple question but it took me a lot of time to look for the solution and it might be benificial to others too and save some time. Related links: https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromregex.html np.fromregex with string as dtype from __future__ import print_function, division, with_statement, unicode_literals import numpy as np import re data = """ DMStack failed for: lsst_z1.0_400.fits DMStack failed for: lsst_z1.0_401.fits DMStack failed for: lsst_z1.0_405.fits DMStack failed for: lsst_z1.0_408.fits DMStack failed for: lsst_z1.0_412.fits DMStack failed for: lsst_z1.0_414.fits DMStack failed for: lsst_z1.0_420.fits DMStack failed for: lsst_z1.0_423.fits DMStack failed for: lsst_z1.0_433.fits """ ifile = 'a.txt' with open(ifile, 'w') as fo: fo.write(data.lstrip()) # regex regexp = r".*_(\d+?).fits" # This works fine ans = [int(re.findall(regexp, line)[0]) for line in open(ifile)] print(ans) # using fromregex dt = [('num', np.int32)] x = np.fromregex(ifile, regexp, dt) print(x) Update The above code failed when I used the future imports. The error log is given below: Traceback (most recent call last): File "a.py", line 31, in &lt;module&gt; x = np.fromregex(ifile, regexp, dt) File "/Users/poudel/miniconda2/lib/python2.7/site-packages/numpy/lib/npyio.py", line 1452, in fromregex dtype = np.dtype(dtype) TypeError: data type not understood $ which python python is /Users/poudel/miniconda2/bin/python $ python -c "import numpy; print(numpy.__version__…
has answer: http://stackoverflow.com/a/50842192
upvote count: 1
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33014828

http://stackoverflow.com/comment/88601937
type: AnswerComment
has text: @Ravikumar - OK, if use `df = df.reset_index(drop=True)` as first step, how it working?
comment on: http://stackoverflow.com/a/50797818
type: Comment
score: 0

http://stackoverflow.com/comment/88573826
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50783587
type: Comment
has text: jezrael - thanks a lot for showing the two ways of doing this. This was exactly what I needed.

http://stackoverflow.com/a/50799421
accepted answer of: http://stackoverflow.com/q/50799076
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50799076
has body: In order to decode it, add the third line which decodes the string to base64 json_data = request.get_json(force=True) img = json_data['img'] imgdata = base64.b64decode(img) filename = 'upload/newimg.jpg' # I assume you have a way of picking unique filenames with open(filename, 'wb') as f: f.write(imgdata)
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88607192

http://stackoverflow.com/comment/88647771
comment on: http://stackoverflow.com/q/50821275
has text: You posted too much code. Please produce an [MCVE](https://stackoverflow.com/help/mcve).
type: Comment
type: QuestionComment
score: 7

http://stackoverflow.com/a/50778544
score: 1
has comment: http://stackoverflow.com/comment/88564472
downvote count: 0
has body: You can use csv.writer: import csv, re from bs4 import BeautifulSoup as soup import requests flag = False with open('filename.csv', 'w') as f: write = csv.writer(f) for i in range(1, 30871): s = soup(requests.get(f'https://howlongtobeat.com/game.php?id={i}').text, 'html.parser') if not flag: #write header to file once write.writerow(['Name', 'Length']+[re.sub('[:\n]+', '', i.find('strong').text) for i in s.find_all('div', {'class':'profile_info'})]) flag = True name = s.find('div', {"class":'profile_header shadow_text'}).text length = [[i.find('h5').text, i.find("div").text] for i in s.find_all('li', {'class':'time_100'})] stats = [re.sub('\n+[\w\s]+:\n+', '', i.text) for i in s.find_all('div', {'class':'profile_info'})] write.writerows([[name, length[0][-1]]+stats[:4]])
has comment: http://stackoverflow.com/comment/88565554
type: Answer
answers question: http://stackoverflow.com/q/50778481
upvote count: 1
has comment: http://stackoverflow.com/comment/88564334
has comment: http://stackoverflow.com/comment/88564164

http://stackoverflow.com/comment/88646155
score: 0
type: AnswerComment
has text: I wish I could buy you lunch. It works! Thank you. I also needed to change my parameters to use client.DefaultRequestHeaders.Add("environment", "dev"); client.DefaultRequestHeaders.Add("path", "Business/Tools");
type: Comment
comment on: http://stackoverflow.com/a/50818727

http://stackoverflow.com/q/50732206
tagged with: python
downvote count: 1
has title: How to call a function in a thread in Python?
score: -1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50732241
has body: Consider this is a class that I have: import threading class SomeClass(threading.Thread): def __init__(self): threading.Thread.__init__(self) def func1(arg): # The body of code. def run(self): while True: func1(arg) I want to call a function in a class in run() method. How can I do it?
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/a/56368864
has comment: http://stackoverflow.com/comment/105404321
has body: len(list(dataset)) works in eager mode, although that's obviously not a good general solution.
has comment: http://stackoverflow.com/comment/105384494
has comment: http://stackoverflow.com/comment/105412209
has comment: http://stackoverflow.com/comment/105432517
score: 51
upvote count: 52
type: Answer
answers question: http://stackoverflow.com/q/50737192
downvote count: 1

http://stackoverflow.com/comment/88600090
type: AnswerComment
type: Comment
score: 0
has text: @PrashantSanap Perhaps to upload image you have to explore the other options e.g. _AutoIT_ or _RIDE_ framework
comment on: http://stackoverflow.com/a/50796465

http://stackoverflow.com/comment/88712894
score: 0
type: AnswerComment
type: Comment
has text: @StephenFong The protocol nicely quoted in Yann Vernier's subsequent comment :-)
comment on: http://stackoverflow.com/a/50854266

http://stackoverflow.com/a/50788056
upvote count: 2
has comment: http://stackoverflow.com/comment/88582963
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88582953
type: Answer
has body: As discussed in the comments, a potential problem could be white spaces that are not visible when you print your data. You can remove them using .str.strip(): df['Status'] = df['Status'].str.strip() Then filtered_df = main_df.query('Status == "Active"') should yield the desired output.
score: 2
accepted answer of: http://stackoverflow.com/q/50787757
downvote count: 0
has comment: http://stackoverflow.com/comment/88582869
has comment: http://stackoverflow.com/comment/88582799
answers question: http://stackoverflow.com/q/50787757

http://stackoverflow.com/comment/102158384
comment on: http://stackoverflow.com/q/50716249
has text: @VladSirbu I had the problem but I fixed it by re-calibrating it.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88703934
has text: Tried your sample code too. It's throwing the same exception on 2nd iteration.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50843371
score: 0

http://stackoverflow.com/q/50743473
has title: Check whether an item appears previously in a list of items using Python Pandas
has answer: http://stackoverflow.com/a/50745582
upvote count: 2
downvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88496183
accepted answer: http://stackoverflow.com/a/50745582
answer count: 1
has body: I have the following table which has IDs and for each ID i have Basket 1, Basket 2 and finally the products in the baskets. I want to find on the sorted table (sort on ID from A-Z, Basket 1 ASC and Basket 2 ASC) whether each product for every ID appears previously (for the same ID) and put Y or N in a new column (column E). Example is below for the first ID: 111AAA222 = [Product1, Product2, Product3, Product1, Product2, Product3, Product1, Product4] 111AAA222 = [N, N, N, Y, Y, Y, Y, N] The example shows that the Products from the 3rd till the 6th position in the list appeared previously in the same list. Im having difficulties to create the new column (Column E: Existed) with the values Y and N using python pandas.
favorite count: 0
tagged with: pandas
tagged with: python
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/50731499
has answer: http://stackoverflow.com/a/50731601
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88470925
tagged with: linux
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50731599
has comment: http://stackoverflow.com/comment/88470935
score: 0
has title: Python Linux: Grab all lines that can be spelled forward and backwards in a text file
has body: I need to grab all the palindrome lines (spelled same forwards and backwards) in a text file from the linux command line. I do not think you can use just one command to do this since you have to check for any length of line. So I do not know of a way to do this other than making a script (correct me if I'm wrong). So what I did is grab all of the lengths of lines and did a grep command that would check for lines that are that long: import os ex_front = "egrep -i '^" ex_middle_front = "" ex_middle_back = "" ex_back = "$' textfile.txt" textFile = open("textfile.txt", "r") stringList = textFile.readlines() lengthList = set([]) for line in stringList: lengthList.add(len(line)) for x in lengthList: ex_middle_front = "" ex_middle_back = "" for i in range(int(x/2), 0, -1): ex_middle_front += "(.)" ex_middle_back += "\\" + str(i) if x % 2 == 0: ex_middle = "" else: ex_middle = "." os.system(ex_front + ex_middle_front + ex_middle + ex_middle_back + ex_back) This works, but I am wondering if there is a better solution.
linked to: http://stackoverflow.com/q/5202533
has answer: http://stackoverflow.com/a/50731599
possible better answer: http://stackoverflow.com/a/50731601

http://stackoverflow.com/a/50777414
type: Answer
answers question: http://stackoverflow.com/q/50772959
has body: After several reloads, code started working as intended. So for anybody looking to change things, change them inside OPTIONS of code.
score: 0

http://stackoverflow.com/comment/88578928
score: 0
type: QuestionComment
type: Comment
has text: apologies for being inexpressive. Lets assume input a ranges from (0.000 to 1.000) similarly b,c,d have there respective input range. Now how would I know if my code runs for all possible combinations.
comment on: http://stackoverflow.com/q/50774928

http://stackoverflow.com/comment/88457624
type: QuestionComment
comment on: http://stackoverflow.com/q/50724300
score: 0
has text: welcome, sorry I just started using this site so I still make mistakes.
type: Comment

http://stackoverflow.com/a/50775020
answers question: http://stackoverflow.com/q/50774939
type: Answer
downvote count: 1
upvote count: 0
has body: Maybe the best option is use numpy [1] np.random.randint(5, size=(2, 4)) [1]https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html
score: -1
has comment: http://stackoverflow.com/comment/88556985

http://stackoverflow.com/comment/88430858
comment on: http://stackoverflow.com/a/50710893
score: 0
type: AnswerComment
type: Comment
has text: OK Thaks. I am trying to get your point but confusion is why the result of these two is same: number = range(1,7) for i in number: print(i) for i in range(1,7): print(i)

http://stackoverflow.com/comment/88462404
type: Comment
type: AnswerComment
has text: thanks but i'm getting SyntaxError on _, *c SyntaxError: invalid syntax
comment on: http://stackoverflow.com/a/50727065
score: 0

http://stackoverflow.com/a/50819970
downvote count: 0
answers question: http://stackoverflow.com/q/50811061
has comment: http://stackoverflow.com/comment/88653759
has comment: http://stackoverflow.com/comment/88653607
upvote count: 2
has comment: http://stackoverflow.com/comment/88659343
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88659339
has body: I would just rank distributions by the goodness-of-fit statistic and not by p-values. We can use the Anderson-Darling, Kolmogorov-Smirnov or similar statistic just as distance measure to rank how well different distributions fit. background: p-values for Anderson-Darling or Kolmogorov-Smirnov depend on whether the parameters are estimated or not. In both cases the distribution is not a standard distribution. In some cases we can tabulate or use a functional approximation to tabulated values. This is the case when parameters are not estimated and if the distribution is a simple location-scale family without shape parameters. For distributions that have a shape parameter, the distribution of the test statistic that we need for computing the p-values depends on the parameters. That is we would have to compute different distributions or tabulated p-values for each set of parameters, which is impossible. The only solution to get p-values in those cases is either by bootstrap or by simulating the test statistic for the specific parameters. The technical condition is whether the test statistic is asymptotically pivotal which means that the asymptotic distribution of the test statistic is independent of the specific parameters. Using chisquare test on binned data requires fewer assumption, and we can compute it even when parameters are estimated. (Strictly speaking this is only true if the parameters are estimated by MLE using the binned data.)

http://stackoverflow.com/q/50752259
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has body: I want use Tensorflow on Android by using pb file trained on python with GPU. Official example of Tensorflow-demo on Android use pre-trained 'tensorflow_inception_graph.pb'. Like above, I want use mine '*.pb' on Android. First, I have trained simple Tensorflow code which similar to mnist-example on python like below. python code def deepnn(x): with tf.name_scope('reshape'): x_image = tf.reshape(x, [-1, 30, 6, 1]) with tf.name_scope('conv1'): W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) with tf.name_scope('conv2'): W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2) + b_conv2) with tf.name_scope('pool2'): h_pool2 = max_pool_2x2(h_conv2) with tf.name_scope('fc1'): W_fc1 = weight_variable([15 * 3 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 15 * 3 * 64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) with tf.name_scope('dropout'): keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) with tf.name_scope('fc2'): W_fc2 = weight_variable([1024, 28]) b_fc2 = bias_variable([28]) y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 return y_conv, keep_prob def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) x = tf.placeholder(tf.float32, [None, 180], name='input') y_ = tf.placeholder(tf.int64, [None]) y_conv, keep_prob = deepnn(x) y_conv = tf.identity(y_conv, 'output') with tf.name_scope('loss'): cross_entropy = tf.losses.sparse_softmax_cross_entropy( labels=y_, logits=y_conv ) cross_entropy = tf.reduce_mean(cross_entropy, name='lo…
tagged with: android
tagged with: python
has title: No Opkernel was registered to support Op 'SparseSoftmaxCrossEntropyWithLogits'
upvote count: 1
has answer: http://stackoverflow.com/a/66595195
tagged with: tensorflow
type: Question
score: 1

python-3.x
tags question: http://stackoverflow.com/q/50783666
tags question: http://stackoverflow.com/q/50848674
tags question: http://stackoverflow.com/q/50744708
tags question: http://stackoverflow.com/q/50848579
tags question: http://stackoverflow.com/q/50795928
tags question: http://stackoverflow.com/q/50781478
tags question: http://stackoverflow.com/q/50705252
tags question: http://stackoverflow.com/q/50730408
tags question: http://stackoverflow.com/q/50846431
tags question: http://stackoverflow.com/q/50725150
tags question: http://stackoverflow.com/q/50750324
tags question: http://stackoverflow.com/q/50819267
tags question: http://stackoverflow.com/q/50748177
tags question: http://stackoverflow.com/q/50852743
tags question: http://stackoverflow.com/q/50801461
tags question: http://stackoverflow.com/q/50744911
tags question: http://stackoverflow.com/q/50733329
tags question: http://stackoverflow.com/q/50790655
tags question: http://stackoverflow.com/q/50807129
tags question: http://stackoverflow.com/q/50806165
tags question: http://stackoverflow.com/q/50817243
tags question: http://stackoverflow.com/q/50732441
tags question: http://stackoverflow.com/q/50752674
tags question: http://stackoverflow.com/q/50740039
tags question: http://stackoverflow.com/q/50724271
tags question: http://stackoverflow.com/q/50785752
tags question: http://stackoverflow.com/q/50848879
tags question: http://stackoverflow.com/q/50835149
tags question: http://stackoverflow.com/q/50830618
tags question: http://stackoverflow.com/q/50783519
tags question: http://stackoverflow.com/q/50845189
tags question: http://stackoverflow.com/q/50772096
tags question: http://stackoverflow.com/q/50752579
tags question: http://stackoverflow.com/q/50848454
tags question: http://stackoverflow.com/q/50846745
tags question: http://stackoverflow.com/q/50850093
tags question: http://stackoverflow.com/q/50723927
tags question: http://stackoverflow.com/q/50777164
tags question: http://stackoverflow.com/q/50841165
tags question: http://stackoverflow.com/q/50700763
tags question: http://stackoverflow.com/q/50759500
tags question: http://stackoverflow.com/q/50785188
tags question: http://stackoverflow.com/q/50848127
tags question: http://stackoverflow.com/q/50757873
tags question: http://stackoverflow.com/q/50840794
tags question: http://stackoverflow.com/q/50715950
tags question: http://stackoverflow.com/q/50739918
tags question: http://stackoverflow.com/q/50713316
tags question: http://stackoverflow.com/q/50774378
tags question: http://stackoverflow.com/q/50780209
tags question: http://stackoverflow.com/q/50818809
tags question: http://stackoverflow.com/q/50847436
tags question: http://stackoverflow.com/q/50712657
tags question: http://stackoverflow.com/q/50803272
tags question: http://stackoverflow.com/q/50819725
tags question: http://stackoverflow.com/q/50755708
tags question: http://stackoverflow.com/q/50837262
tags question: http://stackoverflow.com/q/50828846
tags question: http://stackoverflow.com/q/50710069
tags question: http://stackoverflow.com/q/50823043
tags question: http://stackoverflow.com/q/50738140
tags question: http://stackoverflow.com/q/50709534
tags question: http://stackoverflow.com/q/50707253
tags question: http://stackoverflow.com/q/50803466
tags question: http://stackoverflow.com/q/50705195
tags question: http://stackoverflow.com/q/50699057
tags question: http://stackoverflow.com/q/50752601
tags question: http://stackoverflow.com/q/50710422
tags question: http://stackoverflow.com/q/50703872
tags question: http://stackoverflow.com/q/50763584
tags question: http://stackoverflow.com/q/50787783
tags question: http://stackoverflow.com/q/50757497
tags question: http://stackoverflow.com/q/50847527
tags question: http://stackoverflow.com/q/50788462
tags question: http://stackoverflow.com/q/50775733
tags question: http://stackoverflow.com/q/50785221
tags question: http://stackoverflow.com/q/50772605
tags question: http://stackoverflow.com/q/50792280
tags question: http://stackoverflow.com/q/50793397
tags question: http://stackoverflow.com/q/50779346

http://stackoverflow.com/q/50723303
tagged with: word2vec
tagged with: python
has answer: http://stackoverflow.com/a/50730108
type: AnsweredQuestion
type: Question
upvote count: 4
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50730108
tagged with: gensim
favorite count: 0
score: 4
has title: How is Word2Vec min_count applied
has body: Say that I'm training a (Gensim) Word2Vec model with min_count=5. The documentation learns us what min_count does: Ignores all words with total frequency lower than this. What is the effect of min_count on the context? Lets say that I have a sentence of frequent words (min_count > 5) and infrequent words (min_count &lt; 5), annotated with f and i: This (f) is (f) a (f) test (i) sentence (i) which (f) is (f) shown (i) here (i) I just made up which word is frequently used and which word is not for demonstration purposes. If I remove all infrequent words, we get a completely different context from which word2vec is trained. In this example, your sentence would be "This is a which is", which would then be a training sentence for Word2Vec. Moreover, if you have a lot of infrequent words, words that were originally very far away from each other are now placed within the same context. Is this the correct interpretation of Word2Vec? Are we just assuming that you shouldn't have too many infrequent words in your dataset (or set a lower min_count threshold)?

http://stackoverflow.com/comment/88574369
type: Comment
comment on: http://stackoverflow.com/a/50783403
type: AnswerComment
score: 0
has text: It shows `django.utils.datastructures.MultiValueDictKeyError: 'all_letters` '

http://stackoverflow.com/comment/88712004
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50854615
has text: yes i saw that in opencv imread docs too but was hoping for some way around it https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/py_image_display.html is there a way to apply my first code on a region of an image not on the full image? and just saving it won't do me well i need to work on the main image.
type: AnswerComment

http://stackoverflow.com/comment/129169095
score: 0
type: AnswerComment
type: Comment
has text: This wouldn't work if the index values are not evenly spaced...
comment on: http://stackoverflow.com/a/50806012

http://stackoverflow.com/comment/88667236
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50823267
has text: Wouldn't it be cleaner to create one label and update it instead of creating a new label every second?

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

http://stackoverflow.com/a/50711472
has comment: http://stackoverflow.com/comment/88460060
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50711395
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50711395
downvote count: 0
has comment: http://stackoverflow.com/comment/88459271
has body: Setup df = pd.DataFrame({'datetime': ['1/1/2012 00:05', '1/1/2012 00:10', '1/1/2012 00:15', '1/1/2012 00:20', '1/1/2012 00:25', '1/1/2012 00:30', '1/1/2012 00:35']}) pd.to_datetime with dt.ceil df['datetime'] = pd.to_datetime(df['datetime']).dt.ceil('30min') date 0 2012-01-01 00:30:00 1 2012-01-01 00:30:00 2 2012-01-01 00:30:00 3 2012-01-01 00:30:00 4 2012-01-01 00:30:00 5 2012-01-01 00:30:00 6 2012-01-01 01:00:00

http://stackoverflow.com/comment/88688852
type: QuestionComment
score: 0
has text: You cannot read/write back to the same file at the same time
type: Comment
comment on: http://stackoverflow.com/q/50842628

http://stackoverflow.com/q/50794270
tagged with: google-bigquery
score: 6
tagged with: google-cloud-storage
has answer: http://stackoverflow.com/a/50795097
favorite count: 0
has answer: http://stackoverflow.com/a/50801211
has answer: http://stackoverflow.com/a/63839091
type: UnansweredQuestion
tagged with: python
answer count: 4
has title: Exporting BigQuery Table Data to Google Cloud Storage having where clause using python
upvote count: 7
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/68096194
has body: I want to export table data from BigQuery to Google Cloud Storage. Problem is, I need data from date1 to date2 and not whole table data. extract_job = client.extract_table( table_ref, destination_uri, # Location must match that of the source table. location='US') # API request extract_job.result() This is what I have found on the google cloud help. There is no space for adding query or limiting data using where clause.

http://stackoverflow.com/comment/88420791
comment on: http://stackoverflow.com/q/50705532
score: 0
type: Comment
type: QuestionComment
has text: @Sören. RMSE is the metric used to train the model! I also need to transform the probabilities into logits, but note that my question DOES NOT say anything about classification performance.

http://stackoverflow.com/q/50705231
tagged with: terminal
tagged with: linux
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50705621
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88420326
tagged with: pip
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88419853
has comment: http://stackoverflow.com/comment/88420040
upvote count: 2
has body: virtualenv --version or which virtualenv gets nothing. I have done these things: sudo apt-get update --- this automatically puts python3 into the "directory"? I also want help with wording, is this the correct way to say this? python --version shows nothing but python3 --version shows python 3.6.5 then I did sudo apt install python3-pip. which pip shows nothing and which pip3 shows usr/bin/pip3. Lastly, I did pip install virtualenv. Now here's where I am confused. It successfully installed virtualenv 16.0.0 but if you do virtualenv --version or which virtualenv you get nothing. I think this is a fundamental misunderstanding of what pip does versus sudo apt-get/install. Should I run the command again instead using sudo or is it ok that virtualenv is not found by root? (again missing terminology) If I chose to leave it the way it is can I run virtualenv still? I really would like to set everything up correctly this time and only add python libraries to a virtualenv to keep everything clean. Thanks in advance!!
has title: Linux terminal terminology and command line confusion: pip install versus sudo apt-get and other terminal questions
answer count: 1
has comment: http://stackoverflow.com/comment/88437732
tagged with: virtualenv
favorite count: 0

http://stackoverflow.com/comment/88680989
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50838326
score: 0
has text: @Charles Duffy, not buggy, but neither too canonical. if the question was rounded as MVCE the command line should not be there at all, that was my point

http://stackoverflow.com/a/50844657
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50843877
has body: You can use: html_str = template(body=body) The bodyleft to the equal sign is the name of the variable as it will be called inside the template. The bodyon the right of the equal sign is the name of the variable inside the python code

http://stackoverflow.com/a/50851178
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/50851076
has body: str1 = '000' str2 = '111' all(a &gt;= b for a, b in zip(str1, str2)) # False all(a &gt;= b for a, b in zip(str2, str1)) # True
downvote count: 0

http://stackoverflow.com/comment/88598627
score: 0
type: Comment
type: QuestionComment
has text: Can you provide the traceback of the infinite loop you get with ``django_get_or_create``? That seems to be the proper way to handle your issue :/
comment on: http://stackoverflow.com/q/50782258

http://stackoverflow.com/q/50753236
tagged with: excel
type: Question
has body: I am experiencing a problem whenever I use "ws.print_title_rows = '1:1'" While opening the file Excel complains: "Wir haben ein Problem bei einigen Inhalten in 'output.xlsx' erkannt. Sollten wir so viel wie möglich wiederherstellen? Wenn Sie der Quelle dieser Arbeitsmappe vertrauen, klicken Sie auf 'Ja'." Translated into english: "We have detected a problem with some content in output.xlsx. Should we restore as much as possible? If you trust the source of this workbook, click Yes." After clicking 'Yes' Excel creates a file in my temp folder e.g.: "error256600_01.xml": <?xml version="1.0" encoding="UTF-8" standalone="yes"?> error256600_01.xml Fehler in Datei 'Z:\python\skype_ief_export_excel_auswertung\output.xlsx' Entfernte Datensätze: Benannter Bereich von /xl/workbook.xml-Part (Arbeitsmappe) Anyone knows if that is an Excel Problem or a Problem with Python/openpyxl and if so, how to fix it? My Setup: - Python 3.6.5 (32-bit) on Windows 10 Pro - Excel 2013 (German)
score: 0
answer count: 1
has title: Using "print_title_rows = '1:1'" leads to Excel complaining when opening resulting Excel File
tagged with: python
has comment: http://stackoverflow.com/comment/88526520
type: UnansweredQuestion
tagged with: openpyxl
has answer: http://stackoverflow.com/a/50766825

http://stackoverflow.com/a/58919496
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50784337
downvote count: 0
score: 1
has body: With tensorflow 2.0, you can write customize model and this allows you to compute derivative w.r.t. the input. For example, class MyModel(tf.keras.Model): def __init__(self): super(MyModel,self).__init__(name = 'my_model') self.dense_1 = layers.Dense(32,activation = 'relu', input_dim=2) self.dense_2 = layers.Dense(64,activation=tf.sin) self.dense_3 = layers.Dense(1) def call(self, inputs): # Define your forward pass here x = self.dense_1(inputs) x = self.dense_2(x) return self.dense_3(x) model = MyModel() optimizer = tf.keras.optimizers.RMSprop(0.001) model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse']) history = model.fit(X_train, y_train, epochs=10, batch_size = 1, validation_split = 0.2, verbose=0) To compute the derivative: x = tf.constant(X_train[:1,:]) with tf.GradientTape() as g: g.watch(x) y = model.call(x) dy_dx = g.gradient(y, x) print(y) dy_dx

pytorch
tags question: http://stackoverflow.com/q/50841770
tags question: http://stackoverflow.com/q/50783853
tags question: http://stackoverflow.com/q/50794502
tags question: http://stackoverflow.com/q/50738337
tags question: http://stackoverflow.com/q/50747947
tags question: http://stackoverflow.com/q/50710037
tags question: http://stackoverflow.com/q/50772128
tags question: http://stackoverflow.com/q/50792316
tags question: http://stackoverflow.com/q/50776548
tags question: http://stackoverflow.com/q/50759355
tags question: http://stackoverflow.com/q/50751689
tags question: http://stackoverflow.com/q/50781020
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/50710493
tags question: http://stackoverflow.com/q/50771001
tags question: http://stackoverflow.com/q/50700007
tags question: http://stackoverflow.com/q/50852294
tags question: http://stackoverflow.com/q/50845631
tags question: http://stackoverflow.com/q/50734480
tags question: http://stackoverflow.com/q/50753038
tags question: http://stackoverflow.com/q/50817964
tags question: http://stackoverflow.com/q/50762466
tags question: http://stackoverflow.com/q/50842356
tags question: http://stackoverflow.com/q/50753477
tags question: http://stackoverflow.com/q/50826644
tags question: http://stackoverflow.com/q/50740557
tags question: http://stackoverflow.com/q/50798172
tags question: http://stackoverflow.com/q/50812838
tags question: http://stackoverflow.com/q/50800056
tags question: http://stackoverflow.com/q/50718045

grafana
tags question: http://stackoverflow.com/q/50850767
tags question: http://stackoverflow.com/q/50814354
type: Tag
tag name: grafana

http://stackoverflow.com/q/50768963
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88546426
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/88545791
answer count: 0
has comment: http://stackoverflow.com/comment/88586017
has title: imread returns None on some images but not others in the same folder
tagged with: image-processing
type: Question
has comment: http://stackoverflow.com/comment/88546759
tagged with: imread
tagged with: image
score: 0
has comment: http://stackoverflow.com/comment/88590178
has comment: http://stackoverflow.com/comment/88554975
has body: I have been trying to read jpeg images with imread from cv2 package. So far, other than this seemingly random selection of images to read, it has been great. The problem is that, since I keep all of my images from the same source in the same folder, apparently imread worked on several images but not others for no obvious reason. I have closely inspected and made sure all images are working fine, of the same type, etc. However, as in the screenshots I attach below, only the selected images returned reasonable results whereas all others returned None. The exact code I used here is: img = cv2.imread(image,1) #most None Could anyone kindly suggest what possibly went wrong? Many thanks! My codes as a whole: images = os.listdir(os.path.join(input_dir, folder)) os.chdir(os.path.join(input_dir, folder)) #index += 1 index_array = [] out = [] # a quick recursion of summing up nested lists rec = lambda x: sum(map(rec, x)) if isinstance(x, list) else x minLineLength = 20 ##? how to set these? maxLineGap = 5 ##? how to set these? for image in images: print(image) if image == ".DS_Store" or (not image.endswith(".jpeg")): continue else: img = cv2.imread(image,1) #cv2.cv.LoadImage(image,CV_LOAD_IMAGE_COLOR)## #Opening image if img is None: print("None") continue elif img is not None: print("Pppppppppaaaaaaaaaaassssssssss!") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY); edges = cv2.Canny(gray, 50, 120); nedges = rec(edges.tolist())/255.0; lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength, maxLineGap) if lines is None: nlines = 0 elif lines is not None: nlines = lines.shape[0] img_blur = cv2.GaussianBlur(gray, (5, 5), 0) cimg = cv2.cvtColor(img_blur, cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img_blur, cv2.HOUGH_GRADIENT, 1, 120, param1=100, param2=30, minRadius=0, maxRadius=0) if circles is None: ncircles = 0 elif circles is not None: circles = np.uint16(np.around(circles)) ncircles = circles.shape[1] gray_blur = cv2.normalize(img_blur, img_blur, alpha=0, beta=255,…

http://stackoverflow.com/q/50762819
has title: What kind of table is created when executing a query that returns nothing?
type: AnsweredQuestion
tagged with: etl
has answer: http://stackoverflow.com/a/50762968
possible better answer: http://stackoverflow.com/a/50763055
type: Question
has body: I'm using petl and trying to create a simple table with a value from a query. I have written the following: @staticmethod def get_base_price(date): # open connection to db # run SQL query to check if price exists for that date # set base price to that value if it exists # set it to 100 if it doesn't sql = '''SELECT [TimeSeriesValue] FROM [RAP].[dbo].[TimeSeriesPosition] WHERE TimeSeriesTypeID = 12 AND SecurityMasterID = 45889 AND FundID = 7 AND EffectiveDate = %s''' % date with self.job.rap.connect() as conn: data = etl.fromdb(conn, sql).cache() return data I'm connecting to the database, and if there's a value for that date, then i'll be able to create a table that would look like this: +-----------------+ | TimeSeriesValue | +=================+ | 100 | +-----------------+ However, if the query returns nothing, what would the table look like? I want to set the TimeSeriesValue to 100 if the query returns nothing. Not sure how to do that.
has answer: http://stackoverflow.com/a/50763055
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50762968
tagged with: sql
tagged with: python

http://stackoverflow.com/q/50804416
answer count: 0
has body: To uninstall a program that has been built with pyInstaller I need to delete the folder containing the executable. How could I go about that without leaving any files after the uninstallation? It only has to work on Windows (> Server 2012)
tagged with: pyinstaller
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
type: Question
has title: Python, PyInstaller - delete folder containing exe
downvote count: 0
tagged with: windows
tagged with: exe
favorite count: 0

http://stackoverflow.com/q/50805374
has body: I'm pretty new to asyncio and I'm not able to figure this out by myself at this time and would greatly appreciate any help. The use case is as follows: There is a web service that I need to fetch data from that throttles and blacklists when too many requests are sent to it. I need to make a large number of requests to this web service for data The web service sends data in a paged fashion i.e. when there is too much data for a given request, subsequent requests need to be made to get more pages. Whether more pages need to be fetched can be figured out by examining the response from a particular request. Once data is received on the client-side it needs to written to disk So, in my mind, the setup could be as follows: - An initial list of requests that need to be made is prepared - A Semaphore controls how many requests are made per unit time to control throttling. - All the initial requests are added to a loop. - When a response is received a separate coroutine (or maybe a thread?) is dispatched to persist the data. I don't want persistence to be blocking the fetching of more data. - When a response is received it is examined to see if more pages need to be requested to get the full data. If more pages are needed then another task is added to the loop to fetch the next page. I've written some code for a minimal example that should provide the framework for what I'm trying to achieve: import asyncio import time import datetime from random import random sema = asyncio.Semaphore(2) async def my_worker(): async with sema: print("{}".format(datetime.datetime.now())) print("I'm going to fetch some data") result = await data_fetcher() print("I'm going to save data to disk") await write_result_to_disk(result) if random() &gt; 0.5: print("I need to create and run a new worker here to fetch more data") async def data_fetcher(): await asyncio.sleep(3) return "Bla bla bla" async def write_result_to_disk(result): await asyncio.sleep(3) print(result) blah = [my_worker(), my_worke…
answer count: 1
has answer: http://stackoverflow.com/a/50805736
score: 0
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: python
has title: Asyncio task that adds copies of itself to the loop
type: Question

http://stackoverflow.com/comment/88694981
type: AnswerComment
score: 0
has text: that doesn't cover all cases. try `main("A020A18", "a20a18")`. "Assuming that you mean to say that all zeros should be ignored unless the last character is a zero": Your starting hypothesis is wrong
type: Comment
comment on: http://stackoverflow.com/a/50845713

http://stackoverflow.com/comment/88482640
has text: Just edited the question, should probably have included the part where the files are actually made.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50737109

http://stackoverflow.com/comment/88522868
type: Comment
type: QuestionComment
has text: but like for that entire code should be changed?
comment on: http://stackoverflow.com/q/50757606
score: 0

http://stackoverflow.com/comment/88499282
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50745106
type: Comment
has text: Thank you for your answer. @jdehesa answer was more helpful because I need to use tf.Variable since I am using pymanopt (https://pymanopt.github.io/), see section c in Cost Functions.

http://stackoverflow.com/q/50742651
tagged with: python
tagged with: kernel
downvote count: 1
type: Question
has body: I need to implement GPR (Gaussian process regression) in Python using sci-kit learn library. My input X has two features. Ex. X=[race, BMI]. And output is one dimension y=[age_expectancy] I want to use two Kernels; RBF and Matern, such that RBF uses the 'race' feature while Matern use the 'age' feature. I tried the following: X = np.matrix([[1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.], [1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.],[1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.]]).T y=[84, 42, 47, 55, 25, 78, 52, 25, 75, 22, 45, 45, 88, 56, 77, 58, 48, 79] kernel = R(X[0]) * M(X[1]) gp = GaussianProcessRegressor(kernel=kernel) gp.fit(X, y) But this gives an error 'ValueError: Found input variables with inconsistent numbers of samples: [2, 18]'. I tried several methods but could not find a solution. Really appreciate if someone can help.
tagged with: gaussian
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/50742771
upvote count: 0
has title: Gaussian process with two dimensional feature array as the input in Python
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50742652

http://stackoverflow.com/comment/88491248
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50741194
has text: Advice, for debugging purposes, open developer console of Firefox and write there `new WebSocket("ws://35.185.80.98:6379/chat/")`
score: 0

http://stackoverflow.com/comment/88707528
type: Comment
has text: After doing `CLASS = CLASS.astype(str)`, and then checking the `value_counts()`, I get the identical output as in EDIT 2.
type: AnswerComment
comment on: http://stackoverflow.com/a/50852021
score: 0

http://stackoverflow.com/q/50701683
has comment: http://stackoverflow.com/comment/88428160
has answer: http://stackoverflow.com/a/59769855
has answer: http://stackoverflow.com/a/50702649
has title: Issue Installing misaka in a Django project
has comment: http://stackoverflow.com/comment/88425159
favorite count: 0
upvote count: 2
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55481814
has answer: http://stackoverflow.com/a/61194483
tagged with: django
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/88428082
tagged with: misaka
has body: I need to install misaka, but when I use pip install misaka I get an error that reads: Command "python setup.py egg_info" failed with error code 1 in C:\Users\JHONAT~1\AppData\Local\Temp\pip-build-utm0mant\misaka\ I don't really know what to do to solve it. I've tried using pip3 instead, no change and using pip2 also. I'm currently using python 3.6.4 and Django 1.11. Collecting misaka Using cached https://files.pythonhosted.org/packages/47/c2/ba9c82ae0ec62bcec62d690e715be6ead4457f83000f4ef6e919f77a8e5f/misaka-2.1.0.tar.gz Collecting cffi&gt;=1.0.0 (from misaka) Cache entry deserialization failed, entry ignored Downloading https://files.pythonhosted.org/packages/2f/85/a9184548ad4261916d08a50d9e272bf6f93c54f3735878fbfc9335efd94b/cffi-1.11.5-cp36-cp36m-win_amd64.whl (166kB) 100% |████████████████████████████████| 174kB 17kB/s Collecting pycparser (from cffi&gt;=1.0.0-&gt;misaka) Building wheels for collected packages: misaka Running setup.py bdist_wheel for misaka ... error Complete output from command g:\programming\anaconda3\envs\virtual\scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\JHONAT~1\\AppData\\Local\\Temp\\pip-b uild-9fgtbhdd\\misaka\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\U sers\JHONAT~1\AppData\Local\Temp\tmptz2d209jpip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\misaka copying misaka\api.py -&gt; build\lib.win-amd64-3.6\misaka copying misaka\callbacks.py -&gt; build\lib.win-amd64-3.6\misaka copying misaka\constants.py -&gt; build\lib.win-amd64-3.6\misaka copying misaka\utils.py -&gt; build\lib.win-amd64-3.6\misaka copying misaka\__init__.py -&gt; build\lib.win-amd64-3.6\misaka running build_ext generating cffi module 'build\\temp.win-amd64-3.6\\Release\\misaka._hoedown.c' creating build\temp.win-amd6…
type: Question
has answer: http://stackoverflow.com/a/61872934
has comment: http://stackoverflow.com/comment/88427429
downvote count: 0

http://stackoverflow.com/a/50826575
answers question: http://stackoverflow.com/q/50826542
has comment: http://stackoverflow.com/comment/88657957
type: AcceptedAnswer
score: 0
has body: You can use replace: yourstring = "[['x', '1.1', '2.1', '2.2', '2.3', '3.1', '4.1', '4.2', '4.3', '4.4'], [2.5, 2.8, 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null'], [2.3, 'null', 2.6, 'null', 'null', 'null', 'null', 'null', 'null', 'null'], [2, 'null', 'null', 1.8, 'null', 'null', 'null', 'null', 'null', 'null'], [2, 'null', 'null', 'null', 2.4, 'null', 'null', 'null', 'null', 'null'], [1.8, 'null', 'null', 'null', 'null', 2.4, 'null', 'null', 'null', 'null'], [2, 'null', 'null', 'null', 'null', 'null', 1.5, 'null', 'null', 'null'], [1.1, 'null', 'null', 'null', 'null', 'null', 'null', 1.4, 'null', 'null'], [1.3, 'null', 'null', 'null', 'null', 'null', 'null', 'null', 1.4, 'null'], [1.7, 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null', 1.8]]" print(yourstring.replace("'null'", "null")) But please do not try to produce json by yourself. You will write hard to read code, and probably will make some bugs. Use json.dumps()
accepted answer of: http://stackoverflow.com/q/50826542
type: Answer

http://stackoverflow.com/a/50756746
has body: Your implementation has no regularisation term. The LinearRegression estimator includes by default regularisation with inverse strength C = 1.0. As you set C to higher values, i.e. weaken the regularisation, the decision boundary moves closer to 5.5: for C in [1.0, 1000.0, 1e+8]: lr = LogisticRegression(C=C) lr.fit(inp, labels) print(f'C = {C}, decision boundary @ {(-lr.intercept_/lr.coef_[0])[0]}') Output: C = 1.0, decision boundary @ 3.6888430562595116 C = 1000.0, decision boundary @ 5.474229032805065 C = 100000000.0, decision boundary @ 5.499634348989383
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/50753400
score: 3

http://stackoverflow.com/a/50741119
answers question: http://stackoverflow.com/q/50741017
score: 7
upvote count: 7
type: Answer
downvote count: 0
has body: Have you tried to do it directly? customers_a = dict(a) result = [(customer, customers_a[customer], version) for customer, version in b if customer in customers_a] Now, result is exactly &gt;&gt;&gt; result [('customerB', '1.0.0', '1.1.0'), ('customerC', '1.0.1', '1.0.1')]

http://stackoverflow.com/q/50810846
answer count: 2
score: 0
accepted answer: http://stackoverflow.com/a/50810967
tagged with: python
tagged with: regex
tagged with: text-analysis
has comment: http://stackoverflow.com/comment/88627536
has answer: http://stackoverflow.com/a/50811791
type: AnsweredQuestion
has title: Remove Telephone numbers using Regular Expressions in Python 3
has answer: http://stackoverflow.com/a/50810967
possible better answer: http://stackoverflow.com/a/50811791
has body: I am trying to remove telephone numbers from a bunch of documents that i have parsed using tika but I do not succeed. Here is a screenshot taken by regex101 validator. As you can see, phone numbers are skipped. The same example in text format is the following: "Something here and something here 9, but (I have something here as well), 123456, Hi guys! +39.1234.325636 +39.321.1234567 sex male | date of birth 16/12/1927 | nationality italian some stuff " This is my Regex (I am not an expert in this field): (\(00\d{2}\)|\(\+\d{2}\)|00\d{2}|\+\d{2})[\. ]??3\d{2}[\. \-]??\d{2,4}[\. \-]??\d{2,4}$ Notice that +39 (or 0039) is fixed and the first 3 in the second telephone number is also fixed. Do you have any suggestions? Many thanks.
type: Question

http://stackoverflow.com/q/50841235
has body: I need to write a short script that can consume a REST call, every second. Most of the time, it will get back a response with: "status": "idle" However, if something is happening, we will instead get "status": "scan", with some additional parameters. We consume those parameters, and then make a different call to a cloud service. We would then get a response from that, and send back the JSON to the local web service. Then once completed, it should go back to checking every second for a status other than idle. Is Python a good language to do this on, or should be be using Java? The every second call is over a LAN, not concerns over latency or internet bandwidth. If it crashes or gets an exception we need to be able to restart easily. Any pointers on this would be most appreciated. The response coming back is in the format: [{'status': 'idle', 'log_updated_at': None, 'eprom_version': '03.21', 'data': {}, 'controller_type': 'single_ball', 'address': 1}] I am having some challenges getting that understood as json, to have the status element be accessed by the logic below.
has answer: http://stackoverflow.com/a/50841419
score: -1
tagged with: twisted
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has title: Every second web service call
type: AnsweredQuestion
upvote count: 0
tagged with: java
accepted answer: http://stackoverflow.com/a/50841419
type: Question

http://stackoverflow.com/comment/88738082
comment on: http://stackoverflow.com/a/50851679
type: Comment
score: 0
type: AnswerComment
has text: @user9144536 Read about SQL injections. It's very dangerous to have user defined input to be directly executed as a query. It's the same issue with using format() or any other way of manipulating strings.

http://stackoverflow.com/a/50841078
accepted answer of: http://stackoverflow.com/q/50840511
has comment: http://stackoverflow.com/comment/88687405
answers question: http://stackoverflow.com/q/50840511
has comment: http://stackoverflow.com/comment/88743020
has comment: http://stackoverflow.com/comment/126752482
has comment: http://stackoverflow.com/comment/109092971
has body: I see you are trying to use the Google Cloud Storage client libraries. In order to use it, you should first make sure that it is installed in your machine: pip install --upgrade google-cloud-storage And then, you should probably set up authentication (if you are using Application Default Credentials, from the documentation you mentioned), by setting up the GOOGLE_APPLICATION_CREDENTIALS environment variable in the machine where you are running the code, like below. If you are using Windows, follow the steps presented in the documentation, instead. export GOOGLE_APPLICATION_CREDENTIALS="/path/to/file.json" Alternatively, you can try using explicit credentials. The only difference between the one you shared (using implicit credentials obtained from the environment) and one using explicit credentials, is that when you declare the GCS client, you should do something like: storage_client = storage.Client.from_service_account_json('/path/to/SA_key.json') Once all this is ready, you should have no issues with running the sample code you provided. In order to keep learning about GCS and its client libraries, feel free to search on the documentation I linked and have a look at the library reference page.
type: AcceptedAnswer
downvote count: 0
upvote count: 104
has comment: http://stackoverflow.com/comment/88728783
has comment: http://stackoverflow.com/comment/88705982
type: Answer
score: 104
has comment: http://stackoverflow.com/comment/88705575

http://stackoverflow.com/comment/88463805
has text: Thanks Rakesh, its working now. If possible then can you take a look at the another issue that I posted for help related to data scrapping from table with duplicate (same Header titles) ? Will be much appreciated. - https://stackoverflow.com/questions/50647481/data-scrapping-from-website-having-multiple-tables
comment on: http://stackoverflow.com/a/50717821
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88433215
score: 0
comment on: http://stackoverflow.com/a/50712118
has text: what is your chrome version and chrome driver version?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88557935
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50774626
has text: @@jezrael, I have update my data. My data like this. By the way, the code just mentioned can't draw things. Can you help me?
score: 1

http://stackoverflow.com/a/50837823
type: Answer
has comment: http://stackoverflow.com/comment/88679875
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/50837627
has body: Is this what you are looking for ? var = "953381" df = pd.read_sql('select name, data, from sheet where name =' + var , conn, index_col=['date'], parse_dates=['date'])
upvote count: 0
has comment: http://stackoverflow.com/comment/95224438

http://stackoverflow.com/comment/88509631
type: Comment
comment on: http://stackoverflow.com/q/50750872
score: 0
has text: There are a few forks of the original `f2c` tool, but the official netlib one has supported C++ for a couple decades now, and the one that came with `gfortran` when it was a separate project from `gcc` did, so I'd assume whichever one you're using does as well. But to find out, `man f2c` and see. For example, [the netlib `f2c`](http://www.netlib.org/f2c/f2c.1) says "Convert Fortran 77 to C or C++", and has a `-C++` flag to "Output C++ code".
type: QuestionComment

http://stackoverflow.com/q/50803581
answer count: 1
has comment: http://stackoverflow.com/comment/88613568
tagged with: string
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50803825
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88613095
type: Question
score: 1
has body: Is there an analogy to myStr.find(subStr, startInd) in order to get the index of the first occurrence of subStr before my startInd. Like taking step -1 instead of 1 from startInd? Edit Here an example: myStr = "(I am a (cool) str)" startInd = 9 # print(myStr[startInd]) -&gt; "c" print(myStr.find(")", startInd)) # -&gt; 13 print(myStr.findBefore("(", startInd)) # -&gt; 8 Edit II The following code solves my problem but it is not really convenient. Wanted to ask if there is a simple method to fullfill that task startInd = 9 myStr = "(I am a (cool) str)" print(myStr.find(")", startInd)) # -&gt; 13 print(len(myStr[::-1]) - myStr[::-1].find("(", len(myStr[::-1]) - startInd - 1) - 1) # -&gt; 8
tagged with: substring
has title: Find First Occurrence of Substring Before Index
tagged with: find
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/88653274
comment on: http://stackoverflow.com/a/50823016
score: 0
type: AnswerComment
type: Comment
has text: I need it to start writing from column 6 and skip column 1 to 5 because 1 to 5 already have data in it

http://stackoverflow.com/comment/88456433
comment on: http://stackoverflow.com/q/50723957
has text: The closure is not a method. It does not require `self`. You could place it into the namespace of the module (one level up) to avoid the problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88578538
type: Comment
has text: @Jeremie There are many questions about your solution tbh. I'd separate the function to do one thing.
comment on: http://stackoverflow.com/a/50785888
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88549808
score: 1
has text: show your `import` section.
comment on: http://stackoverflow.com/q/50771146
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57260898
type: Answer
score: 11
downvote count: 0
answers question: http://stackoverflow.com/q/50771584
upvote count: 11
has body: I was looking for this same thing and after some digging into dbutils, this is the solution I came up with: import json context = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson()) print(context['extraContext']['aclPathOfAclRoot']) # Base path print(context['extraContext']['notebook_path']) # Notebook path

http://stackoverflow.com/q/50827099
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/69858290
tagged with: plotly
upvote count: 10
tagged with: jinja2
type: Question
has answer: http://stackoverflow.com/a/66248677
score: 10
has title: Passing dash_html_components into a Jinja template
linked to: http://stackoverflow.com/q/61682730
answer count: 2
tagged with: plotly-dash
downvote count: 0
tagged with: flask
has body: I'm using the Python library Dash and the documentation claims that it doesn't support the ability to write raw html with the dashboard html code. Is there a known work around to this (something like passing dcc.Graph into render_template() with Flask?). The code snippet I would like to migrate to an Jinja template file is: app.layout = html.Div(className='ui container', children=[ html.H1('Locations', className=''), html.Div(id='text-content'), dcc.Graph(id='map', figure={ 'data': [{ 'lat': df['LAT'], 'lon': df['LONG'], 'marker': { 'color': df['YEAR'], 'size': 8, 'opacity': 0.6 }, 'customdata': df['NO'], 'type': 'scattermapbox' }], }, 'hovermode': 'closest', 'margin': {'l': 0, 'r': 0, 'b': 0, 't': 0} } }) ])
favorite count: 0

http://stackoverflow.com/a/50840567
upvote count: 2
has comment: http://stackoverflow.com/comment/90528615
answers question: http://stackoverflow.com/q/50832190
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90565006
has body: Here's a simple example passing a struct in Thrift IDL: https://github.com/RandyAbernethy/ThriftBook/blob/master/part1/arch/halibut.thrift struct Date { 1: i16 year 2: i16 month 3: i16 day } service HalibutTracking { i32 get_catch_in_pounds_today() i32 get_catch_in_pounds_by_date(1: Date dt, 2: double tm) } There's a Java client and server example here: https://github.com/RandyAbernethy/ThriftBook/tree/master/part3/ws/thrift It shows returning a struct (but passing one is pretty easy to extrapolate). There are also many examples in the ThriftBook repo in Python and Java (all source from the Programmer's Guide to Apache Thrift): The example struct return thrift idl looks like: struct TradeReport { 1: string symbol, 2: double price, 3: i32 size, 4: i32 seq_num } service TradeHistory { TradeReport get_last_sale(1: string Symbol) } The Java Client in the listing looks like this: import java.io.IOException; import org.apache.thrift.TException; import org.apache.thrift.transport.TSocket; import org.apache.thrift.protocol.TBinaryProtocol; public class ThriftClient { public static void main(String[] args) throws IOException, TException { TSocket trans = new TSocket("localhost", 9090); TBinaryProtocol proto = new TBinaryProtocol(trans); TradeHistory.Client client = new TradeHistory.Client(proto); trans.open(); for (int i = 0; i &lt; 1000000; i++) { TradeReport tr = client.get_last_sale("APPL"); } trans.close(); } } Other IDL examples are here (including several that pass structs): https://github.com/RandyAbernethy/ThriftBook/tree/master/part2/IDL
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50832190

http://stackoverflow.com/comment/88706566
comment on: http://stackoverflow.com/a/50851748
type: AnswerComment
has text: Got it, if we have only the borders of a square on black image. You want the entire square to be turned into white pixels. Is it right?
type: Comment
score: 0

http://stackoverflow.com/a/50834425
downvote count: 0
type: Answer
has body: You could match one or more uppercase characters [A-Z]+, an underscore _ and then zero or more [A-Z]* times an uppercase character followed by one or more digits [0-9]+. Use might use a word boundary \b so it is not part of a longer match. \b[A-Z]+_[A-Z]*[0-9]+\b Regex demo
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50832864

http://stackoverflow.com/comment/88548192
has text: **@Monso**, your question is unclear. Please add more explanation. Why you are reading **trang.txt** and writing to **trang2.txt** etc. Give more inputs and expected outputs. Do you want to copy all the files available in **Input** directory to **Output** directory?
score: 0
comment on: http://stackoverflow.com/q/50770218
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88526479
comment on: http://stackoverflow.com/q/50756793
type: Comment
type: QuestionComment
has text: @mkrieger1 Delta defines the sensitivity of detecting peaks. Like if you set a higher delta, it will not detect the small peaks. This is particularly useful if you have noise in the signal.
score: 0

http://stackoverflow.com/comment/88655161
type: AnswerComment
comment on: http://stackoverflow.com/a/50824727
type: Comment
has text: Nope, sorting should be exactly the same. this is the original dataframe with one addtional column.
score: 0

http://stackoverflow.com/a/50710953
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50710858
has body: This shouldn't happen. And it wouldn't happen if you made sure your index are actual numbers, not strings. To convert your index to numbers, use e.g. df.index = df.index.values.astype(int) Then remove the set_xticklabels line, because this would anyway only make sense if you set the ticks via set_ticks as well. This will then assure that matplotlib automatically chooses useful spacings between the ticks. Complete example: import matplotlib.pyplot as plt import numpy as np;np.random.seed(9) import pandas as pd inx = np.arange(1978,2017).astype(str) a = np.cumsum(np.random.randn(len(inx),2), axis=0)+10 df = pd.DataFrame(a, index=inx, columns=list("AB")) df.index = df.index.values.astype(int) fig, ax = plt.subplots(figsize=(10,7)) ax.plot(df['A']) ax.plot(df['B']) ax.set_xlabel('YEAR') ax.legend() ax.set_ylim([0, 1.1*max([df['A'].max(), df['B'].max()])]) plt.show()
answers question: http://stackoverflow.com/q/50710858
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88430938
upvote count: 2

http://stackoverflow.com/comment/88602100
has text: Yeah I know I am Lacking many Informations about Django and web Development in General as I started like 4 Weeks ago with web. It would be still nice if you can at least direct me in the right Direction.
comment on: http://stackoverflow.com/q/50797372
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50848528
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88715610
type: Answer
has comment: http://stackoverflow.com/comment/88700446
answers question: http://stackoverflow.com/q/50848383
has comment: http://stackoverflow.com/comment/88700490
has comment: http://stackoverflow.com/comment/88700348
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50848383
score: 1
has comment: http://stackoverflow.com/comment/88700309
has body: https://developer.twitter.com/en/docs/ads/general/guides/response-codes.html as you see here these error codes mean that you reached TOO_MANY_REQUESTS or TWEET_RATE_LIMIT_EXCEEDED.

http://stackoverflow.com/q/50839847
has comment: http://stackoverflow.com/comment/88683887
has answer: http://stackoverflow.com/a/50840223
downvote count: 2
tagged with: output
type: Question
score: -2
has comment: http://stackoverflow.com/comment/88683703
has comment: http://stackoverflow.com/comment/88684036
has body: I have been trying to solve Codeforces problem No. 313A. I take an input from the user and convert it into a list. The code works fine till the input number is 11 to 12 digits long. After that, the code gives no output. Here's my code in Python 3: n = int(input()) if(n &gt;= 0): print(n) else: if(n &lt;= -10 and n&gt;= -90): print(0) else: n = str(n) n.split() k = [] k = n[:len(n) - 1] l = [] l = n[:len(n) - 2] + n[len(n) - 1] k = ''.join(k) l = ''.join(l) k , l = int(k), int(l) if(k &gt;= l): print(k) Here's the link for the problem.
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/88683685
favorite count: 0
tagged with: python-3.x
has title: Why does my list display output only upto a certain length of input number?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50840273
has comment: http://stackoverflow.com/comment/88683970
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/88684023
tagged with: list

http://stackoverflow.com/comment/88532892
has text: @EdChum I tried to verify by converting the feather back to a dataframe but got another error. Updated the question accordingly.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50761777
score: 0

http://stackoverflow.com/comment/88517101
comment on: http://stackoverflow.com/q/50754643
has text: I guess you have a typo in the title (Jason = Jason)?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50775683
has comment: http://stackoverflow.com/comment/88558240
has comment: http://stackoverflow.com/comment/88558281
accepted answer of: http://stackoverflow.com/q/50775629
has comment: http://stackoverflow.com/comment/88558343
downvote count: 0
score: 1
has body: We can use the following regex: (v\d+(?:\.\d+)*)(?:[-]([A-Za-z]+))?((?:\.\d+)*)\.zip This thus produces three groups: the first one the version, the second is optional: a dash - followed by alphabetical characters, and then an optional sequence of dots followed by numbers, and finally .zip. If we ignore the \.zip suffix (well I assume this is rather trivial), then there are still three groups: (v\d+(?:\.\d+)*): a regex group that starts with a v followed by \d+ (one or more digits). Then we have a non-capture group (a group starting with (?:..) that captures \.\d+ a dot followed by a sequence of one or more digits. We repeat such subgroup zero or more times. (?:[-]([A-Za-z]+))?: a capture group that starts with a hyphen [-] and then one or more [A-Za-z] characters. The capture group is however optional (the ? at the end). ((?:\.\d+)*): a group that again has such \.\d+ non-capture subgroup, so we capture a dot followed by a sequence of digits, and this pattern is repeated zero or more times. For example: rgx = re.compile(r'(v\d+(?:\.\d+)*)([-][A-Za-z]+)?((?:\.\d+)*)\.zip') We then obtain: &gt;&gt;&gt; rgx.findall('v1.1.2-beta.2.zip') [('v1.1.2', '-beta', '.2')] &gt;&gt;&gt; rgx.findall('v1.1.2.zip') [('v1.1.2', '', '')]
has comment: http://stackoverflow.com/comment/88558252
has comment: http://stackoverflow.com/comment/88558439
has comment: http://stackoverflow.com/comment/88560862
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50775629

http://stackoverflow.com/q/50736210
tagged with: interpreter
duplicate of: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/88480186
has answer: http://stackoverflow.com/a/50736355
type: Question
tagged with: function
tagged with: scope
linked to: http://stackoverflow.com/q/1132941
downvote count: 3
has title: please explain how python executes the following code:
answer count: 1
favorite count: 0
has body: I am intrigued by the output the following code generates. Can anyone explain to me why python prints [1,5] and not just [5] when it executes the function call for the third time, and if it is a feature or a bug in Python? def funn(arg1, arg2=[]): arg2.append(arg1) print(arg2) funn(1) funn(2, [3, 4]) funn(5)
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: namespaces
upvote count: 0

http://stackoverflow.com/comment/88967697
type: AnswerComment
comment on: http://stackoverflow.com/a/50821555
score: 0
has text: @Shko after booking a car you got redirected to the `index` page or the booking `form` appears again?
type: Comment

http://stackoverflow.com/a/63675145
type: Answer
answers question: http://stackoverflow.com/q/50714469
upvote count: 20
downvote count: 0
has comment: http://stackoverflow.com/comment/140190530
has comment: http://stackoverflow.com/comment/127933252
score: 20
has body: To find just folders the right glob string is: '**/' So to find all the paths for all the folders in your path do this: p = Path('docs') for child in p.glob('**/'): print(child) If you just want the folder names without the paths then print the name of the folder like so: p = Path('docs') for child in p.glob('**/'): print(child.name)

http://stackoverflow.com/q/50745094
has comment: http://stackoverflow.com/comment/88498045
has comment: http://stackoverflow.com/comment/88499540
linked to: http://stackoverflow.com/q/30669474
has answer: http://stackoverflow.com/a/50752488
tagged with: python
has comment: http://stackoverflow.com/comment/88498879
has answer: http://stackoverflow.com/a/65021331
type: AnsweredQuestion
has body: I have the following folder structure: app __init__.py utils __init__.py transform.py products __init__.py fish.py In fish.py I'm importing transform as following: import utils.transform. When I'm running fish.py from Pycharm, it works perfectly fine. However when I am running fish.py from the Terminal, I am getting error ModuleNotFoundError: No module named 'utils'. Command I use in Terminal: from app folder python products/fish.py. I've already looked into the solutions suggested here: Importing files from different folder, adding a path to the application folder into the sys.path helps. However I am wondering if there is any other way of making it work without adding two lines of code into the fish.py. It's because I have many scripts in the /products directory, and do not want to add 2 lines of code into each of them. I looked into some open source projects, and I saw many examples of importing modules from a parallel folder without adding anything into sys.path, e.g. here: https://github.com/jakubroztocil/httpie/blob/master/httpie/plugins/builtin.py#L5 How to make it work for my project in the same way?
tagged with: pycharm
downvote count: 0
has comment: http://stackoverflow.com/comment/114952494
has comment: http://stackoverflow.com/comment/88498502
has comment: http://stackoverflow.com/comment/88498526
has comment: http://stackoverflow.com/comment/88498455
has comment: http://stackoverflow.com/comment/88498488
type: Question
has comment: http://stackoverflow.com/comment/88498468
linked to: http://stackoverflow.com/q/4383571
has comment: http://stackoverflow.com/comment/88498375
has title: ModuleNotFoundError when running script from Terminal
linked to: http://stackoverflow.com/q/1054271
score: 44
possible better answer: http://stackoverflow.com/a/65021331
answer count: 2
has comment: http://stackoverflow.com/comment/88498460
linked to: http://stackoverflow.com/q/14132789
upvote count: 44
accepted answer: http://stackoverflow.com/a/50752488
has comment: http://stackoverflow.com/comment/121627394
has comment: http://stackoverflow.com/comment/88498334
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88527989
comment on: http://stackoverflow.com/a/50758201
score: 0
type: AnswerComment
has text: @user8810517 Regarding your first question: It really depends on the list and the elements theirselves, so I wouldn't rely on it. For instance, if you try with the same list on a different order, such as `['XDA-OT','hi','yeah', 'loc']` you will see that using `range(len(lst)-1)` actually fails.
type: Comment

http://stackoverflow.com/comment/88764487
has text: The question has been edited. Sorry about the imprecise description before.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50848968

http://stackoverflow.com/a/50812426
has comment: http://stackoverflow.com/comment/88655963
has body: EDIT: This is not an Optimistic Lock attempt. This is a direct answer to OP's provided code. Django offers a way to implement conditional queries. It also offers the update_or_create(defaults=None, **kwargs) shortcut which: The update_or_create method tries to fetch an object from the database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary. The values in defaults can be callables. So we can attempt to mix and match those two in order to recreate the supplied query: obj, created = Account.objects.update_or_create( id=self.id, version=self.version, defaults={ balance: Case( When(version=self.version, then=F('balance')+amount), default=amount ), version: Case( When(version=self.version, then=F('version')+1), default=self.version ) } ) Breakdown of the Query: The update_or_create will try to retrieve an object with id=self.id and version=self.version in the database. Found: The object's balance and version fields will get updated with the values inside the Case conditional expressions accordingly (see the next section of the answer). Not Found: The object with id=self.id and version=self.version will be created and then it will get its balance and version fields updated. Breakdown of the Conditional Queries: balance Query: If the object exists, the When expression's condition will be true, therefore the balance field will get updated with the value of: # Existing balance # Added amount F('balance') + amount If the object gets created, it will receive as an initial balance the amount value. version Query: If the object exists, the When expression's condition will be true, therefore the version field will get updated with the value of: # Existing version # Next Version F('version') + 1 If the object gets created, it will receive as an initial version the self.version value (it can also be a default initial version like 1.0.0). Notes: You may need to provide an output_field argument to the Case expression, have a loo…
has comment: http://stackoverflow.com/comment/88655856
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/88655899
accepted answer of: http://stackoverflow.com/q/50699759
answers question: http://stackoverflow.com/q/50699759
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88655940

http://stackoverflow.com/q/50756299
tagged with: regex
has comment: http://stackoverflow.com/comment/88522469
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50757044
has comment: http://stackoverflow.com/comment/88521158
tagged with: if-statement
score: -1
has title: Regex Bash to match a condition
has comment: http://stackoverflow.com/comment/88520920
has comment: http://stackoverflow.com/comment/88521199
upvote count: 0
has body: I wish to match below patterns and then proceed for a shell script in Jenkins. The strings should always start with CMR- and SP- and should be followed up with 4 numbers like below. I am having problem in matching this case for a digit of 4 numbers in the range from 0-9. Any language will do. So my purpose is this. I want to run a script based on below conditions. If the environment doesn't match xyz which is production and doesn't match tickets id's for example CMR-1234 or SP-1234 then script should exit and not run my deployment script. Can someone please help me out? CMR-1256 and SP-1278 My bash expression is like below. end () { exit 1 } echo $CMR if [ ! `echo $CMR | grep -cE "^CMR-{0,9}|^SP-{0,9}" ` -gt 0 -a $environment == "xyz" ] then echo "None of the conditions met" end fi I just modified my question to give it more clarity.
has comment: http://stackoverflow.com/comment/88520575
has comment: http://stackoverflow.com/comment/88521017
answer count: 1
tagged with: shell
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88602245
type: Comment
type: QuestionComment
has text: You can try defining a threshold for your contour areas with `cv2.contourArea(ctr)`. So you are saying that the contours needs to be at least a certain size.
score: 1
comment on: http://stackoverflow.com/q/50797435

django
tags question: http://stackoverflow.com/q/50813567
tags question: http://stackoverflow.com/q/50801015
tags question: http://stackoverflow.com/q/50782337
tags question: http://stackoverflow.com/q/50836829
tags question: http://stackoverflow.com/q/50784664
tags question: http://stackoverflow.com/q/50700897
tags question: http://stackoverflow.com/q/50775750
tags question: http://stackoverflow.com/q/50731886
tags question: http://stackoverflow.com/q/50832981
tags question: http://stackoverflow.com/q/50825957
tags question: http://stackoverflow.com/q/50756193
tags question: http://stackoverflow.com/q/50837943
tags question: http://stackoverflow.com/q/50767745
tags question: http://stackoverflow.com/q/50728574
tags question: http://stackoverflow.com/q/50823788
tags question: http://stackoverflow.com/q/50785955
tags question: http://stackoverflow.com/q/50767257
tags question: http://stackoverflow.com/q/50721473
tags question: http://stackoverflow.com/q/50800858
tags question: http://stackoverflow.com/q/50767861
tags question: http://stackoverflow.com/q/50843113
tags question: http://stackoverflow.com/q/50703912
tags question: http://stackoverflow.com/q/50773815
tags question: http://stackoverflow.com/q/50779713
tags question: http://stackoverflow.com/q/50806927
tags question: http://stackoverflow.com/q/50790223
tags question: http://stackoverflow.com/q/50700546
tags question: http://stackoverflow.com/q/50722714
tags question: http://stackoverflow.com/q/50698816
tags question: http://stackoverflow.com/q/50745368
tags question: http://stackoverflow.com/q/50729027
tags question: http://stackoverflow.com/q/50847000
tags question: http://stackoverflow.com/q/50748203
tags question: http://stackoverflow.com/q/50797573
tags question: http://stackoverflow.com/q/50822307
tags question: http://stackoverflow.com/q/50843141
tags question: http://stackoverflow.com/q/50853397
tags question: http://stackoverflow.com/q/50701738
tags question: http://stackoverflow.com/q/50837818
tags question: http://stackoverflow.com/q/50833833
tags question: http://stackoverflow.com/q/50815095
tags question: http://stackoverflow.com/q/50741729
tags question: http://stackoverflow.com/q/50708767
tags question: http://stackoverflow.com/q/50765946
tags question: http://stackoverflow.com/q/50779565
tags question: http://stackoverflow.com/q/50699759
tags question: http://stackoverflow.com/q/50797557
tags question: http://stackoverflow.com/q/50836922
tags question: http://stackoverflow.com/q/50791827
tags question: http://stackoverflow.com/q/50741687
tags question: http://stackoverflow.com/q/50759310
tags question: http://stackoverflow.com/q/50851305
tags question: http://stackoverflow.com/q/50849692
tags question: http://stackoverflow.com/q/50782897
tags question: http://stackoverflow.com/q/50720688
type: Tag
tags question: http://stackoverflow.com/q/50741194
tags question: http://stackoverflow.com/q/50782240
tags question: http://stackoverflow.com/q/50842176
tags question: http://stackoverflow.com/q/50707496
tags question: http://stackoverflow.com/q/50775006
tags question: http://stackoverflow.com/q/50732260
tags question: http://stackoverflow.com/q/50825169
tags question: http://stackoverflow.com/q/50707133
tags question: http://stackoverflow.com/q/50707948
tags question: http://stackoverflow.com/q/50768811
tags question: http://stackoverflow.com/q/50741927
tags question: http://stackoverflow.com/q/50706292
tags question: http://stackoverflow.com/q/50816798
tags question: http://stackoverflow.com/q/50717572
tags question: http://stackoverflow.com/q/50782769
tags question: http://stackoverflow.com/q/50834317
tags question: http://stackoverflow.com/q/50736011
tags question: http://stackoverflow.com/q/50775665
tags question: http://stackoverflow.com/q/50799470
tags question: http://stackoverflow.com/q/50816914
tags question: http://stackoverflow.com/q/50774504
tags question: http://stackoverflow.com/q/50778767
tags question: http://stackoverflow.com/q/50787563
tags question: http://stackoverflow.com/q/50776076

http://stackoverflow.com/a/50810674
has body: Given that all the data is stored on a single line, just do this: import json with open('file.json', 'r') as f: data = json.loads(line)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50810190

http://stackoverflow.com/q/50816096
favorite count: 0
tagged with: differentiation
type: UnansweredQuestion
tagged with: python
has body: I am trying to figure out how to create and manipulate exact differentials (algebraic treatment of Leibniz notation) in SymPy. To be clear, it is well known that from sympy import * init_printing() x, y=symbols('x, y') f=Function('f')(x, y) Derivative(f, x) yields In the case above, the exact differential is For a physicist this is especially needed given the kind of abuse we do to the chain rule but also for simple things like V = A \ell and dV = dA d\ell, when working with integrals or this classic physics abuse of the Leibniz notation that occurs all the time in thermodynamics.
type: Question
score: 4
tagged with: calculus
upvote count: 4
tagged with: sympy
tagged with: symbolic-math
has title: Creating and working with exact differentials in SymPy
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50850250

http://stackoverflow.com/comment/88429317
comment on: http://stackoverflow.com/q/50710099
type: Comment
type: QuestionComment
has text: That isn't PEP8 though.. that's your linter having trouble.
score: 2

http://stackoverflow.com/a/50714280
has body: I believe need between for boolean mask, invert it ~ and sum of Trues: print ((~df['data'].between(-45, 35)).sum()) Sample: df = pd.DataFrame({'data':[-47,10,0,30,50]}) print (df) data 0 -47 1 10 2 0 3 30 4 50 print ((~df['data'].between(-45, 35)).sum()) 2 Details: print (df['data'].between(-45, 35)) 0 False 1 True 2 True 3 True 4 False Name: data, dtype: bool print (~df['data'].between(-45, 35)) 0 True 1 False 2 False 3 False 4 True Name: data, dtype: bool
answers question: http://stackoverflow.com/q/50714185
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50714185
type: Answer

taskscheduler
tags question: http://stackoverflow.com/q/50711177
type: Tag
tag name: taskscheduler

http://stackoverflow.com/comment/88634775
type: AnswerComment
has text: On my Windows 7 machine I have perl installed and in `PATH`. there are two files in the `bin` named `pkg-config`. One with no extension, and another with the `.bat` extension. If I remove the one with no extension from the file and leave the `.bat` file, then enter `pkg-config` on command line - it calls it. Perhaps it's a 2012 thing?
type: Comment
comment on: http://stackoverflow.com/a/50814730
score: 0

http://stackoverflow.com/comment/88515109
comment on: http://stackoverflow.com/a/50753581
type: AnswerComment
has text: Apparently, it seems an isssue with `matplotlib version < 2`. The code works fine on another PC having matplotlib 2. Let me update it please!
score: 0
type: Comment

http://stackoverflow.com/q/50761146
has comment: http://stackoverflow.com/comment/88537690
upvote count: 1
type: Question
tagged with: pytest
score: 1
has answer: http://stackoverflow.com/a/50771437
answer count: 1
downvote count: 0
favorite count: 0
has body: I have created a project in eclipse using pytest framework class TestClass(object): def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') Now, I want to create a html report for my project.I have done the following: Installed the html plugin Written the below code in conftest.py module import pytest @pytest.mark.hookwrapper def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() When I ran my test, I didn't get any report.Below is my result as expected, but no report got generated &gt; ============================= test session starts ============================= platform win32 -- Python 3.6.5, pytest-3.6.0, py-1.5.3, pluggy-0.6.0 rootdir: D:\Eclipse1\TFCProject, &gt; inifile: plugins: ordering-0.5, metadata-1.7.0, html-1.19.0 collected &gt; 2 items &gt; &gt; TFCPackage\pycheck.py .F &gt; [100%] &gt; &gt; ================================== FAILURES =================================== &gt; _____________________________ TestClass.test_two self = &lt;TFCPackage.pycheck.TestClass object at 0x03778AF0&gt; def test_two(self): x = "hello" &gt; assert hasattr(x, 'check') E AssertionError: assert False E + where False = hasattr('hello', 'check') TFCPackage\pycheck.py:13: AssertionError ===================== 1 failed, 1 passed in 0.41 seconds ====================== Please guide me as I am new to pytest
tagged with: python
tagged with: pytest-html
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/136578912
has title: How to create a HTML report for pytest?
accepted answer: http://stackoverflow.com/a/50771437

http://stackoverflow.com/a/50735939
type: Answer
has body: This cannot work because when you perform a conditional test, you are not entering strings. Here is a sample example: import random strings = ['r', 'p', 's'] computer = strings[random.randint(0, 2)] user_choice = input("enter r for rock,p for paper,s for scissors:\n") if computer==user_choice: print("its a tie") elif computer == 'r' and user_choice == 'p': print(" congrats you won ") elif computer == 'r' and user_choice == 's': print("sorry you lost") elif computer == 'p' and user_choice== 'r': print("sorry you lost") elif computer == 'p' and user_choice == 's': print(" congrats you won ") elif computer == 's' and user_choice == 'p': print("sorry you lost") elif computer == 's' and user_choice == 'r': print(" congrats you won ") else: print('Error') Notice that in each conditional test, we enter the values that we are comparing as strings. If they are not string objects they cannot be compared in this example. Simply placing p, r, or s will not work, but they need to be enclosed in quotes as you see. Otherwise, you will get a traceback error.
answers question: http://stackoverflow.com/q/50735703
score: 0

http://stackoverflow.com/a/50837321
score: 0
has body: This should solve the problem: l = [1,2,3,4,5] result = 0 for val in l: result += val An even shorter way of approaching this is using sum(arr): result = sum([1,2,3,4,5]) # = 15
answers question: http://stackoverflow.com/q/50837262
type: Answer

http://stackoverflow.com/q/50766987
has comment: http://stackoverflow.com/comment/88551151
has body: I want to get an image properties - title and subject values and use it for my program. Here is a screenshot: I can't seem to find a good and simple way to do this. Performance doesn't really matter that much. It will be a small-medium sized project.
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88541655
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88542318
linked to: http://stackoverflow.com/q/4764932
tagged with: python
has title: How can I get an image's title and subject properties?
linked to: http://stackoverflow.com/q/21697645
type: Question

http://stackoverflow.com/a/50804220
has body: If you don't care about preserving the number of spaces something like this will work, and probably faster than using regex: alt_name = 'John A. desmith' name = 'John R. DeSmith' d = {s.lower(): s for s in name.split()} corrected_alt_name = ' '.join(d.get(s.lower(), s) for s in alt_name.split()) print(corrected_alt_name) John A. DeSmith If you do care about spaces then you could use re.split() instead of str.split() as described here: import re corrected_alt_name = ''.join(d.get(s.lower(), s) for s in re.split(r'(\s+)', alt_name)) print(corrected_alt_name)
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50804061
answers question: http://stackoverflow.com/q/50804061

http://stackoverflow.com/comment/88429386
comment on: http://stackoverflow.com/a/50709920
score: 0
type: AnswerComment
type: Comment
has text: Thank you so much. I have no idea how I didn't think of looping the tuples by making a nested for loop, pretty simple and works flawlessly. I guess my biggest issue was how i viewed the tuples before, I was very confused what they even are, now I see they are something like nested lists.

sift
tags question: http://stackoverflow.com/q/50733604
tag name: sift
tags question: http://stackoverflow.com/q/50699527
type: Tag

http://stackoverflow.com/q/50712114
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88433304
duplicate of: http://stackoverflow.com/q/567222
has answer: http://stackoverflow.com/a/50712162
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50712200
tagged with: python
has title: Python Prime Sum Programme
linked to: http://stackoverflow.com/q/567222
has body: I am trying to use python to solve Project Euler's questions. The question i met is to add to all prime number below 2 millions. My codes: import math def isPrime(number): if number == 2: return True for x in range(2,number): if number % x ==0: return False return True number = 3 ans = 2 while number&lt;=2000000: if(isPrime(number)): print(number) ans+=number number+=2 I think it is working, however it is processing too slow. Is there any way to enhance it? (Without using a prime number set in memory). Thank you!
type: Question
tagged with: performance
tagged with: algorithm
tagged with: math
has comment: http://stackoverflow.com/comment/88433128

http://stackoverflow.com/q/50777633
score: 0
has comment: http://stackoverflow.com/comment/88562903
tagged with: python-3.x
has body: I very new to Python, so anything would be very helpful. I need to be able to make adjustments to the price and stock of three inventory items if the user inputs code 3. The user should be able to select the product they want to
type: UnansweredQuestion
tagged with: python
has title: Trying to be able to make updates to the prices and inventory in a simple, three product inventory program
answer count: 0
has comment: http://stackoverflow.com/comment/88562334
type: Question
has comment: http://stackoverflow.com/comment/88562530

http://stackoverflow.com/comment/88664054
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50816356
type: AnswerComment
has text: I get an error when i pass two fit_generator. i have edited the question.

http://stackoverflow.com/comment/88461431
has text: I don't understand how this is supposed to work, you give me feedback to fix my post, but then it gets down voted so now it won't be seen even though it is fixed. I had missed a few things, but now my problem won't get addressed. What's the deal?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50725373

http://stackoverflow.com/comment/88654840
comment on: http://stackoverflow.com/a/50824887
type: Comment
has text: @Jenny I'm glad it helps! Note that I've added another approach using `next()`, which should be far more elegant than the previous one. Make sure to check that out too, as this function can be particularly useful in Python.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50801120
tagged with: cron
has body: I have a simple GUI (created using tkinter) that I want to run at a specific time of day on a Raspberry pi 3. Bellow is the code snippet I used in crontab. I invoked the crontab manager using sudo crontab -e. 0 18 * * * cd /home/pi/gui &amp;&amp; python3 gui.py For the moment, I can execute the GUI by invoking it directly via the Pi's command line. However, it doesn't work when I try to do it using cron. I also tried to switch to a basic python script (writing to a file) and that worked. Is there a specific weird interaction that I need to be aware of? My setup: raspberry pi 3, python 3, raspi-screen, tkinter (latest version as far as I know)
has title: Running a tkinter GUI using crontab
tagged with: python
has answer: http://stackoverflow.com/a/50915743
accepted answer: http://stackoverflow.com/a/50915743
score: 2
type: AnsweredQuestion
tagged with: tkinter
upvote count: 2
has answer: http://stackoverflow.com/a/59136913
type: Question
answer count: 2
tagged with: raspberry-pi
downvote count: 0
possible better answer: http://stackoverflow.com/a/59136913
favorite count: 0

http://stackoverflow.com/comment/88477394
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50734535
has text: as far as i know google speech API is blocked, try sphinx may be!!

http://stackoverflow.com/comment/88712036
comment on: http://stackoverflow.com/q/50854622
score: 0
has text: You better would use the dictionary mode I guess.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50822794
type: Answer
score: 0
has body: Solution I managed to get this sorted, my original way of doing this was working fine and it wasn't actually an issue with pickle at all. It appears that my initialisation vector when calling my decryption function differed from when it was originally encrypted. This still produced an identical string when decryption took place but must have included some differences i was unable to see. I've rewritten the ReadWrite class to make use of Read and Write functions rather than using pickle to dump the serialised/encrypted list into the file. I have also started writing the IV to an external so that it can be read by the decrypt method the next time the program loads. Thank you for any help and suggestions given.
answers question: http://stackoverflow.com/q/50813479

http://stackoverflow.com/comment/89116736
comment on: http://stackoverflow.com/a/50863060
type: Comment
has text: I am not seeing that it gets cancelled. I started 2 train agents and collected the operation object in 2 different variables. The first one did not get cancelled. I checked using object.done().
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88696051
comment on: http://stackoverflow.com/q/50845828
type: QuestionComment
type: Comment
score: 0
has text: If you put your code here, I can show you exactly how to fix it. But more generally, there are two answers: you can `from functools import partial` and then write `command=partial(myclick, a, b, c)`, or you can define a new function, either elsewhere with `def` or directly inline with `lambda`, like `command=lambda: myclick(a, b, c)`. Either way, you get a function that takes no arguments, and, when called, calls `myclick` with the values `a, b, c` as arguments.

http://stackoverflow.com/q/50746194
tagged with: metaclass
upvote count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/50746397
possible better answer: http://stackoverflow.com/a/50746324
type: Question
has answer: http://stackoverflow.com/a/50746324
has answer: http://stackoverflow.com/a/50746298
score: 0
has title: Unexpected behavior of setattr() inside Metaclass __init__
answer count: 3
favorite count: 0
tagged with: python-3.x
has body: Here is a basic Metaclass intending to provide a custom __init__: class D(type): def __init__(cls, name, bases, attributes): super(D, cls).__init__(name, bases, attributes) for hook in R.registered_hooks: setattr(cls, hook.__qualname__, hook) The for loop iterates over a list of functions, calling setattr(cls, hook.__qualname__, hook) for each of it. Here is a Class that use the above Metaclass: class E(metaclass=D): def __init__(self): pass The weird thing: E().__dict__ prints {} But when I call `E.__dict__ prints {'f1': &lt;function f1 at 0x001&gt;, 'f2': &lt;function f2 at 0x002&gt;}` I was expecting to add those function as attributes to the instance attributes, since the __init__ provides a custom initialization for a Class but it seems like the attributes were added to Class attributes. What is the cause of this and how can I add attributes to the instance, in this scenario? Thanks!
accepted answer: http://stackoverflow.com/a/50746298
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50840152
has body: As @ImportanceOfBeingErnest suggested, you should use locators to reformat the xtick labels. I have implemented them below: import matplotlib.pyplot as plt import pandas as pd import matplotlib.dates as mdates # For formatting dates fig, ax = plt.subplots(ncols=2, nrows=1, figsize=(15, 4.18)) # Make the original plot ax[0].plot(df["Date"][:322], df["Concentration"][:322], "+", color="red", linewidth=0.5) ax[0].set_title('Original plot') # New xticks plot months = mdates.MonthLocator() # Add tick every month days = mdates.DayLocator(range(1,32,5)) # Add tick every 5th day in a month monthFmt = mdates.DateFormatter('%b') # Use abbreviated month name # Add the locators to the axis ax[1].xaxis.set_major_locator(months) ax[1].xaxis.set_major_formatter(monthFmt) ax[1].xaxis.set_minor_locator(days) ax[1].plot(df["Date"][:322], df["Concentration"][:322], "+", color="red", linewidth=0.5) ax[1].set_title('Updated xticks') plt.show() Here are some helpful resources: The matplotlib.dates api strftime() directives This example, which I drew from heavily
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50822565
answers question: http://stackoverflow.com/q/50822565
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/88585410
type: AnswerComment
score: 0
type: Comment
has text: My code didn't work because the datatype of the Temp column was object, and the comparison was yielding incorrect values. But your solution worked
comment on: http://stackoverflow.com/a/50788572

http://stackoverflow.com/comment/88566821
type: QuestionComment
comment on: http://stackoverflow.com/q/50779986
has text: Add `print([i[0] for i in sorted(enumerate(a), key=lambda x:x[1])])` before `a.sort()`
score: 0
type: Comment

http://stackoverflow.com/a/50778153
has body: It looks like you are not using the right DataFrame method to get the list of tickets. Use DataFrame.to_dict('records') to simplify extraction of the ticket names. booking.csv 92747,true,Harry Potter 28479,false,Sherlock Holmes Python code import pandas as pd # Load ticket list from CSV file booking_df = pd.read_csv('booking.csv', names=['snum','booked','name']) # Convert ticket list to a list of built-in Python dictionaries ticket_list = booking_df.to_dict('records') # Extract the ticket names from the list of tickets ticket_name_set = {ticket["name"] for ticket in ticket_list} print('The following tickets are available; %s' % ticket_name_set) wanted_ticket_name = input('Which ticket would you like to buy? ') if wanted_ticket_name in ticket_name_set: print('Ok') else: print('Ticket Unavilable') Output: ➜ python tickets.py The following tickets are available; ['Harry Potter', 'Sherlock Holmes'] Which ticket would you like to buy? Harry Potter Ok ➜ python tickets.py The following tickets are available; ['Harry Potter', 'Sherlock Holmes'] Which ticket would you like to buy? Hamlet Ticket Unavilable
has comment: http://stackoverflow.com/comment/88563412
type: Answer
has comment: http://stackoverflow.com/comment/88563613
score: 0
answers question: http://stackoverflow.com/q/50778026

http://stackoverflow.com/a/50733153
accepted answer of: http://stackoverflow.com/q/50731879
upvote count: 1
answers question: http://stackoverflow.com/q/50731879
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88475456
type: AcceptedAnswer
downvote count: 0
has body: A related answer suggests the fix is to move the script out of directories with non-ASCII characters. Junctions/symlinks can also be used to 'fake' non-ASCII directory names, but that is considerably more complicated.

http://stackoverflow.com/comment/88586560
score: 0
comment on: http://stackoverflow.com/q/50790266
type: Comment
type: QuestionComment
has text: Write a function with the changing values as arguments.

http://stackoverflow.com/q/50824112
answer count: 1
has title: How to convert date format (whole column) and produce one more column with Quarter & Year
tagged with: formatting
tagged with: date
has answer: http://stackoverflow.com/a/50824241
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I have an excel file with a date column. Is there a way to change the date format to MM-DD-YY and create one more column with Quarter &amp; Year? I am very new to Python and I would really appreciate it if you could help me with this one. Thanks! Current format Date format: Jan 1, 2016 Desired outcome Date format: 01/01/2016 One more additional column with something like this "Q1-2016"
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: string-formatting
accepted answer: http://stackoverflow.com/a/50824241
upvote count: 1
tagged with: python

http://stackoverflow.com/q/50813479
score: 0
has comment: http://stackoverflow.com/comment/88633635
answer count: 1
has title: Python Pickle, Loading Issue when returning to list
type: UnansweredQuestion
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/88633231
type: Question
has body: I am using pickle to serialize a list of objects, encrypting the serialized string and then using pickle to dump it into a file so that I can be read out in reverse later. I understand this may be a round about way of doing things but in theory I cant seem to get my head around why when reloading the data it continues to fail. Let me first apologize for my horrendous naming conventions one day these will improve. I have dumped the code below, the error only occurs at the very end when loading the data back into the list and fails with the following error: Traceback (most recent call last): File "servertest.py", line 453, in &lt;module&gt; mylist = mary1.ReadFromFile() File "servertest.py", line 142, in ReadFromFile mrylist = pickle.loads(datastring) File "C:\Python27\lib\pickle.py", line 1388, in loads return Unpickler(file).load() File "C:\Python27\lib\pickle.py", line 864, in load dispatch[key](self) KeyError: '\xa7' I have printed the data out at each step when calling both the write and read functions and it appears to be fine: This is rawdata ]q ((c__main__ User q☺oq☻}q♥(U☻idq♦U♦daveq♣U♥pinq♠U☻22qub(h☺o}q (h♦U♦maryq h♠U♥434q♂ube. this is encrypt data '▼ES╬NZ┴w▲sæô▄Hó^┴☻½K◄6►ëΘ░¡√╡▼/ⁿ♀*a]ì╡ 5åα¬δ⌡D╓£o¶α{ô √■♣í♠.|H^E«√☼Hwñ/cúw╠Σ√↔↔╞╞┼3 this is enc data '▼ES╬NZ┴w▲sæô▄Hó^┴☻½K◄6►ëΘ░¡√╡▼/ⁿ♀*a]ì╡ 5åα¬δ⌡D╓£o¶α{ô √■♣í♠.|H^E«√☼Hwñ/cúw╠Σ√↔↔╞╞┼3 unencrypted data ]q ((c__main__ User q☺oq☻}q♥(U☻idq♦U♦daveq♣U♥pinq♠U☻22qub(h☺o}q (h♦U♦maryq h♠U♥434q♂ube. The following shows the two functions I'm using: def WriteToFile(self, mrlist): self.mrlist = mrlist rawdata = pickle.dumps(mrlist, 1) #print 'rawdata1\n' + rawdata #encrypt pickled list (call on my encryption functions) encrydata = self.encryptmessage.EncrMsg(rawdata) print('this is encrypt data \n ' + encrydata) #Open and dump encrypted string to file file=open(self.fn,"wb") pickle.dump(encrydata, file, 1) file.close() #Function to call when reading the file def ReadFromFile(self): mrylist = [] #open file and load file = open…
has answer: http://stackoverflow.com/a/50822794
has comment: http://stackoverflow.com/comment/88632431
tagged with: python-2.7

http://stackoverflow.com/comment/124230036
type: AnswerComment
comment on: http://stackoverflow.com/a/59770106
type: Comment
has text: This is correct and its works for me. Thank you so much @Nishad.
score: 1

http://stackoverflow.com/q/50783047
tagged with: opencv
has body: I used pip to install opencv3 with the following command on an Anaconda virtual environment. install opencv-python I successfully installed it because I can see the package in pip list. (olfatf)rover@rover_pi:/usr/lib/arm-linux-gnueabihf $ pip list | grep opencv opencv-python 3.4.0.14 However, when I do import cv2, I get the following error: (olfatf)rover@rover_pi:/usr/lib/arm-linux-gnueabihf $ python Python 3.4.3 |Continuum Analytics, Inc.| (default, Aug 21 2015, 00:53:08) [GCC 4.6.3] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/pi/.conda/envs/olfatf/lib/python3.4/site-packages/cv2/__init__.py", line 3, in &lt;module&gt; from .cv2 import * ImportError: libavformat.so.56: cannot open shared object file: No such file or directory I checked the /usr/lib/arm-linux-gnueabihf directory and I found: (olfatf)rover@rover_pi:/usr/lib/arm-linux-gnueabihf $ ls | grep libavformat libavformat.a libavformat.so libavformat.so.57 libavformat.so.57.56.101 I you can see there, I have the version 57 but the version 56 is missing. I did research online and people suggested that I should install libavformat-dev (olfatf)rover@rover_pi:/usr/lib/arm-linux-gnueabihf $ sudo apt-get install libavformat-dev Reading package lists... Done Building dependency tree Reading state information... Done libavformat-dev is already the newest version (7:3.2.10-1~deb9u1+rpt1). But it says that the package already exists. I also tried installing ffmpeg. (olfatf)rover@rover_pi:/usr/lib/arm-linux-gnueabihf $ sudo apt-get install ffmpeg Reading package lists... Done Building dependency tree Reading state information... Done ffmpeg is already the newest version (7:3.2.10-1~deb9u1+rpt1). But it says that the package already exists. How to get the 56 version? I use Raspberry Pi Strech
tagged with: anaconda
answer count: 1
downvote count: 0
has title: How to install libavformat.so.56 along with libavformat.so.57?
favorite count: 0
tagged with: package
tagged with: libavformat
tagged with: python
has answer: http://stackoverflow.com/a/50799181
accepted answer: http://stackoverflow.com/a/50799181
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/88455684
score: 1
comment on: http://stackoverflow.com/q/50723581
type: Comment
type: QuestionComment
has text: If you find you are not getting the answers you want, this could be a good question to split into 2. 1 for the regex, and 1 for airflow. I could see a regex pro not wanting to answer since they don't know airflow or vice versa.

http://stackoverflow.com/comment/88531159
comment on: http://stackoverflow.com/q/50761749
score: 1
has text: don't mix up python script directory and current execution directory. Where is `abc.txt` located? where the python script is?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50704350
has comment: http://stackoverflow.com/comment/88418567
type: Question
has body: My text file includes "SSS™" as one of its words and I am trying to find it using regular expression. My problem is with finding ™ superscript. My code is: import re path='G:\python_code\A.txt' f_general=open(path, 'r') special=re.findall(r'\U2122',f_general.read()) print(special) but it doesn't print anything. How can I fix it?
score: 0
answer count: 1
tagged with: superscript
tagged with: regex
has comment: http://stackoverflow.com/comment/88418742
type: UnansweredQuestion
tagged with: python
has title: Find TM superscript in python 2 using regex
has answer: http://stackoverflow.com/a/50705877

http://stackoverflow.com/comment/88424501
score: 0
has text: There is no one-to-one relationship between numeric IP addresses and names.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50707570

http://stackoverflow.com/q/50757953
tagged with: django
tagged with: python
has title: Django- How to view Generic views of a child class
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/50758534
has body: Basically what I am trying to do is view all the comments accompanied with a certain post This is my views.py from django.views import generic from .models import comment, article class IndexView(generic.ListView): template_name = 'newspaper/newspaper.html' context_object_name = 'articles' def get_queryset(self): return article.objects.order_by('-date') class ArticleDetailsView(generic.DetailView): template_name='newspaper/details.html' context_object_name = 'articles' def get_queryset(self): return article.objects.order_by('-date') class CommentsDetailsView(generic.DetailView): template_name='newspaper/details.html' context_object_name = 'comments' def get_queryset(self): return comment.objects.all() models.py from django.db import models from datetime import datetime class article(models.Model): title= models.CharField(max_length=150) body= models.TextField() date= models.DateField() author= models.CharField(max_length=150, default='') def __str__(self): return self.title + ' - ' + str(self.author) class comment(models.Model): main_article=models.ForeignKey('article',on_delete=models.CASCADE) text=models.TextField(default='Empty reply') date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.text urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)$',views.ArticleDetailsView.as_view(),name='articledetails'), url(r'^(?P<main_article_id>[0-9]+)$',views.CommentsDetailsView.as_view(),name='commentdetails'), ] and finally my html file {% extends "header.html" %} {% block title %} Article Details {% endblock %} {% block content %} {% if articles %} {{ articles.title}} {{ articles.body}} Posted on: {{ articles.date}} By: {{articles.author}} Replies {{ comments.count }} {% for y in comments %} {{ y.text}} On: {{ y.date}} {% endfor %} {% else %} There is no articles with the ID {% endif %} {% endblock %} I am just starting with generic vie…
type: Question
tagged with: django-models
accepted answer: http://stackoverflow.com/a/50758534
score: 0
answer count: 1

http://stackoverflow.com/comment/88411873
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50698982
has text: @OferSadan for dataset 1 (source data); here's 3 rows sample: WORD1 ! ? WORD2 < : ) ALT WORD3 A/C DEFFRED WORD5 WORD6 , 1-APU WORD2 ~ REPLACED % WORD3 @ DEF WORD4 ALT WORD5 , WORD1 WORD2 ALT BRK WORD3 WORD4
score: 0

http://stackoverflow.com/comment/88576933
type: AnswerComment
type: Comment
has text: @ᴀʀᴍᴀɴ What? How could it be more readable to reimplement zip in every place where you need it, instead of using the built-in function which everyone who ever used python understands?!
score: 2
comment on: http://stackoverflow.com/a/50785209

http://stackoverflow.com/a/50819926
type: Answer
has body: Try to use / isntead of \. Because / are use in Linux path and \ are use in Windows path.
score: 0
answers question: http://stackoverflow.com/q/50811723

http://stackoverflow.com/comment/88493856
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50742621
has text: You need to work out **how** your systems are going to communicate before working out **what** they will communicate
type: Comment

http://stackoverflow.com/a/50798990
has body: Yes; in Python one can make a list of lists, which would accomplish what you wish. You could either use your existing variables and set rows thus: rows = [row1, row2, row3, row4, row5, row6, row7] or you could simply dispense with the individual rows and set the 2D list in one go, thus: row1 = [[" -", " -", " -", " -", " -", " -", " -"], [" -", " -", " -", " -", " -", " -", " -"], [" -", " -", " -", " -", " -", " -", " -"], [" -", " -", " -", " -", " -", " -", " -"], [" -", " -", " -", " -", " -", " -", " -"], [" -", " -", " -", " -", " -", " -", " -"], [" -", " -", " -", " -", " -", " -", " -"]] Then you can access individual elements as you wished, using rows[2][4], and the like.
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50798909
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50798909

http://stackoverflow.com/comment/89035086
type: Comment
has text: The issue persists. All sub-commands have arguments with `_` (the entrypoint function name), instead `-`. The `replace()` did not worked.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50762991

http://stackoverflow.com/comment/88439650
type: QuestionComment
has text: Instead of posting an image of the error, please copy-paste the error. This will help future readers, search engines, and so on.
comment on: http://stackoverflow.com/q/50714496
score: 0
type: Comment

http://stackoverflow.com/comment/88438995
type: QuestionComment
comment on: http://stackoverflow.com/q/50714877
has text: Yes, but it's a module, not a class. But again, that's also how Java works. The only difference is the entry point into that file. And the fact that Python will execute all the source-code in a module, hence the use of `__name__ == '__main__'` to guard against executing code you might want to place inside a module but only want to execute it if it is the "main" module
type: Comment
score: 2

http://stackoverflow.com/comment/88495269
type: AnswerComment
type: Comment
score: 0
has text: ughh wow okay nice, I was messing with the .format() function but this works will accept
comment on: http://stackoverflow.com/a/50743800

http://stackoverflow.com/comment/88743664
has text: I'm on Windows.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50782056
score: 0

http://stackoverflow.com/comment/88651156
comment on: http://stackoverflow.com/a/50823020
has text: I will apply the decorated method right away and bring the results.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/61182159
upvote count: 2
type: Answer
has body: Seems like the thread is alive for quite long, and I guess you/others already managed, but for future viewers (like me), here's something to save a few minutes of your life: import numpy as np def unmasked_call(func): def func2(*args, **kwargs): with np.errstate(all='raise'): return func(*args, **kwargs) return func2 @unmasked_call def one(): print ("One:") return np.max([1, 2, np.nan]) print ("Starting") one()
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50845185

http://stackoverflow.com/q/50840899
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: list
tagged with: http://stackoverflow.com/tag/json
score: -1
has answer: http://stackoverflow.com/a/50840982
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/30928331
upvote count: 0
has title: Retrieve levels of a nested json
answer count: 1
duplicate of: http://stackoverflow.com/q/30928331
favorite count: 0
has comment: http://stackoverflow.com/comment/88685510
has body: Any techniques to know the number of levels that a nested JSON would contain? For eg: animals = [ { "animal" : { "type" : "bunny" } }, { "animal" : {} }, {} ]

http://stackoverflow.com/a/50796483
score: 1
has comment: http://stackoverflow.com/comment/88599148
has body: If a Favorite doesn't exist for an Item, this will raise because you're using get(). get() raises if an object is not found: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#django.db.models.query.QuerySet.get What I think you want is a combination of filter() and exists() like this: data = { 'is_fav': Favorite.objects.filter(user=request.user, item=favitem).exists(), }
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50796022
has comment: http://stackoverflow.com/comment/88599252
answers question: http://stackoverflow.com/q/50796022
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88538844
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50765631
score: 0
has text: @pault ah, thank you. I should have known better. That worked perfectly. If you turn this into an answer I can "accept it" if you want

http://stackoverflow.com/q/50788148
has title: Create empy pandas DataFrame with DateTimeIndex for random time delta values
possible better answer: http://stackoverflow.com/a/68790674
has comment: http://stackoverflow.com/comment/88582683
upvote count: 7
type: Question
accepted answer: http://stackoverflow.com/a/50790304
score: 7
has body: Im trying to create an empty DataFrame for which I will then constantly be appending rows to using the time stamp when the data arrives as index. This is to code I have so far: import pandas as pd import datetime df = pd.DataFrame(columns=['a','b'],index=pd.DatetimeIndex(freq='s')) df.loc[event.get_datetime()] = event.get_data() The problem Im having is with freq in the DateTimeIndex, the data is not arriving at any predefined intervalls, it is ju when some event tiggers. And also in the code above I need to specify a start and enddate for the index I dont want that I just want to be able to append rows whenever they arrive.
has comment: http://stackoverflow.com/comment/88583210
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88582635
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50790304
tagged with: python
has answer: http://stackoverflow.com/a/68790674
type: AnsweredQuestion

http://stackoverflow.com/comment/88591061
comment on: http://stackoverflow.com/a/50791262
has text: Thank you for your response. I tried what you suggested, and only the first row becomes part of the table. The other rows just display as a bunch of text below. Any suggestion for this?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50758200
downvote count: 0
accepted answer: http://stackoverflow.com/a/50758448
score: 1
favorite count: 0
has title: Using python to create an average out of a list of times in pandas
type: Question
tagged with: data-analysis
has body: I have a large number data. I need to average each fifteen minutes 'w'. Now I use for loop to execute,but it is so slow. pandas have any suite can help? I really need your help.Many thanks.
tagged with: python
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50758448
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/comment/88654972
has text: You have a dictionary, not a string pf data. So, just use dictionary indexing.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50825066

http://stackoverflow.com/q/50774222
tagged with: pandas
downvote count: 0
score: 7
has title: Parsing XML document into a pandas DataFrame
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/59074604
favorite count: 0
has answer: http://stackoverflow.com/a/50779743
tagged with: python
possible better answer: http://stackoverflow.com/a/50774403
answer count: 4
has body: I have an XML file that looks like this: <?xml version="1.0" encoding="utf-8"?> <row Id="1" PostId="2" Score="0" Text="(...)" CreationDate="2011-08-30T21:15:28.063" UserId="16" /> <row Id="2" PostId="17" Score="1" Text="(...)" CreationDate="2011-08-30T21:24:56.573" UserId="27" /> <row Id="3" PostId="26" Score="0" Text="(...)" UserId="9" /> What I'm trying to do is to extract ID, Text and CreationDate colums into pandas DF and I've tried following: import xml.etree.cElementTree as et import pandas as pd path = '/.../...' dfcols = ['ID', 'Text', 'CreationDate'] df_xml = pd.DataFrame(columns=dfcols) root = et.parse(path) rows = root.findall('.//row') for row in rows: ID = row.find('Id') text = row.find('Text') date = row.find('CreationDate') print(ID, text, date) df_xml = df_xml.append(pd.Series([ID, text, date], index=dfcols), ignore_index=True) print(df_xml) But the output is: None None None How do I fix this?
has answer: http://stackoverflow.com/a/50774403
type: AnsweredQuestion
upvote count: 7
accepted answer: http://stackoverflow.com/a/50779743
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/75206739
linked to: http://stackoverflow.com/q/36489576

http://stackoverflow.com/comment/88445188
score: 0
has text: Yes DEBUG is True
type: AnswerComment
comment on: http://stackoverflow.com/a/50710980
type: Comment

http://stackoverflow.com/comment/88499009
type: AnswerComment
has text: @ugabuga77 no problem. Have a nice day!
type: Comment
comment on: http://stackoverflow.com/a/50745121
score: 0

http://stackoverflow.com/comment/88614005
has text: you can't without some kind of memory.
score: 1
comment on: http://stackoverflow.com/q/50803988
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88587739
type: QuestionComment
comment on: http://stackoverflow.com/q/50790815
score: 0
has text: What do you expect in your signal function? what do you really want to do? I see what's wrong with your code, but I don't know what you want to do
type: Comment

http://stackoverflow.com/q/50843490
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88690930
has comment: http://stackoverflow.com/comment/88690716
has comment: http://stackoverflow.com/comment/88691450
has title: Access items in enumerate by index
type: Question
has body: As part of a project, I need to reference specific values in an iterable by their index. Unfortunately, this iterable doesn't have a __getitem__() method defined, so I don't have a way of directly doing this. So far, I've been using enumerate() to get the indices, but unfortunately that doesn't give me a subscriptable object (for reasons that I don't understand, the package I'm working with really doesn't like it when I cast the enumerate to a list either, so that option's out). So far my best solution is this: goodEvs=[(i,ev) for i,ev in enumerate(events) if i in flags] where flags is a list of the indices that I want to keep. Unfortunately, iterating through all of events takes a very long time, so I'd like to be able to do something like this: goodEvs=[events[i] for i in flags] but then I run into subscriptability problems. Sorry for the very weird and specific constraints, I think we're starting to stretch what this package can do (or I'm just bad at this). Thanks!
has comment: http://stackoverflow.com/comment/88691008
has answer: http://stackoverflow.com/a/50843796
has comment: http://stackoverflow.com/comment/88691502
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88690629
has comment: http://stackoverflow.com/comment/88692131
has comment: http://stackoverflow.com/comment/88690907

http://stackoverflow.com/comment/88517338
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50754300
has text: Maybe yes, not sure. I have this problem in some oldier pandas versions only.
type: Comment

http://stackoverflow.com/a/50742437
upvote count: 1
answers question: http://stackoverflow.com/q/50735112
score: 1
downvote count: 0
type: Answer
has body: Thanks to Mr.T I noticed that my understanding of curve fit was wrong. I thought it would iterate over the passed x- and y-data and enter each set of values into the function. In reality curve fit enters the hole x-data, which is a list / array. The function has to be able to handle that list / array itself, as Mr.T explained in his second comment. To solve my problem I just added a for-loop to my function that iterates over the x-data list / array. The return is now a list of values instead of a single value. One value for each x-data set. I'm not sure if that is the nicest solution but the working program is below. import numpy as np from scipy.optimize import curve_fit '''The function I want to optimize. 2D-xdata with 6 free parameters.''' def my_func(X, hx, hy, hz, lx, ly, lz): angles = [] for index in range(len(X)): # These are the two independently measured angles (2D-xdata). phi, alpha = X[index] # y-axis of the coordinate system. yaxis = np.array([[0], [1], [0]]) # First wanted vector h (first three parameters). h = np.array([[hx], [hy], [hz]]) # Second wanted vector l (last three parameters). l = np.array([[lx], [ly], [lz]]) # Projection matrix. Pxy = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]) # Needed to generate the rotation matrix around the unknown vector h. h_norm = h / np.linalg.norm(h) n1, n2, n3 = h_norm[0][0], h_norm[1][0], h_norm[2][0] # Rotation matrix for rotation around the vector h by angle alpha. R_h = np.array([[n1 ** 2 * (1 - np.cos(alpha)) + np.cos(alpha), n1 * n2 * (1 - np.cos(alpha)) - n3 * np.sin(alpha), n1 * n3 * (1 - np.cos(alpha)) + n2 * np.sin(alpha)], [n1 * n2 * (1 - np.cos(alpha)) + n3 * np.sin(alpha), n2 ** 2 * (1 - np.cos(alpha)) + np.cos(alpha), n2 * n3 * (1 - np.cos(alpha)) - n1 * np.sin(alpha)], [n1 * n3 * (1 - np.cos(alpha)) - n2 * np.sin(alpha), n2 * n3 * (1 - np.cos(alpha)) + n1 * np.sin(alpha), n3 ** 2 * (1 - np.cos(alpha)) + np.cos(alpha)]]) # Rotate the vector l around the vector h by angle alpha. l_rot = np.dot(R_h, l…

http://stackoverflow.com/comment/88654346
score: 0
comment on: http://stackoverflow.com/q/50824643
type: Comment
type: QuestionComment
has text: share your code - in its most compact form

http://stackoverflow.com/a/50853339
answers question: http://stackoverflow.com/q/50852088
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88733508
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50852088
has body: Using numpy slices: import numpy as np A = [[(1,1,1,4)], [(1,1,1,5)]] B = [[(2,2,2)], [(3,3,3)]] # A and B are tensors of order 3 A = np.array(A) B = np.array(B) print("A=") print(A) print("B=") print(B) C = np.copy(A) # assign along all 1st and 2nd dimensions, but only the first three elements of the third dimension C[:,:,0:3] = B print("C=") print(C) Output: A= [[[1 1 1 4]] [[1 1 1 5]]] B= [[[2 2 2]] [[3 3 3]]] C= [[[2 2 2 4]] [[3 3 3 5]]]

http://stackoverflow.com/comment/88591243
comment on: http://stackoverflow.com/a/50787869
type: AnswerComment
score: 0
type: Comment
has text: Now a tried the quick-n-dirty method, but still can get it working. My module code is now modified. I put 'move_right = False' before my function (check_key_events()) and then I declare 'global move_right' at the top inside the function. But it still won't make continuous moving. Guess it's because it still sets 'move_right' to false every time it runs the cycle in the while loop?

http://stackoverflow.com/comment/88674588
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50835156
has text: @Jontahan - We don't know, it varies between implementations. The C++ standard generally describes what should happen, not how to implement it.
type: Comment

http://stackoverflow.com/a/50788965
has body: If you want wikipedia sorted too then my_list = ['google.com', 'wikipedia.org/musics', 'facebook.com', 'wikipedia.org/Elon_Musk', 'fb.com'] list(sorted(my_list, key=lambda e: "00"+e if "wikipedia" in e else e))
answers question: http://stackoverflow.com/q/50788921
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50788921

http://stackoverflow.com/q/50824566
has body: Is there any way I can provide the filename for logger from my main module? I am using following way, however it's not working.all the logs go to xyz.log file rather than main.log Updated as per suggestion from nosklo logger.py formatter = logging.Formatter(fmt='[%(asctime)s] - {%(filename)s:%(lineno)d} %(levelname)s - %(message)s') def _get_file_handler(file_name="xyz.log"): file_handler = logging.FileHandler(file_name) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) return file_handler def get_logger(name): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.addHandler(_get_file_handler()) return logger parser.py log = logger.get_logger(__name__) def parse(): log.info("is there anyway this could go to main.log and xyz.log") main.py log = logger.get_logger(__name__) if __name__ == '__main__': for handler in log.handlers: if isinstance(handler, logging.FileHandler): log.removeHandler(handler) log.addHandler(logger._get_file_handler()) log.info("is there anyway this could go to main.log and xyz.log?") parser.parse() Is there a way I can set the Log file name from my main.py module and not from logger.py module?
type: UnansweredQuestion
tagged with: python
tagged with: logging
score: 4
has answer: http://stackoverflow.com/a/50824909
type: Question
has title: Python Logging: Provide log file path from main module
upvote count: 4
tagged with: python-2.7
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50824697
favorite count: 0

http://stackoverflow.com/a/50776384
has body: If you want to do this kind of "cooperative" polled-shutdown, you can use a threading.Event to signal: import threading import time def proc1(): while True: print("1") # payload time.sleep(1) # have we been signalled to stop? if not ev1.wait(0): break # do any shutdown etc. here print ("T1 exiting") ev1 = threading.Event() ev1.set() thread1 = threading.Thread(target=proc1) thread1.start() time.sleep(3) # signal thread1 to stop ev1.clear() But be aware that if the "payload" does something blocking like network or file IO, that op will not be interrupted. You can do those blocking ops with a timeout, but that obviously will complicate your code.
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/134836012
answers question: http://stackoverflow.com/q/50773086
score: 1
upvote count: 1

http://stackoverflow.com/q/50747733
has comment: http://stackoverflow.com/comment/88503157
type: Question
linked to: http://stackoverflow.com/q/2239737
possible better answer: http://stackoverflow.com/a/50747850
upvote count: 2
answer count: 2
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50747819
tagged with: isbn
has answer: http://stackoverflow.com/a/50747850
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I tried to create a python-based ISBN13 Validity Calculator, which is supposed to work according to the following snip of code. It takes in an argument of type string and prints the result. I don't understand where I got wrong here, In this program, common sense tells me num will give a 3 or a 1 alternatively. def isbncheck(isbn): num = int(0) for i in range(0,12): if num % 2 is 1: num = num + (int(isbn[i])*3) print(isbn[i] + " * 3 + at i=" + str(i)) elif num % 2 is 0: num = num + (int(isbn[i])) print(isbn[i] + " * 1 + at i=" + str(i)) else: print("Unhandled Exception.") print("_"*7) print(num) num = num%10 print(num) print(isbn[12]) print(int(isbn[12])) if num != int(isbn[12]): print("This is not valid") else: print("It is Valid.") print(isbncheck("9788177000252")) I expected the output to alternate factors of 1 and 3. Instead, I got this: 9 * 1 + at i=0 7 * 3 + at i=1 8 * 1 + at i=2 8 * 1 + at i=3 1 * 1 + at i=4 7 * 3 + at i=5 7 * 1 + at i=6 0 * 3 + at i=7 0 * 3 + at i=8 0 * 3 + at i=9 2 * 3 + at i=10 5 * 3 + at i=11 _______ 96 6 2 2 This is not valid None How do you work around it? Other than not expanding the loop?
has answer: http://stackoverflow.com/a/50747819
has title: Python Program not working as expected

http://stackoverflow.com/q/50806899
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/419163
has comment: http://stackoverflow.com/comment/88619703
has comment: http://stackoverflow.com/comment/88619652
answer count: 0
duplicate of: http://stackoverflow.com/q/419163
type: Question
tagged with: object
tagged with: oop
tagged with: class
score: 0
has title: Object Oriented Python, if __name__ == '__main__'?
has body: I am following a tutorial on wxPython and the tutorial shows the following code: class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size=(350, 250)) def main(): app = wx.App() ex = Example(None, title='Sizing') ex.Show() app.MainLoop() if __name__ == '__main__': main() I am assuming if __name__ == '__main__': main() is how the main() method is called but I am not really sure. Can someone explain what this bit of code does?
tagged with: python-3.x

http://stackoverflow.com/q/50844245
has comment: http://stackoverflow.com/comment/88754736
linked to: http://stackoverflow.com/q/3420122
downvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/16819222
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50844761
tagged with: python
tagged with: rss
score: 1
upvote count: 1
type: Question
has title: Python - how can I search a dictionary key to see if it contains a certain string
has body: I tried to word my question as best I could since I'm not sure if that is exactly what I am looking for, sorry in advance for that. I am parsing an RSS feed with feedparser. Based on the documentation, I was able to parse my results down to just the link to a certain vulnerability + its RSS post title. Here is my code: import feedparser # product variables ie = ['Internet Explorer', 'IE', 'Explorer', 'Internet_Explorer'] nix = ['Linux', 'SUSE', 'Red Hat', 'RHEL', 'Ubuntu', 'Debian_Linux'] win = ['Windows_'] # NVD RSS feed variable d = feedparser.parse('https://nvd.nist.gov/feeds/xml/cve/misc/nvd-rss- analyzed.xml') print("================================") print(d['feed']['title']) print("================================") for entry in d.entries: print(entry.title, entry.link) this will return results that look like this: CVE-2018-8132 (windows_10, windows_server_2016) https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2018-8132 I also tried just parsing the raw data, which is: for entry in d.entries: print(entry) Now this shows me that title is a key in a dictionary (I think) and the value is CVE-2018-8132 (windows_10, windows_server_2016) What I want to do, is an if statement that would be something like: if titlevalue contains a word (from the lists up top) then do something I couldn't find in feedparser's documentation how to do this. I'd really appreciate any help. EDIT (2018-06-15): I figured it out. Here is my code for whoever is looking for it in the future: # library imports import feedparser import re import smtplib import datetime import time # NVD RSS feed variable d = feedparser.parse('https://nvd.nist.gov/feeds/xml/cve/misc/nvd-rss- analyzed.xml') print("\n+++++++++++++++++++++++++++++++++++++++") print(d['feed']['title'], 'Scanner') print("+++++++++++++++++++++++++++++++++++++++\n") # function for iterating through the entries and printing out how many vulns there are def product_scan(product_name): # vulnerability links list vuln_list = [] # counte…

http://stackoverflow.com/a/50727501
has comment: http://stackoverflow.com/comment/88703265
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88687908
upvote count: 1
has body: I've tried to improve your groupby code, so this should be a lot faster. v = df.groupby(['ITEM', 'STORE'], sort=False).STOCK.diff() df['DELTA'] = np.where(np.isnan(v), 0, v) Some pointers/ideas here: Don't iterate over groups Don't pass series as the groupers if the series belong to the same DataFrame. Pass string labels instead. diff can be vectorized The last line is tantamount to a fillna, but fillna is slower than np.where Specifying sort=False will prevent the output from being sorted by grouper keys, improving performance further This can also be re-written as df['DELTA'] = df.groupby(['ITEM', 'STORE'], sort=False).STOCK.diff().fillna(0)
answers question: http://stackoverflow.com/q/50727342

http://stackoverflow.com/comment/88664454
score: 0
type: Comment
has text: this means that your use_pandas_script() returns an empty dataframe. please update your initial QUESTION and include the full use_pandas_script(), beginning with def and ending with return
type: AnswerComment
comment on: http://stackoverflow.com/a/50811816

http://stackoverflow.com/q/50753069
tagged with: spatial
has title: How to format numpy arrays?
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/50753462
has body: I have data that looks like this listL= array([array([-12939613.07220617, 3962855.50690994]), array([-12939614.67349505, 3962828.80807231]), array([-12939484.00289515, 3962828.1637531 ]), array([-12939484.98046737, 3962854.91251931]), print(type(listL)) -&gt; &lt;class 'numpy.ndarray'&gt; print(type(listL[0])) -&gt; &lt;class 'numpy.ndarray'&gt; print(type(listL[0][0])) -&gt; &lt;class 'numpy.float64'&gt; I have a second piece of data that looks like this: A = array([[ 73.87682896, 8.55827956], [ 57.43741519, 10.40224912], [ 87.88970753, 75.42971056], print(type(A)) -&gt; &lt;class 'numpy.ndarray'&gt; print(type(A[0])) -&gt; &lt;class 'numpy.ndarray'&gt; print(type(A[0][0])) -&gt; &lt;class 'numpy.float64'&gt; The types are the same across both sets of data, but I have a function that works with 'A', but not with 'listL' and I cannot figure out why. A[spatial.KDTree(A).query(coordinate)[1]] works, but listL[spatial.KDTree(listL).query(coordinate)[1]] returns the error: not enough values to unpack (expected 2, got 1)
type: AnsweredQuestion
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50753462
has comment: http://stackoverflow.com/comment/88514507
answer count: 1

http://stackoverflow.com/comment/88759939
has text: if dont like and not interested to share what u know about it, its welcomed , not your Damn Attitide. please keep away from commenting such things.. or please accept u dont know it. its better for us.
comment on: http://stackoverflow.com/q/50842356
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88570645
type: Comment
has text: @ChihebNexusI think as the condition of `if items. item == favitem:` is not true, program should be moving to `else` part. Is there is a known issue that would stop it from advancing to the next part in this case?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50781953

http://stackoverflow.com/comment/88657918
score: 3
type: Comment
type: QuestionComment
has text: JSON doesn't have a concept of a `u` in front of the strings. The string you have is not valid JSON. Is it actually a Python dictionary? You can probably use the `ast` module to load it if so.
comment on: http://stackoverflow.com/q/50826609

http://stackoverflow.com/q/50772605
tagged with: raspberry-pi3
tagged with: speech-recognition
favorite count: 0
has comment: http://stackoverflow.com/comment/88553144
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: voice-recognition
has body: I'm working on voice recognition system with Raspberry pi 3B and while running some code I face some problem which is given below. I was tried so many stuffs from the internet but couldn't found some specific problem so please help me about below error! ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline ALSA lib confmisc.c:1281:(snd_func_refer) Unable to find definition 'defaults.bluealsa.device' ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory ALSA lib conf.c:4996:(snd_config_expand) Args evaluate error: No such file or directory ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM bluealsa ALSA lib confmisc.c:1281:(snd_func_refer) Unable to find definition 'defaults.bluealsa.device' ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory ALSA lib conf.c:4996:(snd_config_expand) Args evaluate error: No such file or directory ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM bluealsa Cannot connect to server socket err = No such file or directory Cannot connect to server request channel jack server is not running or cannot be started JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM …
has answer: http://stackoverflow.com/a/50773330
score: 1
linked to: http://stackoverflow.com/q/48459712
type: Question
downvote count: 0
has title: Python3 OSError: [Errno -9988] Stream closed
answer count: 1

http://stackoverflow.com/comment/88475075
has text: hi , there is small edit . How I can Pass this one by one to response = index_faces(bucket, key) ?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50733655

jupyter-notebook
tags question: http://stackoverflow.com/q/50788168
tags question: http://stackoverflow.com/q/50844535
tags question: http://stackoverflow.com/q/50763033
tags question: http://stackoverflow.com/q/50782334
tags question: http://stackoverflow.com/q/50715262
tags question: http://stackoverflow.com/q/50763717
tags question: http://stackoverflow.com/q/50766976
tags question: http://stackoverflow.com/q/50854931
tags question: http://stackoverflow.com/q/50848644
tags question: http://stackoverflow.com/q/50749820
tags question: http://stackoverflow.com/q/50751554
tags question: http://stackoverflow.com/q/50796257
tags question: http://stackoverflow.com/q/50790266
tags question: http://stackoverflow.com/q/50806231
tags question: http://stackoverflow.com/q/50718109
tags question: http://stackoverflow.com/q/50818864
tags question: http://stackoverflow.com/q/50796722
tags question: http://stackoverflow.com/q/50772816
tags question: http://stackoverflow.com/q/50768396
tags question: http://stackoverflow.com/q/50839214
type: Tag
tags question: http://stackoverflow.com/q/50842160
tags question: http://stackoverflow.com/q/50833802
tags question: http://stackoverflow.com/q/50733688
tags question: http://stackoverflow.com/q/50766122
tags question: http://stackoverflow.com/q/50790348
tags question: http://stackoverflow.com/q/50743275
tags question: http://stackoverflow.com/q/50729599
tags question: http://stackoverflow.com/q/50729806
tags question: http://stackoverflow.com/q/50731262
tags question: http://stackoverflow.com/q/50789142
tags question: http://stackoverflow.com/q/50809564
tags question: http://stackoverflow.com/q/50785439
tags question: http://stackoverflow.com/q/50785665
tags question: http://stackoverflow.com/q/50805503
tags question: http://stackoverflow.com/q/50702983
tags question: http://stackoverflow.com/q/50816320
tags question: http://stackoverflow.com/q/50826305
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/50826750
tags question: http://stackoverflow.com/q/50703457
tags question: http://stackoverflow.com/q/50770394
tags question: http://stackoverflow.com/q/50735242
tags question: http://stackoverflow.com/q/50721735
tags question: http://stackoverflow.com/q/50791324

http://stackoverflow.com/comment/88743075
type: Comment
has text: I updated the answer with an example that shows how to compute `g`.
type: AnswerComment
comment on: http://stackoverflow.com/a/50861399
score: 0

pygobject
type: Tag
tags question: http://stackoverflow.com/q/50772119
tags question: http://stackoverflow.com/q/50813965
tags question: http://stackoverflow.com/q/50767260
tag name: pygobject

http://stackoverflow.com/q/50787891
type: Question
has body: I would like to clear noise from the upper part of the image as it is corrupt and in text recognition produce wrong results I would like to make letter/characters clear and also remove the box surround letter i used this code : def remove_boxes(image,flag=False): # threshold the gray image to binarize, and negate it _,binary = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY) if flag : binary = cv2.bitwise_not(binary) # find external contours of all shapes _,contours,_ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # create a mask for floodfill function, see documentation h,w,_= cropped_top.shape mask = np.zeros((h+2,w+2), np.uint8) # determine which contour belongs to a square or rectangle for cnt in contours: poly = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt,True),True) if len(poly) == 4: # if the contour has 4 vertices then floodfill that contour with black color cnt = np.vstack(cnt).squeeze() _,binary,_,_ = cv2.floodFill(binary, mask, tuple(cnt[0]), 0) # convert image back to original color if flag: binary = cv2.bitwise_not(binary) return binary but it failed in removing the box arround letter D
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: opencv
has title: python opencv clear noise and remove boxes
tagged with: opencv3.0
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/50802349
answer count: 1
has body: I would like to install PyV8. I install it via: sudo pip3 install pyv8 I receive error message: Collecting pyv8 Downloading https://files.pythonhosted.org/packages/c6/fb/5c0512a373e3d0aad0b683f439e7bdd67f95a69e6473b76dc2cfdca2c43f/PyV8-0.5.zip Installing collected packages: pyv8 Running setup.py install for pyv8 ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-0yqr1qf0/pyv8/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-u2aby1pu/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-3.5 copying PyV8.py -&gt; build/lib.linux-x86_64-3.5 running build_ext building '_PyV8' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/src x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DBOOST_PYTHON_STATIC_LIB -Ilib/python/inc -Ilib/boost/inc -Ilib/v8/inc -I/usr/include/python3.5m -c src/Exception.cpp -o build/temp.linux-x86_64-3.5/src/Exception.o cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ In file included from src/Exception.cpp:1:0: src/Exception.h:6:16: fatal error: v8.h: No such file or directory #include &lt;v8.h&gt; ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-0yqr1qf0/pyv8/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-u2aby1pu/install-record.txt --single-version-externally-m…
downvote count: 0
type: UnansweredQuestion
has title: PyV8 - error during installation
type: Question
tagged with: pyv8
score: 1
has answer: http://stackoverflow.com/a/53936940
favorite count: 0
has comment: http://stackoverflow.com/comment/112375978
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50818567
has comment: http://stackoverflow.com/comment/88663182
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50815936
has body: You are currently defining the local Application Entity, i.e. your own python code with the AE title "AETitle". In basic terms your application at the moment is saying "I am AETitle", not "I want to talk to AETitle" as it should, because the server is not recognising the called AE title. You have to add the called AE title as a third argument on your association method call. assoc = ae.associate(serverIP, port, "AEtitle") Otherwise pynetdicom3 will use some kind of internal default or empty value for the called AE title.
has comment: http://stackoverflow.com/comment/88709491
score: 5
has comment: http://stackoverflow.com/comment/88710017
type: AcceptedAnswer
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50815936
has comment: http://stackoverflow.com/comment/88665888

http://stackoverflow.com/comment/88537678
score: 0
type: QuestionComment
has text: @XuMuK I'm almost certain that this is a terrible idea to address whatever problem you're trying to overcome. Could you imagine if regular python builtins behaved like this? A class should have predictable behaviour, even if it's across a variety of scenarios, not the other way around.
type: Comment
comment on: http://stackoverflow.com/q/50764929

http://stackoverflow.com/comment/88664442
comment on: http://stackoverflow.com/q/50829278
has text: Also, what version of Python are you using? UTF-8 is the default encoding for source files starting in 3.4. (Thanks @IljaEverilä)
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88528588
type: QuestionComment
comment on: http://stackoverflow.com/q/50760341
type: Comment
has text: `i` is not used in your `while` loop, except for incrementing. This is a clear sign of bad design. The loop can be avoided completely. Also you know beforehand how many elements will be produced. Oh and btw.: `res` is a `list` and not a matrix!
score: 0

http://stackoverflow.com/q/50818042
has body: Got multiple txt files with filename providing what topic it contains. I need to read the files using glob and then create a data frame with 2 columns, 1 - contents and 2 - topic name (taken from file name) #filename sample - 51132_1.txt for name in gb.glob('./*_1*'): f1 = open(name,"r") rl = f1.readlines() topicName = name.split('_1')[0] #print(topicName) df = pd.DataFrame({'content':rl}) df['topicName'] = topicName print(df) Output: content topicName 0 .\54468 1 .\54468 2 In article &lt;sheafferC63zt0.Brs@netcom.com shea... .\54468 3 .\54468 4 .\54468 5 .\54468 6 It had to happen: the old allegation of the "d... .\54468 I am looking for a different output: content topicname blah blah 54468 blah blah2 51124 blah blah3 54468 How do I achieve this?
tagged with: python
tagged with: append
possible better answer: http://stackoverflow.com/a/50818290
has title: Python - Text Files Reading into a data frame and then appending with part of file name
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50818290
upvote count: 1
has answer: http://stackoverflow.com/a/50818387
type: Question
tagged with: dataframe
answer count: 2
accepted answer: http://stackoverflow.com/a/50818387
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/50715038
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: -1
tagged with: pynput
has title: Python Locking the mouse and keyboard
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50715223
linked to: http://stackoverflow.com/q/7529991
has body: I am writing a code in which I need to lock the user's input via mouse and keyboard. I am using sockets and when i get the message "LOCK" it should lock the computer and when I get the message "UNLOCK" it will unlock the user's PC. I've tried using the module pyhook but if I use this module then the program will stop and I cant receive info from the socket. I have also tried working with pynput but I couldn't find a way to lock the keyboard/ mouse.
duplicate of: http://stackoverflow.com/q/7529991

turtle-graphics
tags question: http://stackoverflow.com/q/50711550
tags question: http://stackoverflow.com/q/50709740
tags question: http://stackoverflow.com/q/50789854
tags question: http://stackoverflow.com/q/50780831
tags question: http://stackoverflow.com/q/50728410
tag name: turtle-graphics
type: Tag
tags question: http://stackoverflow.com/q/50771667
tags question: http://stackoverflow.com/q/50763348

http://stackoverflow.com/q/50774663
answer count: 1
has title: Iterate and compute over multiple dask arrays
tagged with: dask
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have multiple dask arrays and would like to save them to a GIF or some movie format using imageio one frame at a time, but I think the problem is generic enough that the solution could help other people. I'm wondering if there is a way to compute the arrays in order and while computing one array and writing it to disk, start computing the next one on the remaining workers. If possible, it would be nice if the scheduler/graph could share tasks between the dask arrays if any. The code would look something like this in my eyes: import dask.array as da writer = Writer(...) for dask_arr in da.compute([dask_arr1, dask_arr2, dask_arr3]): writer.write_frame(dask_arr) It looks like this is probably hackable by users with the distributed scheduler, but I'd like to use the threaded scheduler if possible. I'm also not sure if this is super useful in my exact real world case given memory usage or possibly having to write entire frames at a time instead of chunks. I also don't doubt that this could be handled in a custom array-like object with da.store...some how.
has answer: http://stackoverflow.com/a/50824610
type: Question
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50824610

http://stackoverflow.com/comment/88620767
comment on: http://stackoverflow.com/q/50806601
type: QuestionComment
type: Comment
score: 1
has text: It isn't worth wasting time trying to improve something that's taking a tiny minority of your total time. Assume we're reading the profiling right, the first thing to improve is your DB query. The second thing appears to be something to do with encoding the output—probably either the JSON encoding, or the UTF-8 encoding done as part of that, which probably means using a faster JSON encoder, unless you can redesign things to not write as much. Next appears to be parsing the query results. If you can optimize all of that to where your algorithm is a good chunk of what's left, worry about it.

http://stackoverflow.com/a/50701548
score: 0
has body: Pagination with Function-Based Views views.py from django.contrib.auth.models import User from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def index(request): user_list = User.objects.all() page = request.GET.get('page', 1) paginator = Paginator(user_list, 10) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'core/user_list.html', { 'users': users }) user_list.html &lt;table class="table table-bordered"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Username&lt;/th&gt; &lt;th&gt;First name&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {% for user in users %} &lt;tr&gt; &lt;td&gt;{{ user.username }}&lt;/td&gt; &lt;td&gt;{{ user.first_name }}&lt;/td&gt; &lt;td&gt;{{ user.email }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; {% if users.has_other_pages %} &lt;ul class="pagination"&gt; {% if users.has_previous %} &lt;li&gt;&lt;a href="?page={{ users.previous_page_number }}"&gt;&amp;laquo;&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class="disabled"&gt;&lt;span&gt;&amp;laquo;&lt;/span&gt;&lt;/li&gt; {% endif %} {% for i in users.paginator.page_range %} {% if users.number == i %} &lt;li class="active"&gt;&lt;span&gt;{{ i }} &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/span&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="?page={{ i }}"&gt;{{ i }}&lt;/a&gt;&lt;/li&gt; {% endif %} {% endfor %} {% if users.has_next %} &lt;li&gt;&lt;a href="?page={{ users.next_page_number }}"&gt;&amp;raquo;&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class="disabled"&gt;&lt;span&gt;&amp;raquo;&lt;/span&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; {% endif %}
type: Answer
answers question: http://stackoverflow.com/q/50700897

pyinstaller
tags question: http://stackoverflow.com/q/50773119
type: Tag
tags question: http://stackoverflow.com/q/50740133
tags question: http://stackoverflow.com/q/50808934
tag name: pyinstaller
tags question: http://stackoverflow.com/q/50711760
tags question: http://stackoverflow.com/q/50804416
tags question: http://stackoverflow.com/q/50817415
tags question: http://stackoverflow.com/q/50811545
tags question: http://stackoverflow.com/q/50753395
tags question: http://stackoverflow.com/q/50844709

http://stackoverflow.com/q/50812289
accepted answer: http://stackoverflow.com/a/50812890
tagged with: python
upvote count: 1
tagged with: tensorflow
possible better answer: http://stackoverflow.com/a/50816829
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50812890
has answer: http://stackoverflow.com/a/50816829
score: 1
has title: Tensorflow multiplication 3D tensor by 2D matrix
type: Question
answer count: 2
downvote count: 0
has body: I am trying multiply 3D tensor by 2D matrix, but with one unknown dimension. I checked all posts about that here, but without I don't found what I want. I have these parameters: T - shape (M,N) L - shape (?,M,M) F - shape (?, N) I want to do multiplication L * T * F with output shape (?,M). I tried expand dimensions etc. Unfortunately, I always lost ?-dimension. Thanks for any advice.
favorite count: 0

http://stackoverflow.com/comment/88558754
type: QuestionComment
comment on: http://stackoverflow.com/q/50775830
has text: A list is *iterable* but it's not an *iterator*, see e.g. https://stackoverflow.com/q/9884132/3001761
score: 0
type: Comment

http://stackoverflow.com/q/50808933
downvote count: 0
has answer: http://stackoverflow.com/a/50809062
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: Trying to modify a list based on multiple user inputs
tagged with: python
answer count: 4
score: 1
has answer: http://stackoverflow.com/a/50809174
type: Question
has body: I have a list of lists with products, price, and quantity [['apple', 'orange', 'banana'], [.50, .75, .20], [10,8,12]] I'm trying to permanently change the list based on asking the user which product they wish to update, if they wish to update the price or the quantity, and then update it how they choose
has answer: http://stackoverflow.com/a/50809194
has answer: http://stackoverflow.com/a/50808955
upvote count: 1

http://stackoverflow.com/comment/88673372
type: Comment
comment on: http://stackoverflow.com/a/50833883
type: AnswerComment
has text: only gives the result of one file in the folder which is strange
score: 0

http://stackoverflow.com/q/50714720
has comment: http://stackoverflow.com/comment/88444973
tagged with: python
linked to: http://stackoverflow.com/q/17743019
tagged with: logging
answer count: 0
has comment: http://stackoverflow.com/comment/88462171
has comment: http://stackoverflow.com/comment/88438283
has comment: http://stackoverflow.com/comment/88449117
has title: Flask logging to file - working locally but not on server
type: Question
has comment: http://stackoverflow.com/comment/88460578
tagged with: server
has comment: http://stackoverflow.com/comment/88459606
tagged with: flask
score: 0
has body: I am trying to diagnose some mysterious Internal Server Errors, so I added logging to the flask app. After digging through many explanations, I found this answer which I am using below, along with the suggestion to put everything inside a @app.before_first_request decorator. Locally this works as expected and werkzeuglog.log contains exactly what is printed to the screen. But on the server: The log file is created. Nothing is written to it. No errors are thrown, at least not to the user @app.before_first_request def initialize(): logger = logging.getLogger('werkzeug') logger.setLevel(logging.DEBUG) handler = logging.FileHandler('werkzeuglog.log') logger.addHandler(handler) if __name__ == '__main__': #run app app.run( host="0.0.0.0", port=int("80"), debug=False ) Am I doing something wrong or is this some server issue that is beyond my scope? Gentle answers appreciated! EDIT: Some context: An internal server error is caused when the user uploads a file and I am trying to figure out what's going wrong using the log. I don't think it can be an issue with permissions since the script definitely creates the file. I checked that the disk is not full. EDIT 2 I reran the run.fcgi file which starts the WSGI Server. Now the manual entries to the log file via logger.info('blah blah') show up but not the others i.e. GET POST etc. I don't have access to /var/log/nginx. It's a student-volunteer run server so I would like to give them as much info as I can. But this is all I have so far.
has comment: http://stackoverflow.com/comment/88461023
has comment: http://stackoverflow.com/comment/88450700
has comment: http://stackoverflow.com/comment/88438547
type: UnansweredQuestion

http://stackoverflow.com/a/50837267
type: Answer
answers question: http://stackoverflow.com/q/50836729
score: 2
has comment: http://stackoverflow.com/comment/88683020
has comment: http://stackoverflow.com/comment/88678735
accepted answer of: http://stackoverflow.com/q/50836729
has comment: http://stackoverflow.com/comment/88678949
type: AcceptedAnswer
has body: This will reset globals here is an example with itertools. import itertools from itertools import * from importlib import reload itools = reload(itertools) for k, v in itools.__dict__.items(): if k in globals(): globals()[k] = v
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88678778

http://stackoverflow.com/comment/88797113
type: Comment
has text: @c-z was this of any help? if so can you accept the answer. Thanks
comment on: http://stackoverflow.com/a/50806918
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88558905
has text: @OferSadan No, it doesn't. Lists are **iterables**, not **iterators**.
score: 0
comment on: http://stackoverflow.com/q/50775830
type: QuestionComment
type: Comment

machine-learning
tags question: http://stackoverflow.com/q/50767157
tags question: http://stackoverflow.com/q/50703359
tags question: http://stackoverflow.com/q/50723432
tags question: http://stackoverflow.com/q/50800085
tags question: http://stackoverflow.com/q/50788098
tags question: http://stackoverflow.com/q/50749588
tags question: http://stackoverflow.com/q/50834820
tags question: http://stackoverflow.com/q/50744565
tags question: http://stackoverflow.com/q/50828900
tags question: http://stackoverflow.com/q/50733342
tags question: http://stackoverflow.com/q/50755706
tags question: http://stackoverflow.com/q/50779773
tags question: http://stackoverflow.com/q/50707717
tags question: http://stackoverflow.com/q/50778953
tags question: http://stackoverflow.com/q/50708074
tags question: http://stackoverflow.com/q/50787555
tags question: http://stackoverflow.com/q/50782187
tags question: http://stackoverflow.com/q/50715928
tags question: http://stackoverflow.com/q/50724495
tags question: http://stackoverflow.com/q/50831358
tags question: http://stackoverflow.com/q/50753400
tags question: http://stackoverflow.com/q/50835327
tags question: http://stackoverflow.com/q/50829494
tags question: http://stackoverflow.com/q/50801434
tags question: http://stackoverflow.com/q/50780561
tags question: http://stackoverflow.com/q/50717791
tags question: http://stackoverflow.com/q/50720275
tags question: http://stackoverflow.com/q/50824819
tags question: http://stackoverflow.com/q/50740316
tags question: http://stackoverflow.com/q/50839758
tags question: http://stackoverflow.com/q/50750387
tags question: http://stackoverflow.com/q/50777658
tags question: http://stackoverflow.com/q/50849640
tag name: machine-learning
tags question: http://stackoverflow.com/q/50760834
tags question: http://stackoverflow.com/q/50809875
tags question: http://stackoverflow.com/q/50829631
tags question: http://stackoverflow.com/q/50747922
tags question: http://stackoverflow.com/q/50824643
tags question: http://stackoverflow.com/q/50820527
tags question: http://stackoverflow.com/q/50789508
tags question: http://stackoverflow.com/q/50761702
tags question: http://stackoverflow.com/q/50751207
tags question: http://stackoverflow.com/q/50714395
tags question: http://stackoverflow.com/q/50730555
tags question: http://stackoverflow.com/q/50710068
type: Tag
tags question: http://stackoverflow.com/q/50809513
tags question: http://stackoverflow.com/q/50840020
tags question: http://stackoverflow.com/q/50782030
tags question: http://stackoverflow.com/q/50712884
tags question: http://stackoverflow.com/q/50716561
tags question: http://stackoverflow.com/q/50832594
tags question: http://stackoverflow.com/q/50796024
tags question: http://stackoverflow.com/q/50721518
tags question: http://stackoverflow.com/q/50841462
tags question: http://stackoverflow.com/q/50706680
tags question: http://stackoverflow.com/q/50827435
tags question: http://stackoverflow.com/q/50848617
tags question: http://stackoverflow.com/q/50784756
tags question: http://stackoverflow.com/q/50774683
tags question: http://stackoverflow.com/q/50850477
tags question: http://stackoverflow.com/q/50715574
tags question: http://stackoverflow.com/q/50772949
tags question: http://stackoverflow.com/q/50806566
tags question: http://stackoverflow.com/q/50768511
tags question: http://stackoverflow.com/q/50784021
tags question: http://stackoverflow.com/q/50700007
tags question: http://stackoverflow.com/q/50826625
tags question: http://stackoverflow.com/q/50768864
tags question: http://stackoverflow.com/q/50758654
tags question: http://stackoverflow.com/q/50852294
tags question: http://stackoverflow.com/q/50741567
tags question: http://stackoverflow.com/q/50814066
tags question: http://stackoverflow.com/q/50732398
tags question: http://stackoverflow.com/q/50806953
tags question: http://stackoverflow.com/q/50721847
tags question: http://stackoverflow.com/q/50770467
tags question: http://stackoverflow.com/q/50800361
tags question: http://stackoverflow.com/q/50744505

http://stackoverflow.com/q/50735242
has body: I love the tqdm progress bar for its simplicity. I have noted however that there are cases, where each update of the progress bar is printed in a new line of a jupyter notebook like in the following screenshot: How can I make sure that the update of a tqdm progress bar is printed in the same line in a jupyter notebook like in the following screenshot: ?
upvote count: 5
has answer: http://stackoverflow.com/a/57174891
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
downvote count: 0
type: Question
score: 5
has title: progress bar update in the same line of a jupyter notebook
tagged with: tqdm
answer count: 1
accepted answer: http://stackoverflow.com/a/57174891
favorite count: 0

http://stackoverflow.com/q/50769850
has comment: http://stackoverflow.com/comment/88566758
has comment: http://stackoverflow.com/comment/88564560
has title: Unable to execute Python script on web server
tagged with: cgi
has body: I have the following HTML file located in the /test folder of my website: Enter the texts to be compared I have this Python script located in the /cgi-bin folder of my website: #!/usr/bin/python print('Content-type: text/html\r\n\r') I am able to access the HTML file using a web browser, but pressing the "Check!" button results in a 404 message. The CGI file has 755 execute permissions assigned to it. This is shared hosting, so I don't know for sure what features are installed or not. But CGI should at least work. I am new to Python. Is there a way to get this setup to work? Thanks.
type: Question
tagged with: webserver
has comment: http://stackoverflow.com/comment/88547296
has comment: http://stackoverflow.com/comment/88547205
score: 0
has comment: http://stackoverflow.com/comment/88547175
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88548145
tagged with: python
has answer: http://stackoverflow.com/a/50780027
has comment: http://stackoverflow.com/comment/88547271

http://stackoverflow.com/comment/88506986
has text: Can you post your attempt? Can you also clarify what "not working" means?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50749696
score: 2

http://stackoverflow.com/comment/88575992
type: Comment
has text: thanks @CoryKramer
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50784677

http://stackoverflow.com/comment/88702315
type: QuestionComment
comment on: http://stackoverflow.com/q/50849365
score: 0
has text: may be you can wait for an answer there. my guess, these are some c++ codes which create temporary python files which act like templates to execute the function
type: Comment

http://stackoverflow.com/comment/88442769
comment on: http://stackoverflow.com/a/50717029
has text: this code also print "[<__main__.X object at 0x01777D70>, <__main__.X object at 0x01777D90>]"
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88639210
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50817026
has text: It appears as if you're missing `from visual.controls import *`, just as the official guide says: http://vpython.org/contents/docs/controls.html
type: Comment

http://stackoverflow.com/q/50822986
has title: Numpy: function that creates block matrices
answer count: 4
has answer: http://stackoverflow.com/a/50824526
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88651170
upvote count: 3
has answer: http://stackoverflow.com/a/50824768
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88651145
possible better answer: http://stackoverflow.com/a/50824275
has comment: http://stackoverflow.com/comment/88651269
has answer: http://stackoverflow.com/a/50824275
accepted answer: http://stackoverflow.com/a/50824768
tagged with: matrix
downvote count: 0
has answer: http://stackoverflow.com/a/50823604
has body: Say I have a dimension k. What I'm looking for is a function that takes k as an input and returns the following block matrix. Let I be a k-dimensional identity matrix and 0 be k-dimensional square matrix of zeros That is: def function(k): ... return matrix function(2) -&gt; np.array([I, 0]) function(3) -&gt; np.array([[I,0,0] [0,I,0]]) function(4) -&gt; np.array([[I,0,0,0] [0,I,0,0], [0,0,I,0]]) function(5) -&gt; np.array([[I,0,0,0,0] [0,I,0,0,0], [0,0,I,0,0], [0,0,0,I,0]]) That is, the output is a (k-1,k) matrix where identity matrices are on the diagonal elements and zero matrices elsewhere. What I've tried: I know how to create any individual row, I just can't think of a way to put it into a function so that it takes a dimension, k, and spits out the matrix I need. e.g. np.block([[np.eye(3),np.zeros((3, 3)),np.zeros((3, 3))], [np.zeros((3, 3)),np.eye(3),np.zeros((3, 3))]]) Would be the desired output for k=3 scipy.linalg.block_diag seems like it might be on the right track...
has comment: http://stackoverflow.com/comment/88651274
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88651344
tagged with: python
has comment: http://stackoverflow.com/comment/88651247

http://stackoverflow.com/q/50711535
type: UnansweredQuestion
tagged with: python
upvote count: 4
downvote count: 0
type: Question
score: 4
has answer: http://stackoverflow.com/a/50711570
tagged with: pandas
has body: I have a csv file I imported and I have with 59 columns. I want to calculate the medians in each column. Each column has a mixture of NaN values and real integer values, as do the rows. I have to keep all records as each row has a valid measurement in it and if I drop the NaN values by column or row my data set is empty. I had set the NaN to zero but I could not get it to ignore the 0 values. Currently I have the site number and one other corresponding measure and removing NaN values for each column as an independent unit but this is very time consuming. Is there a better method to calculate median given data circumstances?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88431932
has title: How to calculate medians using pandas with NaN values?

http://stackoverflow.com/q/50806354
type: Question
tagged with: scikit-learn
tagged with: imputation
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50806988
favorite count: 0
has body: Is there a way for a Scikit-learn Imputer to look for and replace multiple values which are considered "missing values"? For example, I would like to do something like imp = Imputer(missing_values=(7,8,9)) But according to the docs, the missing_values parameter only accepts a single integer: missing_values : integer or “NaN”, optional (default=”NaN”) The placeholder for the missing values. All occurrences of missing_values will be imputed. For missing values encoded as np.nan, use the string value “NaN”.
tagged with: python
type: AnsweredQuestion
score: 3
has title: Scikit-learn Imputer with multiple values
accepted answer: http://stackoverflow.com/a/50806988
upvote count: 3
possible better answer: http://stackoverflow.com/a/71463521
has comment: http://stackoverflow.com/comment/88626230
has answer: http://stackoverflow.com/a/71463521

http://stackoverflow.com/q/50814291
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: selenium
has body: I am working with selenium webdriver to search and extract data from this site https://www.idealista.com/venta-viviendas/marbella-malaga/ I want to get a table with the price of each of the houses (class item_price), the number of rooms (class item_detail) and the sq. meters (class item_detail). I believe I have to use the driver.find_elements() method, but I don't know where to add it and how to make sure we add all prices, rooms and sq. meters in a table with three columns. I got this code so far but it doesn't work. I see FireFox going though pages but it seems it doesn't keep and store the data in houses.csv. Can anyone help? Thanks from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException import pandas as pd import csv import time driver = webdriver.Firefox() driver.get("https://www.idealista.com/venta-viviendas/marbella/las-chapas-el-rosario/") pages_remaining = True price = [] rooms = [] size = [] while pages_remaining: price = driver.find_elements_by_class_name("item-price") rooms = driver.find_elements_by_xpath("//*[contains(text(), 'hab.')]") size = driver.find_elements_by_xpath("//*[contains(text(), 'm²')]") houses = [price, rooms, size] try: # Checks if there are more pages with links next_link = driver.find_element_by_class_name("icon-arrow-right-after") next_link.click() time.sleep(10) except NoSuchElementException: rows_remaining = False with open('houses.csv', 'wb') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerows(houses) print(houses)
tagged with: webdriver
type: Question
has comment: http://stackoverflow.com/comment/88639284
has title: Extract data from site and different pages and save to csv
tagged with: export-to-csv
has comment: http://stackoverflow.com/comment/88637956
has comment: http://stackoverflow.com/comment/88638167
upvote count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88638288
has comment: http://stackoverflow.com/comment/88639198
tagged with: python
has comment: http://stackoverflow.com/comment/88635675
has comment: http://stackoverflow.com/comment/88633755

http://stackoverflow.com/q/50830909
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88673004
type: Question
tagged with: escaping
has answer: http://stackoverflow.com/a/50831048
has comment: http://stackoverflow.com/comment/88666170
has body: I'm trying to create a regular expression to get an entry in an XML file however when trying to run my script re.search() returns None even though I verify the file contains the entry characterCamos. This is my regular expression: &lt;characterCamos&gt;(\d*)&lt;/characterCamos&gt;. However, the backslash gets escaped and it becomes this: &lt;characterCamos&gt;(\\d*)&lt;/characterCamos&gt;. If I try to escape the backslash before entering it then it's still &lt;characterCamos&gt;(\\d*)&lt;/characterCamos&gt;. Either way this does not work and it doesn't capture the entry. How can I avoid this?
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50831048
tagged with: regex
has title: Python adding extra backslash to string?

http://stackoverflow.com/q/50841217
type: Question
has title: Python Decorator Casting Checker
has answer: http://stackoverflow.com/a/50841485
tagged with: casting
has comment: http://stackoverflow.com/comment/88686261
upvote count: 0
tagged with: types
has comment: http://stackoverflow.com/comment/88686256
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88686148
tagged with: python
score: -2
accepted answer: http://stackoverflow.com/a/50841485
type: AnsweredQuestion
has body: I've just written some code that works, but I'm not sure about the syntactic differences between the two. I'm writing code that will check to see if string inputs can be successfully casted into new variable types without ValueError. I'm using decorators to make DRY code as many types needed to evaluated. def typeCheck(castFunc): def newtypeChecker(input): try: variableType = castFunc(input) except ValueError: return False return True return newtypeChecker Using decorators: @typeCheck def is_float(input): return float @typeCheck def is_date(input): return pd.to_datetime @typeCheck def is_int(input): return int Not using decorators: is_int = typeCheck(int) is_date = typeCheck(pd.datetime) is_float = typeCheck(float) Performance is the same: is_int('14x') is_date('2006') is_float('Bob') Can someone explain if there are differences? Obviously decorator syntax seems cleaner.
downvote count: 2

http://stackoverflow.com/comment/88566447
score: 0
comment on: http://stackoverflow.com/q/50719204
type: Comment
type: QuestionComment
has text: Is it your full output file? For 10-label classification your model [should](https://github.com/dmlc/xgboost/issues/806#issuecomment-184066500) contain [n_estimators*10](https://github.com/dmlc/xgboost/issues/1746#issuecomment-267400592) trees, so it really looks strange

http://stackoverflow.com/comment/88632326
has text: No, it is not a default problem. The point is that you second item in sublists, is a string ou may it be a list? If yes, you can iterate over again in sublists. Another point, does order matter? Try to solve a problem each time.
type: Comment
comment on: http://stackoverflow.com/a/50808692
score: 0
type: AnswerComment

http://stackoverflow.com/q/50846694
type: Question
has body: Instead of many entries within a legend I'd like to add one text line which describes multiple lines. I'm looking to an automatic way to do this, instead of fiddling around with the coordinates of the according text object. Right now I'm using a function which takes the coordinates at which the text should start, a list of strings and a list of colors. Then the function assembles the strings using the colors. Is there a way to get the coordinates of an empty legend string (I just plot nothing with an empty label for that)? I tried something like this: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt x = np.linspace(0,6.19, 100) y = np.sin(x) ax = plt.gca() p1 = ax.plot(x,y, label="test") # list of text objects text = [mpl.text.Text(0,0,'$a=$'), mpl.text.Text(0,0,'$2$')] # HPacker of text objects # right way to get them into the legend? hp = mpl.offsetbox.HPacker(children=text) lgd = plt.legend([p1,??], ['legend1',??]) plt.show() Couldn't find out how to add the HPacker to the legend. Is the HPacker the right way to assemble (text-)objects horizontally for the usage as an item within a legend?
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
tagged with: matplotlib
has title: text with multiple colors in legend with matplotlib

http://stackoverflow.com/comment/88667167
score: 0
has text: Please don't edit the code in your question to working code. By doing this, the question becomes very confusing because you seem to have working code already. If you feel the way you managed to make it work is interesting to share please post it as an answer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50822206

http://stackoverflow.com/comment/88722401
comment on: http://stackoverflow.com/q/50846592
type: Comment
type: QuestionComment
has text: Just nothing...
score: 0

arrays
tags question: http://stackoverflow.com/q/50761930
tags question: http://stackoverflow.com/q/50769141
tags question: http://stackoverflow.com/q/50708767
tags question: http://stackoverflow.com/q/50852211
type: Tag
tags question: http://stackoverflow.com/q/50743769
tags question: http://stackoverflow.com/q/50822571
tags question: http://stackoverflow.com/q/50775529
tags question: http://stackoverflow.com/q/50819073
tags question: http://stackoverflow.com/q/50751902
tags question: http://stackoverflow.com/q/50705494
tags question: http://stackoverflow.com/q/50819267
tags question: http://stackoverflow.com/q/50765131
tags question: http://stackoverflow.com/q/50806693
tags question: http://stackoverflow.com/q/50786854
tags question: http://stackoverflow.com/q/50779346
tags question: http://stackoverflow.com/q/50821092
tags question: http://stackoverflow.com/q/50812491
tags question: http://stackoverflow.com/q/50833964
tags question: http://stackoverflow.com/q/50808757
tags question: http://stackoverflow.com/q/50853902
tags question: http://stackoverflow.com/q/50852088
tags question: http://stackoverflow.com/q/50781368
tags question: http://stackoverflow.com/q/50791275
tags question: http://stackoverflow.com/q/50787088
tags question: http://stackoverflow.com/q/50801900
tags question: http://stackoverflow.com/q/50762877
tags question: http://stackoverflow.com/q/50752098
tags question: http://stackoverflow.com/q/50735112
tag name: arrays
tags question: http://stackoverflow.com/q/50839212
tags question: http://stackoverflow.com/q/50825505
tags question: http://stackoverflow.com/q/50817371
tags question: http://stackoverflow.com/q/50832667
tags question: http://stackoverflow.com/q/50784474
tags question: http://stackoverflow.com/q/50742956
tags question: http://stackoverflow.com/q/50775708
tags question: http://stackoverflow.com/q/50706120
tags question: http://stackoverflow.com/q/50772944
tags question: http://stackoverflow.com/q/50825208
tags question: http://stackoverflow.com/q/50825618
tags question: http://stackoverflow.com/q/50810864
tags question: http://stackoverflow.com/q/50715934
tags question: http://stackoverflow.com/q/50751135
tags question: http://stackoverflow.com/q/50821728
tags question: http://stackoverflow.com/q/50756353
tags question: http://stackoverflow.com/q/50826608
tags question: http://stackoverflow.com/q/50801881
tags question: http://stackoverflow.com/q/50806043
tags question: http://stackoverflow.com/q/50762293
tags question: http://stackoverflow.com/q/50753405
tags question: http://stackoverflow.com/q/50801454
tags question: http://stackoverflow.com/q/50816850
tags question: http://stackoverflow.com/q/50752232
tags question: http://stackoverflow.com/q/50853691
tags question: http://stackoverflow.com/q/50848249
tags question: http://stackoverflow.com/q/50775532
tags question: http://stackoverflow.com/q/50819137
tags question: http://stackoverflow.com/q/50821376
tags question: http://stackoverflow.com/q/50774747
tags question: http://stackoverflow.com/q/50760341
tags question: http://stackoverflow.com/q/50760064
tags question: http://stackoverflow.com/q/50723384
tags question: http://stackoverflow.com/q/50756639
tags question: http://stackoverflow.com/q/50750987
tags question: http://stackoverflow.com/q/50779252
tags question: http://stackoverflow.com/q/50817659
tags question: http://stackoverflow.com/q/50829381
tags question: http://stackoverflow.com/q/50769864
tags question: http://stackoverflow.com/q/50757890
tags question: http://stackoverflow.com/q/50806917
tags question: http://stackoverflow.com/q/50704472
tags question: http://stackoverflow.com/q/50764477

http://stackoverflow.com/q/50777751
tagged with: python
downvote count: 1
has title: How to get list using sql query in python?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88562569
tagged with: psycopg
type: Question
answer count: 2
has body: I am defining a function here and making a query. def fetch(temp_pass,temp_accno): cur.execute('''SELECT id, name, acc_no, ph_no,address, email,balance FROM accounts WHERE id = %s and acc_no = %s''', (str(temp_pass), str(temp_accno))); row = cur.fetchall() print(row[2]) In this row should be a list of length 7 but when I run print(row[2]) it gives me error that list index out of range. This is the error I get File "Accounting.py", line 13, in fetch print(row[2]) IndexError: list index out of range
has comment: http://stackoverflow.com/comment/88562896
has answer: http://stackoverflow.com/a/50777966
tagged with: postgresql
score: 0
possible better answer: http://stackoverflow.com/a/50777813
has answer: http://stackoverflow.com/a/50777813
accepted answer: http://stackoverflow.com/a/50777966
favorite count: 0
has comment: http://stackoverflow.com/comment/88562904
has comment: http://stackoverflow.com/comment/88562596
tagged with: python-3.x
upvote count: 1

http://stackoverflow.com/comment/88497135
score: 0
type: Comment
type: QuestionComment
has text: It is not a copy per-se, the idea is not to have 2 arrays in the memory.
comment on: http://stackoverflow.com/q/50744693

http://stackoverflow.com/a/50790567
answers question: http://stackoverflow.com/q/50790554
downvote count: 0
has body: And that's the reason concept of local variable was invented. def getlist(a): d_list = [] b = int(a) + 7 c = [b, b + 9, b + 2*9, b + 3*9] for i in c: text = "%s" % i d_list.append(text) return d_list
score: 2
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88504878
score: 0
type: AnswerComment
has text: Mask 1 could be: `df.drop('Ticker', 1).notnull().all(1)`. I think also we could divide mask2 in two parts for readability. Other than that I think we are getting closer.
type: Comment
comment on: http://stackoverflow.com/a/50748636

http://stackoverflow.com/comment/88778056
comment on: http://stackoverflow.com/a/50824716
has text: Thank you for the response. I ended up recoding it anyways and it worked out. Here was my solution, if you are curious
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50830097
has body: Below is the code I tried but it runs with the error shown below from google.cloud import bigquery from google.cloud.language import enums from google.cloud.language import types import sys import six from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer client = bigquery.Client.from_service_account_json('simple_project//MQ News Matching-2443b471b5ff.json') with open('articles.txt',mode='r', encoding="utf8") as reader: text=reader.read() if isinstance(text,six.binary_type): text = text.decode('utf-8') document = types.Document(content=text.encode('utf-8'),type=enums.Document.Type.PLAIN_TEXT) # Detect and send native Python encoding to receive correct word offsets. encoding = enums.EncodingType.UTF32 if sys.maxunicode == 65535: encoding = enums.EncodingType.UTF16 result = client.analyze_entity_sentiment(document, encoding) sentiment = client.analyze_sentiment(document=document).document_sentiment print('Text: {}'.format(text)) print('Sentiment: {}, {}'.format(SentimentIntensityAnalyzer.score, sentiment.magnitude)) And the error I get is as below print('Sentiment: {}, {}'.format(SentimentIntensityAnalyzer.score, sentiment.magnitude)) AttributeError: type object 'SentimentIntensityAnalyzer' has no attribute 'score'
answer count: 1
has comment: http://stackoverflow.com/comment/88664438
has comment: http://stackoverflow.com/comment/88664499
accepted answer: http://stackoverflow.com/a/50830566
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Unable to print sentiment using google cloud natural language API
favorite count: 0
tagged with: python-3.x
tagged with: google-cloud-nl
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50830566
upvote count: 2

http://stackoverflow.com/q/50705511
downvote count: 0
has comment: http://stackoverflow.com/comment/88420366
has comment: http://stackoverflow.com/comment/88688693
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Shuttle Sort Iteration going back through list?? How?
has body: I'm trying to finish my implementation of the shuttle sort algorithm which if a swap of 2 adjacent items is made it will go back to check the other items. I can check adjacent items fine but how do I check the previous elements of the list using 2 for loops as shown in my code. Any help or suggestions on how to approach this implementation of the algorithm would be greatly appreciated. Thanks. def ShuttleSort(List): for i in range(len(List)): for j in range(len(List)-i): if j == 0: if List[j] &gt; List[j+1]: List[j],List[j+1] = list[j+1],List[j] else: pass elif List[j] &gt; List[j+1]: List[j],List[j+1] = list[j+1],List[j]
score: 2
answer count: 0
upvote count: 2
type: Question
tagged with: algorithm
tagged with: sorting
has comment: http://stackoverflow.com/comment/88420418
has comment: http://stackoverflow.com/comment/88420449

http://stackoverflow.com/comment/88587722
has text: Instead of trying to read your file which doesn't fit in your memory at once, you should treat it line by line.
comment on: http://stackoverflow.com/q/50790824
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88634882
type: Comment
type: QuestionComment
has text: Can you post your view also?
comment on: http://stackoverflow.com/q/50815061
score: 0

http://stackoverflow.com/comment/88699632
type: AnswerComment
comment on: http://stackoverflow.com/a/50847803
type: Comment
has text: @apoklyps3 You just map the button being clicked to a function. That function checks if the checkbox is ticked. The checkbox only will perform an action if the checkbox being clicked is mapped to a function.
score: 0

http://stackoverflow.com/q/50851888
has title: Does Extend function return a new list in Python?
linked to: http://stackoverflow.com/q/16641119
has answer: http://stackoverflow.com/a/50851948
score: -1
downvote count: 2
has body: I'm using extend function to add new item in a list. And gives me None in output. p=["a",1,"b",2,"c",3] a=p.extend(["d",4]) print(a) Output None Why It is giving none instead of ['a', 1, 'b', 2, 'c', 3, 'd', 4]
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88706517
tagged with: python
type: AnsweredQuestion
tagged with: list
duplicate of: http://stackoverflow.com/q/11205254
accepted answer: http://stackoverflow.com/a/50851948
type: Question

http://stackoverflow.com/q/50772882
has comment: http://stackoverflow.com/comment/88553442
score: 0
has comment: http://stackoverflow.com/comment/88553401
has comment: http://stackoverflow.com/comment/88555354
has comment: http://stackoverflow.com/comment/88554000
has comment: http://stackoverflow.com/comment/88554846
tagged with: log-likelihood
has comment: http://stackoverflow.com/comment/88553868
has comment: http://stackoverflow.com/comment/88553956
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88554703
has body: I am trying to maximize the following function: What my goal is to find the values of the vectors x and y, that maximize L. K_i^out and K_i^in are the in_degree and the out degree of a node i, in graph G, which are basically integers from 0 to 100. I read that the minimize function was good for this and therefor I wrote the following code: import networkx as nx import scipy as sp import numpy as np from scipy.optimize import minimize def f(z, n): frst_term = 0 # first term in B(43) scnd_term = 0 # second term in B(43) for i in range(n): # n is the amount of nodes in Graph G. frst_term += -G.out_degree(i)*np.log(z[i]) + -G.in_degree(i)*np.log(z[n+i]) #description of first term where z[i] is x_i and z[n+i] = y_i for j in range(n): if i == j: None else: scnd_term += np.log(1+z[i]*z[n+j]) #z[i] = x_i z[n+j] = y_j lik = (frst_term - scnd_term) #the total function return(lik) w = 2*n*[0.5] #my first guess max_val = minimize(f, w, args=(n)) print(max_val) From this I get the runtime warning invalid value encountered in log and invalid value encountered in reduce return umr_maximum(a, axis, None, out, keepdims) The x and y values are supposed to be all positive, and somewhere between 0 and 10 maximimum, mostly between 0 and 1 though. To conclude: do any of you have suggestions on how to improve this code or any other ways to solve this problem?
tagged with: python
has comment: http://stackoverflow.com/comment/88554733
has comment: http://stackoverflow.com/comment/88553830
linked to: http://stackoverflow.com/q/36229340
has comment: http://stackoverflow.com/comment/88554439
answer count: 0
tagged with: maximize
has title: finding values that maximize log likelihood in python
has comment: http://stackoverflow.com/comment/88554117
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/88554592

http://stackoverflow.com/a/50699263
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/88407687
has comment: http://stackoverflow.com/comment/88407719
score: 3
downvote count: 0
has body: Your for loop is perfectly Pythonic as it is. If you are OK with creating a new dictionary instead of modifying the existing one, you could either use a for loop: new_record = {} for k, v in record.items(): new_record[k] = float(v) if isinstance(v, Decimal) else v or shorten it to a dict comprehension: record = {k: float(v) if isinstance(v, Decimal) else v for k, v in record.items()} Creating a new dictionary this way has the advantage that it allows you to filter out keys and add new keys in the same loop, should you ever need to.
answers question: http://stackoverflow.com/q/50699113
has comment: http://stackoverflow.com/comment/88408118

parsing
tags question: http://stackoverflow.com/q/50710251
tags question: http://stackoverflow.com/q/50789834
tags question: http://stackoverflow.com/q/50712197
tags question: http://stackoverflow.com/q/50847245
tag name: parsing
tags question: http://stackoverflow.com/q/50795252
tags question: http://stackoverflow.com/q/50714609
tags question: http://stackoverflow.com/q/50721525
type: Tag
tags question: http://stackoverflow.com/q/50739241
tags question: http://stackoverflow.com/q/50731313
tags question: http://stackoverflow.com/q/50827221
tags question: http://stackoverflow.com/q/50731989
tags question: http://stackoverflow.com/q/50804368
tags question: http://stackoverflow.com/q/50847058
tags question: http://stackoverflow.com/q/50852723
tags question: http://stackoverflow.com/q/50830140
tags question: http://stackoverflow.com/q/50734530
tags question: http://stackoverflow.com/q/50845282

http://stackoverflow.com/comment/88642822
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50815789
type: QuestionComment
has text: How many of these ball pairs will be existing at the same time?

http://stackoverflow.com/q/50735626
has title: TypeError: list object is not an iterator
has comment: http://stackoverflow.com/comment/88479037
score: 33
possible better answer: http://stackoverflow.com/a/50735994
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50735697
accepted answer: http://stackoverflow.com/a/50735697
duplicate of: http://stackoverflow.com/q/12319025
upvote count: 34
tagged with: flask
linked to: http://stackoverflow.com/q/12319025
has answer: http://stackoverflow.com/a/50735994
favorite count: 0
has body: Am trying to make a simple post api in flask-python but am getting this error : TypeError: list object is not an iterator but when i revise my code seems fine what could be the problem. My function which specifically has the problem: def post(self,name): #return {'message': name} item = next(filter(lambda x: x['name'] == name, items), None) if item: return {'message':"An item with name '{}' already exixts. ".format(name)},400 data = request.get_json() item = {'name': name, 'price':data['price']} items.append(item) return item, 201 When i try to post something on postman i get this logcat error: [2018-06-07 10:41:02,849] ERROR in app: Exception on /item/test [POST] Traceback (most recent call last): File "C:\Python27\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Python27\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 480, in wrapper resp = resource(*args, **kwargs) File "C:\Python27\lib\site-packages\flask\views.py", line 84, in view return self.dispatch_request(*args, **kwargs) File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request resp = meth(*args, **kwargs) File "G:\flask_workspace\MealBookingApp\MealBookingApp\MealBookingApp\views.py", line 30, in post item = next(filter(lambda x: x['name'] == name, items), None) TypeError: list object is not an iterator 127.0.0.1 - - [07/Jun/2018 10:41:02] "POST /item/test HTTP/1.1" 500 - NB: line 30 , is the line below : item = next(filter(lambda x: x['name'] == name, items), None)
tagged with: python
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/88643740
comment on: http://stackoverflow.com/q/50819180
type: Comment
type: QuestionComment
has text: Possible duplicate of [Make division by zero equal to zero](https://stackoverflow.com/questions/27317517/make-division-by-zero-equal-to-zero)
score: 1

http://stackoverflow.com/q/50713828
tagged with: python-2.7
answer count: 3
has comment: http://stackoverflow.com/comment/88440958
tagged with: python
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/88438133
has answer: http://stackoverflow.com/a/50715575
accepted answer: http://stackoverflow.com/a/50751069
has answer: http://stackoverflow.com/a/50725508
has title: Why does the result of scipy.sparse.csc_matrix.sum() change its type to numpy matrix?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50715575
downvote count: 0
has comment: http://stackoverflow.com/comment/88442012
has answer: http://stackoverflow.com/a/50751069
has comment: http://stackoverflow.com/comment/88438556
tagged with: scipy
type: Question
tagged with: numpy
score: 5
has body: I want to generate a large sparse matrix and sum it but I encounter MemoryError a lot. So I tried the operation via scipy.sparse.csc_matrix.sum instead but found that the type of data changed back to a numpy matrix after taking the sum. window = 10 np.random.seed = 0 mat = sparse.csc_matrix(np.random.rand(100, 120)&gt;0.5, dtype='d') print type(mat) &gt;&gt;&gt; &lt;class 'scipy.sparse.csc.csc_matrix'&gt; mat_head = mat[:,0:window].sum(axis=1) print type(mat_head) &gt;&gt;&gt; &lt;class 'numpy.matrixlib.defmatrix.matrix'&gt; So I generated mat as zeros matrix just to test the result when mat_head is all zeros. mat = sparse.csc_matrix((100,120)) print type(mat) &gt;&gt;&gt; &lt;class 'scipy.sparse.csc.csc_matrix'&gt; mat_head = mat.sum(axis=1) print type(mat_head) &gt;&gt;&gt; &lt;class 'numpy.matrixlib.defmatrix.matrix'&gt; print np.count_nonzero(mat_head) &gt;&gt;&gt; 0 Why does this happen? So sum via scipy.sparse is not benefited for preserving memory than numpy as they change the data type back anyway?
has comment: http://stackoverflow.com/comment/88446240
tagged with: sparse-matrix

brute-force
tags question: http://stackoverflow.com/q/50742396
tag name: brute-force
type: Tag

http://stackoverflow.com/comment/88569473
type: Comment
has text: result is ('the number of prime numbers are:', 91) for both programs.
comment on: http://stackoverflow.com/a/50781293
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88563620
score: 1
comment on: http://stackoverflow.com/q/50778302
has text: Your implementation is suffering from the performance issues associated with concatenating immutable strings in a for loop like this; the behavior is polynomial time. However, I suspect that the peep-hole optimizer in the CPython runtime is able to optimize the version with the temporary variable. This is an implementation detail that shouldn't be relied on. Use `messages.append("")` then `'\n'.join(messages)`
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50835651
upvote count: 3
score: 3
has body: I guess this Link partially answers your question: https://twittercommunity.com/t/upcoming-changes-to-the-developer-platform/104603 According to the new new EU privacy laws, Timezone values in Twitter user objects will become private fields after May 23.
answers question: http://stackoverflow.com/q/50830126
downvote count: 0
type: Answer

http://stackoverflow.com/a/50818699
accepted answer of: http://stackoverflow.com/q/50818465
has comment: http://stackoverflow.com/comment/88643605
answers question: http://stackoverflow.com/q/50818465
has body: There are two "points" to supporting distinct stout and stderr streams: When you are writing applications that can be chained together (e.g. using pipelines) you don't want the "normal" output to get mixed up with errors, warnings, debug info and other "chit chat". Mixing them in the same stream would make life difficult for the next program in the chain / pipeline. Example: $ cat some-file | grep not $ echo $? If the cat command did not write its error messages to stderr, then the grep command would see a "file not found" message if "some-file" did not exist. It would then (incorrectly) match on the "not", and set the return code for the pipeline incorrectly. Constructing pipelines that coped with this sort of thing would be hellishly difficult. Separate stdout and stderr streams have been support in (at least) UNIX and UNIX-like system since ... umm ... the 1970's. And they are part of the POSIX standard. If a new programming language's runtime libraries did not support this, then it would be considered to be crippled; i.e. unsuitable for writing production quality applications. (In the history of programming languages, Python is still relatively new.) However, nobody is forcing to write your applications to use stderr for its intended purpose. (Well ... maybe your future co-workers will :-) )
has comment: http://stackoverflow.com/comment/88642966
upvote count: 5
has comment: http://stackoverflow.com/comment/88643507
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88643418
has comment: http://stackoverflow.com/comment/88643042
score: 5
type: Answer

http://stackoverflow.com/q/50724377
tagged with: python
has comment: http://stackoverflow.com/comment/88474288
tagged with: conv-neural-network
upvote count: 3
tagged with: tensorflow
type: Question
has title: Cost remains same at 0.6932 in Siamese Network
score: 3
linked to: http://stackoverflow.com/q/36392952
answer count: 1
downvote count: 0
has body: I am trying to implement a Siamese Network, as in this paper In this paper, they have used cross entropy for the Loss function I am using STL-10 Dataset for training and instead of the 3 layer network used in the paper, I replaced it with VGG-13 CNN network, except the last logit layer. Here is my loss function code def loss(pred,true_pred): cross_entropy_loss = tf.multiply(-1.0,tf.reduce_mean(tf.add(tf.multiply(true_pred,tf.log(pred)),tf.multiply((1-true_pred),tf.log(tf.subtract(1.0,pred)))))) total_loss = tf.add(tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)),cross_entropy_loss,name='total_loss') return cross_entropy_loss,total_loss with tf.device('/gpu:0'): h1 = siamese(feed_image1) h2 = siamese(feed_image2) l1_dist = tf.abs(tf.subtract(h1,h2)) with tf.variable_scope('pred') as scope: predictions = tf.contrib.layers.fully_connected(l1_dist,1,activation_fn = tf.sigmoid,weights_initializer = tf.contrib.layers.xavier_initializer(uniform=False),weights_regularizer = tf.contrib.layers.l2_regularizer(tf.constant(0.001, dtype=tf.float32))) celoss,cost = loss(predictions,feed_labels) with tf.variable_scope('adam_optimizer') as scope: optimizer = tf.train.AdamOptimizer(learning_rate=0.001) opt = optimizer.minimize(cost) However, when I run the training, the cost remains almost constant at 0.6932 I have used Adam Optimizer here. But previously I used Momentum Optimizer. I have tried changing the learning rate but the cost still behaves the same. And all the prediction values converge to 0.5 after a few iterations. After taking the output for two batches of images (input1 and input2), I take their L1 distance and to that I have connected a fully connected layer with a single output and sigmoid activation function. [h1 and h2 contains the output of the last fully connected layer(not the logit layer) of the VGG-13 network] Since the output activation function is sigmoid, and since the prediction values are around 0.5, we can calculate and say that the sum…
favorite count: 0
has answer: http://stackoverflow.com/a/53577756
type: UnansweredQuestion

http://stackoverflow.com/comment/94250316
score: 0
type: Comment
type: QuestionComment
has text: The most time you spend on **read\write** operation. Try to use [codecs.open](https://docs.python.org/2/library/codecs.html#codecs.open) instead of `io` library, it works faster.
comment on: http://stackoverflow.com/q/50801202

http://stackoverflow.com/a/51003128
type: Answer
answers question: http://stackoverflow.com/q/50831551
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91836148
type: AcceptedAnswer
has body: Thanks to @jp2011 for pointing to pygmo First, worth noting the difference from pygmo 1, since the fist link on google still directs to the older version. Second, Multiprocessing island are available only for python 3.4+ Third, it works. The processes I started when I first asked the question are still running while I write, the pygmo archipelago running an extensive test of all the 18 possible DE variations present in saDE made in less than 3h. The compiled version using Numba as suggested here https://esa.github.io/pagmo2/docs/python/tutorials/coding_udp_simple.html will probably finish even earlier. Chapeau. I personally find it a bit less intuitive than the scipy version, given the need to build a new class (vs a signle function in scipy) to define the problem but is probably just a personal preference. Also, the mutation/crossing over parameters are defined less clearly, for someone approaching DE for the first time might be a bit obscure. But, since serial DE in scipy just isn't cutting it, welcome pygmo(2). Additionally I found a couple other options claiming to parallelize DE. I didn't test them myself, but might be useful to someone stumbling on this question. Platypus, focused on multiobjective evolutionary algorithms https://github.com/Project-Platypus/Platypus Yabox https://github.com/pablormier/yabox from Yabox creator a detailed, yet IMHO crystal clear, explaination of DE https://pablormier.github.io/2017/09/05/a-tutorial-on-differential-evolution-with-python/
score: 4
accepted answer of: http://stackoverflow.com/q/50831551

http://stackoverflow.com/q/50841994
answer count: 1
has comment: http://stackoverflow.com/comment/88687598
favorite count: 0
has answer: http://stackoverflow.com/a/50845572
accepted answer: http://stackoverflow.com/a/50845572
tagged with: python
tagged with: dictionary
tagged with: dataflow
has body: I am trying to convert a JSON file into a dictionary and apply key/value pairs, so I can then use groupbykey() to basically deduplicate the key/value pairs. This is the original content of the file: {"tax_pd":"200003","ein":"720378282"} {"tax_pd":"200012","ein":"274027765"} {"tax_pd":"200012","ein":"042746989"} {"tax_pd":"200012","ein":"205993971"} I have formatted it like so: (u'201208', u'010620100') (u'201208', u'860785769') (u'201208', u'371650138') (u'201208', u'237253410') I want to turn these into key/value pairs, so I can apply GroupByKey, in my Dataflow Pipeline. I believe i need to turn it into a dictionary first? I'm new to python and the google cloud applications and some help would be great! EDIT : Code snippets with beam.Pipeline(options=pipeline_options) as p: (p | 'ReadInputText' &gt;&gt; beam.io.ReadFromText(known_args.input) | 'YieldWords' &gt;&gt; beam.ParDo(ExtractWordsFn()) # | 'GroupByKey' &gt;&gt; beam.GroupByKey() | 'WriteInputText' &gt;&gt; beam.io.WriteToText(known_args.output)) class ExtractWordsFn(beam.DoFn): def process(self, element): words = re.findall(r'[0-9]+', element) yield tuple(words)
downvote count: 0
has title: python list to dictionary for dataflow
score: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88691395
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88692205
tagged with: google-cloud-platform
upvote count: 1
has comment: http://stackoverflow.com/comment/88687601

http://stackoverflow.com/comment/88574158
score: 2
has text: You need to calculate the total *after* setting the tax value.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50783835

http://stackoverflow.com/q/50788794
tagged with: openshift
tagged with: bots
has answer: http://stackoverflow.com/a/50788889
has body: To run InstaBot locally, you just clone the repo, install the requirements.txt, put in your login credentials in example.py, and run python example.py. I do not know how this translates to OpenShift. Let's say you push your code to your own GitHub repo with the login credentials in environment variables (in an git ignored file). You can set environment variables on the OpenShift dashboard, but where's the part where you specify python example.py?
type: Question
score: 0
answer count: 1
has title: How do you run InstaBot.py on OpenShift?
tagged with: redhat
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88575842
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50784660
type: QuestionComment
has text: Your question is broad. Can you be more specific? Pick a couple of websites. Show us your code you tried. Where you got stuck. What you want as the result. See also [mcve].

http://stackoverflow.com/q/50816361
has answer: http://stackoverflow.com/a/50816446
type: Question
has comment: http://stackoverflow.com/comment/88639035
has comment: http://stackoverflow.com/comment/88638428
score: 0
linked to: http://stackoverflow.com/q/285061
has body: import json class Myclass(): def __init__(self): with open("file_name.json", "r") as read_file: data = json.load(read_file) for key in data: print key key = getattr(self,'func_name') def func_name(self,arg): print "Pass" obj = Myclass() obj.func_name("test") obj.key_from_file("test") Output: key_from_file Pass Traceback (most recent call last): File "get_at.py", line 22, in &lt;module&gt; obj.key_from_file("test") AttributeError: Myclass instance has no attribute 'key_from_file' I want to dynamically map all key in json file to func_name, so whenever we call obj.key_from_file("test") which should call obj.func_name("test") How to do that ?
upvote count: 1
answer count: 1
downvote count: 1
has title: dynamically mapping function name using getattr in python
favorite count: 0
has comment: http://stackoverflow.com/comment/88637857
accepted answer: http://stackoverflow.com/a/50816446
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88535264
has text: Please don't use answers to post comments.
type: Comment
comment on: http://stackoverflow.com/a/50763782
score: 1
type: AnswerComment

http://stackoverflow.com/q/50806659
accepted answer: http://stackoverflow.com/a/50806680
tagged with: pandas
downvote count: 0
answer count: 1
has body: I am having some trouble with the wide_to_long function. This example works fine: Loc Nom Meas-1 Meas-2 Meas-3 200 A 0.8 1.1 1.2 201 B 4.9 5.1 5.2 pd.wide_to_long(df, 'Meas', i=['Loc','Nom'], j='Ref', sep='-').reset_index() Loc Nom Meas Ref 200 A 0.8 1 200 A 1.1 2 200 A 1.2 3 201 B 4.9 1 201 B 5.1 2 201 B 5.2 3 My problem is that the string that follows "Meas-" in my dataframe is a random, alpha-numeric serial number. A basic example: Loc Nom Meas-1 Meas-2D Meas-3 200 A 0.8 1.1 1.2 201 B 4.9 5.1 5.2 pd.wide_to_long(df, 'Meas', i=['Loc','Nom'], j='Ref', sep='-').reset_index() Loc Nom Meas Meas-2D Ref 200 A 0.8 1.1 1 200 A 1.2 1.1 3 201 B 4.9 5.1 1 201 B 5.2 5.1 3 Worse, if all of the "Meas-" parts are followed by strings containing letters, I get an empty dataframe error: Loc Nom Meas-1D Meas-2D Meas-3D 200 A 0.8 1.1 1.2 201 B 4.9 5.1 5.2 pd.wide_to_long(df, 'Meas', i=['Loc','Nom'], j='Ref', sep='-').reset_index() Empty DataFrame How can I get this function to use whatever string follows "Meas-" for Ref, and not only numbers? Thanks!
favorite count: 0
has comment: http://stackoverflow.com/comment/88619166
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/50806680
type: Question
has title: Pandas wide_to_long with random id variables

http://stackoverflow.com/comment/88432229
type: QuestionComment
has text: Once you call `mainloop()`, the GUI starts up, and you don't get to the rest of the program until you exit the GUI. And you're doing it way up at the top of your method, so the rest of your code never gets to run. You've also got a bunch of other problems in your code (`self.main_window` just references an attribute without doing anything with it, you've defined `calc_info` as a local function nested under `__init__` instead of as a separate method; etc.), and you'll need to fix all of them, but that's the one causing the problem you're asking about.
type: Comment
comment on: http://stackoverflow.com/q/50711605
score: 1

http://stackoverflow.com/comment/88486805
comment on: http://stackoverflow.com/q/50739607
type: QuestionComment
has text: Your code as written is not syntactically correct. The additional columns in the `partition by` are not available, because they are not part of the aggregation. I assume they are not actually necessary -- that is, the contract ref is sufficient.
score: 0
type: Comment

http://stackoverflow.com/comment/88742266
type: Comment
comment on: http://stackoverflow.com/a/50792675
score: 0
type: AnswerComment
has text: Does the above code read through each csv file line by line? It isn't reading in mine

http://stackoverflow.com/comment/88483618
has text: @user1735003 thank you for you answer, I'm gonna test it soon. Can you please also add the option to get the size after the end of the first epoch?
type: QuestionComment
comment on: http://stackoverflow.com/q/50737192
score: 0
type: Comment

http://stackoverflow.com/a/50763271
has body: Check for naming clashes between variables in your different scripts. Try only running it with a and only running it with b to see which one caused the problem, and then look through the two scripts. If they're both running in the same namespace, it's very likely you used the same variable name or function name twice, and something that should be an string was declared an integer in a previous script. Also, have you considered grouping everything into functions and then just importing the other scripts?
type: Answer
answers question: http://stackoverflow.com/q/50762741
score: 0

http://stackoverflow.com/q/50817026
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88641646
tagged with: python
has comment: http://stackoverflow.com/comment/88639210
has comment: http://stackoverflow.com/comment/88640596
type: Question
tagged with: bind
has comment: http://stackoverflow.com/comment/88639017
tagged with: attributeerror
has title: AttributeError: bind missing
has comment: http://stackoverflow.com/comment/88640728
has comment: http://stackoverflow.com/comment/88640915
score: 0
has comment: http://stackoverflow.com/comment/88640481
tagged with: vpython
has comment: http://stackoverflow.com/comment/88639299
has answer: http://stackoverflow.com/a/50858400
answer count: 1
linked to: http://stackoverflow.com/q/28592211
has body: I'm trying to create a button with the vpython module (and not tkinter for some reasons) and I have this error : AttributeError: bind missing What's the bind and how can I fix that ? from vpython import * def change(): # Appelé par controls quand on clique sur le bouton if b.text == 'Click me': b.text = 'Try again' else: b.text = 'Click me' c = controls() # Crée une fenêtre pour les contrôles # Crée un bouton dans la fenêtre des contrôles: b = button( pos=(0,0), width=60, height=60, text='Click me', action=lambda: change() ) while 1: c.interact()

http://stackoverflow.com/a/51498721
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50753038
downvote count: 0
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50753038
has body: Calling add_module will add an entry to the _modules dict. The Module class also overwrites __getattr__ so that when you try to access a layer, it will look inside the _modules dict, despite the fact that the layer is not actually an attribute of the object. But from the user's perspective, it doesn't make a difference whether module.layer returns an actual property or simply an element from some private dict.

http://stackoverflow.com/q/50729289
has answer: http://stackoverflow.com/a/50730740
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50730707
favorite count: 0
tagged with: recovery
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88466394
has comment: http://stackoverflow.com/comment/88466413
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88466430
has body: I was adding final touches to a python code when my computer unexpectedly shut down. When I turned it back on and opened the file, it was blank. Is it possible for me to recover the contents of that file?
has comment: http://stackoverflow.com/comment/88466402
downvote count: 1
type: Question
has title: Unexpected computer shutdown while python file wasn't saved

http://stackoverflow.com/comment/88430390
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50710693
score: 0
has text: You either sort it before you write it or when you load it back in. It won't ever sort itself.

http://stackoverflow.com/q/50825719
has comment: http://stackoverflow.com/comment/88656518
score: 0
has comment: http://stackoverflow.com/comment/88656524
has comment: http://stackoverflow.com/comment/88657040
type: UnansweredQuestion
tagged with: python
has body: Though it might be a very simple problem but I am not able to store output. He is my code. I did tf-idf for text similarity measure: data=pd.read_csv('name.csv') import nltk, string from sklearn.feature_extraction.text import TfidfVectorizer nltk.download('punkt') # if necessary... stemmer = nltk.stem.porter.PorterStemmer() remove_punctuation_map = dict((ord(char), None) for char in string.punctuation) def stem_tokens(tokens): return [stemmer.stem(item) for item in tokens] '''remove punctuation, lowercase, stem''' def normalize(text): return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map))) vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english') def cosine_sim(text1, text2): tfidf = vectorizer.fit_transform([text1, text2]) return ((tfidf * tfidf.T).A)[0,1] cnt=np.array(np.arange(0,13091)) indx=[] for i in cnt: indx.append(cosine_sim(data['names'][i], data['names'][i+1])) After executing the code I am geting following error: KeyError Traceback (most recent call last) &lt;ipython-input-93-14badf13ad3b&gt; in &lt;module&gt;() 25 26 for i in cnt: ---&gt; 27 indx.append(cosine_sim(data['names'][i], data['names'][i+1])) /anaconda2/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key) 621 key = com._apply_if_callable(key, self) 622 try: --&gt; 623 result = self.index.get_value(self, key) 624 625 if not is_scalar(result): /anaconda2/lib/python2.7/site-packages/pandas/core/indexes/base.pyc in get_value(self, series, key) 2558 try: 2559 return self._engine.get_value(s, k, -&gt; 2560 tz=getattr(series.dtype, 'tz', None)) 2561 except KeyError as e1: 2562 if len(self) &gt; 0 and self.inferred_type in ['integer', 'boolean']: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_it…
answer count: 0
type: Question
has title: store result in for loop in python
has comment: http://stackoverflow.com/comment/88656572

http://stackoverflow.com/q/50779161
tagged with: geolocation
tagged with: twitter
tagged with: geocoding
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50813070
answer count: 1
downvote count: 0
has body: I am fetching tweets from a specific region, but i am getting very different result sets. First method by giving longitude and latitude within a given radius. These are the longitude and latitude within city (Lahore,PK) and draw 5km radius. 5km is a very small portion of this city. By this i fetched around 60,000 tweets of a single day. Method1 import tweepy consumer_key= 'xxxxxxxxxxxxxx' consumer_secret= 'xxxxxxxxxxxxx' access_token='xxxxxxxxxxxxxxx' access_token_secret='xxxxxxxxxxxxxxxxxxxx' api = tweepy.API(auth,wait_on_rate_limit = Truewait_on_rate_limit_notify= True) public_tweets = tweepy.Cursor(api.search, count=100, geocode="31.578871,74.305184,5km",since="2018-06-09",show_user = True,tweet_mode="extended").items() for tweet in public_tweets: print(tweet.full_text) Second Method, i used twitter geo search api, by querying Lahore, granularity="city". Now i am fetching tweets of whole city. but now i am getting 1200 tweets only of one day. I also fetched from past 7 days and get only 15,000 tweets. This is a very big difference that whole city is only giving me 1200 tweets and small portion of the same city is giving me more than 60,000 tweets. I also print the place id to verify that i am getting accurate polygons. These are the polygons ( 74.4493870, 31.4512220 74.4493870, 31.6124170 74.2675860, 31.6124170 74.2675860, 31.4512220) and i draw these on https://www.keene.edu/ to verify. and yes these are accurate polygons of Lahore city. Method2 import tweepy consumer_key= 'xxxxxxxxxxxxxx' consumer_secret= 'xxxxxxxxxxxxx' access_token='xxxxxxxxxxxxxxx' access_token_secret='xxxxxxxxxxxxxxxxxxxx' api = tweepy.API(auth,wait_on_rate_limit = Truewait_on_rate_limit_notify= True) places = api.geo_search(query="Lahore", granularity="city") for place in places: print("placeid:%s" % place) public_tweets = tweepy.Cursor(api.search, count=100,q="place:%s" % place.id,since="2018-06-09",show_user = True,tweet_mode="extended").items() for tweet in public_tweets: print(tweet.fu…
has title: Why these two APIs(twitter geo/search APIs) return different result sets?
favorite count: 0
accepted answer: http://stackoverflow.com/a/50813070
tagged with: python
tagged with: tweepy
score: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/88644234
has text: It's extendable either way; you can seamlessly mix definitions of individual key/value pairs with the unpacking existing dicts. `{'a': 1, **x, 'b': 2, 'c': 3, **y}` is perfectly legal, and you can add individual elements on as needed.
comment on: http://stackoverflow.com/a/50819378
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50839629
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88683573
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/88683321
upvote count: 1
tagged with: processing-efficiency
answer count: 1
has body: Goal: Visit a list of blog pages. On each blog page and find the social links (Instagram, Facebook, Twitter) for that blog page. Assumption: The first occurrence of each social link will be the right one. Occurrences later in the page are more likely to refer to someone else's account. The desirable social URL format is www.social_network_name.com/username There are some formats of URL that are not desirable (e.g. instagram.com/abc/) def check_instagram(url): if 'instagram.com/' in url and "instagram.com/abc/" not in url:: return True def check_facebook(url): if 'facebook.com/' in url and "facebook.com/abc/" not in url:: return True #my list of pages t be parsed pages_to_check = ['www.url1.com', 'www.url2.com', ... 'www.urn_n.com'] #iterate through my list of pages t be parsed for page in pages_to_check : #get all the links on the page page_links = *&lt;selenium code to get all links on page&gt;* I tried... For link in page_links: #when first Instagram handle found if check_instagram(url): *code to write to a dataframe here* break #when first Instagram handle found if check_facebook(url): *code to write to a dataframe here* break Problem: As soon as I matched one social URL, it breaks out of the loop and doesn't continue to look for the other network handles. Some options I can think if are not very good. I'm a Noob. I'd really appreciate some advice here. Option #1 - Loop through all the links and test for first match of ONE social network. Loop through all the links and test for first match of NEXT social network. (Hate this) Option #2 - Create variables for each social URL. Create some marker for match and only update the variable of match is not set. (Better but I'm still going to keep iterating after I have filled all the variables) Option #3 - Any suggestions or advice welcome. How would you approach this?
favorite count: 0
tagged with: python-3.x
has title: What is the most efficient way to run multiple tests in a single loop? Python
has answer: http://stackoverflow.com/a/50840090
accepted answer: http://stackoverflow.com/a/50840090
tagged with: python

http://stackoverflow.com/comment/88701953
comment on: http://stackoverflow.com/q/50849478
has text: @abarnert let me have a look. :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50855063
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: The 2GB threshold might hint a hardware issue. What are you running this program on ? When you write to a file, generally the data is not written directly to your hard drive, but rather to cache. This can be distributed between HDD cache, RAM, Swap, or any other fast memory (depending on your specific hardware and OS). The data is then copied (slowly) to the hard drive, in the background. This allows for seemingly quick disk write, but only works as long as there is free cache space. Perhaps your system has ~2GB of available writing cache, and once this is filled up, your write speed is limited to your raw disk write speed. 30MB/s is not great for a HDD, but it could still be coherent. If this is in fact the problem, the solution is upgrading your hardware. Can you add a SSD to write this file to ? Otherwise, you can also compress the data before writing. This will reduce the amount you have to write, and so solve (or at least reduce) your current problem, but it will have a consequent cost on processing power usage.
accepted answer of: http://stackoverflow.com/q/50854680
answers question: http://stackoverflow.com/q/50854680
has comment: http://stackoverflow.com/comment/88713065

http://stackoverflow.com/a/50751493
upvote count: 4
has comment: http://stackoverflow.com/comment/88511609
type: AcceptedAnswer
downvote count: 0
has body: You may use a lambda expression as the replacment argument: re.sub(rx, lambda x: x.group().replace(' ', '_'), s) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From the re.sub documentation: repl can be a string or a function... If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
type: Answer
accepted answer of: http://stackoverflow.com/q/50751339
answers question: http://stackoverflow.com/q/50751339
score: 4

http://stackoverflow.com/comment/88470063
type: Comment
has text: Also, it did the venv command make a folder with venv in it etc? I noticed you are using the python3 binary so repeat seps with that.
comment on: http://stackoverflow.com/a/50731135
type: AnswerComment
score: 0

http://stackoverflow.com/a/50764125
score: 1
has body: Let requests assemble the URL for you. common_params = { "max": maxrec, "type": item, "freq": freq, # etc } for year in range(1991,2018): response = requests.get(base, params=dict(common_params, ps=str(year)) response_data = response.json() new = pd.DataFrame(response_data["dataset"]) comtrade = comtrade.append(new)
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50764002
answers question: http://stackoverflow.com/q/50764002
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88660066
has text: While threading did not give me any performance advantage, creating subprocesses did. Thanks a lot!
comment on: http://stackoverflow.com/a/50827522
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50775036
has answer: http://stackoverflow.com/a/50790620
accepted answer: http://stackoverflow.com/a/50790620
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: pyqt5
type: Question
tagged with: pyqt
upvote count: 1
answer count: 1
has title: PyQt QGraphicsView Dark Area outside rectangle
has body: I need to create an adjustable selection rectangle for QgraphicsView, here is what I have at the moment : I subclassed QGraphicsRectItem object, added the handles and mouse actions, working pretty well! my code is inspired by this one : Resize a QGraphicsItem with the mouse Working current code example : from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class GraphicsRectItem(QGraphicsRectItem): handleTopLeft = 1 handleTopMiddle = 2 handleTopRight = 3 handleMiddleLeft = 4 handleMiddleRight = 5 handleBottomLeft = 6 handleBottomMiddle = 7 handleBottomRight = 8 handleSpace = -4.0 handleSize = 20 handleCursors = { handleTopLeft: Qt.SizeFDiagCursor, handleTopMiddle: Qt.SizeVerCursor, handleTopRight: Qt.SizeBDiagCursor, handleMiddleLeft: Qt.SizeHorCursor, handleMiddleRight: Qt.SizeHorCursor, handleBottomLeft: Qt.SizeBDiagCursor, handleBottomMiddle: Qt.SizeVerCursor, handleBottomRight: Qt.SizeFDiagCursor, } def __init__(self, *args): """ Initialize the shape. """ super().__init__(*args) self.handles = {} self.handleSelected = None self.mousePressPos = None self.mousePressRect = None self.setAcceptHoverEvents(True) self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.setFlag(QGraphicsItem.ItemIsFocusable, False) self.updateHandlesPos() def handleAt(self, point): """ Returns the resize handle below the given point. """ for k, v, in self.handles.items(): if v.contains(point): return k return None def hoverMoveEvent(self, moveEvent): """ Executed when the mouse moves over the shape (NOT PRESSED). """ if self.isSelected(): handle = self.handleAt(moveEvent.pos()) cursor = Qt.ArrowCursor if handle is None else self.handleCursors[handle] self.setCursor(cursor) super().hoverMoveEvent(moveEvent) def hoverLeaveEvent(self, moveEvent): """ Executed when the mouse leaves the shape (NOT PRESSED). """ self.setCursor(Qt.ArrowCursor) super().hoverLea…
favorite count: 0
linked to: http://stackoverflow.com/q/34429632
tagged with: qgraphicsview
tagged with: python

http://stackoverflow.com/q/50834162
has title: In Fabric 2/Invoke: change directory and use sudo
has answer: http://stackoverflow.com/a/50843350
tagged with: fabric
tagged with: python
has body: This works just fine @task def foo(context): with context.cd('/'): context.run('pwd') Output: / But this does not: @task def bar(context): with context.cd('/'): context.sudo('pwd', password='mysecretpassword') Output: [sudo] password: sudo: cd: Befehl nicht gefunden How do I get the second example to run?
score: 9
type: UnansweredQuestion
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/61349793
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50783912
answers question: http://stackoverflow.com/q/50783835
score: 0
type: Answer
has body: Try this: After getting the tax, then calculate the total. Problem of your code is you calculate the total before assigning values to tax. Always your total is for tax = 0 only. But moving the total calculation to the bottom will fix the issue. price = input("How much: ") country = input("which country are you from :") tax = 0 if country =="Canada" : province = input("Which province? :") if province == "Alberta" : tax = 5 elif province == "Ontario" : tax = 13 else : tax = 11 else : tax = 0 total = int(price) + (int(price)*(tax/100)) print(total)

http://stackoverflow.com/comment/88707109
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50852071
has text: Thanks. I was wondering if I could use the searching algorithm for this...

http://stackoverflow.com/comment/88452466
has text: where is your `train.csv` give the `absolute path to it`
comment on: http://stackoverflow.com/q/50722067
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/q/50730070
score: 3
downvote count: 0
has title: Non greedy regex within parenthesis and contains text
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88467905
type: Question
has comment: http://stackoverflow.com/comment/88467946
has answer: http://stackoverflow.com/a/50730129
tagged with: python
tagged with: regex
upvote count: 3
answer count: 2
has body: Suppose I have a string that looks like test = 'this is a (meh) sentence that uses (random bits of meh2) and (this is silly)' I want to extract ONLY text inside the parentheses if it includes the word "meh". Doing a regular non-greedy regex to match anything within parentheses: re.findall(r'\((.*?)\)', test) Returns ['meh', 'random bits of meh2', 'this is silly'] Trying to do that to only include the first and second contents: re.findall(r'\((.*meh.*?)\)', test) Returns ['meh) sentence that uses (random bits of meh2'] I want a regex to return only ['meh', 'random bits of meh2'] Can someone please help? Thanks!
accepted answer: http://stackoverflow.com/a/50730129
possible better answer: http://stackoverflow.com/a/50730133
has answer: http://stackoverflow.com/a/50730133
has comment: http://stackoverflow.com/comment/88467890
type: AnsweredQuestion

http://stackoverflow.com/a/50853274
answers question: http://stackoverflow.com/q/50852719
has comment: http://stackoverflow.com/comment/88709757
score: 0
has body: There are many open-source projects which implement Factorization Machines. Please refer to https://github.com/coreylynch/pyFM https://github.com/scikit-learn-contrib/polylearn
type: Answer

http://stackoverflow.com/comment/88479923
type: AnswerComment
type: Comment
has text: @Mateen Ulhaq, Almost done! The order of lines are missing and want to store it into third file and display a message the count of lines are different on prompt (**NOT IN OUTPUT FILE**) after program completion, as per your first comment the count will be `1`.
comment on: http://stackoverflow.com/a/50735943
score: 0

http://stackoverflow.com/comment/88693862
comment on: http://stackoverflow.com/a/50845055
type: Comment
type: AnswerComment
has text: Good point @user2357112 on the shallow copy. I have corrected the answer above.
score: 0

http://stackoverflow.com/comment/88553364
comment on: http://stackoverflow.com/a/50773008
type: AnswerComment
score: 0
type: Comment
has text: @PrabhjeetSingh can you show your urls? You need to add `id` as url argument.

http://stackoverflow.com/q/50795888
type: Question
downvote count: 0
has title: Selenium web driver native functions work but same functions of ActionChains class do not on the same element
favorite count: 0
has body: While trying to automate using Selenium webdriver and python I am facing the following issue: Simple click is working without action chains class: element.click() But trying to click is not working using action chains class: from selenium.webdriver.common.action_chains import ActionChains action = ActionChains(driver) action.click(element).perform() Similarly, trying to drag drop not working using action chains class: action.drag_and_drop_by_offset(element,0,100).perform() action.drag_and_drop(element,element2).perform() Using ActionChains gives a stale element exception. Is there any other way to perform these operations like move_to, mouse_press, mouse_release, drag_drop etc. without ActionChains class Further - working directly with driver commands: from selenium.webdriver.remote.command import Command driver.execute(Command.CLICK_ELEMENT, {"id":getattr(element,"id")}) But this does not: from selenium.webdriver.remote.command import Command driver.execute(Command.MOVE_TO, {"id":getattr(element,"id")}) driver.execute(Command.MOUSE_DOWN, {}) driver.execute(Command.MOVE_TO, {"id":getattr(element2,"id")}) driver.execute(Command.MOUSE_UP, {}) Also, observed that the jquery to retrieve the position of the object returns undefined even though the object is present: $($x('div[draggable="true" and @class="result selected-row"][1]')).position() Any suggestions?
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
score: 3
answer count: 0
upvote count: 3

http://stackoverflow.com/comment/88622018
score: 0
comment on: http://stackoverflow.com/q/50791452
has text: @Kristada673 -- I think if you were to use some of the comments so so far to clarify and expand on your question, it would likely get answered. You should definitely include details such as the size of the instance running (or other environment like SageMaker), how you're launching the code, and so on. AWS is a huge, huge world -- be specific about which services you're using and why.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50786974
score: -1
possible better answer: http://stackoverflow.com/a/50787108
has answer: http://stackoverflow.com/a/50787108
accepted answer: http://stackoverflow.com/a/50787405
answer count: 2
has title: AttributeError: '_tkinter.tkapp' object has no attribute 'titleBar'
favorite count: 0
tagged with: tkinter
tagged with: multithreading
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88580485
downvote count: 1
has body: I have written an GUI with tkinter. In the background I have to perfom some intensive calculations. From time to time I want to write some information from the calculation thread to the GUI window. First I thought it was a good idea to add the computation code into the "mainloop". But this doesn't work, because the mainloop is resposible for keeping the GUI reactive. It seams to be no good idea to mainpulate it. Below I have created a dummy app that scatches my new idea. The Sample app has a container. Inside that container, there is a TitleBar. The class TitleBar is defined below. It contains only one label. Next I define a simple thread. It simulates a timeconsuming computation that wants to write some information to the GUI. import tkinter as tk import threading import time class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): # initialize the main window tk.Tk.__init__(self, *args, **kwargs) # add a container which will take all the widgets container = tk.Frame(self, bg="green") container.pack(side="top", fill="both", expand=True) # Add a titlebar object (defined below) titleBar = TitleBar(container, controller=self) titleBar.grid(row=0, column=0, columnspan=2, sticky=tk.N+tk.W+tk.E) class TitleBar(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller # the title bar contains only one label element titleLabel = tk.Label(self, text="This is the initial text") titleLabel.pack(side=tk.LEFT) # Define a thread that runs in the background to perform intensive calculations class MyTestThread(threading.Thread): def run(self): for i in range(10): time.sleep(1) a = i+100 # intensive calculation # from time to time: inform use about status print(a) # printing to console works fine app.titleBar.titleLabel['text'] = "test 1" # --- FAILS --- if __name__ == "__main__": app = SampleApp() app.titleBar.titleLabel['text'] = "test 2" # --- FAILS --- t = MyTestThread() t.start() app.mainloop() The problem is that I can…
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/50787405

http://stackoverflow.com/comment/88566468
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50770049
has text: Like I said in the question, the task process is still running, it just doesn't give any new outputs since it's waiting for inputs.
type: Comment

http://stackoverflow.com/comment/88485820
type: AnswerComment
score: 0
type: Comment
has text: I think it's `$PSVersionTable`. Also edited the answer.
comment on: http://stackoverflow.com/a/50739056

http://stackoverflow.com/q/50710057
score: 1
has comment: http://stackoverflow.com/comment/88430857
has answer: http://stackoverflow.com/a/50710630
answer count: 2
possible better answer: http://stackoverflow.com/a/50710170
has answer: http://stackoverflow.com/a/50710170
accepted answer: http://stackoverflow.com/a/50710630
favorite count: 0
has comment: http://stackoverflow.com/comment/88429271
has body: I have this sentence: "int open(const char *" pathname ", int " flags ); I am trying to find a regex to extract the words outside the double quotes. Example: "pathname" and "flags". I created a regex expression, but it only catches the word "flags" and not the word "pathname". Here is what I have: reg2 = r"""(\".*\" (.*) )+\);""" pattern2 = re.compile(reg2) inner = m.group(1) m2 = pattern2.search(inner) EntityI = m2.group(2) print EntityI Note: m.group(1) is: "int open(const char *" pathname ", int " flags ); Thanks for the help! Edit: Just the clarify some more. Another possible case could be: "int open(const char *" pathname ", int " flags ", mode_t " mode ); And I would want to extract the words: "pathname", "flags", and "mode".
has comment: http://stackoverflow.com/comment/88429202
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88430888
type: AnsweredQuestion
has title: Extracting words outside of double quotes with Regex Python
upvote count: 2
linked to: http://stackoverflow.com/q/2301285
has comment: http://stackoverflow.com/comment/88429267
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88430913
linked to: http://stackoverflow.com/q/22444

http://stackoverflow.com/q/50709325
has body: Whenever I see references to modules like SciPy and NumPy the first letter of each part is capitalized. However they must be imported with all lowercase letters. Why is there this difference?
has comment: http://stackoverflow.com/comment/88427785
score: 11
has answer: http://stackoverflow.com/a/50709376
answer count: 1
accepted answer: http://stackoverflow.com/a/50709376
upvote count: 11
favorite count: 0
has title: Why do python module names have some uppercase letters but are always imported in lowercase?
tagged with: python
type: AnsweredQuestion
tagged with: naming-conventions
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88427800

http://stackoverflow.com/a/62504898
has body: I faced similar issue while deploying google cloud functions in Python. My cloud function was using different versions of .proto files in my module (which was again a private module which I wanted to install using requirements.txt). The solution is to use pure python implementation instead of using binary implementation of protobuf. To solve this in cloud functions or in cloud build you can set cloud functions env variables to use python implementation of protocol buffers. In your gcloud cloud function deploy command use following option: &lt;start of command&gt; --set-env-vars=PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION='python' &lt;your rest of the command&gt; or if you are in any other env/os simply do this export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION='python' This solved my issue.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/138913484
upvote count: 6
has comment: http://stackoverflow.com/comment/120725338
score: 6
answers question: http://stackoverflow.com/q/50839667

http://stackoverflow.com/q/50826216
has comment: http://stackoverflow.com/comment/88725332
accepted answer: http://stackoverflow.com/a/50938385
tagged with: python-3.x
has body: So I am using all built in Django, I don't have my own login view. First I'll describe how the scenario is created that causes this error: So someone is logged in and has multiple tabs open and then they log out. Eventually the other tabs will be directed to the accounts/login page either by themselves or the page is refreshed or a link is pressed, it doesn't really matter how. The point is this person now has multiple tabs that are all on the accounts/login screen and no one is authenticated/logged in. So then this person successfully logs in in one of the tabs. They then go and to one of the other tabs, which are still on the accounts/login page (even though a session is already created). If this person then tries to log in as the person logged in, or really anyone, in fact even if the username and password are empty and they simply click the login button, the 403 Error CSRF token missing or incorrect gets thrown. (I hope this makes sense) Anyways, how can I fix this? And this is my html template if that helps: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} Login {% csrf_token %} By using this site, you agree to our privacy policy and terms of use. Login {% endblock %} Edit: I would also like to add that if I create the same scenario and instead of immediately trying to log in, instead I reload the page just once, the 403 error doesn't happen. I just want to be able to prevent users from ever running into an error while using the site (outside of typing things directly into the search bar of course). One idea could be that right when login is clicked it will refresh the csrf token the same way a page refresh would, is this possible and a good idea?
upvote count: 3
tagged with: django
has comment: http://stackoverflow.com/comment/88686974
has comment: http://stackoverflow.com/comment/88725065
type: AnsweredQuestion
score: 3
tagged with: django-authentication
has title: Django Forbidden 403 Error "CSRF token missing or incorrect" when trying to log in when already logged in
tagged with: django-login
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50938385
downvote count: 0
possible better answer: http://stackoverflow.com/a/50827887
has comment: http://stackoverflow.com/comment/88731660
has answer: http://stackoverflow.com/a/50827887
favorite count: 0
has comment: http://stackoverflow.com/comment/88733043
has comment: http://stackoverflow.com/comment/88657855
tagged with: python

http://stackoverflow.com/a/50782948
has comment: http://stackoverflow.com/comment/88586447
has body: It isn't clear to me why you are using numbers as string but your problem is in the Bclear() function: def BClear(): global numOf numOf = str(int(numOf) - 1) numberEt.set(numOf) While the operand sign + is acceptable for string types since it concatenates strings, the operand - cannot be used. Be careful working with strings as str(4) + str(5) means 45, not 9
accepted answer of: http://stackoverflow.com/q/50782900
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50782900
type: Answer
score: 0

http://stackoverflow.com/a/50721723
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50717904
has body: replace + dropna(Notice thresh is the key here) df.replace(dict(zip(list('NnVv'),[np.nan]*4))).dropna(thresh=1) Out[513]: A B C D 0 BUY 150 Q 2018 1 SELL 63 Q 2018 4 SELL 53 Q 2018

http://stackoverflow.com/q/50848178
has comment: http://stackoverflow.com/comment/88699656
downvote count: 3
has comment: http://stackoverflow.com/comment/88699696
type: Question
has answer: http://stackoverflow.com/a/50848202
score: -2
accepted answer: http://stackoverflow.com/a/50848208
possible better answer: http://stackoverflow.com/a/50848202
answer count: 2
tagged with: string
has comment: http://stackoverflow.com/comment/88699666
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/20367305
has comment: http://stackoverflow.com/comment/88699686
has body: I tried to make a odd/even 'calculator' in python and it keeps popping up errors. Here's the code: def odd_even(): print("Welcome to Odd/Even") num = input("Pick a number: ") num2 = num/2 if num2 == int: print("This number is even") else: print("This number is odd") Id like to know whats causing the errors and solutions to them
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/20367305
has answer: http://stackoverflow.com/a/50848208
type: AnsweredQuestion
has title: How do I check if a input is an integer type

list
tags question: http://stackoverflow.com/q/50767359
type: Tag
tags question: http://stackoverflow.com/q/50779667
tags question: http://stackoverflow.com/q/50706675
tags question: http://stackoverflow.com/q/50766319
tags question: http://stackoverflow.com/q/50756085
tags question: http://stackoverflow.com/q/50778026
tags question: http://stackoverflow.com/q/50819137
tags question: http://stackoverflow.com/q/50760341
tags question: http://stackoverflow.com/q/50729340
tags question: http://stackoverflow.com/q/50699641
tags question: http://stackoverflow.com/q/50704846
tags question: http://stackoverflow.com/q/50701156
tags question: http://stackoverflow.com/q/50705975
tags question: http://stackoverflow.com/q/50703339
tags question: http://stackoverflow.com/q/50723384
tags question: http://stackoverflow.com/q/50851888
tags question: http://stackoverflow.com/q/50714333
tags question: http://stackoverflow.com/q/50735522
tags question: http://stackoverflow.com/q/50711739
tags question: http://stackoverflow.com/q/50786866
tags question: http://stackoverflow.com/q/50768432
tags question: http://stackoverflow.com/q/50717813
tags question: http://stackoverflow.com/q/50843126
tags question: http://stackoverflow.com/q/50833129
tags question: http://stackoverflow.com/q/50751184
tags question: http://stackoverflow.com/q/50783262
tags question: http://stackoverflow.com/q/50772321
tags question: http://stackoverflow.com/q/50827588
tags question: http://stackoverflow.com/q/50848201
tags question: http://stackoverflow.com/q/50711353
tags question: http://stackoverflow.com/q/50745248
tags question: http://stackoverflow.com/q/50813544
tags question: http://stackoverflow.com/q/50802082
tags question: http://stackoverflow.com/q/50803334
tags question: http://stackoverflow.com/q/50717368
tags question: http://stackoverflow.com/q/50839690
tags question: http://stackoverflow.com/q/50820962
tags question: http://stackoverflow.com/q/50821092
tags question: http://stackoverflow.com/q/50812491
tags question: http://stackoverflow.com/q/50779467
tags question: http://stackoverflow.com/q/50831284
tags question: http://stackoverflow.com/q/50770201
tags question: http://stackoverflow.com/q/50798909
tags question: http://stackoverflow.com/q/50843859
tags question: http://stackoverflow.com/q/50709515
tags question: http://stackoverflow.com/q/50782327
tags question: http://stackoverflow.com/q/50804350
tags question: http://stackoverflow.com/q/50714321
tags question: http://stackoverflow.com/q/50727542
tags question: http://stackoverflow.com/q/50732688
tag name: list
tags question: http://stackoverflow.com/q/50778241
tags question: http://stackoverflow.com/q/50720128
tags question: http://stackoverflow.com/q/50726665
tags question: http://stackoverflow.com/q/50824438
tags question: http://stackoverflow.com/q/50795055
tags question: http://stackoverflow.com/q/50746022
tags question: http://stackoverflow.com/q/50781368
tags question: http://stackoverflow.com/q/50841195
tags question: http://stackoverflow.com/q/50802824
tags question: http://stackoverflow.com/q/50755500
tags question: http://stackoverflow.com/q/50776182
tags question: http://stackoverflow.com/q/50708033
tags question: http://stackoverflow.com/q/50850093
tags question: http://stackoverflow.com/q/50730172
tags question: http://stackoverflow.com/q/50839106
tags question: http://stackoverflow.com/q/50739918
tags question: http://stackoverflow.com/q/50726729
tags question: http://stackoverflow.com/q/50842687
tags question: http://stackoverflow.com/q/50751177
tags question: http://stackoverflow.com/q/50755708
tags question: http://stackoverflow.com/q/50780322
tags question: http://stackoverflow.com/q/50823043
tags question: http://stackoverflow.com/q/50710422
tags question: http://stackoverflow.com/q/50795092
tags question: http://stackoverflow.com/q/50830592
tags question: http://stackoverflow.com/q/50788144
tags question: http://stackoverflow.com/q/50772780
tags question: http://stackoverflow.com/q/50849097

http://stackoverflow.com/q/50774143
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/50775786
has body: This is the first time I am working with shell scripts. Passing one element at a time works. However I have got confused because I have a method which requires a list as an argument and currently, whatever I tried, it just takes the first element of list. But I wish to pass the entire list at one time only. run.sh #!/bin/bash list = 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95; qsub job.sh "label" $list job.sh #!/bin/bash python file.py $1 $2 file.py import sys import os from myClass import myClass label = sys.argv[1] list = sys.argv[2] myObject = myClass(label,list)
score: 0
has comment: http://stackoverflow.com/comment/88555801
answer count: 2
tagged with: bash
tagged with: shell
has title: Passing a list in shell script
has answer: http://stackoverflow.com/a/50774173
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/64060174
has body: -1 infers to 2, for instance, if you have &gt;&gt;&gt; a = torch.rand(4,4) &gt;&gt;&gt; a.size() torch.size([4,4]) &gt;&gt;&gt; y = x.view(16) &gt;&gt;&gt; y.size() torch.size([16]) &gt;&gt;&gt; z = x.view(-1,8) # -1 is generally inferred as 2 i.e (2,8) &gt;&gt;&gt; z.size() torch.size([2,8])
score: 0
has comment: http://stackoverflow.com/comment/117562163
type: Answer
answers question: http://stackoverflow.com/q/50792316

http
tags question: http://stackoverflow.com/q/50771525
tags question: http://stackoverflow.com/q/50768456
tags question: http://stackoverflow.com/q/50765085
tag name: http
tags question: http://stackoverflow.com/q/50803563
type: Tag
tags question: http://stackoverflow.com/q/50751518
tags question: http://stackoverflow.com/q/50813091

http://stackoverflow.com/comment/88695766
comment on: http://stackoverflow.com/a/50845968
type: Comment
score: 0
type: AnswerComment
has text: Thanks for your answer, btw i tried to use signals ,then got integrity error with i could not able to debug.. .thats why went for neanderthal way..

http://stackoverflow.com/comment/88703386
comment on: http://stackoverflow.com/a/50845326
score: 0
type: AnswerComment
has text: Sometimes there are indeed no matches. Like in your original example, because the word 'mutual' is not even in the text.
type: Comment

http://stackoverflow.com/comment/88519692
has text: Sorry I will change
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50754111

http://stackoverflow.com/comment/88806630
has text: @Maxibon Splitting 2/3 is pretty straightforward. See the updated the post for a more complete answer.
comment on: http://stackoverflow.com/a/50812302
score: 0
type: AnswerComment
type: Comment

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/50776104
type: Tag
tags question: http://stackoverflow.com/q/50779240

http://stackoverflow.com/comment/88572277
comment on: http://stackoverflow.com/q/50782664
score: 0
has text: Do not use .js to specify JSON object. Better is to paste it in .json file and then based on your project path it can be easily read in your views.py.
type: Comment
type: QuestionComment

printing
tags question: http://stackoverflow.com/q/50774738
tag name: printing
tags question: http://stackoverflow.com/q/50796178
tags question: http://stackoverflow.com/q/50802215
type: Tag
tags question: http://stackoverflow.com/q/50733827
tags question: http://stackoverflow.com/q/50730813

http://stackoverflow.com/q/50776518
answer count: 1
has title: Rasa-core, dealing with dates
tagged with: python
tagged with: rasa-core
type: UnansweredQuestion
type: Question
tagged with: rasa-nlu
tagged with: date
has answer: http://stackoverflow.com/a/54032632
has body: I have a problem with rasa core, let's suppose that I have a rasa-nlu able to detect time eg "let's start tomorrow" would get the entity time: 2018-06-10:T18:39:155Z Ok, now I want next branches, or decisions to be conditioned by: time is in the past time before one month from now time is beyond 1 month I do not know how to do that. I do not know how to convert it to a slot able to influence the dialog. My only idea would be to have an action that converts the date to a categorical slot right after detecting time, but I see two problems with that approach: one it would already be too late, meaning that if I do it with a posterior action it means the rasa-core has already decided what decision to take without using the date and secondly, I do know how to save it, because if I have a stories.md that compares a detecting date like in the example with the current time, maybe in the time of the example it was beyond one month but now it is in the past, so the reset of that story would be wrong. I am pretty lost and I do not know how to deal with this, thanks a lot!!!
score: 0

http://stackoverflow.com/q/50761646
answer count: 2
tagged with: three.js
tagged with: python
accepted answer: http://stackoverflow.com/a/50771019
possible better answer: http://stackoverflow.com/a/50762847
has answer: http://stackoverflow.com/a/50762847
has body: I am trying to load a 3d file into three.js with Flask I've tryied in my .html &lt;script&gt; var tridi = '{{ url_for('static', filename = 'mesh.dae') }}' &lt;/script&gt; then load my .js file var loader = new THREE.ColladaLoader( loadingManager ); loader.load( tridi, function ( collada ) { elf = collada.scene; } ); but it doesn't seems to work :/ I've also tryied &lt;script&gt; var loader = new THREE.ColladaLoader( loadingManager ); loader.load( "{{ url_for('static', filename='mesh.dae') }}", function ( collada ) { elf = collada.scene; } ); var loadingManager = new THREE.LoadingManager( function() { scene.add( elf ); } ); &lt;/script&gt; any help pls?
tagged with: flask
has title: load file IN javascript using Flask
has answer: http://stackoverflow.com/a/50771019
type: AnsweredQuestion
type: Question
score: 0

http://stackoverflow.com/a/50810090
answers question: http://stackoverflow.com/q/50809434
has body: You can still use qhull + some post processing: import numpy as np from scipy.spatial import ConvexHull # https://stackoverflow.com/a/47705495/7207392 def connect2(ends): d0, d1 = np.diff(ends, axis=0)[0] if np.abs(d0) &gt; np.abs(d1): return np.c_[np.arange(ends[0, 0], ends[1,0] + np.sign(d0), np.sign(d0), dtype=np.int32), np.full(np.abs(d0)+1, ends[0, 1]) if d1==0 else np.arange(ends[0, 1] * np.abs(d0) + np.abs(d0)//2, ends[0, 1] * np.abs(d0) + np.abs(d0)//2 + (np.abs(d0)+1) * d1, d1, dtype=np.int32) // np.abs(d0)] else: return np.c_[np.full(np.abs(d1)+1, ends[0, 0]) if d0==0 else np.arange(ends[0, 0] * np.abs(d1) + np.abs(d1)//2, ends[0, 0] * np.abs(d1) + np.abs(d1)//2 + (np.abs(d1)+1) * d0, d0, dtype=np.int32) // np.abs(d1), np.arange(ends[0, 1], ends[1,1] + np.sign(d1), np.sign(d1), dtype=np.int32)] def dch(points): ch = ConvexHull(points) n = len(ch.vertices) return np.concatenate([connect2(points[ch.verticesi, (i+1)%n])[:-1] for i in range(n)], axis=0) points = np.argwhere(np.random.random((24, 24)) &lt; 0.03) import pylab pylab.plot(*dch(points).T, 'bo') pylab.plot(*points.T, 'rd') pylab.show()
type: Answer
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/q/50727460
accepted answer: http://stackoverflow.com/a/50728125
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88463823
has title: List comprehension to identify string matches between two lists
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88463147
score: 1
has answer: http://stackoverflow.com/a/50728125
has body: I'm using list comprehension to filter strings in list_a (a large list) that contain any of the strings in list_b (another large list). I've been able to successfully use the code below to generate a list of the items in list_a that have such matches: list_a_results = [s for s in list_a if any(xs in s for xs in list_b)] Now I'm trying to do what I'm thinking of as the reverse process, ie, identify each of the items from list_b that show up in each string listed in list_a_results. Is there a nifty way to use list comprehension to achieve this? An example of what I'm trying to accomplish: when given: list_a_results = ['abc def ghi jkl', 'mno pqr', 'stu', 'vwx yz'] list_b = ['abc', 'ghi', 'pqr', 'stu', 'vwx', 'yz'] I want to be able to generate the following: matches_in_list_a = [['abc', 'ghi'], 'pqr', 'stu', ['vwx','yz']]
upvote count: 1
type: Question
downvote count: 0
tagged with: list-comprehension

http://stackoverflow.com/q/50804656
tagged with: python
has body: Is there any way to adjust the remaining regex pattern to what have been already matched? A rough sketch to illustrate the idea: pattern / | \ / | \ prefix1 prefix2 prefix3 | | | postfix1 postfix2 postfix3 This is a rather theoretical question; the practical application below is only for illustrative purposes. I'm trying to find the first URLs to popular code hosting platforms, like github, gitlab etc., in a large text. The problem is, all platforms have different URL patterns: github.com/&lt;user&gt;/&lt;repo&gt; gitlab.com/&lt;group1&gt;/&lt;group2&gt;/.../&lt;repo&gt; sourceforge.net/projects/&lt;repo&gt; I can use lookbehind expressions, but then the expression gets really monstrous (Python re): pattern = re.compile( r"(github\.com|bitbucket\.org|gitlab\.com|sourceforge\.net)/" # middle part - empty for all except sourceforge r"(?:(?&lt;=github\.com/)|(?&lt;=bitbucket\.org/)|(?&lt;=gitlab\.com/)|" r"(?&lt;=sourceforge\.net/)projects/)(" # final part, the repository pattern r"(?&lt;=github\.com/)[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+|" r"(?&lt;=bitbucket\.org/)[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+|" r"(?&lt;=gitlab\.com/)[a-zA-Z0-9_.-]+(?:/[a-zA-Z0-9_.-]+)+|" r"(?&lt;=sourceforge\.net/projects/)[a-zA-Z0-9_.-]+" r")") Is there a more elegant way to do something like this?
has answer: http://stackoverflow.com/a/50820466
has title: Parsing a "hierarchical" URL with regexes if there are splits in parsing logic
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88620192
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/50820466
score: 0
tagged with: regex
tagged with: url-parsing

http://stackoverflow.com/q/50812766
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/88632676
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66069071
has title: Python Pyodbc cannot return first inserted id via executemany
score: 0
type: Question
linked to: http://stackoverflow.com/q/47188976
linked to: http://stackoverflow.com/q/30058957
has comment: http://stackoverflow.com/comment/88631355
accepted answer: http://stackoverflow.com/a/66069071
linked to: http://stackoverflow.com/q/44777348
has comment: http://stackoverflow.com/comment/88632424
has comment: http://stackoverflow.com/comment/88632192
tagged with: sql
has comment: http://stackoverflow.com/comment/88632559
answer count: 1
has body: SET UP MWE: I have a table in SQL Server as such CREATE TABLE dbo.MyTable( order_id INT IDENTITY(1,1), column2 DECIMAL, column3 INT PRIMARY KEY(order_id) ) I am using pyodbc to insert some data in the form of a pandas.DataFrame into the table. I am using data such as: column2 column3 0 1.23 5 1 4.95 9 2 6.79 10 Where I've created this example dataframe using data = pd.DataFrame({'column2':[1.23, 4.95, 6.79], 'column3':[5,9,10]}) I use the following statement to insert data stmt = "INSERT INTO dbo.MyTable(column2, column3) OUTPUT Inserted.order_id VALUES (?, ?)" ISSUE This is the code that I use to insert everything and returning the values: # Set up connection and create cursor conn_string = "DRIVER={MyDriver};SERVER=MyServer;DATABASE=MyDb;UID=MyUID;PWD=MyPWD" cnxn = pyodbc.connect(conn_string) cnxn.autocommit = False cursor = cnxn.cursor() cursor.fast_executemany = True # Upload data cursor.executemany(stmt, data.values.tolist()) # Process the result try: first_result = cursor.fetchall() except pyodbc.ProgrammingError: first_result = None result_sets = [] while cursor.nextset(): result_sets.append(cursor.fetchall()) all_inserted_ids = np.array(result_sets).flatten() However, I do not get all the ids that I should get! For instance, suppose there is no data in the table, I will not get all_inserted_ids = np.array([1, 2, 3]) But rather I will only get all_inserted_ids = np.array([2, 3]) Which means that I'm losing the first id somewhere! And notice that first_result never works. It always throws the following: pyodbc.ProgrammingError: No results. Previous SQL was not a query. I've also tried using cursor.fetchone(), cursor.fetchone()[0] or cursor.fetchval() but they got me the same error. METHODS THAT I TRIED BUT DID NOT WORK 1) Adding "SET NOCOUNT ON" I tried using the same code as in the question but with stmt = """ SET NOCOUNT ON; INSERT INTO dbo.MyTable(column2, column3) OUTPUT Inserted.order_id VALUES (?, ?) """ The output was [1, 2] so I was missing 3. 2) Addin…
tagged with: sql-server
tagged with: python

http://stackoverflow.com/q/50783175
has body: Overview I am making a game with a spaceship that can move in all 4 directions. In the game while loop my spaceship can be controlled by the keyboard as seen below. For the sake of simplicity I have only shown some part of my code, and only the part where I move my spaceship to the right. Method As seen, I use a 'for loop' and the pygame module to receive the input from the keyboard. And I am using the flag method to enable continuous moving. I start by setting all the flags to False. Then depending on the keyboard press it moves in the different direction and set to False again when the key goes up. Its all working fine... NB: the variable surf_centerx is the center of my spaceship and the screen.blit(surf, surf_rect), pygame.display.flip() at the end is just displaying the spaceship on the screen and updating the latest changes in position of the spaceship, respectively. import pygame # pygame initializing pygame.init() #create the screen surface screen = pygame.display.set_mode((400, 400)) #..snip... speedfactor = 0.1 move_right = False #..snip... while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: move_right = True #..snip... elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: move_right = False #..snip... if move_right: surf_centerx += speedfactor #..snip... screen.blit(surf, surf_rect) pygame.display.flip() Code refactoring - I thought But because my while loop keeps growing I want to do some code refactoring, I thought :o) So I would put my keyboard stuff in a separate module, with a function I would then call in my while loop. I save the value from k_c.check_key_events() in the variable, 'returned' and below that the value is unpacked by the line 'move_right = returned'. My while loop now look like this (a lot shorter): import keyboard_control as k_c while True: returned = k_c.check_key_events() move_right = returned if move_right: surf_centerx += speedfactor #..snip... screen.blit(surf, …
tagged with: flags
has answer: http://stackoverflow.com/a/50787869
tagged with: scope
score: 0
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88629687
tagged with: python
tagged with: pygame
tagged with: module
has title: Pygame: how to put keyboard control in separate module without loosing continuous moving
linked to: http://stackoverflow.com/q/19158339
type: Question
has comment: http://stackoverflow.com/comment/88608552

http://stackoverflow.com/comment/113581027
comment on: http://stackoverflow.com/a/50744752
type: Comment
has text: @dnks23 I am having the same problem. I have 24 columns but I get an error saying the interval is [1,21[. Were you able to solve it?
type: AnswerComment
score: 0

http://stackoverflow.com/q/50772550
has title: Django Create a number of child objects in a create view with parent object
tagged with: django-models
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50985205
has body: I have two models that are related by a foreign key. I am trying to add logic to a form field in the create view where the user fills out a number n and it generates n items in the database. Model.py class Environment(models.Model): name = models.CharField(max_length=50) class Item(models.Model): environment = models.ForeignKey(Environment, on_delete=models.CASCADE) uid = models.CharField(max_length=50, unique=True, null=True, blank=True) def __init__(self): super(Item, self).__init__() self.uid = str(uuid.uuid4()) view.py class EnvironmentCreateView(CreateView): '''View for creating Environments''' model = Environment form_class = EnvironmentCreateForm template_name = 'Environment_create.html' success_url = reverse_lazy('main:Environment list') forms.py If the items field is filled by the user it should generate n items in the database. The current approach I took has an issue overriding the save function. Not really sure if I need to use inline_formeset class EnvironmentCreateForm(forms.ModelForm): name =forms.CharField(max_length=50, required=True, label='Product Name') items =forms.IntegerField(min_value =0, max_value = 100,required=False, label='Number of Items') class Meta: model = Environment fields = ['name',] def save(self): if Environment.is_valid(): Environment.save() if self.items &gt;= 0: for i in range(self.items): Item.objects.create(Environment, uid =str(uuid.uuid4()) )
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50985205
score: 0
tagged with: django-forms
answer count: 1

http://stackoverflow.com/comment/88671307
has text: may be you need add the comma before params?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50833687

http://stackoverflow.com/comment/88467493
has text: Are you sure that your dictionary looks like that? A single string containing "x, y, z" as key?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50729702

http://stackoverflow.com/q/50783729
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/50785040
has comment: http://stackoverflow.com/comment/88579056
type: Question
has answer: http://stackoverflow.com/a/50786658
has comment: http://stackoverflow.com/comment/88576476
has answer: http://stackoverflow.com/a/50785040
has comment: http://stackoverflow.com/comment/88578934
has answer: http://stackoverflow.com/a/50786861
accepted answer: http://stackoverflow.com/a/50786861
has comment: http://stackoverflow.com/comment/88579027
answer count: 3
has title: How to join two tables in a SQLite DB using Python?
tagged with: sql
upvote count: 1
tagged with: sqlite
has body: I have two tables: 1) Table A with columns: id,c2,c3 2) Table B with columns: pid,c2 I want to join them such that, for A.id=B.pid, join columns c2 and c3 from A with the matching row in table B. pid can occur multiple times in table B ,but id occurs only once in table A. I saw other solutions and tried this: cursor.execute("""SELECT A.c2, A.c3, B.c2 FROM A INNER JOIN B ON A.id=B.pid""") conn.commit() The code executed successfully but no changes were reflected in the tables. I can provide actual data of tables and columns if required. UPDATE I understood that SELECT will only select and not update the data in the table B, but I still don't understand how to code the problem.
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/88578971
type: AnsweredQuestion

http://stackoverflow.com/q/50828900
tagged with: machine-learning
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50831111
has comment: http://stackoverflow.com/comment/88663995
answer count: 1
downvote count: 0
score: 1
tagged with: scikit-learn
favorite count: 0
has body: I was wondering whether there is a way to post-process predicted labels in sklearn. My training data has ground truth labels in the form 0, 1 However, the problem is I am currently using Isolation Forest, which predicts: -1 for outliers, equivalent to ground-truth label 1 1 for normal data, equivalent to ground-truth label 0 If I were to write a function to post-process the prediction, it would be very simple: def process_anomaly_labels(raw_y_pred): y_pred = raw_y_pred.copy() y_pred[raw_y_pred == 1] = 0 y_pred[raw_y_pred == -1] = 1 return y_pred But I don't know how to postprocess prediction labels when I finetune the model using RandomSearchCV: from sklearn.model_selection import RandomizedSearchCV # fine tuning forest_params = { "n_estimators": [50, 200, 800], "max_samples": [1000, 4000, 16000, 64000, 120000], "max_features": [1, 5, 15, 30], "contamination": [0.001, 0.1, 0.2, 0.5] } forest_grid_search = RandomizedSearchCV( IsolationForest(), param_distributions=forest_params, scoring="f1", n_jobs=8, n_iter=50, cv=3, verbose=2 ) forest_grid_search.fit(X_train_trans, y_train) I cannot convert the ground truth labels to match with predicted labels, because I would like to use binary F1 score when evaluating.
tagged with: python
tagged with: data-processing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50831111
has title: Scikit-learn fine-tuning: Postprocess predicted labels before evaluation

http://stackoverflow.com/comment/88470062
comment on: http://stackoverflow.com/a/50731135
has text: oh.. no module name `venv`. I don't use `venv` though..?? I would rather stick with `virtualenv`. I'm not familiar wiht `venv`. Do you think it's worth it?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88409985
type: Comment
type: QuestionComment
has text: Provide the snippet of what and how you tried and the error message you are getting, we will be able to give you better solution to your approach then.
comment on: http://stackoverflow.com/q/50699443
score: 2

http://stackoverflow.com/comment/88534549
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50763445
has text: I have sure how to iterate over the multiple rows, there can be n number of rows.
type: QuestionComment

http://stackoverflow.com/a/50759416
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50759380
type: Answer
has body: There is problem different index values, so in subtraction Series are not aligned. Possible solution, if same size of both filtered Series, is create same index values: datum_first_milestone.index = datum_second_milestone.index Also solution should be simplify if need filter only column by loc + column name: datum_first_milestone = data_audit.loc[(data_audit.Audit == audit) &amp; (data_audit.Meilenstein == phase1), 'GeplantesErledigungsdatum'] datum_second_milestone = data_audit.loc[(data_audit.Audit == audit) &amp; (data_audit.Meilenstein == phase2), 'GeplantesErledigungsdatum'] print(datum_first_milestone) print(datum_second_milestone) and if always is returned one value Series.item return scalars: print (datum_first_milestone.item() - datum_second_milestone.item()) More general if there is one or more values is possible select first value for scalars: print (datum_first_milestone.iat[0] - datum_second_milestone.iat[0])
answers question: http://stackoverflow.com/q/50759380

http://stackoverflow.com/comment/88570404
type: Comment
comment on: http://stackoverflow.com/q/50781810
score: 0
type: QuestionComment
has text: There is a handy method to check the same: `keyword.iskeyword(your_word)`.

http://stackoverflow.com/comment/88584777
score: 0
type: Comment
type: QuestionComment
has text: Does flask.send_file() actually support URLs?
comment on: http://stackoverflow.com/q/50788813

http://stackoverflow.com/comment/88651921
score: 0
type: QuestionComment
type: Comment
has text: yes exactly. that should be what I will use for the apriori algorithm.
comment on: http://stackoverflow.com/q/50819737

http://stackoverflow.com/comment/88500860
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50746629
has text: add `\\` (escape character) at every point before the new line.

http://stackoverflow.com/q/50704092
favorite count: 0
has answer: http://stackoverflow.com/a/50704387
tagged with: time
has comment: http://stackoverflow.com/comment/88417461
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88417529
score: 1
has title: Nested Loop or 'in', which is faster?
accepted answer: http://stackoverflow.com/a/50704387
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88417454
linked to: http://stackoverflow.com/q/582336
has comment: http://stackoverflow.com/comment/88417566
answer count: 1
has comment: http://stackoverflow.com/comment/88417528
has body: I am a python novice and was studying some basic coding challenges and was hoping to someone could explain which of the following snippets of code would run faster. The point is to see if there are pairs of integers within the list that add up to 100: list = [1,2,3,99,5] for i in list: for j in list: if i + j == 100: return True or: list = [1,2,3,99,5] for i in list: diff = 100 - i if diff in list: return True
has comment: http://stackoverflow.com/comment/88417701
tagged with: big-o

http://stackoverflow.com/comment/88690310
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50842817
has text: Silly question, what is in prog1.py, for example? Would it be the command I stated in the question?
score: 0

http://stackoverflow.com/q/50786744
has answer: http://stackoverflow.com/a/50786765
tagged with: python
has answer: http://stackoverflow.com/a/50786783
has comment: http://stackoverflow.com/comment/88580154
answer count: 4
has answer: http://stackoverflow.com/a/50786809
has comment: http://stackoverflow.com/comment/88579858
has title: for loop in python with counter?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50786774
has answer: http://stackoverflow.com/a/50786774
accepted answer: http://stackoverflow.com/a/50786783
has body: How can I create a for loop with a counter? I have a list, and I want to read an element after each n elements. I'd initially done this for i in enumerate(n): print(i) But as expected it prints every element instead of every nth element, what would be the Python way of solving this?
type: Question
upvote count: 4
tagged with: for-loop
has comment: http://stackoverflow.com/comment/88579805
downvote count: 0
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/88579807

http://stackoverflow.com/comment/96673431
type: AnswerComment
has text: Did I not mentioned that all images should of same dimension (128x128) say ? The append will fail if at least one differs. You can pad or crop images to make them all same dimension before loading
comment on: http://stackoverflow.com/a/50754111
type: Comment
score: 0

http://stackoverflow.com/a/50785929
has comment: http://stackoverflow.com/comment/88579275
has comment: http://stackoverflow.com/comment/88578351
score: 0
type: Answer
has body: Let suppose your tuple is in MyTuple.txt then you can try below code written in ReadTuple.py to read tuple from a file. &raquo; ReadTuple.py # Open file in read mode with open('MyTuple.json', encoding='utf-8') as f: content = f.read() t = eval(content); # print tuple t read from file print(t); # print type of t print(type(t)); &raquo; MyTuple.txt Finally, if you will run above code using python ReadTuple.py then you will be able to see the read tuple and its type on your screen. &raquo; Output (1, 2, 3) &lt;class 'tuple'&gt;
answers question: http://stackoverflow.com/q/50785752
has comment: http://stackoverflow.com/comment/88579092
has comment: http://stackoverflow.com/comment/88579202

http://stackoverflow.com/a/50808541
has comment: http://stackoverflow.com/comment/88622780
has comment: http://stackoverflow.com/comment/88622837
score: 0
type: Answer
has body: First, no reason to re-invent the wheel. Look at itertools.dropwhile, and just invert your predicate. Second, if you're going to deal with iterators, then you can't assume that they're sliceable, or that you can get their lengths. Basically the only things you can do to get values are for loops, next, and yield from. Also, and I don't want to sound condescending here, all you have to do to call iter explicitly is iter(iterable). That returns an iterator over your iterable. def skip_until(p,iterable): try: it = iter(iterable) curr = next(it) while not p(curr): curr = next(it) yield curr yield from it except StopIteration: return print(list(skip_until(lambda x: len(x) &gt; 1, ['x', 'y', 'abc', 'a', 'xyz']))) # ['abc', 'a', 'xyz']
answers question: http://stackoverflow.com/q/50808335

http://stackoverflow.com/comment/88613767
comment on: http://stackoverflow.com/q/50803737
type: Comment
has text: It seems like you're expecting Python functions to be "pure functions" that always return the same value when called with the same arguments (in this case, no arguments at all). Python _allows_ that, but doesn't _force_ it; if you want to write a function that returns a different random value each time, you can. And that's exactly what you've done.
score: 0
type: QuestionComment

http://stackoverflow.com/q/50802044
score: 1
type: Question
tagged with: yowsup
downvote count: 0
has title: InvalidMessage or KeyId for ..., going to send a retry
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I'm using yowsup, and need to figure out a problem that I haven't faced before. I already received messages via the onMessage event, but now it doesn't work. On debug, I got InvalidMessage or KeyId for xxxxx, going to send a retry. I tried to delete axolotl.db, but nothing. This is my layer.py: class ReadLayer(YowInterfaceLayer): @EventCallback(YowNetworkLayer.EVENT_STATE_CONNECTED) def onConnected(self, yowLayerEvent): print "----- CONECTADO ----- \n" @ProtocolEntityCallback("message") def onMessage(self, messageProtocolEntity): if messageProtocolEntity.getType() == 'text': frm = messageProtocolEntity.getFrom() body = messageProtocolEntity.getBody() print ("- Mensagem de %s \n&gt;&gt;&gt; %s \n\n" % (frm, body)) if messageProtocolEntity.getType() == 'media': if messageProtocolEntity.getMediaType() == 'image': frm = messageProtocolEntity.getFrom() url = messageProtocolEntity.url print ("- Imagem de %s \n&gt;&gt;&gt; %s\n\n" % (frm, url)) self.toLower(messageProtocolEntity.ack()) self.toLower(messageProtocolEntity.ack(True)) @ProtocolEntityCallback("receipt") def onReceipt(self, entity): self.toLower(entity.ack())

http://stackoverflow.com/comment/88696834
score: 1
has text: just careful about cases where `"None"` is returned
comment on: http://stackoverflow.com/a/50846646
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50744665
has comment: http://stackoverflow.com/comment/88507718
has comment: http://stackoverflow.com/comment/88508135
has comment: http://stackoverflow.com/comment/88584245
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88635300
accepted answer of: http://stackoverflow.com/q/50743855
score: 2
answers question: http://stackoverflow.com/q/50743855
has comment: http://stackoverflow.com/comment/88516255
has body: I guess this would help. I am creating a df with random values with 7 columns, dividing the first 6 with 7th column and then calculating hhi using a helper function calculate_hhi. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(20, 7), columns=list('ABCDEFG')) def calculate_hhi(row): hhi = 1 - (row['A']**2 + row['B']**2 + row['C']**2 + row['D']**2 + row['E']**2 + row['F']**2 ) return hhi df.iloc[:, 0:6] = df.iloc[:, 0:6].apply(lambda x: x/df.G, axis=0) df['hhi'] = df.apply(calculate_hhi, axis=1)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50706092
upvote count: 3
downvote count: 2
tagged with: sympy
has comment: http://stackoverflow.com/comment/88422196
answer count: 1
has comment: http://stackoverflow.com/comment/88423123
has comment: http://stackoverflow.com/comment/88423572
favorite count: 0
has comment: http://stackoverflow.com/comment/88425029
has title: Exponential regression function Python
has body: I am trying to implement a exponential regression function. sp stands for sympy. I use numpy and sympy. Firstly, in func_exp I tried to use np.exp but it generated an error (attribute error), so I decided to use sympy instead. Well, this is the code import numpy as np from numpy.linalg import matrix_rank import scipy import scipy.integrate import random import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D from sympy import integrate import sympy as sp x, y = sp.symbols('x, y') sp.init_printing(use_unicode=True,use_latex='mathjax') def exponential_regression (x_data, y_data): def func_exp(x, a, b): return a*sp.exp(b*x) popt, pcov = scipy.optimize.curve_fit(func_exp, x_data, y_data) a = popt[0] # componente a, Parámetro ÓPTimo (popt). b = popt[1] # componente b, Parámetro ÓPTimo (popt). plt.figure() puntos = plt.plot(x_data, y_data, 'x', color='xkcd:maroon') curva_regresion = plt.plot(x_data, func_exp(x_data, a, b), color='xkcd:teal') plt.show(puntos, curva_regresion) return func_exp(x, a, b) I try to execute: x_data = np.arange(0, 51) # Crea un array de 0 a 50. y_data = np.array([0.001, 0.199, 0.394, 0.556, 0.797, 0.891, 1.171, 1.128, 1.437, 1.525, 1.720, 1.703, 1.895, 2.003, 2.108, 2.408, 2.424,2.537, 2.647, 2.740, 2.957, 2.58, 3.156, 3.051, 3.043, 3.353, 3.400, 3.606, 3.659, 3.671, 3.750, 3.827, 3.902, 3.976, 4.048, 4.018, 4.286, 4.353, 4.418, 4.382, 4.444, 4.485, 4.465, 4.600, 4.681, 4.737, 4.792, 4.845, 4.909, 4.919, 5.100]) exponential_regression(x_data, y_data) And I get: exponential_regression(x_data, y_data) TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe' Traceback (most recent call last): File "&lt;ipython-input-122-ee7c243ae4b0&gt;", line 1, in &lt;module&gt; exponential_regression(x_data, y_data) File "/Volumes/TOSHIBA/spline.py", line 35, in exponential_regression popt, pcov = scipy.optimize.curve_fit(func_exp, x_data, y_data) File "/Applications/anaconda3/lib/p…
linked to: http://stackoverflow.com/q/2386714
tagged with: python
has comment: http://stackoverflow.com/comment/88433953
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88421375
tagged with: exponential
score: 1
tagged with: regression
has comment: http://stackoverflow.com/comment/88427548
has comment: http://stackoverflow.com/comment/88425597
has comment: http://stackoverflow.com/comment/88421574
has answer: http://stackoverflow.com/a/50713914
accepted answer: http://stackoverflow.com/a/50713914
type: Question
has comment: http://stackoverflow.com/comment/88421883
tagged with: numpy

http://stackoverflow.com/a/51058639
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50836635
score: 4
answers question: http://stackoverflow.com/q/50836635
type: Answer
has body: I had also some troubles when i installed fiona and tried to import it. I had this kind of message &gt;&gt;&gt; import fiona Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "D:\Software\Ingenieria\Anaconda2\lib\site-packages\fiona\__init__.py", l ine 77, in &lt;module&gt; from fiona.collection import Collection, BytesCollection, vsi_path File "D:\Software\Ingenieria\Anaconda2\lib\site-packages\fiona\collection.py", line 9, in &lt;module&gt; from fiona.ogrext import Iterator, ItemsIterator, KeysIterator ImportError: DLL load failed: The specified module could not be found. How did it work for me at the end? I installed the distributions GDAL 2.2.4 and Fiona from this link Then i checked if my computer has a c++ compiler for python (here link with some information about which one you may need to install). In some forum questions i read that GDAL need this compiler to be able to work. Then i added the Osgeo folder path (there are the dlls for fiona) to my path environment variable, some pics from my pc Print screen 1 Print screen 2 After doing those steps i never had any more problems with fiona. At first, i was using the GDAL version 1.1.4 but it never worked with this one. You can try first with the version one, and if it doesn´t work then install the version 2.2.4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/q/50714185
accepted answer: http://stackoverflow.com/a/50714280
has body: I have a time series data with polynomial features that exceeds the upper and lower thresholds multiple times, I want to count how many times the upper and lower thresholds are exceeded. for example my upper threshold is 35°C and my lower threshold is -45°C. How do I write a function which counts how many times the data exceeds the upper and lower thresholds and also the time when the data was in range? Is there a pythonic way to solve this problem?
tagged with: python
linked to: http://stackoverflow.com/q/19463985
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/15375093
upvote count: 1
possible better answer: http://stackoverflow.com/a/50714518
downvote count: 1
tagged with: signal-processing
has comment: http://stackoverflow.com/comment/88437200
has title: count the times that values exceed over a threshold in time series
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50714518
tagged with: time-series
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50714280
favorite count: 0

http://stackoverflow.com/comment/88500913
has text: To clarify, I'd like the button title to say "Choose Operation" instead of "Select Folder". How can I reference the particular button and change the label?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50746554

http://stackoverflow.com/comment/88564033
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50778569
has text: `', '.join([str(v['name']) for v in data['available_sizes']])`

http://stackoverflow.com/comment/88701472
type: QuestionComment
comment on: http://stackoverflow.com/q/50849097
has text: Is it possible that the key `-1` is an integer, not a string?
score: 0
type: Comment

http://stackoverflow.com/q/50796790
has title: How to get additional information associated to a python concurrent.future?
tagged with: concurrent.futures
favorite count: 0
has body: I am trying to download a bunch of files from S3 in python. To speed it up, I use def sync(self): def wait_for_job(job): (src_filename, dst_filename, f) = job try: result = f.result() logging.info("Download ok: {}, result={}".format(dst_filename, result)) except IOError as e: logging.info("Download error: {} - {}".format(dst_filename, e)) self.projectInfo.downloaded_files[src_filename] = 0 while self.pending_jobs: wait_for_job(self.pending_jobs.pop(0)) def getFiles(files_to_download): for src, dst in files_to_download: self.pending_jobs.append( (src, dst, self.executor.submit(s3_ops.copy_file, src, dst)) ) Now, I'd like to use concurrent.futures.as_completed(). As it takes a list of futures, I can't pass self.pending_jobs to it (it's a list of tuples). I could make self.pending_jobs just a list of futures, whose function would return not only result, but also src and dst: def sync(self): def wait_for_job(f): try: (src_filename, dst_filename, result) = f.result() logging.info("Download ok: {}, result={}".format(dst_filename, result)) except IOError as e: ### Can't get the value of dst_filename logging.info("Download error: {} - {}".format(dst_filename, e)) self.projectInfo.downloaded_files[src_filename] = 0 for job in concurrent.futures.as_completed(self.pending_jobs): wait_for_job(job) def getFiles(files_to_download): for src, dst in files_to_download: l = lambda s, d: (s, d, ops.copy_file(s, d)) self.pending_jobs.append( self.executor.submit(l, src, dst) ) I would get them after calling future.result(), as part of the tuple it returns. But in the case of an exception, I wouldn't be able to get anything. Is there any way to accomplish this? I would expect as_completed including some parameter in the line of key in sorted (i.e., to let it know how to extract the future from an item in the list), but it doesn't seem to be there.
answer count: 0
tagged with: python-multithreading
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
type: Question
downvote count: 0

http://stackoverflow.com/comment/88673567
has text: seems to work now
comment on: http://stackoverflow.com/q/50834040
score: 0
type: QuestionComment
type: Comment

if-statement
tags question: http://stackoverflow.com/q/50773936
tag name: if-statement
tags question: http://stackoverflow.com/q/50798861
type: Tag
tags question: http://stackoverflow.com/q/50737109
tags question: http://stackoverflow.com/q/50778026
tags question: http://stackoverflow.com/q/50836584
tags question: http://stackoverflow.com/q/50808650
tags question: http://stackoverflow.com/q/50750332
tags question: http://stackoverflow.com/q/50836409
tags question: http://stackoverflow.com/q/50826754
tags question: http://stackoverflow.com/q/50708172
tags question: http://stackoverflow.com/q/50756723
tags question: http://stackoverflow.com/q/50764517
tags question: http://stackoverflow.com/q/50730408
tags question: http://stackoverflow.com/q/50756299
tags question: http://stackoverflow.com/q/50784020
tags question: http://stackoverflow.com/q/50761242
tags question: http://stackoverflow.com/q/50828894
tags question: http://stackoverflow.com/q/50752394
tags question: http://stackoverflow.com/q/50746932
tags question: http://stackoverflow.com/q/50820945
tags question: http://stackoverflow.com/q/50724731
tags question: http://stackoverflow.com/q/50759567

http://stackoverflow.com/q/50794502
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50795525
has answer: http://stackoverflow.com/a/50795517
tagged with: pytorch
type: UnansweredQuestion
has body: The below code will show that using python loop is faster than using Pandas. My understanding before I tested it was different. So I'm wondering am I using pandas wrongly for this operation? The below code shows that Pandas solution is about 7 times slower: Pandas time 0.0008931159973144531 Loop time 0.0001239776611328125 Code: import pandas as pd import numpy as np import time import torch batch_size = 5 classes = 4 raw_target = torch.from_numpy(np.array([1, 0, 3, 2, 0])) rows = np.array(range(batch_size)) t0 = time.time() zeros = pd.DataFrame(0, index=range(batch_size), columns=range(classes)) zeros.ilocrows, raw_target.numpy() = 1 t1 = time.time() print("Pandas time ", t1-t0) t0 = time.time() target = raw_target.numpy() zeros = np.zeros((batch_size, classes), dtype=np.float64) for zero, target in zip(zeros, target): zero[target] = 1 t1 = time.time() print("Loop time ", t1-t0) The code uses PyTorch because the actual code where the problem exists uses PyTorch. What could be better/optimal solution to this example? The resulting matrix is: [[0. 1. 0. 0.] [1. 0. 0. 0.] [0. 0. 0. 1.] [0. 0. 1. 0.] [1. 0. 0. 0.]]
tagged with: python
has title: Python loop faster than Pandas
type: Question
score: 0

http://stackoverflow.com/q/50772112
has title: Pandas not reading in file correctly
tagged with: import-from-csv
has comment: http://stackoverflow.com/comment/88585227
type: Question
has comment: http://stackoverflow.com/comment/88600290
has answer: http://stackoverflow.com/a/50891906
has answer: http://stackoverflow.com/a/50772146
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/88557603
has comment: http://stackoverflow.com/comment/88557931
has comment: http://stackoverflow.com/comment/88552067
has comment: http://stackoverflow.com/comment/88572682
has comment: http://stackoverflow.com/comment/88607660
has comment: http://stackoverflow.com/comment/88607612
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: fixed-width
has comment: http://stackoverflow.com/comment/88608899
has body: I have the data file given here:: https://www.dropbox.com/sh/8lsvigjjpjhdlap/AAD3VpFdBifGMxrq5C-6yhpPa?dl=0 and the following code:: import pandas as pd df = pd.read_table('Best_2018_Table1.txt', sep=r"\s*") but something is breaking and pandas doesn't read this admittedly badly formatted table:: df.columns df['PS1gmag'] What's the best way to read in this spaces-for-columns type of file??

http://stackoverflow.com/q/50813961
tagged with: python
has comment: http://stackoverflow.com/comment/88633540
score: 0
has title: django : How to create & call a Constructor on every request?
has comment: http://stackoverflow.com/comment/88633791
tagged with: django
has comment: http://stackoverflow.com/comment/88632962
has comment: http://stackoverflow.com/comment/88635430
has comment: http://stackoverflow.com/comment/88633952
accepted answer: http://stackoverflow.com/a/50815586
type: Question
has comment: http://stackoverflow.com/comment/88633824
type: AnsweredQuestion
tagged with: default-constructor
has body: I want to call a request validator method every time a POST request is called. So Code I want to have like : import validator class ViewClass(): def __CONSTRUCTOR__(self, request): is_valid = validator.validate() if is_valid == FALSE return HttpResponse('Request is Invalid') def request_function_one(request): if request.method == 'POST': return HttpResponse('Request 1 is Valid') def request_function_two(request): if request.method == 'POST': return HttpResponse('Request 2 is Valid') How can I achieve this using django ?
tagged with: validation
answer count: 1
has comment: http://stackoverflow.com/comment/88632989
has answer: http://stackoverflow.com/a/50815586
has comment: http://stackoverflow.com/comment/88633016

http://stackoverflow.com/a/50802773
has body: Dataframe.plot() doesn't actually take a color argument. You'd have to drive a matplotlib.pyplot.bar() call directly if you wanted to use a simple sequence of colours (but note that there are better options, listed below). If you do decide to use matplotlib.pyplot.bar() directly, then take into account that it's color argument then only takes either a single valid color value, so 'r' or 'k', or a sequence of such color values (the documentation for bar() calls it array like). A list of names would work: my_colors = ['r', 'g', 'b', 'k', 'y', 'm', 'c'] # red, green, blue, black, etc. plt.bar(len(train_class), train_class, color=my_colors) The documentation states that the sequence should be equal in length to the number of bars plotted: The optional arguments color, edgecolor, linewidth, xerr, and yerr can be either scalars or sequences of length equal to the number of bars. However, it is just easier to pass in a color map to Dataframe.plot() here. Color maps as a handy and fast path towards distinct bar colors. You can pass one in as the colormap keyword argument, this can be a named map (as a string): train_class.plot(kind='bar', colormap='Paired') or an actual matplotlib colormap object from the matplotlib.cm module: from matplotlib import cm train_class.plot(kind='bar', colormap=cm.Paired) If you wanted to stick with matplotlib.pyplot.bar(), but use a colormap, then create your series of colors from a colormap. Pandas uses np.linspace() for this so here we do too: import numpy as np paired_colors = cm.Paired(np.linspace(0, 1, num=len(train_class)) plt.bar(len(train_class), train_class, color=paired_colors) For bar plots, I'd pick a qualitative colormap; each name is an attribute of the cm colormap module. In the above, cm.Paired is a one such color map. Calling the color map with a sequence of floats between 0.0 and 1.0 gives you back colours picked at each 'percentage' of the range. You could also pass in a sequence of integers to index individual colours instea…
type: Answer
has comment: http://stackoverflow.com/comment/104240163
has comment: http://stackoverflow.com/comment/104232009
upvote count: 7
has comment: http://stackoverflow.com/comment/104096478
accepted answer of: http://stackoverflow.com/q/50802475
answers question: http://stackoverflow.com/q/50802475
has comment: http://stackoverflow.com/comment/104112839
has comment: http://stackoverflow.com/comment/104231911
has comment: http://stackoverflow.com/comment/104293584
has comment: http://stackoverflow.com/comment/104095952
has comment: http://stackoverflow.com/comment/104077421
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/104209598
score: 7

http://stackoverflow.com/comment/88712144
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50826357
has text: @ImportanceOfBeingErnest Found it

http://stackoverflow.com/comment/88423531
type: Comment
comment on: http://stackoverflow.com/a/50706822
score: 1
type: AnswerComment
has text: I like your answer, it's just hard to know when OP won't confirm questions like whether it's always the top three or it could be top n. I posted my naive version.

http://stackoverflow.com/q/50797135
has title: Why does this neural network have zero accuracy and very low loss?
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88600681
tagged with: recurrent-neural-network
tagged with: tensorflow
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88600729
accepted answer: http://stackoverflow.com/a/50797589
upvote count: 3
tagged with: deep-learning
answer count: 1
has answer: http://stackoverflow.com/a/50797589
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/88600567
has body: I have network : Tensor("input_1:0", shape=(?, 5, 1), dtype=float32) _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 5, 1) 0 _________________________________________________________________ bidirectional_1 (Bidirection (None, 5, 64) 2176 _________________________________________________________________ activation_1 (Activation) (None, 5, 64) 0 _________________________________________________________________ bidirectional_2 (Bidirection (None, 5, 128) 16512 _________________________________________________________________ activation_2 (Activation) (None, 5, 128) 0 _________________________________________________________________ bidirectional_3 (Bidirection (None, 1024) 656384 _________________________________________________________________ activation_3 (Activation) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 1) 1025 _________________________________________________________________ p_re_lu_1 (PReLU) (None, 1) 1 ================================================================= Total params: 676,098 Trainable params: 676,098 Non-trainable params: 0 _________________________________________________________________ None Train on 27496 samples, validate on 6875 samples I fit and compile it by: model.compile(loss='mse',optimizer=Adamx,metrics=['accuracy']) model.fit(x_train,y_train,batch_size=100,epochs=10,validation_data=(x_test,y_test),verbose=2) When I run it and also evaluate it on unseen data,it returns 0.0 Accuracy with very low loss. I can't figure out what's the problem. Epoch 10/10 - 29s - loss: 1.6972e-04 - acc: 0.0000e+00 - val_loss: 1.7280e-04 - val_acc: 0.0000e+00
tagged with: python
has comment: http://stackoverflow.com/comment/88600299

http://stackoverflow.com/comment/88666977
has text: The link you added explained the way to convert it to list or tuple.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50831179

http://stackoverflow.com/comment/88427700
comment on: http://stackoverflow.com/q/50706967
has text: It isn't really a rule as such - the post at the above link was written because we get so many people wanting priority over other questions, and after several years of it, I am still mystified by the phenomenon. Perhaps you might shed some light on it, just for my curiosity? Is it normal for you to ask volunteers to treat your problem as more important than other people's problems? Do your friends or colleagues do this? I'm not intending to be hostile - I genuinely want to know.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88515112
type: AnswerComment
comment on: http://stackoverflow.com/a/50753549
score: 0
type: Comment
has text: @vaibhavk I don't see `axis=1` in my answer anywhere... why did you add it? It changes the answer.

http://stackoverflow.com/a/50777966
type: Answer
has comment: http://stackoverflow.com/comment/88563086
accepted answer of: http://stackoverflow.com/q/50777751
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50777751
score: 0
has body: row = cur.fetchall() won't give you a row but a list of rows, so row is not a row at all and row[2] is the third row in the list, not the third field in a row. If you want only a row use cur.fetchone(). Note the the query might return several rows and it is not clear what you want to do in that case so I won't deal with it here. cur.fetchone() will give you only one row anyway.

http://stackoverflow.com/q/50741377
has answer: http://stackoverflow.com/a/56035716
accepted answer: http://stackoverflow.com/a/50743299
answer count: 2
downvote count: 0
tagged with: python-docx
possible better answer: http://stackoverflow.com/a/56035716
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50743299
type: Question
has body: To set a background color for cells in a table I am using the following code: doc.add_paragraph('') t1 = doc.add_table(rows=7, cols=2) t1.style = 'TableGrid' for row in range(7): cell = t1.cell(row, 0) cell._tc.get_or_add_tcPr().append(shading_elm_green) The only problem is that the result is as follows: But I want all of the cells to have the background color. Why is this not setting all the cells. Plus when I am creating many tables all the cells are clear and the very last cell of the very last table is only set. What am I doing wrong? Please I am looking for a solution for many days now!
score: 5
upvote count: 5
has title: python docx setting background color table cell

http://stackoverflow.com/a/50787264
has comment: http://stackoverflow.com/comment/88582572
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50787213
score: 1
upvote count: 1
has body: You can use map. Example: df1.Graduated.map(df2.Graduated) yields 0 Yes 1 No 2 Yes Thus just do that for every column, as follows for col in df1.columns: if col in df2.columns: df1[col] = df1[col].map(df2[col]) Remember to set the index to the answer code first, i.e. df2 = df2.set_index("Answer_Code"), if necessary.

http://stackoverflow.com/comment/88505098
has text: `refresh_current_configs` writes to a log regularly (not shown in above skeleton). If the last write by `config_refresher` thread is like 5 hours ago, I'm guessing the thread was killed.
comment on: http://stackoverflow.com/q/50748748
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50795082
type: Answer
answers question: http://stackoverflow.com/q/50794964
has body: That's not how you do loops in Python or in Jinja. You should use the loop variable. You don't need count at all. &lt;ul&gt; {% for i in attendance['total'] %} &lt;li&gt;{{ i }}&lt;/li&gt; {% endfor %} &lt;/ul&gt;
score: 0

http://stackoverflow.com/comment/88458787
has text: (1) Guesstimates. From (0, 0) we can conclude that a + c = 0. The shape tells us that a < 0. And b should have been set according to the shape to an initial parameter of -0.1 - but hey, it converged nonetheless. (2) Whether it is a better fit than another function is unclear. You have to compare the deviation using pcov to get a measure, how good the fit for each function is. But it surely looks well fitted.
type: Comment
comment on: http://stackoverflow.com/a/50713914
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88711300
score: 0
has text: e.g. if cnt is None: print ("no contour") ... and maybe do something like continue to the next value... same thing with hull and defects. You should also check if the variable is not none, if it is empty with shape or len
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50853133

http://stackoverflow.com/comment/88617343
score: 0
type: Comment
type: QuestionComment
has text: Why are you **decoding** again, then encoding to UTF-8?
comment on: http://stackoverflow.com/q/50805638

http://stackoverflow.com/comment/88437101
comment on: http://stackoverflow.com/a/50713526
score: 0
type: AnswerComment
has text: I see it works correctly now, however, the page does not reload with the correct information after I click on the button, I have to reload it twice to see the updated results. This is because I am passing an outdated context object. I put the `self.get_object()` and `context` lines underneath the `follow_unfollow` method to get the updated context object, however, how do I get `self.object.id` for the `follow_unfollow` method without repeating code?
type: Comment

http://stackoverflow.com/comment/88754031
score: 0
type: Comment
type: QuestionComment
has text: @dieggo111 What do you want to get? The button exists but it is not distinguishable.
comment on: http://stackoverflow.com/q/50738264

http://stackoverflow.com/a/50763362
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50762995
upvote count: 2
answers question: http://stackoverflow.com/q/50762995
type: Answer
has comment: http://stackoverflow.com/comment/88574192
score: 2
has body: From PolynomialFeatures documentation: Generate a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, if an input sample is two dimensional and of the form [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2]. In your case the output is all the combinations of column x with degree less than or equal to 1: [1, x]. In the first column you have x**0 and in the second x**1
has comment: http://stackoverflow.com/comment/88573738

http://stackoverflow.com/a/50818337
has comment: http://stackoverflow.com/comment/88642381
accepted answer of: http://stackoverflow.com/q/50816683
answers question: http://stackoverflow.com/q/50816683
has body: If I understand you correctly, I think this is what you are looking for: term="gpcr[TI] AND {}[TA]".format(value) using this, the each term will be: "gpcr[TI] AND Nature[TA]" "gpcr[TI] AND Science[TA]" "gpcr[TI] AND PNAS[TA]" "gpcr[TI] AND JACS[TA]"
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/88485457
score: 0
type: Comment
has text: you want to use np.mean on all numeric columns or just leeftijd?
type: QuestionComment
comment on: http://stackoverflow.com/q/50737787

http://stackoverflow.com/comment/88595473
type: QuestionComment
comment on: http://stackoverflow.com/q/50794467
score: 0
has text: What is `axarr`? Which libraries do you use? Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
type: Comment

http://stackoverflow.com/q/50793321
has title: Iterate through a json list with dictionaries
has comment: http://stackoverflow.com/comment/88592712
duplicate of: http://stackoverflow.com/q/50019852
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/50793352
linked to: http://stackoverflow.com/q/50019852
has body: I have a json file which contains a list with many dictionaries. Here I've included just two. But I want to iterate through all of the dictionaries and only get the code value (Company1 and Company2). [{"code":"Company1","exchange_short_name":"ST","date":"2000-01-01"}, {"code":"Company2","exchange_short_name":"ST","date":"2000-01-01"}] I've gotten to this, but it gives me all of the values inside the dictionary, and not the code values. for d in jsonData: for key in d: print(d[key])
has answer: http://stackoverflow.com/a/50793352
score: 0
has comment: http://stackoverflow.com/comment/88592859
answer count: 1
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/104698227
score: 2
comment on: http://stackoverflow.com/a/51060374
type: AnswerComment
type: Comment
has text: @Zarkopafilis thanks for pointing out issues with n-gram word embeddings. Also, For people who come here by Google, it would be nice to look at pre-trained language models such as BERT, XLNet, etc. They usually get better results than using old-fashioned embeddings.

module
tags question: http://stackoverflow.com/q/50752340
tags question: http://stackoverflow.com/q/50714278
tags question: http://stackoverflow.com/q/50845316
tags question: http://stackoverflow.com/q/50845926
tags question: http://stackoverflow.com/q/50828930
tags question: http://stackoverflow.com/q/50776362
tags question: http://stackoverflow.com/q/50783175
tags question: http://stackoverflow.com/q/50842360
tags question: http://stackoverflow.com/q/50749039
type: Tag
tags question: http://stackoverflow.com/q/50725079
tag name: module
tags question: http://stackoverflow.com/q/50804354
tags question: http://stackoverflow.com/q/50807760
tags question: http://stackoverflow.com/q/50848070

http://stackoverflow.com/q/50787842
score: 0
has body: I'm using web2py and now I'm fetching all calendar events from db using this code in a view: events: [ {{for row in rowseventi:}} { title: '{{=row.evento.titolo}}', id: '{{=row.evento.id}}', resourceId: '{{=row.evento.risorsa}}', start: '{{=row.evento.inizio}}', end: '{{=row.evento.fine}}', recurring: '{{=row.evento.ricorrenza}}', // allDay: false, color : '{{=row.evento.colore}}', url: '{{=URL('mostra_evento',args=row.evento.id)}}', }, {{pass}} ] It's working perfectly but now I'd like to fetch only events regarding current view using this function https://fullcalendar.io/docs/events-function function( start, end, timezone, callback ) { } There are some example using php but I want only use Python and PyDAL. Can someone give me some examples using only python and JavaScript? rowseventi it's an array retrieved from controller that contains all events... When I change the view with "next", "prev" or something else I'd like to fetch the new events based on the dates showed in the view. Thank you
has comment: http://stackoverflow.com/comment/88596976
has title: fullcalendar fetch events from database using Python web2py
has comment: http://stackoverflow.com/comment/88593990
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88595261
type: Question
has comment: http://stackoverflow.com/comment/88595633
tagged with: javascript
tagged with: fullcalendar
has comment: http://stackoverflow.com/comment/88595731

http://stackoverflow.com/q/50741799
has answer: http://stackoverflow.com/a/50763949
answer count: 2
has title: Create list/tuple for inserting multiple rows with one query
downvote count: 0
accepted answer: http://stackoverflow.com/a/50763949
favorite count: 0
tagged with: python
has body: Based on the question "psycopg2: insert multiple rows with one query" (psycopg2: insert multiple rows with one query) From JS, I receive the following on serverside: "2,3,4..." Then, on server side(python 3.6): list_urlquery = urlquery_partition.strip().split(",") for i in range(len(list_urlquery)): list_urlquery[i] = "(" + str(list_urlquery[i]).strip() + ", '" + str( file.filename).strip() + "," + str(PATH_ID).strip() + "')" insert_query = 'INSERT INTO tbl_ma (theid, thefilename, thepathid) VALUES %s' psycopg2.extras.execute_values(cursor, insert_query, list_urlquery, template=None, page_size=100) print (list_urlquery) Output on Console: ["(2, 'Screenshot from 2018-05-29 07-13-47.png,1')", "(3, 'Screenshot from 2018-05-29 07-13-47.png,1')", "(4, 'Screenshot from 2018-05-29 07-13-47.png,1')"] Error: INSERT has more expressions than target columns I request you to guide me on this. How can I create a proper list/tuple and insert the data into database?
linked to: http://stackoverflow.com/q/8134602
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50742699
upvote count: 1
tagged with: psycopg2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50742699
score: 1
type: Question

http://stackoverflow.com/comment/88562781
type: Comment
type: QuestionComment
has text: But the outputs are different, I mean the conda command has more packages than output of `pip freeze`.
score: 1
comment on: http://stackoverflow.com/q/50777849

http://stackoverflow.com/comment/88558535
type: QuestionComment
comment on: http://stackoverflow.com/q/50772222
has text: Look at this post telling how to create ssh connections simultaneously with paramiko. https://codereview.stackexchange.com/questions/168859/running-ssh-commands-on-multiple-servers
score: 0
type: Comment

http://stackoverflow.com/a/50776743
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: It looks like the files you are processing are quite big (10MB), so the long execution time is expected. There is not much you can do to speed up the execution of your program, apart from more parallelization and being more cautious with memory. That is, you can do the following: use multi-threading with multiprocessing.Pool write each text file to disk separately to free up memory Here is a full program with these optimizations: #!/usr/bin/env python import os from multiprocessing import Pool, cpu_count from io import BytesIO from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter import TextConverter from pdfminer.layout import LAParams PDF_DIRECTORY = "pdfs" def pdf_to_text(pdf_filename): # PDFMiner boilerplate pdf_resource_manager = PDFResourceManager() bytes_io = BytesIO() device = TextConverter( pdf_resource_manager, bytes_io, codec="utf-8", laparams=LAParams()) interpreter = PDFPageInterpreter(pdf_resource_manager, device) # Extract text with open(pdf_filename, "rb") as fp: for page in PDFPage.get_pages(fp): interpreter.process_page(page) text = str(bytes_io.getvalue()) # Cleanup bytes_io.close() device.close() # Print current filename with some of the parsed text print("{} - {}".format(pdf_filename, text[:15].replace("\n", ""))) return text def process_pdf_file(pdf_filename): text_filename = "{}.txt".format(os.path.splitext(pdf_filename)[0]) # Write the text file to disk to avoid having to keep # it in memory with open(text_filename, "w") as text_file: text_file.write(pdf_to_text(pdf_filename)) def main(): pdf_filename_list = [] for filename in os.listdir(PDF_DIRECTORY): if not filename.endswith(".pdf"): continue pdf_filename_list.append(os.path.join(PDF_DIRECTORY, filename)) MULTITHREAD = True if MULTITHREAD: # Use a thread pool to process multiple PDF files at the same time pool = Pool(cpu_count()) pool.map(process_pdf_file, pdf_filename_list) else: # Version without thread pool for…
type: Answer
accepted answer of: http://stackoverflow.com/q/50776263
answers question: http://stackoverflow.com/q/50776263
score: 2

http://stackoverflow.com/comment/88452477
has text: I needed my code to be as little exception-driven as possible. Anyway, I've changed the way it works so now I don't happen to have a long int that exceeds float. I will mark your post as an answer.
score: 0
comment on: http://stackoverflow.com/a/50699471
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139046386
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/62139106
has text: the basic example 2 doesntr work for me

http://stackoverflow.com/q/50833129
linked to: http://stackoverflow.com/q/12319025
tagged with: python
tagged with: list
score: 0
has comment: http://stackoverflow.com/comment/88670161
has comment: http://stackoverflow.com/comment/88670650
has comment: http://stackoverflow.com/comment/88670184
type: UnansweredQuestion
has title: How to obtain elements of a filter object into a list in Python 3?
answer count: 0
has body: myList = list(range(1,50)) # subsetting just the odd ones neighbors = filter(lambda x: x % 2 != 0, myList) print(list(neighbors)) the output I'm getting is: "[ ]" I want to store the elements of "neighbors" in a list so i can use that as an argument for the x_axis for my plot? how can i do this?
tagged with: python-3.x
type: Question
tagged with: filter
has comment: http://stackoverflow.com/comment/88670344

http://stackoverflow.com/a/50786810
type: Answer
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/50786798
has body: I think need to_datetime: df = pd.DataFrame({'year':['01/01/1880 12:00:00 AM']}) df['year'] = pd.to_datetime(df['year']) print (df) year 0 1880-01-01

http://stackoverflow.com/q/50773316
tagged with: mod-wsgi
type: Question
tagged with: wsgi
accepted answer: http://stackoverflow.com/a/50773481
score: 0
has title: Serving multiple Django projects in different virtualenv at the same IP (Apache)
answer count: 1
tagged with: virtualenv
has body: I'm trying to serve two Django projects on different virtualenv at the same IP adress on Apache. My first site is at http://myip/site-1 and the seccond: http://myip/site-2 When I run http://myip/site-1, Apache serves it without issues, but when I run the second (http://myip/site-2) it raises the following: The requested URL /site-2/ was not found on this server. Because it searches in the first site's document root. Here is my apache.conf ServerName site-1.example.com DocumentRoot /home/venv/site-1 # adjust the following line to match your Python path WSGIDaemonProcess site-1.example.com processes=2 threads=15 display-name=%{GROUP} python-home=/home/venv/lib/python2.7 WSGIProcessGroup site-1.example.com WSGIScriptAlias / /home/venv/site-1/site-1/wsgi.py AllowOverride all Require all granted Options FollowSymlinks Alias /static/ /home/venv/site-1/static_root/ AllowOverride all Require all granted Options FollowSymlinks ServerName site-2.example.com DocumentRoot /home/venv_mob/site-2 # adjust the following line to match your Python path WSGIDaemonProcess site-2.example.com processes=2 threads=15 display-name=%{GROUP} python-home=/home/venv_mob/lib/python2.7 WSGIProcessGroup site-2.example.com WSGIScriptAlias / /home/venv_mob/site-2/site-2/wsgi.py AllowOverride all Require all granted Options FollowSymlinks Alias /static/ /home/venv_mob/site-2/static_root/ AllowOverride all Require all granted Options FollowSymlinks I have tried many solutions that I found on the web but the problem remains the same. Any ideas ?
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50773481

http://stackoverflow.com/a/50805324
has body: You have to pick correct interpreter. Click Ctrl+Shift+A, type "Project interpreter", and choose "Anaconda3" in the drop-down menu.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88616983
answers question: http://stackoverflow.com/q/50805246

http://stackoverflow.com/a/50890924
answers question: http://stackoverflow.com/q/50822978
has comment: http://stackoverflow.com/comment/88906078
type: AcceptedAnswer
downvote count: 0
score: 1
has body: You should use in cursor.copy option instead of cursor.execute. For example: # add new import: import cStringIO ... # temporary buffer buff = cStringIO.StringIO() # convert data frame to csv type for row in df.values.tolist(): buff.write('{}|{}\n'.format(*row)) # now insert data with connection.cursor() as cursor: cursor.copy('COPY test (Country, "User") FROM STDIN COMMIT' , buff.getvalue()) On my testing system following results your implementation: $ time ./so.py real 0m4.175s user 0m0.523s sys 0m0.101s my implementation: $ time ./so.py real 0m0.814s user 0m0.530s sys 0m0.078s 5 times faster(4.175s vs 0.814s).
has comment: http://stackoverflow.com/comment/95909748
type: Answer
has comment: http://stackoverflow.com/comment/88997866
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50822978

http://stackoverflow.com/a/50948457
answers question: http://stackoverflow.com/q/50815580
accepted answer of: http://stackoverflow.com/q/50815580
type: Answer
has body: There are several ways to do this. Las files have classification field, you could store the indexes in this field las_file = laspy.file.File("las.las", mode="rw") las_file.classification = indexfromshp However if the Las file has version &lt;= 1.2 the classification field can only store values in the range [0, 35], but you can use the 'user_data' field which can hold values in the range [0, 255]. Or if you need to store values higher than 255 / you need a separate field you can define a new dimension (see laspy's doc on how to add extra dimensions). Your code should be close to something like this outFile1 = laspy.file.File("laswrite2.las", mode = "w",header = inFile.header) # copy fields for dimension in inFile.point_format: dat = inFile.reader.get_dimension(dimension.name) outFile1.writer.set_dimension(dimension.name, dat) outFile1.define_new_dimension( name="index_from_shape", data_type=7, # uint64_t description = "Index of corresponding polygon from shape file" ) outFile1.index_from_shape = indexfromshp outFile1.close()
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/100151431
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88560332
score: 1
comment on: http://stackoverflow.com/q/50776137
type: Comment
type: QuestionComment
has text: @AVT not sure I understand what you ask, so maybe ask a new question (or edit this one as you don't have answer yet) but what I can see is that you don't have a file name in your `to_csv` so try something like `...Only Epidemic\\' +str(n) +'\\file_name.csv')`

django-authentication
tags question: http://stackoverflow.com/q/50826216
tags question: http://stackoverflow.com/q/50784250
tag name: django-authentication
tags question: http://stackoverflow.com/q/50822290
type: Tag

http://stackoverflow.com/q/50742269
has comment: http://stackoverflow.com/comment/88493449
favorite count: 0
tagged with: python-multithreading
linked to: http://stackoverflow.com/q/41037840
tagged with: python
has comment: http://stackoverflow.com/comment/88493527
accepted answer: http://stackoverflow.com/a/50742450
score: 2
has comment: http://stackoverflow.com/comment/88494824
downvote count: 0
has title: Matplotlib threading; closing a specific figure instance
has body: The gist of the problem is: I have a threadpool for generating images for machine learning training. I feed the pool with all images that have been annotated and I generate images from this. (it works) I then add a visualisation step, i.e., generating nice images that are human understandable. For this I use matplotlib. (it works) I then want to do this as an additional step in the pooling, and my code crashes. It seems like the issue is the close and clear statement: import matplotlib.pyplot as plt [code for visualisation] plt.savefig(f, bbox_inches='tight', pad_inches=0) plt.cla() plt.close() plt.switch_backend(backend_org) When one thread reaches the last lines all other plt crashes, therefore in Matlab one was able to specify a variable name that was operated on such that close() or other functions only executed on the specific image. I have not been able to find similar concept in matplotlib, but does it exist? Solution Just to show the object oriented code. fig = plt.figure() fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) ax = fig.add_subplot(1, 1, 1) ax.margins(0, 0) ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) label_viz = label2rgb(label, img, n_labels=len(label_names)) #generate labels ax.imshow(label_viz) ax.axis('off') plt_handlers = [] plt_titles = [] for label_value, label_name in enumerate(label_names): [...] #generate legend ax.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5) f = io.BytesIO() fig.savefig(f, bbox_inches='tight', pad_inches=0) #ax.cla() #resulting in crashes across the thread plt.close(fig)
has answer: http://stackoverflow.com/a/50742450
has comment: http://stackoverflow.com/comment/88492608
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88492334
tagged with: matplotlib
type: Question
upvote count: 2
answer count: 1

http://stackoverflow.com/q/50756032
has comment: http://stackoverflow.com/comment/88543887
tagged with: javascript
score: 0
has comment: http://stackoverflow.com/comment/88527944
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Why iframe to not exist file create empty file?
answer count: 0
tagged with: iframe
type: Question
has body: I need some help or advise. In the template of django application I have iframe widget where user select date and load xls file by url address which I set in js. If file with selected date is not exist I want to show message about it. For some reason in that case iframe create empty xls file. How to fix it? JS: var downloadSideBarFiles = { main_url: "https://example.com", file_types: { 2: "/shares/rpfile/", 1: "/shares/waprfile/" }, init: function() { var e = $(".regulations__download"); this.clickMethod(this, e) }, clickMethod: function(e, a) { a.find(".regulation__download-link").click(function(t) { t.preventDefault(); var r = a.find("input[type=radio]:checked"), o = a.find("input[type=text]"); 0 == r.length ? e.errorMethod("No file type selected") : 0 == o.val().length ? e.errorMethod("No date selected") : (type = e.file_types[r.val()], date = o.val().split("/").join("."), uri = e.main_url + type + date, e.downLoadMethod(e, uri)) }) }, errorMethod: function(e) { alert(e) }, downLoadMethod: function(e, a) { $.fileDownload(a).fail(function() { e.errorMethod("File is not exist") }) } }; views.py: def warpfile_date(request, date): if urllib.urlopen(filepath+ 'wapr' + str(date) + '.xls').code == 200: file = urllib.urlopen(filepath) response = HttpResponse(file, content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=' + 'wapr' + '.xls' else: response = HttpResponse(status=404) return response

http://stackoverflow.com/comment/88466510
has text: The ordering of your examples aren't consistent - what order are you trying to maintain?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50729340

http://stackoverflow.com/q/50850724
has comment: http://stackoverflow.com/comment/88704423
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88704519
has comment: http://stackoverflow.com/comment/88704453
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88704630
has comment: http://stackoverflow.com/comment/88704574
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88704182
tagged with: python
has comment: http://stackoverflow.com/comment/88704544
has body: I have made a pandas dataframe from a CSV file like so: import pandas as pd data = pd.read_csv('dataset.csv') In it, there's a column called CLASS. These are the values contained in CLASS: from collections import Counter Counter(CLASS) Out [1]: Counter({'1': 60783, '2': 37313, '3': 2564, '4': 959, ' ': 346, 'D': 27}) Now, I add a column to the dataframe manually, and save it in a new csv: data['DURATION'] = DURATION data.to_csv('new_dataset.csv') Then, when I open the new CSV and check the values in CLASS, some of them have become integers! dataset = pd.read_csv('new_dataset.csv') CLASS = dataset['OCCUP_CLASS'] Counter(CLASS) Out [1]: Counter({' ': 346, 1: 48418, '1': 12365, 2: 16189, '2': 21124, 3: 848, '3': 1716, 4: 81, '4': 878, 'D': 43}) Why is this happening? This creates problems as I cannot plot or make histograms of CLASS anymore, while before I was able to do so: import matplotlib.pyplot as plt plt.plot(CLASS) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-158-b6bafcfd7ad5&gt; in &lt;module&gt;() 1 import matplotlib.pyplot as plt ----&gt; 2 plt.plot(CLASS) c:\users\h473\appdata\local\programs\python\python35\lib\site-packages\matplotlib\pyplot.py in plot(*args, **kwargs) 3356 mplDeprecation) 3357 try: -&gt; 3358 ret = ax.plot(*args, **kwargs) 3359 finally: 3360 ax._hold = washold c:\users\h473\appdata\local\programs\python\python35\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) 1853 "the Matplotlib list!)" % (label_namer, func.__name__), 1854 RuntimeWarning, stacklevel=2) -&gt; 1855 return func(ax, *args, **kwargs) 1856 1857 inner.__doc__ = _add_data_doc(inner.__doc__, c:\users\h473\appdata\local\programs\python\python35\lib\site-packages\matplotlib\axes\_axes.py in plot(self, *args, **kwargs) 1526 1527 for line in self._get_lines(*args, **kwargs): -&gt; 1528 self.add_line(line) 1529 lines.append(line) 1530 c:\users\h473\appdata\local\programs…
has comment: http://stackoverflow.com/comment/88706272
has comment: http://stackoverflow.com/comment/88706957
has comment: http://stackoverflow.com/comment/88704775
has comment: http://stackoverflow.com/comment/88706315
type: Question
has comment: http://stackoverflow.com/comment/88706718
has title: Why are some values in the pandas dataframe becoming integers from strings after I add a column to the dataframe manually?
answer count: 1
has answer: http://stackoverflow.com/a/50852021

http://stackoverflow.com/a/50720925
downvote count: 0
answers question: http://stackoverflow.com/q/50720165
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50720165
type: AcceptedAnswer
has body: When you're iterating over the result variable, you're iterating over pysolr's own Results object (and not directly over the JSON structure as shown by Solr). import pysolr import pprint conn = pysolr.Solr('http://localhost:8080/solr/corename') result = conn.search('*:*', **{ 'fl': 'content', 'facet': 'true', 'facet.field': 'field_name' }) pprint.pprint(result.facets) Any facets will be present under the facets property of this results object. The example above outputs: {'facet_dates': {}, 'facet_fields': {'field_name': ['value', 54439, 'value2', 21179]}, 'facet_intervals': {}, 'facet_queries': {}, 'facet_ranges': {}}
type: Answer
score: 2

least-squares
tags question: http://stackoverflow.com/q/50782004
tags question: http://stackoverflow.com/q/50706410
tags question: http://stackoverflow.com/q/50770569
tags question: http://stackoverflow.com/q/50725425
tags question: http://stackoverflow.com/q/50705637
tag name: least-squares
type: Tag

http://stackoverflow.com/comment/88605773
score: 0
comment on: http://stackoverflow.com/q/50799552
type: Comment
type: QuestionComment
has text: Yes, I'm updating to clearly explain how! :)

http://stackoverflow.com/q/50799076
favorite count: 0
tagged with: python-3.x
has body: From a post request, I receive a base64 in JSON. Problem is that I can't just change the file type from string to base64 since it's already formatted as base64. need the base64 to convert it back to an image. json_data = request.get_json(force=True) img = json_data['img'] print(img) with open("imageToSave.png", "wb") as fh: fh.write(base64.decodebytes(img))
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50799421
type: Question
score: 3
tagged with: http://stackoverflow.com/tag/json
has title: string formatted as base64 to base64 object
accepted answer: http://stackoverflow.com/a/50799421
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/88506757
type: AnswerComment
has text: Why does it only account for a single character? My loop iterates through a list of special characters and removes any that it finds. And with recursive = True it should recursively search the whole directory tree from /home/.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50746903

http://stackoverflow.com/comment/88432055
has text: Just `df.median()` works :D, the default behavior is to ignore `NaN`
comment on: http://stackoverflow.com/a/50711570
type: AnswerComment
type: Comment
score: 3

http://stackoverflow.com/comment/88712025
type: AnswerComment
has text: no you can not do that. you will have to save that image and pass it to cv2.imread() as a file variable
comment on: http://stackoverflow.com/a/50854362
type: Comment
score: 1

http://stackoverflow.com/comment/88606183
type: AnswerComment
score: 2
type: Comment
has text: Dear @EoinS, you made me smile when I read your code. I am sure it will work. I liked how you used a real unusual approach to solve the problem: going over strings. However, imagine yourself reunderstanding your own code in a few years. It could be difficult.
comment on: http://stackoverflow.com/a/50799321

http://stackoverflow.com/q/50803780
has comment: http://stackoverflow.com/comment/88730526
has comment: http://stackoverflow.com/comment/88729474
has title: eBay SDK not recognizing sandbox user account
type: Question
has answer: http://stackoverflow.com/a/50942224
score: 3
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88836880
has body: This is the contents of my ebay.yaml file: name: ebay_api_config # Trading API Sandbox - https://www.x.com/developers/ebay/products/trading-api api.sandbox.ebay.com: compatability: 719 appid: XXXXXXXXXX certid: XXXXXXXXXX devid: XXXXXXXXXXX token: XXXXXXXXXXX I'm using the exact file from https://github.com/timotheus/ebaysdk-python/blob/master/samples/trading.py to try to test my new Sandbox account, and the majority of the functions are working successfully, however I get following errors when trying to run VerifyAddItem function: Call Success: 4670 in length Response code: 200 Response DOM1: &lt;DOM Element: GetFeedbackResponse at 0x101281170&gt; Response ETREE: &lt;Element GetFeedbackResponse at 0x10124d050&gt; Response dictionary: {'FeedbackScore': '0', 'Ack': 'Success', 'Timestamp': '2018-06-11T18:09:11.892Z', 'Version': '1003', 'FeedbackSummary': {'NegativeFeedbackPeriodArray'... Response Reply: {'FeedbackScore': '0', 'Ack': 'Success', 'Timestamp': datetime.datetime(2018, 6, 11, 18, 9, 11), 'Version': '1003', 'FeedbackSummary': {'NegativeFeedb Sell more, buy more.. u"VerifyAddItem: Class: RequestError, Severity: Error, Code: 120, You need to create a seller's account. Before you can list this item we need some additional information to create a seller's account." {'Ack': 'Failure', 'Timestamp': '2018-06-11T18:09:13.751Z', 'Errors': [{'SeverityCode': 'Warning', 'ErrorClassification': 'RequestError', 'ErrorCode': '21920200', 'LongMessage': 'Return Policy Attribute returnDescription Not Valid On This Site', 'ErrorParameters': {'_ParamID': '0', 'Value': 'returnDescription'}, 'ShortMessage': 'Return Policy Attribute Not Valid'}, {'ErrorCode': '21919158', 'LongMessage': "The email address you entered isn't linked to a PayPal account. If you don't have a PayPal account, you'll need to set one up with this address so that buyers can pay you. (You can set up your account after your item sells).", 'ErrorClassification': 'RequestError', 'SeverityCode': 'Warning', 'ShortM…
has comment: http://stackoverflow.com/comment/88872904
tagged with: python
tagged with: ebay-api
has comment: http://stackoverflow.com/comment/88729780
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88712067
tagged with: sandbox

http://stackoverflow.com/comment/88516816
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50754183
has text: @TobiasBrösamle Reload your page and see my edit. This is fixed.
score: 0

http://stackoverflow.com/comment/88869912
comment on: http://stackoverflow.com/a/50845016
type: Comment
has text: It's software too; bugs are always possible. ;) My key point is it is not an issue with VS Code, and so either PyLint is not installed and being run from the same environment that you have PySide installed into or PyLint simply can't deduce that there is an attribute as you expect.
score: 0
type: AnswerComment

nosql
tags question: http://stackoverflow.com/q/50719426
tag name: nosql
type: Tag

http://stackoverflow.com/q/50744568
has comment: http://stackoverflow.com/comment/88499406
tagged with: python
score: -2
favorite count: 0
type: UnansweredQuestion
downvote count: 2
type: Question
has title: How to create a frequency table of a variable?
upvote count: 0
answer count: 1
has body: I'd like to create a Frequency Table in Python using bins. My data has a 'Population' column. Population 563626 625741 672591 710231 814180 897934 989415 What I want to achieve is something like: Population 563626 - 625741 625741 - 672591 710231 - 814180 897934 - 989415 ... and be able to specify how many bins to use. Any advice? (I've seen something similar to R's cut() function.)
has answer: http://stackoverflow.com/a/50744795

http://stackoverflow.com/a/54873700
has body: The logic for determining running notebook servers relies on iterating over all files in runtime-dir with prefix "nbserver-" and trying to load as JSON. Therefore, a malformed file in this folder may be causing the JSON error. Solved this by deleting all files under the Jupyter runtime-dir: $ jupyter --runtime-dir /home/user/.local/share/jupyter/runtime $ cd $(jupyter --runtime-dir) &amp;&amp; rm *
answers question: http://stackoverflow.com/q/50743275
type: Answer
upvote count: 9
has comment: http://stackoverflow.com/comment/102725226
has comment: http://stackoverflow.com/comment/98374828
score: 9
downvote count: 0

http://stackoverflow.com/a/50840405
has body: The reason is that in Python 2, print(a,b) does not print a and b, but it prints (a, b), i.e. a tuple. Thus, print(a) will call str(a) (the (...) won't make a single element into a tuple), whereas print(a,b) calls the __str__ of the tuple (a, b), which in turn calls the __repr__ of the individual elements. (And if no __repr__ is defined, then it will print the type and memory address by default.) Minimal example: class Test: def __str__(self): return "str" def __repr__(self): return "repr" t = Test() print(t) print(t, t) Output using Python 2: str (repr, repr) On Python 3, on the other hand, or when doing print t, t in Python 2, without the (...), print will call str on both elements directly. str str str Also, unrelated to the problem, I'd suggest changing your Human class to something like this, defining proper methods and not using kwargs. class Human(object): def __init__(self, first, last, height=None, weight=None): self.first_name = first self.last_name = last self.height = height self.weight = weight def bmi(self): return self.weight/float(self.height)**2 def __str__(self): return '{} {}'.format(self.first_name, self.last_name)
type: Answer
answers question: http://stackoverflow.com/q/50839856
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50839856
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50725340
has comment: http://stackoverflow.com/comment/88460472
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Why can't I break out of my loop? (Python)
has comment: http://stackoverflow.com/comment/88458986
has comment: http://stackoverflow.com/comment/88458967
has body: import rando move = rando.Moves() All of this junk is just writing to a file to give some context about the game oof = open('README.txt', 'w') #opens the text file oof.write("The Final Adventure\n") oof.write("\n") #writes text to the file oof.write("This game is about an adventurer(you) trying to fight through a dungeon in order to get the legendary sword of mythos.\n") oof.write("\n") oof.write("With this legendary sword you can finally rid your homeland of the evil king of Mufasa and take the mantle of kingship.\n") oof.write("\n") oof.write("Best of luck to you, Warrior!\n") oof.write("\n") oof.write("You have 3 move options with any enemy you encounter.\n") oof.write("\n") oof.write("1 - Attack\n") oof.write("2 - Run Away\n") oof.write("3 - Talk\n") oof.write("Have fun!!") oof.close() #closes the file print("Please read the README.txt in this file") player = True A buddy of mine told me I had to have two while loops so not too sure why I need those but it works slightly like it's meant to. while True: while player: #First Door print("You walk through the forest until you finally find the talked about entrance door.") print("There is a Gatekeeper standing by the entrance and in order to enter you must defeat him") print("") move = int(input("What will you do?(Please use numbers 1-2-3 for moves) ")) The problem is here. I have a module that I made that if the attack fails, you die and player gets set to False but it still continues the while loop. if move == 1: rando.Moves.move1(player) elif move == 2: rando.Moves.move2(player) elif move == 3: rando.Moves.move3(player) else: print("You ran out of time and died") player = False if player == False: break #First Room print("The door suddenly opens and you walk through.") print("") print("After walking for a bit you discover a chest, probably full of loot!") print("You walk up and begin to open the chest and it clamps down on your hand with razor sharp teeth.") print("ITS A MONSTER!") print("After struggling, you are…
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/50725449
score: 0
tagged with: while-loop

http://stackoverflow.com/comment/88678435
type: Comment
type: QuestionComment
has text: I don't understand why this surprises you. You have a URL which contains one parameter, you click on a URL which doesn't contain that parameter, why would you think your original parameter would be there?
comment on: http://stackoverflow.com/q/50836922
score: 0

http://stackoverflow.com/comment/88553033
type: Comment
type: QuestionComment
has text: You're writing `Words.txt` and sending `words.csv`?
score: 1
comment on: http://stackoverflow.com/q/50772851

http://stackoverflow.com/a/50866516
has comment: http://stackoverflow.com/comment/88827169
has comment: http://stackoverflow.com/comment/88807594
has body: Your question is really general, however I have some suggestions. You could use cross-validation and try different models. Personnaly, I would try SVR,RandomForests and as last choice I would use a MLPR. I modified a bit your code to show a simple example: import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report,confusion_matrix import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_predict from sklearn import svm from sklearn.model_selection import cross_val_score from sklearn.metrics import confusion_matrix from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.model_selection import LeaveOneOut import pandas as pd from sklearn.decomposition import PCA # read the data df = pd.read_excel('python_excel_read.xlsx', header = None) rows, cols = df.shape X = df.iloc[: , 0:(cols - 1)] y = df.iloc[: , cols - 1 ] print(X.shape) print(y.shape) y[y &lt; 500] = 0 y[np.logical_and(y &gt;= 500, y &lt;= 1000)] = 1 y[np.logical_and(y &gt; 1000, y &lt;= 1200)] = 2 y[y &gt; 1200] = 3 print(np.unique(y)) # We can apply PCA to reduce the dimensions of the data # pca = PCA(n_components=2) # pca.fit(X) # X = pca.fit_transform(X) # Use cross-validation #kf = KFold(n_splits = 10, random_state=0) loo = LeaveOneOut() # Try different models clf = svm.SVC(kernel = 'linear') scaler = StandardScaler() pipe = Pipeline([('scaler', scaler), ('svc', clf)]) accuracy = cross_val_score(pipe, X, y.ravel(), cv = loo, scoring = "accuracy") print(accuracy.mean()) #y_pred = cross_val_predict(clf, X, y.ravel(), cv = kf) #cm = confusion_matrix(y, y_pred)
has comment: http://stackoverflow.com/comment/88942399
has comment: http://stackoverflow.com/comment/88761565
upvote count: 1
has comment: http://stackoverflow.com/comment/89026701
has comment: http://stackoverflow.com/comment/88768636
has comment: http://stackoverflow.com/comment/88846213
has comment: http://stackoverflow.com/comment/88804819
has comment: http://stackoverflow.com/comment/88827658
has comment: http://stackoverflow.com/comment/88773901
has comment: http://stackoverflow.com/comment/88912753
has comment: http://stackoverflow.com/comment/89130510
type: Answer
answers question: http://stackoverflow.com/q/50847386
has comment: http://stackoverflow.com/comment/89130514
has comment: http://stackoverflow.com/comment/88769262
downvote count: 0
has comment: http://stackoverflow.com/comment/89132664
has comment: http://stackoverflow.com/comment/88943615
has comment: http://stackoverflow.com/comment/88761528
has comment: http://stackoverflow.com/comment/88987957
has comment: http://stackoverflow.com/comment/89106315
has comment: http://stackoverflow.com/comment/89047734
has comment: http://stackoverflow.com/comment/88945137
has comment: http://stackoverflow.com/comment/89124418
has comment: http://stackoverflow.com/comment/88827038
has comment: http://stackoverflow.com/comment/89030470
has comment: http://stackoverflow.com/comment/88936317
score: 1
has comment: http://stackoverflow.com/comment/88994666
has comment: http://stackoverflow.com/comment/89124378

http://stackoverflow.com/q/50822119
has comment: http://stackoverflow.com/comment/88650491
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88649762
has comment: http://stackoverflow.com/comment/88650424
tagged with: python-imaging-library
has title: Numpy array to PIL image format
accepted answer: http://stackoverflow.com/a/50823003
has comment: http://stackoverflow.com/comment/88649997
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88649306
score: 4
tagged with: image
linked to: http://stackoverflow.com/q/10965417
has body: I'm trying to convert an image from a numpy array format to a PIL one. This is my code: img = numpy.array(image) row,col,ch= np.array(img).shape mean = 0 # var = 0.1 # sigma = var**0.5 gauss = np.random.normal(mean,1,(row,col,ch)) gauss = gauss.reshape(row,col,ch) noisy = img + gauss im = Image.fromarray(noisy) The input to this method is a PIL image. This method should add Gaussian noise to the image and return it as a PIL image once more. Any help is greatly appreciated!
answer count: 1
has answer: http://stackoverflow.com/a/50823003
has comment: http://stackoverflow.com/comment/88649446
favorite count: 0
has comment: http://stackoverflow.com/comment/88649267
has comment: http://stackoverflow.com/comment/88649335
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88649382
upvote count: 6

http://stackoverflow.com/q/50699646
answer count: 1
has comment: http://stackoverflow.com/comment/88408772
favorite count: 0
has comment: http://stackoverflow.com/comment/88408742
type: UnansweredQuestion
score: -3
tagged with: python
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/88408468
upvote count: 0
has title: factorial of a number in python,using for loop and while loop
has answer: http://stackoverflow.com/a/50700192
has body: i ran the code but no output is coming var = int(input("Enter A Number")) if(var&lt;=0): print("Invalid number") product = 1 for i in range(var): product*=var var-=1 while(var==0): print(product) break why it is not executing,no result is coming? O/P: Enter A Number 3 Process finished with exit code 0

http://stackoverflow.com/q/50800042
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: loops
downvote count: 1
linked to: http://stackoverflow.com/q/33747968
type: Question
has title: Python , get duplicates in 1st column of all csv files in a directory
has answer: http://stackoverflow.com/a/50808068
tagged with: duplicates
score: -1
has body: import pandas as pd import glob dataset = pd.read_csv('masterfeedproduction-EURNA_2016-06-27.csv',sep = ',',delimiter = None) # select 1 file in the directory datasets_cols = ['transactionID','gvkey','companyName'] df= dataset.transactionID df.shape df.loc[df.duplicated()] returns the duplicates in the selected file. displays row number and transactionID. so this is correct. target_directory = r'C:\Users\nikol\Downloads\fullDailyDeltas\fullDailyDeltas' file_list = glob.glob(target_directory + "/*.csv") df_result = df.loc[df.duplicated()] for file in file_list: return(df_result) here I am stuck. target_directory = r'C:\Users\nikol\Downloads\fullDailyDeltas\fullDailyDeltas' file_list = glob.glob(target_directory + "/*.csv") for file in file_list: dataset = pd.read_csv(file) df = dataset.transactionID duplicated = df.loc[df.duplicated()] if duplicated.empty == False: print(file) print(duplicated)
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88411379
type: QuestionComment
has text: How do you define a diagonal that is at 60 degrees? Doing the sum on 45 degrees is simple, but I do not even know how to define the 60 degree diagonal. NOTE: this will depend on the shape of your matrix.
score: 1
comment on: http://stackoverflow.com/q/50700256
type: Comment

http://stackoverflow.com/q/50837943
has title: Collect data from a class based form UpdateView django for use in views.py
tagged with: django
type: Question
type: AnsweredQuestion
tagged with: django-views
tagged with: django-models
has comment: http://stackoverflow.com/comment/88679955
tagged with: django-forms
has answer: http://stackoverflow.com/a/50838522
accepted answer: http://stackoverflow.com/a/50838522
answer count: 1
has body: I have a form based on my model "configuration" : models.py class configuration(models.Model): Num_ordre = models.CharField(max_length=15) Composant = models.CharField(max_length=15) Designation = models.CharField(max_length=15) Qte_servie = models.IntegerField() Qte_a_servir = models.IntegerField() Lot = models.CharField(max_length=15) Categorie = models.CharField(max_length=15) Famille = models.CharField(max_length=15) From this model I create a form with the UpdateView function : views.py class ComposantUpdate(UpdateView): model = configuration fields = '__all__' template_name = 'accueil/exploitation/update_composant.html' success_url = reverse_lazy('cahier', args=('OFTSP1611000853',))` My problem is that the success_url gets an argument I have entered manually : OFTSP1611000853 which corresponds to configuration.Num_ordre for pk=1. Instead of 'OFTSP1611000853' I want to put the data written by the user in the corresponding field in the form. How can I collect this value ?
score: 0
linked to: http://stackoverflow.com/q/11027996
tagged with: python

http://stackoverflow.com/comment/105845006
score: 0
type: AnswerComment
has text: So, is there a possibility to use a model pre-trained on multiple Cuda devices when only a single one is available?
type: Comment
comment on: http://stackoverflow.com/a/55730579

http://stackoverflow.com/comment/89519343
type: Comment
comment on: http://stackoverflow.com/q/50751040
score: 0
type: QuestionComment
has text: @StephenRauch changing filename results, yes, but importing functions from this files is not possible. Since I am using multi-command call this isn't work for this issue.

http://stackoverflow.com/q/50786308
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/88578989
has comment: http://stackoverflow.com/comment/120598078
has answer: http://stackoverflow.com/a/74326236
has comment: http://stackoverflow.com/comment/88579164
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50786360
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/88579072
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88579114
has body: I have a function inside inside another and a third function. How can I call my nested function inside of my third function? Is there any special libraries I can use? I am not allowed to edit a() or b(), only c(). def a(): def b(): print("hi") def c(): # code only here to call b() to print
has title: Call nested function from another function in python?
has answer: http://stackoverflow.com/a/50786383

http://stackoverflow.com/q/50732293
favorite count: 0
has comment: http://stackoverflow.com/comment/88472776
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/6345840
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50761058
has body: I am making a game with pygame and I have a file called "settings_template.py" and another file called "pygame_functions.py" and when I import in my variables it gives me an error "NameError: name 'FPS' is not defined" however, I defined "FPS" in "settings_template.py". I don't know what the problem is and I've tried everything. This is in my "settings_template.py" FPS = 10 # how fast the game runs (frames per second) and this is in my "pygame_functions.py" from settings_template import * def showSprite(sprite): global FPS spriteGroup.add(sprite) gameClock.tick(FPS) # changed updateDisplay to tick for better framerate I also tried it without global FPS but it made no difference. If anyone could help me out I will be eternally grateful :)
tagged with: global-variables
has comment: http://stackoverflow.com/comment/88472603
type: Question
has title: how to use a predefined global variable inside a function on a different file
downvote count: 0
has comment: http://stackoverflow.com/comment/88472609
accepted answer: http://stackoverflow.com/a/50761058
answer count: 1

http://stackoverflow.com/a/50823409
score: 5
answers question: http://stackoverflow.com/q/50823043
upvote count: 5
has body: min((v,i) for i,v in enumerate(l) if v is not None) (1.0, 3) # (value, index)
has comment: http://stackoverflow.com/comment/88652278
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50823043

http://stackoverflow.com/comment/88623924
type: AnswerComment
score: 0
type: Comment
has text: At the least, I'd say some more test examples are required to work towards a general solution.
comment on: http://stackoverflow.com/a/50808447

http://stackoverflow.com/comment/88551183
score: 0
type: Comment
has text: I sent you a message. Please agree to go
type: AnswerComment
comment on: http://stackoverflow.com/a/50770785

http://stackoverflow.com/q/50774864
upvote count: 2
tagged with: pandas
answer count: 1
favorite count: 0
has title: Replacing null values in Pandas data frame with a series
has answer: http://stackoverflow.com/a/50774929
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/36921951
score: 2
downvote count: 0
has body: I created a function to replace missing values with knn in Python, following is my function: def missing_variables_knn(x): test = data[data[x].isnull()] train = data[data[x].isnull()==False] X_train = train.loc[:, ['ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term']] Y_train = train[x] X_test = test.loc[:, ['ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term']] knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, Y_train) pred = knn.predict(X_test) pred = pd.Series(pred) data[x].fillna(pred) When I used missing_variables_knn('Gender'), I got an error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
type: Question

http://stackoverflow.com/comment/88665126
score: 0
type: Comment
type: QuestionComment
has text: Can you post a sample of your df?
comment on: http://stackoverflow.com/q/50828886

http://stackoverflow.com/comment/88600243
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50797009
has text: Furthermore it is strange to search for a *single* `B` that has as a related `A` a specific slug: there can be *multiple* such `B`s. How will you decide which one it is?
type: Comment

http://stackoverflow.com/q/50782056
has answer: http://stackoverflow.com/a/64460972
has comment: http://stackoverflow.com/comment/88718930
downvote count: 0
favorite count: 0
score: 8
has body: I want to execute this code in Pycharm x, y = pyautogui.locateCenterOnScreen('LVL35.png') But I get this message ImportError: Pillow module must be installed to use screenshot functions on Windows. The thing is, I use anaconda and Pillow is already installed and I can also find it in the Project Interpreter settings. Requirement already satisfied: Pillow in c:\anaconda3\lib\site-packages (4.2.1) Any idea?
upvote count: 8
tagged with: importerror
possible better answer: http://stackoverflow.com/a/64460972
answer count: 5
has answer: http://stackoverflow.com/a/68548563
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50871295
has comment: http://stackoverflow.com/comment/88743664
has answer: http://stackoverflow.com/a/75089483
type: Question
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/70501596
has title: pyautogui, screenshot function doesn't recognize installed Pillow module
tagged with: pyautogui
accepted answer: http://stackoverflow.com/a/50871295

http://stackoverflow.com/comment/88684540
has text: I tried but end up with below error, I don't want to filter anything. I just required to select all rows of that given columns. return cls.query(bn) TypeError: 'BaseQuery' object is not callable
score: 0
comment on: http://stackoverflow.com/q/50838394
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50712657
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50712920
has body: Good Morning, I will unittest the following class class Sample(object): def __init__(self, dictionary_with_all_button_data, path_to_trunk): self.dictionary_with_all_button_data = dictionary_with_all_button_data self.path_to_trunk = path_to_trunk self.error_main = None self.create_mainframe() self.create_label() self.create_buttons() self.start_mainloop() def create_mainframe(self): self.error_main = NewMainFrame() self.error_main.get_mainframe().title('Hinweis') self.error_main.get_mainframe().geometry(self.get_geometry()) def create_label(self): self.note = """ Der Trunk ist noch nicht Commitet, wenn sie fortfahren, erstellen Sie ein Tag das nicht die aktuelle version des Trunks enthält Wollen sie einen Automatischen Commit ausführen ? dann drücken sie Ja, drücken Sie Nein um ohne commit fortzufahren, zum Beenden drücken Sie abbrechen""" self.hinweis = Label(self.error_main.get_mainframe(), text=self.note, justify=LEFT) self.hinweis.place(width=400, height=150) def create_buttons(self): self.yes_button = NewButton(self.error_main.get_mainframe(), 'Ja', 9, 1, 55, 150, '#0A4C82', 'White', ExitButtonEvent().start_Event) self.no_button = NewButton(self.error_main.get_mainframe(), 'Nein', 9, 1, 155, 150, '#0A4C82', 'White', OpenFolder(self.path_to_trunk, self.error_main).start_Event) self.cancel_button = NewButton(self.error_main.get_mainframe(), 'Abbrechen', 9, 1, 255, 150, '#0A4C82', 'White', CancelEvent(self.error_main).start_Event) def start_mainloop(self): self.error_main.get_mainframe().mainloop() def get_geometry(self): return '400x200+' + str(self.get_mainframe_horizontal_position()) + '+' + str( self.get_mainframe_vertical_position()) def get_mainframe_horizontal_position(self): for element in self.dictionary_with_all_button_data['MainFrame']: return self.dictionary_with_all_button_data['MainFrame']['mainframe'].get_mainframe().winfo_x() def get_mainframe_vertical_position(self): for element in self.dictionary_with_all_button_data['MainFrame']: return self.dict…
tagged with: python
has title: Python how to supress tkinter mainloop() for Unittests
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/50712920
score: 1
upvote count: 1
tagged with: unit-testing

http://stackoverflow.com/q/50807254
tagged with: object-detection-api
has body: I am super new to the field of object detection. I was wondering if anyone can help me somehow on how I can download and use the object detection datasets such as coco or pascal. When I go to their website even after downloading the datasets i feel like i dont know what should i do with them... I know this question is stupid, but a hint to start can be super useful. Thanks
tagged with: python
tagged with: computer-vision
accepted answer: http://stackoverflow.com/a/52325290
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52325290
type: Question
linked to: http://stackoverflow.com/q/52177969
favorite count: 0
upvote count: 3
answer count: 1
has title: How to download and use object detection datasets (e.g. coco or pascal)
tagged with: object-detection

http://stackoverflow.com/q/50724040
answer count: 2
possible better answer: http://stackoverflow.com/a/50724268
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
has body: I have a DataFrame I created using pandas and want to create new table based on the original, but filtered based on certain conditions. df = pd.DataFrame( [['Y', 'Cat', 'no', 'yes', 6], ['Y', 4, 7, 9, 'dog'], ['N', 6, 4, 6, 'pig'], ['N', 3, 6, 'beer', 8]], columns = ('Data', 'a', 'b', 'c', 'd') ) My condition that doesnt work: if (df['Data']=='Y') &amp; (df['Data']=='N'): df3=df.loc[:,['Data', 'a', 'b', 'c']] else: df3=df.loc[:,['Data', 'a', 'b']] I want the new table to contain data that matches the following criteria: If df.Data has value 'Y' and 'N', the new table get columns ('Data', 'a', 'b') If not, the new table gets columns ('Data', 'a', 'b', 'c') Data a b 0 Y Cat no 1 Y 4 7 2 N 6 4 3 N 3 6 Data a b c 0 Y Cat no yes 1 Y 4 7 9 2 Y 6 4 6 3 Y 3 6 beer
has answer: http://stackoverflow.com/a/50724147
accepted answer: http://stackoverflow.com/a/50724147
score: 2
type: AnsweredQuestion
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/88479922
has answer: http://stackoverflow.com/a/50724268
has title: Using the condition, select the desired columns in pandas DataFrame
type: Question
has comment: http://stackoverflow.com/comment/88456682
upvote count: 2

http://stackoverflow.com/q/50767163
has title: Reproducing OLS prediction Python statsmodel
type: Question
tagged with: statsmodels
tagged with: linear-regression
score: 0
has body: I've trained a OLS model in Python using statsmodels OLS. With the code below i've trained the model: import statsmodels.api as sm X2 = sm.add_constant(lin_x_train) est = sm.OLS(lin_y_train, X2) est2 = est.fit() Using est2.params I obtain the following paramters: const -0.394654 pow2 0.920915 eth_36hr -0.028754 eth_24dhr -0.068346 eth_16hr 0.064768 eth_72hr 0.001774 eth_48hr 0.001239 eth_24hr 0.026940 eth_2hr -0.163568 eth_3hr -0.042497 eth_4hr 0.033180 eth_5hr -0.029850 eth_6hr -0.040417 Now I want to predict the following case: pow2 0 eth_36hr 2.91 eth_24dhr 1.34 eth_16hr 1.13 eth_72hr 13 eth_48hr 6.66 eth_24hr -9.89 eth_2hr -3.7 eth_3hr 2.37 eth_4hr 2.36 eth_5hr -2.28 eth_6hr -5.27 Since I've trained a OLS model I was under the assumption that it was simply: y = a + B1 * X1 + B2 *X2 + .... Bn*Xn When I compute this myself I get a Y value of 0.132 However using: Xnew = newcase Xnew = sm.add_constant(Xnew) est2.predict(Xnew) I get a value of 0.699 What am I missing? N.b. using LinearRegression from sklearn I get the same value of 0.699. So I'm clearly missing something. But I can't get my head around it.
has answer: http://stackoverflow.com/a/50872261
answer count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50872261
tagged with: predict

http://stackoverflow.com/a/50878300
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50767157
has comment: http://stackoverflow.com/comment/88776255
has comment: http://stackoverflow.com/comment/88868844
has body: Just wondering, why did you skip the regularization step? Have you tried running program with regularization?

http://stackoverflow.com/a/72804599
downvote count: 0
score: 1
has body: Using threads is not really that much of a hassle since 3.2 when concurrent.futures was added: from urllib3 import ProxyManager from concurrent.futures import ThreadPoolExecutor,wait url_list:list = ['https://URL1.com', 'http://URL2.com', 'http://URL3.com'] thread_pool:ThreadPoolExecutor = ThreadPoolExecutor(max_workers=min(len(url_list),20)) http:ProxyManager = ProxyManager("PROXY-PROXY") tasks = [] for url in url_list: tasks.append(thread_pool.submit(http.request,url,preload_content=False)) wait(tasks) all_responses:list = [task.result().read().decode() for task in tasks] Later versions offer an event loop via asyncio. Issues I've had with asyncio are usually related to portability of libraries (IE aiohttp via pydantic), most of which are not pure python and have external libc dependencies. This can be an issue if you have to support a lot of docker apps which might have musl-libc(alpine) or glibc(everyone else).
upvote count: 1
answers question: http://stackoverflow.com/q/50823753
type: Answer

http://stackoverflow.com/q/50831647
type: Question
has title: dtype('<M8[ns]') Error
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/50831871
favorite count: 0
tagged with: datetime
has body: I'm kind of new to python, today I was trying to do some operations in a financial DataFrame (first column of YYYY-MM-DD and second one of values). When I tried to apply a simple pct_change() operation, it gave me this error: TypeError: ufunc true_divide cannot use operands with types dtype('&lt;M8[ns]') and dtype('&lt;M8[ns]') What is this error exactly caused by? And how can I work around it? Because I couldn't really find many explanations online. Thanks a lot in advance!
tagged with: python
tagged with: error-handling
upvote count: 1
has answer: http://stackoverflow.com/a/50831871
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88667514

http://stackoverflow.com/comment/88667357
has text: I want the final array to include all possible scores, returning zero if that score is not in home team scores, otherwise return the sum of the score. How can I go about it? Im my list there are 36 possible scores
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50831430
score: 0

http://stackoverflow.com/comment/88706915
type: QuestionComment
type: Comment
has text: Does it work locally?
comment on: http://stackoverflow.com/q/50852056
score: 0

http://stackoverflow.com/q/50718447
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/50718782
accepted answer: http://stackoverflow.com/a/50718782
possible better answer: http://stackoverflow.com/a/50718821
tagged with: python
has body: I am new to Keras and would like to build a neural network with two outputs. Basically, what I do is that I set the Dense function of the last layer to 2 just as follows model.add(Dense(2, activation = 'relu',kernel_initializer=RandomNormal(mean=0.0, stddev=0.05, seed=0))) is that correct? Thank you for your help
has title: A neural networks with two outputs
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50718821
score: 1
answer count: 2
tagged with: neural-network
downvote count: 0

http://stackoverflow.com/a/50779377
type: Answer
upvote count: 15
accepted answer of: http://stackoverflow.com/q/50779346
downvote count: 0
score: 15
type: AcceptedAnswer
has body: The problem is you are using np.matrix. Use np.array instead and simply iterate without indexing: result = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) for p in result: print(p) [11 12 13] [21 22 23] [31 32 33] Explanation What you are seeing is the effect of numpy.matrix requiring each row to have 2 dimensions. This is unnecessary and anti-pattern for NumPy. There is a history behind numpy.matrix. It was used initial for convenience of matrix multiplication operators. But this is no longer an issue since @ is possible (Python 3.5+) instead of nested dot calls. Therefore, by default, use numpy.array.
answers question: http://stackoverflow.com/q/50779346

http://stackoverflow.com/comment/122538183
comment on: http://stackoverflow.com/a/50855254
type: AnswerComment
score: 0
type: Comment
has text: Is there an answer to how the package can be imported?

http://stackoverflow.com/comment/88429184
has text: Yes, i saw that, that is what i'm trying to fix right now, can I begin like this `.append([None, None, None])`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50708033

http://stackoverflow.com/comment/92516802
comment on: http://stackoverflow.com/a/50779334
type: AnswerComment
score: 0
type: Comment
has text: mu is the mean and sigma is the variance.

http://stackoverflow.com/comment/88695899
type: Comment
comment on: http://stackoverflow.com/a/50846154
has text: what you want to do with your output?
type: AnswerComment
score: 0

http://stackoverflow.com/q/50798952
has comment: http://stackoverflow.com/comment/88604294
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88604912
tagged with: apply
has comment: http://stackoverflow.com/comment/88604718
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/50799291
answer count: 1
has body: I am trying to add a column to a pandas dataframe import pandas as pd df = pd.DataFrame([['a',1],['b',0],['c',1],['d',1],['e',0],['f',1]]) such that it contains the result of a cumulative custom function a --&gt; (total + a) * a that is, it takes the value a, sums it up with the total and multiplies the result. In my example I would like to have as output: pd.DataFrame([['a',1,1],['b',0,0],['c',1,1],['d',1,2],['e',0,0],['f',1,1]]) I understand that this could be done using df.expanding.apply(some_lambda_function) but I have some difficult in understanding how to code it. Do you have any idea? many thanks.
has title: Cumulative custom function
has comment: http://stackoverflow.com/comment/88603993
has comment: http://stackoverflow.com/comment/88604405
has comment: http://stackoverflow.com/comment/88604591
has comment: http://stackoverflow.com/comment/88604010
has comment: http://stackoverflow.com/comment/88604060
has comment: http://stackoverflow.com/comment/88603890
has answer: http://stackoverflow.com/a/50799291
tagged with: pandas
has comment: http://stackoverflow.com/comment/88604199
has comment: http://stackoverflow.com/comment/88604528
favorite count: 0
has comment: http://stackoverflow.com/comment/88604096
has comment: http://stackoverflow.com/comment/88604274
tagged with: python
score: 2

http://stackoverflow.com/comment/88497100
type: Comment
has text: Better to use `arange` then a list comprehension when using `numpy` here
score: 1
comment on: http://stackoverflow.com/a/50744671
type: AnswerComment

http://stackoverflow.com/q/50829342
tagged with: selenium
has body: With a droplet on DigitalOcean, is it possible to use a floating ip when starting a Selenium WebDriver in Python? This is the code being used to start the webdriver. What do I need to do to make it use a floating IP? from selenium import webdriver browser = webdriver.Chrome(my_driver_location, chrome_options=chromeOptions) browser.get(start_page)
has answer: http://stackoverflow.com/a/52230257
tagged with: digital-ocean
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88664817
has title: How to set up Selenium WebDriver (Python) with DigitalOcean floating IP
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88698627
type: UnansweredQuestion

http://stackoverflow.com/q/50743569
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50747386
has comment: http://stackoverflow.com/comment/88525502
favorite count: 0
has title: How to get parent values in default_get function? In Odoo 9
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: odoo
score: 1
tagged with: odoo-9
has answer: http://stackoverflow.com/a/50747386
has comment: http://stackoverflow.com/comment/88501623
type: Question
answer count: 1
tagged with: default-value
downvote count: 0
has body: I want to create a new register, but I need to put the value of a parent field as a default value of a child field. I read that you can send parent values through context from XML and whenever a new form is opened, "default_get" of that object will be executed. My questions are: How can I pass the parent values to the child? How can I access to those values in the default_get method? I have tried this: In XML view: &lt;field name="my_child_field" context="{'variable1': parent}"/&gt; In .py file: @api.model def default_get(self, vals): context = dict(self.env.context) variable1 = context.get('variable1', False) print ' variable1' That prints False as variable1 value.

http://stackoverflow.com/comment/88651078
comment on: http://stackoverflow.com/q/50823011
type: QuestionComment
type: Comment
has text: Is there a class involved? `doSomething` needs to take `self` as its first argument if it is a method.
score: 1

http://stackoverflow.com/comment/88427231
type: Comment
comment on: http://stackoverflow.com/q/50708938
has text: django `signal` will do it. why calling a field `id_user` while it just contains the users list Instance? why calling a field `id_event` whereas it contains the instance of model which has already the id automatically created by django?
type: QuestionComment
score: 0

http://stackoverflow.com/q/50773564
accepted answer: http://stackoverflow.com/a/50774592
has comment: http://stackoverflow.com/comment/88555684
downvote count: 0
answer count: 1
favorite count: 0
tagged with: text-styling
has answer: http://stackoverflow.com/a/50774592
tagged with: http://stackoverflow.com/tag/csv
has title: save numpy array to csv column start as same point
tagged with: python
type: AnsweredQuestion
tagged with: save
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88554298
score: 1
has body: I have array of numpy and I need to save it to csv file. I want to get nice display as in the picture below when I open it using notepad I want all the column to start at same position, like the [2,5] and [4] are I cant figure out how to set the dynamic padding between columns Thanks alot Alon
has comment: http://stackoverflow.com/comment/88554562
tagged with: numpy

http://stackoverflow.com/comment/88690716
comment on: http://stackoverflow.com/q/50843490
score: 0
type: Comment
type: QuestionComment
has text: The package we're using (the FWLite package for PyRoot, if that helps) is very finicky about this; whenever we try to, it assembles the list fine, but crashes when we try to reference an item from it.

http://stackoverflow.com/a/61238081
type: Answer
has body: You can specify device serial number in config. config = re.config() config.enable_device('805212060066') profile = config.resolve(pipeline)
score: 0
answers question: http://stackoverflow.com/q/50724909

http://stackoverflow.com/comment/88619822
comment on: http://stackoverflow.com/a/50806993
type: Comment
has text: just like I asked abernett above, wouldn't max(height[col:]) be using extra space? I started with list slicing but commented it out when I realized that I could be using extra space.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50814987
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50815115
type: Question
has comment: http://stackoverflow.com/comment/88635173
has answer: http://stackoverflow.com/a/50817013
has body: I am trying to create a "convert to pdf" button for a current page (service detail, which is a dynamic page) I tried to work with ReportLab (as Django documentation suggests, but I just can't make it work, and ReportLab documentation is not saying a word about such possibilities) for now I can create a pdf file out of this view: (edit, got back to the code from django documentation for clarity) views.py @login_required def service_detail(request, pk): service = get_object_or_404(Service, pk=pk) return render(request, 'detail.html', {'service':service, 'pk':pk}) @login_required def render_to_pdf(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="service.pdf"'' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. p.drawString("Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response urls.py url(r'^service/(?P&lt;pk&gt;\d+)/$', views.service_detail, name='service_detail'), #Services details url(r'^render_to_pdf/', views.render_to_pdf, name='render_to_pdf'), The template of the service detail includes dynamic elements, like: Your location: {{ service.user_location }} &lt;br&gt;&lt;br&gt; Anyone knows what can I do, or what other technology I can use to create such PDF? I am mostly working with Python, Django, HTML and CSS
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/pdf
has title: django current page to pdf

http://stackoverflow.com/comment/88558183
score: 0
type: Comment
type: QuestionComment
has text: Try slicing differently? `[1:25]`?
comment on: http://stackoverflow.com/q/50775624

http://stackoverflow.com/a/50741501
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50736393
answers question: http://stackoverflow.com/q/50736393
type: AcceptedAnswer
has body: The setup method is named GPIO.setup() and not GPIO.SETUP() (note the lower-case characters!). So changing the method unlock_cooler to this should solve the error that you got: def unlock_cooler(): GPIO.setup(7, GPIO.OUT) p = GPIO.PWM(7, 50) p.start(2.5) p.ChangeDutyCycle(7.5) time.sleep(3) p.ChangeDutyCycle(2.5) time.sleep(1) p.stop() GPIO.cleanup() Note that you would probably aslo want to call stop() on the PWM instance.

http://stackoverflow.com/comment/88625375
comment on: http://stackoverflow.com/q/50805638
has text: @MartijnPieters: Thank you very much for your help! I think I understand the reasons why it is not working. The author of the book wrote the following challenge: "Extra Challenge: Rewrite the script using b' ' instead of UTF-8 strings, effectively reversing it". That's why I thought I should write the left side of the output into a new file as a starting point for the new script. So how would be the correct way to do it? Thanks!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88498879
type: Comment
has text: You might also want to take a look ath his post: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder?noredirect=1&lq=1 There is a thorough guide about Python imports by Chris Yeh: https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50745094

http://stackoverflow.com/a/50766103
downvote count: 0
answers question: http://stackoverflow.com/q/50765946
upvote count: 2
has body: One possibility is to define a method or property on the model: def cool_interests(self): return self.interests.filter(is_cool=True)
type: Answer
has comment: http://stackoverflow.com/comment/88539771
score: 2

macos
tags question: http://stackoverflow.com/q/50729809
tags question: http://stackoverflow.com/q/50841201
tags question: http://stackoverflow.com/q/50713726
tags question: http://stackoverflow.com/q/50792163
tags question: http://stackoverflow.com/q/50843769
tags question: http://stackoverflow.com/q/50765651
tags question: http://stackoverflow.com/q/50826411
tags question: http://stackoverflow.com/q/50792048
tags question: http://stackoverflow.com/q/50789470
tags question: http://stackoverflow.com/q/50713044
tags question: http://stackoverflow.com/q/50729603
tags question: http://stackoverflow.com/q/50745485
tags question: http://stackoverflow.com/q/50808349
tags question: http://stackoverflow.com/q/50719840
tags question: http://stackoverflow.com/q/50807507
tags question: http://stackoverflow.com/q/50770356
tags question: http://stackoverflow.com/q/50751799
tags question: http://stackoverflow.com/q/50754193
tags question: http://stackoverflow.com/q/50773119
tags question: http://stackoverflow.com/q/50751008
type: Tag
tags question: http://stackoverflow.com/q/50781353
tags question: http://stackoverflow.com/q/50712139
tags question: http://stackoverflow.com/q/50790056
tags question: http://stackoverflow.com/q/50708348
tag name: macos
tags question: http://stackoverflow.com/q/50783978
tags question: http://stackoverflow.com/q/50746436
tags question: http://stackoverflow.com/q/50842554
tags question: http://stackoverflow.com/q/50726520

http://stackoverflow.com/a/50800516
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50784474
answers question: http://stackoverflow.com/q/50784474
score: 1
upvote count: 1
type: AcceptedAnswer
has body: import numpy as np # constants M = 1.0 k = 180 # number of timeslots x1 = [1,0,0] # prob. of No goal scored per timeslot. x2 = [0,1,0] # prob. of Home Team scoring per timeslot. x3 = [0,0,1] # prob. of Away Team scoring per timeslot. # seven scores final_scores = [[2,1],[3,3],[1,2],[1,1],[2,1],[4,0],[2,3]] # time slots with goals Home_Goal = [2, 3] Away_Goal = [4] # numpy arrays of the data final_scores = np.array(final_scores) # team_1 is [:,0], team_2 is [:,1] home_goal = np.array(Home_Goal) away_goal = np.array(Away_Goal) # fudge factor adj_scores = final_scores * M # shape --&gt; (# of scores, 2) # calculate prob_1 slot_goal_probability = adj_scores / k # xG_n / k slot_draw_probability = 1 - slot_goal_probability.sum(axis = 1) #1-(xG_1+xG_2)/k # y for all scores y = np.concatenate((slot_draw_probability[:,None], slot_goal_probability), axis=1) # ssd for x2, x3, x1 home_ssd = np.sum(np.square(x2 - y), axis=1) away_ssd = np.sum(np.square(x3 - y), axis=1) draw_ssd = np.sum(np.square(x1 - y), axis=1) ssd = np.zeros((y.shape[0],k)) ssd += draw_ssd[:,None] # all time slices a draw ssd[:,home_goal] = home_ssd[:,None] # time slots with goal for home games ssd[:,away_goal] = away_ssd[:,None] # time slots with goal for away games Sum of probabilities (prob_1 in your example) for each score: &gt;&gt;&gt; y.sum(axis=1) array([1., 1., 1., 1., 1., 1., 1.]) ssd's shape is (# of scores,180) - it holds the time slot probability for all the scores. &gt;&gt;&gt; ssd.sum(axis=1) array([5.92222222, 6. , 5.93333333, 5.93333333, 5.92222222, 5.95555556, 5.96666667]) &gt;&gt;&gt; for thing in ssd.sum(axis=1): print(thing) 5.922222222222222 6.000000000000001 5.933333333333332 5.933333333333337 5.922222222222222 5.955555555555557 5.966666666666663 &gt;&gt;&gt; Test y with your function: &gt;&gt;&gt; y array([[0.98333333, 0.01111111, 0.00555556], [0.96666667, 0.01666667, 0.01666667], [0.98333333, 0.00555556, 0.01111111], [0.98888889, 0.00555556, 0.00555556], [0.98333333, 0.01111111, 0.0055…

http://stackoverflow.com/q/50742939
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88493759
has comment: http://stackoverflow.com/comment/88493584
has answer: http://stackoverflow.com/a/50743118
tagged with: rename
answer count: 1
downvote count: 0
tagged with: directory
favorite count: 0
has title: Python os.rename() for files within multiple subfolders in a parent directory
tagged with: python
has comment: http://stackoverflow.com/comment/88493682
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/88518309
has body: File Structure I have a parent directory, called test_folder, which has several (approximately 600) subfolders in it. Each subfolder contains the following: - Always a metadump.xml file - Either a .pdf, .pptx, .xls, or .docx file Goal I would like to rename the respective .pdf, .pptx, .xls, or .docx file in each subfolder of my parent directory (test_folder) based on the title information from the .xml file within the same subfolder, named banana in this example below. import os for root, dirs, files in os.walk("C:\\**\\Downloads\\test_folder"): for file in files: if file == 'metadump.xml': filename = os.path.join(root, file) # READ XML FILE TO OBTAIN 'TITLE' INFORMATION with open(filename, 'r', encoding='utf-8') as xml_file: contents = xml_file.read() title = re.search('&lt;dc:title rsfieldtitle="Title" rsembeddedequiv="Name" rsfieldref="8" rsfieldtype="0"&gt;(.+?)&lt;/dc:title&gt;', contents).group(1) print(title) #AS A CHECK FOR SUCCESSFUL TITLE EXTRACTION # GOING THROUGH FILES AGAIN TO FIND NON-XML FILE for file in files: if file != 'metadump.xml': print(file) #CHECKING THE CORRECT FILE TO BE RENAMED IS SELECTED src = os.path.join(root, file) #ORIGINAL SOURCE PATH dst = os.path.join(root, title)#NEW DESTINATION PATH os.rename(src, dst) #TO RENAME FILES IN THE SUBFOLDER TO THE TITLE After running this, I receive the following: Project Alpha &lt;-- The correct title has been extracted from the XML foobar.pdf &lt;-- The correct 'other' file in the subfolder has been selected for renaming [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\**\\Downloads\\test_folder\\banana\\foobar.pdf' -&gt; 'C:\\**\\Downloads\\test_folder\\banana\\Project Alpha' I am unsure why I am unable to rename the other file, foobar.pdf with the 'title' that was extracted from the .XML file in the same subfolder. Example of Desired Output In test_folder parent directory, in banana subfolder we have: Given: - foobar.pdf (generic file name) - metadump.xml (in…
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/50748753
has title: Key Error when passing a variable using session in Flask
favorite count: 0
has answer: http://stackoverflow.com/a/50863389
type: Question
has comment: http://stackoverflow.com/comment/88505166
tagged with: python
has comment: http://stackoverflow.com/comment/88507568
has answer: http://stackoverflow.com/a/50764595
accepted answer: http://stackoverflow.com/a/50918118
has comment: http://stackoverflow.com/comment/88834743
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
answer count: 3
tagged with: mysql
has comment: http://stackoverflow.com/comment/88505189
possible better answer: http://stackoverflow.com/a/50764595
has comment: http://stackoverflow.com/comment/88505258
downvote count: 0
has body: I want to pass variables from a function to a class in a Flask app using session. This is my code: @app.route('/login', methods=['POST']) def login(): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 username = request.json.get('username', None) password = request.json.get('password', None) session['client_fname'] = request.json.get('Client First Name', None) session['client_lname'] = request.json.get('Client Last Name', None) ... ... access_token = create_access_token(identity=username) return jsonify(access_token=access_token), 200 class PrivateResource(Resource): @app.route('/protected', methods=['GET']) @jwt_required def sendData(): return mysqldb.addUser("{}".format(session['client_fname']),"{}".format(session['client_lname'])) The variables I want to pass are session['client_fname'] and session['client_lname']. However, when I try to trigger sendData() using curl -X GET http://localhost:5000/protected -H "Authorization: Bearer JWTGOESHERE" I get: File "/Users/open/venv/FlaskMiddleware/lib/python2.7/site-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/Users/open/venv/FlaskMiddleware/lib/python2.7/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/Users/open/venv/FlaskMiddleware/lib/python2.7/site-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/Users/open/venv/FlaskMiddleware/lib/python2.7/site-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/open/venv/FlaskMiddleware/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/Users/open/venv/FlaskMiddleware/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/open/venv/FlaskMiddleware/lib/python2.7/site-packages/flask_restful/__init__.py", line 273, in error_rout…
tagged with: flask
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50918118

http://stackoverflow.com/comment/88693105
type: Comment
has text: It basically runs for up to 2 hours then it pipes out info to the log with: self.write_log(“Function completed”), but that code located in another .py script that’s being imported.
comment on: http://stackoverflow.com/a/50842601
type: AnswerComment
score: 0

http://stackoverflow.com/q/50821130
tagged with: python
accepted answer: http://stackoverflow.com/a/50843052
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88651528
upvote count: 3
tagged with: java
has body: I'm trying to start a python script via java and send the data via socket back to the java program. My problem is that when I start the python script after the SocketServer is created with Runtime.getRuntime().exec("python3 ~/Documents/sensor/sensorADC.py"); no connection is established and no data is transmitted. But when I start the script manually via CLI, everything works fine. The timing of the program start shouldn't be the problem, because I already tried different ways and orders. The java program is a javaFx application. EDIT: tested in Linux 2nd Edit: private void startPythonScript () { try { measureProcess = Runtime.getRuntime().exec("python3 ~/Documents/sensor/sensorADC.py")); } catch (IOException e) { e.printStackTrace(); } } What am I missing? Thank you in advance
type: Question
has title: Java start python process
has answer: http://stackoverflow.com/a/50843052
answer count: 2
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/50823133
favorite count: 0
has answer: http://stackoverflow.com/a/50823133
has comment: http://stackoverflow.com/comment/88676590

http://stackoverflow.com/q/50821312
linked to: http://stackoverflow.com/q/7610001
tagged with: python
has answer: http://stackoverflow.com/a/69527909
has answer: http://stackoverflow.com/a/50821426
downvote count: 4
has comment: http://stackoverflow.com/comment/88655435
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/7610001
linked to: http://stackoverflow.com/q/22241420
upvote count: 212
has comment: http://stackoverflow.com/comment/88647853
has answer: http://stackoverflow.com/a/69451981
type: Question
has title: What is the effect of using `python -m pip` instead of just `pip`?
answer count: 8
has comment: http://stackoverflow.com/comment/125473343
has answer: http://stackoverflow.com/a/50821379
accepted answer: http://stackoverflow.com/a/50821362
linked to: http://stackoverflow.com/q/25749621
score: 208
duplicate of: http://stackoverflow.com/q/25749621
has answer: http://stackoverflow.com/a/73370509
favorite count: 0
has body: When I use python -m pip install &lt;package&gt;, how is that different from using just pip install &lt;package&gt;? Similarly, why would I write python -m pip install --upgrade pip to upgrade Pip, instead of just pip install --upgrade pip?
has answer: http://stackoverflow.com/a/50821362
tagged with: python-3.x
has answer: http://stackoverflow.com/a/61049005
has answer: http://stackoverflow.com/a/73612436
possible better answer: http://stackoverflow.com/a/69527909
tagged with: pip

http://stackoverflow.com/comment/88440087
has text: so try it that way `return redirect('contents-occasion-step-1',form_data.pk)` or maybe it's not in this `redirect` that you got the issue
type: QuestionComment
comment on: http://stackoverflow.com/q/50707719
score: 0
type: Comment

http://stackoverflow.com/q/50730539
favorite count: 0
tagged with: python-3.x
tagged with: windows
tagged with: python
possible better answer: http://stackoverflow.com/a/50753699
has title: Pyautogui screenshot. Where does it go? How to save and find later?
has answer: http://stackoverflow.com/a/50753699
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50734259
upvote count: 7
has body: I am learning from Al Sweigart's you tube video for automating the boring stuff. I got to the part of taking screenshots. He didn't really explain in his video so I tested things out. I found that it takes screenshots of the whole desktop but I don't know where they go. I can only find it when do a whole computer search and I don't know how to put it into a folder from there. Basically I am asking how I can store the images and find those images taken by the pyautogui.screenshot() function. I am not planning on using this for anything at the moment I just want to know how to do it. I went to the pyautogui website and I didn't find anything on where to find and how to save the screenshots. Thank you in advance for your time!
type: Question
tagged with: automation
score: 7
tagged with: pyautogui
answer count: 2
accepted answer: http://stackoverflow.com/a/50734259
downvote count: 0

http://stackoverflow.com/a/50780091
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Use your "distance" function as the key argument for whatever sorting function you use. &gt;&gt;&gt; Points = [(54,0), (4,6), (-1,6), (5,-7), (5,1)] &gt;&gt;&gt; from math import sqrt as sq &gt;&gt;&gt; dist = lambda point: int(sq(point[0]**2 + point[1]**2)) &gt;&gt;&gt; max(Points, key=dist) (54, 0)
answers question: http://stackoverflow.com/q/50779986

http://stackoverflow.com/q/50840869
has body: A common type of relationship in schemas is this: a joiner table has a datetime element and is meant to store history about relationships between the rows of two other tables over time. These relationships are one-to-one or one-to-many even though we're using an association table which usually implies many-to-many. At any given point in time only one mapping, the latest at that point in time, is valid. For example: Tables: Computer: [id, name, description] Locations: [id, name, address] ComputerLocations: [id, computers_id, locations_id, timestamp] A Computers object can only belong to one Locations object at a time (and Locations can have many Computers), but we store the history in the table. Rows in ComputerLocations aren't deleted, only superseded by new rows at query-time. Perhaps in the future some prune-type event will remove older rows as their usefulness is reduced. What I'm looking do do is model this in SQLAlchemy, specifically in the ORM, so that a Computers class has the following properties: A new Computer can be created without (independently of) a location (this makes sense because the location table is separate) A new Location can be created without (independently of) a computer If a Computer has a location it must be a member of Locations (foreign key constraint) When updating an existing Computers object's location, a new row will be added to ComputerLocations with a datetime of NOW() When creating a new Computers object with a location, a new row will be added to ComputerLocations with a datetime of NOW() Everything should be atomic (i.e. fail if a new Computer is created but the row associating it to a location can't be created) Is there a specific design pattern or a concrete method in SQLAlchemy ORM to accomplish this? The documentation has a section on Non-traditional mappings that includes mapping a class against multiple tables and to arbitrary selects so this looks promising. Further there was another question of stackoverflow that mention…
has title: Association objects with history for relationships using ORM
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/1300433
answer count: 0
score: 1
tagged with: mysql
upvote count: 1
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/q/50805485
downvote count: 1
upvote count: 5
has answer: http://stackoverflow.com/a/62296008
tagged with: python-2.7
answer count: 4
has title: Can't install pip on python 2.7, only python 3
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50805536
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/54101616
has answer: http://stackoverflow.com/a/50805560
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/50805536
possible better answer: http://stackoverflow.com/a/54101616
tagged with: installation
has body: I have been trying to install pip for python 2.7, but I am unable to. I want pip to work for both python 2.7 and python 3. Here is a summary of what I have done so far: python -V Python 2.7.15 echo $PATH ... /usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ... I've also done a few checks to know where everything is (I have two '/usr/local/bin/python'). I believe there should only be one? which -a python /usr/local/bin/python /usr/local/bin/python /usr/bin/python which python /usr/local/bin/python ls -l $(which python) lrwxr-xr-x 1 XXXXX admin 36 May 24 14:28 /usr/local/bin/python -&gt; ../Cellar/python@2/2.7.15/bin/python When I do: brew list python | grep pip I only get results for python3, nothing at all for python2 /usr/local/Cellar/python/3.6.5/bin/pip3 Things I have tried that do not work, include: python get-pip.py "can't open file 'get-pip.py': [Errno 2] No such file or directory" brew install pip "Error: No available formula with the name "pip" " I appreciate your help!

http://stackoverflow.com/q/50745460
has comment: http://stackoverflow.com/comment/88506957
type: AnsweredQuestion
has title: duplicate output for clipboard / pyperclip
has answer: http://stackoverflow.com/a/50758988
accepted answer: http://stackoverflow.com/a/50758988
has body: I want to create a local copy(ctrl+c) history in a txt but in the output I keep getting duplicate entries. My code: import keyboard import win32clipboard print('Waiting Ctrl+C\n') while True if keyboard.is_pressed('ctrl+c'): win32clipboard.OpenClipboard() data = win32clipboard.GetClipboardData() a = open('E:\Python\copyhistory.txt', 'a') a.write(data) # text a.close() win32clipboard.CloseClipboard() print('printed') Output gets duplicated a lot. I also tried pyperclip but that did not help too. Same problem persist in pyperclip as well. Pyperclip example is below: import pyperclip import keyboard while True: if keyboard.is_pressed('ctrl+c'): a = pyperclip.paste() print(a) Terminal output of code 1: Waiting Ctrl+C printed Then 40 lines of "printed" Same goes for pyperclip, code 2 with pyperclip outputted more than 700 lines of same output, the output that should be printed once. Wham am I doing wrong in here, any ideas?
type: Question
tagged with: pyperclip
score: 0
answer count: 1
tagged with: python
tagged with: python-3.x
tagged with: clipboard
has comment: http://stackoverflow.com/comment/88498706

http://stackoverflow.com/q/50723662
has answer: http://stackoverflow.com/a/50724462
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88456056
type: Question
tagged with: reverse
tagged with: shell
tagged with: tkinter
tagged with: sockets
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/88455659
has body: This is a simple GUI program, i would like to be able to send the user input through socket in my reverse shell but im kinda stumped. Any help would be greatly appreciated :) from tkinter import * import tkinter.messagebox as box def dialog1(): username=entry1.get() password = entry2.get() if (username == 'admin' and password == 'secret'): box.showinfo('info','Correct Login') else: box.showinfo('info','Invalid Login') window = Tk() window.title('Countries Generation') frame = Frame(window) Label1 = Label(window,text = 'Username:') Label1.pack(padx=15,pady= 5) entry1 = Entry(window,bd =5) entry1.pack(padx=15, pady=5) Label2 = Label(window,text = 'Password: ') Label2.pack(padx = 15,pady=6) entry2 = Entry(window, bd=5) entry2.pack(padx = 15,pady=7) btn = Button(frame, text = 'Check Login',command = dialog1) btn.pack(side = RIGHT , padx =5) frame.pack(padx=100,pady = 19) window.mainloop()
score: 0
has title: send input from tkinter through socket

http://stackoverflow.com/q/50743290
tagged with: python
has comment: http://stackoverflow.com/comment/88501211
type: Question
has body: Using Windows terminal error after creating executable in /env/bin/python I have no idea for this error I just deploy an hello_world_django Error Step #1: Using base prefix '/opt/python3.6' Step #1: New python executable in /env/bin/python3.6 Step #1: Also creating executable in /env/bin/python Step #1: Installing setuptools, pip, wheel...done. [Errno 0] Error Traceback (most recent call last): File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 844, in Execute resources = calliope_command.Run(cli=self, args=args) File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 756, in Run resources = command_instance.Run(args) File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\surface\app\deploy.py", line 87, in Run parallel_build=False) File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 593, in RunDeploy flex_image_build_option=flex_image_build_option) File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 392, in Deploy flex_image_build_option) ... File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\cloudbuild\logs.py", line 156, in _PrintLogLine self.out.Print(text) File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\log.py", line 168, in Print self._Write(message + '\n') File "\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\log.py", line 193, in _Write self.__stream_wrapper.stream.write(stream_msg) IOError: [Errno 0] Error
score: 0
answer count: 1
tagged with: gcloud
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50743891
has title: gcloud crashed (IOError): [Errno 0] Error when gcloud app deploy

http://stackoverflow.com/comment/88702989
score: 0
type: AnswerComment
type: Comment
has text: @KaranPurohit Please feel free to implement whatever algorithm you wish for your homework assignment. However, for illustration purpose of how to keep track of indices, this example is good enough for me.
comment on: http://stackoverflow.com/a/50849454

numpy
tags question: http://stackoverflow.com/q/50756776
tags question: http://stackoverflow.com/q/50768511
tags question: http://stackoverflow.com/q/50717846
tags question: http://stackoverflow.com/q/50844290
tags question: http://stackoverflow.com/q/50788289
tags question: http://stackoverflow.com/q/50818352
tags question: http://stackoverflow.com/q/50711786
tags question: http://stackoverflow.com/q/50832145
tags question: http://stackoverflow.com/q/50729425
tags question: http://stackoverflow.com/q/50779617
tags question: http://stackoverflow.com/q/50785226
tags question: http://stackoverflow.com/q/50756288
tags question: http://stackoverflow.com/q/50700256
tags question: http://stackoverflow.com/q/50701018
tags question: http://stackoverflow.com/q/50816006
tags question: http://stackoverflow.com/q/50841195
tags question: http://stackoverflow.com/q/50833256
tags question: http://stackoverflow.com/q/50714185
tags question: http://stackoverflow.com/q/50841048
tags question: http://stackoverflow.com/q/50704882
tags question: http://stackoverflow.com/q/50730780
tags question: http://stackoverflow.com/q/50735112
tags question: http://stackoverflow.com/q/50817243
tags question: http://stackoverflow.com/q/50776361
tags question: http://stackoverflow.com/q/50700325
tags question: http://stackoverflow.com/q/50785188
tags question: http://stackoverflow.com/q/50821899
tags question: http://stackoverflow.com/q/50729229
tags question: http://stackoverflow.com/q/50794383
tags question: http://stackoverflow.com/q/50825505
tags question: http://stackoverflow.com/q/50817371
tags question: http://stackoverflow.com/q/50729464
tags question: http://stackoverflow.com/q/50775923
tags question: http://stackoverflow.com/q/50835690
tags question: http://stackoverflow.com/q/50853752
tags question: http://stackoverflow.com/q/50742956
tags question: http://stackoverflow.com/q/50817926
tags question: http://stackoverflow.com/q/50729742
tags question: http://stackoverflow.com/q/50775708
tags question: http://stackoverflow.com/q/50836427
tags question: http://stackoverflow.com/q/50779346
tags question: http://stackoverflow.com/q/50828334
tags question: http://stackoverflow.com/q/50817415
tags question: http://stackoverflow.com/q/50734776
tags question: http://stackoverflow.com/q/50784144
tags question: http://stackoverflow.com/q/50760792
tags question: http://stackoverflow.com/q/50804120
tags question: http://stackoverflow.com/q/50782731
tags question: http://stackoverflow.com/q/50705996
tags question: http://stackoverflow.com/q/50825520
tags question: http://stackoverflow.com/q/50713248
tags question: http://stackoverflow.com/q/50832334
tags question: http://stackoverflow.com/q/50772780
tags question: http://stackoverflow.com/q/50785017
tags question: http://stackoverflow.com/q/50834133
tags question: http://stackoverflow.com/q/50804431
tags question: http://stackoverflow.com/q/50774046
tags question: http://stackoverflow.com/q/50771911
tags question: http://stackoverflow.com/q/50848109
tags question: http://stackoverflow.com/q/50765634
tags question: http://stackoverflow.com/q/50722162
tags question: http://stackoverflow.com/q/50789448
tags question: http://stackoverflow.com/q/50769767
tags question: http://stackoverflow.com/q/50822986
tags question: http://stackoverflow.com/q/50759678
tags question: http://stackoverflow.com/q/50827554
tags question: http://stackoverflow.com/q/50849789
tags question: http://stackoverflow.com/q/50715934
tags question: http://stackoverflow.com/q/50702988
tags question: http://stackoverflow.com/q/50751135
tags question: http://stackoverflow.com/q/50744094
tags question: http://stackoverflow.com/q/50802238
tags question: http://stackoverflow.com/q/50745656
tags question: http://stackoverflow.com/q/50833410
tags question: http://stackoverflow.com/q/50748633
tags question: http://stackoverflow.com/q/50845185
tags question: http://stackoverflow.com/q/50713828
tags question: http://stackoverflow.com/q/50705891
tags question: http://stackoverflow.com/q/50814296
tags question: http://stackoverflow.com/q/50787088

http://stackoverflow.com/comment/88641265
type: Comment
type: QuestionComment
has text: Take a look at https://en.wikipedia.org/wiki/Edit_distance
comment on: http://stackoverflow.com/q/50818131
score: 0

http://stackoverflow.com/comment/88516516
comment on: http://stackoverflow.com/q/50737170
has text: @A.Pinero see my answer.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50803737
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88613513
favorite count: 0
has comment: http://stackoverflow.com/comment/88613676
has comment: http://stackoverflow.com/comment/88613613
has comment: http://stackoverflow.com/comment/88615941
accepted answer: http://stackoverflow.com/a/50803832
score: -3
has comment: http://stackoverflow.com/comment/88613767
tagged with: python
has comment: http://stackoverflow.com/comment/88613698
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88615722
has body: I have a function that's designed to randomly generate numbers from 1 - 6, with some other conditions. I save the number to a variable called 'turn', and later return this when the function ('turnSelector()') is called. The weird part: Later I use conditional statements to check which value (1-6) turnSelector() is equal to. I was getting a non-random distribution, so I threw in an else statement to see if turnSelector() = values that weren't 1-6, and then print these so I could see what they were. The else statement was used, and the values printed were between 1-6 (inclusive). If I global 'turn' and use that in the conditional statements, I get a distribution expected with random generation, and no weird other values with the else statement. So, why is turnSelector() returning different values to 'turn', even though I am returning 'turn'?! def turnSelector(): global save1, save2, save3, turn selection = False while selection == False: turn = randint(1,6) save1, save2, save3 = turn, save1, save2 if turn == save1 == save2 == save3: continue else: selection = True return turn This produces the non-random distribution: def turnExecutor(): global scrambledState, zero, one, two, three, four, five,six if turnSelector()== 1: scrambledState = anterior(scrambledState) zero += 1 elif turnSelector()== 2: scrambledState = posterior(scrambledState) one += 1 elif turnSelector()== 3: scrambledState = dorsal(scrambledState) two += 1 elif turnSelector()== 4: scrambledState = ventral(scrambledState) three += 1 elif turnSelector()== 5: scrambledState = right(scrambledState) four += 1 elif turnSelector()== 6: scrambledState = left(scrambledState) five += 1 else: six += 1 print(str(turnSelector())) This produces the random distribution I want: def turnExecutor(): global scrambledState, zero, one, two, three, four, five,six if turn == 1: scrambledState = anterior(scrambledState) zero += 1 elif turn == 2: scrambledState = posterior(scrambledState) one += 1 elif turn == 3: scrambledState =…
has title: When I check the value of a function in conditional statements, the value is different to that of the variable I returned
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/50803832

http://stackoverflow.com/a/50718285
upvote count: 2
has comment: http://stackoverflow.com/comment/88445500
has comment: http://stackoverflow.com/comment/88445681
has body: pd.DataFrame accepts a list of dictionaries directly: data = [{"character": "Jake Sully", "gender": 2,}, {"character": "Neytiri", "gender": 1}, {"character": "Dr. Grace Augustine","gender": 1}, {"character": "Col. Quaritch", "gender": 2}] df = pd.DataFrame(data) # or pd.DataFrame.from_dict(data) print(df) character gender 0 Jake Sully 2 1 Neytiri 1 2 Dr. Grace Augustine 1 3 Col. Quaritch 2 Therefore, you only need to extract a list of dictionaries from your json file. One way you can do this is via json.loads. A better idea is to read your data directly into a dataframe via pd.read_json.
type: Answer
has comment: http://stackoverflow.com/comment/88445114
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88445340
answers question: http://stackoverflow.com/q/50718146

http://stackoverflow.com/q/50835836
answer count: 1
type: UnansweredQuestion
tagged with: maven
upvote count: 1
tagged with: python
has title: Intellij - Python interpretor
has answer: http://stackoverflow.com/a/50839568
score: 1
type: Question
tagged with: intellij-idea
downvote count: 0
has body: I have an MVN project and would like to add a Python program in the project. The IDE I am using in Intellij. I have added the MVN pom file as below: org.codehaus.mojo versions-maven-plugin 2.1 python src/main/resources/pythonlib PYTHONPATH Added the Python plugin While trying to run from the editor it is asking for Python interpreter: Which has 2 radio buttons: Use SDK of the module Use specified interpreter. In both the list does not have any Python interpreter. How to have the list display a Python interpreter.
favorite count: 0

http://stackoverflow.com/comment/88519760
has text: `element.get_attribute()` work on visible and invisible element, thus no need to modify the CSS to make the element visible to change the original display logical of the page, in some case, this will change the page layout, at least it's not recommend way.
comment on: http://stackoverflow.com/a/50755438
type: AnswerComment
score: 0
type: Comment

anaconda
tags question: http://stackoverflow.com/q/50706354
tags question: http://stackoverflow.com/q/50814511
tags question: http://stackoverflow.com/q/50714931
type: Tag
tags question: http://stackoverflow.com/q/50826256
tags question: http://stackoverflow.com/q/50712246
tags question: http://stackoverflow.com/q/50770394
tags question: http://stackoverflow.com/q/50741997
tags question: http://stackoverflow.com/q/50709249
tags question: http://stackoverflow.com/q/50727926
tags question: http://stackoverflow.com/q/50719618
tags question: http://stackoverflow.com/q/50841555
tags question: http://stackoverflow.com/q/50732381
tags question: http://stackoverflow.com/q/50708910
tags question: http://stackoverflow.com/q/50847721
tags question: http://stackoverflow.com/q/50728057
tags question: http://stackoverflow.com/q/50783047
tags question: http://stackoverflow.com/q/50836956
tags question: http://stackoverflow.com/q/50707728
tags question: http://stackoverflow.com/q/50824745
tags question: http://stackoverflow.com/q/50840725
tags question: http://stackoverflow.com/q/50854078
tags question: http://stackoverflow.com/q/50726622
tags question: http://stackoverflow.com/q/50765892
tag name: anaconda
tags question: http://stackoverflow.com/q/50723642
tags question: http://stackoverflow.com/q/50743724
tags question: http://stackoverflow.com/q/50796254
tags question: http://stackoverflow.com/q/50706802
tags question: http://stackoverflow.com/q/50833740
tags question: http://stackoverflow.com/q/50773388
tags question: http://stackoverflow.com/q/50784067
tags question: http://stackoverflow.com/q/50762627
tags question: http://stackoverflow.com/q/50801992
tags question: http://stackoverflow.com/q/50720551
tags question: http://stackoverflow.com/q/50806075
tags question: http://stackoverflow.com/q/50748673
tags question: http://stackoverflow.com/q/50715679
tags question: http://stackoverflow.com/q/50774662
tags question: http://stackoverflow.com/q/50733572
tags question: http://stackoverflow.com/q/50724366

http://stackoverflow.com/q/50774065
has comment: http://stackoverflow.com/comment/88593474
downvote count: 0
answer count: 1
has body: The Carnegie Mellon University pronouncing dictionary allows to get phonemes from words. I did some research on the Internet and it appears that there are some extensions as the LOGIOS Lexicon Tool which derives the phonemes for arbitrary words that might not be included in the original CMU dictionary (http://www.speech.cs.cmu.edu/tools/lextool.html). The same can be obtained by using a neural network model (https://github.com/cmusphinx/g2p-seq2seq), so that basically for each word we can get the corresponding phonemes. But is the process reversible for every word? Obviously for words already contained in the CMU dictionary the reversing is unnecessary since the word is attached to the corresponding phonemes. But how can I get the word from arbitrary phonemes? Is that a tool for that (possibly in Python) or should I implement the reverse by myself maybe looking at the source code doing the word-to-phoneme parsing and trying to revert it (if possible)?
has comment: http://stackoverflow.com/comment/88565487
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88571470
has answer: http://stackoverflow.com/a/50807810
has title: Reverse phonemes not included in the CMU dictionary
type: Question
tagged with: cmusphinx
accepted answer: http://stackoverflow.com/a/50807810

http://stackoverflow.com/a/50727415
downvote count: 0
has body: Anaconda is a Python distribution, and Conda is the package manager for Anaconda. The issue is when you are installing tensorflow, you are installing it inside a Conda environment. This means it will only work in that environment. In order to use it outside the environment, you either need to install it via pip into a different environment, or need to move your program into the Conda environment to use Tensorflow. It's generally considered bad practice to install packages into the system copy of Python. Packages can install conflicting dependencies, and different programs have different packages. This is why environment managers were made. The Conda environment manager is a great tool, and it's worth the time it takes to learn how to use environment managers.
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50726622
accepted answer of: http://stackoverflow.com/q/50726622
type: AcceptedAnswer

http://stackoverflow.com/a/50746797
answers question: http://stackoverflow.com/q/50746724
type: Answer
score: 0
has body: use try&amp;except import urllib2 try: urllib2.urlopen(quote_page) except urllib2.HTTPError as e: print(e.code) except urllib2.URLError as e: print(e.args)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50746724

http://stackoverflow.com/q/50727899
has comment: http://stackoverflow.com/comment/88974853
has comment: http://stackoverflow.com/comment/88927054
has body: This is how the data currently looks like: id testers_time stage_1_to_2_time activated_time stage_2_to_3_time engaged_time a 10 30 40 30 70 b 30 c 15 30 45 d dict = {'id': ['a','b','c','d'], 'testers_time': [10, 30, 15, None], 'stage_1_to_2_time': [30, None, 30, None], 'activated_time' : [40, None, 45, None],'stage_2_to_3_time' : [30, None, None, None],'engaged_time' : [70, None, None, None]} df = pd.DataFrame(dict, columns=['id', 'testers_time', 'stage_1_to_2_time', 'activated_time', 'stage_2_to_3_time', 'engaged_time']) I have a plot of testers_time against its cumulative probability from a CDF: def ecdf(df): n = len(df) x = np.sort(df) y = np.arange(1.0, n+1) / n return x, y df = df['testers_time'].dropna().sort_values() print(df) x, y = ecdf(df) plt.plot(x, y, marker='.', linestyle='none') plt.axvline(x.mean(), color='gray', linestyle='dashed', linewidth=2) #Add mean x_m = int(x.mean()) y_m = stats.percentileofscore(df, x.mean())/100.0 plt.annotate('(%s,%s)' % (x_m,int(y_m*100)) , xy=(x_m,y_m), xytext=(10,-5), textcoords='offset points') percentiles= np.array([0,25,50,75,100]) x_p = np.percentile(df, percentiles) y_p = percentiles/100.0 plt.plot(x_p, y_p, marker='D', color='red', linestyle='none') # Overlay quartiles for x,y in zip(x_p, y_p): plt.annotate('%s' % int(x), xy=(x,y), xytext=(10,-5), textcoords='offset points') What I am trying to do is graph testers_time against: 1) Its none-cumulative probability, if graphed it should look like a sort of a PDF 2) Its cumulative conversion %, where conversion is any id that has a populated (not blank or null) testers_time. So id a (1 of 4 ids) converts, that's 25%, id b converts, thats 50% (since cumulative), id c converts, that's 75%, and id d doesnt convert so 75% conversion is the max, at 30 days testers_time. Can you assist with adding the above into columns in the df, or graph them? Thank you.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88966288
tagged with: matplotlib
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50992521
has title: Add probability of x and conversion %
downvote count: 5
score: -1
accepted answer: http://stackoverflow.com/a/50992521
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/88943313
favorite count: 0
has comment: http://stackoverflow.com/comment/88973977
tagged with: python

http://stackoverflow.com/comment/88623330
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50807965
has text: that works, fyi it works with date-time not datetime

http://stackoverflow.com/comment/88516165
type: Comment
has text: This is python 3. Sorry I didn't mention that earlier
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50754075

http://stackoverflow.com/q/50787624
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88595257
has comment: http://stackoverflow.com/comment/88581570
favorite count: 0
has comment: http://stackoverflow.com/comment/88590582
has comment: http://stackoverflow.com/comment/88581775
tagged with: python
accepted answer: http://stackoverflow.com/a/50794954
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Optimizing pairwise subtruction
has answer: http://stackoverflow.com/a/50794954
type: Question
has comment: http://stackoverflow.com/comment/88581600
tagged with: optimization
has body: I have to compute the pairwise difference of particle's velocities for around 1e6 objects each with approx. 1e4 particles. Right now I am using itertools.combinations to loop over the particles, but just for one object my code takes already more than 30 minutes. I was wondering what else can I do to speed it up to a feasible speed, since parallelising doesn't seem to add much in python. Is cython the way to go? Here is my code just for one of the objects: def pairwisevel(hist,velj,velk, xj, xk): vlos = (velj - velk) if( (xj - xk) &lt; 0.): vlos = - vlos hist.add_from_value(vlos) for i in itertools.combinations(np.arange(0,int(particles_per_group[0]),1),2): pairwisevel(hist, pvel[i[0]], pvel[i[1]],\ pcoords[i[0]], pcoords[i[1]])

http://stackoverflow.com/a/51045448
score: 0
has body: For anyone else who has run into this issue. I made a wrapper derived from RNNCell that accomplishes what I need. The model_fn is a function that builds a subgraph using input and returns the output tensor. Unfortunately the output shape must be known (at least I couldn't get it to work otherwise). class WrapperCell(tf.nn.rnn_cell.RNNCell): """A Wrapper for a non recurrent component that feeds into an RNN.""" def __init__(self, model_fn, out_shape, reuse=None): super(WrapperCell, self).__init__(_reuse=reuse) self.out_shape = out_shape self.model_fn = model_fn @property def state_size(self): return tf.TensorShape([1]) @property def output_size(self): return tf.TensorShape(self.out_shape) def call(self, x, h): mod = self.model_fn(x) return mod, tf.zeros_like(h)
accepted answer of: http://stackoverflow.com/q/50801949
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50801949
type: Answer

http://stackoverflow.com/comment/88640862
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50815485
score: 0
has text: I just corrected to do a test. My write () function now works but that's not what I want to do. I do not want to replace a field of a line but add a new line. What function do I have to use? Thank you @api.multi def button_for_run_update(self): self.write({'name': "Test"})

http://stackoverflow.com/q/50827210
tagged with: nodes
type: Question
has title: How would you calculate the sum of a binary tree recursively with given input tree?
downvote count: 0
has answer: http://stackoverflow.com/a/61905184
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: binary-search-tree
type: UnansweredQuestion
tagged with: python
has body: Hi! I need help finding a way to calculate the sum of a binary tree recursively. I have put what I have been working on but I am still really confused. Please, any help would be appreciated. Define a recursive function named sum, which takes a binary tree as an argument, and returns an int – the sum of all the node values in the tree. For the tree on bottom for example, the function returns 35. def sum(t: TN) -&gt; int: if t == None: return 0 else: return [sum(t.value)for v in t]
score: 1
upvote count: 1

http://stackoverflow.com/q/50710987
upvote count: 1
tagged with: python
downvote count: 1
has body: I have a dataframe in pandas: a b c d e 0 1 x y t u 1 1 x z y v 2 1 y x t z 3 2 x t z u 4 2 z x y t 5 3 x z y t I need to transform this dataframe into this: a x y z t u v y z 0 1 3 3 2 2 1 1 3 2 1 2 2 1 2 2 1 0 1 2 2 3 1 1 1 1 0 0 0 0
type: AnsweredQuestion
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50711023
type: Question
answer count: 2
favorite count: 0
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88430975
possible better answer: http://stackoverflow.com/a/50711053
has title: Count unique values in multiple columns according by group (pandas dataframe)
has answer: http://stackoverflow.com/a/50711053
has answer: http://stackoverflow.com/a/50711023
tagged with: pivot-table

http://stackoverflow.com/comment/88451763
type: QuestionComment
has text: python does not have NULL, it would be None in such case... not 100% sure in this exact function.
type: Comment
comment on: http://stackoverflow.com/q/50720820
score: 0

http://stackoverflow.com/comment/88685756
has text: @JohnColeman how would i go about writing said function
comment on: http://stackoverflow.com/q/50777577
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50700729
answers question: http://stackoverflow.com/q/50700617
type: Answer
score: 0
has body: Use re.findall: import re txt = '''EquivalentClasses(&lt;http://www.ifomis.org/bfo/1.1/spanTemporalRegion&gt; ObjectUnionOf(&lt;http://www.ifomis.org/bfo/1.1/spanScatteredTemporalRegion&gt; &lt;http://www.ifomis.org/bfo/1.1/spanConnectedTemporalRegion&gt;))''' print('\n'.join(re.findall(r'ObjectUnionOf\((.*)\)\)', txt))) # &lt;http://www.ifomis.org/bfo/1.1/spanScatteredTemporalRegion&gt; # &lt;http://www.ifomis.org/bfo/1.1/spanConnectedTemporalRegion&gt;

http://stackoverflow.com/comment/88578916
score: 0
type: QuestionComment
type: Comment
has text: @DanielRoseman my bad, fixed
comment on: http://stackoverflow.com/q/50786175

http://stackoverflow.com/a/50825200
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50824989
type: AcceptedAnswer
downvote count: 0
has body: As much as I love groupby, I don't think is a good idea here. Your elements alternate veg and non-veg, but groupby expects the groups to be contiguous, which means it's only going to work if you first call sorted, at which point you're throwing away all the simplicity and performance benefits of doing things iteratively. Meanwhile, without sorting, it'll be a lot easier to build up a dict, keyed off the key values, than a list that you have to keep searching for each key. For example: d = collections.defaultdict(lambda: dict(count=0, price=[], quality='')) for entry in A: key = entry['key'] target = d[key] target['count'] += entry['count'] target['price'].extend(entry['price']) target['quality'] = 'something' # I don't know what your aggregation rule is Now, d looks like this: defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, {'non-veg': {'count': 250, 'price': [10, 20, 30, 110, 220, 330]], 'quality': 'something'}, 'veg': {'count': 300, 'price': [100, 200, 300, 1, 2, 3]], 'quality': 'something'}}) And if you really need the list at the end, that's easy: [dict(key=key, **value) for key, value in d.items()] Alternatively, if the dict structure turns out to be more useful than the list, just use that. (Use dict.setdefault instead of a defaultdict, or do d = dict(d) at the end, if you don't want KeyErrors on later lookups to turn into default values, of course.)
answers question: http://stackoverflow.com/q/50824989

http://stackoverflow.com/a/50775054
has body: Have you tried using this? link combined with a code like that: class UploadedImageSerializer(serializers.ModelSerializer): """ Serializer for the UPloadedImage Model Provides the pk, image, thumbnail, title and description """ class Meta: model = UploadedImage fields = ('pk', 'image', 'thumbnail', 'title', 'description', ) read_only_fields = ('thumbnail',)
score: 0
answers question: http://stackoverflow.com/q/50775006
type: Answer

http://stackoverflow.com/comment/88491508
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50741194
has text: @Adelin updated the question to include the results of the test
score: 0

http://stackoverflow.com/comment/88711705
type: Comment
type: QuestionComment
has text: *index of the first occurrence of **three consecutive negative numbers*** - so you expect it to be `7`? or `[7,8,9]` ?
comment on: http://stackoverflow.com/q/50853691
score: 0

http://stackoverflow.com/q/50836922
tagged with: url
tagged with: query-string
score: 0
tagged with: python
has body: Hey guys I'm having a problem passing URL parameters in my Django code. Let say i have a url like below: /search/?q=django and in one of my form I have a href to add another parameter like &lt;a href="?price=all"&gt; ... &lt;/a&gt; But when I actually click the href link I end up with: search/?price=all and the django spits out a ValueError: Cannot use None as a query value any idea of why this is happening??
answer count: 0
has comment: http://stackoverflow.com/comment/88677788
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/88677544
has comment: http://stackoverflow.com/comment/88677860
has title: Django URL Parameters get deleted
has comment: http://stackoverflow.com/comment/88678435
has comment: http://stackoverflow.com/comment/88678402
type: Question
has comment: http://stackoverflow.com/comment/88678780

http://stackoverflow.com/q/50751040
tagged with: command-line-interface
possible better answer: http://stackoverflow.com/a/50762991
has answer: http://stackoverflow.com/a/50762991
answer count: 2
tagged with: python-click
has title: Include submodules on click
has body: I am trying to make a kind of recursive call on my first Click CLI app. The main point is to have sub-commands associated to the first and, so, I was trying to separate it all in different files/modules to improve it's maintainability. I have the current directory: root |-commands |-project |---__init__ |---command1 |---command2 |-database |---__init__ |---command1 |---command2 This is my main file: import click from commands.project import project from commands.database import database @click.group(help="Main command") def main(): pass main.add_command(project) main.add_command(database) My projects __init__ file: from commands.project.command1 import * from commands.project.command2 import * import click @click.group(help="Projects") def project(): pass project.add_command(command1) project.add_command(command2) My commands.project.command1 file: import click @click.command() def command1(): """ Execute all the steps required to update the project. """ pass The main point here is that, every time I want to add a new subcommand, I need to: Add .py file with all code to the command, in respective subcommand/submodule folder (obviously!) Add it's import statement on it's __init__ file Relate this new command to it's parent (project/database, in this case) Is there any way to do a circular/dynamic load to avoid step no.2 and 3? EDIT After tried Stephen Rauch way, it successfully includes all provided files, but none of the commands works with - only with function name (eg: update-project -> update_project). root |-commands |-project |---update |---install_project |-database |---command_one |---command_two main.py # main command ----------------------------------------------------------- ### @click.group(help="CLI tool!", context_settings=dict(max_content_width=120)) def main(): pass # PROJECT command group -------------------------------------------------------- ### @main.group(cls=group_from_folder("commands/project"), short_help="Project installation and upgrade uti…
has comment: http://stackoverflow.com/comment/89519343
has comment: http://stackoverflow.com/comment/89509119
favorite count: 0
has answer: http://stackoverflow.com/a/51390393
tagged with: python-3.x
tagged with: python
score: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89537001
accepted answer: http://stackoverflow.com/a/51390393
downvote count: 1
type: Question
upvote count: 12
has comment: http://stackoverflow.com/comment/89512285

http://stackoverflow.com/comment/88458692
type: QuestionComment
score: 2
has text: `(NULL) disabled != ?` is never true.
comment on: http://stackoverflow.com/q/50725210
type: Comment

http://stackoverflow.com/q/50799688
tagged with: python
has comment: http://stackoverflow.com/comment/88605522
tagged with: list
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88605311
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88608487
has body: So I'm facing the following problem. When creating a List of Integers in Android Studio: List&lt;Integer&gt; myIDs= new ArrayList&lt;&gt;(); I'm putting the integers (id's) in a given order, with a result of, p.e: myIds = [69, 65, 67] I'm using Retrofit for sending the request to the server: @POST("looks/") @FormUrlEncoded Call&lt;Look&gt; createLook( @Field("myIds") List&lt;Integer&gt; myIds, ..., ...); mAPIService.createLook(myIDs, ..., ...).enqueue(new Callback&lt;Look&gt;() { @Override public void onResponse(Call&lt;Look&gt; call, Response&lt;Look&gt; response) { if (response.isSuccessful()) { Log.d("OK: ", "post submitted to API." + response.body().toString()); // We finish the Activity. finish(); } else { ... ... } finish(); } @Override public void onFailure(Call&lt;Look&gt; call, Throwable t) { } }); The problem is that when I'm sending the List to my django server it is ordering it by itself to: "myIds ": [ 65, 67, 69 ] Any idea on why is that happening, and how could I solve it? On the server, this is my models.py ... myIds = models.ManyToManyField('garments.Garment') ... views.py class LookList(generics.ListCreateAPIView): serializer_class = LookSerializer def get_queryset(self): queryset = Look.objects.all() username = self.request.query_params.get('username',None) date = self.request.query_params.get('date', None) if date is not None: queryset = queryset.filter(date=date) if username is not None: queryset = queryset.filter(username=username) return queryset class LookDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Look.objects.all() serializer_class = LookSerializer serializers.py class LookSerializer(serializers.ModelSerializer): class Meta: model = Look fields = ('id','garment_id','username','date') Thank you in advanced!
tagged with: arraylist
has comment: http://stackoverflow.com/comment/88606374
tagged with: retrofit
has title: Django is changing the order of my Integer List
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88606667
type: UnansweredQuestion
tagged with: django

gmail
type: Tag
tags question: http://stackoverflow.com/q/50852056
tag name: gmail

http://stackoverflow.com/q/50716365
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50718468
favorite count: 0
has comment: http://stackoverflow.com/comment/88442455
type: Question
has comment: http://stackoverflow.com/comment/88442037
tagged with: seaborn
upvote count: 1
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/50718468
has body: I am looking at examples, but everything requires a dataframe. If I have the following dataframe: x = ["G","F","E","D","C","B"] y = [3,14,45,47,34,15] df = pd.DataFrame( {'Band': x, 'Count': y, }) I want to create a violin plot using Count as the value and Band as the steps, so I have done this: ax = sns.violinplot( y="Count", data=df) which produces this: However, I want to have the Bands on the y axis, and then the Count to be the size of bulge for each grade. Do you have to only use continuous values on the y axis? Edit: What I want it to look like:
downvote count: 0
has title: Python - Seaborn Violin plot, not doing what I want it to
has comment: http://stackoverflow.com/comment/88442070

http://stackoverflow.com/a/50750397
answers question: http://stackoverflow.com/q/50750368
downvote count: 1
score: 3
upvote count: 4
type: Answer
has body: Use double speech marks instead of single speech marks: "SELECT COUNT(*) FROM X WHERE TABLE_NM = '{}'".format(table) This isn't entirely relevant (more of a nicety than necessity), but you could also use f-strings if you're using Python3.6 (but you still need the double speech marks).

http://stackoverflow.com/a/50781396
upvote count: 3
answers question: http://stackoverflow.com/q/50781368
has body: Using sum and a generator expression: lst = [['linux'], ['ML'], ['linux', 'ML', 'Data Science', 'GIT'],['linux', 'Data Science', 'GIT'], ['GIT'], ['ML', 'GIT'], ['linux'], ['linux'], ['linux'], ['Data Science']] num_items = sum(len(l) for l in lst) print(num_items)
score: 3
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88505496
comment on: http://stackoverflow.com/q/50748963
score: 0
type: Comment
type: QuestionComment
has text: A variable name or a property of a class (or a function for that matter) can not begin with a number in python syntax. Applying `self.year = year` results in `'year': 2000` within the `__dict__`. That's how python works

http://stackoverflow.com/comment/88562766
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50777728
type: QuestionComment
has text: What is x? it is assigned 1 at the beginning and does not change. Thus the loop will continue forever.

http://stackoverflow.com/comment/88532067
type: Comment
type: QuestionComment
has text: Is the `log_handler` or `determine_zone` an important part of the question?
comment on: http://stackoverflow.com/q/50762211
score: 0

http://stackoverflow.com/a/50802197
score: 0
type: Answer
has body: A couple of things to try: You can't always have an index on a NULL field. I don't know the inner workings of BrinIndex but it's something you might like to check. Your model definition should include a db_index attribute: from django.contrib.postgres.indexes import BrinIndex class Measurement(models.Model): time = models.DateTimeField( 'Time of measurement', db_index=True, null=True ) class Meta: indexes = ( BrinIndex(fields=['time']) )
has comment: http://stackoverflow.com/comment/126400149
answers question: http://stackoverflow.com/q/50801196

http://stackoverflow.com/q/50843764
type: Question
has body: When I run this code I get the error AttributeError: '_io.TextIOWrapper' object has no attribute 'split' Any Help would be appreciated #python3.5 print("WELCOME TO THE CLEVERBUY SYSTEM!") productArray= [] productsFile = open("products.txt","r") print (productsFile.split(",")) login = False while login == False: FName = input ("ENTER FIRST NAME - ") custID = input ("ENTER CUSTOMER ID - ") email = input ("ENTER E-MAIL - ") if custID in productArray: if "@" not in email: print ("incorrect e-mail") else: if "." not in email: print ("incorrect e-mail") else: if FName.isalpha(): print ("Welcome") login = True else: print("incorrect first name") else: print("customer ID not found in system")
has comment: http://stackoverflow.com/comment/88691122
has answer: http://stackoverflow.com/a/50843802
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88691101
score: 0
tagged with: python
has title: AttributeError: '_io.TextIOWrapper' object has no attribute 'split' error
has comment: http://stackoverflow.com/comment/88691166
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88691100
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/50715872
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50730942
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88469321
has title: How do I make complex if-conditions maintainable as assignment in if-conditions aren't supported in Python?
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88464609
type: Question
accepted answer: http://stackoverflow.com/a/50730942
has body: I have the following Python code where function print_processed_username contains an if/else construct. The if-line is very long because of the repeating regular expression. If a modification is ever needed in the regular expression, then the same modification must be made in each occurrence of that regular expression (including the call to process_the_username), which makes the code difficult to maintain. import re def process_the_username(username): return 'e' + username[1:] def print_processed_username(args): if len(args) == 1 and type(args[0]) is str and re.compile(r'[\'"]username[\'"]: ?[\'"](\S*)[\'"]', re.IGNORECASE).search(args[0]) and len(re.compile(r'[\'"]username[\'"]: ?[\'"](\S*)[\'"]', re.IGNORECASE).search(args[0]).groups()) == 1 and len(re.compile(r'[\'"]username[\'"]: ?[\'"](\S*)[\'"]', re.IGNORECASE).search(args[0]).groups()[0]) == 7 and re.compile(r'[\'"]username[\'"]: ?[\'"](\S*)[\'"]', re.IGNORECASE).search(args[0]).groups()[0][0] == '_': # Here args is a list containing one item which is a string and the string contains 'username': '&lt;user&gt;' only once where &lt;user&gt; is 7 characters long and starts with _. print process_the_username(re.compile(r'[\'"]username[\'"]: ?[\'"](\S*)[\'"]', re.IGNORECASE).search(args[0]).groups()[0]) else: print "Missing or correct user name format. Nothing to do." If Python like many other languages had had support for assignment in if-conditions, this problem would have been easy to solve. But as we know, Python doesn't support that. Thus I'm asking for suggestions on how to write the if-condition the Pythonic way, where the repetition of the regular expression is eliminated. All suggestions that make the code simpler and easier to maintain are highly appreciated. Here are a few sample executions where the username is processed as expected. &gt;&gt;&gt; args = ["'location': 'Frankfurt', 'Phone': '+49 123 456789', 'UserName': '_beka01'"] &gt;&gt;&gt; print_processed_username(args) ebeka01 &gt;&gt;&gt; &gt;&gt;…
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50752283
score: 1
accepted answer: http://stackoverflow.com/a/50981628
has title: Google Cloud Datastore 'NoneType' object has no attribute 'email'
has body: When I try getting a kind from my datastore it returns NoneType, as if the query is empty. I know the datastore is working properly while saving, but pulling a kind from the a query is not. Also using the GQL Query in the Google cloud Console website and using SELECT * FROM User does return all the kinds. User kind has no parents, it is at the root. I made sure all the properties are indexed as well. I am not sure what I am doing wrong on GET. MyApp.py import webapp2 from google.appengine.ext import ndb from google.appengine.ext.db import GqlQuery class MainHandler(webapp2.RequestHandler): def post(self): message = self.request.body message = message.splitlines() if message[0] == "register": user = User.create_user(message[1], message[2], message[3]) user_key = User.save_user(user) if user_key is not None: self.response.write(user_key) else: user = User.get_by_id(User.email == message[0]) if User.token == message[1]: self.response.write("CURRENT") else: User.token = message[1] User.save_user(user) self.response.write("UPDATED") def get(self): self.response.write("CONNECTED") user= User.query().get() self.response.write("\n" + query.email) class User(ndb.Model): email = ndb.StringProperty() token = ndb.StringProperty() name = ndb.StringProperty() @classmethod def create_user(cls, email, token, name): user = User(email=email, token=token, name=name, id=email) return user @classmethod def save_user(cls, user): user_key = user.put() return user_key @classmethod def get_user(cls, email): return User.get_by_id(User.email == email) app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True)
possible better answer: http://stackoverflow.com/a/50752423
type: Question
tagged with: webapp2
answer count: 2
has answer: http://stackoverflow.com/a/50752423
tagged with: google-cloud-datastore
has answer: http://stackoverflow.com/a/50981628
tagged with: python-2.7
upvote count: 1
favorite count: 0
tagged with: google-app-engine
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/50843993
favorite count: 0
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/50844171
answer count: 4
upvote count: 2
has answer: http://stackoverflow.com/a/50844281
has body: Hello I am trying to split a data frame into 2: first data frame should have all the rows occurred first and remaining all occurrences into another table. please see below sample input data frame and output data frames i am looking for: i will sort data by group and number before i split input data: Group number Short 1 Short 2 Moderate 55 Moderate 31 Tall 24 Tall 11 yellow 101 Dataframe 1 Group Number Short 1 Moderate 55 Tall 24 Yellow 101 Dataframe 2 Group Number Short 2 moderate 31 Tall 11 Please advice how i can solve this problem. if its duplicate Question please point to any solution which is already provided. Thanks
downvote count: 1
has comment: http://stackoverflow.com/comment/88691978
type: AnsweredQuestion
has title: python Split Dataframe based first occurrence
score: 1
has answer: http://stackoverflow.com/a/50844171
type: Question
has answer: http://stackoverflow.com/a/50844092
accepted answer: http://stackoverflow.com/a/50844092
linked to: http://stackoverflow.com/q/26244309
has answer: http://stackoverflow.com/a/50844492

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/50820029
tags question: http://stackoverflow.com/q/50773909
tags question: http://stackoverflow.com/q/50769972
tags question: http://stackoverflow.com/q/50723020
type: Tag
tags question: http://stackoverflow.com/q/50783151
tag name: pdf
tags question: http://stackoverflow.com/q/50803037
tags question: http://stackoverflow.com/q/50809802
tags question: http://stackoverflow.com/q/50699443
tags question: http://stackoverflow.com/q/50723770
tags question: http://stackoverflow.com/q/50701021
tags question: http://stackoverflow.com/q/50848194
tags question: http://stackoverflow.com/q/50789153
tags question: http://stackoverflow.com/q/50814987

http://stackoverflow.com/a/74811948
upvote count: 1
has body: To send html emails using smtplib I use the following code: from email.message import EmailMessage content = " This is a paragraph! " msg = EmailMessage() msg.set_content(content, subtype='html') msg['Subject'] = "Subject" msg['From'] = "SENDER" msg['To'] = "RECEIVER" with smtplib.SMTP("SERVER", 587) as smtp: smtp.starttls() smtp.login("SENDER", "PASS") smtp.send_message(msg)
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50762077

http://stackoverflow.com/comment/88573438
score: 0
has text: I parsed the response using beautiful soup. I get the whole html page as the response. Since I was expecting the output to be the latitude. I tried using soup.find(id="latitude") to get the coordinates but it prints nothing. I'm totally new to python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50783048

http://stackoverflow.com/q/50842873
answer count: 1
has answer: http://stackoverflow.com/a/50842937
has body: I have this function where it calculates today. I am wondering why is the following results are happening. today = datetime.datetime.now() shows as 2018-06-13 17:13:42.372469 today = datetime.datetime.now().date() shows as 2018-06-13 but when I try to use timedelta like this: today = datetime.datetime.now().date() + datetime.timedelta(hours=-8) it shows 2018-06-12. A full day back instead of 8 hours (should show 2018-06-13 9:13:42) Can someone please explain why this happens and have timedelta correctly go back 8 hours instead of a day?
accepted answer: http://stackoverflow.com/a/50842937
has title: Why does timedelta work differently when working with datetime
score: 0
tagged with: datetime
tagged with: python
tagged with: python-3.x
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/50847548
has comment: http://stackoverflow.com/comment/88748107
downvote count: 0
upvote count: 6
has comment: http://stackoverflow.com/comment/88776845
has comment: http://stackoverflow.com/comment/88744009
has body: The example you show comes from the documentation of the respective method. Such methods have little space to go into much detail, so please don't blame the people for actually providing such example in the unusual place of a method docstring. A more detailed explanation of the rc file, the context and examples are found in the Customizing tutorial (the second tutorial in the tutorials page, little chance to miss it). Sticking to the case from the question, the concrete case is you have a python file which contains this code, and in addition you have two text files, named screen.rc and print.rc. The .py file: import matplotlib as mpl import matplotlib.pyplot as plt x = [1,2,3,4] a = [1,2,4,4] b = [1,1,2,4] c = [2,3,3,1] with mpl.rc_context(fname='screen.rc'): plt.plot(x, a) with mpl.rc_context(fname='print.rc'): plt.plot(x, b) plt.plot(x, c) plt.show() The screen.rc file: lines.linewidth : 1 ## line width in points lines.linestyle : - ## linestyle The print.rc file: lines.linewidth : 5 ## line width in points lines.linestyle : : ## linestyle Running the py file would produce something like this as output The blue line is the one created from plt.plot(x, a). It has a solid linestyle and is one point wide. Similar, the green line, plt.plot(x, c), because both are inside the screen.rc context, but not within the print.rc. The orange line is the one created from within the print.rc context. It hence has a linewith of 5 points and is dotted.
has comment: http://stackoverflow.com/comment/88744285
type: Answer
score: 6
answers question: http://stackoverflow.com/q/50846289
has comment: http://stackoverflow.com/comment/88792501

http://stackoverflow.com/q/50801649
tagged with: floating-point
linked to: http://stackoverflow.com/q/8751653
type: Question
duplicate of: http://stackoverflow.com/q/8751653
score: 0
has body: I would to convert a float to binary repr. then convert back the binary repr. to float in python. For the first part float to binary, I am using Float to binary @Ozbolt answer, def float_to_bin(x): if x == 0: return "0" * 64 w, sign = (float.hex(x), 0) if x &gt; 0 else (float.hex(x)[1:], 1) mantissa, exp = int(w[4:17], 16), int(w[18:]) return "{}{:011b}{:052b}".format(sign, exp + 1023, mantissa) Which work very good, for example calling : float_to_bin(10.24) answer: 0100000000100100011110101110000101000111101011100001010001111011 But how to reverse the process (to do binary to float)? I expect something like: bin_to_float("0100000000100100011110101110000101000111101011100001010001111011") which answer: 10.24
has comment: http://stackoverflow.com/comment/88611939
linked to: http://stackoverflow.com/q/4838994
tagged with: binary
has comment: http://stackoverflow.com/comment/88609540
type: UnansweredQuestion
tagged with: python
has title: How to convert bin to float using 64bit IEE754,
answer count: 0

http://stackoverflow.com/q/50718109
has comment: http://stackoverflow.com/comment/88444907
score: 0
tagged with: pandas
tagged with: jupyter-notebook
has title: How to merge two dataframe for only few columns
has answer: http://stackoverflow.com/a/50719348
tagged with: python
tagged with: merge
type: AnsweredQuestion
tagged with: dataframe
has body: Any way to merge two dataframe, but not merge all the columns? I have two dataframes, I want to merge one column to the other dataframe. My data like this In [1]: left = pd.DataFrame({'key1':['a','b','c'], 'key2':['1','2','3'], 'v1':['january','january','january']}, index=[0,5,8]); left Out[1]: key1 key2 v1 0 a 1 january 5 b 2 january 8 c 3 january In [2]: right = pd.DataFrame({'key1':['a','b','c'], 'key2':['1','2','3'], 'v1':['1&lt;0xA4EB&gt;','1&lt;0xA4EB&gt;','1&lt;0xA4EB&gt;'], 'new_value':[23,346,435]}); right Out[2]: key1 key2 v1 new_value 0 a 1 1&lt;0xA4EB&gt; 23 1 b 2 1&lt;0xA4EB&gt; 346 2 c 3 1&lt;0xA4EB&gt; 435 In [3]: pd.merge(left, right'key1', 'key2', 'new_value', on=['key1', 'key2']) Out[3]: key1 key2 v1 new_value 0 a 1 january 23 1 b 2 january 346 2 c 3 january 435 I select the key column and new column, then merge them. But I think this way is not smart. I want to find more easier way, if any one know about this please tell me. Thanks in advance.
type: Question
accepted answer: http://stackoverflow.com/a/50719348
answer count: 1

http://stackoverflow.com/a/50751274
upvote count: 0
answers question: http://stackoverflow.com/q/50731649
score: -1
downvote count: 1
type: Answer
has body: This should work values = df.techies.groupby(df.index).mean() for i, v in enumerate(values): ax.text(v, i-0.1, '%.2f' % v, fontsize=10) Example with a sample dataset import seaborn as sns tips = sns.load_dataset("tips") ax = sns.barplot(y="day", x="total_bill", data=tips) for i, v in enumerate(tips.groupby('day').total_bill.mean()): ax.text(v, i-0.1, '%.2f' % v, fontsize=10)

http://stackoverflow.com/comment/88610460
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50802059
score: 0
has text: Why are you joining it? This makes your solution that much more complicated, and searching one big strings with a complex regex may end up being worse than searching smaller strings with a simpler regex.

http://stackoverflow.com/a/50822862
has comment: http://stackoverflow.com/comment/88653015
upvote count: 1
has comment: http://stackoverflow.com/comment/88651289
has comment: http://stackoverflow.com/comment/88653283
score: 1
has comment: http://stackoverflow.com/comment/88653198
has body: After looking at the site, the form post uses HTTP not HTTPS. It appears their website doesn't respond correctly if you post using HTTPS. This should work: import requests data = { 'MaxLines': '2000', 'MaxNu': '600', 'MinNu': '500', 'Mol': '18003+H2O', 'StrLim': '-500', 'UnitNu': 'GHz', } r = requests.post('http://spec.jpl.nasa.gov/cgi-bin/catform', data=data) print(r.status_code) print(r.text.split('\n')[:10]) Out: ['&lt;OPTION&gt;1001 H-atom ', '&lt;OPTION&gt;2001 D-atom ', '&lt;OPTION&gt;3001 HD ', '&lt;OPTION&gt;4001 H2D+ ', '&lt;OPTION&gt;7001 Li-6-H ', '&lt;OPTION&gt;8001 LiH ', '&lt;OPTION&gt;8002 Li-6-D ', '&lt;OPTION&gt;9001 LiD ', '&lt;OPTION&gt;12001 C-atom ', '&lt;OPTION&gt;13001 C-13-atom ']
has comment: http://stackoverflow.com/comment/88651182
has comment: http://stackoverflow.com/comment/88652024
downvote count: 0
has comment: http://stackoverflow.com/comment/88651238
type: Answer
has comment: http://stackoverflow.com/comment/88651105
has comment: http://stackoverflow.com/comment/88652058
answers question: http://stackoverflow.com/q/50822755
has comment: http://stackoverflow.com/comment/88650937
has comment: http://stackoverflow.com/comment/88652844

http://stackoverflow.com/q/50708269
has answer: http://stackoverflow.com/a/50709827
has comment: http://stackoverflow.com/comment/88426116
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88425804
accepted answer: http://stackoverflow.com/a/50729691
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88426844
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88426558
score: 1
upvote count: 1
tagged with: ping
has title: How to do Ping Test of devices from csv list with Python
type: Question
has answer: http://stackoverflow.com/a/50729691
has body: I am trying to import a csv file that has hostnames and do ping test for such ~100 devices. CSV1: Hostname abc bcd efg . . and so on I want to do ping test and write the ping status whether it is UP or Down in the output csv file along with the corresponding hostnames. Something like this: Output: Hostname Ping Status abc UP bcd DOWN efg DOWN . . . . and so on I have tried my best to lookup on the internet and SO, but found no luck. I am very new to python and I am still in the learning stages. Please help!! import os import csv with open('CSV1.csv', 'r') as f: reader = csv.DictReader(f) rows = list(reader) hosts = [row['CI_Name'] for row in rows] statuses = [row['Status'] for row in rows] for row in rows: #ping hosts hostname = row['CI_Name'] response = os.system("ping -n 1 " + hostname) print ("[DEBUG]", response) if response == 0: print (hostname, 'is up') row['Status'] = 'Up' else: print (hostname, 'is down') row['Status'] = 'Down' #write results with open("Output Final.csv", "w") as w: writer = csv.writer(w) I am getting the output in Python console, and it is displaying the same details of ping that we get when done from 'CMD'. but my output csv file goes untouched. This is much finished version of the code; although i am still working on it to print the ip address of those devices and get the headers correct when writing it to the csv file. import socket import os import csv name = {} CI = {} hostname = {} status = {} with open('Output1.csv', 'r', newline='') as csvinput: reader = csv.DictReader(csvinput) for rows in reader: CI = rows['CI_Name'] name = socket.getfqdn(CI) data = name hostname = rows['CI_Name'] response = os.system('ping -n 2 ' + hostname) if response == 0: status = 'Up' else: status = 'Down' with open('Output Final.csv', 'a', newline='') as csvoutput: output = csv.writer(csvoutput) output.writerow([hostname] + [data] + [status])
has comment: http://stackoverflow.com/comment/88426927
has comment: http://stackoverflow.com/comment/88426047
has comment: http://stackoverflow.com/comment/88425772
possible better answer: http://stackoverflow.com/a/50709827
answer count: 2

http://stackoverflow.com/comment/88469710
type: AnswerComment
comment on: http://stackoverflow.com/a/50730602
type: Comment
has text: Forgot to ask...@coldspeed do you know if there's a way to add two calculated columns inside the originally created pivot table and to keep the original format the same? I had some attempt on this, but didn't get the solution.
score: 0

http://stackoverflow.com/comment/88603873
has text: Thanks Rakesh for the response..If i have more than 100 of files then how should i maintain that?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50798806
score: 0

http://stackoverflow.com/q/50745293
has comment: http://stackoverflow.com/comment/88502215
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/50747217
has comment: http://stackoverflow.com/comment/88498996
tagged with: python
has title: Run python script after pushing ladda button
has body: I've made a few python scripts that I want to execute when I push a ladda button. https://lab.hakim.se/ladda/ First I've created a php file to run the python script &lt;?php $command = escapeshellcmd('/www/html/enable_s1.py'); $output = shell_exec($command); echo $output; header( "refresh:3;url=index.php" ); ?&gt; This works without any problems Next I've created a page to test the ladda button. This also works. But now I want to link an action to the button. I want to run a python script after a button is pressed. When I also include the php code to execute python, it will run everytime the page loads. How can I stop this behavior? Is PHP for executing the python script the best option?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88498356
tagged with: php
type: Question

http://stackoverflow.com/q/50796719
answer count: 1
downvote count: 0
has title: rabbitmq credential issue. only works with localhost
favorite count: 0
has answer: http://stackoverflow.com/a/50800562
tagged with: python
upvote count: 1
tagged with: rabbitmq
accepted answer: http://stackoverflow.com/a/50800562
type: AnsweredQuestion
has body: I have a question regarding rabbitmq. I am trying to set up a messaging system based off the queue name and so far everything has been good with localhost. As soon as I set some credentials for local connection, I get a timeout error. (I have lengthened the timeout time as well.) I have also gave the user administrative privileges and the guest account administrative privileges. I get this error when ran with both the consume and produce script. Port 5672 is open as well. This is all being done on a ubuntu 14.04 LTS machine and python 2.7.14. Guest and my other rabbit user are both allowed to use the default vhost too. import pika, json credentials = pika.credentials.PlainCredentials('guest', 'guest') connection = pika.BlockingConnection(pika.ConnectionParameters('&lt;ip here&gt;', 5672, '/', credentials)) channel = connection.channel() result = channel.queue_declare(queue='hello', durable=True) def callback(ch, method, properties, body): print "localhost received %r" % json.loads(body) channel.basic_consume(callback, queue='hello') print 'localhost waiting for messages. To exit press CTRL+C' channel.start_consuming() channel.close() Here is my error message too. Just a timeout method which would make me think that the connection is failing and this is a network problem but when I replace my ip in the credentials with 'localhost', everything works fine. Any ideas? pika.exceptions.ConnectionClosed: Connection to &lt;ip here&gt;:5672 failed: timeout
score: 1
type: Question
tagged with: pika

http://stackoverflow.com/comment/88695718
comment on: http://stackoverflow.com/q/50845990
score: 0
has text: https://django-allauth.readthedocs.io/en/latest/configuration.html scroll to the acocunt forms header. Does this section help you?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88615068
comment on: http://stackoverflow.com/a/50803635
score: 0
type: AnswerComment
has text: That issue is not a decode error, since it is a `UnicodeEncodeError` so it is an error encoding, not decoding. Try doing both separately, first do `obj = json.loads(r.content.decode(r.encoding))` and in the line below do `print(obj)` ... if the error is in the `print` part, the decoding is working.
type: Comment

http://stackoverflow.com/a/50754091
type: Answer
answers question: http://stackoverflow.com/q/50754069
has body: try my_df.to_dict(orient='records')
score: 0

http://stackoverflow.com/q/50797375
has body: I'm trying to perform the following assertation which fails for some reason: {'a': [('Power', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 2.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)]), ('Speed', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 3.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)])], 'b': [('Power', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 4.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)]), ('Speed', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 5.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)])], 'c': [('Power', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 6.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)]), ('Speed', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 7.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)])]} != {'a': [('Power', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 2.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)]), ('Speed', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 3.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)])], 'b': [('Power', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 4.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)]), ('Speed', [(datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), 5.0), (datetime.datetime(2018, 6, 11, 14, 1, 26, 911251), nan)])], 'c': [('Power…
has comment: http://stackoverflow.com/comment/88601343
upvote count: 2
has comment: http://stackoverflow.com/comment/88601023
type: Question
has comment: http://stackoverflow.com/comment/88602401
linked to: http://stackoverflow.com/q/44367557
tagged with: numpy
downvote count: 0
answer count: 1
has title: Python unittest assert complex dictionary
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50798374
tagged with: python
score: 2

routes
tags question: http://stackoverflow.com/q/50752137
tag name: routes
type: Tag

http://stackoverflow.com/comment/88425189
comment on: http://stackoverflow.com/q/50708021
score: 0
type: Comment
type: QuestionComment
has text: what is in `self.magic[i]['dmg']` i think there is something with type `str` not `int`, can you show all class ?

export-to-csv
tags question: http://stackoverflow.com/q/50814291
tags question: http://stackoverflow.com/q/50828125
type: Tag
tags question: http://stackoverflow.com/q/50712062
tag name: export-to-csv
tags question: http://stackoverflow.com/q/50829206

http://stackoverflow.com/a/50807797
has comment: http://stackoverflow.com/comment/88644329
accepted answer of: http://stackoverflow.com/q/50776019
answers question: http://stackoverflow.com/q/50776019
type: Answer
score: 2
has body: I don't know if this is the best way, but it's fairly straightforward, and easy to modify. It handles the example in your problem statement, plus most of the example from your comment. import sys, re text = sys.stdin.read() # A pattern expressing the parts of the input that we want to preserve: keeper_pattern = r'''(?x) # verbose format ( # We put parens around the whole pattern # (and use ?: for subgroups) # so that when we use it as the splitter-pattern for re.split(), # the result contains one string for each occurrence of the pattern # (in addition to the usual between-splitter strings). # The main thing we want to keep is paragraph-separators, # and the 'lead' of the line that follows a para-sep: # \n{2,} # two or more newlines, followed by \x20* # optional indentation (zero or more spaces), followed by (?: # an optional item-marker, which is (?: # either \d+ \. # digits followed by a dot, | # or [a-z] \) # a letter followed by a right-paren, ) # followed by \x20+ # one or more spaces. )? | # The other thing we want to keep is # item-markers within paragraphs: # \( i+ \) # a lower-case Roman numeral between parens # (generalize as necessary) ) ''' for (i, chunk) in enumerate(re.split(keeper_pattern, text)): # In the result of re.split(), # the splitters (keepers) will be in the odd positions. is_keeper = (i % 2 == 1) if is_keeper: if chunk.startswith('\n'): # paragraph-separator etc replacement = chunk else: # within-para item-marker replacement = ' ' + chunk + ' ' else: if chunk == '': # (happens if two keepers are adjacent) replacement = '' else: # everything else replacement = '&lt;string&gt;' sys.stdout.write(replacement)
upvote count: 2
has comment: http://stackoverflow.com/comment/88632978
has comment: http://stackoverflow.com/comment/88627541
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88645005
has text: I understand that it expects it, but the httpclient won't let you set an authorization header by using the defaultrequestheaders.add method. You need to set it wiht the Authorization property of the DefaultRequestHeaders.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50818727

http://stackoverflow.com/a/50785594
has comment: http://stackoverflow.com/comment/88577975
type: Answer
has comment: http://stackoverflow.com/comment/88600083
downvote count: 0
answers question: http://stackoverflow.com/q/50785498
has body: Use pandas for such manipulations. Load both csv file in two data-frame using pandas and take the intersection of both column. Pandas have inbuilt features. pd.merge Import pandas as pd df1 = pd.read_csv(file1) df2 = pd.read_csv(file2) output = pd.merge(df1, df2, how="inner", on="column_name") #column_name should be common in both dataframe #how represents type of intersection. In your case it will be inner(INNER JOIN) output['count'] = output.groupby('column_name')['column_name'].transform('size') #pandas query final_output = output.drop_duplicates() #It will remove duplicate rows Hope, It will help.
accepted answer of: http://stackoverflow.com/q/50785498
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/50816996
tagged with: chatbot
answer count: 2
has answer: http://stackoverflow.com/a/50863060
has answer: http://stackoverflow.com/a/67725633
accepted answer: http://stackoverflow.com/a/67725633
upvote count: 2
favorite count: 0
has body: I am using python package dialogflow to connect to my dialogflow agent. I have 2 doubts regarding dialogflow agent training When I add intents using RPC, do I need to explicitly train? And by train I mean call the TrainAgent function and wait for it to complete. If I call TrainAgent twice in succession without waiting between those calls, will dialogflow train twice or just take the recentmost request and train once?
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50863060
tagged with: dialogflow-es
has title: Training Dialogflow Doubts
type: Question

http://stackoverflow.com/q/50717900
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88444724
has comment: http://stackoverflow.com/comment/88444580
answer count: 0
has title: Selenium Django/Python error:Unable to find a matching set of capabilities
type: Question
has body: Running this Django tests on chat app that has uses selenium tests.py from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait import os print(os.environ['PATH']) class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Firefox() except: super().tearDownClass() raise ... when I run the test I get this error (chatenv) muiruri_samuel@train:~/webapp/chatsys$ python manage.py test chat.tests /home/muiruri_samuel/webapp/chatenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games: /usr/local/games:/snap/bin Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: setUpClass (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/muiruri_samuel/webapp/chatsys/chat/tests.py", line 17, in setUpClass cls.driver = webdriver.Firefox() File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py" , line 170, in __init__ keep_alive=True) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 245, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 314, in execute self.error_handler.check_response(re…
linked to: http://stackoverflow.com/q/43713445
tagged with: python
score: 0
tagged with: selenium
tagged with: django
has comment: http://stackoverflow.com/comment/88444933

http://stackoverflow.com/q/50805511
has body: I'm having a problem calling python scripts from vba in Excel. I read other threads that addressed the same problem, but when I run the code, a Python screen flashes and then disappears. FYI, I downloaded python 3.6.5 for Windows 10 and added it to PATH. Can someone let me know why the screen flashes and what I can do to solve it? Thanks Sub Run_python() Dim Ret_Val Dim args As String args = "C:\Users\opera\AppData\Local\Programs\Python\Python36\Tools\scripts\db2pickle.py" Ret_Val = Shell("C:\Users\opera\AppData\Local\Programs\Python\Python36\python.exe" &amp; " " &amp; args, vbNormalFocus) If Ret_Val = 0 Then MsgBox "Couldn't run python script!", vbOKOnly End If End Sub
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50805987
upvote count: 1
tagged with: vba
possible better answer: http://stackoverflow.com/a/61072336
has answer: http://stackoverflow.com/a/50805987
has title: Call Python Script from VBA
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88617180
tagged with: excel
has comment: http://stackoverflow.com/comment/88639010
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61072336
downvote count: 0
has comment: http://stackoverflow.com/comment/88617591
score: 1

http://stackoverflow.com/comment/88566070
comment on: http://stackoverflow.com/q/50779576
score: 0
type: Comment
type: QuestionComment
has text: What do you mean get the value? Use the somewhere else in the code? Printing it? Displaying it in a widget?

http://stackoverflow.com/comment/102326889
comment on: http://stackoverflow.com/q/50815151
type: QuestionComment
has text: @EthanField I am betting it isn't fun asking following questions where it seems that there is dissonance between us - thank you for your time and patience. I haven't encountered the ID you mention, i did however encounter the dictionary key. Do we mean same thing ? When i say layered frames, to add to description above, i mean that multiple frames are part of `Tk/tk` root window.
score: 0
type: Comment

http://stackoverflow.com/comment/95909748
has text: Regarding this question.... df.to_sql() won't work with Vertica?? Thanks
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50890924
score: 1

http://stackoverflow.com/q/50725830
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/55426513
answer count: 1
has body: I believe I understand HMM at its core. Through HMM we solve evaluation (prob of emitted seq), decoding (most probable hidden seq), and learning problem (learning transition and emission prob-matrix from observed set of emission seq). My problem is associated with the learning problem. I have emission sequence but with that I also have associated features (meaning hidden state value, but the number of hidden states is not known) for each sequence. As in learning problem of HMM, we estimate hidden-sequence (size and prob-matrix) and for that we just need emission sequence (size of hidden sequence can be optimized if not known in advance). I am using HMM library for my computation. Of course, it does not have the option I want. import numpy as np import pandas as pd from hmmlearn import hmm filenames = [f for f in os.listdir(dir_path) if '.csv' in f.lower()] d1 = pd.read_csv(dir_path + filenames[0]).as_matrix() # Shape = [m, 3] =&gt; first two column is featute and last is the emission-state d2 = pd.read_csv(dir_path + filenames[1]).as_matrix() # Shape = [m, 3] ## remodel = hmm.GaussianHMM(n_components=4, covariance_type="full", n_iter=100) remodel.fit(d1[:, 0:2]) # Problem would have been solved if there was supervised option to pass the states as well pred_1 = remodel.predict(d1[:, 0:2]) true_1 = d1[:, -1] # Last column is state of the feature in 1, 2 column. pred_2 = remodel.predict(d2[:, 0:2]) true_2 = d2[:, -1] Is there a way to do supervised learning in HMM, if yes then how? If not then can I still solve my problem using HMM? If it is possible then how?
has title: Can we do supervised learning through HMM?
tagged with: hmmlearn
downvote count: 0
type: UnansweredQuestion
favorite count: 0
tagged with: hidden-markov-models
type: Question
score: 3
tagged with: supervised-learning

virtualenv
tags question: http://stackoverflow.com/q/50841069
tags question: http://stackoverflow.com/q/50792179
tags question: http://stackoverflow.com/q/50730946
tags question: http://stackoverflow.com/q/50713316
tags question: http://stackoverflow.com/q/50785230
tags question: http://stackoverflow.com/q/50791205
tags question: http://stackoverflow.com/q/50835383
tags question: http://stackoverflow.com/q/50773316
tags question: http://stackoverflow.com/q/50705231
tags question: http://stackoverflow.com/q/50790105
tag name: virtualenv
tags question: http://stackoverflow.com/q/50709439
tags question: http://stackoverflow.com/q/50840159
tags question: http://stackoverflow.com/q/50813738
tags question: http://stackoverflow.com/q/50774504
tags question: http://stackoverflow.com/q/50731010
tags question: http://stackoverflow.com/q/50721944
tags question: http://stackoverflow.com/q/50801820
tags question: http://stackoverflow.com/q/50759255
tags question: http://stackoverflow.com/q/50846300
type: Tag

http://stackoverflow.com/comment/88692715
type: QuestionComment
type: Comment
has text: Also, please show us why you think the quotes or slash are the culprits. Most likely, you're using `subprocess` in a way where the whole string `a` is being interpreted as a *program* to run rather than a *command* to be executed by DOS. But without an MVCE, we're left guessing. Show us your code!
score: 0
comment on: http://stackoverflow.com/q/50844354

http://stackoverflow.com/comment/88466999
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50729511
has text: "it doesn't work" is not a helpful response.
type: Comment

scipy
tags question: http://stackoverflow.com/q/50699854
tags question: http://stackoverflow.com/q/50849365
tags question: http://stackoverflow.com/q/50774022
tags question: http://stackoverflow.com/q/50850399
tags question: http://stackoverflow.com/q/50802642
tags question: http://stackoverflow.com/q/50795981
tags question: http://stackoverflow.com/q/50704701
tags question: http://stackoverflow.com/q/50713828
tags question: http://stackoverflow.com/q/50711945
tags question: http://stackoverflow.com/q/50806259
tags question: http://stackoverflow.com/q/50798935
tags question: http://stackoverflow.com/q/50816375
tags question: http://stackoverflow.com/q/50786498
type: Tag
tags question: http://stackoverflow.com/q/50742920
tags question: http://stackoverflow.com/q/50775532
tag name: scipy
tags question: http://stackoverflow.com/q/50719450
tags question: http://stackoverflow.com/q/50838346
tags question: http://stackoverflow.com/q/50778206
tags question: http://stackoverflow.com/q/50841800
tags question: http://stackoverflow.com/q/50786376
tags question: http://stackoverflow.com/q/50839521
tags question: http://stackoverflow.com/q/50712589
tags question: http://stackoverflow.com/q/50845507
tags question: http://stackoverflow.com/q/50786145
tags question: http://stackoverflow.com/q/50827728
tags question: http://stackoverflow.com/q/50812319
tags question: http://stackoverflow.com/q/50822925
tags question: http://stackoverflow.com/q/50773233
tags question: http://stackoverflow.com/q/50812323
tags question: http://stackoverflow.com/q/50761126
tags question: http://stackoverflow.com/q/50750146
tags question: http://stackoverflow.com/q/50725227
tags question: http://stackoverflow.com/q/50831551
tags question: http://stackoverflow.com/q/50732866
tags question: http://stackoverflow.com/q/50700098
tags question: http://stackoverflow.com/q/50778877
tags question: http://stackoverflow.com/q/50823131
tags question: http://stackoverflow.com/q/50785188
tags question: http://stackoverflow.com/q/50825505
tags question: http://stackoverflow.com/q/50767157
tags question: http://stackoverflow.com/q/50700890
tags question: http://stackoverflow.com/q/50701425
tags question: http://stackoverflow.com/q/50804120
tags question: http://stackoverflow.com/q/50835952
tags question: http://stackoverflow.com/q/50748725
tags question: http://stackoverflow.com/q/50772882
tags question: http://stackoverflow.com/q/50827554
tags question: http://stackoverflow.com/q/50706410
tags question: http://stackoverflow.com/q/50739860
tags question: http://stackoverflow.com/q/50746293
tags question: http://stackoverflow.com/q/50735112
tags question: http://stackoverflow.com/q/50820206
tags question: http://stackoverflow.com/q/50793435
tags question: http://stackoverflow.com/q/50757847
tags question: http://stackoverflow.com/q/50709478

http://stackoverflow.com/comment/88535198
comment on: http://stackoverflow.com/q/50763441
score: 1
has text: What about individual file permissions? Your bucket may allow read-only access, but do the individual files in your bucket allow your user to look at them? I had a similar problem with viewing a static website a while back.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88726752
type: AnswerComment
has text: If your `features` contain a list of 2D coordinates, you can retrieve the corresponding values at once with `tf.gather_nd()`. If your `features` is a single 2D coordinate or coordinate range, you can more simply use the shorter numpy-like notation.
type: Comment
comment on: http://stackoverflow.com/a/50822680
score: 0

http://stackoverflow.com/comment/88463990
score: 0
type: Comment
has text: What do you mean by moving the path import to the end of the node module? Can I ask for an example applied to my case?
comment on: http://stackoverflow.com/a/50727781
type: AnswerComment

http://stackoverflow.com/comment/88503960
has text: @FrançoisAndrieux right thats why i included more documentation
comment on: http://stackoverflow.com/a/50748215
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88565919
type: QuestionComment
has text: You have numerous errors with your `filterOddInList()` function. You are accidentally recursing - did you mean `odd = isOddNumber(item)`. `x` doesn't exist so you can't `pop()` from it. You are never changing `i` so it will loop forever. And you are not `return`ing anything from it.
comment on: http://stackoverflow.com/q/50779389
score: 1
type: Comment

http://stackoverflow.com/a/50832787
type: AcceptedAnswer
has body: Assuming you have any word2vec utility as word2vec: import numpy as np words1 = sentence1.split(' ') words2 = sentence2.split(' ') #The meaning of the sentence can be interpreted as the average of its words sentence1_meaning = word2vec(words1[0]) count = 1 for w in words1[1:]: sentence1_meaning = np.add(sentence1_meaning, word2vec(w)) count += 1 sentence1_meaning /= count sentence2_meaning = word2vec(words2[0]) count = 1 for w in words2[1:]: sentence2_meaning = np.add(sentence2_meaning, word2vec(w)) count += 1 sentence2_meaning /= count #Similarity is the cosine between the vectors similarity = np.dot(sentence1_meaning, sentence2_meaning)/(np.linalg.norm(sentence1_meaning)*np.linalg.norm(sentence2_meaning))
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50832594
answers question: http://stackoverflow.com/q/50832594

http://stackoverflow.com/comment/88530008
has text: You could also make this a bit more generic by expecting a format string for values: `values='={}!$M$1:$M$400'`
type: Comment
comment on: http://stackoverflow.com/a/50761204
score: 0
type: AnswerComment

http://stackoverflow.com/a/50702086
has comment: http://stackoverflow.com/comment/88414209
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50702058
answers question: http://stackoverflow.com/q/50702058
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88414058
downvote count: 0
has body: You can use the __name__ attribute: &gt;&gt;&gt;string.__class__.__name__ == 'str' True However, to use __class__, compare with str as a builtin: &gt;&gt;&gt;string.__class__ == str True
upvote count: 2

http://stackoverflow.com/comment/88647932
score: 0
type: AnswerComment
has text: Glad it helps you. df[df.bullishSignal].Date will get you all the dates when the signal occurs.
type: Comment
comment on: http://stackoverflow.com/a/50814127

http://stackoverflow.com/q/50738955
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88485691
has comment: http://stackoverflow.com/comment/88486067
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Converting Hexadecimal character of string to normal characters in python
has answer: http://stackoverflow.com/a/50752772
score: 1
tagged with: mysql
tagged with: character-encoding
has body: I have a scenario where I have to lodge file path to DB and while fetching the content, I am getting the special characters converted into Hexadecimal values. But with that path, I would not be able to open the files, so I need them in a normal string. I tried searching a lot but could not get the solution, for example, I am getting the output as "D:\nhubh\x07oo\x08\x07m" and my expectation is: D:\nhubh\aoo\b\am Please help. Thanks in advance :)
type: Question
has comment: http://stackoverflow.com/comment/88485930
downvote count: 0
has comment: http://stackoverflow.com/comment/88486476
linked to: http://stackoverflow.com/q/9641440
has comment: http://stackoverflow.com/comment/88485536

http://stackoverflow.com/a/50750580
type: AcceptedAnswer
score: 0
has body: As k and H are floats, (k/H) turns out to be a float. You cant multiply a sequence with a float, must be an int. Also multiplying a sequence will expand the sequence which I am guessing isn't what you want. I believe what you are probably looking is a result. You can simply get rid of the [ ] brackets.
type: Answer
accepted answer of: http://stackoverflow.com/q/50750444
answers question: http://stackoverflow.com/q/50750444
has comment: http://stackoverflow.com/comment/88528836

pykafka
tag name: pykafka
type: Tag
tags question: http://stackoverflow.com/q/50716679

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/50762489
tags question: http://stackoverflow.com/q/50790965
tags question: http://stackoverflow.com/q/50759182

http://stackoverflow.com/q/50749517
upvote count: 3
tagged with: pip
has answer: http://stackoverflow.com/a/50750665
type: Question
type: AnsweredQuestion
score: 3
has title: pip install ourSQL "Cannot find the file specified"
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50750665
favorite count: 0
tagged with: oursql
tagged with: python
has body: When I try to use pip to install oursql I run into the following error C:\Users\user&gt;pip install oursql Collecting oursql Using cached https://files.pythonhosted.org/packages/8c/88/9f53a314a2af6f56c0a1249c5673ee384b85dc791bac5c1228772ced3502/oursql-0.9.3.2.tar.gz Installing collected packages: oursql Running setup.py install for oursql ... error Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\user\\appdata\\local\\temp\\pip-install-l7rkx0\\oursql\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\user\appdata\local\temp\pip-record-yke4zh\install-record.txt --single-version-externally-managed --compile: cython not found, using previously-cython'd .c file. running install running build running build_ext error: [Error 2] The system cannot find the file specified ---------------------------------------- Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\user\\appdata\\local\\temp\\pip-install-l7rkx0\\oursql\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\user\appdata\local\temp\pip-record-yke4zh\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\user\appdata\local\temp\pip-install-l7rkx0\oursql\ And I run into the same error when I try to install from source C:\Users\user\Downloads\oursql-0.9.3.1&gt;python setup.py install cython not found, using previously-cython'd .c file. running install running build running build_ext error: [Error 2] The system cannot find the file specified I've tried running cmd as administrator and the same errors occurred. Any help in this would be appreciated. (Windows 10, Python 2.7)
has comment: http://stackoverflow.com/comment/88506614

http://stackoverflow.com/a/50769760
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: I'm working with the elasticsearch_dsl library but this question is broadly applicable to Python. It is not broadly applicable to Python, actually. In a normal class, accessing cls.Meta.index would just work as usual here. DocType has a metaclass that removes Meta from the class namespace. If I'm reading the source code correctly, the attribute you're looking for should be available at cls._doc_type.index. &gt;&gt;&gt; class Example(DocType): ... class Inner: ... index = 'inner_var' ... class Meta: ... index = 'meta_var' ... @classmethod ... def foo(cls): ... print(cls.Inner.index) ... print(cls._doc_type.index) ... &gt;&gt;&gt; Example.foo() inner_var meta_var Note: The presence of a leading underscore on the DocTypeOptions instance, i.e. _doc_type, suggests private API. Perhaps you should look for a public API to create index instead.
answers question: http://stackoverflow.com/q/50769603
type: Answer
accepted answer of: http://stackoverflow.com/q/50769603

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/50709114
tags question: http://stackoverflow.com/q/50756758
tags question: http://stackoverflow.com/q/50730502
tags question: http://stackoverflow.com/q/50827039
tags question: http://stackoverflow.com/q/50712106
tags question: http://stackoverflow.com/q/50845807
tags question: http://stackoverflow.com/q/50710987
tags question: http://stackoverflow.com/q/50709365
type: Tag

http://stackoverflow.com/q/50847997
has title: Divide several columns by one constant via a for loop
has answer: http://stackoverflow.com/a/50848030
has body: I want to divide several columns by the same constant via a for loop in python. The below is a subset of my dataframe: dataframe: DF team group1 group2 group3 group4 blue 100 400 650 75 green 150 500 350 186 red 200 600 175 540 orange 250 700 900 375 I have attempted: for col in DF.columns[1:]: DF[col] = df[col]/10 the below code works, but I want to use a for loop to iterate through all columns. Ideally, i would not like to have to pick out the numeric columns and apply the division to all columns and if it does run into a string, to ignore the string DF['group1'] = DF['group1']/10 the error i am getting is : 'unsupported operand type(s) for /: 'str' and 'int'
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50848372
possible better answer: http://stackoverflow.com/a/50848026
favorite count: 0
has answer: http://stackoverflow.com/a/50848026
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50848030
type: AnsweredQuestion
score: 1
type: Question
downvote count: 0

http://stackoverflow.com/comment/88656518
type: QuestionComment
has text: That stack trace doesn't make sense. You're getting a KeyError, inside a `try` that explicitly catches `KeyError`? Also, you seem to have cut off part of the end of the message.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50825719

http://stackoverflow.com/q/50778932
tagged with: matplotlib
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/9295026
tagged with: percentage
has title: Horizontal bars using Python
has comment: http://stackoverflow.com/comment/88573920
has comment: http://stackoverflow.com/comment/88570271
has comment: http://stackoverflow.com/comment/88569860
answer count: 0
tagged with: progress-bar
type: Question
tagged with: visualization
has body: I am new to Python and I wanted to know if there was any way, using a library, to display such bars. Not necessarily with the colors or the percentage shown, but this idea of horizontal bars showing a level of progress. I've tried the barh tool of matplotlib but it doesn't seem to be what I need, since I can only have a horizontal bar going to a certain value, but not the "empty" part (let's say if I have 60%, "empty" part would be the other 40%), plus it lacks of customization (hide the graph axis etc.) Thanks in advance!
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/88565528
linked to: http://stackoverflow.com/q/11892175
duplicate of: http://stackoverflow.com/q/11892175

http://stackoverflow.com/comment/88588311
score: 0
has text: Is ``/var/www/html/test`` the value given by ``sys.prefix`` for the Python installation or virtual environment you want used? See http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50791205

http://stackoverflow.com/q/50759094
type: Question
has answer: http://stackoverflow.com/a/50759155
tagged with: algorithm
score: 1
has answer: http://stackoverflow.com/a/50759452
accepted answer: http://stackoverflow.com/a/50759155
has title: Yield number into parts smaller than a threshold in Python
possible better answer: http://stackoverflow.com/a/50759295
has body: Assuming I have a number n=22500 and a threshold t=10000, I want to have a function that yields: 10000, 10000, 2500. How do I do this? My non-working attempt because once you go over 20000 it returns numbers larger than 10000. def chunk(number): steps = 10000 if number &gt; steps: yield steps yield number - steps else: yield number for i in chunk(35000): print(i) # prints (wrongly): # 10000 # 25000 Or is there a builtin library for this?
downvote count: 0
has answer: http://stackoverflow.com/a/50759295
has comment: http://stackoverflow.com/comment/88525695
answer count: 3
tagged with: python
favorite count: 0
tagged with: generator
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/a/50773678
answers question: http://stackoverflow.com/q/50773602
has comment: http://stackoverflow.com/comment/88554492
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You can achieve this by generating the cartesian product of the elements using itertools: import itertools letters = ["O", "Z"] length = 3 vals = [''.join(comb) for comb in itertools.product(letters, repeat=length)] print(vals) &gt;&gt;&gt;['OOO', 'OOZ', 'OZO', 'OZZ', 'ZOO', 'ZOZ', 'ZZO', 'ZZZ']

http://stackoverflow.com/comment/88570666
comment on: http://stackoverflow.com/q/50781953
has text: @AhmedWagdi: but it does this *for every `item`*. Hence it will construct a `Favorite` that perhaps in a next round is removed.
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/50748885
answers question: http://stackoverflow.com/q/50747359
has comment: http://stackoverflow.com/comment/88506962
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50747359
has body: This is about 1.7 times faster than your method_1 and a little tidier: df_expand = pd.DataFrame.from_records( ( (d, r.type, r.value) for r in df.itertuples() for d in pd.date_range(start=r.start, end=r.end, freq='D') ), columns=['day', 'type', 'row'] ) You can get about 7 times faster by creating your own date range instead of calling pd.date_range(): one_day = dt.timedelta(1) df_expand = pd.DataFrame.from_records( ( (r.start + i * one_day, r.type, r.value) for r in df.itertuples() for i in range(int((r.end-r.start)/one_day)+1) ), columns=['day', 'type', 'row'] ) Or you can get up to 24 times faster by using numpy's arange function to generate the dates: one_day = dt.timedelta(1) df_expand = pd.DataFrame.from_records( ( (d, r.type, r.value) for r in df.itertuples() for d in np.arange(r.start.date(), r.end.date()+one_day, dtype='datetime64[D]') ), columns=['day', 'type', 'row'] ) I couldn't resist adding one more that is a little more than twice as fast as the last one. Unfortunately, it's a lot harder to read. This groups the readings based on how many days they span ('dur'), then uses vectorized numpy operations to expand each group in a single batch. def expand_group(g): dur = g.dur.iloc[0] # how many days for each reading in this group? return pd.DataFrame({ 'day': (g.start.values[:,None] + np.timedelta64(1, 'D') * np.arange(dur)).ravel(), 'type': np.repeat(g.type.values, dur), 'value': np.repeat(g.value.values, dur), }) # take all readings with the same duration and process them together using vectorized code df_expand = ( df.assign(dur=(df['end']-df['start']).dt.days + 1) .groupby('dur').apply(expand_group) .reset_index('dur', drop=True) ) Update: Responding to your comment, below is a simplified version of the vectorized approach, which is faster and easier to read. Instead of using the groupby step, this makes a single matrix as wide as the longest reading, then filters out the unneeded entries. This should be pretty efficient unless the maximum duration for …
has comment: http://stackoverflow.com/comment/88983018
has comment: http://stackoverflow.com/comment/88874332
has comment: http://stackoverflow.com/comment/88921257
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88919869
has comment: http://stackoverflow.com/comment/88984325
has comment: http://stackoverflow.com/comment/88513744
type: Answer

http://stackoverflow.com/comment/88715149
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50845631
has text: In Windows, you need to wrap your code with if __name__ == '__main__': block. https://stackoverflow.com/questions/50701690/pytorch-tutorial-error-training-a-classifier/50716024#50716024
type: Comment

http://stackoverflow.com/comment/88601158
type: Comment
comment on: http://stackoverflow.com/q/50796370
type: QuestionComment
has text: At least in PyCharm, you can add `tests` as source root in the project settings; this resolves the import issues.
score: 2

http://stackoverflow.com/q/50798517
favorite count: 0
tagged with: amazon-redshift
tagged with: python
has comment: http://stackoverflow.com/comment/88611838
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/50798726
has title: Is there a way to use COPY on multiple files at once?
has comment: http://stackoverflow.com/comment/88603203
has body: I am trying to find a way to move our MySQL databases and put them on Amazon Redshift for its speed and scalable storage. They recommend splitting the data into multiple files and using the COPY command to copy data from S3 into the data warehouse. I am using Python to attempt to automate this process and plan to use boto3 for client side encryption of the data s3 = boto3.client('s3', aws_access_key_id='[Access key id]', aws_secret_access_key='[Secret access key]') filename = '[S3 file path]' bucket_name = '[Bucket name]' # Uploads the given file using a managed uploader, which will split up large # files automatically and upload parts in parallel. s3.upload_file(filename, bucket_name, filename) #create table for data statement = 'create table [table_name] ([table fields])' conn = psycopg2.connect( host='[host]', user='[user]', port=5439, password='[password]', dbname='dev') cur = conn.cursor() cur.execute(statement) conn.commit() #load data to redshift conn_string = "dbname='dev' port='5439' user='[user]' password='[password]' host='[host]'" conn = psycopg2.connect(conn_string); cur = conn.cursor() cur.execute("""copy [table_name] from '[data location]' access_key_id '[Access key id]' secret_access_key '[Secret access key]' region 'us-east-1' null as 'NA' delimiter ',' removequotes;""") conn.commit() The problem is with this code is I think I would have to individually create a table for every table and then copy it over for every file individually. Is there a way to get the data into redshift using a single copy for multiple files? Or is it possible to run multiple copy statements at once? And is it possible to do this without creating a table for every single file?
type: Question
tagged with: copy
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50798726
tagged with: amazon-web-services

http://stackoverflow.com/comment/88614981
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50804061
type: QuestionComment
has text: Isn't possible to modify the original string because in python strings are immutable.

http://stackoverflow.com/q/50707777
has title: Set IAM Policy works on local machine but not in GCE instance
score: 0
type: Question
tagged with: docker
has answer: http://stackoverflow.com/a/50861504
tagged with: google-cloud-platform
answer count: 1
has body: The following lines from my Python app execute with no problems on my local machine. import googleapiclient.discovery project_id = 'some-project-id' resource_manager = googleapiclient.discovery.build('cloudresourcemanager', 'v1') iam_policy_request = resource_manager.projects().getIamPolicy(resource=project_id, body={}) iam_policy_response = iam_policy_request.execute(num_retries=3) new_policy = dict() new_policy['policy'] = iam_policy_response del new_policy['policy']['version'] iam_policy_update_request = resourcemanager.projects().setIamPolicy(resource=project_id, body=new_policy) update_result = iam_policy_update_request.execute(num_retries=3) When I run the app in a GCE instance, and more precisely from within a Docker container inside the GCE instance, I get the exception: URL being requested: POST https://cloudresourcemanager.googleapis.com/v1/projects/some-project-id:setIamPolicy?alt=json Traceback (most recent call last): File "/env/lib/python3.5/site-packages/google/api_core/grpc_helpers.py", line 54, in error_remapped_callable return callable_(*args, **kwargs) File "/env/lib/python3.5/site-packages/grpc/_channel.py", line 487, in __call__ return _end_unary_response_blocking(state, call, False, deadline) File "/env/lib/python3.5/site-packages/grpc/_channel.py", line 437, in _end_unary_response_blocking raise _Rendezvous(state, None, None, deadline) grpc._channel._Rendezvous: &lt;_Rendezvous of RPC that terminated with (StatusCode.PERMISSION_DENIED, User not authorized to perform this action.)&gt; i.e. an authorization error. Oddly, when I open a Python terminal session inside the GCE instance and run the Python code line by line, I do not get the exception. It only throws the exception when the code is running as part of the app. I am using a service account inside of the GCE instance, as opposed to my regular account on my local machine. But I don't think that is the problem since I am able to run the lines of code one by one inside of the instance while …
tagged with: python-3.x
type: UnansweredQuestion
tagged with: google-compute-engine
tagged with: python

http://stackoverflow.com/comment/88661347
comment on: http://stackoverflow.com/q/50828295
type: QuestionComment
type: Comment
has text: Not quite sure I understand what you're looking for, but can you just add the two lists as parameters to the function and keep passing them through, ultimately returning them?
score: 2

http://stackoverflow.com/q/50747481
has comment: http://stackoverflow.com/comment/88502579
has comment: http://stackoverflow.com/comment/88502981
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88503713
downvote count: 2
has comment: http://stackoverflow.com/comment/88502744
has comment: http://stackoverflow.com/comment/88503685
has body: I've been trying to define a function that returns the word with the highest score. Firstly, I made a dictionary (because there are letters who have no punctuation and others have the same). So, imagine I have best(["Babel", "Xadrez"]). It is supposed to return "Xadrez", because it has 21 points against the 10 points of the other word, but I'm not getting it. This is my code by now: def best(lista): dic = {'D':2, 'C':2, 'L':2, 'P':2, 'B':3, 'N':3, 'F':4, 'G':4, 'H':4, 'V':4, 'J':5, 'Q':6, 'X':8, 'Y':8, 'Z':8} for i in range(len(lista)): if lista[i] &gt;= 'A' and lista[i] &lt;= 'Z': lista.append(lista[i]) return lista txt = lista soma1 = 0 soma2 = 0 soma3 = 0 for palavra in txt: soma1 = soma1 + dic.get(palavra, 0) for palavra in txt: soma2 = soma2 + dic.get(palavra, 0) for palavra in txt: soma3 = soma3 + dic.get(palavra, 0) #I think the problem starts here, because we don't know where the next #word starts neither how many words there are if soma1 &gt; soma2 and soma1 &gt; soma3: return soma1 elif soma2 &gt; soma1 and soma2 &gt; soma3: return soma2 else: return soma3 #I know that this returns the punctuation of the word instead of the #word itself, but I did it for just a reason: if the code was right #it would be easy to return the word #Thanks.
has comment: http://stackoverflow.com/comment/88502755
type: Question
has comment: http://stackoverflow.com/comment/88502569
score: -2
has answer: http://stackoverflow.com/a/50747581
has comment: http://stackoverflow.com/comment/88502777
has comment: http://stackoverflow.com/comment/88502814
has comment: http://stackoverflow.com/comment/88502845
upvote count: 0
has title: Return the word with the highest score
answer count: 1
has comment: http://stackoverflow.com/comment/88502622
has comment: http://stackoverflow.com/comment/88502876
has comment: http://stackoverflow.com/comment/88502929
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50747581
has comment: http://stackoverflow.com/comment/88502822
tagged with: python

http://stackoverflow.com/q/50709114
answer count: 1
linked to: http://stackoverflow.com/q/47152691
upvote count: 1
has answer: http://stackoverflow.com/a/50709190
duplicate of: http://stackoverflow.com/q/47152691
tagged with: group-by
accepted answer: http://stackoverflow.com/a/50709190
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has body: I have the following dataframe: name state teams score abc NY red 1 def VA yellow 9 ghi MO green 6 abc WA red 2 klm IL yellow 1 ghi MN green 8 def VA blue 3 xyz NY blue 5 abc NY blue 5 abc NY red 4 ghi MN green 7 I want to group the data in such a way for every name state combination, I want the least score for each team, for example in the data we have: name 'abc', state 'NY' and team 'red' has two scores 1 and 4 then here the least score for team 'red' is 1. And for the teams we do not have the score the least score can be 0. Example Output: name state red yellow green blue abc NY 1 0 0 5 def VA 0 9 0 3 ghi MO 0 0 6 0 abc WA .................... klm IL .................... ghi MN 0 0 7 0 xyz NY 0 0 0 5
score: 1
favorite count: 0
type: Question
tagged with: pivot-table
has title: How to use groupby or pivot in this pandas dataframe in python
tagged with: python

http://stackoverflow.com/comment/88424675
score: 1
has text: https://gitpython.readthedocs.io/en/stable/tutorial.html#switching-branches and https://gitpython.readthedocs.io/en/stable/tutorial.html#using-git-directly
comment on: http://stackoverflow.com/q/50707781
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50786767
accepted answer of: http://stackoverflow.com/q/50784250
type: Answer
has body: It seems based on this bug report that the username_validator setting doesn't work as intended - although that bug is old and the docs for 2.0 still provide this method, I'm assuming it hasn't been fixed as I've tried everything. Ultimately I'm going to bite the bullet and migrate to a custom user model, I should have done it from the get go but luckily I'm just implementing django all-auth as my exclusive sign in method and planned on dropping existing users anyways so hopefully the migration shouldn't be too much trouble. EDIT: For anyone else who runs into this, I highly recommend switching to custom user model. It's not as scary to switch mid-project as the docs make it sound.
answers question: http://stackoverflow.com/q/50784250
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/88535862
has text: @MaartenBodewes -- That makes sense, and implies that the reason for separating the key as done here is to simplify key administration rather than improve security. It's still a good reason: no need to revise source when simply updating keys.
type: Comment
comment on: http://stackoverflow.com/a/50726241
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88709002
has text: I thought so as well, but somehow if I try this, I get an empty dict.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50842481

http://stackoverflow.com/comment/88596436
type: Comment
comment on: http://stackoverflow.com/q/50793063
score: 0
has text: No, I want to know , why my output has an extra 'u' such as (u'Rami', u'PERSON')
type: QuestionComment

http://stackoverflow.com/comment/88577042
score: 1
has text: I tried `re.findall(r" (.*?)<\\\\\/[p]>", data.decode('utf-8'))` and it's working well. This method is not recommendable for others because the closing tag is also changing every request like `<\\/p>` then `<\/p>` then back again to `<\\/p>`. I hope that bs4 maintainers will include this capability in the future.
type: AnswerComment
comment on: http://stackoverflow.com/a/50785026
type: Comment

http://stackoverflow.com/comment/88569229
has text: try printing `print(os.path.join("C:\ThisDirectoryDoesNotExists\","neitherDoesThisFile.txt"))` - works as well.... because the error is thrown when you try to access a file thats not there inside `os.rename(path_to_file_that_does_not_exist, newname)`
type: QuestionComment
comment on: http://stackoverflow.com/q/50781199
score: 0
type: Comment

http://stackoverflow.com/comment/88764946
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50841181
type: AnswerComment
has text: OK this is fast but for niso=12 this is still to slow and I get a memory error, so is there any other way? I tried to decrease the lenth of the expressions by inserting A = simplify(A) b = simplify(b) X = simplify(A.LUsolve(b))

ipython-parallel
type: Tag
tags question: http://stackoverflow.com/q/50759237
tag name: ipython-parallel

http://stackoverflow.com/q/50843139
has title: Can caffe take in a batch of inputs with different resolutions at once? If so how?
tagged with: caffe
tagged with: deep-learning
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50849844
tagged with: python
tagged with: c++
downvote count: 0
score: 1
type: Question
has body: I am thinking of building a larger network with more input layers which would consist of all the respective reshaped input resolutions from the batch. Please let me know if this is possible and if it is what would be the most efficient way? For example: 3x160x160 + 3x48x48 + 3x128x128 | | | Rest of the network | | | Outputs
tagged with: pycaffe

mne-python
type: Tag
tags question: http://stackoverflow.com/q/50814953
tag name: mne-python

http://stackoverflow.com/q/50769141
has title: Order one numpy array by another
has comment: http://stackoverflow.com/comment/88742007
upvote count: 5
linked to: http://stackoverflow.com/q/16992713
type: Question
tagged with: numpy
score: 5
linked to: http://stackoverflow.com/q/8251541
tagged with: arrays
downvote count: 0
tagged with: sorting
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50769263
has body: I have an array that determines an ordering of elements: order = [3, 1, 4, 2] And then I want to sort another, larger array (containing only those elements): a = np.array([4, 2, 1, 1, 4, 3, 1, 3]) such that the element(s) that come first in order come first in the results, etc. In straight Python, I would do this with a key function: sorted(a, key=order.index) [3, 3, 1, 1, 1, 4, 4, 2] How can I do this (efficiently) with numpy? Is there a similar notion of "key function" for numpy arrays?
has answer: http://stackoverflow.com/a/50770155
linked to: http://stackoverflow.com/q/41242159
has answer: http://stackoverflow.com/a/50769904
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50819977
answers question: http://stackoverflow.com/q/50819227
type: Answer
score: 0
has body: Try stripping the extra info. Ex: import time from datetime import datetime date = '2018-06-12T14:03:35.306662173Z' d = datetime.strptime(date[:26],"%Y-%m-%dT%H:%M:%S.%f") unixTime = time.mktime(d.timetuple()) print(unixTime) Output: 1528792415.0

django-channels
tags question: http://stackoverflow.com/q/50734957
tags question: http://stackoverflow.com/q/50841604
type: Tag
tags question: http://stackoverflow.com/q/50741194
tag name: django-channels
tags question: http://stackoverflow.com/q/50808651

http://stackoverflow.com/comment/88509784
type: QuestionComment
type: Comment
has text: I would suggest you flatten dictionary using some delimeter on keys ( dot for example ) than merge like you would merge 1d dictionary and than create nested dictionary from merged 1d dict
comment on: http://stackoverflow.com/q/50750971
score: 1

http://stackoverflow.com/comment/88717580
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50856376
type: Comment
has text: Does that mean that if I have more than one thread running on my application, if thread1 set the context variable `user_id` it will be only set for this thread, and not for the others?

http://stackoverflow.com/a/50819102
score: 0
has body: After some digging I found out lambda should return a pd.Series() like return pd.Series((low , high, int(IPAddress(low)) , int(IPAddress(high)))) and the assign would be chunk'low_ip' , 'high_ip' , 'low_ip_int', 'high_ip_int' = chunk.apply(lambda row: getAllIpFields(row['network']), axis=1) this way I joined all applies into one, saving some performance.
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50806010
accepted answer of: http://stackoverflow.com/q/50806010

http://stackoverflow.com/comment/88702900
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50850068
has text: What is the error that python produces?

http://stackoverflow.com/q/50750359
tagged with: bokeh
type: Question
answer count: 2
has title: Trouble displaying Bokeh toolbar
tagged with: flask
has answer: http://stackoverflow.com/a/50750977
score: 0
has body: I'm new to Bokeh and Flask python in general but i have managed to create a graph and then output it on my browser via flask. The only problem is that im not getting the "Bokeh tool bar" next to my graph. My code looks like this from flask import Flask, render_template, request import pandas as pd import csv from bokeh.plotting import figure from bokeh.io import show from bokeh.embed import components from bokeh.models import Range1d from bokeh.resources import CDN app = Flask(__name__) # Create the main plot def create_figure(): xvals = [] yvals = [] with open('test.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: xvalue = row[0] yvalue = row[1] xvals.append(xvalue) yvals.append(yvalue) p = figure(plot_width=400, plot_height=400, x_range=(0, 20)) p.y_range = Range1d(0, 15) p.circle(xvals, yvals, size=10) return p # Index page @app.route('/') def index(): plot = create_figure() script, div = components(plot) cdn_js = CDN.js_files[0] cdn_css = CDN.css_files[0] return render_template("index.html", script=script, div=div, cdn_js=cdn_js, cdn_css=cdn_css) # With debug=True, Flask server will auto-reload # when there are code changes if __name__ == '__main__': app.run(port=5000, debug=True) and my index.html code looks like this: First Am i missing something? When i output the graph to a output_file i get the toolbar. Any help would be appreciated.
has answer: http://stackoverflow.com/a/50974925
type: UnansweredQuestion
tagged with: python
tagged with: plot

http://stackoverflow.com/comment/88561314
comment on: http://stackoverflow.com/q/50776671
score: 0
type: Comment
type: QuestionComment
has text: In template matching I gave this type of images as templates and could identify only few objects ( two or three.) I want to identify the objects from around 100 objects spread cross an image.

http://stackoverflow.com/comment/88466201
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50727556
has text: Is this what you are looking for? https://blog.arkency.com/2016/02/private-classes-in-ruby/ `private_constant` would allow you to make a class private inside a module. e.g. `module Foo; class Bar; end; private_constant :Bar;end` would cause `Foo::Bar` to raise a `NameError` if accessed from outside of the context of `Foo`
score: 0

http://stackoverflow.com/comment/88643614
comment on: http://stackoverflow.com/a/50819173
type: AnswerComment
type: Comment
has text: I get this: `Requirement already up-to-date: pip in /media/rmn/data/projects/anaconda3/envs/monily/lib/python3.6/site-packages (10.0.1)`
score: 0

http://stackoverflow.com/comment/88456283
has text: @ahbon: Okay, but then why does your example include zero underscores? If that's something you want help with why don't you show it in your data? And what meaning does NUMBER DASH NUMBER have? How are you making calculations from it? You want help but you are keeping your assumptions in your head and out of your question.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50723687

http://stackoverflow.com/comment/88541377
type: Comment
has text: the original data from the database was extremely 'dirty', after cleaning the data everything worked just fine! Thank you for your time.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50725532

http://stackoverflow.com/q/50732381
tagged with: spyder
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50732517
has title: looping, timer and threading in python
has answer: http://stackoverflow.com/a/50734085
tagged with: anaconda
has body: how to I checking this script will be running every 2 minutes, where file 'odata_peng5.txt' still renewable every 2 minutes? import pandas as pd import threading def printit(): threading.Timer(120.0, printit).start() df = pd.read_csv('data_peng5.txt', header=None) a=100 b=1/a df[15] = df[3]+b+50 df.to_csv('odata_peng5.txt', header=None, index=False) print "Hello, World!" printit() Output: =============== RESTART: C:/Users/xxx/timer3.py =============== &gt;&gt;&gt; Even though, I'am testing with mode print mode still running: #import pandas as pd import threading def printit(): threading.Timer(120.0, printit).start() print "Hello, World!" printit() Output: =============== RESTART: C:/Users/xxx/timer3.py =============== Hello, World! &gt;&gt;&gt; Hello, World! Hello, World!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88473322
tagged with: python-2.7
score: 2

raspberry-pi
tags question: http://stackoverflow.com/q/50818491
tags question: http://stackoverflow.com/q/50801120
tags question: http://stackoverflow.com/q/50722690
type: Tag
tags question: http://stackoverflow.com/q/50732289
tags question: http://stackoverflow.com/q/50781836
tags question: http://stackoverflow.com/q/50738670
tags question: http://stackoverflow.com/q/50749840
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/50799898
tags question: http://stackoverflow.com/q/50799143
tags question: http://stackoverflow.com/q/50764622
tags question: http://stackoverflow.com/q/50737026
tags question: http://stackoverflow.com/q/50734252
tags question: http://stackoverflow.com/q/50760318
tags question: http://stackoverflow.com/q/50770703
tags question: http://stackoverflow.com/q/50813430
tags question: http://stackoverflow.com/q/50781534
tags question: http://stackoverflow.com/q/50705195
tags question: http://stackoverflow.com/q/50786055
tags question: http://stackoverflow.com/q/50771671
tags question: http://stackoverflow.com/q/50706795
tags question: http://stackoverflow.com/q/50791252
tags question: http://stackoverflow.com/q/50792412

http://stackoverflow.com/comment/88442354
type: QuestionComment
has text: Sorry, I messed that up. It should be the inverse of the counts. I fixed that.
score: 0
comment on: http://stackoverflow.com/q/50715065
type: Comment

http://stackoverflow.com/comment/88693466
comment on: http://stackoverflow.com/q/50839952
score: 0
type: QuestionComment
type: Comment
has text: Yes. The transactions intent is entirely handled by the platform. Anything custom you want to do will need to be done ahead of this intent.

http://stackoverflow.com/a/50850172
accepted answer of: http://stackoverflow.com/q/50850068
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50850068
has body: Shop catalog is defined as: shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 } However, you are trying to access the key by number. Such as shopCatalog[2] which doesn't exist as a valid key. A valid key would be shopCatalog['2. Gucci Belt'] Instead, try a list of tuples. A list is better because the order is guaranteed. In a dict, even though you numbered your items, it may print out of order. shopCatalog = [ ('MCM Backpack', 790), ('Gucci Belt' : 450) , ...] If you want the first item, you can just access it by the index. If you want them numbered, again, just use the index (although for both, keep in mind it is zero-indexed so you may have to add on to print your numbering and subtract one to get the right item. Also, there is a flaw in your logic here: shopChoice == 1 or 2 or 3 or 4 or 5 or 6: While people talk like that, coding doesn't work like that. Instead, you'd have to do: shopChoice ==1 or shopChoice ==2 and so on. But skip all of that and just say: elif 1 &lt;= shopChoice &lt;= 6:
has comment: http://stackoverflow.com/comment/88703279
score: 0

http://stackoverflow.com/comment/88443651
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50715975
has text: But the error was still the same? And it had `execute` and `read` permissions ?
type: AnswerComment

http://stackoverflow.com/comment/88449485
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50720275
has text: It is just decided to use increments of 1 in this use case. This function helps to visualize P-sum curve of repeated draws vs. win/loss(?) probability. I suppose. I have not reviewed the whole code.
score: 0

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/50706992

http://stackoverflow.com/q/50703942
has title: Creating a neural network that is capable of forecasting electricity usage on a range of scales
has comment: http://stackoverflow.com/comment/88417438
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88418511
tagged with: tensorflow
type: Question
tagged with: time-series
has comment: http://stackoverflow.com/comment/88418061
tagged with: keras
has body: I have a number of usage patterns for different kinds of customers. Large scale factories and small scale customers or even single devices such as AC units. I am trying to create a model with keras that can predict any of these inputs, given proper prior scaling of the input. When I run a model on each customer individually, the predictions are sort of good. Once I train that model on a number of inputs however, the results degrade greatly. Is it possible to train a network that can handle a range of inputs and recognize them as different classes / types. How would such a model have to look like? This is my current one: model_unif = Sequential() # input layer input_shape = (cfg.DEMAND_ONE_WEEK,) model_unif.add(Dense(168, input_shape=input_shape, activation='linear')) model_unif.add(BatchNormalization()) #applying batch normalization now model_unif.add(Dense(100, activation='linear')) model_unif.add(Dense(100, activation='linear')) model_unif.add(Dense(100, activation='linear')) model_unif.add(Dense(50, activation='linear')) model_unif.add(Dense(50, activation='linear')) model_unif.add(Dense(24)) model_unif.add(Activation('linear')) model_unif.compile(loss='mse', optimizer='rmsprop')
score: 0

http://stackoverflow.com/comment/88448464
comment on: http://stackoverflow.com/a/50708286
score: 0
type: AnswerComment
has text: Depending on how exactly it's executed, a database search is probably not a good place for a progress bar. To update the progress bar you need to have incremental progress that you can monitor. I'm not sure how you would get incremental updates from a database search. Probably the best bet would be set the label to indicate the search has started before calling `data = search_DB()` and change the label to indicate the search is complete by connecting to the finished signal. The progress bar would be more useful if the data processing stage, after the data is retrieved, took some time.
type: Comment

http://stackoverflow.com/q/50699746
tagged with: join
type: Question
answer count: 2
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50700088
has title: Join multiple CSV files by using python pandas
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I am trying to create a CSV file from multiple csv files by using python pandas. accreditation.csv :- "pid","accreditation_body","score" "25799","TAAC","4.5" "25796","TAAC","5.6" "25798","DAAC","5.7" ref_university :- "id","pid","survery_year","end_year" "1","25799","2018","2018" "2","25797","2016","2018" I want to create a new table by reading the instruction from table_structure.csv. I want to join two tables and rewrite the accreditation.csv . REFERENCES ref_university(id, survey_year) is connecting with ref_university.csv and inserting id and survery_year columns value by matching the pid column value. table_structure.csv :- table_name,attribute_name,attribute_type,Description ,,, accreditation,accreditation_body,varchar, ,grading,varchar, ,pid,int4, "REFERENCES ref_university(id, survey_year)" ,score,float8, Modified CSV file should look like, New accreditation.csv :- "accreditation_body","grading","pid","id","survery_year","score" "TAAC","","25799","1","2018","2018","4.5" "TAAC","","25797","2","2016","2018","5.6" "DAAC","","25798","","","","5.7" I can read the csv in panda df = pd.read_csv("accreditation.csv") But, what is the recommended way to read the REFERENCES instruction and pick the columns value. If there is no value then column should be blank. We can not hardcore pid in panda function. We have to read table_structure.csv and match if there is a Reference then call the mentioned columns. It should not be merged, just the specific columns should be added.
has answer: http://stackoverflow.com/a/73675245

http://stackoverflow.com/comment/88623532
comment on: http://stackoverflow.com/q/50793063
score: 0
type: Comment
type: QuestionComment
has text: Is this a problem, to have unicode format in output?

http://stackoverflow.com/comment/88577698
has text: Java doesn't have "magic" methods that map to language functionality - it's a language choice. For a reason, you'd need to need to ask James Gosling - my guess is that because Java was designed to be the epitome of a simple lanuage it was decided that adding such magic would detract from this goal.
comment on: http://stackoverflow.com/q/50785573
type: Comment
type: QuestionComment
score: 1

mining
type: Tag
tags question: http://stackoverflow.com/q/50825598
tag name: mining

http://stackoverflow.com/a/50823217
upvote count: 3
has comment: http://stackoverflow.com/comment/88652081
has comment: http://stackoverflow.com/comment/88652182
downvote count: 0
has comment: http://stackoverflow.com/comment/88652242
answers question: http://stackoverflow.com/q/50823043
has comment: http://stackoverflow.com/comment/88669571
type: Answer
score: 3
has body: You can define a conversion function and use this with min: lst = [2., None, 3., 1., None, 2., None, 5.] def converter(x): return x[1] if x[1] is not None else float('inf') res = min(enumerate(lst), key=converter)[::-1] (1.0, 3) If you're happy using a 3rd party library, the equivalent in NumPy: arr = np.array(lst).astype(float) arr[np.isnan(arr)] = np.inf res = arr.min(), arr.argmin() Or, more efficiently, you can use np.nanargmin: arg = np.nanargmin(arr) minval = arr[arg] res = minval, arg

http://stackoverflow.com/comment/88466867
score: 1
type: Comment
type: QuestionComment
has text: You use `local` mode so, "master" is the only node you have. What else do you expect here? If you have distributed cluster, you should point connect to it (not use `local[*]`). Also what is `renameColumns` and `validate` suppose to do?
comment on: http://stackoverflow.com/q/50729345

http://stackoverflow.com/comment/88664851
type: Comment
has text: Oh this is embarrassing...It did work, however after about 47 comments I received a prompt stating that I have to wait for a variable amount of time(time wasn't specified :p) before I can post another comment.
comment on: http://stackoverflow.com/a/50822672
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88852832
comment on: http://stackoverflow.com/a/50925250
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173392/discussion-between-jencko-and-willem-van-onsem).
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50844957
type: Answer
has comment: http://stackoverflow.com/comment/88695240
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50843953
has comment: http://stackoverflow.com/comment/88695264
has comment: http://stackoverflow.com/comment/88694886
has comment: http://stackoverflow.com/comment/88694669
answers question: http://stackoverflow.com/q/50843953
score: 4
has comment: http://stackoverflow.com/comment/88694311
has comment: http://stackoverflow.com/comment/88694867
type: AcceptedAnswer
has body: There is a problem with your key. It is too much short. Written some code for Fernet encryption/decryption (it is very basic, not stream-based), tested with a test vector found at a javascript implementation of Fernet. The specification of the Fernet algorithm can be found here. Note that you can't use directly Convert.FromBase64String, because the format used by Fernet is Base64 url-safe. I've put a small method to convert from it. public static class SimpleFernet { // Fernet: from https://github.com/fernet/spec/blob/master/Spec.md // return value is base64 url encoded // trimEnd is to force trimming of return value public static string EncryptFernet(byte[] key, byte[] data, DateTime? timestamp = null, byte[] iv = null, bool trimEnd = false) { // Fernet: from https://github.com/fernet/spec/blob/master/Spec.md if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.Length != 32) { throw new ArgumentException(nameof(key)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (iv != null &amp;&amp; iv.Length != 16) { throw new ArgumentException(nameof(iv)); } if (timestamp == null) { timestamp = DateTime.UtcNow; } byte[] result = new byte[57 + ((data.Length + 16) / 16 * 16)]; result[0] = 0x80; { // BigEndian to LittleEndian long timestamp2 = new DateTimeOffset(timestamp.Value).ToUnixTimeSeconds(); timestamp2 = IPAddress.NetworkToHostOrder(timestamp2); byte[] timestamp3 = BitConverter.GetBytes(timestamp2); Buffer.BlockCopy(timestamp3, 0, result, 1, timestamp3.Length); } using (var aes = new AesManaged()) { aes.Mode = CipherMode.CBC; byte[] encryptionKey = new byte[16]; Buffer.BlockCopy(key, 16, encryptionKey, 0, 16); aes.Key = encryptionKey; if (iv != null) { aes.IV = iv; } else { aes.GenerateIV(); } Buffer.BlockCopy(aes.IV, 0, result, 9, 16); aes.Padding = PaddingMode.PKCS7; using (var encryptor = aes.CreateEncryptor()) { byte[] encrypted = encryptor.TransformFinalBlock(data, 0, data.Length); Buffer.BlockCopy(encrypted, 0, resul…
has comment: http://stackoverflow.com/comment/88694775
has comment: http://stackoverflow.com/comment/88695130

hover
tags question: http://stackoverflow.com/q/50715776
type: Tag
tags question: http://stackoverflow.com/q/50835979
tag name: hover

http://stackoverflow.com/comment/88634285
has text: @MartijnPieters glad that you mentioned that it is not recommended by the community. Will then take a look at Think Python then.
comment on: http://stackoverflow.com/q/50805638
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88416698
score: 0
type: AnswerComment
has text: Can I compare times in datetime64 format as I would do with datetime?
type: Comment
comment on: http://stackoverflow.com/a/50703619

http://stackoverflow.com/a/52044825
answers question: http://stackoverflow.com/q/50744522
score: 0
type: Answer
has body: Initially when you create repositry do the following: Create a readme file and license After successfully creating a readme.md file you'll see a button 'upload files'. You can either browse to upload or drag the entire folder from your system. After uploading files click 'commit' button. You are done!

http://stackoverflow.com/a/50775234
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88557683
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88557404
accepted answer of: http://stackoverflow.com/q/50772342
has body: Resolving import issues You can't simply invoke import esptool because esptool.py is an executable script, thus not meant to be imported like a plain module. However, there are workarounds for importing code from executable scripts; here are two I know of: extending sys.path You can extend the sys.path to include the bindir containing the esptool.py script. Simple check from command line: $ PYTHONPATH=$(which esptool.py)/.. python -c "import esptool; esptool.main()" should print you the usage help text. Extending sys.path in code: import os import sys try: from shutil import which except ImportError: from distutils.spawn import find_executable as which bindir = os.path.dirname(which('esptool.py')) sys.path.append(bindir) # after this line, esptool becomes importable import esptool if __name__ == '__main__': esptool.main() using import machinery You can avoid extending sys.path by using the mechanisms of importing Python code from arbitrary files. I like this solution more than fiddling with sys.path, but unfortunately, it is not portable between Python 2 and 3. Python 3.5+ import importlib.machinery import importlib.util from shutil import which if __name__ == '__main__': loader = importlib.machinery.SourceFileLoader('esptool', which('esptool.py')) spec = importlib.util.spec_from_loader(loader.name, loader) esptool = importlib.util.module_from_spec(spec) loader.exec_module(esptool) # after this line, esptool is imported esptool.main() Python 2.7 import imp from distutils.spawn import find_executable as which if __name__ == '__main__': esptool = imp.load_source('esptool', which('esptool.py')) esptool.main() Passing command line arguments The command line arguments are stored in sys.argv list, so you will have to temporarily overwrite it in order to pass the arguments to the main function: # assuming esptool is imported import sys if __name__ == '__main__': # save the current arguments argv_original = sys.argv[:] # overwrite arguments to be passed to esptool argparser…
answers question: http://stackoverflow.com/q/50772342

http://stackoverflow.com/comment/88466879
score: 1
comment on: http://stackoverflow.com/a/50718410
has text: If your code currently works, and you are looking to improve it, you might find better luck at [codereview.se]. Remember to read [their requirements](https://codereview.stackexchange.com/help/on-topic) as they are a bit more strict than this site.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88689098
comment on: http://stackoverflow.com/a/50842689
type: Comment
score: 0
type: AnswerComment
has text: Yes, the same process will work. The only requirement is that the type of you series is the same as your dictionary key type. So strings + strings, or numeric + numeric will work.

selenium
tags question: http://stackoverflow.com/q/50766586
tags question: http://stackoverflow.com/q/50817812
tags question: http://stackoverflow.com/q/50709755
tags question: http://stackoverflow.com/q/50822230
tags question: http://stackoverflow.com/q/50716593
tags question: http://stackoverflow.com/q/50806124
tags question: http://stackoverflow.com/q/50778504
tags question: http://stackoverflow.com/q/50800769
tags question: http://stackoverflow.com/q/50848352
tags question: http://stackoverflow.com/q/50845079
tags question: http://stackoverflow.com/q/50755766
tags question: http://stackoverflow.com/q/50729431
tags question: http://stackoverflow.com/q/50826057
tags question: http://stackoverflow.com/q/50729024
tags question: http://stackoverflow.com/q/50727573
tags question: http://stackoverflow.com/q/50784498
tags question: http://stackoverflow.com/q/50830140
tags question: http://stackoverflow.com/q/50710312
tags question: http://stackoverflow.com/q/50792181
tags question: http://stackoverflow.com/q/50849686
tags question: http://stackoverflow.com/q/50715435
tags question: http://stackoverflow.com/q/50841439
tags question: http://stackoverflow.com/q/50733098
tags question: http://stackoverflow.com/q/50773103
tags question: http://stackoverflow.com/q/50743117
tags question: http://stackoverflow.com/q/50753754
tags question: http://stackoverflow.com/q/50741980
tags question: http://stackoverflow.com/q/50755719
tags question: http://stackoverflow.com/q/50744911
tags question: http://stackoverflow.com/q/50702522
tags question: http://stackoverflow.com/q/50789890
tags question: http://stackoverflow.com/q/50829342
tags question: http://stackoverflow.com/q/50799046
tags question: http://stackoverflow.com/q/50729809
tags question: http://stackoverflow.com/q/50758984
tags question: http://stackoverflow.com/q/50729310
tags question: http://stackoverflow.com/q/50837611
tags question: http://stackoverflow.com/q/50843358
tag name: selenium
tags question: http://stackoverflow.com/q/50812011
tags question: http://stackoverflow.com/q/50849057
tags question: http://stackoverflow.com/q/50782124
tags question: http://stackoverflow.com/q/50767308
tags question: http://stackoverflow.com/q/50817880
tags question: http://stackoverflow.com/q/50733262
tags question: http://stackoverflow.com/q/50841915
tags question: http://stackoverflow.com/q/50698948
tags question: http://stackoverflow.com/q/50764879
tags question: http://stackoverflow.com/q/50805949
tags question: http://stackoverflow.com/q/50843847
tags question: http://stackoverflow.com/q/50814291
tags question: http://stackoverflow.com/q/50705881
tags question: http://stackoverflow.com/q/50804438
tags question: http://stackoverflow.com/q/50853027
tags question: http://stackoverflow.com/q/50794314
tags question: http://stackoverflow.com/q/50704849
tags question: http://stackoverflow.com/q/50794514
tags question: http://stackoverflow.com/q/50815894
tags question: http://stackoverflow.com/q/50769439
tags question: http://stackoverflow.com/q/50699057
tags question: http://stackoverflow.com/q/50776071
tags question: http://stackoverflow.com/q/50805089
tags question: http://stackoverflow.com/q/50788131
tags question: http://stackoverflow.com/q/50717900
tags question: http://stackoverflow.com/q/50744892
tags question: http://stackoverflow.com/q/50708063
tags question: http://stackoverflow.com/q/50728690
tags question: http://stackoverflow.com/q/50737246
tags question: http://stackoverflow.com/q/50824810
tags question: http://stackoverflow.com/q/50777329
tags question: http://stackoverflow.com/q/50761757
tags question: http://stackoverflow.com/q/50711167
tags question: http://stackoverflow.com/q/50750225
tags question: http://stackoverflow.com/q/50705928
tags question: http://stackoverflow.com/q/50714354
tags question: http://stackoverflow.com/q/50818782
tags question: http://stackoverflow.com/q/50789537
tags question: http://stackoverflow.com/q/50769931
tags question: http://stackoverflow.com/q/50752182
tags question: http://stackoverflow.com/q/50812070

http://stackoverflow.com/a/50758171
answers question: http://stackoverflow.com/q/50757873
has comment: http://stackoverflow.com/comment/88594344
score: 0
type: Answer
has body: In both cases, the error message says it cannot find the driver (ODBC) or the provider (ADO). In ODBC, are you sure that this driver is installed? You can have a list of available drivers using pyodbc.drivers() for example, in my case, I read MS Access data using this driver Microsoft Access Driver (*.mdb)

http://stackoverflow.com/comment/88913376
type: Comment
has text: I reverted to SDK version 200.0.0 and the issue is fixed.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50721890

http://stackoverflow.com/q/50819224
has comment: http://stackoverflow.com/comment/88643754
possible better answer: http://stackoverflow.com/a/50819387
has title: Add string to dictionary in list comprehension
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/14071038
linked to: http://stackoverflow.com/q/38987
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50819387
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88644052
tagged with: list-comprehension
has body: Say I have a list of filenames files containing data in json format. To receive the data in a list with an entry for each file, I use a list comprehension: &gt;&gt;&gt; import json &gt;&gt;&gt; data = [json.load(open(file)) for file in files] Now I was wondering, if there is a way to append the file name file to the json data, as if it looked like this: { 'Some': ['data', 'that', 'has', 'already', 'been', 'there'], 'Filename': 'filename' } For my case, json.load() returns a dict, so I've tried something similar to this question. This didn't work out for me, because files contains strings and not dictionaries. Edit For clarification, if dict.update() didn't return None, this would probably work: &gt;&gt;&gt; data = [dict([('filename',file)]).update(json.load(open(file))) for file in files]
answer count: 2
has answer: http://stackoverflow.com/a/50819378
accepted answer: http://stackoverflow.com/a/50819378
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50753925
score: 0
has answer: http://stackoverflow.com/a/50754214
has answer: http://stackoverflow.com/a/50753969
downvote count: 1
has comment: http://stackoverflow.com/comment/88516038
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88515712
has title: Python regex group not returning full group
linked to: http://stackoverflow.com/q/10678916
has comment: http://stackoverflow.com/comment/88515787
type: Question
has comment: http://stackoverflow.com/comment/88515840
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50754214
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88516028
has comment: http://stackoverflow.com/comment/88515892
accepted answer: http://stackoverflow.com/a/50753969
duplicate of: http://stackoverflow.com/q/10678916
has body: regexlord = re.compile(r'([a-z])+(0)+(\d)+') yomyomnumber = regexlord.search('spam003') print (yomyomnumber.group(1)) print (yomyomnumber.group(2)) print (yomyomnumber.group(3)) So I've got a string in the form of spam003 and I want to be able to change the number at the end (the 3). Thus, I want to use regex and call the specific groups. However, when I call the groups, group 1 prints only (m), group 2 prints only (0), and group 3 only prints (3). Because this is greedy matching, I'm expecting that group 1 prints (spam), group 2 prints (00), and group 3 prints (3). I'm stumped on why this isn't happening.
favorite count: 0

http://stackoverflow.com/q/50716214
has answer: http://stackoverflow.com/a/50717280
tagged with: python
favorite count: 0
upvote count: 1
answer count: 1
tagged with: opencv
has title: Python OpenCV - apply colored mask to image
has body: I got the following things: an Image read with OpenCV (numpy array) a binary mask of the same size as the image a color string like 'red','blue', etc Q: how do i color the mask before i add it to the image? explicitly: how do i add color channels to a binary mask given a color string I know how to add the mask (for example with cv2.addWeighted(mask,alpha,image,1-alpha,0,image) ) , but i dont know how to convert the binary mask to color space with a simple color 'string' as input. I know this works in PIL with rgb = PIL.ImageColor.getrgb(color), but i dont know how to do this with OpenCV! EDIT: i managed to get the colors in channel tuples (0,0,0) and currently my workaround is: mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB) mask[np.where((mask == [1,1,1]).all(axis = 2))] = color cv2.addWeighted(mask,alpha,image,1-alpha,0,image) but the problem is, now the image is greyscale with a colored map... So the first line needs to be exchanged
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question

http://stackoverflow.com/q/50718122
has comment: http://stackoverflow.com/comment/88446398
has title: pandas DataFrame style like Excel Graded color scale conditional formatting
downvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/38931566
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88444989
has comment: http://stackoverflow.com/comment/88446262
tagged with: python
score: 2
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/38931566
type: Question
has comment: http://stackoverflow.com/comment/94601429
tagged with: pandas
has body: I would like to render a DataFrame as in Excel when using the Graded color formatting: I'm not able to get similar result with Pandas (v0.23.0) style: import pandas as pd import numpy as np shape = (3,3) np.random.seed(0) df=pd.DataFrame(np.random.uniform(0.,144, size=9).reshape(shape)) df.iloc[0,0] = np.nan df.iloc[1,1] = 144 df.iloc[0,2] = 0 df[3] = 144 df.style.background_gradient(cmap='RdYlGn').highlight_null('white') This is what I get: Any idea? Thanks, Greg EDIT This solution worked: import matplotlib.pyplot as plt from matplotlib import colors def background_gradient(s, m, M, cmap='PuBu', low=0, high=0): rng = M - m norm = colors.Normalize(m - (rng * low), M + (rng * high)) normed = norm(s.values) c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)] return ['background-color: %s' % color for color in c] df.style.apply(background_gradient, cmap='RdYlGn', m=df.min().min(), M=144).highlight_null('white')

http://stackoverflow.com/q/50709371
has body: I'm trying to use ast.literal_eval on a string, but am getting a memory error. Is the list too nested or what is the problem? Is there an alternative? MemoryError Traceback (most recent call last) &lt;ipython-input-138-3ea9110f7dc3&gt; in &lt;module&gt;() 1 s = "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[['Xenophrys_bairdii'],'Vulpanser_spaldingi'],'Vipera_yeltoniensis'],'Vipera_minutus'],'Vanellus_vegans'],'Vanellus_bedriagai'],'Ursus_gratiosa'],'Uroplatus_flavomaculatus'],'Trionyx_leporosum'],'Tringa_aspera'],'Trachemys_sirtalis'],'Terpsihone_varius'],'Spermophilus_hassanica'],'Siniperca_decor'],'Scolopendra_marcianus'],'Rufibrenta_montela'],'Riparia_clinatus'],'Rhinolophus_tuberculosus'],'Rhacodactylus_citrsola'],'Remiz_niloticus'],'Pterinochilus_physalus'],'Procellaria_truncatus'],'Procellaria_lutris'],'Poephagus_indica'],'Platemys_albopillosum'],'Pica_totanus'],'Pica_mexicana'],'Phrynomerus_pelagicus'],'Philothamnus_tuberculosus'],'Petrocincla_acuta'],'Pelomedusa_rusticolus'],'Pagophila_metallica'],'Pachytriton_sibiricus'],'Otis_moschata'],'Otis_franckii'],'Otis_emarginatus'],'Opheodrys_clarus'],'Mylopharyngodon_diffidens'],'Mergus_carinata'],'Meles_carbonaria'],'Mabuya_carnivorus'],'Lystrophis_siebenrocki'],'Lyrurus_tinctorius'],'Lycodon_dendrophila'],'Lutra_plathyrhychos'],'Leptopelis_plumipes'],'Leptopelis_licin'],'Leiurus_grossmani'],'Lasiodora_hipposideros'],'Larus_pulchripes'],'Kinosternon_guineti'],'Kassina_canorus'],'Hysterocrates_chukar'],'Hydrochelidon_euptilura'],'Hemitheconyx_pulchripes'],'Haplopelma_arcticus'],'Hadrurus_dominus'],'Gypaetus_schneideri'],'Glareola_leucophyllata'],'Gerrhosaurus_ruficollis'],'Geochelone_filipjevi'],'Gallinago_pallasii'],'Eutamias_multifasciata'],'Eulabeia_tinnunculus'],'Eudrornias_penelope'],'Eudramias_tadorna'],'Eschrichtius_pulchra'],'Eremophila_similis'],'Equus_fluviatilis'],'Epicrates_carinatus'],'Emydura_avosetta'],'Emberiza_japonica'],'Dyscophus_rubicola'],'Dend…
tagged with: out-of-memory
accepted answer: http://stackoverflow.com/a/50710268
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50710268
has comment: http://stackoverflow.com/comment/88441742
has title: ast.literal_eval memory error on nested list
score: 0
has comment: http://stackoverflow.com/comment/88427940
answer count: 1

http://stackoverflow.com/comment/88611119
type: Comment
comment on: http://stackoverflow.com/q/50802158
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172907/discussion-between-arthur-and-yash).
score: 0
type: QuestionComment

http://stackoverflow.com/a/50825589
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50825520
type: Answer
has body: np.array is a function, so you cannot subscribe it using []. In the second case you are inputting your list of dictionaries wrong, you should make a list of them then pass it to the first argument. Right now you are passing a dictionary as arguments of the function. So this should work: np.array([{"russia" : 0}, {"saudi_arabia" : 0}, {"egypt" : 0}, {"uruguay" : 0}])
upvote count: 1

http://stackoverflow.com/q/50849207
downvote count: 1
accepted answer: http://stackoverflow.com/a/50849387
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/88701677
type: Question
upvote count: 0
has title: How to skip first few rows of text while importing csv with pandas?
has answer: http://stackoverflow.com/a/50849387
has comment: http://stackoverflow.com/comment/88702267
tagged with: data-analysis
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
favorite count: 0
has body: We receive a csv file from our vendor everyday. However, the format is like this: #Receiver #DateTime #Address Col1 Col2 Col3 1 A 3 10% 2 B 3 20% 3 C 2 10% I need to use pandas to read the table which starts at row 5 and column 3. How could I skip the first few rows? Thanks.
tagged with: data-cleaning
tagged with: python

http://stackoverflow.com/a/50814424
upvote count: 1
has body: At least this might be an attempt to discuss about, as @abarnert said. re.sub('(?&lt;![$.0-9])\d*[.]*\d+(?![%.0-9])', 'x', s) It's about searching for bunches of numbers which can have periods in the middle or the beginning (\d*[.]*\d+) surrounded by negative lookarounds with regards to digits, periods and dollars before / percentages after ((?&lt;![$.0-9])and (?![%.0-9])). Output: "Hi there my name is Jon Doe, I haven't been here for x years, my birthday is x/x/x, I received 10% off of my $20.50 purchase."
score: 1
answers question: http://stackoverflow.com/q/50806403
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50806403
type: Answer

http://stackoverflow.com/comment/88577709
type: QuestionComment
comment on: http://stackoverflow.com/q/50782248
score: 1
has text: and y = 23.244252 for this row
type: Comment

http://stackoverflow.com/comment/88674586
type: AnswerComment
comment on: http://stackoverflow.com/a/50825599
type: Comment
has text: they are valid, just ruining my visualization. I have excluded them an re standardized my values, which produced a few more valid outliers. Tedious process but very interesting. thank you
score: 0

http://stackoverflow.com/comment/88420682
comment on: http://stackoverflow.com/a/50704232
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot for this solution, This works perfectly for me! @dano

http://stackoverflow.com/comment/88679153
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50834357
score: 0
has text: Apologies if I am being dim - when you say "file" do you mean my text file? If so, that is the text file. Starting from "switch#" downwards that is the text file, that is all that is in it. It's an output from running a "show inventory" command on a Cisco switch. If you mean code, sure thing.

http://stackoverflow.com/comment/88677544
comment on: http://stackoverflow.com/q/50836922
score: 0
has text: Well this is really not the way how to add a `GET` parameter.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50720589
score: 0
has comment: http://stackoverflow.com/comment/88458729
has comment: http://stackoverflow.com/comment/88456152
answer count: 1
tagged with: nlp
has comment: http://stackoverflow.com/comment/88449686
tagged with: spacy
has body: I have 90 documents with around 40 pages each (raw text). I want to tokenize them with spacy. nlp = spacy.load('de') tokenized_list = [] for document in doc_collection: temp_doc = nlp(document) tokenized_list.append(temp_doc) It's working for a low number of documents, but if i want to tokenize all, then it gives a "MemoryError". "...site-packages\numpy\core\shape_base.py", line 234, in vstack return _nx.concatenate([atleast_2d(_m) for _m in tup], 0) MemoryError" Does somebody know how I can fix it? Update: I can execute it over and over again without changing the documents and it get stuck sometimes in this document sometimes in that - really weird... Does somebody know a similar problem?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88449750
has answer: http://stackoverflow.com/a/50737138
accepted answer: http://stackoverflow.com/a/50737138
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88449896
has comment: http://stackoverflow.com/comment/88449739
has title: How I can iterate through a bunch of documents and execute spacy's nlp for each of them, without getting a memory error?

http://stackoverflow.com/q/50744453
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50745263
has title: Default loss function contrib.learn DNNRegressor
has body: super quick question. What is the default loss function in Tensorflow's contrib.learn? I looked at the documentation and could not find anything. Just to clarify, I am asking if it is absolute difference, MAE, MSE, RMSE or any other. Thank you!
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46538710
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50745263

http://stackoverflow.com/q/50818782
has title: "Method has not yet been implemented" error when using ActionChains for Appium iOS automation
score: 0
has comment: http://stackoverflow.com/comment/88699912
has answer: http://stackoverflow.com/a/75071868
type: UnansweredQuestion
has body: I currently have scripts for web browser automation for my web app, and I am trying to implement those scripts for mobile automation. Everything seems to work, but my code will exit where I implemented ‘ActionChains’ and I receive the error that “Method has not yet been implemented.” Is ActionChains not compatible with Appium? Also, I tried using TouchAction in place of Action Chains, but it gives me errors such as AttributeError: ‘int’ object has no attribute ‘id’ ‘Str’ object has no attribute ‘id’ I saw somewhere that TouchAction only works in a native context. I am trying to test my web app on an iPad, so does TouchAction not support web context?
tagged with: python
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/88644312
tagged with: automation
tagged with: appium
tagged with: mobile
answer count: 1

http://stackoverflow.com/a/50775271
has comment: http://stackoverflow.com/comment/88557678
has comment: http://stackoverflow.com/comment/88557494
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50774939
has comment: http://stackoverflow.com/comment/88557616
answers question: http://stackoverflow.com/q/50774939
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88557659
has comment: http://stackoverflow.com/comment/88559260
has comment: http://stackoverflow.com/comment/88557633
upvote count: 2
has body: The principle here is to create a list/array with the values appearing a set number of times, shuffling that list/array and then reshaping it. The starting point to generate the data: a = [1 for x in range(20)] b = [2 for x in range(30)] c = [3 for x in range(50)] full_array = a + b + c A pure python approach might use this slightly adapted: import random def chunks(l, n): n = max(1, n) return [l[i:i+n] for i in range(0, len(l), n)] random.shuffle(full_array) matrix = chunks(full_array, 10) If you use numpy then things become easier: import numpy as np full_array = np.array(full_array) np.random.shuffle(full_array) matrix = full_array.reshape(10, 10)
type: Answer
has comment: http://stackoverflow.com/comment/88558453
score: 1
has comment: http://stackoverflow.com/comment/88557685

http://stackoverflow.com/q/50709759
answer count: 5
has answer: http://stackoverflow.com/a/50709980
tagged with: python
has answer: http://stackoverflow.com/a/50709881
tagged with: list
upvote count: 1
has answer: http://stackoverflow.com/a/50709920
has answer: http://stackoverflow.com/a/50709889
type: UnansweredQuestion
has body: I'm kinda new to Programming and Python and I'm self learning before going to uni so please be gentle, I'm a newbie. I hope my english won't have too many grammatical errors. Basically I had this exercise in a book I'm currently reading to take a list of tuples as a function parameter, then take every item in the each tuple and put it to 2nd power and sum the items up. My code looks like this and works good if my function call includes the same amount of arguments as the function for loop requires: def summary(xs): for x,y,z in xs: print( x*x + y*y + z*z) xs =[(2,3,4), (2,-3,4), (1,2,3)] summary(xs) However, If I use a list with less tuples than the function definition, I get an error: ValueError : not enough values to unpack(expected 3, got 0): xs =[(2,3,4), (), (1,2,3)] I would like to know how to make a function that would accept a tuple I shown before () - with no tuples, and the function would return 0. I have been trying multiple ways how to solve this for 2 days already and googling as well, but it occurs to me I'm either missing something or I'm not aware of a function i could use. Thank you all for the help.
has comment: http://stackoverflow.com/comment/88428724
has comment: http://stackoverflow.com/comment/88428739
has title: Tuple in list has less items than the function needs Python 3
has answer: http://stackoverflow.com/a/50710842
tagged with: function
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: tuples
type: Question

http://stackoverflow.com/q/50831859
tagged with: observers
has title: Openpyxl observing the max_row of a sheet?
has body: Is it possible to observe the max row of a sheet for changes? I have some functions I'd like to run everytime that value is updated (they would be the observers). Does openpyxl support that?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51102743
type: Question
tagged with: openpyxl
tagged with: python
answer count: 1
score: 0
tagged with: observer-pattern

http://stackoverflow.com/comment/88453686
score: 0
type: Comment
has text: I have an error with this : `a1 = e)/ragues numbera1 = sum(1 for match in re.finditer(r"\b{}\b".format(a1), resp))` this return : `sre_constants.error: unbalanced parenthesis at position 3`
comment on: http://stackoverflow.com/a/50720264
type: AnswerComment

http://stackoverflow.com/a/50798448
score: 2
answers question: http://stackoverflow.com/q/50798335
has body: The best may be to use python standard rotating logs like mentionned here Look at the TimedRotatingFileHandler
downvote count: 0
has comment: http://stackoverflow.com/comment/88603899
upvote count: 2
type: Answer

http://stackoverflow.com/a/50749647
score: 4
answers question: http://stackoverflow.com/q/50747064
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: So I had two issues here, which I was able to figure out thanks to @Ernie Yang and @Cris Luengo. Thank you very much for your help! 1) The issue of my average calculation was that it was overflowing I was summing up the pixel values. That is why the result was looking weird since it was wrapping around. So I had to change: average = np.average(px1 + px2 + px3 + px4 + px5 + px6 + px7 + px8 + px9) to: average = px1/9. + px2/9. + px3/9. + px4/9. + px5/9. + px6/9. + px7/9. + px8/9. + px9/9. 2) However, this did not smooth my image, since I was just assigning the average value to all 9 pixels within the patch. So this caused the picture to be pixelated and not smoothed. Therefore I had to write the result of the average only to the middle pixel, not to all 3x3 pixels in the neighborhood. I also had to write it to a separate output image. You cannot do this operation in place, as it will affect the result for the later pixels. Correct code sample: import matplotlib.pyplot as plt import numpy as np import cv2 as cv from PIL import Image import scipy.ndimage as ndimage from scipy.ndimage.filters import gaussian_filter # 1. Load Image name = 'ebay.png' img = cv.imread(name) #import image h, w = img.shape[:2] smoothedImage = cv.imread(name) #initialize second image # 2. Smooth with with kernel size 3 for y in range(0, w-2): for x in range(0, h-2): px1 = img[x][y] #0/0 px2 = img[x][y+1] #0/1 px3 = img[x][y+2] #0/2 px4 = img[x+1][y] #1/0 px5 = img[x+1][y+1] #1/1 px6 = img[x+1][y+2] #1/2 px7 = img[x+2][y] #2/0 px8 = img[x+2][y+1] #2/1 px9 = img[x+2][y+2] #2/2 average = px1/9. + px2/9. + px3/9. + px4/9. + px5/9. + px6/9. + px7/9. + px8/9. + px9/9. smoothedImage[x+1][y+1] = average #1/1 # 3. Transform the resulting image into pgm format and save result new_image = Image.fromarray(smoothedImage) new_image.save('new.png') # 4. Show image new_image.show() Original Image: Smoothed Image: Edit: Hey folks, I am back from my afternoon nap. I had quite a few interesting thoughts, here is …
type: Answer
accepted answer of: http://stackoverflow.com/q/50747064

http://stackoverflow.com/a/50774822
has body: You can either install the required packages manually by using conda or pip, or if you want to install all the packages that come by default you can use conda install anaconda Note this will download files of size more than 300MB.
answers question: http://stackoverflow.com/q/50774662
score: 0
has comment: http://stackoverflow.com/comment/88557691
type: Answer

http://stackoverflow.com/comment/88560490
comment on: http://stackoverflow.com/q/50775518
score: 0
has text: In your question you stated that you were trying to click the shopping cart button. That's what I clicked. You should add the HTML that *you* are trying to click in your question and then update with the results of the newer code attempts.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50711214
score: 1
answers question: http://stackoverflow.com/q/50711082
has body: Don't try to throw all the exceptions at once, that's just pointless and serves no other purpose than to properly confuse the user. Either throw one specific exception per error found, or throw a general exception with a message that contains all the errors found.
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88606332
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50800076
has text: Or don't use windows ))

http://stackoverflow.com/a/50720180
score: 3
has comment: http://stackoverflow.com/comment/88483933
has body: A dictionary comprehension cannot be used in this recursive manner. It cannot continually update an item as word is iterated. Another way to think of this is that the keys and values of your dictionary are not available for manipulation until the entire comprehension is complete. You can consider the dictionary comprehension to be replicating the for loop below. As with the for loop, you will be setting values rather than adding to the value previously assigned to the key. for letter in word: extra_hand['letter'] = hand['letter'] - 1 Your loop is perfectly fine and there is no need to use a dictionary comprehension. As an alternative, if you only wish to calculate non-zero counts, you can use collections.Counter: from collections import Counter hand = {'h': 1, 'e': 1, 'l': 2, 'o': 1} word = 'hello' res = Counter(hand) - Counter(word) # Counter() hand = {'h': 1, 'e': 2, 'l': 2, 'o': 1} word = 'hello' res = Counter(hand) - Counter(word) # Counter({'e': 1})
has comment: http://stackoverflow.com/comment/88449598
accepted answer of: http://stackoverflow.com/q/50720106
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50720106
upvote count: 3
type: Answer
downvote count: 0

deserialization
type: Tag
tag name: deserialization
tags question: http://stackoverflow.com/q/50791275

http://stackoverflow.com/comment/88555403
score: 0
type: Comment
type: QuestionComment
has text: IMO if you can't `import csv` it sounds like your Python installation is messed up—and it would be very worthwhile to fix that because who knows what other issues it may cause.
comment on: http://stackoverflow.com/q/50773114

http://stackoverflow.com/comment/88671486
type: QuestionComment
comment on: http://stackoverflow.com/q/50833410
has text: @jpp The example is exactly how I want it, but the rows could have been fed in any random way, so my input could have been: [ [1.1, 0.995] [-0.1, 1.001] [0.005, 0.02] [0.99, 0.004] ]
score: 0
type: Comment

http://stackoverflow.com/comment/88544420
type: Comment
type: QuestionComment
score: 0
has text: I think I got it thanks!
comment on: http://stackoverflow.com/q/50768396

http://stackoverflow.com/q/50715249
has answer: http://stackoverflow.com/a/50715272
upvote count: 3
answer count: 2
tagged with: pandas
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have two dataframe read from two csv file. train = pd.read_csv(r"C:\Users\DIU\Desktop\ML-titanic\train.csv") test = pd.read_csv(r"C:\Users\DIU\Desktop\ML-titanic\test.csv") In train dataframe i have 891 rows and in test dataframe i have 418 rows. I concatenate this two dataframe into a new dataframe full_data. full_data = pd.concat([train, test]) full_data now contains 1309 rows, BUT the problem is, the default generated index are separate for both dataframe. Both index are started from one. BUT i want the test dataframe index should start from 892 instead of 0. How do i do that?
downvote count: 0
has title: Concatenating to DataFrame will gives two separate start Index
has comment: http://stackoverflow.com/comment/88439244
type: Question
score: 3
tagged with: dataframe
has answer: http://stackoverflow.com/a/50715437

http://stackoverflow.com/comment/88508738
has text: Input are individual 0.25 mile parcel buffers and the Geology is a geology id feature class. Result needed (for a total of 41k buffers) intersect each individual parcel buffer with geology layer and write results to new feature class. It seems to work until ..for row in sc:
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50750333
score: 0

http://stackoverflow.com/comment/88649762
type: QuestionComment
comment on: http://stackoverflow.com/q/50822119
score: 0
type: Comment
has text: @AGNGazer Like this you mean: im = Image.fromarray(np.uint8(noisy * 255))

http://stackoverflow.com/a/50765547
type: Answer
has body: This issue seemed to have been addressed on the Google Cloud Platform issue tracker link. As explained on that link, usually, 5xx responses are from nginx commonly caused when application is too busy to respond. The nginx webserver sits in front of App Engine application on Google App Engine Instance. However, further review suggests to avoid the use gevent async workers with the Google Cloud Client Library as they cause requests to hang, but instead use more gunicorn workers.
answers question: http://stackoverflow.com/q/50707888
score: 0

http://stackoverflow.com/comment/88635414
type: Comment
comment on: http://stackoverflow.com/a/50713765
type: AnswerComment
has text: I am also trying to apply the same logic for 'Connected Cursive handwritten character'. Please take a look at this link, https://stackoverflow.com/questions/50815307/extract-character-images-from-cursive-continuous-handwritten-image
score: 0

http://stackoverflow.com/q/50756557
has answer: http://stackoverflow.com/a/50758249
type: Question
type: AnsweredQuestion
has body: Imagine the following model: class Person(models.Model): name = models.CharField() address_streetname = models.CharField() address_housenumber = models.CharField() address_zip = models.CharField() I have a django rest framework ModelSerializer that exposes all the fields. But I would like to be able to serialize the address fields into a dict. So when serialized to json output would be: { name: 'Some name', address: { streetname: 'This is a test', housenumber: '23', zip: '1337', } } I tried creating creating a AddressSerializer class Address(object): ... class AddressSerializer(serializers.Serializer): streetname = serializers.CharField() housenumber = serializers.CharField() zip = serializers.CharField() ... and then set the PersonSerializer.address to use the AddressSerializer class PersonSerializer(serializers.ModelSerializer): ... address = AddressSerializer() This results in my schema being correct. I generate swagger docs by using drf-yasg. It looks at the serializers to generate the correct model definitions. So the serializers needs to represent the schema. So this is where I am at, at the moment. Obviously now it fails because there is no address property in the Person model. How would you go about solving this?
upvote count: 4
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50758249
tagged with: django-rest-framework
score: 4
favorite count: 0
tagged with: drf-yasg
tagged with: serialization
tagged with: python
has title: Serialize model fields into nested object/dict
has answer: http://stackoverflow.com/a/50756715
possible better answer: http://stackoverflow.com/a/50756715
tagged with: django

http://stackoverflow.com/a/50706000
type: Answer
has comment: http://stackoverflow.com/comment/88423804
accepted answer of: http://stackoverflow.com/q/50705881
upvote count: 1
has comment: http://stackoverflow.com/comment/88472588
has comment: http://stackoverflow.com/comment/88421291
has comment: http://stackoverflow.com/comment/88426097
score: 1
has comment: http://stackoverflow.com/comment/88496564
answers question: http://stackoverflow.com/q/50705881
type: AcceptedAnswer
downvote count: 0
has body: I've found that time.sleep(x) is usually the problem when writing similar code for Selenium. The problem is that it pauses all computation and tends to cause more harm than good, at least in my experience. I try to use Expected Conditions whenever possible for this type of thing. from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(my_selenium_driver, 15) my_button = wait.until(EC.element_to_be_clickable((By.XPATH,self._my_button_xpath))).click() As an example, you can keep your current action chain that is in charge of scrolling through the list and allow it to do so but during that scroll have the EC.wait looking for your desired element and clicking it as soon as it is visible.

http://stackoverflow.com/q/50759886
score: 0
tagged with: sql
tagged with: python
type: UnansweredQuestion
has title: SQL QUERY: Fetch many locations from MySQL, geocode with, then update records with lat / long
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/50761992
answer count: 1
has body: I have a series of locations saved in a database and I need to fetch them all, geocode them, then put the lat / long back into the database. I'm using Pymysql to do this and have the following code but really not sure how to put the SQL query together. I've currently got the following (I know the query is wrong!) def geocode(): rows = myCursor.execute("SELECT location, id FROM jobs WHERE latitude IS NULL").fetchall() for location in rows: latitude = geocoder.google(location).lat longitude = geocoder.google(location).lng myCursor.execute("UPDATE jobs SET latitude= %s, longitude =%s WHERE id=id",(latitude, longitude)) connection.commit() print ("Locations geocoded") As always, all help is greatly appreciated!
tagged with: pymysql
has comment: http://stackoverflow.com/comment/88528192

http://stackoverflow.com/a/50898254
type: AcceptedAnswer
has body: The following works for me. While it technically isn't a flag, it you do know exactly which row is row number 1. df.withColumn("rowNum",F.row_number().over(Window.partitionBy('person_id','session_id').orderBy("unix_ts")))
type: Answer
accepted answer of: http://stackoverflow.com/q/50805994
answers question: http://stackoverflow.com/q/50805994
score: 0

http://stackoverflow.com/q/50749343
has comment: http://stackoverflow.com/comment/89210910
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88614456
has comment: http://stackoverflow.com/comment/89198501
has body: I created a GUI tool with Qt Creator and Python. In the GUI the user would select types of the shapefile he/she wants to generate. The script stores the selection in a list. Generating of each type of shapefile is handled by separate QThreads. Each QThread would print some messages like "Processing AAA....". The "run" button function would then do: if optionA in selection_list: QThreadA.start() if optionB in selection_list: QThreadB.start() if optionC in selection_list: QThreadC.start() Now I am trying to have the GUI pop up a window when all QThreads finish. I found it here https://riverbankcomputing.com/pipermail/pyqt/2007-May/016026.html that QThread.wait() works the same as thread.join(), and I am trying to utilize it. I cannot do if optionA in selection_list: QThreadA.start() if optionB in selection_list: QThreadB.start() if optionC in selection_list: QThreadC.start() QThreadA.wait() QThreadB.wait() QThreadC.wait() print("All set") Since sometimes not all QThreads would be running. But if I do if optionA in selection_list: QThreadA.start() if optionB in selection_list: QThreadB.start() if optionC in selection_list: QThreadC.start() if optionA in selection_list: QThreadA.wait() if optionB in selection_list: QThreadB.wait() if optionC in selection_list: QThreadC.wait() print("All set") Not only does this look dumb, when I hit "run" button, I would also get "All set" "Processing AAA..." "Processing BBB..." "Processing CCC..." The messages appear altogether when apparently everything finished, instead of what I was hoping to see: "Processing AAA..." some time passed... "Processing BBB..." some more time passed... "Processing CCC..." some more time passed... "All set" What is the order of the things that happen here? And this basically makes the messages useless as the user would only see them when everything finishes at last. Could use some help on how to reconstruct the functions. Edit: According to @Nimish Bansal's recommendation, I come up with this: dict = {opt…
tagged with: pyqt
has answer: http://stackoverflow.com/a/51112069
has comment: http://stackoverflow.com/comment/88531929
favorite count: 0
has comment: http://stackoverflow.com/comment/88508792
upvote count: 1
tagged with: python
has title: PyQt Confirmation Finishing of Multiple QThreads
tagged with: qthread
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88614542
accepted answer: http://stackoverflow.com/a/51112069
score: 1
has comment: http://stackoverflow.com/comment/88537581
type: Question

http://stackoverflow.com/comment/88560620
type: QuestionComment
comment on: http://stackoverflow.com/q/50776805
has text: the errors arent relevant. What I need is a module.py file of the module. There isnt one, but i can still import module, so im wondering if there is some reverse functionality like export module or something?
score: 0
type: Comment

http://stackoverflow.com/a/50781144
downvote count: 0
has body: You are confusing c/c++/c# for syntax with python. In c/c++/c# you have a conditional inside the for syntax: for (var i= 0; i&lt;100;i++) # this is checked each time you come back here, incrementing # the i will skip some runs and change how often the for is done Pythons for is more a foreach: for i in range(3): ==> foreach(var k in new []{0,1,2}) # it takes a fresh "k" out every time it comes here { ... } if you modify k it will still only run 3 times.
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50781119

http://stackoverflow.com/comment/88465623
score: 0
type: QuestionComment
has text: You can use .update on the row, however this will only return the data and you have to "somehow" update the table with those values. As others said, pandas or even a pure python iteration may be easier to operate, depends on your data source. initial_price_row.update('Price List', 100), however this will only return the row with the updated values, it will NOT update your table without further actions I do not really know from looking at petl for a short time.
comment on: http://stackoverflow.com/q/50728473
type: Comment

http://stackoverflow.com/comment/88647920
score: 0
type: AnswerComment
has text: That's what you used in your example. You can use a comma or any other symbol instead.
type: Comment
comment on: http://stackoverflow.com/a/50821239

http://stackoverflow.com/q/50760834
has comment: http://stackoverflow.com/comment/88530329
upvote count: 5
tagged with: scikit-learn
score: 4
possible better answer: http://stackoverflow.com/a/50845118
has answer: http://stackoverflow.com/a/50845118
has comment: http://stackoverflow.com/comment/88530417
accepted answer: http://stackoverflow.com/a/50761942
favorite count: 0
has comment: http://stackoverflow.com/comment/88529566
has title: Explanation of the percentage value in scikit-learn PCA method
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
tagged with: pca
has answer: http://stackoverflow.com/a/50761942
downvote count: 1
type: Question
answer count: 2
has body: In scikit-learn, there is a method called PCA. This method takes a percentage parameter. This site explains this parameter as follows: Notice the code below has .95 for the number of components parameter. It means that scikit-learn choose the minimum number of principal components such that 95% of the variance is retained. &gt; from sklearn.decomposition import PCA &gt; # Make an instance of the Model &gt; pca = PCA(.95) I'm a bit in the dark about the interpretation of this explanation. Let's say the output of the PCA would be as follows: PC1 explains 70 % of the complete variance PC2 explains 15 % of the complete variance PC3 explains 10 % of the complete variance PC4 explains 4 % of the complete variance PC5 explains 1 % of the complete variance Would the statement PCA(0.71) return PC1 and PC5 (as they both explain exactly 71 % of the variance) or would it return PC1 and PC2? What happens if I would like to retrieve 0.5 % of the variance, i.e. which PC would the statement PCA(0.005) return?

http://stackoverflow.com/q/50751319
tagged with: python
type: UnansweredQuestion
upvote count: 1
tagged with: python-requests
has body: I'm trying to place an order using V2 of the HITBTC API (docs here). I'm trying to place an order via a POST request, and everything is fine authorization wise, but upon placing the order, the following function returns what the server is sending back, which is the following JSON: {'error': {'code': 2001, 'message': 'Symbol not found', 'description': 'Try get /api/2/public/symbol, to get list of all available symbols.'}} My issue arises with the fact that I'm passing the pair I wish to order in the format that's specified by this call for the symbols, which returns JSON like the following: {"id":"NOAHBTC","baseCurrency":"NOAH","quoteCurrency":"BTC","quantityIncrement":"1000","tickSize":"0.000000001","takeLiquidityRate":"0.001","provideLiquidityRate":"-0.0001","feeCurrency":"BTC"} I'm passing a string formatted exactly as 'id' is formatted. def HITBTCorder(pair, side, quantity, price, session): ''' Creates an order on HITBTC, returns status (filled or not filled) Side: 'buy' or 'sell' ''' orderData = json.dumps({'symbol': pair, 'side': side, 'quantity': quantity, 'price': price}) print(orderData) response = session.post('https://api.hitbtc.com/api/2/order', data = orderData) responseDict = json.loads(response.text) return responseDict The code I'm running looks like this: session = requests.session() session.auth = ('APIPUBLIC', 'APISECRET') response = trade.HITBTCorder("NOAHBTC", 'buy', 1000, tickers.HITBTCprice("NOAHBTC"), session) Any idea how to get this working?
type: Question
score: 1
has comment: http://stackoverflow.com/comment/139236853
answer count: 2
has answer: http://stackoverflow.com/a/51024298
has title: Why is the HITBTC V2 REST API returning a 2001 error (Incorrect Pair)?
downvote count: 0
tagged with: algorithmic-trading
favorite count: 0
tagged with: rest
has answer: http://stackoverflow.com/a/56798831

http://stackoverflow.com/comment/88543657
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50767370
has text: @KlausD.: `sys.stdin.read()` doesn’t return until the EOF, so there’s no way to detect `"exit"` like this to begin with.
type: Comment

http://stackoverflow.com/q/50723072
score: 2
has comment: http://stackoverflow.com/comment/88455343
has title: Stop Tensorflow from reloading model per request
has comment: http://stackoverflow.com/comment/88458087
tagged with: tensorflow-serving
tagged with: tensorflow
type: Question
tagged with: tensorflow-estimator
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/110244820
favorite count: 0
has answer: http://stackoverflow.com/a/54277707
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88457158
tagged with: python
has comment: http://stackoverflow.com/comment/88455936
has body: I've inherited some TF code that does the following per request: def predict_tf(ml_wrapper, prediction_row_df): log.debug('request POST {}'.format(prediction_row_df)) prediction_row_df, _, _ = ml_wrapper._engineer_features(prediction_row_df) # As method says; delete stuff we don't want and scale and impute if needed ml_wrapper._delete_unused_values_and_scale_and_impute_missing_values(prediction_row_df, single_row_prediction=True) features, labels = ml_wrapper._split_features_and_labels(prediction_row_df) panda_function_for_prediction = tf.estimator.inputs.pandas_input_fn( features, labels, batch_size=ml_wrapper.batch_size, num_epochs=1, shuffle=False ) predictions = ml_wrapper.tf_model.predict( input_fn=panda_function_for_prediction) probas = list(predictions)[0]['probabilities'] log.warning('PREDICTED: no:{} yes:{}'.format(probas[0], probas[1])) return probas The code appears to work, though in console I see something like this: 2018-06-06 16:32:46,767 INFO [tensorflow:116] Calling model_fn. 2018-06-06 16:32:50,848 INFO [tensorflow:116] Done calling model_fn. 2018-06-06 16:32:51,082 INFO [tensorflow:116] Graph was finalized. 2018-06-06 16:32:51,083 INFO [tensorflow:116] Restoring parameters from /model_tensorflow/model.ckpt-719 2018-06-06 16:32:51,494 INFO [tensorflow:116] Running local_init_op. 2018-06-06 16:32:51,536 INFO [tensorflow:116] Done running local_init_op. This operation seems to take 4s per request - is there a way to load the model/estimator just once and predict on it?

http://stackoverflow.com/comment/88441647
type: Comment
comment on: http://stackoverflow.com/q/50716186
type: QuestionComment
has text: @samorr Yes, that's what I was thinking but I'm kinda stuck on how to do it, without having to change the code each time
score: 0

http://stackoverflow.com/a/55601111
score: 1
has body: You're doing a get instead of a post, and it expects a straight string as the data parameter and not a JSON object as the param parameter. I pass the text I want interpreted into a method like this def apiai_text_request(self, text): request_text = '{"q":"'+text+'"}' result = requests.post("http://localhost:5000/parse", data = request_text) return result.json()
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50716360
downvote count: 0

http://stackoverflow.com/comment/88573776
has text: Formally this is a new question, but it is very simple so: Set the first index of the input shape as -1. E.g. a gray picture with 30x30 pixels has the shape of [-1, 30, 30, 1]. Tensorflow will then automatically calculat the batch size. And please mark my answer as answered if it fixed your problem.
comment on: http://stackoverflow.com/a/50781250
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88598724
type: Comment
has text: `lxml`'s proxies are not special to the `.xpath()` method. `lxml` creates proxy elements for *all elements* that it exposes, not just elements returned from an XPath evaluation. Just put a breakpoint on `_elementFactory` and run `ET.fromstring("<doc/>")` without any other code. You'll see the factory being called once, even though XPath is not involved at all in this code. Moreover, the proxies do not do shallow copies. That's not their job. If they did then calling `.node()` in the OP's code would work just as well as calling `.xpath()`.
comment on: http://stackoverflow.com/a/50785151
type: AnswerComment
score: 0

google-sheets-api
tags question: http://stackoverflow.com/q/50828208
type: Tag
tags question: http://stackoverflow.com/q/50844968
tag name: google-sheets-api

http://stackoverflow.com/a/50752442
answers question: http://stackoverflow.com/q/50752385
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50752385
type: Answer
has body: Instead of repeating random.choice multiple times, you can use random.choices and provide k=10 as argument. A list comprehension then allows to keep only numbers greater than 40. import random # Pick 10 random numbers with replacement numbers = random.choices(range(10, 96), k=10) # Filter out numbers &lt;= 40 numbers_above_40 = [x for x in numbers if x &gt; 40] print(numbers_above_40) # [54, 77, 60, 75, 70, 90, 75, 44] If you want to randomly pick numbers without replacement use random.sample instead.

http://stackoverflow.com/comment/88633428
comment on: http://stackoverflow.com/q/50813906
has text: What do you mean "I still couldn't get the csv file" ?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/50805080
has comment: http://stackoverflow.com/comment/133869017
has body: I currently have Python 2.7.15 installed, and I am trying to import the python opcua module. I am doing this specifically to access the Server method. So far, I have tried two approaches, both which gave the same error that follows. ImportError: No module named opcua First approach: from opcua import Server Second approach: from __future__import opcua Do I first need to install a separate package before I can use the opcua module?
has answer: http://stackoverflow.com/a/51081117
tagged with: python
tagged with: opc-ua
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has title: opcua module in python
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88616185
accepted answer: http://stackoverflow.com/a/51081117
favorite count: 0

http://stackoverflow.com/a/74969025
score: 0
has body: def report_confirm(request): return render(request, 'fostania_web_app/report_confirm.html', context) #add the context You need to pass in the "context" so that it shows in the template
type: Answer
answers question: http://stackoverflow.com/q/50807332

tkinter
tags question: http://stackoverflow.com/q/50751630
tags question: http://stackoverflow.com/q/50753310
tags question: http://stackoverflow.com/q/50780461
tags question: http://stackoverflow.com/q/50820405
tags question: http://stackoverflow.com/q/50707248
tags question: http://stackoverflow.com/q/50748750
tags question: http://stackoverflow.com/q/50745781
tags question: http://stackoverflow.com/q/50806334
tags question: http://stackoverflow.com/q/50788007
tags question: http://stackoverflow.com/q/50848212
tags question: http://stackoverflow.com/q/50787864
tags question: http://stackoverflow.com/q/50728173
tags question: http://stackoverflow.com/q/50785536
tags question: http://stackoverflow.com/q/50743096
tags question: http://stackoverflow.com/q/50769264
tags question: http://stackoverflow.com/q/50748571
tags question: http://stackoverflow.com/q/50786184
tags question: http://stackoverflow.com/q/50814594
tags question: http://stackoverflow.com/q/50852171
tags question: http://stackoverflow.com/q/50807750
tag name: tkinter
tags question: http://stackoverflow.com/q/50851250
tags question: http://stackoverflow.com/q/50847585
tags question: http://stackoverflow.com/q/50723906
tags question: http://stackoverflow.com/q/50822206
tags question: http://stackoverflow.com/q/50801120
tags question: http://stackoverflow.com/q/50767199
tags question: http://stackoverflow.com/q/50707709
tags question: http://stackoverflow.com/q/50709931
tags question: http://stackoverflow.com/q/50767995
tags question: http://stackoverflow.com/q/50732085
tags question: http://stackoverflow.com/q/50821996
tags question: http://stackoverflow.com/q/50749781
tags question: http://stackoverflow.com/q/50817679
tags question: http://stackoverflow.com/q/50842779
tags question: http://stackoverflow.com/q/50756873
tags question: http://stackoverflow.com/q/50749686
tags question: http://stackoverflow.com/q/50782813
tags question: http://stackoverflow.com/q/50770356
tags question: http://stackoverflow.com/q/50723662
tags question: http://stackoverflow.com/q/50833518
tags question: http://stackoverflow.com/q/50702674
tags question: http://stackoverflow.com/q/50725476
tags question: http://stackoverflow.com/q/50727923
tags question: http://stackoverflow.com/q/50783616
tags question: http://stackoverflow.com/q/50824974
tags question: http://stackoverflow.com/q/50835624
tags question: http://stackoverflow.com/q/50724731
tags question: http://stackoverflow.com/q/50704612
tags question: http://stackoverflow.com/q/50711605
tags question: http://stackoverflow.com/q/50815547
tags question: http://stackoverflow.com/q/50845828
tags question: http://stackoverflow.com/q/50784959
tags question: http://stackoverflow.com/q/50783894
tags question: http://stackoverflow.com/q/50815151
tags question: http://stackoverflow.com/q/50718834
tags question: http://stackoverflow.com/q/50803301
tags question: http://stackoverflow.com/q/50784007
tags question: http://stackoverflow.com/q/50731915
tags question: http://stackoverflow.com/q/50804764
tags question: http://stackoverflow.com/q/50764622
tags question: http://stackoverflow.com/q/50785759
tags question: http://stackoverflow.com/q/50746554
tags question: http://stackoverflow.com/q/50699949
tags question: http://stackoverflow.com/q/50786590
tags question: http://stackoverflow.com/q/50756252
tags question: http://stackoverflow.com/q/50808428
tags question: http://stackoverflow.com/q/50854951
tags question: http://stackoverflow.com/q/50765266
tags question: http://stackoverflow.com/q/50837855
tags question: http://stackoverflow.com/q/50795324
tags question: http://stackoverflow.com/q/50779576
tags question: http://stackoverflow.com/q/50708033
tags question: http://stackoverflow.com/q/50744947
tags question: http://stackoverflow.com/q/50706071
tags question: http://stackoverflow.com/q/50786974
tags question: http://stackoverflow.com/q/50779558
tags question: http://stackoverflow.com/q/50818809
tags question: http://stackoverflow.com/q/50712657
tags question: http://stackoverflow.com/q/50801991

http://stackoverflow.com/comment/88529898
has text: I really think giving more information on the expected output would really helps us help you.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50761157

vertica
tag name: vertica
type: Tag
tags question: http://stackoverflow.com/q/50822978

http://stackoverflow.com/comment/88690022
score: 0
comment on: http://stackoverflow.com/q/50825683
type: Comment
type: QuestionComment
has text: The project is configured properly. Even without passing this argument. If I run ```client.project``` shows me the right project name. But I tested your suggestion and still not working.

http://stackoverflow.com/comment/88545310
type: Comment
has text: Hi, what version of Python would I require to implement this?
comment on: http://stackoverflow.com/a/50768796
type: AnswerComment
score: 0

http://stackoverflow.com/q/50780461
has comment: http://stackoverflow.com/comment/88568047
has title: Python how to change colour of individual square of grid on mouse click
has comment: http://stackoverflow.com/comment/88568538
has comment: http://stackoverflow.com/comment/88567991
tagged with: tkinter
has answer: http://stackoverflow.com/a/50780915
has comment: http://stackoverflow.com/comment/88567883
tagged with: python
has body: How do I change the color of an individual square of the grid. This grid is drawn over an image. I calculated the center point of each square of the grid. When a user clicks on a specific square of the grid, I get the centroid of that square (already implemented). How can I change the color of the square of the grid. I have centroid of the clicked square in variable "closest_centroid". # Get closes centroid def closest_node(node, nodes): nodes = np.asarray(nodes) dist = np.sum((nodes - node)**2, axis=1) return np.argmin(dist) # print co-ordinate function def get_coords(event): mouse_xy = (event.x, event.y) closest_centroid = centers[closest_node(mouse_xy, centers)] print(closest_centroid) My idea is to change the color of pixels of an image contained in the clicked square of the grid. My libraries are: import math from Tkinter import * from PIL import Image, ImageDraw import numpy as np
type: AnsweredQuestion
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/88568079
type: Question
answer count: 1
tagged with: python-2.7
score: 0
tagged with: colors
accepted answer: http://stackoverflow.com/a/50780915

http://stackoverflow.com/comment/88475233
type: AnswerComment
type: Comment
has text: word: ['i', 'want', 'to', 'study', 'Hindi', 'and', 'english'] But its not match and display accurate ans.
score: 0
comment on: http://stackoverflow.com/a/50716522

http://stackoverflow.com/q/50816417
type: Question
type: AnsweredQuestion
has body: One column has dates but the other has a string containing a date, so I first need to extract the date part from that string. import pandas as pd import datetime from dateutil.relativedelta import relativedelta # the dataframe - id column always starts with year, month and day df = pd.DataFrame({'id': ['19520630F8', '19680321A5', '19711113E2'], 'dte': ['2010-06-02', '2007-08-12', '2013-01-23']}) # create a date string from df['id'] to the format yyyy-mm-dd dob = (df['id'].str[:4] + '-' + df['id'].str[4:6] + '-' + df['id'].str[6:8]) # calculate age (years only) at df['dte'] df['age'] = relativedelta(date, dob).years I get the error message: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I don't understand the ambiguousness of my data, and where to apply those empty/bool/item... The df['dta'] column if of object data type and not datetime, but wrapping the creation of dob in pd.to_datetime wont help. EDIT The expected output should be dte id age 0 2010-06-02 19520630F8 57 1 2007-08-12 19680321A5 39 2 2013-01-23 19711113E2 41
tagged with: dataframe
downvote count: 0
answer count: 3
tagged with: pandas
tagged with: datetime
tagged with: python
possible better answer: http://stackoverflow.com/a/50816668
has answer: http://stackoverflow.com/a/50816455
upvote count: 6
accepted answer: http://stackoverflow.com/a/50816455
favorite count: 0
has title: How to calculate number of years between two dates in different pandas columns
has answer: http://stackoverflow.com/a/67831190
score: 6
has answer: http://stackoverflow.com/a/50816668

http://stackoverflow.com/q/50812512
accepted answer: http://stackoverflow.com/a/50822509
tagged with: matlab
type: AnsweredQuestion
tagged with: netcdf4
tagged with: netcdf
type: Question
has body: I used this function to all the format and dimension of netCDF file. This is how I used this in Matlab: filename = 'C:\Users\my_name\Desktop\metopa_AM.nc' ncdisp(filename) Source: C:\Users\my_name\Desktop\metopa_nh3nn_20100101_AM.nc Format: netcdf4 Global Attributes: Title = 'Ammonia total columns retrieved from IASI measurements from the NH3-ULBNN retrieval algorithm' Institution = 'Universite Libre de Bruxelles (ULB)/Laboratoire atmosph�res, milieux et observations spatiales (LATMOS)' Product_Version = '1.0' keywords = 'satellite, observation, atmosphere, ammonia' date_created = '2016-04-26 12:44:52' contact_emails = 'Simon Whitburn (simon.whitburn@ulb.ac.be) and Lieven Clarisse (lclariss@ulb.ac.be)' platform = 'Metop-A' spatial_resolution = '12 km diameter pixel at nadir' Dimensions: time = 649874 Variables: time Size: 649874x1 Dimensions: time Datatype: single Attributes: long_name = 'UTC time of acquisition' standard_name = 'time' units = 'HHMMSS.ms' example = '252.9025=000252.9025 &gt;&gt; HH=00, MM=02, SS=52, ms=902' latitude Size: 649874x1 Dimensions: time Datatype: single Attributes: long_name = 'latitude' standard_name = 'latitude' units = 'degrees_north' valid_range = [-90 90] longitude Size: 649874x1 Dimensions: time Datatype: single Attributes: long_name = 'longitude' standard_name = 'longitude' units = 'degrees_east' valid_range = [-180 180] column Size: 649874x1 Dimensions: time Datatype: single Attributes: long_name = 'Ammonia total column' standard_name = 'NH3_total_column' units = 'molec.cm^{-2}' missing_value = 'NaN' error Size: 649874x1 Dimensions: time Datatype: single Attributes: long_name = 'Error on the ammonia total column' standard_name = 'NH3_total_column_error' units = '%' missing_value = 'NaN' CLcov Size: 649874x1 Dimensions: time Datatype: single Attributes: long_name = 'Cloud coverage in the on ground pixel' standard_name = 'cloud_cover' units = '%' VertProf Size: 649874x1 Dimensions: time Datatype: int32 Attributes: long_name = 'Verti…
has answer: http://stackoverflow.com/a/50822509
has title: Alternative function for ncdisp() of MATLAB in python in netCDF4 library
answer count: 1
tagged with: python-3.x
score: 0
tagged with: python

http://stackoverflow.com/a/50784620
has body: First, maybe you should enable trace log by: capabilities = DesiredCapabilities.FIREFOX.copy() capabilities["moz:firefoxOptions"] = { "log": { "level": "trace", }, } driver = webdriver.Firefox(capabilities=capabilities) Or opts = Options() opts.log.level = "trace" driver = webdriver.Firefox(firefox_options=opts) Second, as far as I think, this issue is usually casued by Graphic environment requirement. It seems if you are not running a firefox instance in a session with valid DISPLAY, it will exit with code 1. So maybe your question can be resolved by: options = Options() profile = webdriver.FirefoxProfile() options.add_argument("--headless") driver = webdriver.Firefox(profile, firefox_options=options) Finally, I must say I'm actually not sure about your problem as there is just limited information.
upvote count: 1
answers question: http://stackoverflow.com/q/50784498
has comment: http://stackoverflow.com/comment/88619456
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/88640716
has comment: http://stackoverflow.com/comment/88622147

http://stackoverflow.com/comment/88719890
has text: Try including `plt.savefig('graph_brand' + df['brand']) at the end of the for loop
comment on: http://stackoverflow.com/a/50845564
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88484982
type: Comment
comment on: http://stackoverflow.com/a/50738208
score: 0
type: AnswerComment
has text: @khelwood how do I tackle this statement?:

http://stackoverflow.com/a/50700769
has comment: http://stackoverflow.com/comment/88412759
has comment: http://stackoverflow.com/comment/88411734
has comment: http://stackoverflow.com/comment/88411870
has comment: http://stackoverflow.com/comment/88411154
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50699944
has body: Pending clarification, this is either a problem of enumerating all maximum matchings (1) or finding one maximum matching (2). (1) Algorithms for Enumerating All Perfect, Maximum and Maximal Matchings in Bipartite Graphs Takeaki UNO http://research.nii.ac.jp/~uno/papers/isaac97web.pdf (2) e.g., Hopcroft--Karp https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm
has comment: http://stackoverflow.com/comment/88411114

http://stackoverflow.com/comment/88465693
has text: I guess I am stuck on thinking that I have to loop through all sub-nodes (hence I am trying to build it out using 'findall' instead of 'find') and when I do that, i have values segregated out in different rows `(None, None, None, None, None) (None, None, None, None, None) (None, '8302-2', 'Height', None, None) (None, 'completed', None, None, None) (None, None, None, '20170130', None) (None, None, None, '61.2598', 'Inches')`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50710440
type: Comment

http://stackoverflow.com/comment/88452180
has text: This is interesting behavior of glob. I had no idea you could completely "wildcard" directories. Thanks for sharing.
comment on: http://stackoverflow.com/a/50721824
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88660787
has text: After some testing, my answer wasn't quite ideal because I lost the Gene information. I have also been trying to figure out how to change the zscore function for this purpose so that if the group size is less than 2, it will return 1 instead of trying to calc a zscore: zscore = lambda x: stats.zscore(x) if len(x) > 1 else 1 But that doesn't want to work either :/
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50828055
type: Comment

http://stackoverflow.com/a/50738208
has comment: http://stackoverflow.com/comment/88540459
has comment: http://stackoverflow.com/comment/88540444
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88484195
accepted answer of: http://stackoverflow.com/q/50738140
has body: The result of adding two vectors of length 3 should be a vector with 3 elements, where each element is the sum of the corresponding elements in the original two vectors. def __add__(self,other): return Vector([a+b for a,b in zip(self.vector, other.vector)]) This uses zip to iterate through both the starting vectors together, and constructs the new list using a list comprehension. &gt;&gt;&gt; x = Vector([2,4,6]) &gt;&gt;&gt; y = Vector([7,8,9]) &gt;&gt;&gt; x+y==Vector([9,12,15]) True More: If you want to support scalar multiplication, as indicated by your comments, then your other operand is not another vector, but a number. So you need to multiply each element individually by that number. def __mul__(self, other): return Vector([a*other for a in self.vector]) __rmul__ = __mul__ This should allow you to perform both v*5 and 5*v where v is a Vector object. &gt;&gt;&gt; x = Vector([2,4,6]) &gt;&gt;&gt; x*5==Vector([10,20,30]) True More Here is an example of how you might write a dot-product between two vectors: def dot(self, other): return sum(a*b for (a,b) in zip(self.vector, other.vector)) &gt;&gt;&gt; x = Vector([1,2,3]) &gt;&gt;&gt; y = Vector([3,2,1]) &gt;&gt;&gt; x.dot(y) 10
has comment: http://stackoverflow.com/comment/88494476
has comment: http://stackoverflow.com/comment/88484085
has comment: http://stackoverflow.com/comment/88540346
answers question: http://stackoverflow.com/q/50738140
has comment: http://stackoverflow.com/comment/88544976
has comment: http://stackoverflow.com/comment/88484982
has comment: http://stackoverflow.com/comment/88485038
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88485672
has comment: http://stackoverflow.com/comment/88540430
has comment: http://stackoverflow.com/comment/88494446
has comment: http://stackoverflow.com/comment/88494646
has comment: http://stackoverflow.com/comment/88484262
type: Answer

http://stackoverflow.com/a/79424224
has body: There are dss files being written for all simulations in RAS. access the files from both the simulation and read them using python.
score: 0
answers question: http://stackoverflow.com/q/50813889
type: Answer

http://stackoverflow.com/comment/88705282
type: AnswerComment
comment on: http://stackoverflow.com/a/50808670
type: Comment
has text: It's strange when you installed it but the output say it can't find bzlib. Great chance that there is something to do with your PATH. Have you tried to recheck your PATH? I suggest you do the following, not an elegant solution but it will work: `1.` Find libbz in your system by using `find . -name "bzlib*"` `2.` Copy the output dir. Within a terminal session `export PATH=/path/to/bzlib/:$PATH`. If you want the change to be permanent, add the `export` command to `~/.bashrc`. Tell me if you still have problem!
score: 0

http://stackoverflow.com/comment/88412874
comment on: http://stackoverflow.com/q/50701738
type: Comment
has text: Why don't you create a separate `Service` and `Addon` model?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88509417
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50750716
has text: `subprocess.check_output('/usr/bin/pmset -g batt')` also gives error. I am using python 2.7.14.
score: 0

http://stackoverflow.com/q/50779565
favorite count: 0
accepted answer: http://stackoverflow.com/a/50783905
has comment: http://stackoverflow.com/comment/88567101
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88568494
has comment: http://stackoverflow.com/comment/88566001
has comment: http://stackoverflow.com/comment/88567011
has comment: http://stackoverflow.com/comment/88573251
type: AnsweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/88568687
type: Question
has title: How to create nested list from hierarchy
has body: I have some UserInvites, where an invite has from and to User properties. E.g., UserInvite1.from = User1 UserInvite1.to = User2 UserInvite1b.from = User1 UserInvite1b.to = User4 UserInvite2.from = User2 UserInvite2.to = User3 UserInvite3.from = User2 UserInvite3.to = User5 Thus, User1 invited User2 and User4; User2 invited User3 and User5. Given a list of those invites, e.g., [UserInvite1, UserInvite2, ... ], or another means of iterating over them(?), how can I generate a "hierarchical" (nested) list representing those invited? E.g., starting with the "root" User1, I'd like a nested list as such: &gt;&gt;&gt; make_nest_list_from_invites([invites]) [User1, [User2, [User3, User5], User4]] If you're familiar with Django, I'm trying to get from my "invites" to something hierarchical that I can feed to the Django template tag unordered_list Clearly this is something like tree traversal, but I'm stumped at the moment. I tried some recursion-ey stuff, but kept ending up with an extra level of nesting in places that was throwing things off. UPDATE: Example of something I tried def tree_from_here(user): children = get_children(user) if children: return [user, [tree_from_here(c) for c in children]] else: return user Which gives: &gt;&gt;&gt; tree_from_here(User1) [&lt;User: 1&gt;, [[&lt;User: 2&gt;, [&lt;User: 3&gt;, &lt;User: 5&gt;]], &lt;User: 4&gt;]] Which is almost correct for my current set of users, with the exception that the nesting goes too deep in the second element. I am trying for: [&lt;User: 1&gt;, [&lt;User: 2&gt;, [&lt;User: 3&gt;, &lt;User: 5&gt;], &lt;User: 4&gt;]] I feel like it's staring me in the face, but I am not sure how to return the right thing at the moment.
has comment: http://stackoverflow.com/comment/88565998
tagged with: data-structures
has comment: http://stackoverflow.com/comment/88567124
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50783905

http://stackoverflow.com/comment/88601287
comment on: http://stackoverflow.com/q/50794245
has text: Just wondering: Why do you call `browse()` in your last line? `template.send_mail(res_id, force_send=True)` would be enough.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50761199
has comment: http://stackoverflow.com/comment/88870294
has comment: http://stackoverflow.com/comment/88950272
downvote count: 0
has comment: http://stackoverflow.com/comment/88944040
has comment: http://stackoverflow.com/comment/88573285
tagged with: ocr
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/105084969
upvote count: 2
has comment: http://stackoverflow.com/comment/88538970
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/105019905
has comment: http://stackoverflow.com/comment/88999017
tagged with: opencv
score: 2
has comment: http://stackoverflow.com/comment/88902565
tagged with: image-processing
has body: want to extract the drug name ONLY from the label (heading) using OCR tesseract from PIL import Image import pytesseract im = Image.open("sample1.jpg") text = pytesseract.image_to_string(im, lang = 'eng') print(text) I want it to recognize the drug name automatically with out using positioning and return glimepiride what should i add to the code??
has comment: http://stackoverflow.com/comment/88573252
has comment: http://stackoverflow.com/comment/88536369
type: Question
has title: extract certain text from an image using OCR

unix
tags question: http://stackoverflow.com/q/50768623
tags question: http://stackoverflow.com/q/50843717
tags question: http://stackoverflow.com/q/50777423
tags question: http://stackoverflow.com/q/50836829
tags question: http://stackoverflow.com/q/50805474
tags question: http://stackoverflow.com/q/50848968
type: Tag
tag name: unix

http://stackoverflow.com/comment/88449662
type: Comment
comment on: http://stackoverflow.com/q/50720133
has text: But `-0.25, 0, 0` are three values which are larger than `-0.3`, so it should be three zeros, shouldn't it?
score: 0
type: QuestionComment

http://stackoverflow.com/a/50729372
answers question: http://stackoverflow.com/q/50722486
has comment: http://stackoverflow.com/comment/88500302
type: Answer
has comment: http://stackoverflow.com/comment/88484934
downvote count: 0
has comment: http://stackoverflow.com/comment/88499246
has comment: http://stackoverflow.com/comment/88475301
score: 1
has body: Thanks for showing me. That code isn’t going to do anything. You have to actually do something with the stored data structure after registering keys. For example: #change store key function to do something on submission of a certain key that indicated send, will use pound for example. def store_key(self,key): If(key==‘#’): #im printing but you should do whatever it is you intend to do with the sequence of keys. print(self.pressed_keys) else: self.pressed_keys.append(key) That code will print the internal data structure on # being pressed. Of course I’m assuming the key passed on is a string, but I don’t really know I’m not familiar with the library.
upvote count: 1

http://stackoverflow.com/comment/88608289
type: AnswerComment
comment on: http://stackoverflow.com/a/50800931
type: Comment
has text: I have added some explanation to my answer with a sample code, please have a look
score: 0

http://stackoverflow.com/q/50786362
has comment: http://stackoverflow.com/comment/88579520
has comment: http://stackoverflow.com/comment/88579607
type: Question
has body: I have the following code. Although, the problem is very simple but I cannot figure out the reason behind it. The following is my main.py: from model_MNIST import Model def main(): model = Model() if __name__ == '__main__': main() And the model_MNIST.py file is as follows: # some import statements class Model(object): def __init__(self, input_dimensions, output_dimensions): # some init statements def train_on_data(self, training_data, training_labels): N = training_labels.size Whenever the class initialization is called I get an output as name 'training_labels' is not defined. This is preventing the execution of the program. Can someone point me out what I might be missing? Edit1: Please refer to the shared link for the file. SharedFolder
has comment: http://stackoverflow.com/comment/88583320
has comment: http://stackoverflow.com/comment/88579191
has comment: http://stackoverflow.com/comment/88579493
score: 0
answer count: 3
has title: Python: Variable not defined in external class
possible better answer: http://stackoverflow.com/a/50786640
has answer: http://stackoverflow.com/a/50786668
has answer: http://stackoverflow.com/a/50786640
has comment: http://stackoverflow.com/comment/88579447
has comment: http://stackoverflow.com/comment/88579629
has comment: http://stackoverflow.com/comment/88579533
has answer: http://stackoverflow.com/a/50786673
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88579442
has comment: http://stackoverflow.com/comment/88579650
has comment: http://stackoverflow.com/comment/88579214
accepted answer: http://stackoverflow.com/a/50786673
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50737279
has answer: http://stackoverflow.com/a/50741914
answer count: 6
duplicate of: http://stackoverflow.com/q/12723751
type: Question
has comment: http://stackoverflow.com/comment/88497003
has comment: http://stackoverflow.com/comment/88483338
has answer: http://stackoverflow.com/a/50737557
linked to: http://stackoverflow.com/q/12723751
has answer: http://stackoverflow.com/a/50738088
accepted answer: http://stackoverflow.com/a/50738088
has answer: http://stackoverflow.com/a/50737352
has comment: http://stackoverflow.com/comment/88482673
score: 0
has title: How to make a program which "translates" letters?
has answer: http://stackoverflow.com/a/50737733
has body: I am trying to make a program, which replaces letters with other letters, for instance 'Q' into 'R', or 'D' into 'U'. I'm stuck here: def dna(): seq = input('Enter the sequence:') list1 = list(seq) for i in seq: if i == 'A': seq[i] = 'T' return ''.join(list1) This returns an error. What can I do?
tagged with: python
tagged with: biopython
has comment: http://stackoverflow.com/comment/88482028
tagged with: bioinformatics
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50737453
possible better answer: http://stackoverflow.com/a/50737733

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/50720740
tags question: http://stackoverflow.com/q/50766100
tag name: kivy-language

http://stackoverflow.com/q/50803526
has title: Python, regex - retrieve keywords from strings within dictionary
tagged with: python
has comment: http://stackoverflow.com/comment/88613356
tagged with: dictionary
has body: I have a dictionary with long strings as keys and sets as values. I also have a list of keywords. For example, dict1 = {"This is the long key with 9 in it.": {'value1'}, 'I have another long string with 4 and keyword': {'value2'}} list_of_keywords = ['this', 'is', 'a', 'keyword'] I would like to filter the new values into a tuple with either digits or words from the keyword list. So the above dictionary would be turned into final_dict1 = {('9', 'this', 'is'): {'value1'}, ('4', 'keyword'): {'value2'}} I have two regular expressions below that work and I have a function that does most of what I would like it to do: import re digit_regxep = r"\s\b\d{1,3}\b" keyword_regexp = r"\b({})\b" def filter_dict_values_for_keyword_digit(dict1, keyword_regexp, digit_regexp, list_of_keywords, sep='|'): formatted_regexp = regexp.format(sep.join(keyword_regexp)) word = re.compile(formatted_regexp) word1 = re.compile(digit_regexp) filtered_dict = dict1.update(((list(re.findall(word1, k)), list(re.findall(word, k))), v) for k, v in dict1.items()) return filtered_dict but whenever I try to run this I get the following error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in filter_dict_values_for_two_keywords File "&lt;stdin&gt;", line 5, in &lt;genexpr&gt; File "/anaconda/lib/python3.6/re.py", line 222, in findall return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object Is there something that I am misunderstanding about the composition of my dictionary that is affecting my function? I am having trouble determining whether or not it is a problem in the function or if it is because my initial values are a set as opposed to a string.
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50803573
type: Question
accepted answer: http://stackoverflow.com/a/50803573
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88613285
tagged with: findall
has comment: http://stackoverflow.com/comment/88613154
answer count: 1
favorite count: 0
tagged with: python-3.x
downvote count: 2

http://stackoverflow.com/comment/92903914
score: 0
type: AnswerComment
type: Comment
has text: Did you find an answer? I'm running into the same thing. I"ve tried string.encode in the geolite2.lookup call but still get error.
comment on: http://stackoverflow.com/a/50820879

http://stackoverflow.com/q/50771084
tagged with: python
upvote count: 2
type: UnansweredQuestion
tagged with: calculation
has body: Hi I am working on a calculator program and am trying to solve an issue where when a zero is in front of the calculation. For example, 03+03 an error occurs as I am using eval. the calculation must be kept in string form as eval uses the string form and gives me the sum. I need to find a way to get rid of the zeros before the calculation happens through eval.
score: -2
has comment: http://stackoverflow.com/comment/88549667
type: Question
downvote count: 4
has answer: http://stackoverflow.com/a/50771268
answer count: 1
has title: How to get rid of zeros in a calculation so an error does not occur Python
tagged with: calculator
has comment: http://stackoverflow.com/comment/88549666
favorite count: 0
tagged with: eval

http://stackoverflow.com/a/59520201
downvote count: 0
answers question: http://stackoverflow.com/q/50806334
score: 1
type: Answer
upvote count: 1
has body: Question: Keep from moving focus to window On X11, you can set the -type attribute: self.wm_attributes("-type", 'dock') 'dock' will working for me not to grab the focus, but are not supported by all window managers. Reference: wm attributes Communicate with window manager A list of types -type Requests that the window should be interpreted by the window manager as being of the specified type(s). This may cause the window to be decorated in a different way or otherwise managed differently, though exactly what happens is entirely up to the window manager. 'dock' indicates a dock/panel feature, import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.wm_attributes("-type", 'dock') for n in range(64, 68): btn = tk.Button(self, text=chr(n), takefocus=0) btn.bind("&lt;Button-1&gt;", self.on_click) btn.pack() def on_click(self, event): w = event.widget print(w['text']) if __name__ == '__main__': App().mainloop()

http://stackoverflow.com/comment/115200447
comment on: http://stackoverflow.com/a/50829107
type: AnswerComment
has text: while you're right about the general implementation of seq2seq, in the tutorial the OP is asking about there's no batch (B=1), so the bmm is redundant - see my answer
score: 0
type: Comment

http://stackoverflow.com/a/50733993
answers question: http://stackoverflow.com/q/50733978
has comment: http://stackoverflow.com/comment/88475757
score: 3
upvote count: 3
has body: Use between with boolean indexing: df = df[df['price'].between(10, 100)] print (df) id price 0 1 10.0 3 4 100.0 If dont need include values 10 and 100: df = df[df['price'].between(10, 100, inclusive=False)]
downvote count: 0
has comment: http://stackoverflow.com/comment/126623803
type: Answer

http://stackoverflow.com/q/50807507
tagged with: macos
has answer: http://stackoverflow.com/a/54926622
favorite count: 0
has answer: http://stackoverflow.com/a/50893981
has answer: http://stackoverflow.com/a/57700335
tagged with: python
has body: I am trying to install numpy on macOS X but after executing the command pip install numpy I am getting the error: Environment error :[error 13]: permission denied : 'usr/local/bin/f2py How do I fix it?
has answer: http://stackoverflow.com/a/57720740
has answer: http://stackoverflow.com/a/53027283
upvote count: 105
type: UnansweredQuestion
has title: Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"
linked to: http://stackoverflow.com/q/42988977
has answer: http://stackoverflow.com/a/63598024
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52341097
has answer: http://stackoverflow.com/a/56857828
has answer: http://stackoverflow.com/a/55716389
answer count: 11
has answer: http://stackoverflow.com/a/69075106
has answer: http://stackoverflow.com/a/64059034
linked to: http://stackoverflow.com/q/1880321
has comment: http://stackoverflow.com/comment/88788261
score: 104
downvote count: 1

http://stackoverflow.com/q/50784806
type: Question
has answer: http://stackoverflow.com/a/50985340
tagged with: database
score: -1
answer count: 2
has body: I have made a bot in Python using Chatterbot module. It works fine but whenever I launch it, It starts training itself again that I already did. I want that it loads the sql database file when it starts and dont train itself again and again it is very irritating need help....
tagged with: sql
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/59646720
has comment: http://stackoverflow.com/comment/88579181
tagged with: bots
upvote count: 2
has title: How to load sql database files instantly in python chatbot?
downvote count: 3

http://stackoverflow.com/comment/88584632
comment on: http://stackoverflow.com/q/50752302
type: QuestionComment
has text: Hello everyone, I already resolved this issue. `export PYTHONDONTWRITEBYTECODE=1` works. The generation of `pycache` folder is in the docker (I used docker as well). What I did is inside the docker, I have this `export PYTHONDONTWRITEBYTECODE=1` So it solved the issue. thank you for your help.
score: 0
type: Comment

http://stackoverflow.com/comment/88640107
comment on: http://stackoverflow.com/q/50817332
type: QuestionComment
type: Comment
has text: Get rid of the `attrs` package (a typical "good idea that is actually not such a good idea") and use custom descriptors (computed attributes) doing the validation. My 2 cents...
score: 2

http://stackoverflow.com/comment/88703526
type: Comment
type: QuestionComment
has text: https://pandas.pydata.org/pandas-docs/stable/merging.html
score: 0
comment on: http://stackoverflow.com/q/50850337

http://stackoverflow.com/comment/88703858
comment on: http://stackoverflow.com/q/50850489
score: 0
type: Comment
has text: also, just using SHA256 hash is not a good way of storing passwords. It has bad consequences if your db is ever compromised (your user's passwords could be attacked with a rainbow table easily). You should use a longer algorithm, and use salt on your password. have a look at bcrypt libraries.
type: QuestionComment

http://stackoverflow.com/q/50783545
has title: Pandas: reshaping a dataframe with duplicate entries
score: 1
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50783587
downvote count: 0
answer count: 1
has body: I have a Pandas DF (brief snippet below) called df deathtype height deaths 0 AMS 4900 1 1 AMS 5150 1 2 AMS 5300 1 3 Avalanche 5350 14 4 Avalanche 5600 4 5 Avalanche 5700 1 6 Avalanche 5800 17 7 Unexplained 8500 1 8 Unexplained 8560 1 I'm trying to reshape the data into the following; deaths 1 4 14 17 deathtype AMS 4900,5150,5300 0 0 0 Avalanche 5700 5600 5350 5800 Unexplained 8500, 8560 0 0 0 I know that a pivot_table can't achieve this since the aggfunc uses the mean for duplicate values which means that for all the deaths values of 1, the mean will be recorded. A pivot_table gives me the following; df.pivot_table(index='deathtype', columns='deaths', values='height', fill_value='0') deaths 1 4 14 17 deathtype AMS 5116.666667 0 0 0 Avalanche 5700.000000 5600 5350 5800 Unexplained 8530.000000 0 0 0 I'm looking for some advice on how to go about doing this. It looks like a pivot_table isn't the right approach here. Can someone please provide some pointers.
favorite count: 0
tagged with: pandas
tagged with: reshape
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50783587

http://stackoverflow.com/q/50851054
has comment: http://stackoverflow.com/comment/88705290
type: Question
score: 3
linked to: http://stackoverflow.com/q/3206344
tagged with: flask
has title: how can I load svg file into my python flask page?
answer count: 2
has comment: http://stackoverflow.com/comment/88705139
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has body: So I want to put an svg file into my page(not as an image, as an xml element) - need it like this so I could dynamically change elements within the page. and I made a simple code that I thought it'll do: @app.route('/map_test/') def test(): svg = render_template('file.svg') response = make_response(svg) response.content_type = 'image/svg+xml' return render_template('test.html', svg=response) and test.html: {% block content %} &lt;section&gt; {{ svg }} &lt;/section&gt; {% endblock %} ....which just returned &lt;Response 126181 bytes [200 OK]&gt; instead of svg element... so... what do I need to do in order to get this to work?
tagged with: python
has answer: http://stackoverflow.com/a/50852201
duplicate of: http://stackoverflow.com/q/3206344
upvote count: 4
tagged with: http://stackoverflow.com/tag/svg
has answer: http://stackoverflow.com/a/50853313

http://stackoverflow.com/comment/88534785
has text: If one character isn't a vowel you immediately conclude that the whole word doesn't have any vowel inside?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50763508

http://stackoverflow.com/comment/88550225
type: Comment
has text: It works now. Thank you. but how can i apply this on a video?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50771223

http://stackoverflow.com/q/50711550
has body: I am having trouble with my code, I don't know what I can do. My code has a variable "bheight" and it splits into parts automatically(which I have coded and is good) but I want it so whenever it goes through the "def Building():" code it adds 1 onto bheight[0] so when it loops through next time it'll be bheight[1]. import turtle turtle.bgcolor("orange") blist = input('Please enter builidng heights e.g. "50 30 60"') leo = turtle.Turtle() bsplit = blist.split() bheight = list(map(int, bsplit)) size = len(bsplit) def Water(): leo.penup() leo.goto(-200,0) leo.fillcolor('midnightblue') leo.begin_fill() for a in range (1,3): leo.forward(400) leo.right(90) leo.forward(150) leo.right(90) leo.end_fill() leo.pendown() def Building(): for x in range (0,int(size)): leo.fillcolor('darkslategrey') leo.begin_fill() leo.left(90) leo.forward(bheight[-1+1]) leo.right(90) leo.forward(20) leo.right(90) leo.forward(bheight[-1+1]) leo.left(90) leo.end_fill() def Reset(): leo.towards(leo) Water() Building()
tagged with: python
has title: Python Coding Need Assistance
has answer: http://stackoverflow.com/a/50711649
downvote count: 1
type: Question
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/50726779
answer count: 2
favorite count: 0
tagged with: turtle-graphics
type: UnansweredQuestion

http://stackoverflow.com/q/50792318
has body: I am working with a dataset of about 400.000 x 250. I have a problem with the model yielding a very good R^2 score when testing it on the training set, but extremely poorly when used on the test set. Initially, this sounds like overfitting. But the data is split into training/test set at random and the data set i pretty big, so I feel like there has to be something else. Any suggestions? Splitting dataset into training set and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(df.drop(['SalePrice'], axis=1), df.SalePrice, test_size = 0.3) Sklearn's Linear Regression estimator from sklearn import linear_model linReg = linear_model.LinearRegression() # Create linear regression object linReg.fit(X_train, y_train) # Train the model using the training sets # Predict from training set y_train_linreg = linReg.predict(X_train) # Predict from test set y_pred_linreg = linReg.predict(X_test) Metric calculation from sklearn import metrics metrics.r2_score(y_train, y_train_linreg) metrics.r2_score(y_test, y_pred_linreg) R^2 score when testing on training set: 0,64 R^2 score when testing on testing set: -10^23 (approximatly)
has comment: http://stackoverflow.com/comment/88591894
type: Question
score: 0
answer count: 1
has title: Linear regression: Good results for training data, horrible for test data
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/50793298
tagged with: python
has comment: http://stackoverflow.com/comment/88613970
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: linear-regression

http://stackoverflow.com/q/50850819
type: Question
accepted answer: http://stackoverflow.com/a/50850860
possible better answer: http://stackoverflow.com/a/50850931
has answer: http://stackoverflow.com/a/50850931
score: 4
upvote count: 4
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50850860
tagged with: python
type: AnsweredQuestion
has body: As far as I have read it seems like Jinja is only for creating HTML files. Can it be used for creating python files as well?
has title: Is It possible to create Python files using Jinja
tagged with: jinja2

http://stackoverflow.com/comment/88572566
score: 0
has text: Yes, this is what I want.
type: Comment
comment on: http://stackoverflow.com/a/50782994
type: AnswerComment

http://stackoverflow.com/comment/88436867
type: AnswerComment
type: Comment
has text: You can play with Integrity Protection to get access to protected areas: https://developer.apple.com/library/archive/documentation/Security/Conceptual/System_Integrity_Protection_Guide/ConfiguringSystemIntegrityProtection/ConfiguringSystemIntegrityProtection.html
comment on: http://stackoverflow.com/a/50713012
score: 0

http://stackoverflow.com/comment/88556649
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50774763
has text: Does your input always contain only ones or is this just an example that could be also `arr=np.arange(5 * 7).reshape(5,7)`?
type: Comment

http://stackoverflow.com/comment/88841078
type: Comment
has text: It's most likely the blanks
type: AnswerComment
comment on: http://stackoverflow.com/a/50827993
score: 0

http://stackoverflow.com/comment/88573379
has text: yes it does. sort of. I do get a black windows on top of my control window and it really bothers me. Is there a way to get the control window just to show the trackbars? maybe i want to add a few buttons later but this helps for the start.
type: Comment
comment on: http://stackoverflow.com/q/50720820
score: 0
type: QuestionComment

http://stackoverflow.com/q/50825652
favorite count: 0
linked to: http://stackoverflow.com/q/42913798
has title: How to stop a for loop in a list once an element in a dictionary (contained in the list) has been found
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50825690
downvote count: 2
has comment: http://stackoverflow.com/comment/88656164
has body: I have just started to learn Python and I have a question regarding the FOR LOOP and how to make it loop until he finds a specific element in a list and then make it stop without iterating through the other list's elements : I created two python file: 1) Database.py 2) App.py In "Database.py" I have the following code: books = [] In "App.py" I have this code: def prompt_read_book(): book_to_search = input("Write the NAME of the book you want to mark as 'READ':\n") for book in database.books: if book_to_search.lower() == book["name"]: print(f"The book '{book_to_search}' is now marked as READ") book["read"] = True print("-" * 40) else: print(f"Sorry but the book {book_to_search} is not in the database") print("-" * 40) When I have more than 1 book (2 or more) in my books list, the function I wrote does not work as I expected. Example: books = [{"name": "Fight Club", "author": "Chuck Palahniuk", "read": False}, {"name": "Homo Deus", "author": "Yuval Noah Harari", "read": False}] I want to "mark as READ" only the book with name "Fight Club". So I input the name "Fight Club". The book_to_search variable becomes: Fight Club The function runs correctly and changes the {"read": False} to {"read": True} HOWEVER Since I am in the for loop, it keeps iterating and it also prints: "Sorry but the book Homo Deus is not in the database" (My understanding of the problem is the following: since we are in a for loop, the program checks one by one all the elements of the list to find if they match with the input the user wrote. Thus I need a way to stop the for loop once the matching element has been found). What I would like is the following: -Once the book_to_search matches with the element of the dictionary, the for loop has to stop without iterating the others list' elements -If the book_to_search does to match with any element in the dictionary, I want to print "Sorry but the book {book_to_search} is not in the database"
upvote count: 1
has comment: http://stackoverflow.com/comment/88656207
type: Question
duplicate of: http://stackoverflow.com/q/42913798
score: -1
accepted answer: http://stackoverflow.com/a/50825690
answer count: 1

http://stackoverflow.com/q/50716794
has comment: http://stackoverflow.com/comment/88444838
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88445516
has comment: http://stackoverflow.com/comment/88445056
has title: How to open PyQt app from separate python process
tagged with: python
has body: I was wondering if it is possible to open a PyQT app (with a QmainWindow) from a separate python process by running something like the subprocess command. My PyQt app is executable from command line as PyQT_App.py arg1 The code for running the app is quite long, but the basic structure is def call_app(arg1): class AppWindow(QtGui.QMainWindow): def __init__(self,arg1): do stuff... ... app = QtGui.QApplication([]) win = AppWindow(arg1) print sys.exit(app.exec_()) return app if __name__=="__main__": call_app(arg1) and I was hoping to run import subprocess subprocess.Popen(["PyQT_App.py", "arg1"]) If I do this and check system monitor, it appears that the app has been launched, but the main window does not appear. Is there an obvious reason this does not work that I am missing? Is there a simple solution?
tagged with: subprocess
has answer: http://stackoverflow.com/a/50721264
upvote count: 1
type: Question
tagged with: pyqt
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/50709171
has answer: http://stackoverflow.com/a/50709230
score: 0
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: map-function
type: UnansweredQuestion
has body: So I tried this z=0 x = [2, 3, 4] y = [4, 5] t = map(lambda v : map(lambda w : v + w, y), x) # t == [[6, 7], [7, 8], [8, 9]] z = sum(t, []) our loops iterate through x and y and add the sum of the values to z. For some reason, I get the error: TypeError: can only concatenate list (not "map") to list Any ideas?
tagged with: python
tagged with: dictionary
tagged with: lambda
has answer: http://stackoverflow.com/a/50709640
type: Question
has title: Using encapsulated Lambda functions in Python to calculate the sum of lists

opencv
tags question: http://stackoverflow.com/q/50854146
type: Tag
tags question: http://stackoverflow.com/q/50853133
tags question: http://stackoverflow.com/q/50783658
tags question: http://stackoverflow.com/q/50795684
tags question: http://stackoverflow.com/q/50776354
tags question: http://stackoverflow.com/q/50831530
tags question: http://stackoverflow.com/q/50756306
tags question: http://stackoverflow.com/q/50851219
tags question: http://stackoverflow.com/q/50847827
tags question: http://stackoverflow.com/q/50793126
tags question: http://stackoverflow.com/q/50711919
tags question: http://stackoverflow.com/q/50807554
tags question: http://stackoverflow.com/q/50854070
tags question: http://stackoverflow.com/q/50797435
tags question: http://stackoverflow.com/q/50812654
tags question: http://stackoverflow.com/q/50738541
tags question: http://stackoverflow.com/q/50850319
tags question: http://stackoverflow.com/q/50786376
tags question: http://stackoverflow.com/q/50716186
tags question: http://stackoverflow.com/q/50797863
tags question: http://stackoverflow.com/q/50822858
tags question: http://stackoverflow.com/q/50703087
tags question: http://stackoverflow.com/q/50720820
tags question: http://stackoverflow.com/q/50747636
tags question: http://stackoverflow.com/q/50811464
tags question: http://stackoverflow.com/q/50792863
tags question: http://stackoverflow.com/q/50854235
tags question: http://stackoverflow.com/q/50726744
tags question: http://stackoverflow.com/q/50821447
tags question: http://stackoverflow.com/q/50733604
tags question: http://stackoverflow.com/q/50758799
tags question: http://stackoverflow.com/q/50851658
tags question: http://stackoverflow.com/q/50850937
tags question: http://stackoverflow.com/q/50826733
tags question: http://stackoverflow.com/q/50736708
tags question: http://stackoverflow.com/q/50821145
tags question: http://stackoverflow.com/q/50849686
tags question: http://stackoverflow.com/q/50743476
tags question: http://stackoverflow.com/q/50713398
tags question: http://stackoverflow.com/q/50831093
tags question: http://stackoverflow.com/q/50817442
tags question: http://stackoverflow.com/q/50716214
tags question: http://stackoverflow.com/q/50808428
tags question: http://stackoverflow.com/q/50731170
tags question: http://stackoverflow.com/q/50788432
tags question: http://stackoverflow.com/q/50778184
tags question: http://stackoverflow.com/q/50700053
tag name: opencv
tags question: http://stackoverflow.com/q/50761199
tags question: http://stackoverflow.com/q/50777951
tags question: http://stackoverflow.com/q/50850692
tags question: http://stackoverflow.com/q/50787891
tags question: http://stackoverflow.com/q/50748775
tags question: http://stackoverflow.com/q/50710297
tags question: http://stackoverflow.com/q/50784144
tags question: http://stackoverflow.com/q/50783177
tags question: http://stackoverflow.com/q/50748725
tags question: http://stackoverflow.com/q/50707714
tags question: http://stackoverflow.com/q/50723257
tags question: http://stackoverflow.com/q/50747064
tags question: http://stackoverflow.com/q/50812665
tags question: http://stackoverflow.com/q/50759678
tags question: http://stackoverflow.com/q/50803957
tags question: http://stackoverflow.com/q/50768963
tags question: http://stackoverflow.com/q/50776671
tags question: http://stackoverflow.com/q/50829870
tags question: http://stackoverflow.com/q/50744094
tags question: http://stackoverflow.com/q/50713023
tags question: http://stackoverflow.com/q/50783617
tags question: http://stackoverflow.com/q/50792915
tags question: http://stackoverflow.com/q/50702186
tags question: http://stackoverflow.com/q/50768295
tags question: http://stackoverflow.com/q/50795543
tags question: http://stackoverflow.com/q/50728186
tags question: http://stackoverflow.com/q/50783047
tags question: http://stackoverflow.com/q/50784148
tags question: http://stackoverflow.com/q/50701410
tags question: http://stackoverflow.com/q/50753075
tags question: http://stackoverflow.com/q/50794490

http://stackoverflow.com/comment/88638947
score: 0
comment on: http://stackoverflow.com/q/50816915
has text: Kindly add some code you did. Also the dataframe.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88467291
comment on: http://stackoverflow.com/q/50702983
score: 0
has text: Your file is called a package in Python. To import a package you should use `import main`, not `import main.py`. Otherwise, it is not very obvious what you are trying to accomplish - for example, where is your notebook - is it in notebooks directory? If so, you could just use `import os; os.chdir('..')` to set the current working directory to top-level dir in your project.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50761015
tagged with: date
has comment: http://stackoverflow.com/comment/88529475
upvote count: 0
has comment: http://stackoverflow.com/comment/88529506
has title: calculate the days between two times in python with presicion value
favorite count: 0
linked to: http://stackoverflow.com/q/466345
type: Question
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50761138
has body: I have two times like t1= "2018-04-28 10:32:32+00:00" and t2= "2018-04-29 20:32:32+00:00" Need to find the number of days between these two days. Actually in the above two days there is 36(means 1 and half day) hours difference is there so I need output as 1.5(which mean 1day and half day). How this is possible with python
downvote count: 2
has comment: http://stackoverflow.com/comment/88529623
answer count: 1
linked to: http://stackoverflow.com/q/1345827
type: UnansweredQuestion

http://stackoverflow.com/q/50841425
accepted answer: http://stackoverflow.com/a/50841504
type: Question
has answer: http://stackoverflow.com/a/50842817
tagged with: python-2.7
score: 0
answer count: 2
tagged with: shell
tagged with: linux
tagged with: python
has body: I have a python command that runs as follows: python script.py -file 1000G_EUR_Phase3_plink/1000G.NUMBER --out GTEx_Cortex.chrNUMBER I would like to replace the NUMBER variable with the numbers 1:20. So if I replace NUMBER with 1 it would look like this: python script.py -file 1000G_EUR_Phase3_plink/1000G.1 --out GTEx_Cortex.chr1 and this on the second iteration (if I replace it with 2): python script.py -file 1000G_EUR_Phase3_plink/1000G.2 --out GTEx_Cortex.chr2 But I don't want to keep manually changing NUMBER 20 times. I want to automate the entire thing. How can I do this in the command prompt? Should this be done in VIM or is there another way in python? Thanks!
has answer: http://stackoverflow.com/a/50841504
has title: Run Python Script with variable in arguments
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50842817

http://stackoverflow.com/a/50756898
answers question: http://stackoverflow.com/q/50756758
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88522130
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88521928
has comment: http://stackoverflow.com/comment/88522172
has comment: http://stackoverflow.com/comment/88521913
has body: One possible a bit dynamic solution is omit fill_value=0: table = a.pivot_table(index='customer_id', columns='hour', values='size') print (table) hour 0 1 customer_id 1 1.0 18.0 2 NaN 7.0 a = table.agg(['count','sum']) b = table.T.agg(['count','sum']).T print (table.fillna(0).append(a).join(b)) 0 1 count sum 1 1.0 18.0 2.0 19.0 2 0.0 7.0 1.0 7.0 count 1.0 2.0 NaN NaN sum 1.0 25.0 NaN NaN
type: Answer
has comment: http://stackoverflow.com/comment/88522184
has comment: http://stackoverflow.com/comment/88522115
accepted answer of: http://stackoverflow.com/q/50756758

http://stackoverflow.com/a/50768579
type: AcceptedAnswer
downvote count: 0
has body: You can do so(df is the dataframe you wrote): import matplotlib import matplotlib.pyplot as plt matplotlib.style.use('ggplot') df.groupby(['Question Text','Answer Text']).sum().unstack().plot(kind='bar') plt.show() Output: You can also rotate the xlabel in this way: plt.xticks(rotation=45) but I suggest you to make the labels shorter to make it more clear
accepted answer of: http://stackoverflow.com/q/50765643
answers question: http://stackoverflow.com/q/50765643
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88637578
score: 1

http://stackoverflow.com/a/50849964
type: AcceptedAnswer
downvote count: 0
has body: Interesting question! Would this work: import math def three_motors(degree): theta1, theta2, theta3 = 150.0, 270.0, 30.0 motor1 = math.sin((degree-theta1)*(math.pi/180.0)) motor2 = math.sin((degree-theta2)*(math.pi/180.0)) motor3 = math.sin((degree-theta3)*(math.pi/180.0)) return motor1, motor2, motor3 three_motors(0) Out[40]: (-0.49999999999999994, 1.0, -0.49999999999999994) Sign convention is if your eye was at the center and you were looking out at the spinning wheels, then a positive number corresponds to a counter-clockwise rotation and a negative number corresponds to a clockwise rotation. You could divide by the norm if that's required.
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88742575
answers question: http://stackoverflow.com/q/50849484
accepted answer of: http://stackoverflow.com/q/50849484

http://stackoverflow.com/q/50725518
has answer: http://stackoverflow.com/a/50725641
has comment: http://stackoverflow.com/comment/88459291
downvote count: 3
type: Question
answer count: 2
has title: Error sre_constants.error: unbalanced parenthesis python
score: -2
has body: I have this error sre_constants.error: unbalanced parenthesis at position 3 when I execute this code : a3 = "e)/ragues" numbera3 = sum(1 for match in re.finditer(r"\b{}\b".format(a3), resp)) I thinks it's due to the regex and the ")" of a3 variable but I don't know how can I do to do to not have this error.. Thanks,
has comment: http://stackoverflow.com/comment/88459244
has answer: http://stackoverflow.com/a/50725665
favorite count: 0
has comment: http://stackoverflow.com/comment/88460160
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/74818421
upvote count: 1
score: 1
has body: The above answer from Printthis worked and thanks a lot, yes i also added conn.commit() after: row = cursor.fetchone() token=row[0] conn.commit() if i put commit before fetchone, i would get an error, sequence error sqlfetch...
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50750101

http://stackoverflow.com/q/50848772
answer count: 1
has body: the joblib module has provided a tremendously easy-to-use function Parallel to simplify coding. However, it always gathers all the results before you can access any of them. I have the need to deal with the results one by one because the results are big arrays taking a lot of memory. They cannot reside in the memory at the same time. So I need to deal with part of them first and then discard. Originally, I used futures.as_completed method from MultiprocessPool so that results can be handled immediately when they are available. But now I also want to use joblib to manage the memmaped arrays for me. Does joblib also has the interface like MultiprocessPool? I looked into the code a little and found MemmapingPool. But these is no document and examples on how to use it. I have the following questions: Do I use them the same as using MultiprocessPool? How to handle Ctrl-C in this case?
tagged with: joblib
has answer: http://stackoverflow.com/a/51356515
tagged with: python
has title: directly use MemmapingPool in python joblib module
type: AnsweredQuestion
type: Question
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/51356515
score: 0

http://stackoverflow.com/q/50756723
has comment: http://stackoverflow.com/comment/88521638
downvote count: 1
type: Question
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/50757138
tagged with: function
has answer: http://stackoverflow.com/a/50756918
has answer: http://stackoverflow.com/a/50757138
score: 0
accepted answer: http://stackoverflow.com/a/50757651
answer count: 3
has comment: http://stackoverflow.com/comment/88521208
has comment: http://stackoverflow.com/comment/88521227
has comment: http://stackoverflow.com/comment/88521210
favorite count: 0
tagged with: python
has body: Hi and thanks for checking, I am programming in Python and have a simple question to which I did not find an answer so far. I have a function output, which I need to use multiple times in an if-else statement. Here an example code: result = fooB(fooA()) if fooA()==*someComparison* else fooA() Is there an elegant way to use such a function output multiple times without calling the function multiple times (computationally expensive) or having to temporarily save the output in a previous line?
has comment: http://stackoverflow.com/comment/88521515
has comment: http://stackoverflow.com/comment/88522273
type: AnsweredQuestion
has title: Reuse function output in if-else condition without temporary
has answer: http://stackoverflow.com/a/50757651
has comment: http://stackoverflow.com/comment/88521587
upvote count: 1
linked to: http://stackoverflow.com/q/2220699

http://stackoverflow.com/q/50744133
upvote count: 1
has body: If I have a dendropy tree that I annotate with some metadata, for example with some taxonomies, how can I convert the whole tree with metadata into a ete3 object? import dendropy t = dendropy.Tree.get_from_string("(A,(B,(C,D)));", "newick") categories = {"A" : "Human", "B": "Mouse", "C": "Bee", "D": "dolphin", "E":"Ecoli"} for taxon in tree.taxon_namespace: taxon.category = categories[taxon.label] taxon.annotations.add_bound_attribute("category") I tried to pass it directly: from ete3 import PhyloTree tree = PhyloTree(t) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.4/dist-packages/ete3/phylo/phylotree.py", line 391, in __init__ TreeNode.__init__(self, newick=newick, format=format, **kargs) File "/usr/local/lib/python3.4/dist-packages/ete3/coretype/tree.py", line 211, in __init__ quoted_names=quoted_node_names) File "/usr/local/lib/python3.4/dist-packages/ete3/parser/newick.py", line 254, in read_newick raise NewickError("'newick' argument must be either a filename or a newick string.") ete3.parser.newick.NewickError: 'newick' argument must be either a filename or a newick string. You may want to check other newick loading flags like 'format' or 'quoted_node_names'. Also I tried to write as nexml format and read it with the nexml parser form ete3: tree.write_to_path(output_tree_file, nexml) from ete3 import Nexml, nexml nexml_project = Nexml() # Load content from NeXML file nexml_project.build_from_file(tree) # Extracts all the collection of trees in the project tree_collections = nexml_project.get_trees() # Select the first collection collection_1 = tree_collections[0] However it seems that the tree in nexml might be strange format as it is not recognised by the xml parser from ete3. Traceback (most recent call last): nexml_project.build_from_file(tree) File "/usr/local/lib/python3.4/dist-packages/ete3/nexml/__init__.py", line 59, in build_from_file doc = _nexml.parsexml_(fname) File "/usr/local/lib/…
tagged with: dendropy
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: ete3
tagged with: python
tagged with: etetoolkit
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has title: How to pass a Dendropy object with metadata to ete3 in python3?

http://stackoverflow.com/comment/88612129
has text: Glad to hear it! Have a nice day!
comment on: http://stackoverflow.com/a/50800931
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88480101
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50736134
type: QuestionComment
has text: Yes, In terminal I execute the code with python3 command and it works correctly but when I use it in VS Code I get this error.

http://stackoverflow.com/comment/88641581
comment on: http://stackoverflow.com/a/50818251
has text: Will this suggest words that are not in the dictionary? For example, given the word 'sira', it should suggest words that are phonetically correct, but may not necessarily be in any dictionary.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50745793
accepted answer of: http://stackoverflow.com/q/50745690
type: Answer
answers question: http://stackoverflow.com/q/50745690
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88499538
type: AcceptedAnswer
downvote count: 0
has body: L is 720 elements long. for i in range(len(L)) corresponds to for i in range(720) You delete elements from K, so at a certain moment, K is 432 elements long, and i is 432 (you are trying to take the 433nd element of a 432-long list) Perhaps this should do the job ? import itertools Numb = 'abxxxc' L=list(itertools.permutations(list(Numb))) L=[''.join(str(i) for i in x) for x in L] K = [elt for elt in L if elt[-1] != 'x'] print(K) You should usually try to avoid using del. It is better to construct a new list containing the elements you need.

http://stackoverflow.com/q/50708768
possible better answer: http://stackoverflow.com/a/50708953
score: 1
has comment: http://stackoverflow.com/comment/88426972
has answer: http://stackoverflow.com/a/50708953
upvote count: 1
accepted answer: http://stackoverflow.com/a/50708872
type: Question
answer count: 2
downvote count: 0
has title: python drop duplicates by certain order (not `first`, `last`)
favorite count: 0
has comment: http://stackoverflow.com/comment/88426640
has answer: http://stackoverflow.com/a/50708872
has body: ID values 111 reason1 111 reason2 111 reason3 222 reason2 222 reason4 222 reason5 df.drop_duplicates(["ID"], keep='???', inplace=True) The way I know is using the drop_duplicates, but it only gives me the option first, last. I want to check that if there is reason2, then keep the record with reason2, else check reason3, etc. Basically, there is particular order, such as reason2, reason3, reason4, etc.
tagged with: pandas
has comment: http://stackoverflow.com/comment/88426627
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88551402
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50771961
has text: Thanks! I've added the line of code to the corresponding location.

http://stackoverflow.com/q/50714278
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/88437353
has body: I know it's possible to import everything in a file into another file like this: from app1.models import * But I want to do something like this: from *.models import * It means import everything inside models file from any directory. for example in this file structure /module /app1 /models.py /app2 /models.py /allModels.py I want to import all models.py files into allModels.py Is it possible? Do we have such syntax?
type: Question
score: 0
tagged with: python-import
has comment: http://stackoverflow.com/comment/88437794
has title: Import files in python
has comment: http://stackoverflow.com/comment/88437478
has comment: http://stackoverflow.com/comment/88437443
linked to: http://stackoverflow.com/q/2386714
tagged with: python
tagged with: module

http://stackoverflow.com/q/50821143
has answer: http://stackoverflow.com/a/50822150
tagged with: text
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88647779
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/88647728
possible better answer: http://stackoverflow.com/a/50821425
has answer: http://stackoverflow.com/a/50821425
accepted answer: http://stackoverflow.com/a/50822150
has comment: http://stackoverflow.com/comment/88647679
answer count: 2
tagged with: pandas
has title: Pandas Dataframe: Count unique words in a column and return count in another column
downvote count: 0
favorite count: 0
has body: I have a dataframe which has the following columns df['Album'] (contains album names of artistX ) df['Tracks'] (contains Tracks in the albums of artistX) df['Lyrics'] (contains Lyrics of the tracks ) I am trying to count the number of words in df['Lyrics'] and return a new column called df['wordcount'] as well count the number of unique words in df['Lyrics'] and return a new column called df['uniquewordcount']. I have been able to get df['wordcount'] by counting every string in df['lyrics'] minus white space. totalscore = df.Lyrics.str.count('[^\s]') #count every word in a track df['wordcount'] = totalscore df I have been able to count unique words in df['Lyrics'] import collections from collections import Counter results = Counter() count_unique = df.Lyrics.str.lower().str.split().apply(results.update) unique_counts = sum((results).values()) df['uniquewordcount'] = unique_counts And that gives me the count of all the unique words in df['Lyrics'], which is what the code is meant to do, but I want the unique words in the lyrics of each track, My python isn't great currently so the solution might be obvious to everyone but not me. I would love someone to point me in the right direction on how to get the count of the unique words for each track. expected output: Album Tracks Lyrics wordcount uniquewordcount A Ball Ball is life and Ball is key 7 5 Pass Pass me the hookah Pass me the 7 4 what I got: Album Tracks Lyrics wordcount uniquewordcount A Ball Ball is life and Ball is key 7 9 Pass Pass me the hookah Pass me the 7 9
has comment: http://stackoverflow.com/comment/88647645
upvote count: 2
tagged with: python

http://stackoverflow.com/q/50832896
score: 0
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/88670955
type: UnansweredQuestion
has title: call python script from flask_restful
type: Question
has comment: http://stackoverflow.com/comment/88670166
has answer: http://stackoverflow.com/a/50857691
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/88670427
has body: I would like to call python script using flask_restful and I followed below link to implement https://dev.to/aaahmedaa/create-restapi-for-your-python-scripts-using-flask-with-15-line-of-code-10ml I execute the command python app.py from command prompt and passed image as input from browser as below http://localhost:5000/ImageClassification/image1.jpg I am getting output as {"data": null} It suppose to get output as shown below from cnn_classification.py script, please let me know where I did mistake. cnn_classification.py: import os import subprocess os.getcwd() os.chdir("D:/LH_data/LH_tensorflow/tensorflow-for-poets-2/") def lh_image_classification(input_image): subprocess.call(['python', '-m', 'scripts.label_image', '--graph=tf_files/optimized_graph.pb', '--image=' + input_image]) app.py: import cnn_classification from flask import Flask, request from flask_restful import Resource, Api from sys import argv app = Flask(__name__) api = Api(app) #input_image = argv[1] class imageClassification(Resource): def get(self, input_image): return {'data': cnn_classification.lh_image_classification(input_image)} api.add_resource(imageClassification, '/ImageClassification/&lt;input_image&gt;') if __name__ == '__main__': app.run()

http://stackoverflow.com/comment/88594273
has text: Possible duplicate of [Pythonically add header to a csv file](https://stackoverflow.com/questions/20347766/pythonically-add-header-to-a-csv-file)
score: 0
comment on: http://stackoverflow.com/q/50794024
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50788087
score: 2
downvote count: 0
type: Answer
has body: Seems like what you want is some "syntax sugar"... If you have a lambda function such as l = lambda x: datetime(*[int(_) for _ in x.split('/')[::-1]]) than you can just wrap your dates using day/month/year and the function will convert that for you. df[(df['date'] &gt; l("04/10/2018")) &amp; (df['date'] &lt; l("05/10/2018"))] My function is just an example, you can define whatever function you'd think fits. There are infinite possibilities
answers question: http://stackoverflow.com/q/50787981
upvote count: 2

http://stackoverflow.com/comment/88574269
score: 0
type: QuestionComment
type: Comment
has text: That sounds reasonable, and should handle the slash correctly. I think the key part is how are you doing the extraction? That's the bit that sounds like it needs to be fixed. That is, what happens when you do `print(returned_string)`? I'm expecting the slashes will have disappeared. Your extraction method needs to make sure it preserves these slashes as they are important.
comment on: http://stackoverflow.com/q/50782488

http://stackoverflow.com/q/50820243
linked to: http://stackoverflow.com/q/50704932
upvote count: 1
tagged with: python
favorite count: 0
downvote count: 0
has title: Setting the style of the center marker in a matplotlib polar plot
has answer: http://stackoverflow.com/a/50821353
accepted answer: http://stackoverflow.com/a/50821353
tagged with: plot
type: AnsweredQuestion
score: 1
tagged with: matplotlib
has body: I asked a related question in Adding tick marks on Thetagrid lines of a polar plot and was able to answer most of that question. However, I can't find a way to style the center marker. This marker is always the color and style of the marker below the last theta grid label (TG06 in the example plot). I've noted this in a comment inside of the decorate_ticks function. How do I style the center marker differently than the marker below the last theta grid label? import numpy as np import matplotlib.pyplot as plt class Radar(object): def __init__(self, fig, titles, label, rect=None): if rect is None: rect = [0.05, 0.15, 0.95, 0.75] self.n = len(titles) self.angles = [a if a &lt;=360. else a - 360. for a in np.arange(90, 90+360, 360.0/self.n)] self.axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i) for i in range(self.n)] self.ax = self.axes[0] # Show the labels self.ax.set_thetagrids(self.angles, labels=titles, fontsize=14, weight="bold", color="black") for ax in self.axes[1:]: ax.patch.set_visible(False) ax.grid(False) ax.xaxis.set_visible(False) self.ax.yaxis.grid(False) for ax, angle in zip(self.axes, self.angles): ax.set_rgrids(range(1, 6), labels=label, angle=angle, fontsize=12) # hide outer spine (circle) ax.spines["polar"].set_visible(False) ax.set_ylim(0, 6) ax.xaxis.grid(True, color='black', linestyle='-', zorder=1) # draw a line on the y axis at each label ax.tick_params(axis='y', pad=0, left=True, length=6, width=1, direction='inout') def decorate_ticks(self, axes): for idx, tick in enumerate(axes.xaxis.majorTicks): # get the gridline gl = tick.gridline gl.set_marker('o') gl.set_markersize(15) if idx == 0: gl.set_markerfacecolor('#003399') elif idx == 1: gl.set_markerfacecolor('#336666') elif idx == 2: gl.set_markerfacecolor('#336699') elif idx == 3: gl.set_markerfacecolor('#CC3333') elif idx == 4: gl.set_markerfacecolor('#CC9933') # this doesn't get used. The center doesn't seem to be different than 5 else: gl.set_markerfacecolor('#000000') if…
type: Question
answer count: 1

http://stackoverflow.com/comment/88455276
type: Comment
score: 1
has text: [split](https://docs.python.org/2/library/stdtypes.html#str.split) on `\n\n` or whatever the line separator character is **doubled** and get the 0-index element.
comment on: http://stackoverflow.com/q/50723416
type: QuestionComment

http://stackoverflow.com/q/50745486
has comment: http://stackoverflow.com/comment/88499091
type: AnsweredQuestion
has title: How to use pyunpack to unpack .7z file?
has body: Im trying to unpack a 7z file but got an error. This is the code: from pyunpack import Archive Archive('E:/Desktop/vnpt2/2_1_0_2841.7z').extractall('E:/Desktop/vnpt2/new') And this is error: Traceback (most recent call last): File "E:\Desktop\vnpt2\zip.py", line 2, in &lt;module&gt; Archive('E:/Desktop/vnpt2/2_1_0_2841.7z').extractall('E:/Desktop/vnpt2/new') File "C:\Python27\lib\site-packages\pyunpack\__init__.py", line 90, in extractall self.extractall_patool(directory, patool_path) File "C:\Python27\lib\site-packages\pyunpack\__init__.py", line 62, in extractall_patool raise PatoolError('patool can not unpack\n' + str(p.stderr)) pyunpack.PatoolError: patool can not unpack patool error: error extracting E:\Desktop\vnpt2\2_1_0_2841.7z: could not find an executable program to extract format 7z; candidates are (7z,7za,7zr), How can I fix it?
type: Question
has answer: http://stackoverflow.com/a/59305379
upvote count: 12
has answer: http://stackoverflow.com/a/60155378
score: 12
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/88498676
downvote count: 0
possible better answer: http://stackoverflow.com/a/60155378
favorite count: 0
accepted answer: http://stackoverflow.com/a/59305379
tagged with: python

http://stackoverflow.com/comment/88443896
type: QuestionComment
type: Comment
has text: What is your Django version? There was a usage of redirect as `return redirect('contents-occasion-step-1', args=(form_data.pk,))` maybe you can try this.
comment on: http://stackoverflow.com/q/50707719
score: 0

http://stackoverflow.com/q/50840511
tagged with: google-cloud-platform
has title: google.cloud import storage: cannot import storage
accepted answer: http://stackoverflow.com/a/50841078
downvote count: 0
favorite count: 0
answer count: 3
upvote count: 51
tagged with: python
has answer: http://stackoverflow.com/a/58063253
has answer: http://stackoverflow.com/a/64575479
score: 51
has answer: http://stackoverflow.com/a/50841078
possible better answer: http://stackoverflow.com/a/64575479
type: AnsweredQuestion
has body: I tried to run the code bellow by following the google tutorials i found here: https://cloud.google.com/docs/authentication/production def implicit(): from google.cloud import storage # If you don't specify credentials when constructing the client, the # client library will look for credentials in the environment. project = 'my_project_name' storage_client = storage.Client(project=project) # Make an authenticated API request buckets = list(storage_client.list_buckets()) print(buckets) implicit() But it keeps giving me the following error: Traceback (most recent call last): File "[PATH]/scratch_5.py", line 13, in &lt;module&gt; implicit() File "[PATH]/scratch_5.py", line 2, in implicit from google.cloud import storage ImportError: cannot import name storage Could someone help me with this?
tagged with: google-cloud-storage
type: Question

http://stackoverflow.com/a/50846623
answers question: http://stackoverflow.com/q/50845338
upvote count: 26
accepted answer of: http://stackoverflow.com/q/50845338
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can maintain the datetime functionality and set the time portion to 00:00:00 with normalize. df.index = df.index.normalize() # For non-Index datetime64[ns] dtype columns you use the `.dt` accessor: # df['column'] = df['column'].dt.normalize() import pandas as pd df = pd.DataFrame([1, 2, 3, 4], index=pd.date_range('2018', periods=4, freq='H')) df.index = df.index.normalize() print(df) # 0 #2018-01-01 1 #2018-01-01 2 #2018-01-01 3 #2018-01-01 4 Looking at the index: df.index #DatetimeIndex(['2018-01-01', '2018-01-01', '2018-01-01', '2018-01-01'], dtype='datetime64[ns]', freq=None) And the values are Timestamps: df.index[0] #Timestamp('2018-01-01 00:00:00')
has comment: http://stackoverflow.com/comment/138523726
score: 26

http://stackoverflow.com/a/69026327
has body: In TensorFlow 2.6.0 (I am not sure if it was possible in earlier versions or no): https://www.tensorflow.org/api_docs/python/tf/data/Dataset#__len__ Dataset.__len__()
answers question: http://stackoverflow.com/q/50737192
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/138955636

http://stackoverflow.com/a/50815162
has comment: http://stackoverflow.com/comment/88638833
has comment: http://stackoverflow.com/comment/132450838
type: Answer
has comment: http://stackoverflow.com/comment/88637215
has body: before i givet you work code i would like tell you: 1) in tk (and Python) ttk.Button(root, text='Last Date', command=example1) you concatenate name with function (command=example1), but if you change on ttk.Button(root, text='Last Date', command=example1()) you will get two windows, because you run automatic function 2) i am not sure that is is good practices, but it situation you will need create two functions almost the same, but with one different print('next_date="{}"'.format(cal.selection_get())) here is full work code: import tkinter as tk from tkinter import ttk from tkcalendar import Calendar def example1(): def print_sel(): print('last_date="{}"'.format(cal.selection_get())) def quit1(): top.destroy() top = tk.Toplevel(root) cal = Calendar(top, font="Arial 14", selectmode='day', cursor="hand1", year=2018, month=2, day=5) cal.pack(fill="both", expand=True) ttk.Button(top, text="ok", command=print_sel).pack() ttk.Button(top, text="exit", command=quit1).pack() def example2(): def print_sel(): print('next_date="{}"'.format(cal.selection_get())) def quit1(): top.destroy() top = tk.Toplevel(root) cal = Calendar(top, font="Arial 14", selectmode='day', cursor="hand1", year=2018, month=2, day=5) cal.pack(fill="both", expand=True) ttk.Button(top, text="ok", command=print_sel).pack() ttk.Button(top, text="exit", command=quit1).pack() root = tk.Tk() s = ttk.Style(root) s.theme_use('clam') ttk.Button(root, text='Last Date', command=example1).pack(padx=10, pady=10) ttk.Button(root, text='Next Date', command=example2).pack(padx=10, pady=10) root.mainloop() if use classes and get values: import tkinter as tk from tkinter import ttk from tkcalendar import Calendar class t: def __init__(self): self.root = tk.Tk() self.s = ttk.Style(self.root) self.s.theme_use('clam') self.last_date = 'Last Date' self.next_date = 'Next Date' self.b1 = ttk.Button(self.root, text='Last Date', command=self.example1).pack(padx=10, pady=10) self.b2 = ttk.Button(self.root, text='Next Date', command…
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88636529
downvote count: 0
has comment: http://stackoverflow.com/comment/88663371
answers question: http://stackoverflow.com/q/50814594
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88638110
accepted answer of: http://stackoverflow.com/q/50814594
has comment: http://stackoverflow.com/comment/88644702

http://stackoverflow.com/comment/88653198
has text: If you view source on the page the form action is indeed http not https. Using chrome developer tools and setting preserve log I see a 307 redirect returned via HTTP. Honestly I didn't look at the protocol of the responses after that. I am familiar with Firefox dev tools consolidating multiple requests that include redirects and only showing the last response received.
type: Comment
comment on: http://stackoverflow.com/a/50822862
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88726154
type: Comment
has text: Updated the Q with code sample to better see the shapes.
type: AnswerComment
comment on: http://stackoverflow.com/a/50860401
score: 0

http://stackoverflow.com/q/50772060
tagged with: scikit-learn
favorite count: 0
upvote count: 5
type: UnansweredQuestion
tagged with: python
has body: Assuming we have a Pandas dataframe and a scikit-learn model, trained (fit) using that dataframe. Is there a way to do row-wise prediction? The use case is to use the predict function to fill in empty values in the dataframe, using an sklearn model. I expected that this would be possible using the pandas apply function (with axis=1), but I keep getting dimensionality errors. Using Pandas version '0.22.0' and sklearn version '0.19.1'. Simple example: import pandas as pd from sklearn.cluster import kmeans data = [[x,y,x*y] for x in range(1,10) for y in range(10,15)] df = pd.DataFrame(data,columns=['input1','input2','output']) model = kmeans() model.fit(df'input1','input2',df['output']) df['predictions'] = df'input1','input2'.apply(model.predict,axis=1) The resulting dimensionality error: ValueError: ('Expected 2D array, got 1D array instead:\narray=[ 1. 10.].\nReshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.', 'occurred at index 0') Running predict on the whole column works fine: df['predictions'] = model.predict(df'input1','input2') However, I want the flexibility to use this row-wise. I've tried various approaches to reshape the data first, for example: def reshape_predict(df): return model.predict(np.reshape(df.values,(1,-1))) df'input1','input2'.apply(reshape_predict,axis=1) Which just returns the input with no error, whereas I expect it to return a single column of output values (as an array). SOLUTION: Thanks to Yakym for providing a working solution! Trying a few variants based on his suggestion, the easiest solution was to simply wrap the row values in square brackets (I tried this previously, but without the 0 index for the prediction, with no luck). df['predictions'] = df'input1','input2'.apply(lambda x: model.predict([x])[0],axis=1)
downvote count: 0
type: Question
score: 5
has answer: http://stackoverflow.com/a/50772129
has title: Row-wise prediction over Pandas dataframe by passing sklearn.predict to df.apply
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/50845338
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50845561
accepted answer: http://stackoverflow.com/a/50846623
upvote count: 24
type: Question
has title: Remove time portion of DateTime index in pandas
score: 24
has body: When I query a service through their API for daily data, they throw in a time portion which is equal to whatever time the query was made. So my pandas dataframe looks like this when I called the function at 14:54:36 - 2018-05-16 14:54:36 1024.75 1008.25 ... 39221 242897 2018-05-17 14:54:36 1017.00 1002.00 ... 35361 241132 2018-05-18 14:54:36 1015.75 1002.75 ... 49090 242938 2018-05-21 14:54:36 1034.50 1020.75 ... 56950 243316 2018-05-22 14:54:36 1043.75 1028.50 ... 49724 247874 2018-05-23 14:54:36 1049.00 1036.25 ... 46256 253609 2018-05-24 14:54:36 1059.75 1047.00 ... 65352 259617 As this is daily data, the time portion is useless. When I do: data = pd.read_csv(StringIO(data), index_col=0, header=None,names=['High','Low','Open','Close','Volume','OpenInterest']) data.index = pd.to_datetime(data.index,format="%Y-%m-%d") The format doesn't seem to work. The DateTime index still contains time. Any idea how I can remove the time portion?
answer count: 3
has answer: http://stackoverflow.com/a/52132627
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/50846623
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88694625
has answer: http://stackoverflow.com/a/50845561

http://stackoverflow.com/comment/94313558
type: Comment
has text: The script is scraping a website and getting each entry in a variable and before writing it to a file I create a dictionary of all variables and write the dictionary as an entry one at a time
comment on: http://stackoverflow.com/a/50888495
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88414637
has text: I just uninstalled everything, including python and all the packages, and installed from scratch and just worked.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50699840
type: AnswerComment

http://stackoverflow.com/q/50733903
upvote count: 1
tagged with: subplot
tagged with: matplotlib
type: UnansweredQuestion
tagged with: dataframe
tagged with: pandas
has answer: http://stackoverflow.com/a/50734331
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50734230
type: Question
tagged with: python
has title: Pandas bar plot always creates an empty subplot
has body: I want to plot two bar plots in one figure, but I always fail. Below is my code: def plot_data_group2(factor,xlabel): #xlabel: 这里是为了x轴坐标设置的 survived_count=survived_passenger.groupby([factor])['PassengerId'].count() fig_1 = plt.figure() #指定figure的宽和高，单位为英寸 fig_1=plt.subplot(121) survived_count.plot(kind='bar') fig_1.set_title('Survived rate group by ' + factor) fig_1.set_xlabel(factor) fig_1.set_ylabel("count of the survived") plt.xticks(rotation=0) #旋转x轴的标签至水平（默认是和x轴垂直的） fig_2=plt.subplot(122) survived_count_group = titanic_data.groupby([factor, 'Survived'])['PassengerId'].count().unstack() survived_rate = survived_count_group.apply(lambda x: (x / x.sum() * 100),axis=1) survived_rate.plot(kind='bar') fig_2.set_title('Survived rate group by ' + factor) fig_2.set_xlabel(factor) fig_2.set_ylabel("ration of " + factor + " in the survived") plt.xticks(rotation=0) #plt.show() plot_data_group2('Age_group',['under 18','young','not old','old']) The output is the following:
answer count: 2

http://stackoverflow.com/q/50803589
answer count: 1
has body: I have a delimiter separated dat file that I'm looking to manipulate. Below is what it looks like at the start: 'Field1'|'Field2'|'Field3'|'Field4'|'Field5' 'George'|'June'|'11'|'1943'|'Yes' 'Steve'|'May'|'17'|'1905'|'' 'Jerry'|'March'|'01'|'1993'|'Yes' Field 5 I will consider to be my "wiping" field. So, let's say if Field 5's value is "Yes", then wipe all other fields that the user selected. I essentially want to have the user select the "wipe" field, have the user select the "to be wiped" fields, and it will export a new DAT file. For example, the user says wiping field = Field 5 The "to be wiped" fields are Field 2 and Field 3 Once complete, the script should also remove the wiping field altogether The output should look like as follows: 'Field1'|'Field2'|'Field3'|'Field4' 'George'|''|''|'1943' 'Steve'|'May'|'17'|'1905' 'Jerry'|''|''|'1993' I've been working with the csv module but I'm having a difficult time. Any input would be appreciated. Thanks
has answer: http://stackoverflow.com/a/50804635
type: Question
has comment: http://stackoverflow.com/comment/88613283
tagged with: python
tagged with: python-3.x
score: 0
has title: DAT file manipulation in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88613330

http://stackoverflow.com/comment/88655977
type: QuestionComment
score: 1
has text: `for i,search in enumerate(listsearch)` and the print `i`, not `a`.
comment on: http://stackoverflow.com/q/50825516
type: Comment

http://stackoverflow.com/q/50708155
score: 0
tagged with: apache-spark
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50711630
has body: I have a data frame like below in pyspark. +---+-------------+----+ | id| device| val| +---+-------------+----+ | 3| mac pro| 1| | 1| iphone| 2| | 1|android phone| 2| | 1| windows pc| 2| | 1| spy camera| 2| | 2| spy camera| 3| | 2| iphone| 3| | 3| spy camera| 1| | 3| cctv| 1| +---+-------------+----+ I want to populate some columns based on the below lists phone_list = ['iphone', 'android phone', 'nokia'] pc_list = ['windows pc', 'mac pro'] security_list = ['spy camera'] ucg_list = ['ipad'] I have done like below. from pyspark.sql.functions import col, when, lit from pyspark.sql.types import IntegerType df1 = df.withColumn('phones', lit(None).cast(IntegerType())).withColumn('pc', lit(None).cast(IntegerType())).withColumn('security', lit(None).cast(IntegerType())).withColumn('null', lit(None).cast(IntegerType())).withColumn('ucg', lit(None).cast(IntegerType())) import pyspark.sql.functions as F df1.withColumn('cat', F.when(df1.device.isin(phone_list), 'phones').otherwise( F.when(df1.device.isin(pc_list), 'pc').otherwise( F.when(df1.device.isin(security_list), 'security'))) ).groupBy('id', 'phones', 'pc', 'security', 'null', 'ucg').pivot('cat').agg(F.count('cat')).show() output I am receiving +---+------+----+--------+----+----+----+---+------+--------+ | id|phones| pc|security|null| ucg|null| pc|phones|security| +---+------+----+--------+----+----+----+---+------+--------+ | 3| null|null| null|null|null| 0| 1| 0| 1| | 2| null|null| null|null|null| 0| 0| 1| 1| | 1| null|null| null|null|null| 0| 1| 2| 1| +---+------+----+--------+----+----+----+---+------+--------+ What I want is to create columns first based on the list names and then populate values expected output +---+------+---+------+--------+----+ | id| ucg| pc|phones|security|null| +---+------+---+------+--------+----+ | 1| 0| 1| 2| 1| 0| | 2| 0| 0| 1| 1| 0| | 3| 0| 1| 0| 1| 1| +---+------+---+------+--------+----+ How can I get what I want? Edit when I do the below df1 = df.withColumn('cat', f.when(df.device.i…
tagged with: python
has title: Pivot values to existing columns in PySpark data frame
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
tagged with: pyspark
has answer: http://stackoverflow.com/a/50711630

http://stackoverflow.com/a/50750005
has comment: http://stackoverflow.com/comment/88508323
type: Answer
has comment: http://stackoverflow.com/comment/88507935
has comment: http://stackoverflow.com/comment/88508297
has comment: http://stackoverflow.com/comment/88507951
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50749798
has comment: http://stackoverflow.com/comment/88507821
has comment: http://stackoverflow.com/comment/88508114
has body: You need to add the match field to your GameSerializer, and handle the save yourself. class GameSerializer(serializers.ModelSerializer): matches = MatchSerializer(many=True, source='match_set') def save(self): matches = self.validated_data.get('matches', []) game = super(GameSerializer, self).save() for match in matches: match['game'] = game Match.objects.create(**match) Add matches to your fields. In the validated_data of the serializer, matches will be a list of validated datas from MatchSerializer. So you can go ahead and create the Match object directly in your GameSerializer save. Ref: http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers Or if your usecase involves matches sending already existing Match object and you will only need to send the ids in your data, then use this: class GameSerializer(serializers.ModelSerializer): matches = serializers.ListField( child=serializers.PrimaryKeyRelatedField(Match)) def save(self): matches = self.validated_data.get('matches') game = super(GameSerializer, self).save() for match in matches: match.game = game match.save()
answers question: http://stackoverflow.com/q/50749798
has comment: http://stackoverflow.com/comment/88507916
has comment: http://stackoverflow.com/comment/88508256
has comment: http://stackoverflow.com/comment/88508233
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88507905
has comment: http://stackoverflow.com/comment/88507886
has comment: http://stackoverflow.com/comment/88507977

http://stackoverflow.com/q/50739732
has title: How to Covert PNG to JPEG using Pillow while image color is black?
has comment: http://stackoverflow.com/comment/88487166
type: Question
has comment: http://stackoverflow.com/comment/88487228
linked to: http://stackoverflow.com/q/7911451
upvote count: 3
tagged with: file-conversion
has answer: http://stackoverflow.com/a/50740371
accepted answer: http://stackoverflow.com/a/50740371
answer count: 1
linked to: http://stackoverflow.com/q/1962795
has comment: http://stackoverflow.com/comment/88487776
favorite count: 0
has body: I have looked at the below links to see how to convert PNG to JPG: How to get alpha value of a PNG image with PIL? PIL Convert PNG or GIF with Transparency to JPG without The conversion works as expected, but when the image color itself is not black! I have the below image: And the code is: im.convert('RGB').save('test.jpg', 'JPEG') It makes the whole picture black. How should I convert this PNG in correct format and color? The color can be anything from black to white.
tagged with: python
tagged with: http://stackoverflow.com/tag/png
tagged with: http://stackoverflow.com/tag/jpeg
type: AnsweredQuestion
score: 3
tagged with: python-imaging-library
downvote count: 0
has comment: http://stackoverflow.com/comment/94955914

http://stackoverflow.com/comment/88428257
type: QuestionComment
has text: Dicktlist? Hehe
comment on: http://stackoverflow.com/q/50709515
score: 0
type: Comment

http://stackoverflow.com/comment/88442365
has text: it prints the lines above.
comment on: http://stackoverflow.com/a/50715975
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50786939
type: AcceptedAnswer
has body: You can use dask.dataframe to lazily load data with a filter. Internally, this library works by chunking. It just hides the chunking from the user and leverages Pandas syntax to make usage seamless. import pandas as pd import numpy as np import dask.dataframe as dd # file.csv # 1 2 3 4 # 5 6 7 8 # .... # 33 34 35 36 # 37 38 39 40 # read file - LAZY df = dd.read_csv(r'C:\Temp\file.csv', header=None, sep=' ', names=['col1', 'col2', 'col3', 'col4']) # filter file - LAZY df = df[df['col4'].between(10, 25)] # apply computations and extract to pandas dataframe df = df.compute() # extract numpy array from pandas dataframe arr = df.values print(arr) array([[ 9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]], dtype=int64)
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50785017
downvote count: 0
answers question: http://stackoverflow.com/q/50785017
score: 1

http://stackoverflow.com/comment/88468265
has text: Well at first i have just list[0] = t0. Your ideas dont work
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50730237
type: Comment

http://stackoverflow.com/comment/88438535
type: QuestionComment
has text: But when I have multiple modules then first line of which module will run at first? Is it randomly selected?
score: 0
comment on: http://stackoverflow.com/q/50714877
type: Comment

http://stackoverflow.com/q/50757275
tagged with: python
answer count: 0
tagged with: gimpfu
has body: I'm currently working on a small automation script for gimp. For this, I need the function pdb.plug_in_vpropagate() My problem now is, that the result of my script differs greatly from the resualt via the same filter with the (supposingly) same parameters via the UI. The call of the python function (with the parameters) is: pdb.plug_in_vpropagate(image, drawable, 1, 0, 1, 15, 0, 255) The parameters I used in the UI are: lower threshol: 0 upper threshold: 1,0 propagating rate: 1,0 all boarders propagating value channel: yes propagating alpha channel: yes To exclude any mistakes done by other steps of my script (including values given via UI) I put everything besides this one command in comments. I also took a look in the python procedure browser in gimp to make sure that I get the right parameters. There I discovered that in the UI you can only choose values from 0 to 1 for the "upper threshold" while in the python procedure browser is written that you have to give values from 0 to 255. So to try if this may have been a mistake, I also tried the value 1 (which I used in the UI too), but the result still is totally wrong. the result via UI, what it should look like the result via the python command Does anyone know how to make the "vpropagate" function work properly in python?
type: Question
tagged with: automation
tagged with: gimp
has title: Gimpfu, vpropagate parameters
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88527699
has comment: http://stackoverflow.com/comment/88530520

http://stackoverflow.com/comment/88559072
has text: @jordanm I guess I interpreted the problem diferently that what it should be.
comment on: http://stackoverflow.com/a/50775441
score: 0
type: AnswerComment
type: Comment

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/50818952
tag name: google-oauth

web
tags question: http://stackoverflow.com/q/50703572
tags question: http://stackoverflow.com/q/50699780
tags question: http://stackoverflow.com/q/50731954
type: Tag
tags question: http://stackoverflow.com/q/50771146
tag name: web
tags question: http://stackoverflow.com/q/50841850
tags question: http://stackoverflow.com/q/50852056
tags question: http://stackoverflow.com/q/50786529
tags question: http://stackoverflow.com/q/50824031
tags question: http://stackoverflow.com/q/50744144
tags question: http://stackoverflow.com/q/50767257

http://stackoverflow.com/a/50808471
type: AcceptedAnswer
score: 0
type: Answer
has body: File this under "never mind". The problem was due to a missing slash after the url. I was copying the link from Azure, but it doesn't add it automatically and I missed it in the code.
accepted answer of: http://stackoverflow.com/q/50808403
answers question: http://stackoverflow.com/q/50808403

http://stackoverflow.com/q/50842506
tagged with: python-3.x
type: Question
has body: The project structure is something like below: project/ |-- src/ | |--sub_project1/ | |--__init__.py | |-- main.py | |-- __init__.py | |-- requirements.txt | |-- setup.py |-- README.md |-- MANIFEST.in I started with setuptools in order to package my project. I think I am successful in creating a distribution but I am not sure with the later process of how to thoroughly set up the project in the virtual environment (venv) to run src\sub_project1\main.py. Steps I followed so far: Created requirements.txt through pipreqs. Created setup.py, which sets include_package_data=True to include requirements.txt mentioned in MANIFEST.in setup.py: from setuptools import setup, find_packages import pkg_resources with open("README.md", "r") as fh: long_description = fh.read() # read data from .txt as str, decode and then split to get a list of requirements requirements = pkg_resources.resource_string('src', 'requirements.txt').decode("utf-8").split() setup( ... packages=find_packages(), include_package_data=True, install_requires=requirements, ... ) MANIFEST.in: include *.txt Generated the distribution: python setup.py sdist bdist_wheel Now, since I have packaged the project, I want to create a Virtual environment, set up dependencies and run it. I started by creating a virtual environment, using python -m venv &lt;DIR&gt;. And have one of the below two commands to install all requirements: pip install -r requirements.txt or pip install ./downloads/SomeProject-1.0.4.tar.gz which does install all the required packages. But, from here onwards I am not sure about to steps to actually execute my script. How to actually execute the project in the created virtual environment? Moreover, some questions I have: Is setup.py used only to install requirements? How are the above two commands different in terms of output? Apart from installing requirements, do you manually need to put the project files in the needed directory? As pip install *.tar.gz didn't unzip any project files! How to use e…
tagged with: python
has answer: http://stackoverflow.com/a/50852412
tagged with: python-packaging
tagged with: setuptools
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50955527
has comment: http://stackoverflow.com/comment/88707555
has comment: http://stackoverflow.com/comment/88864025
type: UnansweredQuestion
downvote count: 0
score: 1
has title: Up and Running a project packaged through 'setuptools' in a venv with all requirements
favorite count: 0

http://stackoverflow.com/comment/88411271
has text: *"How do I tell ax2 that there is already n=1 lines drawn on that axis"* There is no line drawn on `ax2` yet, so it chooses the first color of the colorcycle.
comment on: http://stackoverflow.com/q/50701005
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88412877
has text: @Hari I dont have any!
type: Comment
comment on: http://stackoverflow.com/q/50701322
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88530727
type: Comment
type: QuestionComment
has text: If you are not setting CONCURRENT_REQUESTS (I think the default is 16) you could try altering that value. Sometimes lowering it can provide a better speed overall.
score: 0
comment on: http://stackoverflow.com/q/50761567

http://stackoverflow.com/comment/88468495
comment on: http://stackoverflow.com/a/50729923
type: Comment
has text: The answer provided by @ascriptor should be accepted since it was provided first and fully addresses the question.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88678366
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50836786
has text: I solved the above error. The CSV File had few entries not as per format. It has to be like <num>,<num> ie 3,4. But few entries were <num>, ie 3, .
type: AnswerComment

http://stackoverflow.com/a/50742015
score: 0
type: Answer
has body: why you are keeping head in the memory. You can directly use the loop and stop when you reach 1 million.
answers question: http://stackoverflow.com/q/50741843

http://stackoverflow.com/comment/88576287
comment on: http://stackoverflow.com/q/50784722
has text: @RajatJain I didn't mean change of code, I need the function to be called when there is a change in values of fields of few Model entries or when few specific Django Views/APIs get called.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50704701
type: Question
score: 0
answer count: 2
tagged with: probability-distribution
has comment: http://stackoverflow.com/comment/140204598
tagged with: statistics
tagged with: model-fitting
has answer: http://stackoverflow.com/a/50704888
linked to: http://stackoverflow.com/q/6620471
has title: Trying to fit Pearson3 probability distribution using scipy
type: UnansweredQuestion
tagged with: python
has body: I am trying to understand how to fit a probability distribution function, such as Pearson type 3, to a data set (specifically, mean annual rainfall in an area). I've read some questions about this, but I still miss something and the fitting doesn't get right. As for now my code is this (the specific data file can be downloaded from here): import numpy as np import matplotlib.pyplot as plt from scipy.stats import pearson3 year,mm = np.loadtxt('yearly_mm_sde_boker_month_1960_2016.csv',delimiter=',').T fig,ax=plt.subplots(1,2,figsize=(2*1.62*3,3)) ax[0].plot(year,mm) dump=ax[1].hist(mm) size = len(year) param = pearson3.fit(mm) pdf_fitted = pearson3.pdf(year, *param[:-2], loc=param[-2], scale=param[-1]) * size plt.plot(pdf_fitted, label=dist_name) plt.xlim(0,len(year)) plt.legend(loc='upper right') plt.show() What am I missing?
tagged with: scipy
has answer: http://stackoverflow.com/a/79500966

http://stackoverflow.com/a/50752466
upvote count: 1
answers question: http://stackoverflow.com/q/50729353
downvote count: 0
has body: Your template loop is not right. A plot in your plots list looks like: (script, div). You loop over all the plot in plots, but then you also do this: {% for part in plot %} {% endfor %} The first iteration over a part includes the script twice, then the next iteration includes the div twice. This causes things to be duplicated.
type: Answer
score: 1

http://stackoverflow.com/q/50700151
type: Question
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/50701040
answer count: 1
downvote count: 0
tagged with: gitlab-ci
favorite count: 0
has title: Unit test coverage with GitLab CI
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50701040
tagged with: pytest-cov
tagged with: unit-testing
has body: I'm trying to set up a unit test coverage tool for one of the Python projects. I managed to script the GitLab CI YML file, but it runs into errors when triggered. Here is the error that I get: ImportError while importing test module '/builds/user1/myProj/tests/test_run.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: tests/test_run.py:12: in &lt;module&gt; from data import prepare_data as pd E ImportError: No module named 'data' =========================== 1 error in 0.06 seconds ============================ In the test_run.py, I have the following imports: sys.path.append(os.path.abspath('../src')) from data import prepare_data as pd Here is my GitLab CI YML file: - pip install -r requirements.txt - python -m pytest -v --cov=myproj/ --cache-clear --color=yes tests/ I have the needed __init__.py in the src folder. The src folder has a sub folder called data which I'm importing in my unit test as: sys.path.append(os.path.abspath('../src')) Is there something that I'm missing?

http://stackoverflow.com/a/50908416
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50736689
answers question: http://stackoverflow.com/q/50736689
type: Answer
has body: You'll need to use the pytz library from pytz import timezone ... ... defaultfilters.date(event['test'].start_time.astimezone(timezone('Asia/Kolkata')), 'DATETIME_FORMAT')

http://stackoverflow.com/q/50853128
favorite count: 0
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
has body: I am writing a python script that polls two sensors using threading, which records the data from these sensors to a csv log file. Each sensor records data at a different rate (sensor 1: 1 sample/second; sensor 2: 10 samples/second) - and are implemented with threading.Thread. Ideally, every time sensor 2 makes a new reading, the data from both sensors would be recorded to the log file - or any variation on this. My unfamiliarity with multithreading means I am not sure about best practice here and grappling to find a sensible way to implement this: the options I have considered are: Have data logging as a separate thread, waiting for an event. When sensor 2 takes a new reading, sensor 2 sets the event, and the logging occurs data logging as a timer based separate thread, writing new data as it finds it passing a data logging function as an argument for the sensor polling function All of these options could be implemented but they all seem a bit clunky - what would you suggest is the most pythonic way to approach this?
has title: Python polling to log sensor data
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50853243
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88717349
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50722829
has text: I'm fine with hacks (I just need the bloody graph to plot), but using "ax2.fill_between(np.linspace(min(plt.xlim()), max(plt.xlim()), len(df)), ymin, ymax, color=color, alpha=0.3, where=(df.traffic_density > 10) & (df.traffic_density < 40))", I'me getting the same 2 shaded regions.

http://stackoverflow.com/comment/88590939
type: Comment
has text: @sudonym Edited my answer
type: AnswerComment
comment on: http://stackoverflow.com/a/50792395
score: 0

http://stackoverflow.com/a/52561267
answers question: http://stackoverflow.com/q/50731242
upvote count: 0
has body: You may also use the plain and simple python eval as follows: import pandas as pd from io import StringIO mystr = StringIO("""a {'word': 5.7} {'khfds': 8.34}""") df = pd.read_csv(mystr) df['a'] = df['a'].apply(eval) print(df['a'].apply(lambda x: type(x))) 0 &lt;class 'dict'&gt; 1 &lt;class 'dict'&gt; Name: a, dtype: object
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/114745265
downvote count: 3

http://stackoverflow.com/comment/88577896
type: QuestionComment
has text: See for example https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop/1835036 . Using threads with tkinter will probably get you into problems unless you really know what you are doing. That's probably why the answer you accepted on your previous question, which recommended you to use them, got downvoted: it's bad advice.
score: 0
comment on: http://stackoverflow.com/q/50784959
type: Comment

http://stackoverflow.com/q/50710718
possible better answer: http://stackoverflow.com/a/50711040
has comment: http://stackoverflow.com/comment/88430766
has comment: http://stackoverflow.com/comment/88430734
tagged with: django-models
score: 0
has answer: http://stackoverflow.com/a/50712290
answer count: 3
accepted answer: http://stackoverflow.com/a/50712290
has comment: http://stackoverflow.com/comment/88430737
has answer: http://stackoverflow.com/a/50711040
has comment: http://stackoverflow.com/comment/88430787
tagged with: python
has comment: http://stackoverflow.com/comment/88430964
has body: I have created a movie renting app in Django 2.0 and Python 3.6. I am getting an error on BoundField and I am trying to add the new movie to the existing table in the database like movie_name and price. Bellow is mentioned code: #module.py file from django.db import models from django.forms import ModelForm class Customer(models.Model): f_name = models.CharField(max_length=50) l_name = models.CharField(max_length=50) address = models.CharField(max_length=125) cell = models.IntegerField(blank=True, null=True) class Movie(models.Model): genre = models.CharField(max_length=50) price = models.FloatField(blank=True, null=True) flag = models.BooleanField(default=True) user_id = models.ForeignKey('Customer', on_delete=models.SET_NULL, null=True) views.py code from django.shortcuts import render from .models import Customer, Movie # from django.http import HttpResponseRedirect from .forms import MovieForm, CustForm def dashboard(request): customer_data = Customer.objects.all() context = {'Customer_List': customer_data} return render(request, 'movie_renting_app/home.html', context) def movie_list(request): movie_data = Movie.objects.all() context = {"Movie_List": movie_data} return render(request, 'movie_renting_app/all_movies.html', context) def rented_movies(request): rented_movie = Movie.objects.filter(flag=True) context = {"Rented_Movies_List": rented_movie} return render(request, 'movie_renting_app/rent.html', context) def add_movies(request): if request.POST: form = MovieForm() print(request) m = Movie(genre=form['genre'], price=form['price'], flag=form['flag']) m.save() return movie_list(request) else: form = MovieForm() return render(request, 'movie_renting_app/new_movie.html', {'form': form}) def add_customer(request): if request.POST: form = request.POST print(request) c = Customer(f_name=form['f_name'], l_name=form['l_name'], address=form['address'], cell=form['cell']) c.save() return dashboard(request) else: form = CustForm() return render(request, 'movie_renting…
tagged with: django-views
has title: Why an Internal Server Error ? TypeError : float() argument must be a string or a number, not 'BoundField'
has comment: http://stackoverflow.com/comment/88430839
tagged with: django
has answer: http://stackoverflow.com/a/50711259
tagged with: django-forms
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/50791158
has body: I have installed AVbin10 in my computer(os windows7),As i running my program as the error comming.The error is “IOError Integer divided by zero” Import pyglet pyglet.lib.load_library (‘c:\\user\\administrator\\desktop\\avbin64’) pyglet.have_avbin=True music=pyglet.media.load (‘c:\\user\\administrator\\desktop\\1.mp3’) music.play () pyglet.app.run()
has comment: http://stackoverflow.com/comment/88590017
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88589358
answer count: 0
type: Question
has title: trouble on playing mp3 with pyglet module
score: 0

http://stackoverflow.com/comment/101575139
comment on: http://stackoverflow.com/a/50756187
has text: @ted, why do you pass `tok` to `report`? The function does nothing with this argument, so imo it can be omitted.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88430037
has text: Nice man thank you, that works perfectly for my needs. I appreciate it
comment on: http://stackoverflow.com/a/50710459
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88585248
score: 0
type: AnswerComment
type: Comment
has text: 1. I need the original source directory hierarchy to replicate same structure within destination directory 2. Also, some of the file names are 260 characters in length
comment on: http://stackoverflow.com/a/50789483

http://stackoverflow.com/comment/122633850
score: 1
comment on: http://stackoverflow.com/a/50766337
type: AnswerComment
type: Comment
has text: `df.index.levels[1]` is useful but it does not keep the order of the items in that index level(!)

http://stackoverflow.com/comment/88667290
type: Comment
has text: File "<ipython-input-45-6c512429cd24>", line 2 data1['full_scores_list'].apply(lamda v: v in com_vals) ^ SyntaxError: invalid syntax My df id data1
comment on: http://stackoverflow.com/a/50831430
score: 0
type: AnswerComment

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/50760873
tags question: http://stackoverflow.com/q/50849560

http://stackoverflow.com/q/50838326
has body: I'm trying to write code where after giving name and email input in the command prompt it should update the data in the Postgres database. English is not my first language, but I'll try my best to describe my situation. So basically when typing in the cmd: python myProgram.py jacob8 jacob8@company.com It should update the jacob8 in the username column and jacob8@company.com in the email column. So my code is like this: import sys import psycopg2 conn = psycopg2.connect("user=nana password=nana dbname=nana host=localhost") cur = conn.cursor() userName = str(sys.argv[1]) eMail = str(sys.argv[2]) cur.execute('UPDATE "table" SET "user_name" = userName WHERE "address"=%s', (mac,)) cur.execute('UPDATE "table" SET "user_email" = eMail WHERE "address"=%s', (mac,)) conn.commit() ...but for some reason userName that Im using where I'm trying to SET, doesn't recognize the userName that I assigned as sys.argv[1] and the same goes about eMail. When I'm adding them inside single quotation marks, it's recognized, but it messes up (makes the rest of the line green) the rest of the line starting with WHERE. I also tried to put sys.argv[1] and sys.argv[2] straight into SET line (like UPDATE "table" SET "user_name" = sys.argv[1] WHERE) but it gives me the same kind of problem - it wont recognize the import sys anymore. What am I missing here? It's clearly something to do with how to add quotation marks but I can't find the correct way..
has title: Variables (assigned from CLI arguments) not recognized in SQL query
has comment: http://stackoverflow.com/comment/88681036
tagged with: postgresql
tagged with: python
has comment: http://stackoverflow.com/comment/88680902
has comment: http://stackoverflow.com/comment/88680831
has comment: http://stackoverflow.com/comment/88680851
type: AnsweredQuestion
tagged with: command-prompt
score: 0
has answer: http://stackoverflow.com/a/50838459
type: Question
has comment: http://stackoverflow.com/comment/88680989
accepted answer: http://stackoverflow.com/a/50838459
answer count: 1

http://stackoverflow.com/comment/88657909
has text: Is there a way of doing this without using anaconda navigator which I cannot access on a Mac?
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50826519

http://stackoverflow.com/comment/88467905
has text: ^yup: `\((.*?meh.*?)\)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50730070
score: 2

http://stackoverflow.com/a/50753830
has body: It's simply the L2 norm (a.k.a Euclidean norm) of the tensor. Below is a reproducible illustration: In [15]: x = torch.randn(3, requires_grad=True) In [16]: y = x * 2 In [17]: y.data Out[17]: tensor([-1.2510, -0.6302, 1.2898]) In [18]: y.data.norm() Out[18]: tensor(1.9041) # computing the norm using elementary operations In [19]: torch.sqrt(torch.sum(torch.pow(y, 2))) Out[19]: tensor(1.9041) Explanation: First, it takes a square of every element in the input tensor x, then it sums them together, and finally it takes a square root of the resulting sum. All in all, these operations compute the so-called L2 or Euclidean norm.
type: AcceptedAnswer
downvote count: 0
upvote count: 32
has comment: http://stackoverflow.com/comment/89977779
type: Answer
accepted answer of: http://stackoverflow.com/q/50753477
score: 32
answers question: http://stackoverflow.com/q/50753477

http://stackoverflow.com/comment/88521638
type: Comment
has text: If `lambda` becomes "too small" for what you're trying to do within it, then yes, write a `def` function instead.
score: 1
comment on: http://stackoverflow.com/q/50756723
type: QuestionComment

http://stackoverflow.com/a/50838539
type: Answer
has comment: http://stackoverflow.com/comment/88723619
answers question: http://stackoverflow.com/q/50834506
has body: @Mahantesh, as I read and understood from your code, I've tried to implement your problem in my way. I have taken varible names same as you've taken. I've also used json module for pretty printing the dictionary. Please check the below code and let me know if you need any changes. Don't forget to check the output. import json def get_averages(): student_marks = {}; successful_trials = 0; # IT IS NOT REQUIRED, JUST TO MAKE PROGRAM USER FRIENDLY while True: try: # CREATE A LIST # ['Rishikesh', '90', '95', '90', '80', '85', '70'] line = input('\n('+ str(successful_trials + 1) + ') ENTER NAME SEPARATED BY 1 OR MORE SCORES SPACE SEPARATED (TYPE exit TO STOP) &gt;&gt;&gt; ').split(); if len(line) &gt; 0: # NAME OF STUDENT =&gt; 'Rishikesh' name = line[0]; if name.lower() == 'exit': # IF USER ENTERS ANYTHING STARTING WITH exit (stop iteration) break # SCORES OF A STUDENT (INTEGERS) =&gt; [90, 95, 90, 80, 85, 70] scores = [int(number) if (int(number) &gt;= 0 and int(number) &lt;= 100) else -1 for number in line[1:]] if not scores: print("\nERROR: INPUT SHOULD HAVE AT LEAST 1 OR MORE SCORES (SPACE SEPARATED)") continue else: print("\nERROR: INPUT SHOULD HAVE NAME FOLLOWED BY AT LEAST 1 OR MORE SCORES (SPACE SEPARATED)") continue if -1 not in scores: # SCORES ARE IN RANGE MEANS IT IS NOT LIKE [90, -1, 90, -1, 85, 70] student_marks[name] = { "scores": scores, "average": sum(scores) / len(scores) # AVERAGE } else: print("\nERROR: ENTERED SCORES ARE NOT IN RANGE") continue successful_trials += 1; # IF EVERYTHING PASSED except Exception as error: print('\nERROR OCCURED: ', error) print("\nPLEASE ENTER CORRECT VALUE") continue return student_marks; # DICTIONARY OF DICTIONARIES if __name__ == "__main__": # CALL TO get_averages() student_marks = get_averages(); # PRETTY PRINTING DICTIONARY USING json MODULE print(json.dumps(student_marks, indent=4)); &raquo; Output1 (py3.6) H:\RishikeshAgrawani\Projects\Sof\EntrySof&gt;python EntrySof.py (1) ENTER NAME SEPARATED BY 1 OR MORE SCORES …
score: 0

http://stackoverflow.com/comment/88548357
type: QuestionComment
has text: Okay, the line inside text files in **Input** folder contains `%` and you want to replace it with `''`? Am I correct? It means the **Output** folder is going to contain the text files with lines that has no `%` in it. Thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50770218

http://stackoverflow.com/comment/88648980
type: AnswerComment
has text: @AntonvBR for what I am trying to do I had preprocessed my text and removed all special characters and punctuations, so they actually don't exist in my text. Thanks a lot for your response I am just getting into NLTK and I actually used it in finding the most used words by artistX
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50821425

http://stackoverflow.com/a/50791745
type: Answer
has comment: http://stackoverflow.com/comment/88592939
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88600269
accepted answer of: http://stackoverflow.com/q/50791696
has body: I can't make a commit to git locally from my computer in an easy way, right? You need to differentiate between pushing a branch to a server, which may require some configuration, and simply creating a commit, which can be as easy as running a command: $ git commit --allow-empty -m "Testing my hook"
answers question: http://stackoverflow.com/q/50791696
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88839626
comment on: http://stackoverflow.com/a/50842590
score: 0
type: Comment
has text: if os.path.exists(yesterday_log_file): with open(yesterday_log_file) as f: Date = json.load(f) Date1 = (Date[-1]) Comparision_Date = Date1['time'] a = datetime.strptime(Comparision_Date[:10],'%d/%m/%Y') print(a) now = datetime.strptime(datetime.now(),'%d/%m/%Y') if a == now: with open(yesterday_log_file, 'r') as r: data = json.load(r) data.append(entry) with open(log_file, mode='w') as f: json.dump(data, f, indent=3)
type: AnswerComment

http://stackoverflow.com/comment/88526497
type: QuestionComment
comment on: http://stackoverflow.com/q/50759439
score: 0
has text: @Ev.Kounis I'd call it random with respect to a constraint. You could create all the permutations of the list that satisfy the condition and then pick one randomly. One way is probably to construct a generator that enumerates these permutations and then create a random integer (edit: between 1 and #<allowed permutations>) and advance the generator as many times as that integer.
type: Comment

http://stackoverflow.com/comment/88687896
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50841165
has text: A Python 2 implementation should work fine without modification on Python 3. There are no new rules about wrapping dicts. Your messed-up implementations fail on Python 3, but they also fail on Python 2.
score: 1

http://stackoverflow.com/comment/88631669
has text: Global flags are used in the child processes that have a data relationship. For example Run_sub_thread (my_global_var_1,...), Run_sub_thread1 (my_global_var_1,...), you cannot change the my_global_var_1 variable (in the sub-process). Administrator, Practitioner, controller, security are indispensable parts of an application. **You can perform one operation at a time on the computer (for the programmer).** You can initiate different processes, but it actually means running a single transaction, since the filter will advance to a specific step. **Chronos has all the controls.**
comment on: http://stackoverflow.com/q/50757940
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88682816
score: 0
comment on: http://stackoverflow.com/q/50839396
type: Comment
type: QuestionComment
has text: @VendelUtto those are the same questions. Don't believe you're unique. The question has been asked a lot of times here.

http://stackoverflow.com/comment/88691604
has text: @DyZ It's unnecessary
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50843926
type: Comment

http://stackoverflow.com/comment/88618220
comment on: http://stackoverflow.com/q/50806053
has text: and `which pip`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88600385
type: Comment
comment on: http://stackoverflow.com/a/50784323
type: AnswerComment
score: 0
has text: if I run it into a while loop, is it possible getting duplicated data?

http://stackoverflow.com/q/50812693
has title: python - Adding a new column(Pandas Dataframe) into Postgresql Table
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88630898
type: Question
has body: How can i dynamically create new column in exisitng postgresql database table and populate Pandas Dataframe into it ? Till i have used: from sqlalchemy import create_engine engine=create_engine('postgresql+psycopg2://postgres@localhost:5432/db_name') df.to_sql('table_name', engine,if_exists='append',index=False) where df = already created panda dataframe Also i have two columns in Dataframe and i want to make separate columns for them in database table. Thanks in advance!
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/88630855
tagged with: pandas
has comment: http://stackoverflow.com/comment/88646266

http://stackoverflow.com/comment/89249090
comment on: http://stackoverflow.com/a/50757651
score: 1
type: AnswerComment
type: Comment
has text: You should at least propose an alternative working solution rather than suggesting people to compile a specific Python branch and enjoy a feature not even yet accepted... `result = fooA(); if result == bar: result = fooB(result)` looks fine to me.

http://stackoverflow.com/comment/88411194
comment on: http://stackoverflow.com/q/50700797
type: QuestionComment
has text: I have already tried that and it gave me the same importerror @cleblanc
score: 0
type: Comment

http://stackoverflow.com/comment/88701996
type: Comment
type: QuestionComment
score: 1
has text: Please include what data.txt looks like and the expected output of the script. Also, what do you mean by "_tag the words_"?
comment on: http://stackoverflow.com/q/50849547

http://stackoverflow.com/comment/88461613
type: QuestionComment
has text: multiple version of python don't have different PYTHONPATH variables
comment on: http://stackoverflow.com/q/50726520
score: 0
type: Comment

http://stackoverflow.com/q/50837066
accepted answer: http://stackoverflow.com/a/50838061
tagged with: algorithm
has comment: http://stackoverflow.com/comment/88678099
has title: Find sublists with common starting elements - python
type: Question
score: 0
has answer: http://stackoverflow.com/a/50838061
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88678293
tagged with: lcs
has comment: http://stackoverflow.com/comment/88678387
has comment: http://stackoverflow.com/comment/88677917
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88677989
has comment: http://stackoverflow.com/comment/88677831
tagged with: python
has comment: http://stackoverflow.com/comment/88678405
has body: I have a nested list: lists =[['a','b','c'], ['a','b','d'], ['a','b','e'], ['с','с','с','с']] I need to find sublists with 2 or more common (2 or more occurrences) first elements, make a single string from this elements, and make a single string from sublists, which does not contain common first elements. Sublists can go in different order, so just checking next or previous element is the wrong way, I suppose. Desired output: [['a b','c'], ['a b','d'], ['a b','e'], ['с с с с']] I tried some for loops, but with no success. I currently don't know, where to start, so any help would be appreciated. Thank you for your time!
downvote count: 1
has comment: http://stackoverflow.com/comment/88678264
type: AnsweredQuestion

http://stackoverflow.com/comment/88622752
has text: Perhaps `{k : list(map(str.lower, v)) if isinstance(v, list) else v for k, v in my_dict.iteritems()}`
type: Comment
comment on: http://stackoverflow.com/q/50808495
score: 1
type: QuestionComment

http://stackoverflow.com/comment/88456945
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50724196
has text: Before jumping to find a vectorized method, work on a loopy solution?
score: 0

http://stackoverflow.com/q/50731937
tagged with: class
linked to: http://stackoverflow.com/q/50634481
type: AnsweredQuestion
has title: Debugging in Python: IDE that shows you class instances live update
has body: Recently I was debugging some code in Python. As I stepped through my lines of code, I kept my eye on the variable explorer in my IDE (Spyder). I noticed that when it came to looking at instances of a class I had created, the variable explorer was poor. It wouldn't show me the values of member variables as I stepped through my code. I could double click on my class instance and see the values of the member variables, but they would stay static, making it useless. I would have had to double click on the instance every time I wanted to see if anything had changed. (I wrote a question about it here.) When I was programming in c++, xCode had the capability to show you the class instance and all its members, updating live, from the variable explorer. I wonder if there's an IDE that does this for Python. (Perhaps xCode itself?) I use Mac.
tagged with: ide
has answer: http://stackoverflow.com/a/50732076
type: Question
tagged with: python
score: 0
accepted answer: http://stackoverflow.com/a/50732076
answer count: 1
tagged with: debugging

http://stackoverflow.com/q/50785498
has answer: http://stackoverflow.com/a/50785594
accepted answer: http://stackoverflow.com/a/50785594
favorite count: 0
has title: Python Comparing columns of 2 csv files and writing to a new csv
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
tagged with: compare
answer count: 1
has body: I have 2 csv files each with only 1 column as below: csv file 1 : adam3us.csv created_at 6/7/2018 19:00 6/6/2018 12:00 6/6/2018 9:00 6/6/2018 9:00 6/6/2018 5:00 6/5/2018 16:00 6/5/2018 7:00 6/4/2018 16:00 csv file 2 : Bitcoin Hourly Based created_at 1/8/2017 0:00 1/8/2017 1:00 1/8/2017 2:00 1/8/2017 3:00 1/8/2017 4:00 1/8/2017 5:00 1/8/2017 6:00 6/7/2018 19:00 I am trying to write a python script that will compare each value of the csv file 2 with every entry in the csv file 1 using a loop and if the entries match, should increment a declared variable called count and then should write to a new csv file, with one column created_at containing the time that is same for both csv files and a second column with the value of count. For example, the 1st iteration will take the 1st row of csv file 2, i.e. 6/7/2018 19:00 and compare its value with every row present in the csv file 1. If the 1st row of the csv file 2 matches any row of csv file 1 then count variable should be incremented. In this case it will match the 1st row of the csv file 2 with the last row of the csv file 1 and would increment count from 0 to 1 and would write the value of created_at and the value of count to new separate csv file called output. The output file for this example should look like as below : output.csv created_at count 6/7/2018 19:00 1 The count variable should be set to 0 for every iteration and the process should repeat for every iteration. My code that I have is as below : import csv count=0 path1 = r'C:\Users\Ahmed Ismail Khalid\Desktop\Bullcrap Testing Delete Later\Bitcoin Prices Hourly Based.csv' path2 = r'C:\Users\Ahmed Ismail Khalid\Desktop\Bullcrap Testing Delete Later\adam3us.csv' path3 = r'C:\Users\Ahmed Ismail Khalid\Desktop\output.csv' with open(path1,'rt',encoding='utf-8') as csvin: reader1 = csv.reader(csvin) for row in reader1: b=row[0] with open(path2,'rt',encoding='utf-8') as csvinpu: with open(path3, 'w', newline='',encoding='utf-8') as csvoutput: writer = csv.writer(csv…

http://stackoverflow.com/comment/88584366
score: 1
comment on: http://stackoverflow.com/q/50788871
type: Comment
type: QuestionComment
has text: http://pythontutor.com/visualize.html

http://stackoverflow.com/comment/88464590
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50727341
has text: Yes, I know. But even when you load the geojson as json->dict, accessing the coordinates should give a single object (a list of two elements). So I don't directly know where the error would be coming from. You could report it to topojson.py

http://stackoverflow.com/q/50843717
answer count: 0
type: UnansweredQuestion
has body: I am looking for help to convert more complex xml to file or hive table using unix or python scripting. xml data is <EVNT_UNIX id="1234" name="USA"/> <EVNT_UNIX id="12345" name="INDIA"/> <WORKS id='W123' name ='KRISH'/> <WORKS id='W456' name ='Jhon'/> <WORKS id='W789' name ='Nancy'/> <EVNT_UNIX id="1234" name="INDIA"/> <WORKS id='W123' name ='KRISH'/> <WORKS id='W456' name ='Jhon'/> <LOCATION space='available' name ='TEST'/> .. I have tried below sample code so far in phyton and getting only specific tag details irrespective of inner tag details. doc = minidom.parse("test.xml") foldlist = doc.getElementsByTagName("fold") for fold in foldlist: fname = fold.getAttribute("name") title = fold.getElementsByTagName("title") print("fname:%s, title:%s" % (fname, title)) expected output is ENTERTAINMENT,MOVIE1,1234,USA ENTERTAINMENT,MOVIE2,12345,INDIA ENTERTAINMENT,MOVIE2,w123,KRISH ENTERTAINMENT,MOVIE2,w456,Jhon ENTERTAINMENT,MOVIE2,W789,Nancy ENTERTAINMENT,MOVIE3,1234,INDIA ENTERTAINMENT,MOVIE3,W123,KRISH ENTERTAINMENT,MOVIE3-1,4 ENTERTAINMENT,MOVIE3-1,W456,Jhon ENTERTAINMENT,MOVIE3-1,available,TEST
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88692169
score: 1
type: Question
has title: nested & repeated XML data to file or hive table using unix/python
has comment: http://stackoverflow.com/comment/88692021
has comment: http://stackoverflow.com/comment/88692499
downvote count: 0
tagged with: pyspark
has comment: http://stackoverflow.com/comment/88692262
favorite count: 0
has comment: http://stackoverflow.com/comment/88692201
tagged with: unix
tagged with: python-3.x

http://stackoverflow.com/comment/88567771
has text: Be aware that the answer may depend on the language as well.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50779869

http://stackoverflow.com/q/50744612
has title: merge two dataframes of different lengths but keep additional column values
has comment: http://stackoverflow.com/comment/88520845
score: 0
tagged with: pandas
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88500594
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: merge
downvote count: 1
has body: I am trying to merge two dataframes of different lengths, which should match on all 35 columns except for the extra two columns the second dataset has, which provides an additional and much-needed value. So in this example LR_06_18_PPD is much longer and has 35 columns, where as LR_06_18_COU_D is much shorter and has 37 columns (the first 35 being the same name as the other dataset). The extra two columns in the second dataset (Change Indicator and Date) have a flag ("D") and a date in them, respectively. When I try to merge them using: LR_06_18_COU_deleted = LR_06_18_PPD.merge(LR_06_18_COU_D,how='left') I get a dataset the length of the first dataset, which is what I want as the other dataset should be matched to the other (the second dataset should match corresponding rows in the first dataset but have in addition the Change Indicator and Date columns), however while the length is now 37 columns and Change Indicator and Date are included, the flags and dates themselves have completely vanished. The matched rows should all have "D" in the Change Indicator column, but they do not, there are no "D" flags in the merged dataset. Does anyone know how to do this but keep the values in the added columns from the second dataset? Edit: First five rows of first dataframe (for the last few columns): Proprietor (4)|Date Proprietor Added|Additional Proprietor nan 15-11-1995 Y nan 09-03-2017 N nan 26-07-2006 N nan 30-05-2007 N nan 09-02-2017 N nan 01-08-2007 N First five rows of second dataframe (for the last few columns): Additional Proprietor indicated| Change Indicator| Change Date N D 01-06-2018 N D 01-06-2018 N D 01-06-2018 N D 01-06-2018 N D 01-06-2018 N D 01-06-2018 Desired output: Proprietor (4)|Date Proprietor Added|Additional Proprietor| Change Indicator nan 15-11-1995 Y D nan 09-03-2017 N D nan 26-07-2006 N D nan 30-05-2007 N D nan 09-02-2017 N D nan 01-08-2007 N D (can't fit date column to the right). I might even be asking the wrong question. What I'm actually tryin…
has comment: http://stackoverflow.com/comment/88496936
type: Question

http://stackoverflow.com/q/50767717
score: 2
type: AnsweredQuestion
type: Question
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50767876
has body: I have two dataframes and need to either alter the second to fit the format of my first or I can create a new dataframe altogether. The first dataframe is simply... stores_df = pd.DataFrame({'Stores': ['Kroger', 'United'], 'City':['Dallas','Austin']}) Stores City 0 Kroger Dallas 1 United Austin The second is formatted like so (this is how it is given to me, I can't change it)... apples_df = pd.DataFrame({'Color': ['Red', 'Green', 'Yellow','Red', 'Green', 'Yellow'], 'Store':['Kroger','Kroger','Kroger','United','United','United'], 'Ripe': ['20','17', '14', '23', '18', '0']}) Color Stores Ripe 0 Red Kroger 20 1 Green Kroger 17 2 Yellow Kroger 14 3 Red United 23 4 Green United 18 5 Yellow United 0 My desired dataframe is the combination of both, except color value + column header 'Ripe' becomes the destination's column header and the count is added to each of the first dataframe's store row. Like so... Stores City Red Ripe Green Ripe Yellow Ripe 0 Kroger Dallas 20 17 14 1 United Austin 23 18 0 I'm somewhat familiar with merging/joining and messed around with pivot tables enough to realize I need some help. Thanks.
has answer: http://stackoverflow.com/a/50767876
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50767813
upvote count: 2
tagged with: python
tagged with: merge
has title: Pandas: Create DF with custom columns based on different DF
accepted answer: http://stackoverflow.com/a/50767813

http://stackoverflow.com/comment/88622138
score: 0
has text: Thanks @RafeeMuhammad for pointing out. I have updated. of course it doesn't look as neat but it sure is faster :)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50807324

http://stackoverflow.com/q/50754020
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/88541028
upvote count: 2
tagged with: sympy
tagged with: matrix
answer count: 1
has title: speeding up sympy matrix operations
favorite count: 0
has body: I have written a code, which uses sympy to set up a matrix and a vector. The elements of these two are sympy symbols. Then I invert the matrix and multiply the inverted matrix and the vector. This should be a generic solver for linear equation systems with n variables. I am interested in the symbolic solution of these linear equations. The problem is that my code is too slow. For instance, for n=4 it takes roughly 30 sec but for n=7 I haven't been able to solve it so far, the code ran all night (8h) and hasn't finished in the morning. This is my code. from sympy import * import pprint MM = Matrix(niso,1, lambda i,j:var('MM_%s' % (i+1) )) MA = Matrix (niso,1, lambda i,j:var('m_%s%s' % ('A', chr(66+i)) ) ) MX = Matrix (niso,1, lambda i,j:var('m_%s%s'% (chr(66+i), 'A'))) RB = Matrix(niso,1, lambda i,j:var('R_%s%s' % ('A'+chr(66+i),i+2))) R = Matrix (niso, niso-1, lambda i,j: var('R_%s%d' % (chr(65+i) , j+2 ))) K= Matrix(niso-1,1, lambda i,j:var('K_%d' % (i+2) ) ) C= Matrix(niso-1,1, lambda i,j:var('A_%d' % i)) A = Matrix(niso-1,niso-1, lambda i,j:var('A_%d' % i)) b = Matrix(niso-1,1, lambda i,j:var('A_%d' % i)) for i in range(0,niso-1): for j in range(0,niso-1): A[i,j]=MM[j+1,0]*(Add(Mul(R[0,j],1/MA[i,0]/(RB[i,0]-R[0,i])))+R[i+1,j]/MX[i,0]/(-RB[i,0]+R[0,i])) for i in range(0,niso-1): b[i,0]=MM[0,0]*(Add(Mul(1,1/MA[i,0]/(RB[i,0]-R[0,i])))+1/MX[i,0]/(-RB[i,0]+R[0,i])) A_in = Inverse(A) if niso &lt;= 4: X =simplify(A_in*b) if niso &gt; 4: X = A_in*b pprint(X) Is there a way to speed it up?
has answer: http://stackoverflow.com/a/50766961
accepted answer: http://stackoverflow.com/a/50766961
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/50724652
downvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/2612802
linked to: http://stackoverflow.com/q/240178
tagged with: python
score: 1
has title: List unchanged after called in a function
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: I'm working on a Python exercise in which I will rotate a 2d vector counterclockwise by theta degree. Here is the function I wrote import math def rotate(coordinate,theta): theta=math.radians(theta) x=coordinate[0] y=coordinate[1] coordinate[0]=x*math.cos(theta)-y*math.sin(theta) coordinate[1]=x*math.sin(theta)+y*math.cos(theta) return coordinate where coordinate is a list that contains the x and y value of the vector. However, when I try to call this function in the following way, something weird happened. points=[] test=[1,0] # a test vector #rotate the test vector 360 times for j in range(360): #print(rotate(test,j)) points.append(rotate(test,j)) #print the content of the vectors after rotation for item in points: print(item) In the code above, I have a test vector [1,0] and I would like to rotate it 360 times, and the rotated vector will be add to the list "points". However, if I print the content of list "points", I got [1.0000000000000002, -4.098804629038e-14] [1.0000000000000002, -4.098804629038e-14] [1.0000000000000002, -4.098804629038e-14] [1.0000000000000002, -4.098804629038e-14] [1.0000000000000002, -4.098804629038e-14] [1.0000000000000002, -4.098804629038e-14] [1.0000000000000002, -4.098804629038e-14] [1.0000000000000002, -4.098804629038e-14] ... which suggests the vector has not been rotated at all! I know this error can be fixed in many ways, but I still don't quite understand why this happens. Could anyone give some explanations? Thank you.
upvote count: 1
has comment: http://stackoverflow.com/comment/88457738
has comment: http://stackoverflow.com/comment/88457775
has comment: http://stackoverflow.com/comment/88457766
type: Question
linked to: http://stackoverflow.com/q/2612802

http://stackoverflow.com/q/50801442
type: Question
answer count: 1
has body: I have an interesting scenario where a date object looks like the following: '6/7/2018 7:59:11 PM' in the format m/d/yyyy h:mm:ss PM (or AM). Note that the month and hour is not padded with a zero. I have tried the following line of code using a Pandas date object: data = pd.read_csv('file.txt', sep="\t", header=None, dtype = 'str') data.columns = ['A', 'B', 'C', ...] The data.columns provides a look at the format of the file, all tab-delimited (note that is not an actual line of code, just an arbitrary way to show how the columns were labeled). The time series are in Column A. I attempted the conversion using: time = pd.to_datetime(pd.Series(data['A']), format = '%-m/%-d/%Y %-H/%M/%S %p') The return is: ValueError: '-' is a bad directive in format '%-m/%-d/%Y %-H/%M/%S %p' Any suggestions on how to go about resolving this issue would be greatly appreciated!
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/50801508
score: 0
has comment: http://stackoverflow.com/comment/88608843
has comment: http://stackoverflow.com/comment/88612785
has title: How to convert non-traditional formatted Pandas date object to datetime
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50801508

http://stackoverflow.com/a/55426513
has body: hmmlearn does not implement supervised learning (hmmlearn#109). The seqlearn library implements supervised HMMs, but does not seem to implement GMMs. The library pomegranate however seems to implement supervised Hidden Markov Models with Gaussian Mixture Models. Something like this: import pomegranate as pg X = ... y = ... distribution = pg.MultivariateGaussianDistribution model = pg.HiddenMarkovModel.from_samples(distribution, n_components=5, X=X, labels=y, algorithm='labeled')
has comment: http://stackoverflow.com/comment/129689515
downvote count: 0
answers question: http://stackoverflow.com/q/50725830
type: Answer
score: 6
upvote count: 6

http://stackoverflow.com/comment/88685333
type: QuestionComment
comment on: http://stackoverflow.com/q/50840532
score: 0
has text: I fixed the issue because I forgot to include `files` next to the directory when uploading it to Twitter but now it only uploads one instead of multiple.
type: Comment

http://stackoverflow.com/a/50776434
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50771146
upvote count: 1
downvote count: 0
has body: Ok so i figured it out.. Thanks guys! I needed to import the python script where i define User(). Rookie mistake sry...

http://stackoverflow.com/q/50706501
downvote count: 0
favorite count: 0
tagged with: python
has body: I just started working with python. I just wished to verify that suppose I pass some .root file to a method which first converts it to dataframe, them shuffles the events in them and gives the output in terms of .h5 format. def loadDF(self, rndm = 12345): df = rpd.read_root(self.file_name,self.tree_name) rndseed = rndm np.random.seed(rndseed) index = list(df.index) np.random.shuffle(index) self.df = df hdf = pd.HDFStore(self.tree_name + '.h5') hdf.put('hdf', self.df) self.hdf = hdf hdf.close() And now suppose I want to get the same shuffled dataframe from .root file. All I want is that now .h5 should not be created. Then is the following method correct? def loadDF(self, rndm = 12345): ddf = rpd.read_root(self.file_name,self.tree_name) rndseed = rndm np.random.seed(rndseed) index = list(ddf.index) np.random.shuffle(index) self.ddf = ddf In short, by "np.random.seed(same_number)" could we retrace the same randomized data?
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50718891
has title: Obtaining same random events of a dataframe
accepted answer: http://stackoverflow.com/a/50718891
upvote count: 1
has comment: http://stackoverflow.com/comment/88444727
type: Question
has comment: http://stackoverflow.com/comment/88422210
answer count: 1

http://stackoverflow.com/a/50796660
answers question: http://stackoverflow.com/q/50794251
type: Answer
has body: Here is my implementation inside a class function. This also counts inversions. You can uncomment the statements to see an alternative way of keeping track of the inversions. class MergeSort(object): ''' Instantiates an array into the object from which the method 'merge_sort' can be called. Returns number of inversions and sorted array. &gt;&gt;&gt;x = MergeSort([1,6,5,2,10,8,7,4,3,9]) &gt;&gt;&gt;x.merge_sort() (20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ''' def __init__(self, array): self.array = array def merge_sort(self): count = 0 #count_ = [] if len(self.array) &gt; 1: m = len(self.array)//2 left = self.array[:m] right = self.array[m:] leftsorter = MergeSort(left) leftsorter = leftsorter.merge_sort() rightsorter = MergeSort(right) rightsorter = rightsorter.merge_sort() # Two different ways to track inversions # numeric counter, better way count += leftsorter[0] count += rightsorter[0] # list counter #count_.append(leftsorter[0]) #count_.append(rightsorter[0]) i = 0 j = 0 k = 0 while i &lt; len(left) and j &lt; len(right): if left[i] &lt; right[j]: self.array[k] = left[i] i += 1 else: self.array[k] = right[j] j += 1 count += len(left[i:]) #count_.append(len(left[i:])) k += 1 while i &lt; len(left): self.array[k] = left[i] i += 1 k += 1 while j &lt; len(right): self.array[k] = right[j] j += 1 k += 1 return count, self.array, #sum(count_) Which runs thus. array = [1,6,5,2,10,8,7,4,3,9] x = MergeSort(array) x.merge_sort() Out[ ]: (20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
score: 0

http://stackoverflow.com/q/50701644
tagged with: generator
type: AnsweredQuestion
downvote count: 2
accepted answer: http://stackoverflow.com/a/50734097
type: Question
score: -2
has body: I don't even know if it is the proper way to put it, but I recently had trouble while trying to use a method from an object, both as a map engine (mapping closure to elements of an iterator) and as a generator of generator. I is probably much more simple to explain this through a code example: class maybe_generator(): def __init__(self, doer): self.doer = doer def give(self): for i in [1,2,3]: self.doer(i) def printer(x): print('This is {}'.format(x)) def gener(x): yield(x) p = maybe_generator(printer) p.give() g = maybe_generator(gener) print('Type of result is {}'.format(g.give())) Output is This is 1 This is 2 This is 3 Type of result is None I would have expected the g object ot be of type generator instead of NoneType. Then I wonder how it is possible to implement a function that can potentially generate a generator, or directly perform some border effect on the iterable. Thank you in advance for your help
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88412895
has title: Can generator be used through polymorphism
favorite count: 0
has answer: http://stackoverflow.com/a/50734097
tagged with: python

http://stackoverflow.com/comment/88523090
has text: Please update your question with the output you are expecting.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50757595
type: Comment

http://stackoverflow.com/a/60318766
has body: Use can use pygalmesh for surface remeshing, too. (It's a easy-to-use interface to CGAL.) import pygalmesh # create verts, faces meshio.write_points_cells("in.vtu", verts, [("triangle", faces)]) mesh = pygalmesh.remesh_surface( "in.vtu", edge_size=0.025, facet_angle=25, facet_size=0.1, facet_distance=0.001, verbose=False, ) # mesh.points, mesh.cells
answers question: http://stackoverflow.com/q/50822911
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/50750021
favorite count: 0
accepted answer: http://stackoverflow.com/a/50750338
tagged with: python
has body: I need to use a for statement in order to print each value of a list on separate lines. When using the for statement it prints the entire list on one line. Additionally when trying to print just the values in the list on the same line it appears with double brackets instead of single. Numbers=range(5,25,4) NumberSequence=[] NumberSequence.append(Numbers) print NumberSequence for elem in NumberSequence: print elem NumberSequence2=[] Numbers2=range(26,0,-7) NumberSequence2.append(Numbers2) print NumberSequence2 for digits in NumberSequence2: print digits
type: AnsweredQuestion
tagged with: pycharm
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50750338
has comment: http://stackoverflow.com/comment/88511495
score: -1
has comment: http://stackoverflow.com/comment/88507766
tagged with: for-loop
upvote count: 0
has title: How to print values in a list on separate lines? Must use a for statement.
answer count: 1

http://stackoverflow.com/a/50825599
score: 0
has body: As part of the Exploratory Data Analysis(EDA) Process, you'll want to visualize your data with all data points, identify outliers and then further investigate those outliers to figure out what to do with them. Are these outliers inaccurate values that need to be corrected? Perhaps erroneous entries in the raw data? Or are they valid data points that might point to something interesting? You can also assess the distribution of your data with df.describe() If they are errors, correct them in your dataset and don't delete them. If they are accurate, valid outliers, just exclude them from the visualization to have a better picture of the rest of your data. Does this help?
has comment: http://stackoverflow.com/comment/88674586
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50824847
answers question: http://stackoverflow.com/q/50824847
type: Answer

http://stackoverflow.com/q/50760065
has body: Given that I have: * 3D object mesh (*.obj file) * camera intrinsics * camera/object pose What I need is someway (in python) to get, for each pixel the corresponding 3D coordinates (if available) of the object model. Similarly to a depth map (https://en.wikipedia.org/wiki/Depth_map). One could do this by looking for intersections between all triangles in the mesh and the line produced by each pixel and the projection matrices. And then get the intersections that are closer to the camera. But there must be faster and more elegant way. I've been looking at ray casting and the PyOpenGL framework but I am still not sure how to do it. Can anyone help?
has title: Getting pixel coordinates on the 3D object mesh (python)
has comment: http://stackoverflow.com/comment/88531348
answer count: 1
has answer: http://stackoverflow.com/a/51385240
tagged with: geometry
accepted answer: http://stackoverflow.com/a/51385240
has comment: http://stackoverflow.com/comment/88527846
tagged with: python
tagged with: computer-vision
linked to: http://stackoverflow.com/q/48187981
has comment: http://stackoverflow.com/comment/88562844
type: AnsweredQuestion
tagged with: render
type: Question
score: 0

http://stackoverflow.com/comment/88544201
type: Comment
comment on: http://stackoverflow.com/q/50768136
type: QuestionComment
has text: You don't need to "run the bytecode". If you `import`ed it, the top-level code has already been run. If there are any functions, classes, etc., you just call them, the same way you do for anything else. The fact that you don't have the accompanying `.py` file that the `.pyc` file was compiled from doesn't matter, except that things like tracebacks or stepping through in the debugger won't be as nice.
score: 0

http://stackoverflow.com/comment/88469170
type: QuestionComment
has text: For starters, calling the function repeatedly will likely use some sort of loop. Just what depends very much on your program architecture, especially the way you've implemented movement in this world.
comment on: http://stackoverflow.com/q/50730450
score: 0
type: Comment

http://stackoverflow.com/comment/88658470
type: Comment
type: QuestionComment
has text: @9769953 - that was very useful note. gracias.
comment on: http://stackoverflow.com/q/50826754
score: 0

http://stackoverflow.com/comment/88657095
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50825530
type: AnswerComment
has text: `set()` is good for a StringVar but I think they just need the simple `get()` and `insert()` methods. Maybe add those into your example.

http://stackoverflow.com/q/50793945
tagged with: python
tagged with: regex
has title: RegEx string works when directly assigned in Python, but not from a PostgreSQL database
type: AnsweredQuestion
type: Question
linked to: http://stackoverflow.com/q/2081640
has answer: http://stackoverflow.com/a/50794209
tagged with: postgresql
score: 0
answer count: 1
has body: I have a working routine to determine the categories a news item belongs to. The routine works when assigning values in Python for the title, category, subcategory, and the search words as RegExp. But when retrieving these values from PostgreSQL as strings I do not get any errors, or results from the same routine. I checked the datatypes, both are Python strings. What can be done to fix this? # set the text to be analyzed title = "next week there will be a presentation. The location will be aat" # these could be the categories category = "presentation" subcategory = "scientific" # these are the regular expressions main_category_search_words = r'\bpresentation\b' sub_category_search_words= r'\basm microbe\b | \basco\b | \baat\b' category_final = '' subcategory_final = '' # identify main category r = re.compile(main_category_search_words, flags=re.I | re.X) result = r.findall(title) if len(result) == 1: category_final = category # identify sub category r2 = re.compile(sub_category_search_words, flags=re.I | re.X) result2 = r2.findall(title) if len(result2) &gt; 0: subcategory_final = subcategory print("analysis result:", category_final, subcategory_final)
accepted answer: http://stackoverflow.com/a/50794209

http://stackoverflow.com/q/50744505
tagged with: machine-learning
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/53475612
has body: I am trying to build a model for adversarial example for malicious detection. but getting an error Attempting to use uninitialized value dense_24/bias Even if I initialize all variable as a global variable, and keeping the session in mind. Here is the full code with tf.Session() as sess: sess.run(tf.global_variables_initializer()) tf.set_random_seed(42) def mlp_model (): model_adv = Sequential() model_adv.add(Dense (256, activation ='relu', input_shape =(X_train.shape[1],))) model_adv.add(Dropout(0.4)) model_adv.add(Dense(256, activation ='relu')) model_adv.add(Dropout(0.4)) model_adv.add(Dense(2, activation ='softmax')) model_adv.compile(loss ='categorical_crossentropy', optimizer ='adam', metrics = ['accuracy']) model_adv.summary() return model_adv model_adv = mlp_model() source_samples = X_test.shape[0] X_adv = np.empty((0,36)) #numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values.generating empty array with shape same as X_test data jsma = SaliencyMapMethod(model_adv, back = 'tf', sess = sess) #initializing object for saliencyMapMethod jsma_params = {'theta': 1., 'gamma': 0.1, 'clip_min': 0., 'clip_max': 1., 'y_target': None} print (jsma) for sample_ind in range(0, source_samples): print('Generating sample no: ' + str(sample_ind)) sample = X_test[sample_ind:(sample_ind+1)] current_class = int(np.argmax(y_test[sample_ind])) target_classes = other_classes(2, current_class) if current_class != 0 : target_classes = [0] else : rand_class = random.randint(1,1) target_classes = [rand_class] for target in target_classes: one_hot_target = np.zeros((1, 2), dtype=np.float32) one_hot_target[0, target] = 1 jsma_params['y_target'] = one_hot_target adv_x = jsma.generate_np(sample, **jsma_params) X_adv = np.vstack([X_adv, adv_x]) print (X_adv.shape) error:- FailedPreconditionError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 1321 try: -&…
score: 0
has title: FailedPreconditionError: Attempting to use uninitialized value dense
answer count: 1
accepted answer: http://stackoverflow.com/a/53475612
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50785188
score: 1
has answer: http://stackoverflow.com/a/50785506
tagged with: scipy
type: Question
tagged with: numpy
downvote count: 0
has answer: http://stackoverflow.com/a/50785346
upvote count: 1
accepted answer: http://stackoverflow.com/a/50785309
possible better answer: http://stackoverflow.com/a/50785506
has body: I want to calcultate the definite integral with quadratures of sin(x)/x in python using scipy. With n = 256. It doesnt seem to work well: from scipy import integrate exact = integrate.quad(lambda x : (np.sin(x))/x, 0, 2*np.pi)[0] print("Exact value of integral:", exact) # Approx of sin(x)/x by Trapezoidal rule x = np.linspace(0, 2*np.pi, 257) f = lambda x : (np.sin(x))/x approximation = np.trapz(f(x), x) print ("Estimated value of trapezoidal O(h^2):", round(approximation, 5), '+', round((2/256)**2, 5)) print ("real error:", exact - approximation) # Approx of sin(x)/x by Simpsons 1/3 rule approximation = integrate.simps(f(x), x) print("Estimated value of simpsons O(h^4):", round(approximation, 9), '+', round((2/256)**4, 9)) print ("real error:", exact - approximation) plt.figure() plt.plot(x, f(x)) plt.show() The exact integral is calculated well, but I get an error with quadratures... What is wrong? Exact value of integral: 1.4181515761326284 Estimated value of trapezoidal O(h^2): nan + 6e-05 real error: nan Estimated value of simpsons O(h^4): nan + 4e-09 real error: nan Thanks in advance!
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/70003437
has title: Numeric integral of sin(x)/x
has answer: http://stackoverflow.com/a/50785309
tagged with: integral
tagged with: python
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/88467853
has text: This answer is more of a comment than a true answer. See [how to get initial reputation](https://meta.stackexchange.com/questions/139661/how-to-get-initial-reputation-on-stack-overflow-with-the-new-user-restrictions-i/139689) for some tips for getting enough reputation to comment.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50729986

http://stackoverflow.com/comment/88656638
type: Comment
comment on: http://stackoverflow.com/q/50814591
has text: Hey Scott, I am not specialized in coding or IT, I just stuck on that with my project, I've been trying for 4 days now and no chance, and I have to hand it by Thursday.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88577562
comment on: http://stackoverflow.com/a/50785448
type: Comment
score: 0
type: AnswerComment
has text: Asking recommendations for offline resources such as libraries, etc., are off-topic in SO, so they should avoid responding, I recommend reading [answer]

http://stackoverflow.com/comment/88467276
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50723432
has text: The gradients w.r.t total error are determined individually for each parameter, yet in each step the parameters are all changed simultaneously and *not* individually. This combined change might not be perpendicular to the contour lines, as you have seen here.
type: Comment

http://stackoverflow.com/comment/88521157
score: 1
comment on: http://stackoverflow.com/q/50756288
type: Comment
type: QuestionComment
has text: Please see the edit of the main post. Thanks in advance

http://stackoverflow.com/q/50821476
answer count: 0
type: UnansweredQuestion
has body: I have an instance of SQL server running. I am perfectly able to login and perform CRUD operations using Python MSSQL library. When I am trying to connect it using Microsoft server studio 14.0 or Pycharm, I am getting error 18456. I have checked that 'Windows and SQL Server Authentication' is already activated on it. I am unable to fetch the error logs of the SQL server, as I dont have rights for it. How to connect to the server using SQL server authentication. Did I miss anything while connecting?!!
has comment: http://stackoverflow.com/comment/88688959
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88681101
has comment: http://stackoverflow.com/comment/88732555
has comment: http://stackoverflow.com/comment/88656384
tagged with: sql-server
has comment: http://stackoverflow.com/comment/88727119
tagged with: python
has title: Unable to login to SQL server, using Microsoft server studio

http://stackoverflow.com/a/50855685
downvote count: 0
answers question: http://stackoverflow.com/q/50853735
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: Okay, so I figured out the answer. Since one of the dataframes had an index based on datetime, while the other had an index on integer, I used reset_index to make both dataframes have an index consisting of integers. This then let me use the above code mentioned. df["Diff"] = df["Time"] - df_target["Time"] Thank you for all your help!
score: 2
accepted answer of: http://stackoverflow.com/q/50853735

http://stackoverflow.com/q/50851966
has answer: http://stackoverflow.com/a/50864417
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88713290
tagged with: python
tagged with: pyqt5
downvote count: 1
tagged with: socket.io
has answer: http://stackoverflow.com/a/50920650
type: Question
has title: PyQt5 window crashes when socket is continue running in background
has comment: http://stackoverflow.com/comment/88707372
score: 0
answer count: 2
tagged with: api
upvote count: 1
tagged with: pyqt
has comment: http://stackoverflow.com/comment/88713376
has body: I have written a python code using PyQt5 and "socketIO_client_nexus". which will initiate socket connection as a client which will read the response from the server when "s_id" method trigger using `socketIO.on' after getting SocketID I have to stop the socketIO in order to save window from crashing window. if I do not stop socketIO PyQt5 window will automatically crash Please help me with an option through which I can solve this issue from PyQt5.QtWidgets import QMainWindow, QLabel, QLineEdit, QApplication from PyQt5.QtWidgets import QPushButton from PyQt5.QtCore import QSize, QThread import requests import json import sys from socketIO_client_nexus import SocketIO, LoggingNamespace import logging import requests class SendInvitation(QMainWindow): def __init__(self, arg): QMainWindow.__init__(self) self.setMinimumSize(QSize(240, 500)) self.setWindowTitle("GetUserlist") self.userid = arg url = 'http://192.168.2.36:5200/get_userlist' head = {'Content-Type': 'application/x-www-form-urlencoded'} data = {'user_id': self.userid} ret = requests.post(url, data, head) responcedict = json.loads(ret.content) print(responcedict) userData = responcedict['data'] x=100 y=100 for i in userData: useridstring = str(i['user_id']) buttonname = QPushButton(useridstring, self) buttonname.move(20, y) y= y + 30 buttonname = QPushButton(i['user_name'],self) buttonname.move(120, x) x = x+30 self.nameLabel = QLabel(self) self.nameLabel.setText('Enter Opponant ID: ') self.line1 = QLineEdit(self) self.line1.move(120, 25) self.line1.resize(100, 25) self.nameLabel.move(20, 20) OKbutton = QPushButton('OK', self) OKbutton.clicked.connect(self.clickMethod) OKbutton.resize(100,32) OKbutton.move(80, 60) def clickMethod(self): self.OpponantID = self.line1.text() print("Invitation send ID:" + self.OpponantID) # return OpponantID def getSID(args): # print(userid) NOWsocketID = args print("YOUR SocketID: " + NOWsocketID) url = 'http://192.168.2.36:5200/start_game' head = {'Content-Type': 'application/x-w…

http://stackoverflow.com/comment/88472160
comment on: http://stackoverflow.com/a/50732067
type: AnswerComment
score: 0
type: Comment
has text: Thanks alot! This was exactly what i was looking for!

http://stackoverflow.com/comment/88699789
type: Comment
type: QuestionComment
has text: The first step is to build a dict mapping strings to functions. And ideally a `command, *args = parse(message)` so you can just look up `functions[command]`, instead of having to iterate `for function in functions: if function in message: …`.
score: 1
comment on: http://stackoverflow.com/q/50848229

http://stackoverflow.com/q/50755480
tagged with: python
type: AnsweredQuestion
score: 1
has title: Pandas MultiIndex Dataframe to Excel | second Index as column name
type: Question
tagged with: numpy
tagged with: pandas
upvote count: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50755505
accepted answer: http://stackoverflow.com/a/50755505
has body: Sample Data frame : import pandas as pd idx = pd.MultiIndex.from_product([['Microsoft', 'Google', 'Apple'], ['OS', 'Web']], names=['Brand', 'Metric']) col = ['Count'] df = pd.DataFrame(10, idx, col) df the data looks like this When I download it as csv then it download like df.to_csv('example.csv') My Requirement is to download this data as pivot table, I am not able to find any way to move the second index as column name, the desired output of data looks like this
favorite count: 0

http://stackoverflow.com/a/50781907
has comment: http://stackoverflow.com/comment/88693292
type: Answer
has comment: http://stackoverflow.com/comment/88570555
upvote count: 1
score: 1
has body: You can use the subprocess module to run external programs from within a Python script. For example, &gt;&gt;&gt; output = subprocess.Popen("solveme.exe", stdout=subprocess.PIPE) &gt;&gt;&gt; output.communicate()[0] 'hello fellow, can you solve this math problem?\n\n2 x 7?\n' &gt;&gt;&gt;
downvote count: 0
has comment: http://stackoverflow.com/comment/88570484
answers question: http://stackoverflow.com/q/50781828

http://stackoverflow.com/comment/88545445
type: Comment
comment on: http://stackoverflow.com/q/50768638
has text: it would help if you added another `print` to the loop so we could tell if you're printing the blank on every other iteration, or they're part of the line that's being printed.
score: 0
type: QuestionComment

http://stackoverflow.com/a/50808621
type: Answer
has comment: http://stackoverflow.com/comment/88622919
score: 0
has comment: http://stackoverflow.com/comment/88623079
has body: You can use re.findall with ".*?": import re a, *_ = re.findall('start.*?end', 'STUFF start STUFF I CARE ABOUT end STUFF end STUFF end') Output: 'start STUFF I CARE ABOUT end'
answers question: http://stackoverflow.com/q/50808598

http://stackoverflow.com/a/50770475
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: The traceback indicates that you have some dependencies not installed in your app's lib directory, they're picked up from your local python installation libraries. Note the .../python2.7/site-packages/google/api_core/gapic_v1 path in there. You need to install all your app's dependencies in your app's lib dir, like mentioned in here.
answers question: http://stackoverflow.com/q/50768023

http://stackoverflow.com/q/50750999
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88509944
has answer: http://stackoverflow.com/a/50751176
has body: I have 2 df like these: df1 Pressure merge_key 923.3383179 1/1/2012 0:00 923.2299805 1/1/2012 0:30 923.1216431 1/1/2012 1:00 923.1466675 1/1/2012 1:30 df2 merge_key value 1/1/2012 0:30 16.9444 1/1/2012 0:30 16.6837 1/1/2012 0:30 16.6837 1/1/2012 0:30 16.9444 1/1/2012 0:30 16.1623 1/1/2012 0:30 16.6837 1/1/2012 1:00 16.1623 1/1/2012 1:00 16.423 1/1/2012 1:00 16.1623 1/1/2012 1:00 17.2051 1/1/2012 1:00 16.9444 1/1/2012 1:00 16.423 try all sort of merge command and it still give me a df with no data except for column header. Any solution? Thanks!
type: Question
has comment: http://stackoverflow.com/comment/88620029
tagged with: dataframe
score: 0
has title: Merging two pandas data frames, only getting column header
answer count: 1
has comment: http://stackoverflow.com/comment/88510218
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50751176
has comment: http://stackoverflow.com/comment/88510147
tagged with: python
tagged with: merge

sql
tags question: http://stackoverflow.com/q/50701902
tags question: http://stackoverflow.com/q/50827270
tags question: http://stackoverflow.com/q/50850840
tags question: http://stackoverflow.com/q/50782134
tags question: http://stackoverflow.com/q/50748443
tags question: http://stackoverflow.com/q/50782566
tags question: http://stackoverflow.com/q/50699737
tags question: http://stackoverflow.com/q/50739607
tags question: http://stackoverflow.com/q/50747136
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/50772343
tags question: http://stackoverflow.com/q/50796212
tags question: http://stackoverflow.com/q/50783729
tags question: http://stackoverflow.com/q/50766670
tags question: http://stackoverflow.com/q/50829798
tags question: http://stackoverflow.com/q/50743230
tags question: http://stackoverflow.com/q/50812766
tags question: http://stackoverflow.com/q/50840126
tags question: http://stackoverflow.com/q/50710412
tags question: http://stackoverflow.com/q/50837627
tags question: http://stackoverflow.com/q/50845484
tags question: http://stackoverflow.com/q/50729327
tags question: http://stackoverflow.com/q/50838199
tags question: http://stackoverflow.com/q/50762819
tags question: http://stackoverflow.com/q/50773280
tags question: http://stackoverflow.com/q/50774190
tags question: http://stackoverflow.com/q/50798353
tags question: http://stackoverflow.com/q/50784806
tags question: http://stackoverflow.com/q/50750368
tags question: http://stackoverflow.com/q/50844790
tags question: http://stackoverflow.com/q/50759886
tags question: http://stackoverflow.com/q/50786175
tags question: http://stackoverflow.com/q/50810204

http://stackoverflow.com/comment/88650652
comment on: http://stackoverflow.com/q/50822290
score: 0
type: Comment
type: QuestionComment
has text: To clarify, are you in control of the authentication of the external API or do you simply expect the Django credentials to match the external APIs credentials ?

http://stackoverflow.com/q/50727516
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88463352
score: 1
upvote count: 1
type: Question
has title: How to print a backspace character with python using repl.it
tagged with: replit
has body: I am using python3 on repl.it. I was trying to print a backspace but it prints instead print("hello\bworld") should print hellworld but it prints helloworld. I tried to use sys.stdout.write("\b") but it still prints . Can someone please help?
has answer: http://stackoverflow.com/a/50727868
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88601370
comment on: http://stackoverflow.com/q/50797550
score: 0
type: Comment
type: QuestionComment
has text: look in to cross correlation: https://en.wikipedia.org/wiki/Cross-correlation

http://stackoverflow.com/q/50736011
type: Question
has title: Django celery monitor doesn't show any tasks
has body: I cannot see the tasks in admin. I followed the steps in https://github.com/jezdez/django-celery-monitor I used celery==4.1.1 django-celery-results==1.0.1 django-celery-beat==1.0.1 django_celery_monitor==1.1.2 ran manage.py migrate celery_monitor The migrations went well. ran celery -A lbb events -l info --camera django_celery_monitor.camera.Camera --frequency=2.0 and celery -A lbb worker -l info in separate shells. But still cannot see the tasks I ran in celery-monitor &gt; tasks table.
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50737626
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50737626
tagged with: celery

http://stackoverflow.com/comment/88408118
type: AnswerComment
comment on: http://stackoverflow.com/a/50699263
type: Comment
has text: @OlivierMelançon. You're right. I have residual PTSD from Java. Updated.
score: 1

http://stackoverflow.com/comment/88495153
type: Comment
type: QuestionComment
has text: Looks like the file is encoded with an coding that can't be read, what happens when you try to find and open the README in an editor?
comment on: http://stackoverflow.com/q/50743723
score: 0

http://stackoverflow.com/q/50849119
linked to: http://stackoverflow.com/q/31915018
has comment: http://stackoverflow.com/comment/88708190
type: Question
has comment: http://stackoverflow.com/comment/88701251
has answer: http://stackoverflow.com/a/50849552
has comment: http://stackoverflow.com/comment/88701357
has body: I have a text file that looks like this essentially: Game #16406772158 starts.\n#Game No : 16406772158\n .... wins $0.75 USD\n\n\n_ Lots of \n (new text) \n (new text) and then \n\n\n. I want to find all of the instances where this occurs in my text file. When my code looks like this, it works (but only for the first instance): gameRegex = re.compile(r"""Game #(.+\n)*""") game = gameRegex.search(totalContent) When I switch to the findall method, outputting the "game" variable looks like this: ['Yl9Ui1OhAPyGV0JlCPLRrg wins $0.75 USD\n', 'G72AzGPQLTOWfYoNST1K/g wins $10 USD\n', '4bSQFjpEWTIcsil7GJkkVA wins $39.99 USD from the main pot with three of a kind, Kings.\n', 'U3xFxCVFfFBt50sL9VgLgQ wins $1.45 USD\n', ..., ] Very new to programming, I have no idea what to do here. I want it to look like this, where it creates a list. Within each item of the list, it displays the text up until the \n\n\n: game = ['Game #16406772158 starts.\n#Game No : 16406772158\n***** Hand History for Game 16406772158 *****\n$50 USD NL Texas Hold'em - Wednesday, July 01, 00:00:01 EDT 2009 ... Yl9Ui1OhAPyGV0JlCPLRrg wins $0.75 USD\n', 'Game #16406772158 starts.\n#Game No : 16406772158\n***** Hand History for Game 16406772158 *****\n$50 USD NL Texas Hold'em - Wednesday, July 01, 00:00:01 EDT 2009 ... Yl9Ui1OhAPyGV0JlCPLRrg wins $0.75 USD\n']
score: 0
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88701465
tagged with: python
has title: regex findall() to ignore ONE newline, but recognize more than one
tagged with: regex

http://stackoverflow.com/comment/88725308
comment on: http://stackoverflow.com/q/50848163
type: Comment
type: QuestionComment
has text: Yes, they are 2 floats values.
score: 0

http://stackoverflow.com/q/50728328
has comment: http://stackoverflow.com/comment/88464821
tagged with: matplotlib
linked to: http://stackoverflow.com/q/15713279
duplicate of: http://stackoverflow.com/q/20646822
accepted answer: http://stackoverflow.com/a/50728936
has title: Python: How to show matplotlib in flask
type: Question
answer count: 2
score: 65
linked to: http://stackoverflow.com/q/9622163
has comment: http://stackoverflow.com/comment/88464854
tagged with: flask
favorite count: 0
upvote count: 66
linked to: http://stackoverflow.com/q/31492525
duplicate of: http://stackoverflow.com/q/9622163
has comment: http://stackoverflow.com/comment/88465071
duplicate of: http://stackoverflow.com/q/31492525
has body: I'm very new to Flask and Matplotlib. I'd like to be able to show a simple chart I generated in some html, but I'm having a very hard time figuring out how. Here is my Python code: from flask import Flask, render_template import numpy as np import pandas import matplotlib.pyplot as plt app = Flask(__name__) variables = pandas.read_csv('C:\\path\\to\\variable.csv') price =variables['price'] @app.route('/test') def chartTest(): lnprice=np.log(price) plt.plot(lnprice) return render_template('untitled1.html', name = plt.show()) if __name__ == '__main__': app.run(debug = True) And here is my HTML: Price Chart {{ name }}
possible better answer: http://stackoverflow.com/a/50728818
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/50728818
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50728936
linked to: http://stackoverflow.com/q/20646822

http://stackoverflow.com/q/50734464
type: Question
has comment: http://stackoverflow.com/comment/88476765
answer count: 1
has comment: http://stackoverflow.com/comment/88477356
score: -1
has comment: http://stackoverflow.com/comment/88476851
has comment: http://stackoverflow.com/comment/88477611
has comment: http://stackoverflow.com/comment/88476811
has comment: http://stackoverflow.com/comment/88478083
has answer: http://stackoverflow.com/a/50735034
has comment: http://stackoverflow.com/comment/88476875
downvote count: 1
has comment: http://stackoverflow.com/comment/88478050
has comment: http://stackoverflow.com/comment/88477865
favorite count: 0
tagged with: python-3.x
has title: UnicodePython 3: EncodeError: 'ascii' codec can't encode character '\xe4' in position 277: ordinal not in range(128)
has comment: http://stackoverflow.com/comment/88476736
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88476787
has body: When I tried to make request with python requests library like below. I am getting the below exception def get_request(url): return requests.get(url).json() Exception palo:dataextractor minisha$ python escoskill.py Traceback (most recent call last): File "escoskill.py", line 62, in &lt;module&gt; print(response.json()) UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 277: ordinal not in range(128) However, the same piece of code works for some request and not for all. For the below url, it doesn't work. https://ec.europa.eu/esco/api/resource/concept?uri=http://data.europa.eu/esco/isco/C2&amp;language=en Url that works https://ec.europa.eu/esco/api/resource/taxonomy?uri=http://data.europa.eu/esco/concept-scheme/isco&amp;language=en
has comment: http://stackoverflow.com/comment/88478014
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88477243
has comment: http://stackoverflow.com/comment/88477419
upvote count: 0
has comment: http://stackoverflow.com/comment/88477128
has comment: http://stackoverflow.com/comment/88477164
has comment: http://stackoverflow.com/comment/88477578
has comment: http://stackoverflow.com/comment/88477546
has comment: http://stackoverflow.com/comment/88477039

http://stackoverflow.com/comment/88573332
has text: still does not work :((
type: Comment
comment on: http://stackoverflow.com/q/50773587
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88667603
type: QuestionComment
has text: Thanks. What do you mean by structure here? can you give an example?
comment on: http://stackoverflow.com/q/50831530
score: 0
type: Comment

http://stackoverflow.com/q/50761987
has body: file1: 2018-06-07, AAA, 26543.0, 123, 0.0 2018-06-07, AAA, 26512.0, 123, 1.0 file2: 20180608, B, 12345, 343, 0 20180607, AAA, 26512, 123, 1 20180608, C, 123, 343, 0 20180607, AAA, 26543, 123, 0 Right now, I can figure out one way, for every line in file1, I simply process it and try to find the matched line in file2. However, this solution could potentially have some problems, since we deal with relatively large data, this method (algorithm) could be extremely slow. I'm wondering if there is some Python built-in library that allows me to check this easily, like Pandas... (note: the data format, type for the second and last fields are different, but the data is the same) If no library allows me to do this stuff directly, is there some better algorithm that allows me to achieve the goal? Thanks
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/88531588
has answer: http://stackoverflow.com/a/50762410
tagged with: pandas
upvote count: 0
has title: How to check if every line of one file is in another file Python
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88533356
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/50645297
has comment: http://stackoverflow.com/comment/88531600
has comment: http://stackoverflow.com/comment/88531569
tagged with: python

http://stackoverflow.com/comment/88657145
type: QuestionComment
has text: `i.Test` is not `int` datatype. verify by `print(i.Test)`
score: 0
comment on: http://stackoverflow.com/q/50826140
type: Comment

http://stackoverflow.com/comment/107614415
score: 0
type: Comment
type: QuestionComment
has text: Handling C++ STL types from ctypes is difficult because of mangling, and mangling is implementation specific also an std::vector is not a primitive C type so, ctypes is unable to handle it.
comment on: http://stackoverflow.com/q/50835156

http://stackoverflow.com/comment/88587779
type: QuestionComment
comment on: http://stackoverflow.com/q/50786427
score: 0
has text: just train the layer where you change the channel and load existing weights in the rest of the layer's
type: Comment

http://stackoverflow.com/comment/88423004
score: 0
has text: @Attersson right, 'term' is a user input (search).
comment on: http://stackoverflow.com/q/50706782
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50758988
type: Answer
has body: The problem occurs due to delay between key_down and key_up. This can be prevented by reading either key_down or key_up. I tried how to do it but it was dead end for me so I decided to use the output of the difference in clipboard.
score: 0
accepted answer of: http://stackoverflow.com/q/50745460
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50745460

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/50741927
tags question: http://stackoverflow.com/q/50722536
type: Tag

http://stackoverflow.com/q/50756058
tagged with: floating-point
has body: when i run this python code in python3 it shows different results from python2? why there are different values? d = 0 x1 = 0 x2 = 1 y1 = 1 e=125 phi=238 temp_phi = phi while e &gt; 0: print (e, temp_phi) temp1 = temp_phi / e print (temp1) temp2 = temp_phi - temp1 * e print (temp2) temp_phi = e e = temp2 x = x2 - temp1 * x1 y = d - temp1 * y1 x2 = x1 x1 = x d = y1 y1 = y print (d + phi) if temp_phi == 1: print (d + phi)
accepted answer: http://stackoverflow.com/a/50756270
type: Question
has comment: http://stackoverflow.com/comment/88519879
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88519814
has comment: http://stackoverflow.com/comment/88519910
tagged with: variables
tagged with: iteration
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50756270
possible better answer: http://stackoverflow.com/a/50756163
tagged with: python
has answer: http://stackoverflow.com/a/50756163
has title: different run results between python3 and python2 for the same code
has comment: http://stackoverflow.com/comment/88519832
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/21316968

http://stackoverflow.com/comment/88533120
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50762585
has text: I removed the break because it didn't change anything, the intended break occurs within the while loop, because it runs, if loss occurs, trebles bet and runs again until a win, however I am trying to break the loop when the bet becomes bigger than the amount of cash, to try and make bet < cash at all times

http://stackoverflow.com/q/50776671
has comment: http://stackoverflow.com/comment/88560613
has answer: http://stackoverflow.com/a/50777777
answer count: 2
upvote count: 0
has body: I want to identify three different objects from a satellite wind image. The problem is three of them are somewhat similar. I tried to identify using templete matching but it didn't work. Three objects are as follows. Here the direction of the object is not important but the type of the head in the line is important. Can you suggest a way to proceed?
favorite count: 0
has title: How to identify three types of objects in a image?
has comment: http://stackoverflow.com/comment/88561314
type: UnansweredQuestion
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/88581756
tagged with: classification
downvote count: 2
tagged with: image-processing
has answer: http://stackoverflow.com/a/50777409
type: Question
tagged with: opencv

http://stackoverflow.com/comment/88518324
score: 0
type: Comment
type: QuestionComment
has text: Thanks Juanpa, that works. I just was wondering if I'm doing something wrong. If you want please anwer this question and I will accept.
comment on: http://stackoverflow.com/q/50751554

http://stackoverflow.com/comment/88619281
score: 0
comment on: http://stackoverflow.com/a/50806680
type: Comment
type: AnswerComment
has text: I don't know how you always answer my questions before I could get a cup of coffee, but this worked perfectly. Thank you!

http://stackoverflow.com/comment/88502414
type: AnswerComment
comment on: http://stackoverflow.com/a/50722390
type: Comment
has text: user thanked me for my response so im not sure why you are telling me the answer is wrong, also i didnt specify which worked like private and which worked like protected. simply said _ or __ make the variables either private or protected. again though, user has already fixed his issue with my support.
score: 0

http://stackoverflow.com/q/50798650
has comment: http://stackoverflow.com/comment/88610795
has comment: http://stackoverflow.com/comment/88603383
has body: Is there a way to remove a certain percentage (let's say 20) of a queue once it reaches a certain size? This question stems from a problem where a search algorithm is used that saves children nodes of the root parent board in a priority queue. There are so many different nodes to go through, that it takes more than 20 hours to find a solution. I would like to make rough cuts in the queue to shorten the number of nodes in order to find the solution faster, with the risk of throwing away the essential nodes that would lead to that goal.
upvote count: 1
has title: Removing percentage of a priority queue in python
answer count: 1
has answer: http://stackoverflow.com/a/50798942
favorite count: 0
has comment: http://stackoverflow.com/comment/88759637
accepted answer: http://stackoverflow.com/a/50798942
tagged with: priority-queue
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: queue
type: Question

http://stackoverflow.com/comment/88614598
has text: Yes, if you were to say run your command in some other system such as an EC2 instance, you would need to run all these commands again so it can be downloaded locally, the other alternative is to alter the nltk search path to some custom location and package your code with the libraries you need, so it can directly fetch them, off the top of my head another hack would be to create a file that notes if the download command has been run on the system in the past, (you can update this based on your needs) and download only if it has not been executed before.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50804171
type: AnswerComment

http://stackoverflow.com/comment/88648127
type: Comment
comment on: http://stackoverflow.com/a/50820234
score: 0
type: AnswerComment
has text: What I meant by "not periodic" is that if you calculate `sin(x)` from `-np.pi,np.pi` "including the last point" then the generated function is not periodic contrary to what you think.

http://stackoverflow.com/comment/88466474
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50728574
type: QuestionComment
has text: If you intend to deliver nested data with CSV - that is a bad idea, think of CSV as a representation of a single table - either you export 2 CSV files (one containing the games, the other the scores and link them with FK to PK), or export the data with JSON or XML.

http://stackoverflow.com/comment/88693437
score: 0
type: Comment
type: QuestionComment
has text: I am using Oracle database. Type of column is char(5). I am giving input as: C0002. And the ouput is: []
comment on: http://stackoverflow.com/q/50844790

http://stackoverflow.com/q/50760338
answer count: 1
has title: Setting object attributes in a loop results in all attributes having the same value
has answer: http://stackoverflow.com/a/50760547
has body: I'm trying to wire up some buttons to a Raspberry Pi to have different behaviour when they are pressed. I want each of them to print their name and state when the button is pressed or released. In this example I instantiate three buttons, and set their when_pressed and when_released attributes in the for-loop: #!/usr/bin/env python3 from gpiozero import LED, Button from signal import pause buttons = { "bcn": Button(2), "land": Button(3), "taxi": Button(4) } for name, btn in buttons.items(): btn.when_pressed = lambda: print(name + ' ON') btn.when_released = lambda: print(name + ' OFF') print('ready') pause() But, when I press the buttons, they report the correct state, but all of them report the same name. For example, all buttons might report bcn ON or bcn OFF. Strangely, when I restart the script, another -seemingly random- name is chosen and all buttons report e.g. land ON or land OFF. It seems to me like it is only creating a single lambda function for all press handlers, and one for all release handlers. How can I modify this script to print the correct name for each button?
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50760547
type: Question
upvote count: 2
tagged with: python
tagged with: lambda

http://stackoverflow.com/comment/88537297
type: QuestionComment
has text: @hoefling IT WORKED!!! Now of course I'm running into a plethora of other problems with actually getting the proper modules INSTALLED, but it's nice to at least be able to use pip!! Thank you so much for your help! I had resigned myself to life without pip before this...
score: 0
comment on: http://stackoverflow.com/q/50742538
type: Comment

http://stackoverflow.com/q/50838052
accepted answer: http://stackoverflow.com/a/50840796
tagged with: int64
has title: Change of value to the converter Int64 in string Python
tagged with: python
type: AnsweredQuestion
has body: I have a problem understanding what causes the date value to change when I convert. I have the following value "19670619", type int64. I need to convert to String and leave the date "06/19/1967". I did it this way: Op['dt'] = pd.to_datetime(Op['dt'], unit = 'ms') Op['dt'] = Op['dt'].fillna(datetime(2200,12,31)) OP['dt'] = Op['dt'].apply(lambda x: x.strftime('%d/%m/%Y')) I have the result: 01/01/1970 which is different from the original date it entered. Another way I tried was: Op['dt'] = pd.to_datetime(Op['dt'], unit = 'm') Op['dt'] = Op['dt'].fillna(datetime(2200,12,31)) OP['dt'] = Op['dt'].apply(lambda x: x.strftime('%d/%m/%Y')) And the result was: 27/05/2007, I can not understand why this happened even when reading the other conversion cases. Can anybody help me ?
type: Question
has answer: http://stackoverflow.com/a/50840796
tagged with: data-conversion
has answer: http://stackoverflow.com/a/50838139
tagged with: type-conversion
score: 0
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50838139

http://stackoverflow.com/comment/88569253
type: Comment
comment on: http://stackoverflow.com/q/50781216
score: 0
has text: @EcirHana In this [official documentation](https://docs.python.org/3.7/library/multiprocessing.html), it shows all examples with `if __name__ == '__main__'`. Do you mean it is okay to put `if __name__ == '__main__'` within a class method and even though we run a python script (e.g. `python file1.py --num_processes 5`) which internally create the class and call this method ?
type: QuestionComment

http://stackoverflow.com/a/50939211
has comment: http://stackoverflow.com/comment/110158595
answers question: http://stackoverflow.com/q/50807744
score: 104
has body: Pandas' to_html simply outputs a large string containing HTML table markup. The classes argument is a convenience handler to give the a class attribute that will be referenced in a previously created CSS document that styles it. Therefore, incorporate to_html into a wider HTML document build that references an external CSS. Interestingly, to_html adds dual classes which can be referenced in CSS individually, .dataframe {...} .mystyle{...}, or together .dataframe.mystyle {...}. Below demonstrates with random data. Data import pandas as pd import numpy as np pd.set_option('display.width', 1000) pd.set_option('colheader_justify', 'center') np.random.seed(6182018) demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50), 'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50), 'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50), 'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50), 'num1': np.random.randn(50)*100, 'num2': np.random.uniform(0,1,50), 'num3': np.random.randint(100, size=50), 'bool': np.random.choice([True, False], 50) }, columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool'] ) print(demo_df.head(10)) # date analysis_tool num1 database num2 os num3 bool # 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True # 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False # 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False # 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False # 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True # 5 2018-04-05 sas -68.140295 sql server 0.346894 windows 10 0 True # 6 2018-05-07 julia 12.874660 postgres 0.195217 ios 79 True # 7 2018-01-22 r 189.410928 mysql 0.234815 windows 10 56 False # 8 2018-01-12 pandas -111.412564 sql server 0.580253 debian 30 False # 9 2018-04-12 r 38.963967 pos…
has comment: http://stackoverflow.com/comment/105302365
has comment: http://stackoverflow.com/comment/110140332
has comment: http://stackoverflow.com/comment/88905034
has comment: http://stackoverflow.com/comment/111154124
has comment: http://stackoverflow.com/comment/88903299
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88909248
has comment: http://stackoverflow.com/comment/137995384
upvote count: 104
has comment: http://stackoverflow.com/comment/88909053
has comment: http://stackoverflow.com/comment/114741580
type: Answer
has comment: http://stackoverflow.com/comment/124799017
accepted answer of: http://stackoverflow.com/q/50807744

web3py
tags question: http://stackoverflow.com/q/50731830
tags question: http://stackoverflow.com/q/50764686
type: Tag
tag name: web3py

http://stackoverflow.com/q/50762627
linked to: http://stackoverflow.com/q/19256127
tagged with: anaconda
has answer: http://stackoverflow.com/a/57213129
score: 4
tagged with: shell
has answer: http://stackoverflow.com/a/71949137
has comment: http://stackoverflow.com/comment/88533007
favorite count: 0
has answer: http://stackoverflow.com/a/50762816
upvote count: 5
has title: How to install Python packages in a specific environment?
has body: I installed Anaconda3 so I can create environments and install different packages in each environment. But I fail to understand the difference between the Python in /usr/bin/python and /opt/anaconda3/bin/python I can seem to access Python 3.6.5 Anaconda from both, why is that? And, what is the difference between both? Furthermore, I would like to install packages to a single Python environment only.
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50762868
accepted answer: http://stackoverflow.com/a/50762868
has comment: http://stackoverflow.com/comment/88532935
downvote count: 1
possible better answer: http://stackoverflow.com/a/71949137
type: Question

http://stackoverflow.com/comment/88645508
comment on: http://stackoverflow.com/q/50820074
score: 0
has text: `ex` is not exposed and can't be imported like that. `main` is, however, if that helps illustrate what is exported.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50772320
has comment: http://stackoverflow.com/comment/88552207
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88552166
type: Question
tagged with: telegram-webhook
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50772535
accepted answer: http://stackoverflow.com/a/50772535
favorite count: 0
tagged with: telegram-bot
has title: telegram.ext CommandHandler works in personal chat but doesn't work in group chat
tagged with: python-telegram-bot
tagged with: telegram
has body: I have a telegram bot and I'm trying to add little "features" to it that I find useful by adding more CommandHandler. The new features work fine in personal chat but don't work in group chats. I am perplexed by this. My code is something as follows def func1(bot, update): &lt;somecode&gt; def func2(bot, update, args): &lt;somecode&gt; def error(bot, update, error): &lt;errorhandler&gt; def newfunc(bot, update, args): &lt;newcode&gt; dispatcher.add_handler(CommandHandler('func1', func1)) dispatcher.add_handler(CommandHandler('func2', func2, pass_args=True)) dispatcher.add_handler(CommandHandler('newfunc', newfunc, pass_args=True)) dispatcher.add_error_handler(error) The func1 and func2 work fine and they were there before but the new newfunc does not work in group chats. I have no idea whats causing this
tagged with: python

http://stackoverflow.com/q/50723259
has title: Matplotlib : Dual Axis chart has is not working as aspected
has comment: http://stackoverflow.com/comment/88462065
score: 0
has comment: http://stackoverflow.com/comment/88473796
type: UnansweredQuestion
has body: Hi I have my first matplotlib code is here. import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt fig = plt.figure() # Create matplotlib figure ax = fig.add_subplot(111) # Create matplotlib axes ind = np.arange(5) avg_bar1 = (10,20,30,60,14) avg_bar2 = (20,26,31,31,55) avg_bar3 = (30,38,38,39,40) avg_bar4 = (40,25,25,28,27) avg = [] rects1 = plt.bar(ind, avg_bar1, 0.20, color='#68c7b7',label='bar1') rects2 = plt.bar(ind + 0.20, avg_bar2, 0.20, color='#e19300', label='bar2') rects3 = plt.bar(ind + 0.40, avg_bar3, 0.20, color='#969696', label='bar3') rects4 = plt.bar(ind + 0.60, avg_bar4, 0.20, color='#17839a', label='bar4') high_point_x = [] high_point_y = [] for i in range(0,5): single_bar_group={rects1[i].get_height():rects1[i].get_x() + rects1[i].get_wi dth()/2.0, rects2[i].get_height():rects2[i].get_x() + rects2[i].get_w idth()/2.0, rects3[i].get_height():rects3[i].get_x() + rects3[i].get_w idth()/2.0, rects4[i].get_height():rects4[i].get_x() +rects4[i].get_wi dth()/2.0} height_list = list(single_bar_group.keys()) height_list.sort(reverse=True) for single_height in height_list: high_point_y.append(single_height) high_point_x.append(single_bar_group[single_height]) break ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.tick_params( axis = 'y', left = False, right = False ) ax2 = ax.twinx() trend_line =ax2.plot(high_point_x,high_point_y,marker='o',color='#7cb85e',label= 'Trend Linei') plt.xticks(ind+0.20, ('Q1 2017', 'Q2 2017', 'Q3 2017', 'Q4 2017', 'Q5 2017')) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_visible(False) ax2.spines['top'].set_visible(False) ax2.tick_params( axis = 'y', left = False, right = False ) plt.savefig('foo.png', bbox_inches="tight", pad_inches=0) I wanted to build the combo chart ( Which is basically group of bar chart and average of bar chart ). But the average line does not look as expected also i believe y axis values ar…
tagged with: python
answer count: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88461984
type: Question
has comment: http://stackoverflow.com/comment/88473806

http://stackoverflow.com/q/50833802
tagged with: async-await
downvote count: 1
type: Question
has body: I've seen examples of such code working in certain environments (eg https://github.com/ipython/ipykernel/pull/323). But for me this only raises SyntaxError so far: Update: I know that in "pure" python it won't work and await is supposed to be used in async def's only. I also know that in jupyter it is possible (see link above) so the engine is capable of doing this. The question is how to get rid of this error message. Update2 What's the idea of calling await directly: I'm working with an async library. In current version of jupyter it's hard to get the return value of a coroutine: The best thing I've come up to is through global variables: One of the problems here is that res is not ready in the cell 25 yet. I have to wait until I see "done", then use the value in the another cell. Another problem is semantic asymmetry between calling a coroutine from the cell directly and from another coroutine, which is pretty irrelevant when writing scripts in an editor, but quite crucial for repl. Now consider this:
score: 10
upvote count: 11
has title: Is there a way to call await directly in Jupyter cell?
tagged with: python-asyncio
answer count: 1
has answer: http://stackoverflow.com/a/50844238
favorite count: 0
tagged with: jupyter-notebook
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50839277
has body: I don't know if there is a direct way in pandas, but you can create a function to write your specific format, and then use groupby and apply, such as: def create_specific_format (df_grouped): dict_output = {'serial_no': df_grouped['serial_no'].iloc[0]} dict_output['readings'] = [] for col in ['parameter1','parameter2','parameter3']: dict_output['readings'].append({'name':col, 'datapoints': df_grouped.apply(lambda row: (row['timestamp'], row[col]),1).tolist()}) return dict_output And what you want can be optained by: df.groupby('serial_no', as_index=False).apply(create_specific_format).tolist()
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88704194
accepted answer of: http://stackoverflow.com/q/50837180
type: Answer
answers question: http://stackoverflow.com/q/50837180
score: 2
upvote count: 2

http://stackoverflow.com/comment/88494476
has text: `def __mul__(self,other): j= Vector([a*b for a,b in zip(self.vector, other.vector)]) return sum(j)` Doesnt work:(
comment on: http://stackoverflow.com/a/50738208
score: 0
type: AnswerComment
type: Comment

convex-hull
tags question: http://stackoverflow.com/q/50809434
type: Tag
tags question: http://stackoverflow.com/q/50715934
tag name: convex-hull

http://stackoverflow.com/q/50845507
type: Question
tagged with: numpy
tagged with: algorithm
tagged with: spatial
has body: I have data geographically scattered without any kind of pattern and I need to create an image where the value of each pixel is an average of the neighbors of that pixel that are less than X meters. For this I use the library scipy.spatial to generate a KDTree with the data (cKDTree). Once the data structure is generated, I locate the pixel geographically and locate the geographic points that are closest. # Generate scattered data points coord_cart= [ [ feat.geometry().GetY(), feat.geometry().GetX(), feat.GetField(feature), ] for feat in layer ] # Create KDTree structure tree = cKDTree(coord_cart) # Get raster image dimensions pixel_size = 5 source_layer = shapefile.GetLayer() x_min, x_max, y_min, y_max = source_layer.GetExtent() x_res = int((x_max - x_min) / pixel_size) y_res = int((y_max - y_min) / pixel_size) # Create grid x = np.linspace(x_min, x_max, x_res) y = np.linspace(y_min, y_max, y_res) X, Y = np.meshgrid(x, y) grid = np.array(zip(Y.ravel(), X.ravel())) # Get points that are less than 10 meters away inds = tree.query_ball_point(grid, 10) # inds is an np.array of lists of different length, so I need to convert it into an array of n_points x maximum number of neighbors ll = np.array([len(l) for l in inds]) maxlen = max(ll) arr = np.zeros((len(ll), maxlen), int) # I don't know why but inds is an array of list, so I convert it into an array of array to use grid[inds] # I THINK THIS IS A LITTLE INEFFICIENT for i in range(len(inds)): inds[i].extend([i] * (maxlen - len(inds[i]))) arr[i] = np.array(inds[i], dtype=int) # AND THIS DOESN'T WORK d = np.linalg.norm(grid - grid[inds]) Is there a better way to do this? I'm trying to use IDW to perform the interpolation between the points. I found this snippet that uses a function that gets the N nearest points but it does not work for me because I need that if there is no point in a radius R, the value of the pixel is 0. d, inds = tree.query(zip(xt, yt, zt), k = 10) w = 1.0 / d**2 air_idw = np.sum(w * air.flatten()[ind…
score: 0
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50851205
tagged with: python
tagged with: scipy
has title: Calculate distance between neighbors efficiently

http://stackoverflow.com/q/50709381
has comment: http://stackoverflow.com/comment/88428555
has comment: http://stackoverflow.com/comment/88428124
tagged with: python-datetime
has answer: http://stackoverflow.com/a/50709427
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/88427863
has title: Python - identical code, identical pc's; but only 1 gets TypeError: (pywintypes.datetime)
has comment: http://stackoverflow.com/comment/88427906
tagged with: typeerror
has comment: http://stackoverflow.com/comment/88428317
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88427899
favorite count: 0
has body: I have a Python script that I wrote recently and it runs perfectly on one pc, but not on another pc. I have verified that both machines have the exact same version of Python (3.6.0) and the exact same verion of Anaconda (4.3.1 64-Bit) The code: import requests from win32com.client import Dispatch import win32com.client #as win32 import datetime import os import re import pywintypes import time # First I obtain data from a given webpage using the 'requests' library # .. and write it to file text_file.write(re.sub(r'[^\x00-\x7f]',r'', result.text)) # Next, I parse the text file using the below: if 'startDate' in line: str = line str = str.replace('"','') str = str.replace(':','') str = str.replace('{','') str = str.replace('}','') str = str.replace('[','') str = str.replace(']','') str = str.replace('startDate','') str = str.replace("\n","") dt = datetime.datetime.fromtimestamp(int(str)/1000.0) str = dt.strftime("%m/%d/%y" + " %H:%M:%S %p") xlSht.Cells(i,6).Value = str #xlSht.Cells(i,6).Value = dt.strftime("%m/%d/%y") + " %I:%M:%S %p") xlSht.Cells(i,6).NumberFormat = "[$-409]mm/dd/yy hh:mm:ss AM/PM;@" # Line that is parsed: "starDate":1528231802193}, # I then parse the field which will be compared to the above: if '"date":{"endDate":' in line: # Column U str = line str = str.replace('"','') str = str.replace(':','') str = str.replace('{','') str = str.replace('}','') str = str.replace('[','') str = str.replace(']','') str = str.replace('endDate','') str = str.replace("\n","") dt = datetime.datetime.fromtimestamp(int(str)/1000.0) xlSht.Cells(i,21).Value = dt.strftime("%m/%d/%y" + " %H:%M:%S %p") xlSht.Cells(i,21).NumberFormat = "[$-409]m/d/yy hh:mm:ss AM/PM;@" # Line that is parsed: "endDate":1528231801083}, # Finally I compare the two values within excel xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlWb = xlApp.Workbooks.Add() xlSht = xlWb.Worksheets(1) x = 2 while len(xlSht.Cells(x,1).Text) &gt; 0: if xlSht.Cells(x,6).Value &lt; xlSht.Cells(x,21).Value: xl…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88428310
tagged with: python
has comment: http://stackoverflow.com/comment/88427946

http://stackoverflow.com/a/50729263
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88468017
has body: You can perform such aggregate with the groupby function of itertools. It is a requirement that the elements appearch in "chunks" with respect to the "grouper criteria". But this is the case here, since you use order_by. We can thus write it like: from itertools import groupby from operator import itemgetter query = (Event.objects.all.select_related('event_type') .order_by('date', 'event_type') .distinct('date', 'event_type') .values_list('date', 'event_type__name')) result = [ { 'date': k, 'datetypes': [v[1] for v in vs]} for k, vs in groupby(query, itemgetter(0)) ] You also better use 'event_type' in the order by criterion. This will result in something like: [{'date': datetime.date(2018, 5, 19), 'datetypes': ['Famous person died', 'Royal wedding']}, {'date': datetime.date(2018, 5, 24), 'datetypes': ['Famous person died']}, {'date': datetime.date(2011, 5, 25), 'datetypes': ['Important law enforced', 'Referendum']}] (based on quick Wikipedia scan of the last days in May). The groupby works in linear time with the number of rows returned.
has comment: http://stackoverflow.com/comment/88467707
answers question: http://stackoverflow.com/q/50729034
type: Answer
has comment: http://stackoverflow.com/comment/88467775
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50729034
has comment: http://stackoverflow.com/comment/88468202

http://stackoverflow.com/comment/88581728
score: 0
comment on: http://stackoverflow.com/a/50786922
type: AnswerComment
type: Comment
has text: Thanks a bunch. I knew it was a simple solution to my error.

http://stackoverflow.com/q/50779042
has comment: http://stackoverflow.com/comment/88566800
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88570793
tagged with: python
has title: How to cast printf() from C function into a python data structure?
tagged with: python-c-api
has body: EDIT: This question is related to this: Python ctypes: how to pass row outputs from a C function into a pandas DataFrame? My question is how to parse text printed to STDOUT via printf() into something useable by Python. I'm working with a Python wrapper in Python3.x around a C library using ctypes. The C library currently does database queries. The function I'm accessing via ctypes is printing the tab-delimited rows of the database via printf(): void print_query(const char *input_file, const char *index, const char *query_string); whereby input_file is the path to the file, index is the index already generated, and query_string is the string used to query the database. Here is the Python code I have now: from ctypes import CDLL import ctypes lib = CDLL(".../path/libshared.so") lib.print_query.restype = ctypes.c_char lib.print_query.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p) According to the documentation, https://docs.python.org/3/library/ctypes.html ctypes.c_char is a 1-character bytes object. When I try using the function lib.print_query, the function returns rows via printf() to STDOUT: foo = lib.print_query('../file', '.../index', 'January') outputs 2012 februari 32.610 2012 maart 33.195 2012 april 51.891 and print(foo) returns b'\x02' I cannot "access" what has been printed to STDOUT, and I'm not sure how to translate this into a simple string of text. I get the same results trying foo = io.BytesIO(lib.print_query('../file', '.../index', 'January')) How can I access this text? It would be useful to stream this into a pandas Dataframe, as it's tab-delimited data. EDIT: I've tried piping with the following import subprocess proc = subprocess.Popen(lib.print_query('../file', '.../index', 'January'), stdout=subprocess.PIPE) Here's the output: FileNotFoundError: [Errno 2] No such file or directory: b'\x02': b'\x02'
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/50777214
has comment: http://stackoverflow.com/comment/88567583
downvote count: 1
type: Question
tagged with: ctypes
tagged with: casting
has comment: http://stackoverflow.com/comment/88565058
has comment: http://stackoverflow.com/comment/88567200
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/88571102
has comment: http://stackoverflow.com/comment/88566811
has comment: http://stackoverflow.com/comment/88565033

http://stackoverflow.com/a/50822007
has body: The problem is really simple: mnuQuit is a variable not a member of the class so it can not be accessed by other methods of the class, plus I see it unnecessary to use that line of code, just call close(): def triggerAct(self, x): if x.text() == "Create New": print("Trigger Create New...") elif x.text() == " Quit": self.close() # mnuQuit.triggered.connect(self.close) It is not appropriate to call exit() within the GUI because the GUI has to free memory and if you call exit() it does not give you the time to do it. with close() the GUI closes correctly.
answers question: http://stackoverflow.com/q/50821563
has comment: http://stackoverflow.com/comment/88650336
has comment: http://stackoverflow.com/comment/88649299
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88652940
has comment: http://stackoverflow.com/comment/88652869
has comment: http://stackoverflow.com/comment/88650342
has comment: http://stackoverflow.com/comment/88650090
has comment: http://stackoverflow.com/comment/88649272
type: Answer
has comment: http://stackoverflow.com/comment/88650298
has comment: http://stackoverflow.com/comment/88649171
upvote count: 2
has comment: http://stackoverflow.com/comment/88650162
accepted answer of: http://stackoverflow.com/q/50821563

http://stackoverflow.com/comment/88689030
has text: Okay, so I tried that and I found out some valuable information that makes everything this much harder: the list I'm trying to get apparently isn't a wikitable. So that solution doesn't work. I checked the article that I linked in the question, I went into the part where you can edit the section. There, it is supposed to say class="wikitable", but it doesn't. That's probably why everything I've tried doesn't work.
type: Comment
comment on: http://stackoverflow.com/a/50831448
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88420876
type: QuestionComment
type: Comment
has text: Hi this doesn't actually answer why this is occurring, The same issue can be seen when testing 1.0065 and 1.0075.
score: 0
comment on: http://stackoverflow.com/q/50705777

http://stackoverflow.com/comment/88540896
has text: It is installed by the GPU driver. If you don't have a GPU driver installed on your system (for example if you are on a build machine) then there won't be an ordinarily installed `libcuda.so` on your machine (and that is what the stub version is for). If you have a GPU driver installed, the driver will install it in a location that is OS-dependent. Use a linux utility to locate it on your machine, such as `find`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50766473
score: 0
type: Comment

http://stackoverflow.com/q/50853179
has body: I am trying to filter a pandas DataFrame df by keeping only the rows which contain one of several strings I have in a mylist = ['cat', 'mouse'], in a specific column df['Title']: df.head() Title Duration ... 0 The Cat1 &amp; Mouse2 33 min ... 1 Legend of the cat 10 min ... 2 Foo-Bar 3 min ... 3 Legend of Mousopia 5 min ... 4 Cat + Mouse 7 min ... Looking at similar questions, I have attempted to filter df by doing the following: z = df['Title'].str.lower() df = df[z.contains([x for x in mylist])] Expecting df.head() to look something like: Title Duration ... 0 The Cat1 &amp; Mouse2 33 min ... 1 Legend of the cat 10 min ... 4 Cat + Mouse 7 min ... However, I keep getting the following error: AttributeError: 'Series' object has no attribute 'contains' I have updated conda and pandas but keep getting the same result. conda version : 4.5.4 conda-build version : 3.8.0 python version : 3.6.5.final.0 pandas version : 0.23.0 py36h830ac7b_0 What am I missing?
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/50853202
downvote count: 0
linked to: http://stackoverflow.com/q/12065885
tagged with: filter
tagged with: pandas
answer count: 1
duplicate of: http://stackoverflow.com/q/12065885
favorite count: 0
has title: How to filter pandas DataFrame with a list of strings
has answer: http://stackoverflow.com/a/50853202
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88639425
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50817121
has text: No. It is the same run of the job...
score: 0

http://stackoverflow.com/q/50738541
has comment: http://stackoverflow.com/comment/88497361
has title: Why is Python OpenCV camera read in Ubuntu slower than Windows?
accepted answer: http://stackoverflow.com/a/60255570
upvote count: 3
has comment: http://stackoverflow.com/comment/88497754
tagged with: image-processing
has body: I have a really simple code to view video from web-cam (Microsoft HD LifeCam Studio) as follow: import cv2 from imutils.video import FPS cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) fps = FPS().start() while cap.isOpened(): _,frame = cap.read() cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break fps.update() fps.stop() print("{}".format(fps.fps())) cap.release() cv2.destroyAllWindows() The code will print out the FPS when the program ends. When running this code on Windows, I receive 30 FPS. However, when running on Ubuntu, I only receive 10 FPS. I have tried cap.set(cv2.cv.CV_CAP_PROP_FPS, 30) but it does not work. Does anyone experience the same situation? Is there any solution for this problem? I'm running Windows 10 and Ubuntu 16.04 Python 3.5.2 OpenCV 3.4.0
type: Question
has comment: http://stackoverflow.com/comment/88495460
has answer: http://stackoverflow.com/a/60255570
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
tagged with: opencv
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/88514507
type: Comment
has text: The `type` doesn't help much. Look at `shape` and `dtype` instead. `listL` Iwhich is missing a `])`) is a 1d object dtype array (shape (4,). `A` is a 2d array of numbers, shape (3,2). `np.stack(listL)` should produce a (4,2) numeric array.
comment on: http://stackoverflow.com/q/50753069
score: 0
type: QuestionComment

http://stackoverflow.com/q/50764897
score: 1
favorite count: 0
type: Question
tagged with: python
tagged with: plotly
upvote count: 1
has body: I'm currently working on my first web-application. I recently started following tutorials on python and on some modules. Most of the questions I have I'm able to figure by looking them up, exceptfor this one. I can't figured it out. Goal is as follows: - I'm trying to show a graph with a line-chart which dynamically updates by the user input. The user can choose multiple items from a multiple value dropdown. If I add multiple 'go.Scatters' I can add multiple lines to the graph, except then the trace in the graph is static. So, I tried to write a for loop in go.Scatter that adds more go.Scatters for each item in data_name. Each time I try I got syntax erros. I tried to add values to the data list in dcc.Graph. Each time i failed. The questions I've are the following: - Where can i add the for loop to add traces to the data list? - How should the for loop be structed? I'm just a beginner so every advice is welcome :-) Thanks in advance. If i'm not clear enough on the question, please let me know. My code is the following: import dash import dash_core_components as dcc import dash_html_components as html from pandas_datareader.data import DataReader import time from collections import deque import plotly.graph_objs as go import random app = dash.Dash('vehicle-data') max_length = 50 #times = deque(maxlen=max_length) times = [1,2,3,4,5,6,7,8,9,10,11,12] oil_temps = [11,12,13,14,15,16,17,18,19] intake_temps = [11,12,13,14,15,16,17,18,19] coolant_temps = [11,12,13,14,15,16,17,18,19] #rpms = deque(maxlen=max_length) #speeds = deque(maxlen=max_length) #throttle_pos = deque(maxlen=max_length) data_dict = {"NH Utrecht":oil_temps, "NH Amsterdam": intake_temps, "NH Schiller": coolant_temps #"NH Sparrenhorst":rpms, #"Amsterdam":speeds, #"Overig":throttle_pos } app.layout = html.Div([ html.Div([ html.H2('Hotel', style={'float': 'left', }), ]), dcc.Dropdown(id='vehicle-data-name', options=[{'label': s, 'value': s} for s in data_dict.keys()], value=['NH Utrecht'], multi=True ), html…
tagged with: plotly-dash
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: Dynamically adding traces to graph with dropdown input

http://stackoverflow.com/comment/88548834
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50770013
type: AnswerComment
has text: ah, sorry new to this website

http://stackoverflow.com/q/50723114
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
tagged with: indexing
tagged with: dataframe
has answer: http://stackoverflow.com/a/50723193
accepted answer: http://stackoverflow.com/a/50723193
upvote count: 3
has body: I have a dataframe which is defined like so: df = pd.DataFrame({'A':[5,8,96,3,5,41,2,45,7,8], 'B':[1,2,3,5,6,10,11,12,13,18]}) df = df.set_index('B') df.index.name = None My goal is to assign to the dataframes subsets which have a continuous index a value like so: Algorithm: As you can see from the image the first 3 rows have index 1,2,3 which increase by 1 (thus continuous). Therefore I assign to this subset them value 0 in column C. The second subset is formed by rows having the continuous indexes 5 and 6 (note there is no index 4!). Therefore I assign to them the value 1 in column C. Question: Do you know an efficient and smart way to achieve such result? I was able to achieve such result by using a a lot of for loops and ifs but it was pretty nasty.
tagged with: pandas
has title: How to identify subsets with continuous index within dataframe
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/88646980
type: Comment
type: QuestionComment
has text: This may help: http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html
comment on: http://stackoverflow.com/q/50820707
score: 0

http://stackoverflow.com/comment/117592951
comment on: http://stackoverflow.com/a/50758844
has text: Is it the case that because both of them are 1 it needed to check if they were equal, but when ONLY one of them is 1 it doesn't need to check for equality?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50782488
has comment: http://stackoverflow.com/comment/88574521
favorite count: 0
has comment: http://stackoverflow.com/comment/88574725
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88573821
has comment: http://stackoverflow.com/comment/88596813
has body: I got a returned string value returned_string = '{"url":"src=\"http:the_url\""}' and I want to convert it to a dictionary type. When I try eval(),following error appears: File "", line 1 {"url":"src="http:the_url""} ^ SyntaxError: invalid syntax When I try json.loads(),following error appears: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 14 (char 13) I know if the string is like this: returned_string = r'{"url":"src=\"http:the_url\""}' then both eval() and json.loads() work. But as the value name tells ,it's a string which is returned by some function() , so I cant transform it to r'..' or I just don't know how. So,It will be really helpful if anyone know how to convert returned_string to a dictionay.Thanks.
downvote count: 1
has comment: http://stackoverflow.com/comment/88574795
type: Question
has title: python-Convert a returned string which has " and \" both in it to dict
has comment: http://stackoverflow.com/comment/88573570
has comment: http://stackoverflow.com/comment/88574208
has answer: http://stackoverflow.com/a/50782606
has comment: http://stackoverflow.com/comment/88571709
score: 0
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88574269

http://stackoverflow.com/a/50740665
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88502600
accepted answer of: http://stackoverflow.com/q/50740610
has comment: http://stackoverflow.com/comment/88502522
has comment: http://stackoverflow.com/comment/88502156
answers question: http://stackoverflow.com/q/50740610
type: Answer
has comment: http://stackoverflow.com/comment/88502397
has body: json_first["c1"] is a dict like any other, so you add new key-value pairs to it with indexed assignment. &gt;&gt;&gt; date1, date2 = '2018-06-06','2018-06-07' &gt;&gt;&gt; json_first = { ... "c1": { date1 : {'title':'t1','link': 'l1','summary': 's1'}}, ... "c2": { date2 : {'title':'t2','link': 'l2','summary': 's2'}} ... } &gt;&gt;&gt; json_first["c1"]['2018-06-08'] = {'title':'t3','link': 'l3','summary': 's3'} &gt;&gt;&gt; json_first {'c1': {'2018-06-06': {'title': 't1', 'link': 'l1', 'summary': 's1'}, '2018-06-08': {'title': 't3', 'link': 'l3', 'summary': 's3'}}, 'c2': {'2018-06-07': {'title': 't2', 'link': 'l2', 'summary': 's2'}}}
upvote count: 2
has comment: http://stackoverflow.com/comment/88502346

http://stackoverflow.com/q/50845631
linked to: http://stackoverflow.com/q/50701690
tagged with: python
answer count: 0
tagged with: pytorch
tagged with: broken-pipe
has title: Python: BrokenPipeError when calling iter on a torch.utils.data.DataLoader object
type: Question
has comment: http://stackoverflow.com/comment/88728445
duplicate of: http://stackoverflow.com/q/50701690
score: 0
has comment: http://stackoverflow.com/comment/88715149
tagged with: python-3.x
has body: I'm currently following a PyTorch tutorial, and I'm trying to get this example to work. However, upon running the line dataiter = iter(trainloader) my program first does something I don't understand how it's possible – it seems to jump backwards in the program and re-run lines of codes which it has already run even though there is no loop. Then it runs into a BrokenPipeError and crashes. Here is a minimal working example that triggers the problem: import torch import torchvision import torchvision.transforms as transforms transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) dataiter = iter(trainloader) and this is the output I'm getting: "D:\Program Files\Python35\python.exe" D:/work/programs/pytorch/60_minute_blitz_tutorial/3_training_a_classifier/MWE.py Files already downloaded and verified Files already downloaded and verified Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "D:\Program Files\Python35\lib\multiprocessing\spawn.py", line 106, in spawn_main exitcode = _main(fd) File "D:\Program Files\Python35\lib\multiprocessing\spawn.py", line 115, in _main prepare(preparation_data) File "D:\Program Files\Python35\lib\multiprocessing\spawn.py", line 226, in prepare _fixup_main_from_path(data['init_main_from_path']) File "D:\Program Files\Python35\lib\multiprocessing\spawn.py", line 278, in _fixup_main_from_path run_name="__mp_main__") File "D:\Program Files\Python35\lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "D:\Program Files\Python35\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "D:\Program Files\Python35\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\work\programs\py…
type: UnansweredQuestion

http://stackoverflow.com/q/50710258
tagged with: sympy
has answer: http://stackoverflow.com/a/50718831
tagged with: symbolic-math
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88442692
tagged with: python
has title: Exponentiate symbolic matrix expression using SymPy
accepted answer: http://stackoverflow.com/a/50718831
type: AnsweredQuestion
score: 2
upvote count: 2
has body: I am trying to work with the multivariate normal distribution in symbolic form using SymPy. However, it doesn't seem capable of realizing that the matrix expression I want to exponentiate evaluates to a scalar. Here's the code: from sympy import * # Sample size, number of covariates n, k = symbols('n k') # Data X = MatrixSymbol('X', n, k) y = MatrixSymbol('y', n, 1) # Parameters beta = MatrixSymbol('beta', k, 1) Sigma = MatrixSymbol('Sigma', n, n) # Exponent expression, OK: (-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta)) # Trying to use as exponent, not OK: exp(-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta)) The error message that follows: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-76-62c854b75962&gt; in &lt;module&gt;() ----&gt; 1 exp((-Rational(1, 2)*(y - X*beta).T*Sigma*(y - X*beta))) D:\Programming\Anaconda3\lib\site-packages\sympy\core\function.py in __new__(cls, *args, **options) 425 426 evaluate = options.get('evaluate', global_evaluate[0]) --&gt; 427 result = super(Function, cls).__new__(cls, *args, **options) 428 if not evaluate or not isinstance(result, cls): 429 return result D:\Programming\Anaconda3\lib\site-packages\sympy\core\function.py in __new__(cls, *args, **options) 248 249 if evaluate: --&gt; 250 evaluated = cls.eval(*args) 251 if evaluated is not None: 252 return evaluated D:\Programming\Anaconda3\lib\site-packages\sympy\functions\elementary\exponential.py in eval(cls, arg) 300 301 elif arg.is_Matrix: --&gt; 302 return arg.exp() 303 304 @property AttributeError: 'MatMul' object has no attribute 'exp'
type: Question

http://stackoverflow.com/a/50714002
type: Answer
has comment: http://stackoverflow.com/comment/88450444
has comment: http://stackoverflow.com/comment/88437457
has body: try this one, following suggestions provided here: self.request.files['1'][0]['body'].decode('iso-8859-1').encode('utf-8')
has comment: http://stackoverflow.com/comment/88439720
answers question: http://stackoverflow.com/q/50713390
has comment: http://stackoverflow.com/comment/88445549
has comment: http://stackoverflow.com/comment/88439168
score: 0
has comment: http://stackoverflow.com/comment/88437256

http://stackoverflow.com/q/50744516
tagged with: argparse
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88497606
tagged with: python
has answer: http://stackoverflow.com/a/50744651
type: Question
has title: argparse: How to stop interpreting arguments after first argument not starting with '-'?
tagged with: command-line-arguments
has body: I am writing a command line tool that executes other commands in a sandbox. The basic usage of my tool is: my_tool 'echo "hello"' which executes echo "hello". I would like to be able to write my_tool echo "hello" instead; however, this results in my_tool: error: unrecognized arguments: hello because besides the main argument, my tool takes only the boolean option -n. I would like to have parse_args() realize that echo "hello" is the main argument even if not enclosed by ticks because echo starts without a minus, and thus signalizes the beginning of the main argument. I have tried parse_known_args(). However, options of the sandboxed tool get mixed into options of my own tool, e.g.: my_tool echo -n "hello" has the same result as my_tool -n echo "hello" which it shouldn't.
score: 0

http://stackoverflow.com/a/50768681
has comment: http://stackoverflow.com/comment/88544991
accepted answer of: http://stackoverflow.com/q/50768544
has comment: http://stackoverflow.com/comment/88545125
upvote count: 6
has comment: http://stackoverflow.com/comment/88545234
has body: Matplotlib cannot work with colour.Color instances. You may convert those to RGB values if you like. Next, pandas does not like to be given several colors. But you may use a matplotlib plot instead. import matplotlib.pyplot as plt import pandas as pd from colour import Color df = pd.DataFrame({"x" : list(range(3,13))}) red = Color("red") colors = list(red.range_to(Color("green"),10)) colors = [color.rgb for color in colors] plt.bar(df.index, df["x"], color=colors) plt.xlabel('Column', labelpad=12) plt.tight_layout() plt.show() Note that usually you would rather work with a colormap. You may call this colormap with the normalized values according to which you want to colorize your bars. import matplotlib.pyplot as plt import matplotlib.colors as mcolors import pandas as pd import numpy as np df = pd.DataFrame({"x" : np.random.rand(10)*10}) cmap = mcolors.LinearSegmentedColormap.from_list("", ["red", "yellow", "green"]) plt.bar(df.index, df["x"], color=cmap(df.x.values/df.x.values.max())) plt.xlabel('Column', labelpad=12) plt.tight_layout() plt.show()
type: AcceptedAnswer
score: 6
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50768544

http://stackoverflow.com/a/50705742
has comment: http://stackoverflow.com/comment/88421311
downvote count: 1
has comment: http://stackoverflow.com/comment/88421911
has comment: http://stackoverflow.com/comment/88421657
has comment: http://stackoverflow.com/comment/88422441
answers question: http://stackoverflow.com/q/50705637
has comment: http://stackoverflow.com/comment/88422703
upvote count: 5
has comment: http://stackoverflow.com/comment/88422481
has comment: http://stackoverflow.com/comment/88421256
has comment: http://stackoverflow.com/comment/88422030
has comment: http://stackoverflow.com/comment/88422596
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88423000
has comment: http://stackoverflow.com/comment/88422895
type: Answer
has comment: http://stackoverflow.com/comment/88423046
score: 4
has comment: http://stackoverflow.com/comment/88421830
has comment: http://stackoverflow.com/comment/88422104
has comment: http://stackoverflow.com/comment/88420937
has comment: http://stackoverflow.com/comment/88422460
has comment: http://stackoverflow.com/comment/88422256
has body: From documentation of numpy.linalg.lstsq(): residuals : {(), (1,), (K,)} ndarray ... If the rank of a is < N or M <= N, this is an empty array. ... The rank of your matrix is 1. NOTE: What you think are "missing" residuals can be found using numpy as well (you do not need other packages): residuals = y - np.dot(A, model_parameters)
accepted answer of: http://stackoverflow.com/q/50705637

http://stackoverflow.com/comment/88559030
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50775649
has text: yes, that works! thanks @cricket_007
score: 0

http://stackoverflow.com/q/50733329
type: Question
has comment: http://stackoverflow.com/comment/88474640
tagged with: python
linked to: http://stackoverflow.com/q/3845018
upvote count: 2
has comment: http://stackoverflow.com/comment/88474546
has comment: http://stackoverflow.com/comment/88474490
answer count: 1
downvote count: 1
has body: Can Someone Explain the Difference between logical and Boolean &amp; in this code def isprime(num): return [i for i in range(2,num) if num%i==0]==[] num_which_are_prime=[i for i in range(1,100) if isprime(i) and i!=1] print(num_which_are_prime) num_which_are_prime=[i for i in range(1,100) if isprime(i) &amp; i!=1] print(num_which_are_prime) Shows this: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] [2, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99]
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50733476
tagged with: python-2.7
has title: Can Someone Explain the difference between Logical and Boolean And in this Case,
has comment: http://stackoverflow.com/comment/88474437
has comment: http://stackoverflow.com/comment/88474651
score: 1
tagged with: boolean-logic
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50712607
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50712748
has answer: http://stackoverflow.com/a/50712748
has title: Crawler data form website use Scrapy 1.5.0 - Python
type: Question
has body: I try to crawler data form a website with Scrapy (1.5.0)- Python Project directory : stack/ scrapy.cfg stack/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py stack_spider.py Here is my items.py import scrapy class StackItem(scrapy.Item): title = scrapy.Field() and here is stack_spider.py from scrapy import Spider from scrapy.selector import Selector from stack.items import StackItem class StackSpider(Spider): name = "stack" allowed_domains = ["batdongsan.com.vn"] start_urls = [ "https://batdongsan.com.vn/nha-dat-ban", ] def parse(self, response): questions = Selector(response).xpath('//div[@class="p-title"]/h3') for question in questions: item = StackItem() item['title'] = question.xpath( 'a/text()').extract()[0] yield item I don't know why i can't crawler the data, i really need your help. Thanks
accepted answer: http://stackoverflow.com/a/50716860
score: 0
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50716860
has answer: http://stackoverflow.com/a/50715455
tagged with: scrapy
has answer: http://stackoverflow.com/a/50715022

http://stackoverflow.com/q/50731253
tagged with: merge
has body: I have two dataframes as below. I want to combine these two dataframes in the following rule. First, I want to focus on column A,B,C,and D. If those values are all same among two dataframes, I want to calculate the sum of the value. Also, for column E, I want to leave the df1 value. The expected outcome is below figure. If you could help, I would appreciate it very much. Thank you very much for your help.
type: AnsweredQuestion
has title: How to combine dataframes in specific situations?
tagged with: dataframe
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50731337
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50731337
has comment: http://stackoverflow.com/comment/88470233
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88470207
has comment: http://stackoverflow.com/comment/88470482
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88663077
comment on: http://stackoverflow.com/q/50829381
type: QuestionComment
score: 1
has text: Didn't you forget the second, not duplicated 'aaa'? `li_count = [['aaa',1],['bbb',1],['aaa',1],['abb',2],['bbb',3],['aaa,2]]` should be correct. And please, show what your attempts look like so far and why do they not work.
type: Comment

http://stackoverflow.com/q/50773936
linked to: http://stackoverflow.com/q/423379
tagged with: definition
type: Question
tagged with: if-statement
tagged with: boolean
score: 0
has title: Python 3 - Boolean not working within definitions
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/423379
has comment: http://stackoverflow.com/comment/88554982
type: UnansweredQuestion
has body: I've been working on a choose your own adventure-type game as my final project for a school assignment, but I noticed that boolean values don't work within functions, I've added some test code to show this: tv = False def defin(): if if_stat == 'A': tv = True if_stat = input("") print(tv) #Before anything is done defin() print(tv) #Definition result if if_stat == 'A': tv = True print(tv) #If statement result I don't see what's going wrong and I need these values to be changed by if statements within definitions for my project.
tagged with: python
has comment: http://stackoverflow.com/comment/88554958
answer count: 0

http://stackoverflow.com/a/50728741
score: 5
has comment: http://stackoverflow.com/comment/88532264
type: AcceptedAnswer
downvote count: 0
has body: For this we use floodFill function. import cv2 import numpy as np if __name__ == '__main__': # read image and convert to gray img = cv2.imread('image.png',cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # threshold the gray image to binarize, and negate it _,binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY) binary = cv2.bitwise_not(binary) # find external contours of all shapes _,contours,_ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # create a mask for floodfill function, see documentation h,w,_ = img.shape mask = np.zeros((h+2,w+2), np.uint8) # determine which contour belongs to a square or rectangle for cnt in contours: poly = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt,True),True) if len(poly) == 4: # if the contour has 4 vertices then floodfill that contour with black color cnt = np.vstack(cnt).squeeze() _,binary,_,_ = cv2.floodFill(binary, mask, tuple(cnt[0]), 0) # convert image back to original color binary = cv2.bitwise_not(binary) cv2.imshow('Image', binary) cv2.waitKey(0) cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/88468520
accepted answer of: http://stackoverflow.com/q/50728186
type: Answer
answers question: http://stackoverflow.com/q/50728186
has comment: http://stackoverflow.com/comment/88531402
has comment: http://stackoverflow.com/comment/88533247
has comment: http://stackoverflow.com/comment/88530977
has comment: http://stackoverflow.com/comment/88598478
upvote count: 5
has comment: http://stackoverflow.com/comment/88531597
has comment: http://stackoverflow.com/comment/88530052
has comment: http://stackoverflow.com/comment/88534598

fullcalendar
tags question: http://stackoverflow.com/q/50787842
tag name: fullcalendar
type: Tag

performance
tags question: http://stackoverflow.com/q/50806601
tags question: http://stackoverflow.com/q/50778302
tags question: http://stackoverflow.com/q/50726080
tags question: http://stackoverflow.com/q/50798432
tags question: http://stackoverflow.com/q/50814296
tags question: http://stackoverflow.com/q/50731160
tags question: http://stackoverflow.com/q/50802583
tags question: http://stackoverflow.com/q/50764548
tags question: http://stackoverflow.com/q/50786498
tags question: http://stackoverflow.com/q/50752438
tags question: http://stackoverflow.com/q/50831284
tags question: http://stackoverflow.com/q/50724196
tags question: http://stackoverflow.com/q/50815015
tags question: http://stackoverflow.com/q/50712202
tags question: http://stackoverflow.com/q/50776263
tags question: http://stackoverflow.com/q/50773556
tags question: http://stackoverflow.com/q/50765131
tags question: http://stackoverflow.com/q/50712114
tags question: http://stackoverflow.com/q/50749481
tags question: http://stackoverflow.com/q/50838886
tags question: http://stackoverflow.com/q/50754020
tag name: performance
tags question: http://stackoverflow.com/q/50699713
tags question: http://stackoverflow.com/q/50804499
tags question: http://stackoverflow.com/q/50779617
type: Tag
tags question: http://stackoverflow.com/q/50728117
tags question: http://stackoverflow.com/q/50836427
tags question: http://stackoverflow.com/q/50726104
tags question: http://stackoverflow.com/q/50731549
tags question: http://stackoverflow.com/q/50822099
tags question: http://stackoverflow.com/q/50799820
tags question: http://stackoverflow.com/q/50801103

http://stackoverflow.com/comment/88696306
type: Comment
score: 0
has text: @Rohi as mentioned, you won't find a solution to that with the same process for the aforementioned reasons. You could use another process to monitor the to be killed process but obviously without access to the variables. Not sure why you need a solution to that. What do you think the point of forcfully killing the process is? It is up to the OS to clean up local resources like memory and for the remote service to handle connection loses. My 'bonus' was not a solution but a counter to not being able to use a context manager.
comment on: http://stackoverflow.com/a/50846073
type: AnswerComment

http://stackoverflow.com/a/50710440
has comment: http://stackoverflow.com/comment/88462649
has body: Here's an Xpath 1.0 query that gets the expected result. Tested with XML without namespaces since OP did not post a complete sample "//observation[code[@displayName="Height"]]/*[self::effectiveTime | self::value | self::code]/@*[name()="value" or name()="unit" or name()="displayName"] Parts of the XPath details: Get node containing interesting nodes: "//observation[code[@displayName="Height"]]" Get interesting nodes "*[self::effectiveTime | self::value | self::code]" children of the node above. Meaning any node that is effectiveTime, value or code. Given the above nodes, get attributes whose names are value, unit or diaplayName: "@*[name()="value" or name()="unit" or name()="displayName"]" Testing on command line xmllint --xpath '//observation[code[@displayName="Height"]]/*[self::effectiveTime | self::value | self::code]/@*[name()="value" or name()="unit" or name()="displayName"]' test.xml | tr ' ' '\n'; echo Result, attributes appear in document order: displayName="Height" value="20110130" unit="Inches" value="61.2598" In case of trouble, get the node containing expected values and then find them taking it as a reference // find an observation node containing a code node with a displayName attribute = "Height" refNode = root.find(".//{urn:hl7-org:v3}observation[{urn:hl7-org:v3}code[@displayName='Height']]") for each in refNode.findall("some xpath"): ...
has comment: http://stackoverflow.com/comment/88469804
has comment: http://stackoverflow.com/comment/88461146
score: 0
answers question: http://stackoverflow.com/q/50708574
type: Answer
has comment: http://stackoverflow.com/comment/88465693

http://stackoverflow.com/a/50737557
answers question: http://stackoverflow.com/q/50737279
score: 0
has body: Here's one way using a comprehension and a lookup dictionary, which should be more easily expandable to include more characters: mapping = {'Q': 'R', 'D': 'U'} seq = input('Enter the sequence:') new = ''.join(mapping.get(c, c) for c in seq) Example input 'QUAD' becomes 'RUAU'.
type: Answer

http://stackoverflow.com/q/50701322
has comment: http://stackoverflow.com/comment/88413718
answer count: 2
has comment: http://stackoverflow.com/comment/88412877
has comment: http://stackoverflow.com/comment/88412900
upvote count: 3
downvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/25981703
has body: I am trying to install PIP using python get-pip.py and since I am behind a corporate firewall, the installation keeps failing. $ python get-pip.py Collecting pip Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pip/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pip/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pip/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pip/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pip/ Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)) - skipping Could not find a version that satisfies the requirement pip (from versions: ) No matching distribution found for pip Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)) - …
has comment: http://stackoverflow.com/comment/88413353
score: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50701407
tagged with: pip
type: Question
has title: Unable to install PIP behind a corporate firewall
has comment: http://stackoverflow.com/comment/88420158
has answer: http://stackoverflow.com/a/71680403
linked to: http://stackoverflow.com/q/4750806
has comment: http://stackoverflow.com/comment/88412794
has comment: http://stackoverflow.com/comment/88437471
has comment: http://stackoverflow.com/comment/88412561
favorite count: 0
has comment: http://stackoverflow.com/comment/88412031

http://stackoverflow.com/a/50749634
has body: Creating the appropriate header over the corresponding column did the trick: import pandas as pd df = pd.read_csv('test2_output copy.tsv', sep='\t', names=['Cluster Number', '#', 'Cluster_Type']) df.Cluster_Type.value_counts() Output: t1pks 7 nrps 7 other 3 terpene 2 t1pks-nrps 1 indole 1 Thanks, 'The Unfun Cat'
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50748511
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88565487
has text: What do you mean by "arbitrary phonemes" ? You can extend cmudict with new words and their phoneme sequence using g2p tool and then do reverse search for phonemes.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50774065

http://stackoverflow.com/comment/101601588
type: AnswerComment
type: Comment
score: 2
has text: @LuisFelipe, the moment I wrote my reply the OpenCV 4 was not released yet, so I worked with OpenCV 3. I'll check my code with the OpenCV 4 and will add an update later.
comment on: http://stackoverflow.com/a/51756462

http://stackoverflow.com/q/50730012
type: Question
score: 5
has answer: http://stackoverflow.com/a/50748768
upvote count: 6
tagged with: pybind11
answer count: 2
downvote count: 1
has title: What is the proper syntax to bind a typedef type using pybind11?
favorite count: 0
has body: I have a struct very similar to this: struct data_point { data_point() = delete; data_point(const int&amp; data) : m_data(data) {} int m_data; }; I also have this type declared as such. typedef std::vector&lt;data_point&gt; data_list; The binding for this struct is defined: PYBIND11_MODULE(data_lib, ref) { py::class_&lt;data_point&gt; dp(ref, "data_point"); dp.def(py::init&lt;const int&amp;&gt;()); dp.def_readwrite("m_data", &amp;data_point::m_data); } How do I define a binding for the typedef list type? Its not clear to me how to do this in the pybind documentation.
tagged with: python
possible better answer: http://stackoverflow.com/a/77865531
tagged with: c++
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77865531
tagged with: syntax
accepted answer: http://stackoverflow.com/a/50748768

http://stackoverflow.com/q/50785020
has comment: http://stackoverflow.com/comment/88576710
duplicate of: http://stackoverflow.com/q/25445439
downvote count: 5
tagged with: python-2.7
upvote count: 0
score: -5
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50785164
has comment: http://stackoverflow.com/comment/88576773
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88576677
has comment: http://stackoverflow.com/comment/88576516
has comment: http://stackoverflow.com/comment/88576597
tagged with: python
linked to: http://stackoverflow.com/q/25445439
has title: why am I getting a syntax error in python 2.7.14
has comment: http://stackoverflow.com/comment/88576512
has comment: http://stackoverflow.com/comment/88576563
has comment: http://stackoverflow.com/comment/88576770
type: Question
has body: coord = {'latitude' : '37.24N' , 'longitude' : '-115.81'} print 'coordinates: {latitude}, {longitude}' .format(**coord) I've been recently following this new program on learning python and I've come across an error that says SyntaxError: invalid syntax,but I can't spot any syntax errors, if anyone can offer help it would be much appreciated.

http://stackoverflow.com/comment/88542169
has text: How do I check that? If it is type float, could its still be inferred as a string?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50767299

http://stackoverflow.com/comment/88512998
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50740336
score: 0
has text: @Harvey, you need to provide an output location for an Athena query, even if you read the results directly into your code. [Lambda Python request athena error OutputLocation ](https://stackoverflow.com/questions/47551305/lambda-python-request-athena-error-outputlocation/47559999#47559999)

http://stackoverflow.com/a/50788209
has comment: http://stackoverflow.com/comment/88582918
answers question: http://stackoverflow.com/q/50788144
score: 0
has comment: http://stackoverflow.com/comment/88653609
type: Answer
has body: You are only returning the first match, you should build up a list as you iterate over the first list. def find_smallest(xy): m = None matches = [] for i, n in enumerate(xy): if n == m: matches.append((n, i)) if m is None or n &lt; m: m = n matches = [(n, i)] return matches print(find_smallest([0,1,2,0,3])) # [(0, 0), (0, 3)] print(find_smallest([6,0,1,2,0,3])) # [(0, 1), (0, 4)]

http://stackoverflow.com/a/50795580
answers question: http://stackoverflow.com/q/50794468
score: 20
upvote count: 20
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50794468
has body: I have successfully achieved it by changing mocker.patch('main.utils.string.get_random_string', return_value='123456') to mocker.patch('engine.get_random_string', return_value='123456'). Details can be found here.

http://stackoverflow.com/a/50776741
has body: You could not do that as rightly pointed out by @Willem See below interpreter example &gt;&gt;&gt; dict1={0:"abc",1:"ab",2:"a"} &gt;&gt;&gt; dict1.keys() dict_keys([0, 1, 2]) &gt;&gt;&gt; for key in dict1.keys(): ... print(key) ... The output would be as follows 0 1 2 But in python 2 it is possible thar you get list in return to your call to dictionary keys &gt;&gt;&gt; dict1={0:"New York", 1:"California", 2:"Bangalore"} &gt;&gt;&gt; dict1.keys() [0, 1, 2] So as suggested above make appropriate changes for your code to work
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50776631
upvote count: 1

http://stackoverflow.com/comment/88533316
type: AnswerComment
type: Comment
has text: Thanks for your Answer; i confirm your presentation completely. thanks for that. My problem is the second condition: foo(**b) should not be changed is this possible too
comment on: http://stackoverflow.com/a/50726314
score: 0

http://stackoverflow.com/q/50784875
upvote count: 1
tagged with: tensorflow
type: Question
has title: Magenta Attention_RNN: Nan Loss during training
tagged with: magenta
downvote count: 0
score: 1
tagged with: python
has body: This is in the context of the Google Magenta package, specifically the melody RNN model. I have tried training a basic_rnn with my own dataset and it worked well, producing a usable checkpoint. However, when I try to use an attention_rnn instead, by adding the "attn_length=40" to the hparams, I get the error "NaN loss during training.". I have tried changing the attn_length to other values such as 10 or 20 and I still get this error. Also, I made sure to create the dataset using the "attention_rnn" parameter, so that should not be an issue. Anyone have any similar issues? Here are the commands I used: convert_dir_to_note_sequences --input_dir=$INPUT_DIRECTORY --output_file=$SEQUENCES_TFRECORD --recursive melody_rnn_create_dataset --config="attention_rnn" --input=".../mono_notesequences.tfrecord" --output_dir="..." --eval_ratio="0.10" python ${MODEL}/melody_rnn_train.py --config=attention_rnn --run_dir=${OUTPUT} --sequence_example_file=${INPUT}/attention_rnn/training_melodies.tfrecord --hparams="batch_size=128,rnn_layer_sizes=[512,512],attn_length=40" --num_training_steps=20000
favorite count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88691622
has text: @DeliriousLettuce, i think i should agree with DyZ, because..defaults change over time. and he mentioned it because he wanted the user to know what's the default
comment on: http://stackoverflow.com/a/50843926
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/50843495
has comment: http://stackoverflow.com/comment/88691412
type: Answer
upvote count: 1
score: 1
has body: This is overkill to use Pandas to sort a list: lot_file = pd.DataFrame() lot_file['SPOOL'] = ['A39','B34','A3','B37','A6','B18','A48','B15','A47'] group_lots = lot_file.sort_values(by=['SPOOL']) group_lots['SPOOL'].tolist() Output: ['A3', 'A39', 'A47', 'A48', 'A6', 'B15', 'B18', 'B34', 'B37'] Or use sorted spool_list = ['A39','B34','A3','B37','A6','B18','A48','B15','A47'] sorted(spool_list) Output: ['A3', 'A39', 'A47', 'A48', 'A6', 'B15', 'B18', 'B34', 'B37']
downvote count: 0
answers question: http://stackoverflow.com/q/50843370

http://stackoverflow.com/a/50782032
answers question: http://stackoverflow.com/q/50781888
downvote count: 0
has comment: http://stackoverflow.com/comment/88570903
has comment: http://stackoverflow.com/comment/88570983
type: Answer
has body: Python 3: # -*- coding: utf-8 -*- import os os.mkdir('Gebäude') Python 2.7: # -*- coding: utf-8 -*- import os os.mkdir(u'Gebäude') At least this works on macOS, I hope it helps.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88571007

http://stackoverflow.com/comment/88688410
has text: no mention of shuffling some collection in the question. just to get a random variable that is not present in a list
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50842408

http://stackoverflow.com/comment/88706525
type: QuestionComment
has text: @Jakob: could you at least confirm the version of python you are using? The default `python` tag assumes python 3, if you are still on Python 2 then please use the correct tag.
score: 0
comment on: http://stackoverflow.com/q/50851359
type: Comment

http://stackoverflow.com/comment/88710412
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50853397
has text: Do you face the same error while doing `pip install simplejson`? Can you try that and edit your question with any new problem that shows up. Also please don't post screenshots, copy paste the text in the error message and format it using `Ctrl+K`
score: 0

http://stackoverflow.com/comment/88637613
type: Comment
type: AnswerComment
has text: @eryksun Gee, thanks for the info! Anyway, the important thing is, Python doesn't catch it by default and makes it disproportionally hard to catch it otherwise, so this will work almost always. While Ctrl-C won't if there's so much as the dreaded `except:`.
score: 0
comment on: http://stackoverflow.com/a/50784998

http://stackoverflow.com/comment/88689750
type: Comment
score: 2
type: AnswerComment
has text: Nitpick: they are all terminal emulators, a "real terminal" would be *a physical video terminal* like this: https://en.wikipedia.org/wiki/VT100
comment on: http://stackoverflow.com/a/50842919

http://stackoverflow.com/q/50784540
has body: I want to make a Seq2Seq model for reconstruction purpose. I want a model trained to reconstruct the normal time-series and it is assumed that such a model would do badly to reconstruct the anomalous time-series having not seen them during training. I have some gaps in my code and also in the understanding. I took this as an orientation and did so far: traindata: input_data.shape(1000,60,1) and target_data.shape(1000,50,1) with target data being the same training data only in reversed order as sugested in the paper here. for inference: I want to predict another time series data with the trained model having the shape (3000,60,1). T Now 2 points are open: how do I specify the input data for my training model and how do I build the inference part with the stop condition ? Please correct any mistakes. from keras.models import Model from keras.layers import Input from keras.layers import LSTM from keras.layers import Dense num_encoder_tokens = 1#number of features num_decoder_tokens = 1#number of features encoder_seq_length = None decoder_seq_length = None batch_size = 50 epochs = 40 # same data for training input_seqs=()#shape (1000,60,1) with sliding windows target_seqs=()#shape(1000,60,1) with sliding windows but reversed x= #what has x to be ? #data for inference # how do I specify the input data for my other time series ? # Define training model encoder_inputs = Input(shape=(encoder_seq_length, num_encoder_tokens)) encoder = LSTM(128, return_state=True, return_sequences=True) encoder_outputs = encoder(encoder_inputs) _, encoder_states = encoder_outputs[0], encoder_outputs[1:] decoder_inputs = Input(shape=(decoder_seq_length, num_decoder_tokens)) decoder = LSTM(128, return_sequences=True) decoder_outputs = decoder(decoder_inputs, initial_state=encoder_states) decoder_outputs = TimeDistributed( Dense(num_decoder_tokens, activation='tanh'))(decoder_outputs) model = Model([encoder_inputs, decoder_inputs], decoder_outputs) # Training model.compile(optimizer='adam', loss…
tagged with: lstm
possible better answer: http://stackoverflow.com/a/50789970
upvote count: 2
answer count: 3
accepted answer: http://stackoverflow.com/a/50858610
has answer: http://stackoverflow.com/a/50789970
has comment: http://stackoverflow.com/comment/103977123
has title: seq2seq prediction for time series
tagged with: keras
has answer: http://stackoverflow.com/a/50858610
tagged with: python
has comment: http://stackoverflow.com/comment/103977027
has answer: http://stackoverflow.com/a/50858131
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: tensorflow
type: Question
tagged with: time-series

http://stackoverflow.com/comment/88497724
comment on: http://stackoverflow.com/q/50743951
has text: This won't work because you are installing from a wheel. When using `--install-scripts`, `pip` will warn you about it being unable to use wheels. Build a source distribution of `my-package` (`python setup.py sdist`) and pass the resulting file to `pip` instead of the wheel for your command to work.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50780361
has comment: http://stackoverflow.com/comment/88567459
tagged with: tensorflow
type: Question
upvote count: 2
has title: In Tensorflow how to deal with Input and Out_backprop must have the same batch size
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50790132
has comment: http://stackoverflow.com/comment/88567477
accepted answer: http://stackoverflow.com/a/50790132
score: 2
type: AnsweredQuestion
has body: I am trying to repeat an experiment involved in the paper called Composite Functional Gradient Learning of Generative Adversarial Models. In this process, I have met an error that I have never seen before. I do not know what causes this problem. I hope someone who can help me. Thank you so much! The following is my coding. I think the problem is at 'self.generator(index, reuse=True)'. The self.zs is defined as follow. self.sz = np.random.uniform(-1, 1, size=(self.sz_num, self.z_dim)).astype(np.float32) I just want to sample 64 pieces of data from self.sz as the input for my generator. # Update the G network if self.iteration == 1: for i in range(0, 10): index_g = self.sz[i:(i+1)*self.batch_size] temp = self.generator(index_g, reuse=True) self.prev_G_tf.append(temp) temp = temp.eval(session=self.sess) self.prev_G.extend(temp) Every time, I run this code, I get the error as the following. Caused by op 'generator_2/g_h1_deconv/conv2d_transpose', defined at: File "G:/deep_learning/XICFG/main.py", line 107, in &lt;module&gt;tf.app.run() File "C:\Users\XJTU-GY\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 126, in run _sys.exit(main(argv)) File "G:/deep_learning/XICFG/main.py", line 90, in main dcgan.train(FLAGS) File "G:\deep_learning\XICFG\model.py", line 239, in train temp = self.generator(index_g, reuse=True) File "G:\deep_learning\XICFG\model.py", line 336, in generator self.h1 = deconv2d(self.h0, [self.batch_size, 7, 7, self.gf_dim * 2], name='g_h1_deconv', with_w=False) File "G:\deep_learning\XICFG\ops.py", line 75, in deconv2d strides=[1, d_h, d_w, 1]) File "C:\Users\XJTU- GY\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1258, in conv2d_transpose name=name) File "C:\Users\XJTU-GY\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_nn_ops.py", line 1336, in conv2d_backprop_input dilations=dilations, name=name) File "C:\Users\X…
downvote count: 0

http://stackoverflow.com/a/50807163
has body: The problem is that you're storing (pID,userID) as part of a tuple stored in sqlquery, instead of passing them as the arguments to execute: sqlquery='''UDPATE likesartmovement SET likesartmovement.rating=%s WHERE likesartmovement.artisticID=? AND likesartmovement.userID=?''' % (rate,) cursor.execute(sqlquery, (pID,userID)) It may be clearer to see why these are different if you take a simpler example: s = 'abc' spam(s, 2) s = 'abc', 2 spam(s) Obviously those two don't do the same thing. While we're at it: You have to spell UPDATE right. You usually want to use query parameters for SET clauses for exactly the same reasons you want to for WHERE clauses. You don't need to include the table name in single-table operations, and you're not allowed to include the table name in SET clauses in single-table updates. So: sqlquery='''UDPATE likesartmovement SET rating=? WHERE artisticID=? AND userID=?''' cursor.execute(sqlquery, (rating, pID, userID))
has comment: http://stackoverflow.com/comment/88620149
score: 1
answers question: http://stackoverflow.com/q/50807088
has comment: http://stackoverflow.com/comment/88620079
has comment: http://stackoverflow.com/comment/88620121
accepted answer of: http://stackoverflow.com/q/50807088
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/50748971
tagged with: pandas
has comment: http://stackoverflow.com/comment/88505666
has title: Element difference of a list inside a dataframe
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88505384
has comment: http://stackoverflow.com/comment/88505573
has answer: http://stackoverflow.com/a/50749266
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88505487
has body: I have a pandas dataframe with lists inside one of the columns (LOG_TIMES), how can I create a new column with the time differences (in seconds) of the list elements? DATE_RECORDED PERSON LOG_TIMES 0 2018-03-22 11:58:23.585 JOHN [15/03/2018 10:30:48, 15/03/2018 10:29:48, ... 1 2018-03-22 11:58:23.585 JOHN [20/03/2018 14:28:36, 20/03/2018 14:26:36, ... The expected output would be the datafame with a column displaying the time differences (values in seconds): DATE_RECORDED PERSON LOG_TIMES 0 2018-03-22 11:58:23.585 JOHN [60, ... 1 2018-03-22 11:58:23.585 JOHN [120, ...
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50749266
score: 0

http://stackoverflow.com/comment/88671098
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50833013
score: 0
has text: Thanks for the vote of confidence @FHTMitchell :-|

http://stackoverflow.com/q/50808757
linked to: http://stackoverflow.com/q/7946798
has answer: http://stackoverflow.com/a/50808910
upvote count: 27
has title: Interleave 4 lists of same length python
has answer: http://stackoverflow.com/a/50808771
has answer: http://stackoverflow.com/a/50816127
has answer: http://stackoverflow.com/a/50808784
tagged with: arrays
answer count: 7
duplicate of: http://stackoverflow.com/q/7946798
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50808784
tagged with: python
accepted answer: http://stackoverflow.com/a/50808771
has body: I want interleave 4 lists of same length in python. I search this site and only see how to interleave 2 in python: Interleaving two lists in Python Can give advice for 4 lists? I have lists like this l1 = ["a","b","c","d"] l2 = [1,2,3,4] l3 = ["w","x","y","z"] l4 = [5,6,7,8] I want list like l5 = ["a",1,"w",5,"b",2,"x",6,"c",3,"y",7,"d",4,"z",8]
has answer: http://stackoverflow.com/a/50809030
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50808942
type: Question
downvote count: 5
score: 22
has answer: http://stackoverflow.com/a/50808888

http://stackoverflow.com/comment/88583990
type: QuestionComment
has text: That's because you call str on list. If you iterate `pytz.all_timezones` directly and than call `.lower()` on each of it - you would get expected result
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50788809

http://stackoverflow.com/q/50745076
has comment: http://stackoverflow.com/comment/88510597
score: 0
has body: I want to import W matrix from script_1 to script_2. How can I do that? Script_1 `def main(): W=W_fc.eval() Script_2 `from Script_1 import W os.system("python Script_1.py") print W`
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88498503
has title: Importing matrix from one file to other using os.system

http://stackoverflow.com/q/50821463
tagged with: python
has answer: http://stackoverflow.com/a/50837731
answer count: 1
has comment: http://stackoverflow.com/comment/88648201
score: 0
has comment: http://stackoverflow.com/comment/88669277
has title: OSQuery and Python extensions with virtualenv
tagged with: monitoring
type: UnansweredQuestion
tagged with: osquery
type: Question
has body: I'm using OSQuery throught osqueryi and/or osqueryd on Windows. I've written some Python extensions (tables) and I try using virtualenv to run these Python extensions. When I run osqueryi.exe and python extensions separately from command line, the extensions are loaded ok and I can query my python tables. In this scenario, I use virtualenv ok. When I use extensions.load, with my Python extensions and osquery.flags has the next content --disable_extensions=false --config_path=C:\ProgramData\osquery\osquery.conf --config_plugin=filesystem --logger_plugin=filesystem --logger_path=C:\ProgramData\osquery\log --extensions_autoload=C:\ProgramData\osquery\extensions.load In this scenario, osqueryi.exe shows the next error Traceback (most recent call last): File "C:\ProgramData\osquery\extensions\my_table.ext", line 3, in &lt;module&gt; import osquery ImportError: No module named osquery First, I activate my virtualenv and later I run osqueryi.exe with this osquery.flags file In both scenarios, I used the same virtualenv environment with external modules installed via pip. How can I configure OSquery To use virtualenv with Python Extensions. Thanks

http://stackoverflow.com/comment/88655192
has text: May I ak you to update the answer with sorting please
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50824727
type: AnswerComment

http://stackoverflow.com/q/50743216
has answer: http://stackoverflow.com/a/50743445
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88494967
type: Question
answer count: 2
has body: Assume I have a word list like [cat,hat,mat,ate] and I would like to to remove all the letter a in a string like acatbatmate to catbtmate if the letter a is not in the word list. In the current step, I can split the string by the words in the word list with the following codes: ''.join([word.replace('a','') if word not in ['cat','hat','mat','ate'] else word for word in re.split('(cat|hat|mat|ate)','acatbatmate') ]) Is it possible for me to use re.sub(pattern, repl, string) to remove the letter a straightforwardly?
downvote count: 0
possible better answer: http://stackoverflow.com/a/50743370
accepted answer: http://stackoverflow.com/a/50743445
favorite count: 0
has answer: http://stackoverflow.com/a/50743370
has title: Python Regular Expression: replace a letter if it is not a part of the word in a list
has comment: http://stackoverflow.com/comment/88494925
tagged with: regex
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88494305
upvote count: 2
tagged with: python

http://stackoverflow.com/a/50828159
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50828074
type: Answer
has body: This is because list.index(&lt;element&gt;) returns the index of the element. If the element appears more than once index() always returns index of the first occurrence. However, in your code you don't need to call index since you are accessing the element via mm that is already the index. Why not just append mm. Like: if self.Angle[mm] == 89.0: cc.append(mm) Moreover, same code can be elegantly written with list comprehension like: indexes = [x for x in range(0, len(self.Angle)) if self.Angle[x] == 89.0]
accepted answer of: http://stackoverflow.com/q/50828074
score: 0

http://stackoverflow.com/q/50784284
tagged with: where-clause
favorite count: 0
tagged with: python
has title: with numpy where: for black cell, putting new value in a column
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50784293
score: 1
upvote count: 1
type: Question
has body: I am working with numpy in a csv file. I have 3 columns. For 500 value in column 'PUMA', I wanted to put 5 in 'HTYPE' column. It worked with following code. But for a black cell(nan) in column 'PUMA'(3rd row), I wanted to put '-999' in the 'HTYPE' column. With the same code, it is not working. How to put a value in a column, if there is nan in another column, using np.where? import pandas as pd, numpy as np df= pd.read_csv(input_folder + input_file ) df['HTYPE'] = np.where(df['PUMA']==500, 5, df['HTYPE'] ) df['HTYPE'] = np.where(df['PUMA']==np.NaN, -999, df['HTYPE'] ) df.to_csv('output.csv', index=False)
tagged with: numpy
tagged with: pandas
has answer: http://stackoverflow.com/a/50784293
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50732317
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50732260
score: 2
has body: I don’t actually think it’s your aggregate counter that is slow, but your query set evaluation ie your data access. See Django ORM QuerySets are what’s know as “lazy”. They can be manipulated but evaluation (actually getting the data) is deferred until some triggering execution context. Here is the docs outlining this: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#when-querysets-are-evaluated When QuerySets are evaluated¶ Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset. So because of your timeit construct, it just looks like the bottleneck is your aggregate counter, buts it likely not. It’s likely the evaluation of the query set. There are some tactics for optimization of dB access, they are outlined here: https://docs.djangoproject.com/en/2.0/topics/db/optimization/ Without knowing a little more, we can’t be more specific. If you wouldn’t mind sharing your dB model and some details about how much data it’s actually getting, I’d be happy to help. You could run timeit on a forced evaluation with one of the methods outlined in the article , like using the built in list() on the query set, and have that happen before the counter constructor to know for sure.
accepted answer of: http://stackoverflow.com/q/50732260
has comment: http://stackoverflow.com/comment/88479726

http://stackoverflow.com/comment/88673482
type: Comment
type: QuestionComment
has text: Please do let me know if there is anything else you need to help me with this problem! @BryceRamgovind Thanks
score: 0
comment on: http://stackoverflow.com/q/50833473

http://stackoverflow.com/comment/88661011
type: Comment
has text: Added a section under the bold for you. Nothing has changed as far as I can tell.
type: QuestionComment
comment on: http://stackoverflow.com/q/50825707
score: 0

http://stackoverflow.com/a/50703084
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88415608
has comment: http://stackoverflow.com/comment/88415557
has comment: http://stackoverflow.com/comment/88415588
upvote count: 2
has comment: http://stackoverflow.com/comment/88420588
has body: IIUC you want: In[116]: df_grouped = df.groupby(['cc', 'odd', 'tree1', 'tree2']).filter(lambda x: (x['day'] &gt; 4).any()) df_grouped Out[116]: cc odd tree1 tree2 day 4 BB 3435 SAP ATK 3 5 BB 3435 SAP ATK 4 6 BB 3435 SAP ATK 5 7 BB 3435 SAP ATK 6 8 DD 3434 ASP ATK 2 9 DD 3434 ASP ATK 3 10 DD 3434 ASP ATK 4 11 DD 3434 ASP ATK 5 12 DD 3435 SAP ATK 1 13 DD 3435 SAP ATK 3 14 DD 3435 SAP ATK 5 15 DD 3435 SAP ATK 7 16 ZZ 3434 ASP ATK 1 17 ZZ 3434 ASP ATK 2 18 ZZ 3434 ASP ATK 6 19 ZZ 3434 ASP ATK 8 20 ZZ 3435 SAP ATK 2 21 ZZ 3435 SAP ATK 4 22 ZZ 3435 SAP ATK 6 23 ZZ 3435 SAP ATK 8 So this will filter out the groups where within the group none of the 'day' values are greater than 4 timings: %timeit df[df.day.gt(4).groupby([df.cc, df.odd, df.tree1, df.tree2]).transform('any')] %timeit df.groupby(['cc', 'odd', 'tree1', 'tree2']).filter(lambda x: (x['day'] &gt; 4).any()) %timeit df[df.assign(key=df.day &gt; 4).groupby(['cc', 'odd', 'tree1', 'tree2']).key.transform('any')] 100 loops, best of 3: 5.9 ms per loop 100 loops, best of 3: 5.42 ms per loop 100 loops, best of 3: 3.62 ms per loop So @coldspeed's first method is the fastest here
has comment: http://stackoverflow.com/comment/88415918
has comment: http://stackoverflow.com/comment/88416089
answers question: http://stackoverflow.com/q/50702709
type: Answer
has comment: http://stackoverflow.com/comment/88415634

http://stackoverflow.com/comment/88628723
comment on: http://stackoverflow.com/a/50811611
type: Comment
has text: why this line, can you explain `dct = defaultdict(list)`
score: 0
type: AnswerComment

http://stackoverflow.com/a/50833867
downvote count: 0
has comment: http://stackoverflow.com/comment/88673018
has comment: http://stackoverflow.com/comment/88681334
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88682980
has body: Be careful with your connections. In the first two blocks the BatchNormalization is not connected to the dropout. Change the input of the two first dropout. xx = Dense(256, activation = 'relu')(x) x1 = BatchNormalization()(xx) x2 = Dropout(0.3)(x1) y = Dense(256, activation = 'relu')(x2) yy = BatchNormalization()(y) y1 = Dropout(0.3)(yy) The values you give implies that your network is overfitting. The batch normalization or adding more dropout might help. But, given the small number of images you should really try image augmentation to increase the number of training images.
has comment: http://stackoverflow.com/comment/88672976
answers question: http://stackoverflow.com/q/50831870

http://stackoverflow.com/a/50825530
downvote count: 0
answers question: http://stackoverflow.com/q/50824974
type: Answer
has body: There are multiple ways to do this in tkinter, here's a rework of your code using StringVar objects set to the textvariable properties of your Entry objects: import tkinter as tk def doit(): out_string.set("Hello " + in_string.get()) root = tk.Tk() in_string = tk.StringVar() out_string = tk.StringVar() cat = tk.Entry(root, textvariable=in_string) cat.place(x=20, y=25, width=100) user = tk.Entry(root, textvariable=out_string) user.place(x=20, y=75) btn = tk.Button(root, text='START', command=doit) btn.place(x=20, y=150) root.mainloop() Per @Mike-SMT, here's a different approach using Entry.get() and Entry.insert(). It augments the text when the user clicks the button: import tkinter as tk def doit(): user.insert(tk.END, cat.get()) root = tk.Tk() cat = tk.Entry(root) cat.place(x=20, y=25, width=100) user = tk.Entry(root) user.place(x=20, y=75) user.insert(0, "Hello ") btn = tk.Button(root, text='START', command=doit) btn.place(x=20, y=150) root.mainloop() However, you'll see that subsequent button clicks keep appending the text. When working with Entry.insert(), you need to work with Entry.delete() and/or other Entry methods to properly manipulate the text.
has comment: http://stackoverflow.com/comment/88657095
has comment: http://stackoverflow.com/comment/88797990
has comment: http://stackoverflow.com/comment/88733689
score: 1
has comment: http://stackoverflow.com/comment/88803350
has comment: http://stackoverflow.com/comment/88754497
has comment: http://stackoverflow.com/comment/88803423
upvote count: 1

http://stackoverflow.com/comment/88581570
has text: Just to be clear, you want all the combinations of 1e6 and 1e4 points? I.e. on the order of 1e10 pairings? That is going to take a while, no matter what... (Although 30 mins for just one of the points (i.e. just 1e6 or 1e4 pairs) seems definitely too long)
comment on: http://stackoverflow.com/q/50787624
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/88538503
type: AnswerComment
comment on: http://stackoverflow.com/a/50765139
type: Comment
score: 1
has text: Thanks for the answer! I had no idea you could expand dimensions while broadcasting like that!

http://stackoverflow.com/comment/88694876
has text: A series (or column in a df) of ints is different than an actual int. If you are down to the actual int like `5`, it no longer has the methods from pandas
comment on: http://stackoverflow.com/a/50843478
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50790034
answers question: http://stackoverflow.com/q/50789729
score: 0
type: Answer
has body: The reason is that the data you want to retrieve is contained inside the iframe, which has caused the selenium cannot visit the data directly. Try the following code: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver=webdriver.Chrome() URL='http://2ez.gg/#gg?name=Doombag&amp;server=lan' driver.get(URL) driver.switch_to.frame('iframe-content') elem=driver.find_element_by_css_selector('.WinRatioGraph div.Text') print(elem.text) Output: 55%

http://stackoverflow.com/q/50797275
possible better answer: http://stackoverflow.com/a/50797579
has title: Loop through two lists where one is smaller than the other
upvote count: 2
has answer: http://stackoverflow.com/a/50797579
downvote count: 2
has answer: http://stackoverflow.com/a/50802137
has comment: http://stackoverflow.com/comment/88600845
has comment: http://stackoverflow.com/comment/88607024
tagged with: python
has comment: http://stackoverflow.com/comment/88604828
has answer: http://stackoverflow.com/a/50799512
has comment: http://stackoverflow.com/comment/88604648
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88600857
has comment: http://stackoverflow.com/comment/88601079
has answer: http://stackoverflow.com/a/50799519
has comment: http://stackoverflow.com/comment/88606712
has comment: http://stackoverflow.com/comment/88600447
type: Question
has comment: http://stackoverflow.com/comment/88600780
score: 0
has comment: http://stackoverflow.com/comment/88606565
accepted answer: http://stackoverflow.com/a/50799519
has comment: http://stackoverflow.com/comment/88600520
has comment: http://stackoverflow.com/comment/88602839
has comment: http://stackoverflow.com/comment/88603460
answer count: 4
has body: I have two lists where one list is a list of tuples (will call it list2), and another is a list of strings (will call it list1). list1 is smaller than list2 but I want to be able to loop through them both and compare values from list1 in each tuple that is in list2. So far I have been managing to get results but it does not have the in the correct order. My code so far is; list1 = ['2018-24', '2018-23', '2018-22', '2018-21', '2018-20', '2018-19', '2018-18', '2018-17', '2018-16', '2018-15', '2018-14', '2018-13', '2018-12', '2018-11'] list2 = [(27, 'Deutsche Bank', 'Opportunities email 2018-7'), (5, 'Deutsche Bank', 'Opportunities email 2018-2'), (4, 'Deutsche Bank', 'Opportunities email 2018-6'), (3, 'Deutsche Bank', 'Opportunities email 2018-10'), (3, 'Deutsche Bank', 'Opportunities email 2018-14'), (3, 'Deutsche Bank', 'Opportunities email 2017-50'), (3, 'Deutsche Bank', 'Opportunities email 2018-12'), (3, 'Deutsche Bank', 'Opportunities email 2018-4'), (2, 'Deutsche Bank', 'Opportunities email 2018-5'), (2, 'Deutsche Bank', 'Opportunities email 2018-3'), (2, 'Deutsche Bank', 'Opportunities email 2017-51'), (1, 'Deutsche Bank', 'Opportunities email 2018-13'), (1, 'Deutsche Bank', 'Opportunities email 2018-11')] new_list = [] for x in list2: ii = x[2].split(' ')[2] if ii not in list1: new_list.append(0) else: print('This is ii ' + ii) for y in list1: if ii in y: new_list.append(x[0]) print(new_list) print(len(new_list)) print(len(list1)) o/p &gt; 'This is ii 2018-14' 'This is ii 2018-13' 'This is ii 2018-12' 'This is ii 2018-11' [0, 0, 0, 3, 0, 3, 0, 0, 0, 0, 0, 1, 1] 13 14 It can be seen above that the len of the new_list and list1 are different they should both be the same. But also it can be seen that the order of the new_list does not match up with the list1 values so for example the value at index 3 of the new_list should actually be at index 10. I am not sure why it seems to be re-ordering the new_list. The output I am expecting to get is new_list and list1 to…
favorite count: 0

http://stackoverflow.com/comment/89036439
type: AnswerComment
type: Comment
has text: For me it's not about "doing all the work for you" at all but more whether the question is interesting enough to put effort on it. I've been myself countless times spending a lot of time answering a lot of interesting questions but not because "I was doing all the job for anybody" but because I was interested enough myself on learning more about the subject. I'm pretty much sure I'm not the only one thinking that way cos I've seen a lot of times people spending a lot of time and giving high-quality answers. So yeah, you can't say so categorically what SO is all about cos it depends... ;)
comment on: http://stackoverflow.com/a/50977713
score: 0

http://stackoverflow.com/q/50829366
has comment: http://stackoverflow.com/comment/88663088
has comment: http://stackoverflow.com/comment/88663044
has comment: http://stackoverflow.com/comment/88664400
tagged with: python
has body: I have a JSON response string that contains the results from scans from multiple antivirus sites. It looks something like - "scans": { "Bkav": { "detected": false, "version": "1.3.0.9466", "result": null, "update": "20180609" }, "MicroWorld-eScan": { "detected": true, "version": "14.0.297.0", "result": "W97M.Downloader.AIU", "update": "20180611" }, "CMC": { "detected": false, "version": "1.1.0.977", "result": null, "update": "20180610" }, "CAT-Quickheal": { "detected": true, "version": "14.00", "result": "X97M.Dropper.PD", "update": "20180611" }, "McAfee": { "detected": true, "version": "6.0.6.653", "result": "X97M/Downloader.asi", "update": "20180611" }, }, "tags": { ... }, How can I extract all the non-empty results (all the results that are not null) from the scans tag in this JSON and store it into a single comma separated string in a table column of my database? Thanks!
type: AnsweredQuestion
has title: Python - Storing part of JSON response as a Comma Separated String
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88665115
type: Question
has answer: http://stackoverflow.com/a/50831016
accepted answer: http://stackoverflow.com/a/50831016
possible better answer: http://stackoverflow.com/a/50832576
has comment: http://stackoverflow.com/comment/88664524
has comment: http://stackoverflow.com/comment/88664619
tagged with: database
has comment: http://stackoverflow.com/comment/88662993
has comment: http://stackoverflow.com/comment/88664534
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50832576

http://stackoverflow.com/q/50717438
has body: grid = [] grid.clear() f = open('grid.csv','r') for line in f : values = line.split() for n in range(0,20) : grid.append(values[n]) f.close() grid grid.csv is file containing grid of 20*20 integers. the output prints a list with each element in separate line. I tried this grid = list(map(lambda s: s.strip('\n'),grid)) but the output was still in separate lines
has comment: http://stackoverflow.com/comment/88443696
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88443441
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88443376
has title: how to convert multi-line list to a single line list?
tagged with: python
has answer: http://stackoverflow.com/a/50718082
has comment: http://stackoverflow.com/comment/88443786
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88443602
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50718082

http://stackoverflow.com/a/50876317
accepted answer of: http://stackoverflow.com/q/50795252
upvote count: 2
answers question: http://stackoverflow.com/q/50795252
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
has body: To be accepted as a Python package, a directory must have an __init__.py file. Variables declared in this file can be access as if the package is a regular module. It can also be empty. tl;dr: Add an empty __init__.py file to the directory and it should work.

http://stackoverflow.com/a/50855254
downvote count: 0
has body: Installing anything from Github is easy using pip: !pip install git+https://github.com/cehorn/GLRM.git You have acces to the full command line in Google Colab, so you can install anything you want, any way you want. Just put a ! in front of any command in a cell and it is executed on the command line.
accepted answer of: http://stackoverflow.com/q/50850216
has comment: http://stackoverflow.com/comment/132253544
has comment: http://stackoverflow.com/comment/122538183
score: 42
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/116917650
has comment: http://stackoverflow.com/comment/122586346
type: Answer
upvote count: 42
answers question: http://stackoverflow.com/q/50850216

http://stackoverflow.com/a/50791789
has body: I got the same issue. like dakshina11 said pip install 'awsebcli==3.13.0' --upgrade --user the older version of awsebcli==3.13.0 solved this problem. Currently 3.14.0 still not working.
score: 5
accepted answer of: http://stackoverflow.com/q/50757023
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50757023
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/q/50789693
type: Question
has title: How do I inspect the contents of tf.estimator.inputs.numpy_input_fn?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50790054
answer count: 1
downvote count: 0
has body: I want to train my tensorflow graph over a set of data repeatedly, and I think tf.estimator.inputs.numpy_input_fn might be what I'm looking for. I find the distinction between batch sizes, repeats, epochs and iterators to be incredibly confusing, so I started trying to inspect the contents of my datasets to try to figure out what's actually going on. However, whenever I try to to do this my program just hangs. Here is the smallest test case I came up with to reproduce this: import tensorflow as tf import numpy class TestMock(tf.test.TestCase): def test(self): inputs = numpy.array(range(10)) targets = numpy.array(range(10,20)) input_fn = tf.estimator.inputs.numpy_input_fn( x=inputs, y=targets, batch_size=1, num_epochs=2, shuffle=False) print input_fn() with self.test_session() as sess: # sess.run(input_fn()[0]) # it'll hang if I run this pass if __name__ == '__main__': tf.test.main() This program outputs (&lt;tf.Tensor 'fifo_queue_DequeueUpTo:1' shape=(?,) dtype=int64&gt;, &lt;tf.Tensor 'fifo_queue_DequeueUpTo:2' shape=(?,) dtype=int64&gt;) Which seems reasonable, but as soon as I try to run that sess.run line, my program freezes and I have to kill the process. What am I doing wrong here? What I want to do is make sure that the data I'm feeding into my process is actually what I think it is, but I don't think I can do that without the ability to inspect the data.
favorite count: 0
accepted answer: http://stackoverflow.com/a/50790054
tagged with: python
score: 2
upvote count: 2
tagged with: tensorflow

http://stackoverflow.com/comment/88552080
type: Comment
type: QuestionComment
has text: and if you type `/home/myusername/.virtualenvs/worldmodels/bin/python -m pip freeze` does it list tensorflow?
comment on: http://stackoverflow.com/q/50772096
score: 0

http://stackoverflow.com/q/50826614
type: UnansweredQuestion
tagged with: discord.py
tagged with: bots
has answer: http://stackoverflow.com/a/50826781
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88657980
answer count: 1
tagged with: python
tagged with: discord
has title: Discord Python Bot: How to move specific users mentioned by the author of the message
has body: I am looking for a way to allow a user to move him or her self and another user to a different voice channel. I already got the command to work for the author of the message, but I am having trouble finding out a way to move another user in the same message. The idea is that the user would be able to type "n!negotiate [Other User]" and it would move the author and the other user to the Negotiation channel. I would love some help with how I might be able to do this. The code is provided below excluding the tokens and ids. Code: import discord from discord.ext.commands import Bot from discord.ext import commands import asyncio import time Client = discord.Client() #Initialise Client client = commands.Bot(command_prefix = "n!") #Initialise client bot and prefix @client.event async def on_ready(): print("Logged in as:") print(client.user.name) print("ID:") print(client.user.id) print("Ready to use!") @client.event async def on_message(check): #Bot verification command. if check.author == client.user: return elif check.content.startswith("n!check"): await client.send_message(check.channel, "Nations Bot is online and well!") async def on_message(negotiation): #Negotiate command. Allows users to move themselves and other users to the Negotiation voice channel. if negotiation.author == client.user: return elif negotiation.content.startswith("n!negotiate"): author = negotiation.author voice_channel = client.get_channel('CHANNELID') await client.move_member(author, voice_channel) client.run("TOKEN")

http://stackoverflow.com/comment/88449684
score: 2
type: Comment
has text: there are too many boxes to group, so it is skipping those boxes
type: QuestionComment
comment on: http://stackoverflow.com/q/50720588

http://stackoverflow.com/q/50772954
type: Question
has title: Time format on x axis in Matplotlib
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50792803
accepted answer: http://stackoverflow.com/a/50792803
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: The time on the x-axis must be represented with a time interval of 3 seconds but the increment of time in my data is 2 seconds. So, I tried to do that as demonstrated in the code, but I’m getting the time demonstrated until 09:56:09 though the time goes till 09:56:22. Note that, the time should be start from 09:56:00 How can be the time on the x-axis completely demonstrated? Code: import matplotlib.pyplot as plt import time from datetime import datetime, timedelta import numpy as np import matplotlib.dates as mdates SO=[100,300,600,800,850,310,560,790,500,810,790,490];the_date_0=['01-02-2018 09:56:00.0000','01-02-2018 09:56:02.0000', '01-02-2018 09:56:04.0000','01-02-2018 09:56:06.0000', '01-02-2018 09:56:08.0000','01-02-2018 09:56:10.0000', '01-02-2018 09:56:12.0000','01-02-2018 09:56:14.0000', '01-02-2018 09:56:16.0000','01-02-2018 09:56:18.0000', '01-02-2018 09:56:20.0000','01-02-2018 09:56:22.0000'] the_date=[] Date_axis=[] for i in the_date_0: the_date.append(time.mktime(time.strptime(i, "%d-%m-%Y %H:%M:%S.0000"))) for i1 in range(0,len(the_date),3): time1=datetime.fromtimestamp(time.mktime(time.strptime("01-02-2018 09:56:00.0000", "%d-%m-%Y %H:%M:%S.0000")))+timedelta(seconds=i1) Date_axis.append(time.mktime(time1.timetuple())) fig = plt.figure() dateconv=np.vectorize(datetime.fromtimestamp) Date_F=dateconv(the_date) Date_axis_ok=dateconv(Date_axis) ax1 = plt.subplot2grid((1,1), (0,0)) ax1.plot_date(Date_F,SO,'r-',label='the values') ax1.set_yticks(range(0,1000,100)) ax1.set_xticks(Date_axis_ok) ax1.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S")) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) ax1.grid(True) plt.legend() plt.show() Graph
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: plot

http://stackoverflow.com/a/50811932
has comment: http://stackoverflow.com/comment/88705901
has body: How to know whether your model is overfitting is something you do while training the model. You have to set apart another set called validation dataset which is different from the test and training sets. A typical split of datasets is 70%-20%-10% for training, testing and validating respectively. During the training, every n steps you test your model on the validation dataset. During the first iterations the score on your validation set will get better but at some point it will get worse. You can use this information to stop your training when your model starts to overfit but doing it right is an art. You could for instance stop after 5 tests that your accuracy has been decreasing consecutively, because sometimes you can see that it gets worse but in the next test it gets better. It's hard to say, it depends on many factors. Regarding to your second question, iterating another 100 steps could make your model better or worse, depending on whether it's overfitting or not, so I'm afraid that question doesn't have a clear answer. The weights will rarely stop changing because the iterations/steps are "moving" them, for good or for bad. Again, it's difficult to say how to get good results, but you could try early stopping using a validation set, as I've mentioned before.
score: 0
answers question: http://stackoverflow.com/q/50809933
type: Answer

http://stackoverflow.com/comment/88497998
comment on: http://stackoverflow.com/a/50738304
type: Comment
has text: @Bryan Oh, sorry, I don't know why I wrote True. I have corrected it. It should be ax1, in order to tell matplotlib with whom should the xaxis be shared
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88650430
type: AnswerComment
comment on: http://stackoverflow.com/a/50803435
type: Comment
has text: @Dennis Then you want my first answer, where you just assign `L[:] = …` at the end, instead of returning the new list to the caller.
score: 0

http://stackoverflow.com/q/50734877
has answer: http://stackoverflow.com/a/50744808
tagged with: aws-sdk
tagged with: python
has title: How to get the value of a specific field out of cloudformation stack dictionary with python
upvote count: 1
accepted answer: http://stackoverflow.com/a/50744808
type: AnsweredQuestion
tagged with: aws-cloudformation
has body: I'm using AWS Cloudformation to create a stack and would like to get the value of the 'PublicIP' field out of the dictionary returned from describe_stacks(). The following schematic code does the work, but it is not resilient to changes in the dictionary structure: #!/usr/bin/python import sys import boto3 import rest_client if len(sys.argv) &lt; 2: print "Bad usage: missing stack name" exit(1) session = boto3.Session(profile_name='profile name') client = session.client('cloudformation') response = client.describe_stacks(StackName=sys.argv[1]) try: ip = response['Stacks'][0]['Outputs'][1]['OutputValue'] print "Extracted instance IP address ({0})".format(ip) except IndexError: print "IP address not found" exit(1) Is there a more specific API I can use to get this field directly?
type: Question
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/a/50735638
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50735446
has body: Use wide_to_long: df = pd.wide_to_long(df.reset_index(), stubnames=['x', 'value_x'], i='index', j='a') print (df) x value_x index a 0 1 a 1 1 1 a 3 2 1 b 5 0 2 b 2 1 2 c 4 2 2 c 6 And then unstack with some data cleaning: df = (df.reset_index(level=1, drop=True) .set_index('x', append=True)['value_x'] .unstack(fill_value=0) .rename_axis(None) .rename_axis(None, axis=1)) print (df) a b c 0 1 2 0 1 3 0 4 2 0 5 6
accepted answer of: http://stackoverflow.com/q/50735446
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/50829288
tagged with: command-line
linked to: http://stackoverflow.com/q/1471994
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88662857
type: Question
has comment: http://stackoverflow.com/comment/88663190
tagged with: command-line-interface
score: 0
has comment: http://stackoverflow.com/comment/88662889
has comment: http://stackoverflow.com/comment/88663069
has title: Turning Python script into CLI and enabling its distribution
tagged with: python
has body: I have a Python file called recognize.py, which takes multiple images and performs OCR with multiple processes, where ocr_tools is a large self-written module: import argparse import json from multiprocessing import Pool from ocr_tools import Organize organizer = Organize() parser = argparse.ArgumentParser(description="Recognize the contents on a lab report and return a json string.") parser.add_argument("-i", "--image", nargs="*", required=True, help="path to input image file") args = parser.parse_args() if __name__ == "__main__": with Pool() as p: report_set = json.dumps({"report_set": p.map(organizer.finalize_report, args.image)}, ensure_ascii=False) print(report_set) For ocr_tools, I also have a requirements.txt generated by pipreqs for users to install the required packages from PyPI: numpy==1.14.3 regex==2018.2.21 requests==2.18.4 pandas==0.23.0 opencv_python==3.4.1.15 scikit_learn==0.19.1 If I distribute these files and modules, users should be able to execute python recognize.py --image &lt;path_to_an_image&gt; from the command lines and get OCR results after they install those packages listed in requirements.txt. Now I wonder if there's a way to further enable users to do something like ocr --image &lt;path_to_an_image&gt;, i.e. the same job without specifying python interpreter in the command lines. I've read a tutorial, How Do I Make My Own Command-Line Commands Using Python? but it seems effective only locally and cannot be distributed. I've also glanced Writing the Setup Script, hoping to find solutions for distribution. However, I don't find a way to specify external packages to be installed from PyPI. (Or maybe I missed something - I am a beginner in Python.) Besides, setup.py seems like neither a good way to install the packages according to comments under the accepted answer of What is setup.py?, nor being capable of enabling CLI.

http://stackoverflow.com/q/50809860
type: Question
tagged with: swagger-codegen
has comment: http://stackoverflow.com/comment/88833920
has answer: http://stackoverflow.com/a/59975074
downvote count: 0
answer count: 1
has body: I have this json file and I have been trying to create models and API code through swagger codegen. This has not been quiet effective as it throws error. Exception in thread "main" java.lang.RuntimeException: missing swagger input or config! at io.swagger.codegen.DefaultGenerator.generate(DefaultGenerator.java:735) at io.swagger.codegen.cmd.Generate.run(Generate.java:285) at io.swagger.codegen.SwaggerCodegen.main(SwaggerCodegen.java:35) The swagger docs version is 1.2. And I am using swagger-codegen version 2.4.0. java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i ./json/docs.json -l python -o C:/Users/sk/projects/generated-sdk
favorite count: 0
has title: Swagger codegen failed: missing swagger input or config
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/88846016
type: UnansweredQuestion
score: 6

http://stackoverflow.com/q/50848191
type: UnansweredQuestion
tagged with: python
score: 1
has body: I am trying to read in my workbook and append certain worksheets in order to create 1 big table. However, I only want to append according to certain columns (f_name, lname, address ect) I keep getting an error that says with pd.read_excel(xls,sheet,lines = True) as df: AttributeError: exit I am not sure what the issue is. import sys, os import pandas as pd import xlrd import xlwt b = ['sh1', 'sh2','sh3'] #sheet Name df_t = pd.DataFrame(columns=["fname","lname","address","zip","school"]) xls= 'address/Documents/wrkbook.xls' for sheet in b: with pd.read_excel(xls,sheet,lines = True) as df: df.rename(columns=lambda x: x.strip().upper(), inplace=True) df_b = df_b.append(df[columns]) Surveys = df_b Survey.to_excel('Surveyss.xlsx', index=False)
upvote count: 1
tagged with: excel
type: Question
has title: Read in and append sheets by column in Python
tagged with: python-2.7
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50849099

http://stackoverflow.com/comment/88482288
score: 0
comment on: http://stackoverflow.com/q/50737109
type: Comment
type: QuestionComment
has text: Atleast that's what I get when I type it in console. I just tried adding `not` to both. It did everything it needed to and printed it the first time. The second time it only printed `Raw Data: #some data here` and skipped the `if` statement again even though the file was never made.

http://stackoverflow.com/a/50803832
upvote count: 1
score: 1
has body: if turnSelector()== 1: scrambledState = anterior(scrambledState) zero += 1 elif turnSelector()== 2: scrambledState = posterior(scrambledState) one += 1 This doesn't look right to me. You call turnSelector in each of your conditionals, which means it can return a different value each time. You have a (5/6)^6 chance that none of your conditionals will pass, and the else will execute. Try calling turnSelector once, and storing the result, and comparing against that stored result in your conditionals. def turnExecutor(): global scrambledState, zero, one, two, three, four, five,six x = turnSelector() if x== 1: scrambledState = anterior(scrambledState) zero += 1 elif x== 2: scrambledState = posterior(scrambledState) one += 1 elif x == 3: scrambledState = dorsal(scrambledState) two += 1 elif x== 4: scrambledState = ventral(scrambledState) three += 1 elif x== 5: scrambledState = right(scrambledState) four += 1 else: scrambledState = left(scrambledState) five += 1
accepted answer of: http://stackoverflow.com/q/50803737
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50803737
type: Answer

http://stackoverflow.com/q/50768295
has answer: http://stackoverflow.com/a/50770310
upvote count: 1
has answer: http://stackoverflow.com/a/50769296
has comment: http://stackoverflow.com/comment/88545724
favorite count: 0
has title: OpenCV :Text Processing and Noise Removal
tagged with: python
tagged with: opencv
type: AnsweredQuestion
tagged with: opencv3.0
downvote count: 0
score: 1
has body: I would like to remove the background of an image that contains text to make it text on white background. sample of image I have tried till now to get HSV of an image and upper and lower boundaries but I can't find upper and lower boundaries that can remove all the background effect Code used till now : import cv2 import numpy as np # Take each frame filename = 'img2.png' img = cv2.imread(filename, 1) # Convert BGR to HSV hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # define range of blue color in HSV lower_blue = np.array([110,50,50]) upper_blue = np.array([130,255,255]) # Threshold the HSV image to get only blue colors image_final = cv2.inRange(hsv, lower_blue, upper_blue) # Bitwise-AND mask and original image res = cv2.bitwise_and(img,img, mask= mask) cv2.imshow('frame',img) cv2.imwrite('mask.png',image_final) cv2.waitKey(0) Is there a better way to it or do I have to combine multiple lower and upper boundaries to reach my goal?
accepted answer: http://stackoverflow.com/a/50769296
has comment: http://stackoverflow.com/comment/88545440
type: Question
possible better answer: http://stackoverflow.com/a/50770310
answer count: 2

http://stackoverflow.com/a/50703967
downvote count: 0
answers question: http://stackoverflow.com/q/50702264
has body: Figured out a (gross) way to do it using xpath. def hocr_to_dataframe(fp): from lxml import etree import pandas as pd import os doc = etree.parse('fp') words = [] wordConf = [] for path in doc.xpath('//*'): if 'ocrx_word' in path.values(): conf = [x for x in path.values() if 'x_wconf' in x][0] wordConf.append(int(conf.split('x_wconf ')[1])) words.append(path.text) dfReturn = pd.DataFrame({'word' : words, 'confidence' : wordConf}) return(dfReturn)
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50702264
type: AcceptedAnswer

http://stackoverflow.com/comment/88479724
has text: give me some hints to get started
comment on: http://stackoverflow.com/q/50735993
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88616629
type: Comment
type: QuestionComment
has text: It is not recommended to use the Task constructor as the Task.Run method should be used to instantiate and start a task (see https://msdn.microsoft.com/en-us/library/dd321321(v=vs.110).aspx).
comment on: http://stackoverflow.com/q/50804706
score: 0

docker
tags question: http://stackoverflow.com/q/50821693
type: Tag
tags question: http://stackoverflow.com/q/50727619
tags question: http://stackoverflow.com/q/50751294
tags question: http://stackoverflow.com/q/50707777
tags question: http://stackoverflow.com/q/50815894
tags question: http://stackoverflow.com/q/50825683
tags question: http://stackoverflow.com/q/50713497
tags question: http://stackoverflow.com/q/50781915
tag name: docker
tags question: http://stackoverflow.com/q/50751500
tags question: http://stackoverflow.com/q/50743651
tags question: http://stackoverflow.com/q/50737088
tags question: http://stackoverflow.com/q/50703087
tags question: http://stackoverflow.com/q/50751952
tags question: http://stackoverflow.com/q/50778357
tags question: http://stackoverflow.com/q/50803382
tags question: http://stackoverflow.com/q/50778583
tags question: http://stackoverflow.com/q/50762736

http://stackoverflow.com/comment/88707336
type: Comment
has text: Rgb image then i have to do the necessary modification if needed but kindly note the image is mostly black and white but still in rgb
type: AnswerComment
comment on: http://stackoverflow.com/a/50851748
score: 0

http://stackoverflow.com/a/50846104
has comment: http://stackoverflow.com/comment/88696505
answers question: http://stackoverflow.com/q/50846049
has comment: http://stackoverflow.com/comment/88696295
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50846049
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88695840
score: 4
has body: On Windows, I would use os.path.splitdrive combined with a strip of the separator import os path1 = 'C:/folder1/folder2/' path2 = 'D:/directory1/directory2/' seps = os.sep+os.altsep if os.altsep else os.sep path3 = os.path.join(path1,os.path.splitdrive(path2)[1].lstrip(seps)) # handles / and \ as separators on windows print(path3) result: C:/folder1/folder2/directory1/directory2/ (if the second path is a relative path, it also works) The seps = os.sep+os.altsep if os.altsep else os.sep line allows to be compatible with systems with no alternate separators (Linux). This solution works on Windows &amp; Linux, os.splitdrive is a dummy on Linux (returning a tuple with empty first element)
type: Answer

http://stackoverflow.com/q/50822826
tagged with: django
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50823020
type: Question
upvote count: 4
downvote count: 0
answer count: 1
score: 4
has body: I have a strange issue. Whenever I try to send an email from a TestCase, I cannot receive it. However, I try the same approach on Django shell and it successfully send the email. Here is my TestCase: class DefaultEmailTestCase(TestCase): def test_send(self): msg = EmailMessage( "Test Message", "This is a test message.", to=["foo@bar.com", "foo@baz.com"] ) val = msg.send() self.assertEqual(val, 1) It completes successfully, but I do not receive the email. And here is what I do on Django's shell: from django.core.mail import EmailMessage receivers = ["foo@bar.com", "foo@baz.com"] msg = EmailMessage( "Test Message", "This is a test message." to=receivers ) msg.send() And I successfully receive the message. Here is my settings in order (with dummy info): EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' EMAIL_HOST = "foo.bar.com" EMAIL_PORT = 465 # This is the port that my email provider uses. EMAIL_HOST_USER = "foo@bar.com" EMAIL_HOST_PASSWORD = "123456" # EMAIL_USE_TLS = True # Django raised an error saying that I cannot use both TLS and SSL. So I commented it out. EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = "Bar Testing Message &lt;foo@bar.com&gt;" I have also used django.core.mail.backends.smtp.EmailBackend as EMAIL_BACKEND but no luck. Both the test case and Django shell uses my development settings, so they are the same. I do not have any idea why this does not work. Thanks in advance. Environment Python 3.6.5 Django 2.0.4
favorite count: 0
tagged with: email
tagged with: python
has title: Django does not Send Email on TestCase, but It Does on Shell
has answer: http://stackoverflow.com/a/50823020

http://stackoverflow.com/comment/88608073
type: Comment
comment on: http://stackoverflow.com/q/50801041
type: QuestionComment
score: 1
has text: add `encoding='latin-1'`

http://stackoverflow.com/a/50788034
has body: It's actually what you would expect if you blindly run and expect gradient descent methods to learn any function. The behaviour you observe stems from 2 reasons: The derivative that SGD uses to update weights actually depends on the input. Take a very simple case y = f(wx + b), the derivative of y with respect to w is f'(wx + b)*x using the chain rule. So when there is an update for an input that is extremely large / unnormalised it blows up. Now the update is basically w' = w - alpha*gradient, so the weight suddenly becomes very small, in fact negative. After a single gradient update the output became negative because the SGD just overshot. Since you again have relu in the final layer, that just outputs 0 and the training stalls because when the output is negative derivative of relu is 0. You can reduce the datasize to np.arange(1, 10) and reduce the number of hidden neurons to say 12 (more neurons make the output even more negative after single update as all their weights become negative as well) and you will be able to train the network.
downvote count: 0
answers question: http://stackoverflow.com/q/50787555
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/50701317
answer count: 1
has title: InvalidRequestError when adding data to database with SQLAlchemy and SQL server
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50712747
tagged with: python
tagged with: sqlalchemy
type: Question
has body: I'm trying to build a many to many relationship with sqlalchemy with pyodbc and SQL Server , and here is my code: from sqlalchemy import Table, Text from sqlalchemy import ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() courses_students = Table('courses_students',Base.metadata, Column('stu_id',ForeignKey('student.id'),primary_key=True), Column('cour_id',ForeignKey('course.id'),primary_key=True), Column('grade',Integer()) ) # from sqlalchemy.ext.declarative import declarative_base # Base = declarative_base() class Student(Base): __tablename__ = 'student' stu_id = Column('id',Integer,primary_key=True) name = Column('name',String(10)) stu_class = Column('class',String(10)) #courses = relationship('Course',secondary=courses_students,back_populates='students') def __init__(self,stu_id,name,stu_class): self.stu_id = stu_id self.name = name self.stu_class = stu_class def __repr__(self): _str = "Student({_id},{_name},{_class})".format(_id=self.stu_id,_name=self.name, _class=self.stu_class) return _str # from sqlalchemy.ext.declarative import declarative_base # Base = declarative_base() class Course(Base): __tablename__ = 'course' cour_id = Column('id',Integer,primary_key=True) name = Column('name',String(20)) teacher_name = Column('teacher_name',String(10)) credit = Column('credit',Integer()) students = relationship('Student',secondary=courses_students,backref='courses') def __init__(self,c_id,name,t_name,credit): self.cour_id = c_id self.name = name self.teacher_name = t_name self.credit = credit def __repr__(self): _str = "Course({_id},{_na},{_t_na},{_cre})".format(_id=self.cour_id,_na=self.name, _t_na=self.teacher_name, _cre=self.credit) return _str However, when I tried to add data with session.add(), I met the following errors: InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|Student|student'. Original exception was: When initializi…

http://stackoverflow.com/q/50754269
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88516546
linked to: http://stackoverflow.com/q/17071871
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50754300
type: Question
has comment: http://stackoverflow.com/comment/88516501
has body: I want to get only those rows in a dataframe where a particular coulmn value is less than some upper bound. I used to do this: final_data[final_data['Time']&lt;30.000000] It gives me the error: IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match I again tried with: final_data.loc[:,final_data['Time']&lt;30.000000] and I get: IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match How can I implement the filter in pandas based on column value?
has comment: http://stackoverflow.com/comment/88517094
score: 0
has comment: http://stackoverflow.com/comment/88516722
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50754300
has title: Pandas Can't Filter by Column Values
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88517356
downvote count: 1

tkinter-entry
tags question: http://stackoverflow.com/q/50824974
tags question: http://stackoverflow.com/q/50723906
tag name: tkinter-entry
tags question: http://stackoverflow.com/q/50707709
type: Tag

http://stackoverflow.com/q/50717769
tagged with: pandas
answer count: 1
tagged with: python-3.x
tagged with: python
type: UnansweredQuestion
score: 0
has body: I have 2 columns date_1 (dtype('O')) and date_2(dtype(') date_1 date_2 2018-06-06 2018-04-01 when i do subtraction to get days df['date_1'] - df['date_2'] i get the error TypeError: incompatible type [object] for a datetime/timedelta operation
has answer: http://stackoverflow.com/a/50717816
type: Question
has title: Subtracting Dates to get Days in pandas

neural-network
tags question: http://stackoverflow.com/q/50794383
tags question: http://stackoverflow.com/q/50843487
tags question: http://stackoverflow.com/q/50756732
tags question: http://stackoverflow.com/q/50779773
tags question: http://stackoverflow.com/q/50853708
tags question: http://stackoverflow.com/q/50724495
tags question: http://stackoverflow.com/q/50835327
tags question: http://stackoverflow.com/q/50718447
tags question: http://stackoverflow.com/q/50768538
tags question: http://stackoverflow.com/q/50824819
tags question: http://stackoverflow.com/q/50766976
tags question: http://stackoverflow.com/q/50783854
tags question: http://stackoverflow.com/q/50767472
tags question: http://stackoverflow.com/q/50710493
type: Tag
tags question: http://stackoverflow.com/q/50706680
tags question: http://stackoverflow.com/q/50847386
tags question: http://stackoverflow.com/q/50850477
tags question: http://stackoverflow.com/q/50798045
tags question: http://stackoverflow.com/q/50814066
tags question: http://stackoverflow.com/q/50806953
tags question: http://stackoverflow.com/q/50767157
tags question: http://stackoverflow.com/q/50853699
tags question: http://stackoverflow.com/q/50838376
tags question: http://stackoverflow.com/q/50700307
tags question: http://stackoverflow.com/q/50814880
tags question: http://stackoverflow.com/q/50762466
tag name: neural-network
tags question: http://stackoverflow.com/q/50740557
tags question: http://stackoverflow.com/q/50784337

http://stackoverflow.com/comment/88579191
score: 2
has text: Please edit your question to include your actual code, and the full error traceback output.
comment on: http://stackoverflow.com/q/50786362
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88586518
comment on: http://stackoverflow.com/a/50777902
type: Comment
has text: ok, thank you very much for helping me to verify this. I was worried that it wouldn't be possible but wasn't sure how to check. I have decided to use Chart.js instead.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50729422
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50725093
accepted answer of: http://stackoverflow.com/q/50725093
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: One approach is to sort the numeric column, then use searchsorted + iloc. E.g. df.iloc[df.field3.searchsorted(min_v, 'left'):df.field3.searchsorted(max_v, 'right')] This seems to be about 8 times as fast as df.query on my machine with 100k records. If you know the set of your queries ahead of time, you can do better. For example, say you have arrays mins and maxs with len(mins) == len(maxs) == 6000. You can pre-compute min_ix = df.field3.searchsorted(mins, 'left') max_ix = df.field3.searchsorted(maxs, 'right') And iterate over filtered frames via for i, j in zip(min_ix, max_ix): print(df.iloc[i:j])

http://stackoverflow.com/comment/88682555
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50835240
has text: @AnttiHaapala there's no confusion. jupyter users are kinda common here
type: Comment

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/50725830

http://stackoverflow.com/a/50829938
downvote count: 0
type: Answer
upvote count: 1
has body: Assuming that they're all the same size: a = [] for i in len(one): a.append([]) for list in list_: a[-1] += list[1] even better, in a list comprehension: import itertools [list(itertools.chain.from_iterable([list[x] for list in list_])) for x in len(one)]
score: 1
answers question: http://stackoverflow.com/q/50829800

http://stackoverflow.com/comment/88611817
comment on: http://stackoverflow.com/a/50802815
has text: I don't think it does, user is a row and players are multiple users. I want to determine that the user is not in the list. I don't think my query does that.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50845775
type: Answer
has comment: http://stackoverflow.com/comment/88695035
has body: It may help to understand what this array of strings contains: In [643]: input_array = np.array([['Red', 'Green', 'Blue', 'Yellow'], ...: ['Purple', 'Orange', 'Cyan', 'Pink']]).T ...: ...: In [644]: input_array.size Out[644]: 8 In [645]: input_array.itemsize Out[645]: 24 In [646]: input_array.nbytes Out[646]: 192 Because it is a transpose, the shape and strides differ from the input array, but the strings are in the original order. In [647]: input_array.__array_interface__ Out[647]: {'data': (139792902236880, False), 'strides': (24, 96), 'descr': [('', '&lt;U6')], 'typestr': '&lt;U6', 'shape': (4, 2), 'version': 3} My guess is that Array should be defined with nbytes rather than size.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50844290
downvote count: 0

http://stackoverflow.com/a/50735343
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50735149
type: Answer
has body: It seems your dataset is a string, and a string does not have the attibute or method loc. Check the type of your dataset with type() or isinstance() and see that it is the correct data type.
score: 1

http://stackoverflow.com/q/50812860
answer count: 1
has comment: http://stackoverflow.com/comment/88631845
has title: Python 3: capture a matrix return from subprocess with Rscript
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/88630937
upvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: subprocess
type: UnansweredQuestion
tagged with: python
has body: I am using subprocess to run a Rscript. The script returns a R matrix. I am using subprocess.check_output in Python and get a string. But is there a way to get directly the output matrix in Python? Thanks
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88630972
has answer: http://stackoverflow.com/a/50813075
has comment: http://stackoverflow.com/comment/88631053
type: Question

http://stackoverflow.com/comment/88525022
comment on: http://stackoverflow.com/q/50758785
type: Comment
type: QuestionComment
score: 1
has text: Show us what you tried and what specific problems you encountered.

http://stackoverflow.com/q/50749481
favorite count: 0
has comment: http://stackoverflow.com/comment/88507001
has comment: http://stackoverflow.com/comment/88506635
has comment: http://stackoverflow.com/comment/88507311
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88507575
has comment: http://stackoverflow.com/comment/88506946
has comment: http://stackoverflow.com/comment/88507690
tagged with: python
upvote count: 6
has body: I am trying to calculate the standard deviation for topological properties in matrices of around 100 nodes. What I am trying to code is the following: how to calculate the standard deviation (there needs to be a square bracket closing this) Where X is how to calculate the topological property X but a should be replaced with g. As a result I coded the following. I trial ran the code with a random graph of about 85 nodes. Therefor, S and G are both an 85 by 85 matrix where all entries are floats between 0 and 1 and n is the number of nodes, 85 in this case. Input into the code is M_std (type = numpy.ndarray, S in input of function), which is a matrix of standard deviations of g_{ij}, and M_p (type = numpy.ndarray, G in input of function) is a matrix of the expectational values of g_{ij}. Derivative refers the (delta X)/(delta g_{ij}). Std_1 is everything in between the square. import networkx as nx import numpy as np import math def new_calc_std_1(S, G, n): std_1 = 0 for e in range(n): for f in range(n): derivative = 0 for i in range(n): for j in range(n): for k in range(n): if i == j or i == k or j == k: None elif (e not in [i,j,k]) or (f not in [i,j,k]): None else: if e == i and f == j: deriv += -G[j,i]*G[j,k]*(1-G[k,j])*(1-G[i,k])*(1-G[k,i]) elif e == j and f == i: deriv += (1-G[i,j])*G[j,k]*(1-G[k,j])*(1-G[i,k])*(1-G[k,i]) elif e == j and f == k: deriv += (1-G[i,j])*G[j,i]*(1-G[k,j])*(1-G[i,k])*(1-G[k,i]) elif e == k and f == j: deriv += -(1-G[i,j])*G[j,i]*G[j,k]*(1-G[i,k])*(1-G[k,i]) elif e == i and f == k: deriv += -(1-G[i,j])*G[j,i]*G[j,k]*(1-G[k,j])*(1-G[k,i]) elif e == k and f == i: deriv += -(1-G[i,j])*G[j,i]*G[j,k]*(1-G[k,j])*(1-G[i,k]) else: derivative += 0 std_1 += (S[e,f]*derivative)**2 std_1 = math.sqrt(std_1) return std_1 This took a total of 21 minutes. I tried find a solution so then I read that I had to minimize the use of for loops, especially in python. Therefor I rewrote the code to def new_new_calc_std_1(S, G, n): blwsqrt = 0 for e in range(n): …
has comment: http://stackoverflow.com/comment/88507858
score: 6
has comment: http://stackoverflow.com/comment/88508069
has comment: http://stackoverflow.com/comment/88507260
has comment: http://stackoverflow.com/comment/88507192
tagged with: networkx
has comment: http://stackoverflow.com/comment/88507392
type: Question
has title: Nested for loops slow python for calculating special standard deviation
tagged with: performance
has comment: http://stackoverflow.com/comment/88506927
has comment: http://stackoverflow.com/comment/88508057
has comment: http://stackoverflow.com/comment/88507367
has comment: http://stackoverflow.com/comment/88506754
tagged with: optimization
has comment: http://stackoverflow.com/comment/88507995
tagged with: for-loop
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88508023
has comment: http://stackoverflow.com/comment/88507796
has answer: http://stackoverflow.com/a/50833430
has comment: http://stackoverflow.com/comment/88508116
has comment: http://stackoverflow.com/comment/88507323

http://stackoverflow.com/a/50759816
has comment: http://stackoverflow.com/comment/88526994
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: ip_data = [] for row in sheet.cell(i, col_source_IP).value: temp_list = row.split('\n') # if IPs are seperated by \n for ip in temp_list: ip_data.append(ip)
accepted answer of: http://stackoverflow.com/q/50759706
score: 1
answers question: http://stackoverflow.com/q/50759706

http://stackoverflow.com/comment/88426640
has text: Create a new variable that is an integer with increasing values that tie back to the reasons, sort the data, keep first.
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50708768

http://stackoverflow.com/comment/88556011
score: 0
type: Comment
type: AnswerComment
has text: Yes, you can take a look at the [matplotlib documentation](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplot.html#matplotlib.pyplot.subplot), the [examples](https://matplotlib.org/gallery/subplots_axes_and_figures/subplots_demo.html) or search here at stackoverflow for both matplotlib and suplot tag at the same time: https://stackoverflow.com/questions/tagged/matplotlib+subplot
comment on: http://stackoverflow.com/a/50738304

http://stackoverflow.com/q/50729702
has comment: http://stackoverflow.com/comment/88467293
has comment: http://stackoverflow.com/comment/88467230
type: Question
has comment: http://stackoverflow.com/comment/88478737
accepted answer: http://stackoverflow.com/a/50729912
has comment: http://stackoverflow.com/comment/88467267
has body: I am new in Python and I wanted to convert below dictionary to html table format in python. Please let me know the efficient way to do achieve this Input dict_data = {'x,y,z':['1','5','6'],'p,q,r':['10','25','36']} Output : col1 col2 col3 val1 val2 x y z 1 5 p q r 10 25
has comment: http://stackoverflow.com/comment/88467530
answer count: 1
has title: Convert dict to HTML table
has comment: http://stackoverflow.com/comment/88467493
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/50729912
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88467320

http://stackoverflow.com/q/50788977
type: UnansweredQuestion
tagged with: python
has title: Histogram with counts of string variables in matplotlib
has comment: http://stackoverflow.com/comment/88584418
has comment: http://stackoverflow.com/comment/88584489
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88584505
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88584496
linked to: http://stackoverflow.com/q/19198920
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88584595
tagged with: histogram
has body: I want to plot a histogram with matploblib in Python, but my code doesn't seem to work. I imported data from a textfile with the following code: vragenlijst_data= np.genfromtxt('antwoorden.txt', delimiter=',', dtype=None, names=('geslacht', 'leeftijd', 'stelling1', 'doorvraag1', 'stelling2', 'stelling3', 'doorvraag3', 'opmerking')) Now my data looks like this: [ ("'vrouw'", 43, " '2'", " 'onbeantwoord'", " '2'", " '2'", " 'onbeantwoord'", " ''") ("'vrouw'", 34, " '2'", " 'onbeantwoord'", " '2'", " '2'", " 'onbeantwoord'", " ''") ("'vrouw'", 32, " '2'", " 'onbeantwoord'", " '2'", " '2'", " 'onbeantwoord'", " ''") ("'vrouw'", 32, " '2'", " 'onbeantwoord'", " '2'", " '2'", " 'onbeantwoord'", " ''") ("'vrouw'", 43, " '3'", " 'sport'", " '2'", " '2'", " 'onbeantwoord'", " ''") ("'vrouw'", 32, " '2'", " 'onbeantwoord'", " '2'", " '2'", " 'onbeantwoord'", " ''") ("'vrouw'", 43, " '2'", " 'onbeantwoord'", " '3'", " '3'", " 'collega'", " 'nee'") ("'vrouw'", 27, " '3'", " 'in alle'", " '3'", " '4'", " '3'", " ''") ("'vrouw'", 34, " '4'", " 'prive en werk'", " '3'", " '2'", " 'onbeantwoord'", " 'fghfgh'") ("'vrouw'", 32, " '2'", " 'onbeantwoord'", " '2'", " '2'", " 'onbeantwoord'", " 'k'") ("'vrouw'", 46, " '4'", " 'werk'", " '4'", " '4'", " 'werk'", " 'nee'")] And I want to plot a histogram with counts of answers in matplotlib. For example, number of vrouw/man and number of times that answer 1, 2, 3, 4, or 5 occurs. However, it seems only possible to plot a histogram with x and y values. I there any way to do this anyway?
duplicate of: http://stackoverflow.com/q/19198920
has comment: http://stackoverflow.com/comment/88584296

http://stackoverflow.com/q/50741997
has answer: http://stackoverflow.com/a/50743847
tagged with: pycharm
downvote count: 0
score: 1
type: Question
tagged with: anaconda
has title: libgdal.so.20: undefined symbol
has body: yesterday the code was running but when I run my code today, the following error occurs: runfile('/media/mattes/data1/dataDMattes/Code/Python/PythonProgram/main.py', wdir='/media/mattes/data1/dataDMattes/Code/Python/PythonProgram') Traceback (most recent call last): File "&lt;ipython-input-1-e8fdc416f3c8&gt;", line 1, in &lt;module&gt; runfile('/media/mattes/data1/dataDMattes/Code/Python/PythonProgram/main.py', wdir='/media/mattes/data1/dataDMattes/Code/Python/PythonProgram') File "/home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/media/mattes/data1/dataDMattes/Code/Python/PythonProgram/main.py", line 17, in &lt;module&gt; import ogr File "/home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/site-packages/ogr.py", line 2, in &lt;module&gt; from osgeo.gdal import deprecation_warn File "/home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/site-packages/osgeo/__init__.py", line 21, in &lt;module&gt; _gdal = swig_import_helper() File "/home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/site-packages/osgeo/__init__.py", line 17, in swig_import_helper _mod = imp.load_module('_gdal', fp, pathname, description) File "/home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: /home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/site-packages/osgeo/../../../libgdal.so.20: undefined symbol: _ZN11xercesc_3_211InputSource11setEncodingEPKDs I also tried to reinstall all and installed gdal and libgdal again but the error still occurs. I use a virtual environment in which I have: gdal 2.2.…
tagged with: gdal
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50743769
downvote count: 0
has body: I'm new to python but I'm really confused on this project I'm trying to do. I've got an image shown here. What I'm trying to do is to find an average across all the squares in the image where the pixel range is from 0 to 255. The code below shows the method I used to calculate the value for the picture. The problem that arises is that the pixels/squares are not the same size where some are bigger than the other. For example, at one instance when looking at a part of the initial picture here, the squares are all equal, therefore the arrays are all equal. However in this picture, we can see that the right hand side squares are smaller than the left hand side ones. I was thinking of creating a subarray from the original array where, any repeated values are ignored. For example like the one below: 1 1 1 2 2 1 2 1 1 1 2 2 1 2 1 1 1 2 2 1 2 1 1 1 2 2 1 2 3 3 3 4 4 1 2 3 3 3 4 4 1 2 5 5 5 6 6 1 2 7 7 7 8 8 1 2 7 7 7 8 8 1 2 to 1 2 1 2 3 4 1 2 5 6 1 2 7 8 1 2 I tried using the following: 1. unique_rows = np.unique(data, axis=0) 2. unique_columns = np.unique(unique_rows, axis=1) to get all the not repeated rows to be displayed into a new array from the original and then get all the non-repeated columns from the new array using the 2nd code. Unfortunately, what this does is get rid of all the repeated values. What I want is only get rid of the repeated consecutive values. I'm really confused on what to do please help! Code: from PIL import Image import numpy as np img = Image.open('greyscale.png').convert('L') # convert image to 8-bit grayscale WIDTH, HEIGHT = img.size data = list(img.getdata()) # convert image data to a list of integers # convert that to 2D list (list of lists of integers) data = np.array ([data[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)]) #unique_rows = np.unique(data, axis=0) #unique_columns = np.unique(unique_rows, axis=1) # At this point the image's pixels are all in memory and can be accessed # individually using data[row][col]. # …
has answer: http://stackoverflow.com/a/50750630
favorite count: 0
accepted answer: http://stackoverflow.com/a/50750630
linked to: http://stackoverflow.com/q/37839928
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50744582
has title: Deleting consecutive numbers from a numpy array
linked to: http://stackoverflow.com/q/51022577
type: Question
type: AnsweredQuestion
upvote count: 2
tagged with: numpy
possible better answer: http://stackoverflow.com/a/50744582
answer count: 2
tagged with: arrays

http://stackoverflow.com/comment/88691498
has text: @DeliriousLettuce I used the same options as the OP.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50843926
type: Comment

http://stackoverflow.com/comment/88651928
type: Comment
comment on: http://stackoverflow.com/q/50823256
score: 0
type: QuestionComment
has text: @abarnert macOS. It might still be -lm, I'll give that a try. But even without the math, it still errors when I return a list.

http://stackoverflow.com/a/50710279
score: 1
accepted answer of: http://stackoverflow.com/q/50709402
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: One option would be to use selenium. In particular, you can use execute_script to convert to a JSON string which Python can easily parse. Since I don't know what the URL of the page you are working with is, I just created a local HTML file which included your script tag example. Using headless is not mandatory and I only added that option so the browser window doesn't open. test.html &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;script&gt; var main_obj = { "link": "", "stock": "", "price": [{"qty": 1000, "value": "100$"}, {"qty": 10000, "value": "1000$"}] } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; Script In[2]: import os ...: import json ...: ...: from selenium import webdriver ...: ...: chrome_options = webdriver.ChromeOptions() ...: chrome_options.add_argument('--headless') ...: driver = webdriver.Chrome(chrome_options=chrome_options) ...: ...: driver.get('file://{}/test.html'.format(os.getcwd())) ...: json_string = driver.execute_script('return JSON.stringify(main_obj)') ...: driver.quit() ...: ...: json_data = json.loads(json_string) In[3]: json_data Out[3]: {'link': '', 'stock': '', 'price': [{'qty': 1000, 'value': '100$'}, {'qty': 10000, 'value': '1000$'}]} In[4]: for item in json_data['price']: ...: print('Quantity: {:d}\tValue: ${:.2f}'.format( ...: item['qty'], float(item['value'].rstrip('$')) ...: )) ...: Quantity: 1000 Value: $100.00 Quantity: 10000 Value: $1000.00
answers question: http://stackoverflow.com/q/50709402
upvote count: 1

http://stackoverflow.com/comment/88682315
has text: This yields the same error. I forgot to mention that I tried this too. Thanks.
comment on: http://stackoverflow.com/q/50805588
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88545109
comment on: http://stackoverflow.com/a/50767382
type: Comment
has text: Thanks for telling me it's not possible as stated. I don't want to waste time going down a rabbit hole. I've taken @j_4321's advice and will be using something like the gradientbar.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88636898
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50814714
has text: Oh when you subclass you transmit the structure of Counter! Python is so handy x')

http://stackoverflow.com/a/50845383
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88695738
type: Answer
answers question: http://stackoverflow.com/q/50845282
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50845282
has body: data = 'GAGACAGAGTCTCACTCTGTTGCACAGGCTGGAGTGCAGTGGCACAATCTCTGCTCACTGCAACCTCCTC' chunk_size = 5 overlap = 2 for pos in range(0, len(data), chunk_size - overlap): print(data[pos:pos+chunk_size]) The results: GAGAC ACAGA GAGTC TCTCA CACTC TCTGT ...
has comment: http://stackoverflow.com/comment/88736913

http://stackoverflow.com/comment/127395739
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/53420574
has text: @quickinsights io in sleep because you input ms and get sleep as output?

http://stackoverflow.com/comment/88679009
type: AnswerComment
comment on: http://stackoverflow.com/a/50837562
score: 0
type: Comment
has text: @LukasBach I think I've included your point in my answer. Thanks.

http://stackoverflow.com/comment/88478050
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50734464
has text: @Minisha What operating system? (Windows, OS X, Linux, etc.?)
score: 0

http://stackoverflow.com/q/50784668
has comment: http://stackoverflow.com/comment/88580577
upvote count: 3
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: tensorflow
has body: I have trained a seq2seq model and saved it with tf.Saver(). Now, the model I've been playing with has those placeholders: encoder_inputs = tf.placeholder(shape=(None, None), dtype=tf.int32, name='encoder_inputs') encoder_inputs_length = tf.placeholder(shape=(None,), dtype=tf.int32, name='encoder_inputs_length') decoder_targets = tf.placeholder(shape=(None, None), dtype=tf.int32, name='decoder_targets') Let's focus on decoder_targets. This placeholder is the wanted result if I recall correctly. This is a problem. If I want to predict a translation (this means that I have no 'wanted result'), what could I do? This is what I have currently import tensorflow as tf tf.reset_default_graph() saver = tf.train.Saver() encoder_inputs = tf.placeholder(shape=(None, None), dtype=tf.int32, name='encoder_inputs') encoder_inputs_length = tf.placeholder(shape=(None,), dtype=tf.int32, name='encoder_inputs_length') decoder_targets = tf.placeholder(shape=(None, None), dtype=tf.int32, name='decoder_targets') encoder_inputs_ = 0 encoder_inputs_length_ lol = 0 with tf.Session() as sess: # Restore model saver.restore(sess, "./rsc/model.ckpt") # Init sess.run(tf.initialize_all_variables()) # Test sess.run(lol, feed_dict={encoder_inputs: encoder_inputs_, encoder_inputs_length: encoder_inputs_length_, ?????}) Do I need to write the whole model in this file too? (sorry for the code, I was testing a few things)
score: 3
downvote count: 0
type: Question
has title: TensorFlow: Predicting with already trained model?
favorite count: 0

http://stackoverflow.com/comment/88688322
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50842285
has text: Is it reasonable not to think that the "Forbidden" list increases with a new randon number every iteration?
score: 0

http://stackoverflow.com/a/50812302
type: Answer
upvote count: 1
has body: I'm really not happy with this approach. Calculating where the y coordinate for a point with your data's x coordinate would fall on the curve seems better. This approach works similarly, but uses the arc's finite vertices: arc1v = ax.transData.inverted().transform(arc1.get_verts()) arc2v = ax.transData.inverted().transform(arc2.get_verts()) for (x,y) in zip(x1[0], y1[0]): err = (arc1v[:,0] - x)**2 + (arc1v[:,1] - y)**2 nearest = (arc1v[err == min(err)])[0] line_x = (x, nearest[0]) line_y = (y, nearest[1]) ax.add_line(mpl.lines.Line2D(line_x, line_y)) if x &gt; nearest[0]: ax.scatter(x, y, marker='^', s=100, c='k', zorder=1) else: ax.scatter(x, y, marker='v', s=100, c='k', zorder=1) This "labels" points on the left of the (left) curve with a down-facing triangle and points on the right of it with an up-facing triangle. The lines on the graph point to the nearest defined vertex on the curve and are for illustration only. You could do this for the other curve as well, and the bin 2/3 division is straightforward. Here's an example output figure: Update: Here's a more complete answer: import matplotlib.pyplot as plt import matplotlib as mpl import math import numpy as np BIN_23_X = 50 # The separator between bin 2 and 3 x1 = np.random.randint(80, size=(400, 10)) y1 = np.random.randint(80, size=(400, 10)) x2 = np.random.randint(80, size=(400, 10)) y2 = np.random.randint(80, size=(400, 10)) fig, ax = plt.subplots() ax.grid(False) plt.scatter(x1[0],y1[0], c = 'r', zorder = 2) plt.scatter(x2[0],y2[0], c = 'b', zorder = 2) ang1 = 0, 50 ang2 = 100, 50 angle = math.degrees(math.acos(5.5/9.15)) xy = 50, 50 Halfway = mpl.lines.Line2D((BIN_23_X,BIN_23_X), (0,100), c = 'white') arc1 = mpl.patches.Arc(ang1, 65, 100, angle = 0, theta2 = angle, theta1 = 360-angle, lw = 2) arc2 = mpl.patches.Arc(ang2, 65, 100, angle = 0, theta2 = 180+angle, theta1 = 180-angle, lw = 2) Oval = mpl.patches.Ellipse(xy, 100, 100, lw = 3, alpha = 0.1) ax.add_line(Halfway) ax.add_patch(arc1) ax.add_patch(arc2…
has comment: http://stackoverflow.com/comment/88854545
answers question: http://stackoverflow.com/q/50811060
score: 1
has comment: http://stackoverflow.com/comment/88874524
accepted answer of: http://stackoverflow.com/q/50811060
has comment: http://stackoverflow.com/comment/88806847
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88837667
has comment: http://stackoverflow.com/comment/88901669
has comment: http://stackoverflow.com/comment/88634103
downvote count: 0
has comment: http://stackoverflow.com/comment/88854239
has comment: http://stackoverflow.com/comment/88860236
has comment: http://stackoverflow.com/comment/88803018
has comment: http://stackoverflow.com/comment/88634310
has comment: http://stackoverflow.com/comment/88916496
has comment: http://stackoverflow.com/comment/88806984
has comment: http://stackoverflow.com/comment/88806630

http://stackoverflow.com/q/50779617
tagged with: pandas
has answer: http://stackoverflow.com/a/50881584
has comment: http://stackoverflow.com/comment/88652992
has comment: http://stackoverflow.com/comment/88566194
has body: In Python generally, membership of a hashable collection is best tested via set. We know this because the use of hashing gives us O(1) lookup complexity versus O(n) for list or np.ndarray. In Pandas, I often have to check for membership in very large collections. I presumed that the same would apply, i.e. checking each item of a series for membership in a set is more efficient than using list or np.ndarray. However, this doesn't seem to be the case: import numpy as np import pandas as pd np.random.seed(0) x_set = {i for i in range(100000)} x_arr = np.array(list(x_set)) x_list = list(x_set) arr = np.random.randint(0, 20000, 10000) ser = pd.Series(arr) lst = arr.tolist() %timeit ser.isin(x_set) # 8.9 ms %timeit ser.isin(x_arr) # 2.17 ms %timeit ser.isin(x_list) # 7.79 ms %timeit np.in1d(arr, x_arr) # 5.02 ms %timeit [i in x_set for i in lst] # 1.1 ms %timeit [i in x_set for i in ser.values] # 4.61 ms Versions used for testing: np.__version__ # '1.14.3' pd.__version__ # '0.23.0' sys.version # '3.6.5' The source code for pd.Series.isin, I believe, utilises numpy.in1d, which presumably means a large overhead for set to np.ndarray conversion. Negating the cost of constructing the inputs, the implications for Pandas: If you know your elements of x_list or x_arr are unique, don't bother converting to x_set. This will be costly (both conversion and membership tests) for use with Pandas. Using list comprehensions are the only way to benefit from O(1) set lookup. My questions are: Is my analysis above correct? This seems like an obvious, yet undocumented, result of how pd.Series.isin has been implemented. Is there a workaround, without using a list comprehension or pd.Series.apply, which does utilise O(1) set lookup? Or is this an unavoidable design choice and/or corollary of having NumPy as the backbone of Pandas? Update: On an older setup (Pandas / NumPy versions) I see x_set outperform x_arr with pd.Series.isin. So an additional question: has anything fundamentally changed …
has comment: http://stackoverflow.com/comment/88566147
has comment: http://stackoverflow.com/comment/88566625
favorite count: 0
score: 41
has comment: http://stackoverflow.com/comment/88566132
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/48129713
has comment: http://stackoverflow.com/comment/88566200
type: AnsweredQuestion
tagged with: performance
accepted answer: http://stackoverflow.com/a/50881584
has comment: http://stackoverflow.com/comment/88566152
has comment: http://stackoverflow.com/comment/88566944
type: Question
tagged with: numpy
upvote count: 43
has comment: http://stackoverflow.com/comment/88566145
answer count: 1
has comment: http://stackoverflow.com/comment/88566161
has title: Pandas pd.Series.isin performance with set versus array
tagged with: series

http://stackoverflow.com/comment/140036168
type: AnswerComment
comment on: http://stackoverflow.com/a/51060721
has text: Anybody looking for another example of directing `print()` and plots to tab widgets, see [here](https://discourse.jupyter.org/t/plot-to-output-in-tab-rendering-in-cell/32351/2?u=fomightez).
score: 0
type: Comment

http://stackoverflow.com/a/50804425
has comment: http://stackoverflow.com/comment/88614849
type: Answer
has comment: http://stackoverflow.com/comment/88614840
score: 3
accepted answer of: http://stackoverflow.com/q/50804350
upvote count: 3
has body: You have a random return statement within the run_CSV function, and when you hit that your functions returns nothing - None When your main funcion tries to do len on that None you will get that error. Since this is part of a loop i'm guessing you meant to use break there and not return It should look like this: for row in ed_reader: if not row[0] and not row[1]: print('\n%i records written to csv' % record_count + '\n%i valid emails found' % valid_email_count) break # formerly "return" was here
answers question: http://stackoverflow.com/q/50804350
type: AcceptedAnswer
downvote count: 0

checkin
tag name: checkin
tags question: http://stackoverflow.com/q/50751672
type: Tag

http://stackoverflow.com/q/50783745
has title: how to extract part of string in python (the string length may vary)
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88574159
linked to: http://stackoverflow.com/q/4289331
answer count: 2
linked to: http://stackoverflow.com/q/4666973
tagged with: string
duplicate of: http://stackoverflow.com/q/4666973
has body: I'm having this string in my app which stores different percentage, I want to just extract the percentage value and convert it to int( ). My String looks something like this.. note: there will be one or more blank space(s) before the number. result ='bFilesystem Size Used Avail Use% Mounted on\n/dev/sda4 30G 20G 8.4G 71% /\n' percentage = getPercentage(result) #This method should output 71 in this example print("Percentage is: ", percentage) Thank you in advance.
has answer: http://stackoverflow.com/a/50783826
tagged with: python
favorite count: 0
score: 0
possible better answer: http://stackoverflow.com/a/50783805
has comment: http://stackoverflow.com/comment/88573978
upvote count: 1
has answer: http://stackoverflow.com/a/50783805
downvote count: 1
accepted answer: http://stackoverflow.com/a/50783826

http://stackoverflow.com/comment/121985670
comment on: http://stackoverflow.com/a/62038408
has text: These solutions overwrite your pandas dataframe with a list
type: AnswerComment
score: 4
type: Comment

http://stackoverflow.com/q/50765643
favorite count: 0
has body: I have written code to show my data set as bar chart. this is my code: I have read my data from .csv file in this way: names = ["Clinic Number","Question Text","Answer Text","Answer Date","Class"] data = pd.read_csv('ADLCI.csv', names = names) And then grouped = data.groupby(['Question Text','Answer Text']).size().reset_index(name='counts') import matplotlib.pyplot as plt plt.figure() grouped.plot(kind='bar', title ="Functional Status Count", figsize=(15, 10), legend=True, fontsize=12) plt.show() This is also the result of data frame I have which I want to show as bar chart. Question Text Answer Text counts 0 CI function No 513 1 CI function Yes 373 2 bathing? No 2827 3 bathing? Yes 408 4 dressing? No 2824 5 dressing? Yes 423 6 feeding No 2851 7 feeding Yes 160 8 housekeeping No 2803 9 housekeeping Yes 717 10 preparing food No 2604 11 preparing food Yes 593 12 responsibility for own medications No 2793 13 responsibility for own medications Yes 625 14 shopping No 35 15 shopping Yes 49 16 toileting No 2843 17 toileting Yes 239 18 transferring No 2834 19 transferring Yes 904 20 using transportation No 2816 21 using transportation Yes 483 the first column that is number has been added automatically, Actually I do not have that in my data set. Here is the bar chart created by this code. As you see in the bar chart, all bars has the same color. also the x axis is the number I was saying. but I dont want in this shape. the thing I want is look like this link: Im going to explain what changes I want to the picture I have uploaded here. Instead of 0 and 1 ... in the x axis, it should depict the Question Text column. In detail, the bar chart in x axis will be: as we see in the dataframe there is two CI function one for yes and one for No. I want CI function instead of 0 and 1 with two different colors one pointing to the count of No 1596 and one different color pointing to Yes 1376. The next item will be bathing?, again one bar pointing to 17965 and another one to 702. With t…
tagged with: data-visualization
tagged with: python
type: AnsweredQuestion
has title: show text description in x axis rather than numbers using pandas matplotlib
upvote count: 1
has answer: http://stackoverflow.com/a/50768579
type: Question
linked to: http://stackoverflow.com/q/29498652
accepted answer: http://stackoverflow.com/a/50768579
tagged with: matplotlib
tagged with: pandas
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/50783619
tagged with: contour
has comment: http://stackoverflow.com/comment/88574925
has answer: http://stackoverflow.com/a/50783702
has answer: http://stackoverflow.com/a/50783638
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/54540732
upvote count: 2
answer count: 5
type: UnansweredQuestion
has title: Getting the x and y coordinates from cv2.contour in Open CV Python and store it to different variables
tagged with: python
has answer: http://stackoverflow.com/a/63123821
downvote count: 2
has comment: http://stackoverflow.com/comment/88574852
has answer: http://stackoverflow.com/a/66226708
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/88574422
has comment: http://stackoverflow.com/comment/88573715
has comment: http://stackoverflow.com/comment/88574302
has body: I'm printing the contour from cv2.findContours. It prints out something like these: [[370 269]] What i want is to get the 370 and store it into a variable. import cv2 import numpy as np cap = cv2.VideoCapture(0) while True: _, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower = np.array([0,0,255]) upper = np.array([255,255,255]) imgThreshHigh = cv2.inRange(hsv, lower, upper) thresh = imgThreshHigh.copy() _,contours,_ = cv2.findContours(thresh, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) print(contours) cv2.imshow('frame',frame) cv2.imshow('Object',thresh) k = cv2.waitKey(5) &amp; 0xFF if k == 27: break cv2.destroyAllWindows()
score: 0

http://stackoverflow.com/a/50856245
type: Answer
has comment: http://stackoverflow.com/comment/88720135
answers question: http://stackoverflow.com/q/50854974
has body: Essentially what you're looking for is a way to share a state between a set of function. The canonical way to do so in an object oriented language is to use a class: class Foo(object): def __init__(self, operation, user=None): self._operation = operation self._user_id = user.id if user else None def f1(self): print("in f1 : {}".format(self._user_id)) self.f2() def f2(self): print("in f2 : {}".format(self._user_id)) self.f3() def f3(self): print("in f3 : {}".format(self._user_id)) f = Foo(operation, user) f.f1() With this solution, your class instances (here f) are "the context" in which the functions are executed - each instance having it's own dedicated context. The functional programing equivalent would be to use closures, I'm not going to give an example here since while Python supports closures, it's still first and mainly an object language so the OO solution is the most obvious. And finally, the clean procedural solution is to pass this context (which can be expressed as a dict or any similar datatype) all along the call chain, as shown in DFE's answer. As a general rule : relying on global variables or some "magic" context that could - or not - be set by you-dont-who-nor-where-nor-when makes for code that is hard if not impossible to reason about, and that can break in the most unpredictable ways (googling for "globals evil" will yield an awful lot of litterature on the topic).
upvote count: 12
score: 12
downvote count: 0

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/50719584

http://stackoverflow.com/q/50736152
favorite count: 0
has body: I need to intergrate datatable and load all the data into the Tkinter GUI in python.. Is it possible to load datatable in Tkinter?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50736889
tagged with: datatable
score: -1
tagged with: tkinter
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88480685
has title: How to integrate datatables in Tkinter?
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/88603748
comment on: http://stackoverflow.com/q/50796254
type: Comment
type: QuestionComment
score: 0
has text: Thanks for the comment. What I did right now was to downgrade Anaconda Python from 3.6.x to 3.5.x and all surprisingly everything works fine now... So in case anyone cannot import pandas because of numpy and getting the same error try to use another version of python.

http://stackoverflow.com/q/50722088
possible better answer: http://stackoverflow.com/a/50722251
upvote count: 1
tagged with: shell
favorite count: 0
accepted answer: http://stackoverflow.com/a/50723635
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88453458
has title: Running shell command in a loop on every files to convert every file from scalar to corresponding csv
tagged with: python
has answer: http://stackoverflow.com/a/50723635
downvote count: 0
has answer: http://stackoverflow.com/a/50722251
type: AnsweredQuestion
score: 1
has body: I need to achieve the following task, help will be appreciated. I run a shell command as scavetool x A.sca -o A.csv This command with scavetool converts the scalar file into the corresponding csv file on my Ubuntu terminal. For example after running this command, it converts the A.sca file into corresponding A.csv file with the same name but only extension is changed to .csv. Thus, I have 100 files starting exactly like this A-#0.sca, A-#1.sca A-#2.sca and so on upto 100, and I want to convert them into their corresponding csv files like A-#0.csv, A-#1.csv, A-#2.csv, and so on upto 100. I need to do this in Python and I know how to run the terminal command inside the python script which is through os.system as follow: for example os.system("command") So far my code look likes this. #!/usr/bin/python3 import csv, os, glob for file in glob.glob('*.sca'): os.system('scavetool x *sca -o *.csv') However, the problem is, it converts all my scalar files into one single .csv file and I know it is because of * sign. But I have tried to loop through on every file as well but I do not get the desired output because with the loop my scavetool command complaints and I can not get the output for every single separate files as a separate csv file. Please help to achieve this.
type: Question
tagged with: scalar
answer count: 2

http://stackoverflow.com/comment/88690593
comment on: http://stackoverflow.com/q/50843370
type: Comment
type: QuestionComment
score: 1
has text: Also, what is your sorting logic? Does "A30" come before "A4" ?

http://stackoverflow.com/a/50732572
score: 6
accepted answer of: http://stackoverflow.com/q/50732536
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50732536
type: Answer
upvote count: 6
has body: In order to remove rows with 'empty' cells, do this: 1. Import .csv to pandas dataframe import pandas as pd df_csv = pd.read_csv('yourfile.csv') 2. Drop NaN rows df_csv.dropna(axis = 0, how = 'any', inplace = True) # axis = 1 will drop the column instead of the row # how = 'all' will only drop if all cells are NaN 3. Save to .csv df_csv.to_csv('yourfile_parsed.csv', index = False) Comments It is better to refer to None or NaN rather than saying 'empty' Also, 'clear' better called 'drop' - people otherwise may think you want to remove all values while keeping the row
has comment: http://stackoverflow.com/comment/88472971

http://stackoverflow.com/q/50746528
downvote count: 0
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/50747696
upvote count: 3
tagged with: pandas
answer count: 1
has title: how do I return all points pairs that satisfy a distance threshold criteria using haversine distance matrix
tagged with: haversine
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have 39,803 different lat lon points (here are the first 5 points) lat lon 0 27.269987 -82.497004 1 27.537598 -82.508422 2 27.337793 -82.533753 3 27.497719 -82.570261 4 27.512062 -82.722158 That I've calculated the haversine distance matrix for array([[ 0. , 29.77832527, 8.36846516, ..., 30.07072193, 7.60700598, 7.63477669], [ 29.77832527, 0. , 22.35749757, ..., 2.6836159 , 22.17639199, 23.07090099], [ 8.36846516, 22.35749757, 0. , ..., 23.07825172, 3.10333262, 0.75441483], ..., [ 30.07072193, 2.6836159 , 23.07825172, ..., 0. , 22.53766911, 23.75965211], [ 7.60700598, 22.17639199, 3.10333262, ..., 22.53766911, 0. , 3.03795035], [ 7.63477669, 23.07090099, 0.75441483, ..., 23.75965211, 3.03795035, 0. ]]) thus my matrix is 39,803 by 39,803. I would like to figure out a way to find all pairs that had a distance of less than 25 meters. For instance, if we consider the first array [ 0. , 29.77832527, 8.36846516, ..., 30.07072193, 7.60700598, 7.63477669] the pair (lat[0],lon[0])-(lat[2],lon[2])=(27.269987,-82.497004)-(27.337793,-82.533753) = 8.36846516 satisfies this criteria but (lat[0],lon[0])-(lat[1],lon[1])=(27.269987,-82.497004)-(27.537598,-82.508422) = 29.77832527 does not. I'd like to get a subset of points that satisfy this criteria. This is what I have so far: X=df'lat','lon'.dropna(axis=0) coors=np.array(X) from math import radians, cos, sin, asin, sqrt from scipy.spatial.distance import pdist, squareform from sklearn.cluster import DBSCAN import matplotlib.pyplot as plt import pandas as pd def haversine(lonlat1, lonlat2): lat1, lon1 = lonlat1 lat2, lon2 = lonlat2 lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers. Use 3956 for miles return c * r distance_matrix = squareform(pdist(X, (lambda u,v: haversine(u,v)))) I'd greatly appreciate any help on how I could potent…
score: 3

http://stackoverflow.com/a/56449929
has body: You could turn NII into numpy array firstly and then turn it into NRRD with using: nrrd and nibabel import numpy as np import nibabel as nib import nrrd # Download NII example_filename = "image.nii.gz" image = nib.load(example_filename) # Turn into numpy array array = np.array(img.dataobj) # Save NRRD nrrd_path_to = "image.nrrd" nrrd.write(image_path_to, array)
has comment: http://stackoverflow.com/comment/108850642
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50845524
type: Answer
upvote count: 2

stop-words
tags question: http://stackoverflow.com/q/50794820
type: Tag
tags question: http://stackoverflow.com/q/50850926
tag name: stop-words
tags question: http://stackoverflow.com/q/50764855

http://stackoverflow.com/q/50814024
tagged with: python
has comment: http://stackoverflow.com/comment/88634225
has comment: http://stackoverflow.com/comment/88634192
upvote count: 1
has comment: http://stackoverflow.com/comment/88633369
type: Question
type: AnsweredQuestion
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/50814707
has comment: http://stackoverflow.com/comment/88633413
has comment: http://stackoverflow.com/comment/88633535
has title: "errorMessage": "Unable to import module 'lambda_function'
has comment: http://stackoverflow.com/comment/88636049
has comment: http://stackoverflow.com/comment/88633128
answer count: 1
downvote count: 0
has body: Upon testing my lambda function I get the following error message: { "errorMessage": "Unable to import module 'lambda_function'" } I uploaded a .zip which only includes the following dependancies: requests, boto3, PIL, Pillow-4.0.0.dist-info &amp; the lambda function lambda_function.py - which is a copied example from AWS: from __future__ import print_function import boto3 import os import sys import uuid from PIL import Image import PIL.Image s3_client = boto3.client('s3') def resize_image(image_path, resized_path): with Image.open(image_path) as image: image.thumbnail(tuple(x / 2 for x in image.size)) image.save(resized_path) def handler(event, context): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = record['s3']['object']['key'] download_path = '/tmp/{}{}'.format(uuid.uuid4(), key) upload_path = '/tmp/resized-{}'.format(key) s3_client.download_file(bucket, key, download_path) resize_image(download_path, upload_path) s3_client.upload_file(upload_path, '{}resized'.format(bucket), key) My handler is: lambda_function.lambda_handler Any idea what the problem is?
score: 1
tagged with: amazon-web-services
favorite count: 0
linked to: http://stackoverflow.com/q/45473501
accepted answer: http://stackoverflow.com/a/50814707

http://stackoverflow.com/q/50761252
has comment: http://stackoverflow.com/comment/88530668
has comment: http://stackoverflow.com/comment/88530245
has comment: http://stackoverflow.com/comment/88530613
answer count: 0
tagged with: fortran
type: UnansweredQuestion
has title: f2py on Windows: undefined references
linked to: http://stackoverflow.com/q/2842469
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88532004
type: Question
has comment: http://stackoverflow.com/comment/88530927
downvote count: 0
has body: I try to compile a simple Hello_World.f90 program with f2py on Windows but get lot's of undefined references First error is: C:\Users\KB\AppData\Local\Temp\tmpv4ama102\Release\users\KB\appdata\local\temp\tmpv4ama102\src.win-amd64-3.4\hellomodule.o: In function `import_array': C:/Users/KB/Python/python-3.4.4.amd64/lib/site-packages/numpy/core/include/numpy/__multiarray_api.h:1466: undefined reference to `_imp__PyImport_ImportModule' with several following errors of the same type. I tried adding -D MS_WIN64 to the compiler argument compiler_so in cygwinccompiler.py (from Python: undefined reference to `_imp __Py_InitModule4&#39;) but that doesn't help. How can I solve this problem ? Some of the output is following below: c:\Users\KB\Fortran_Routines&gt;python C:\Users\KB\Python\python-3.4.4.amd64\Scripts\f2py.py -c --fcompiler=gnu95 --compiler=mingw32 -lmsvcr71 -m hello hello.f90 running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options running build_src build_src building extension "hello" sources f2py options: [] f2py:&gt; C:\Users\KB\AppData\Local\Temp\tmpv4ama102\src.win-amd64-3.4\hellomodule.c creating C:\Users\KB\AppData\Local\Temp\tmpv4ama102\src.win-amd64-3.4 Reading fortran codes... Reading file 'hello.f90' (format:free) Post-processing... Block: hello Block: mod_hello Block: hello Post-processing (stage 2)... Block: hello Block: unknown_interface Block: mod_hello Block: hello Building modules... Building module "hello"... Constructing F90 module support for "mod_hello"... Constructing wrapper function "mod_hello.hello"... hello(a) Wrote C/API module "hello" to file "C:\Users\KB\AppData\Local\Temp\tmpv4ama102\src.win-amd64-3.4\hellomodule.c" Fortran 90 wrappers are saved to "C:\Users\KB\AppData\Local\Temp\tmpv4ama102\src.win-amd64-3.4\hello-f2pywrappers2.f90" adding 'C:\Users\KB\AppData\Local\Temp\tmp…
tagged with: f2py
has comment: http://stackoverflow.com/comment/88530841
tagged with: windows
favorite count: 0

http://stackoverflow.com/comment/88424111
has text: See EDIT in the question as to why I can't keep a string.
comment on: http://stackoverflow.com/q/50707239
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88798948
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50832825
has text: Also think of Cache misses which have a lot of influence on your performance.

http://stackoverflow.com/q/50780492
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/50780512
answer count: 1
has title: Python: What is Wrong With This datetime.strptime Parsing?
has body: I try to parse a string into a datetime object: from datetime import datetime last_time = '2018-06-01T19:00:00.000000000Z' datetime.strptime(last_time, '%Y-%m-%dT%H:%M:%S.%fZ') unfortunately, this fails: ValueError: time data '2018-06-04T08:44:10.000000000Z' \ does not match format '%Y-%m-%dT%H:%M:%S.%fZ' What am I doing wrong? This describes the parameters for parsing: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50780512
favorite count: 0
type: Question

http://stackoverflow.com/q/50775733
tagged with: python-3.x
has title: How do I make Python code to execute only once?
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88558370
score: 2
has answer: http://stackoverflow.com/a/50775856
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50775789
possible better answer: http://stackoverflow.com/a/50775856
type: Question
has body: I was thinking of how you execute code only once in Python. What I mean is setup code like when you set-up software; it only happens once and remembers you have already set up the software when you start the program again. So in a sense I only want Python to execute a function once and not execute the function again even if the program is restarted.
tagged with: function
downvote count: 0
accepted answer: http://stackoverflow.com/a/50775789
answer count: 3
has answer: http://stackoverflow.com/a/51121332
favorite count: 0

http://stackoverflow.com/q/50718084
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/50744538
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python
has body: The file I import with OBSPY has 207 traces forming a stream, each trace has 30k samples. The data from each trace is accessed by seismic_data[trace_number].data and is a 1-d ndarray. I am using a function that takes a trace and an int as parameters: kurt_1d(signal_1d, samples). It returns a 1-d array of the same size. Currently I am using a for loop over the 207 traces to run the function over each trace: def kurt_nd(signal_nd, samples): kurt_array = signal_nd.copy() for index in range(207): kurt_array[index].data = kurt_1d(signal_1d=signal_nd[index].data,samples=samples) return(kurt_array) How can I apply this function kurt_1d(signal_1d, samples) over the whole stream (207 traces) using multiprocessing to boost the speed? The goal is to store each resulting 1-D ndarray in its respective index at the original stream copy.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50744538
upvote count: 1
has title: How to apply multiprocessing on OBSPY stream?
type: Question

qpropertyanimation
tag name: qpropertyanimation
tags question: http://stackoverflow.com/q/50725166
type: Tag

http://stackoverflow.com/comment/88648981
score: 1
comment on: http://stackoverflow.com/q/50821899
has text: Possible duplicate of [Why can't i raise to a negative power in numpy?](https://stackoverflow.com/questions/43287311/why-cant-i-raise-to-a-negative-power-in-numpy)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88437460
comment on: http://stackoverflow.com/q/50714006
score: 0
type: Comment
type: QuestionComment
has text: looking for curl command to solve this

http://stackoverflow.com/q/50831165
tagged with: http://stackoverflow.com/tag/json
type: Question
has body: I dont know a bit of python and below script is output of 6 hour google research. My task is very simple. Wanted to created a text file with movie information pulled from OMDB. I dumped all movie names in a text file and ran following script. Each time I run following script I get only 15-20 movie info but afterwards I get decoder error. When I rerun by removing the movie names for which I already got the info I again get 10-15 movie info! I am not expert in Python but everything below looks fine so not sure why I am getting this. import json import requests import sys import time if(len(sys.argv) != 2): print("Please provide the movie file name as input arg. Ex " + sys.argv[0] + " movie_names.txt") print("Please note that in movie file each movie name should be on a new line") else: with open(sys.argv[1]) as f: for line in f: json_obj_movie_detail = requests.get ("http://www.omdbapi.com/?t=\"" + line.rstrip('\n') + "\"&amp;apikey=$$$$$$$") j = json.loads( json_obj_movie_detail.content ) if(j.get('Title')): print (j['Title']+ ";" , end='', flush=True) else: print (line.rstrip('\n') + ";" + "Could not find this movie!", end='', flush=True) if(j.get('Genre')): print (j['Genre']+ ";" , end='', flush=True) else: print ("null" + ";", end='', flush=True) if(j.get('Plot')): print (j['Plot']+ ";" , end='', flush=True) else: print ("null" + ";" , end='', flush=True) counter = 0 if(j.get('Title')): for each_rating_source in j['Ratings']: print (j['Ratings'][counter]['Source'] + ";", end='', flush=True) print (j['Ratings'][counter]['Value'] + ";", end='', flush=True) counter = counter + 1 else: print ("null", end='', flush=True) print(" ") f.close() would really appreciate help from Python / Json experts. /********* Error *****/ Traceback (most recent call last): File "C:\Users\peacedove\movie_detail.py", line 13, in &lt;module&gt; j = json.loads( json_obj_movie_detail.content ) File "C:\Users\peacedove\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in…
has comment: http://stackoverflow.com/comment/89376697
has comment: http://stackoverflow.com/comment/88666738
has title: Frequent json decoder error - decoder.py line 357, in raw_decode
score: 0
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/a/50742095
answers question: http://stackoverflow.com/q/50741927
score: 0
type: Answer
has body: usually in every project we have some utility code. Some reusable functions, custom configurations of our project. I prefer to create a core app (Click here to see a example project), and just create a few files in there, something like: utils.py or snippets.py, you decide. If you can contextualize your code inside some folder it should be even better for understanding. But the Django itself doesn't care for how many files you create inside your apps.

http://stackoverflow.com/q/50713726
tagged with: plotly
has answer: http://stackoverflow.com/a/68594285
tagged with: pip
has comment: http://stackoverflow.com/comment/88436276
type: Question
score: 5
has title: How to install cufflinks in Python3?
has answer: http://stackoverflow.com/a/58030032
has comment: http://stackoverflow.com/comment/88436303
has answer: http://stackoverflow.com/a/59928246
tagged with: macos
favorite count: 0
tagged with: python-3.x
upvote count: 5
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53476555
tagged with: python
has answer: http://stackoverflow.com/a/65417147
has body: I am using Python 3 on macOS. I have cufflinks installed but IDLE shows ModuleNotFoundError: No module named 'cufflinks' I have used multiple commands in the terminal such as: pip install cufflinks conda install cufflinks conda install -c bioconda cufflinks pip3 install cufflinks conda-forge install cufflinks I have even tried to uninstall and reinstall cufflinks multiple times but IDLE still does not work properly.
downvote count: 0

http://stackoverflow.com/comment/88683642
has text: Thanks so much! DJANGO_SETTINGS_MODULE was the problem. and now that I see the value, the error message makes total sense.
comment on: http://stackoverflow.com/q/50836060
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50839111
score: 0
answer count: 2
has body: I am building a web-application and want to implement webpack in order to run react and django simultaneously. When I attempt to run "webpack --config webpack.config.js" I receive the following error as shown in the stack trace. It seems like it could be a trivial problem, however I can't seem to identify the root of the issue in order to debug. Full Stack Trace SyntaxError: Unexpected token ) at NativeCompileCache._moduleCompile (.\node_modules\v8-compile-cache\v8-compile-cache.js:226:18) at Module._compile (.\node_modules\v8-compile-cache\v8-compile-cache.js:172:36) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Module.require (module.js:587:17) at require (.\node_modules\v8-compile-cache\v8-compile-cache.js:159:20) at WEBPACK_OPTIONS (.\node_modules\webpack-cli\bin\convert-argv.js:133:13) at requireConfig (.\node_modules\webpack-cli\bin\convert-argv.js:135:6) at .\node_modules\webpack-cli\bin\convert-argv.js:142:17 at Array.forEach (&lt;anonymous&gt;) at module.exports (.\node_modules\webpack-cli\bin\convert-argv.js:140:15) at yargs.parse (.\node_modules\webpack-cli\bin\cli.js:241:39) at Object.parse (.\node_modules\yargs\yargs.js:552:18) at .\node_modules\webpack-cli\bin\cli.js:219:8 at Object.&lt;anonymous&gt; (.\node_modules\webpack-cli\bin\cli.js:530:3) at Module._compile (module.js:643:30) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Module.require (module.js:587:17) at require (internal/module.js:11:18) at module.exports.filename (.\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\import-local\index.js:16:66) at .\AppData\Roaming\npm\node_modules\webpack-cli\bin\cli.js:13:6 at Object.&lt;anonymous&gt; (.\AppData\Roaming\npm\node_modules\webpack-cli\bin\cli.js:530:3) at Module._compile (module.js:643:30) at Ob…
has comment: http://stackoverflow.com/comment/88682334
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88682343
has answer: http://stackoverflow.com/a/50839492
tagged with: django
tagged with: python
has title: Receive unexpected token ), on webpack config
type: Question
tagged with: reactjs
tagged with: webpack
has answer: http://stackoverflow.com/a/50839404

http://stackoverflow.com/a/50763612
score: 1
upvote count: 1
has body: You can change this using the backgroundattrs attribute. class graph.graph.graphxy(xpos=0, ypos=0, width=None, height=None, ratio=goldenmean, key=None, backgroundattrs=None, axesdist=0.8*unit.v_cm, xaxisat=None, yaxisat=None, **axes) backgroundattrs is a list of attributes for drawing the background of the graph. Allowed are decorators, strokestyles, and fillstyles. None disables background drawing. http://pyx.sourceforge.net/manual/graph.html#module-graph-graph-graph-geometry
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50763326

http://stackoverflow.com/comment/88566582
has text: @wwii Not sure what you mean by "dribble". The process sends data to sdtdout (pipe) AND to a log file. So if it stop sending to stdout and the log file hasn't changed, the process is waiting for new input. With the current code you can say that the process never terminates (I waited for some minutes and it was still running, because of the buffered inputs). Maybe it will help if you think of it as a Python (or whatever) shell that is running a script that after doing some stuff waits for new input (which can be either "run more stuff" or "exit").
comment on: http://stackoverflow.com/q/50769466
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50808996
has comment: http://stackoverflow.com/comment/88696655
has comment: http://stackoverflow.com/comment/88696593
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88983281
has comment: http://stackoverflow.com/comment/88696623
tagged with: http://stackoverflow.com/tag/html
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: scraping data using python and beautiful soup
has comment: http://stackoverflow.com/comment/88778080
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/88624133
type: Question
has body: I am trying to scrape data from the At The Races website for horse racing results. I want to be able to include the horse name, horse stall, jockey/trainer name, price, age, weight, distance beaten. I can get all of this with a simple command of: for i in soup.select('td'): print(i.text) However, I am presented with the data as below, but it also includes comments which I don't need and I really need it in a format that can be exported to csv. I have tried to break the scraping down with a line of code as such: results = soup.find_all('tr', attrs={'class':'data-number'}) But, that just returns zero results. Included below is a copy of some of the HTML code from the website itself: 1 2. Attain (7) mid-division, headway well over 1f out, soon chasing leaders, led inside final furlong, ran on 5/2 Fav 9 10-12 67 Mr S WalkerArchie Watson I am a complete novice at this so any help or suggestions are greatly appreciated. 1 2. Attain (7) mid-division, headway well over 1f out, soon chasing leaders, led inside final furlong, ran on 5/2 Fav 9 10-12 67 Mr S WalkerArchie Watson 2 5 6. Muthraab Aldaar (IRE) (4) tracked leader, led over 1f out, soon hung left, headed inside final furlong, not run on 11/1 5 9-11 p 59 Miss S Stevens (7)J R Boyle 3 ½ 1. Black Caesar (IRE) (5) led until over 1f out, soon rallied, weakened closing stages 3/1 2Fav 7 10-7 69 Miss M E Spencer (7)P Hide 4 1½ 7. Edge (IRE) (1) held up towards rear, headway over 1f out, chased leaders inside final furlong, never able to challenge 6/1 7 10-2 b 57 Mr R BirkettB J Llewellyn 5 1
tagged with: export
has comment: http://stackoverflow.com/comment/88983227

http://stackoverflow.com/a/50804203
answers question: http://stackoverflow.com/q/50804036
type: Answer
score: 3
downvote count: 0
has body: Data from jpp s[s.str.isalpha()] Out[261]: 0 ABC 2 DEF 6 GHI dtype: object
upvote count: 3
has comment: http://stackoverflow.com/comment/88614506

http://stackoverflow.com/comment/88555214
type: QuestionComment
comment on: http://stackoverflow.com/q/50773388
score: 0
has text: Please see the code in the answer, can you replicate it?
type: Comment

http://stackoverflow.com/comment/103412783
type: Comment
comment on: http://stackoverflow.com/a/50719479
has text: @endolith Interesting, but not helpful. In which version of matplotlib and pandas does which code not work? (Best use a new question for that.)
type: AnswerComment
score: 0

http://stackoverflow.com/a/50774626
has comment: http://stackoverflow.com/comment/88557330
has comment: http://stackoverflow.com/comment/88560081
answers question: http://stackoverflow.com/q/50774598
has comment: http://stackoverflow.com/comment/88558406
has comment: http://stackoverflow.com/comment/88558611
has comment: http://stackoverflow.com/comment/88559867
has comment: http://stackoverflow.com/comment/88557935
accepted answer of: http://stackoverflow.com/q/50774598
has comment: http://stackoverflow.com/comment/88559904
has comment: http://stackoverflow.com/comment/88558726
has comment: http://stackoverflow.com/comment/88557305
score: 0
has comment: http://stackoverflow.com/comment/88557516
has comment: http://stackoverflow.com/comment/88559304
has body: All working nice, but count is 1 for your data sample, because groupby by columns time and id and for ech pair get size of groups 1: print (df2.groupby(['time','id']).count()['w']) time id 2017-04-03 18:09:04 39 1 2017-04-03 18:16:04 39 1 2017-04-03 18:23:04 39 1 2017-04-03 18:30:04 39 1 2017-04-03 18:37:04 39 1 2017-04-03 18:44:04 40 1 2017-04-03 18:51:04 40 1 2017-04-03 18:58:04 40 1 2017-04-03 19:05:04 40 1 2017-04-03 19:12:04 40 1 Name: w, dtype: int64 Then reshaped output is DataFrame with 2 columns filled by 1 and NaNs for values which not exist in pairs: df = df2.groupby(['time','id']).count()['w'].unstack() print (df) id 39 40 time 2017-04-03 18:09:04 1.0 NaN 2017-04-03 18:16:04 1.0 NaN 2017-04-03 18:23:04 1.0 NaN 2017-04-03 18:30:04 1.0 NaN 2017-04-03 18:37:04 1.0 NaN 2017-04-03 18:44:04 NaN 1.0 2017-04-03 18:51:04 NaN 1.0 2017-04-03 18:58:04 NaN 1.0 2017-04-03 19:05:04 NaN 1.0 2017-04-03 19:12:04 NaN 1.0 If values are dates only, so need Grouper by 7d for week or MS for start of month instead time columns (also added parameter fill_value=0 for replace NaNs to 0): df = df2.groupby([pd.Grouper(freq='7d', key='time'),'id'])['w'].count().unstack(fill_value=0) print (df) buildingid 39 40 reporttime 2018-03-01 7 5 2018-03-08 1 0 2018-04-19 1 0 2018-04-26 5 4 So finally your code looks like: fig, ax = plt.subplots(figsize=(15,7)) df2.groupby([pd.Grouper(freq='7d', key='time'),'id'])['w'].count().unstack(fill_value=0).plot(ax=ax)
has comment: http://stackoverflow.com/comment/88559237
has comment: http://stackoverflow.com/comment/88558498
has comment: http://stackoverflow.com/comment/88558749
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88557984
type: Answer

http://stackoverflow.com/q/50818961
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50819076
type: Question
tagged with: average
accepted answer: http://stackoverflow.com/a/50819076
tagged with: group-by
has title: Average one field over two columns
tagged with: dataframe
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50819264
has body: I have searched around and have my own solution, but I believe there is a better way to achieve the result. I have a dataframe with the following columns: from_country to_country score from_country and to_country columns have the same set of entries, e.g. US, UK, China, and so on. For each combination of from-to, there is a specific score. I need to calculate the average of score for each country, regardless appearing in the from_country or the to_country field. df_from = df"from_country", "score".copy() df_from.rename(columns={"from_country":"country"}, inplace=True) df_to = df"to_country", "score".copy() df_to.rename(columns={"to_country":"country"}, inplace=True) df_countries = pd.concat([df_from, df_to]) and then finally calculated the average over the new dataframe. Is there a way to do it better? Thanks
has answer: http://stackoverflow.com/a/50819264

http://stackoverflow.com/comment/88613758
has text: Thanks, @Vivek Kumar I can manually select the y(target) to solve Problem #2. However, then I think I need to fit(X,y) and GridSearch inside the loop which I am not sure if I can do that. This is the main question.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50757948
type: Comment

http://stackoverflow.com/comment/88564572
comment on: http://stackoverflow.com/a/50710666
score: 0
type: AnswerComment
type: Comment
has text: Thanks! Index decreases elapsed time. For 4692 pairs it takes 32 s now.

http://stackoverflow.com/comment/88445600
type: Comment
comment on: http://stackoverflow.com/q/50718604
score: 0
has text: Which Python version do you want it on? There are 2+ default installations on Linux, `python` by default is Python 2.7. You get `python3` as well
type: QuestionComment

http://stackoverflow.com/comment/88467082
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50711159
has text: In short, to solve out of memory of a thrid party API call that is too much memory. I'm running into memory issues after firing more than a certain number of calls to a thrid party application API using python. So, I want to kill ipython in spyder after certain calls and restart my kernel to complete the rest of the calls.

http://stackoverflow.com/comment/88654307
type: QuestionComment
type: Comment
has text: how can I improve my question, to make it easier to answer ?
comment on: http://stackoverflow.com/q/50823531
score: 0

http://stackoverflow.com/a/50725247
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: There could be multiple reasons but my guess is the following: penalty - by default logistic regression is trained with a l2 penalty to prevent overfitting. In this case, the loss function is cross entropy loss plus the l2 norm of weights. As a result, more features will not necessarily guarantee that the cross entropy itself decreases. Btw, it seems like your goal is to get the highest score (lowest loss) on a training set. I am not gonna dispute that but maybe look into test/validation sets.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88460774
accepted answer of: http://stackoverflow.com/q/50723704
answers question: http://stackoverflow.com/q/50723704

http://stackoverflow.com/a/50757081
has comment: http://stackoverflow.com/comment/88521968
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50756288
downvote count: 0
has body: A solution using indexing with numpy arrays: import numpy as np y_labeled=[np.array([1,2,2,4,4,1,1]), np.array([2,1,1,4,4,0,0]), np.array([2,2,2,2,0,0,0])] # Convert dictionary to numpy array weights_dict={1:5, 2:6, 4:19} weight_vector = np.zeros(max(weights_dict.keys()) + 1) for k, v in weights_dict.items(): weight_vector[k] = v print("Weight vector") print(weight_vector) # use y_labeled to select the coefficients of weight_matrix weight = [weight_vector[y] for y in y_labeled] print("Output weight") for w in weight: print(w) Output: Weight vector [ 0. 5. 6. 0. 19.] Output weight [ 5. 6. 6. 19. 19. 5. 5.] [ 6. 5. 5. 19. 19. 0. 0.] [6. 6. 6. 6. 0. 0. 0.]
type: Answer

http://stackoverflow.com/q/50838011
has title: Django - list of choice in a ModelForm
score: 1
has answer: http://stackoverflow.com/a/50838447
upvote count: 1
linked to: http://stackoverflow.com/q/24679181
type: Question
has comment: http://stackoverflow.com/comment/88680631
has comment: http://stackoverflow.com/comment/88681412
downvote count: 0
has answer: http://stackoverflow.com/a/50838500
answer count: 2
has body: I want to customize a modelForm with a list of choices from 0 to 10. I tried to add a widget, but can't figure out how to make it work : class Abonnements(models.Model): id = models.AutoField(primary_key=True) nombre_d_exemplaire = models.IntegerField(blank=True, null=True) numero_d_adherent = models.IntegerField(blank=True, null=True) date_d_enregistrement = models.DateTimeField(blank=False, null=False) # This field type is a guess. premier_numero_a_servir = models.FloatField(blank=True, null=True) remarques = models.TextField(blank=True, null=True) destinataire_facture = models.TextField(blank=True, null=True) adresse_facture = models.TextField(blank=True, null=True) code_postal_facture = models.TextField(blank=True, null=True) ville_facture = models.TextField(blank=True, null=True) personne = models.ForeignKey('personnes.Personnes',on_delete=models.PROTECT,) class Meta: db_table = 'abonnements' ordering = ['-date_d_enregistrement'] class AbonnementsForm(ModelForm): class Meta: model = Abonnements fields = [ "nombre_d_exemplaire" ] widgets = {'"nombre_d_exemplaire" : forms.ChoiceField(widget=forms.RadioSelect, choices=range(10)) } Gives me an error : 'ChoiceField' object has no attribute 'is_hidden'
has comment: http://stackoverflow.com/comment/88679861
favorite count: 0
has comment: http://stackoverflow.com/comment/88680347
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/50852048
has comment: http://stackoverflow.com/comment/88712230
has body: You are expected to crop the region on the image displayed using your mouse. After you have selected the region of interest , hit the Enter key and it will return the cropped image. Now when you check the value of r it returns a tuple of the top-left and bottom-right coordinates of the cropped image. Code: if __name__ == '__main__' : # Read image im = cv2.imread("C:/Users/Desktop/Bengal_cat.png") # Select ROI r = cv2.selectROI(im, False, False) # Crop image imCrop = im[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])] # Display cropped image cv2.imshow("Image", imCrop) cv2.waitKey(0) cv2.destroyAllWindows() Illustration: Assume I have the following image: Now when the code executes r = cv2.selectROI(im, False, False) , the image appears where you can crop using the mouse: Upon hitting the 'Enter' key (or any other key), the cropped image is displayed: That's all that there is to it !! Variable r returns a tuple, which in this case is : (31, 65, 125, 120) where, (31, 65, 125, 120) ^ ^ ^ ^ | | | | x1 y1 | y2 = 120 + 65 x2 = 125 + 31
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88712486
has comment: http://stackoverflow.com/comment/88707635
answers question: http://stackoverflow.com/q/50851658
upvote count: 1

http://stackoverflow.com/a/50767206
has comment: http://stackoverflow.com/comment/88541776
type: Answer
score: 115
has comment: http://stackoverflow.com/comment/88541966
upvote count: 115
accepted answer of: http://stackoverflow.com/q/50766461
answers question: http://stackoverflow.com/q/50766461
has body: The type generated by subclassing typing.NamedTuple is equivalent to a collections.namedtuple, but with __annotations__, _field_types and _field_defaults attributes added. The generated code will behave the same, for all practical purposes, since nothing in Python currently acts on those typing related attributes (your IDE might use them, though). As a developer, using the typing module for your namedtuples allows a more natural declarative interface: You can easily specify default values for the fields (edit: in Python 3.7, collections.namedtuple got a new defaults keyword so this is no longer an advantage) You don't need to repeat the type name twice ("Employee") You can customize the type directly (e.g. adding a docstring or some methods) As before, your class will be a subclass of tuple, and instances will be instances of tuple as usual. Interestingly, your class will not be a subclass of NamedTuple. If you want to know why, read on for more info about the implementation detail. from typing import NamedTuple class Employee(NamedTuple): name: str id: int Behaviour in Python <= 3.8 >>> issubclass(Employee, NamedTuple) False >>> isinstance(Employee(name='guido', id=1), NamedTuple) False typing.NamedTuple is a class, it uses metaclasses and a custom __new__ to handle the annotations, and then it delegates to collections.namedtuple to build and return the type. As you may have guessed from the lowercased name convention, collections.namedtuple is not a type/class - it's a factory function. It works by building up a string of Python source code, and then calling exec on this string. The generated constructor is plucked out of a namespace and included in a 3-argument invocation of the metaclass type to build and return your class. This explains the weird inheritance breakage seen above, NamedTuple uses a metaclass in order to use a different metaclass to instantiate the class object. Behaviour in Python >= 3.9 typing.NamedTuple is changed from a type (class) to a funct…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88432997
type: QuestionComment
comment on: http://stackoverflow.com/q/50711963
has text: In what tool(s) are you testing with? That XPath expression in fact should select the text node `2016`, not instead that `a` element node.
score: 0
type: Comment

http://stackoverflow.com/comment/88606987
type: Comment
score: 0
has text: @ADITYA after option 3? If so, open another question for that
type: AnswerComment
comment on: http://stackoverflow.com/a/50788391

http://stackoverflow.com/q/50829497
has answer: http://stackoverflow.com/a/50829530
accepted answer: http://stackoverflow.com/a/50829530
has body: When I try to install the firebase package in python using: python -m pip install firebase I get the output: Could not find a version that satisfies the requirement firebase (from versions: ) No matching distribution found for firebase Can't seem to find a solution for windows devices.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88663378
has title: Installing Firebase package in Python
upvote count: 2
tagged with: pip
tagged with: python
type: AnsweredQuestion
score: 1
downvote count: 1
type: Question

http://stackoverflow.com/a/50844156
has body: The tkinter.dnd module, as suggested by j_4321 in comments. Here is some sample code using that library to do what you have said: from tkinter import * from tkinter.dnd import Tester as DragWindow, Icon as Dragable # Make a root window and hide it, since we don't need it. root = Tk() root.withdraw() # Make the actual main window, which can have dragable objects on. main = DragWindow(root) def make_btn(): """Make a new test button.""" # The functional part of the main window is the canvas. Dragable('B').attach(main.canvas) # Make a button and bind it to our button creating function. Button(main.top, text='A', command=make_btn).pack() # Start the mainloop. mainloop()
score: 4
answers question: http://stackoverflow.com/q/50803301
downvote count: 0
has comment: http://stackoverflow.com/comment/88700935
type: Answer
has comment: http://stackoverflow.com/comment/127451970
upvote count: 4
has comment: http://stackoverflow.com/comment/127474205
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50803301

http://stackoverflow.com/comment/88671799
score: 0
type: AnswerComment
type: Comment
has text: when i use stat().st_ctime we will get the timestamp(date+time). When i am comparing this value with my specific date, which will fail. Any solution to get only date from st_ctime?
comment on: http://stackoverflow.com/a/50823135

http://stackoverflow.com/comment/88827658
score: 0
type: AnswerComment
has text: Would you be able to add it to your answer? I split the column up in 0-3 by <500 being 0, 500-1000 being 1, 1000-1200 being 2 and 1200+ being 3. Im using mlpclassifier now, but I still have to look up how to tune it properly, so any help would be appreciated
comment on: http://stackoverflow.com/a/50866516
type: Comment

http://stackoverflow.com/comment/88784547
score: 0
has text: What IDE/debugger are you using? Perhaps you should check its settings for "send sigint" option, this makes atexit and context manager solutions feasible.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50782326

http://stackoverflow.com/q/50817905
has comment: http://stackoverflow.com/comment/88643989
tagged with: pytest
has title: pytest dynamically parametrized test
has comment: http://stackoverflow.com/comment/88643650
answer count: 2
has comment: http://stackoverflow.com/comment/88643097
has comment: http://stackoverflow.com/comment/88643843
favorite count: 0
has answer: http://stackoverflow.com/a/50818238
tagged with: python
score: 8
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50818238
has comment: http://stackoverflow.com/comment/88641009
downvote count: 0
has body: I have created a 'dynamic' list of parameters which I pass to parametrize. OPTIONS = ['a', 'b', 'c'] def get_unique_pairs(): unique_list = [] for first in OPTIONS: for second OPTIONS: if first == second: continue unique_list.append({'first':first, 'second':second)) return unique_list def some_func() unique_pairs = get_unique_pairs() result = [] for pair in unique_pair: if test(pair): continue else: result.append(pair) return pair @pytest.mark.parametrize('param', some_fnc()) def test_fnc(param): first = param['first'] second = param['second'] The input I wish to pass to test_fnc is [('a','b'),('a','c')...('c','b')] where the first and second elements are never the same. There is some additional logic I am using to further remove specific pairs. When I run the test I get the output: ::test_fnc[param0] PASSED ::test_fnc[param1] PASSED ::test_fnc[param2] PASSED I have two issues: I'm not entirely sure how to describe what I am doing to find further documentation / help. I would like more descriptive output (i.e. not param0), and I'd like to continue using dictionaries to pass data to the test.
has answer: http://stackoverflow.com/a/50819647
accepted answer: http://stackoverflow.com/a/50819647
upvote count: 8
type: Question

http://stackoverflow.com/q/50774725
downvote count: 0
has body: I need to check if two DataFrames are somewhat "equal", but in a looser sense than pandas.DataFrame.equals is implementing it currently. I am aware of pandas.testing.assert_frames_equal and I really love it, but now I need it a control flow statement and not for testing. For instance I'd like the following code snippet to output equal: df1 = pd.DataFrame([[1]]) df2 = pd.DataFrame([[1.0]]) if frames_equals(df1, df2, check_dtypes=False): print("equal") else: print("not equal") Is there such a function readily available in the pandas library? Note: The question is not about how to build one, but rather if there already is one.
favorite count: 0
has comment: http://stackoverflow.com/comment/88556692
has title: Equality of pandas data frames except dtypes
tagged with: python
has comment: http://stackoverflow.com/comment/88556360
has answer: http://stackoverflow.com/a/79367397
type: UnansweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88578731
has comment: http://stackoverflow.com/comment/88556388
type: Question
has comment: http://stackoverflow.com/comment/88584790
tagged with: dataframe
tagged with: python-3.6
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/88535484
has text: I'm starting to suspect the problem is with numpy. I have other things that are failing to install, and they all point to numpy. I'll look and see if I can find a conda for my platform. I guess it can't hurt.
type: QuestionComment
comment on: http://stackoverflow.com/q/50745656
score: 0
type: Comment

http://stackoverflow.com/q/50836427
possible better answer: http://stackoverflow.com/a/50838910
has comment: http://stackoverflow.com/comment/88698360
type: AnsweredQuestion
score: 3
tagged with: performance
tagged with: dataframe
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/50838910
downvote count: 0
has comment: http://stackoverflow.com/comment/88712159
upvote count: 3
accepted answer: http://stackoverflow.com/a/50837304
tagged with: pandas
has title: Adding to window in pandas
tagged with: python
has body: I have two pandas DataFrames like this: category 1 2 3 b 15 35 20 d 40 35 15 category total a 10 b 10 c 10 d 10 e 10 f 10 In the second Dataframe the categories are unique, and there is only one row per category. In the first Dataframe a category can appear more than once. I would like to add the element in column '2' in the first DataFrame to the corresponding element in the second DataFrame, the element in column '1' should be added to the cell above and the one in column '3' to the cell below. Rendering this result: category total a 10 + 15 b 10 + 35 c 10 + 20 + 40 d 10 + 35 e 10 + 15 f 10 Is there a good way to do this using Pandas? I have a very large dataset so it is important to me that the approach I choose is fast and doesn't use too much memory. Would it be better if I did not use Pandas and used Numpy instead?
favorite count: 0
has answer: http://stackoverflow.com/a/50837304

http://stackoverflow.com/q/50793134
has answer: http://stackoverflow.com/a/50806762
accepted answer: http://stackoverflow.com/a/50806762
type: Question
answer count: 2
tagged with: mocking
has title: How to mock datetime in just one file?
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/50793811
has body: I have two files in which I use datetime. Is there a way to mock it in just one file and not the other? Following is an example of where I'm seeing a weird behavior. File: test_file_one.py import datetime as dt def print_datetime(): print 'First: {}'.format(dt.datetime.utcnow()) File: test_file_two.py import datetime as dt def print_datetime(): print 'Second: {}'.format(dt.datetime.utcnow()) File: main.py import test_file_one as first import test_file_two as second import mock from datetime import datetime, timedelta @mock.patch('test_file_one.dt.datetime') def main(mock_datetime): mock_datetime.utcnow.return_value = datetime.utcnow() + timedelta(days=1) first.print_datetime() second.print_datetime() if __name__ == '__main__': main() Output First: 2018-06-12 08:12:43.838243 Second: 2018-06-12 08:12:43.838243 As you see, both return the same datetime which was mocked. Why are both mocked? How to limit the mock to just one file?
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/50793811

http://stackoverflow.com/q/50742757
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
score: 2
has title: TensorFlow Object Detection API - Out of Memory
tagged with: object-recognition
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55567845
has body: I am using Tensorflow Object Detection API to train my own object detector. I downloaded the faster_rcnn_inception_v2_coco_2018_01_28 from the model zoo (here), and made my own dataset (train.record (~221Mo), test.record and the label map) to fine tune it. But when I run it : python train.py --logtostderr --pipeline_config_path=/home/username/Documents/Object_Detection/training/faster_rcnn_inception_v2_coco_2018_01_28/pipeline.config --train_dir=/home/username/Documents/Object_Detection/training/ the process is killed during the filling up shuffle buffer operation, looks like an OOM problem (16Go RAM)... 2018-06-07 12:02:51.107021: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:94] Filling up shuffle buffer (this may take a while): 410 of 2048 Process stopped Does it exist a way to reduce the shuffle buffer size ? What impact its size ? Then, I add some swap (115Go swap + 16Go RAM) and the filling up shuffle buffer op finished, but my training took all the RAM and swap after step 4 whereas my train.record is just about 221 Mo ! I already added those lines to my pipeline.config > train_config: batch_size: 1 batch_queue_capacity: 10 num_batch_queue_threads: 8 prefetch_queue_capacity: 9 and these ones to my pipeline.config > train_input_reader : queue_capacity: 2 min_after_dequeue: 1 num_readers: 1 following this post. I know my images are very (very very) large : 25Mo each, but as I only took 9 images to make my train.record (just to test if my installation gone well), it should not be so memory consuming right ? Any other idea about why it uses so much RAM ? (BTW I only use CPU)
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/55567845
answer count: 1

http://stackoverflow.com/q/50776137
tagged with: python
has title: Make a file directory with variables as names
has comment: http://stackoverflow.com/comment/88559645
linked to: http://stackoverflow.com/q/273192
has comment: http://stackoverflow.com/comment/88559909
answer count: 0
has comment: http://stackoverflow.com/comment/88560064
type: Question
has comment: http://stackoverflow.com/comment/88559707
score: 0
has comment: http://stackoverflow.com/comment/88560332
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/88559919
downvote count: 1
has comment: http://stackoverflow.com/comment/88559574
has body: I want a list of directories called sim1, sim 2, etc. created when a particular variable in my for loop is equal to 1, 2, etc. I know that I have to use the os package (specifically the os.makedirs() function for directory creation) but have unfortunately not found the documentation pertaining specifically to this. for n in np.arange(0,100): os.makedirs('C:\\Users\\adeet\\Desktop\\'/n) I tried the above code- got the error - unsupported operand type(s) for /: 'str' and 'float' and when I tried this- for n in np.arange(0,100): os.makedirs('C:\\Users\\adeet\\Desktop\\n') It made a folder named 'n' once and then gave me an error -[WinError 183] Cannot create a file when that file already exists: 'C:\Users\adeet\Desktop\n'
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88559729

http://stackoverflow.com/a/50733856
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/50733827
has body: &gt;&gt;&gt; print ("Cost: %f" % 25.77) Cost: 25.770000 &gt;&gt;&gt; print ("Cost: %.2f" % 25.77) Cost: 25.77 Unsure where to find it exactly in PyDoc, but at least the same width-precision rules can be found here.
type: Answer

rose-plot
tags question: http://stackoverflow.com/q/50821406
tag name: rose-plot
type: Tag

http://stackoverflow.com/comment/88507510
has text: Exactly what i needed, great explanation!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50746445

http://stackoverflow.com/q/50842554
score: 0
has title: ImportError after changing the top level directory name
tagged with: python
has body: I changed the top level directory name on a project, and now I'm getting an import error for Flask: ImportError: No module named flask The virtual environment is active - so unless there's something broken in its settings, that's not the problem. I thought the error was because my path had changed, so in Sublime Text 2 I corrected the path name in the project's .sublime-project file to reflect the new top level directory name. However, this doesn't seem to have worked, or it is insufficient, as I'm still getting errors. Where else might I need to address this path change to get things working again, or is there something else I need to do? Thanks in advance for your help!
tagged with: sublimetext2
has comment: http://stackoverflow.com/comment/88689011
answer count: 0
type: UnansweredQuestion
tagged with: flask
tagged with: python-2.7
type: Question
linked to: http://stackoverflow.com/q/6628476
tagged with: macos
has comment: http://stackoverflow.com/comment/88688929
has comment: http://stackoverflow.com/comment/88689480

http://stackoverflow.com/a/50854371
answers question: http://stackoverflow.com/q/50854133
score: 0
type: Answer
has body: You made a typo in the second condition. This gives you a:e,k:m: i, j = 0, 0 for lo1,la1 in zip(X_A, Y_A): for lo2,la2 in zip(X_B, Y_B): if abs(lo1 - lo2) &lt;= error and abs(la1 - la2) &lt;= error: Node_A.append(A[i]) Node_B.append(B[j]) break j += 1 i += 1 j = 0

http://stackoverflow.com/q/50762252
tagged with: pandas
tagged with: python
has body: I am bit puzzled because I would expect the following code to produce a Pandas DataFrame or Series and instead returns a tuple. import pandas_datareader.data as web import random import pandas as pd start_date = '2018-01-01' end_date = '2018-06-06' SPY = web.DataReader('SPY', 'yahoo', start_date, end_date) SPY = SPY'Adj Close' SPY.columns = ['Price'] SPY1 = SPY.iloc[random.sample(range(len(SPY.index)), 80), ] SPY2 = SPY.iloc[random.sample(range(len(SPY.index)), 80), ] SPY3 = SPY1.align(SPY2, join = 'inner', axis = 0) type(SPY3) tuple I can transform the tuple to a Series as follows: SPY3 = pd.Series(SPY3[0]) Still I wonder why a tuple is returned in the first place.
accepted answer: http://stackoverflow.com/a/50762395
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88533383
has title: align returns tuple instead of Pandas DataFrame
downvote count: 0
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/50762395
linked to: http://stackoverflow.com/q/44045158
favorite count: 0
tagged with: series
tagged with: tuples

http://stackoverflow.com/a/50753235
answers question: http://stackoverflow.com/q/50753043
accepted answer of: http://stackoverflow.com/q/50753043
has body: I think it can be helpful to see what is actually happening under the hood when each of these expressions is called. f"{f'{a*b}'}" def om1(a, b): return f"{f'{a*b}'}" dis.dis(om1) 2 0 LOAD_FAST 0 (a) 2 LOAD_FAST 1 (b) 4 BINARY_MULTIPLY 6 FORMAT_VALUE 0 8 FORMAT_VALUE 0 10 RETURN_VALUE The outer f-string encounters an expression which it evaluates, and the inner f-string also finds an expression which it evaluates, which results in the call to BINARY_MULTIPLY f"{f'{expr}'}" def om2(a, b): expr = 'a*b' return f"{f'{expr}'}" dis.dis(om2) 2 0 LOAD_CONST 1 ('a*b') 2 STORE_FAST 2 (expr) 3 4 LOAD_FAST 2 (expr) 6 FORMAT_VALUE 0 8 FORMAT_VALUE 0 10 RETURN_VALUE Here, the first f-string encounters an expression and evaluates it, and the inner f-string, encounters a string, resulting in the call to LOAD_FAST instead of evaluating the contents of the string as Python code. Also it is important to note in this second example the missing LOAD_FAST calls to both a and b, which are present in the first example.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88514546
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/50801616
has body: I have a list of values [3, 3, 3, 0, 0, 2, 2, 2, 2, 1, 5, 5, 5] and I want to return a list of True/False values based on whether or not there are consecutive duplicates. I also want to set a threshold so that I only start getting True's if there are at least 3 consecutive values. For example, the output of the list above would be... [True, True, True, False, False, True, True, True, True, False, True, True, True] I don't really know what the most straightforward and robust way would be to do this. I did a for loop to check if the current value is equal to the next value, and set it to true, but that doesn't account for the beginning and end cases as well (for example one the first set of 3s I will get True, True, False) Also I feel like there's some difficulty with the beginning and ends of the list.
has comment: http://stackoverflow.com/comment/88609339
has comment: http://stackoverflow.com/comment/88609239
has answer: http://stackoverflow.com/a/50801727
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50801727
has comment: http://stackoverflow.com/comment/88609367
type: Question
has comment: http://stackoverflow.com/comment/88609340
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88609214
answer count: 1
has title: Take in a list, return a list of True/False based on consecutive duplicate values

http://stackoverflow.com/comment/88557903
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50775312
score: 0
has text: or share link to gdocs, dropbox...

http://stackoverflow.com/q/50713258
accepted answer: http://stackoverflow.com/a/53230177
has title: matplotlib y-adjustment of texts using adjustText
score: 0
has body: That is a plot i generated using pyplot and (attempted to) adjust the text using the adjustText library which i also found here. as you can see, it gets pretty crowded in the parts where 0 &lt; x &lt; 0.1. i was thinking that there's still ample space in 0.8 &lt; y &lt; 1.0 such that they could all fit and label the points pretty well. my attempt was: plt.plot(df.fpr,df.tpr,marker='.',ls='-') texts = [plt.text(df.fpr[i],df.tpr[i], str(df.thr1[i])) for i in df.index] adjust_text(texts, expand_text=(2,2), expand_points=(2,2), expand_objects=(2,2), force_objects = (2,20), force_points = (0.1,0.25), lim=150000, arrowprops=dict(arrowstyle='-',color='red'), autoalign='y', only_move={'points':'y','text':'y'} ) where my df is a pandas dataframe which can be found here from what i understood in the docs, i tried varying the bounding boxes and the y-force by making them larger, thinking that it would push the labels further up, but it does not seem to be the case.
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/53230177
type: AnsweredQuestion
tagged with: matplotlib
type: Question

http://stackoverflow.com/a/50719747
has comment: http://stackoverflow.com/comment/88475121
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50719532
answers question: http://stackoverflow.com/q/50719532
type: Answer
has body: You code is currently only storing the last pair, and writing that to the database. You need to call fname and lname inside the loop and write each pair seperately to the database. You can ammend your code to this: import pymysql import xlrd book = xlrd.open_workbook('C:\SqlExcel\Backup.xlsx') sheet = book.sheet_by_index(0) # Connect to the database connection = pymysql.connect(host='localhost', user='root', password='', db='test', autocommit=True) cursor = connection.cursor() query = """INSERT INTO report_table (FirstName, LastName) VALUES (%s, %s)""" # loop over each row for r in range(1, sheet.nrows): # extract each cell fname = sheet.cell(r,1).value lname = sheet.cell(r,2).value # extract cells into pair values = fname, lname # write pair to db cursor.execute(query, values) # close everything cursor.close() connection.close() Note: You can set autocommit=True in the connect phase. PyMySQL disables autocommit by default. This means you dont have to call cursor.commit() after your query.

http://stackoverflow.com/q/50793654
tagged with: indexing
type: AnsweredQuestion
has title: Convert value based on index location in Python
score: 1
has answer: http://stackoverflow.com/a/50793933
has comment: http://stackoverflow.com/comment/88593367
type: Question
has body: I need the value from the first column, first row index (iloc[0]) in df1, and to convert the matching value in df2 to 0. I was trying something like this but I'm aware the syntax is out df2[df1['ID'].iloc[0]] = 0 df1: ID Name X 6539 CM 20 9999 FM 30 df2: Out 1 Out 2 Out 3 Out 4 Out 5 7000 8000 6539 6539 6539 So the output would be Out 1 Out 2 Out 3 Out 4 Out 5 7000 8000 0 0 0
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50793834
favorite count: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88593602
upvote count: 1
has answer: http://stackoverflow.com/a/50793834
accepted answer: http://stackoverflow.com/a/50793933

http://stackoverflow.com/q/50841195
accepted answer: http://stackoverflow.com/a/50841736
tagged with: list
has answer: http://stackoverflow.com/a/50841320
type: Question
type: AnsweredQuestion
has body: I have an nd-array 'A' of dimensions (n, m, p), and I have a list of length n*m that contains arrays a1,a2,.. each of the arrays being of length p. What I am trying to do is to sequentially (by rows) fill 'A' using the arrays 'a'. Consider for instance the following example: A = np.empty ((2,3,4)) a1 = np.array([1,2,3,0]) a2 = np.array([3,4,6,9]) a3 = np.array([9,5,8,5]) a4 = np.array([1,5,4,2]) a5 = np.array([9,7,0,5]) a6 = np.array([4,3,2,1]) lst = [a1, a2, a3, a4, a5, a6] I am trying to find some way to do A = DoSomething(A, lst) print(A) array([[[ 1., 2., 3., 0.], [ 3., 4., 6., 9.], [ 9., 5., 8., 5.]], [[ 1., 5., 4., 2.], [ 9., 7., 0., 5.], [ 4., 3., 2., 1.]]]) So this way A[0, 0, :]=a1, A[0, 1, :]=a2 and so on.
has title: How to sequentially fill a 3d matrix in python?
tagged with: numpy
score: 0
tagged with: numpy-ndarray
answer count: 3
has answer: http://stackoverflow.com/a/50841736
has answer: http://stackoverflow.com/a/50841365
tagged with: python
possible better answer: http://stackoverflow.com/a/50841320

http://stackoverflow.com/comment/88548670
comment on: http://stackoverflow.com/q/50770356
type: Comment
type: QuestionComment
has text: @estephan500 It is only to know, if you are comparing the same library on different platforms you should know the versions, have you tried another computer ?, In addition it would be advisable to indicate how you have installed tkinter in macos.
score: 0

http://stackoverflow.com/comment/88648654
has text: I meant a [mcve](https://stackoverflow.com/help/mcve). If you can produce that it would be easier to help you out.
score: 1
comment on: http://stackoverflow.com/q/50819051
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50774542
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50774712
accepted answer: http://stackoverflow.com/a/50774712
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88555992
has body: I have two lists: one with partial transactions, and another one with their parent transactions: partials = [1,2,3,4,5,6,7,8,9,10] parents = ['a','b','c','d','a','d','f','c','c','a'] I zip those lists into dictionary: transactions = zip(partials, parents) As you can see, some partial transactions have same parent transactions. I need to group the items in dictionary into smaller groups (smaller dictionaries?) in such way that in each group there will be no more than one transaction belonging to one parent. So for example all transactions with parent "a" will need to end up in different groups. I also need as few groups as possible, because in real world each group will be a file to upload manually. Expected output would be like this: Group 1 would contain transactions 1a, 2b,3c, 4d, 7f, Group 2 would contain transactions 5a, 6d, 8c, Group 3 would contain transactions 9c, 10a I have been scratching my head for a while on this and will appreciate any suggestions. So far I do not have any working code to post.
has answer: http://stackoverflow.com/a/50775497
has comment: http://stackoverflow.com/comment/88556331
type: Question
has title: Splitting dictionary items into smaller dictionaries based on condition
answer count: 3
has comment: http://stackoverflow.com/comment/88556004
upvote count: 1
has answer: http://stackoverflow.com/a/50774714
favorite count: 0
has comment: http://stackoverflow.com/comment/88556198
tagged with: python
possible better answer: http://stackoverflow.com/a/50774714
has comment: http://stackoverflow.com/comment/88556318

http://stackoverflow.com/comment/88423217
score: 0
has text: @abarnert Maybe you are right. I am not a python expert, just identified a language-agnostic problem here.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50706682

http://stackoverflow.com/comment/88680338
type: Comment
type: QuestionComment
has text: Should be not, since I can get correct data if I using numbers, 953381.
comment on: http://stackoverflow.com/q/50837627
score: 0

http://stackoverflow.com/q/50822127
possible better answer: http://stackoverflow.com/a/50822540
tagged with: pickle
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50822329
accepted answer: http://stackoverflow.com/a/50822329
type: Question
has title: How to perform a pickling so that it is robust against crashing?
has body: I routinely use pickle.dump() to save large files in Python 2.7. In my code, I have one .pickle file that I continually update with each iteration of my code, overwriting the same file each time. However, I occasionally encounter crashes (e.g. from server issues). This may happen in the middle of the pickle dump, rendering the pickle incomplete and the pickle file unreadable, and I lose all my data from the past iterations. I guess one way I could do it is to save one .pickle file for each iteration, and combine all of them later. Are there any other recommended methods, or best practices in writing to disk that is robust to crashing?
has answer: http://stackoverflow.com/a/78368378
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/50822540
favorite count: 0

http://stackoverflow.com/comment/88517189
score: 0
comment on: http://stackoverflow.com/q/50754643
type: QuestionComment
type: Comment
has text: What is the problem in reading 300mb of json? Did you try it? (`pip install mpu` and then `import mpu.io; data = mpu.io.read("your path.json")`). I guess reading it takes less time than writing this question.

http://stackoverflow.com/q/50839121
upvote count: 2
has title: Pandas replace not working as expected on multiple column subset
answer count: 1
accepted answer: http://stackoverflow.com/a/50839148
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88682197
has body: There seems to be an issue with pandas replace() option when doing replacement on only a few columns: # Example dataframe: pd.DataFrame(data={"x":[1,2,3,4,5], "y":[2,4,1,2,4], "z":["no", "yes", "no", "no", "no"], "t":["a", "b", "c", "d", "d"]}) # Try to replace the 2s inplace: a.loc[:, ["x", "y"]].replace(2,-9999, inplace=True) a is still: Out[32]: x y z t 0 1 2 no a 1 2 4 yes b 2 3 1 no c 3 4 2 no d 4 5 4 no d Note that I do not get a settingWithCopy warning - also, I am using .loc as recommended. Since I use inplace=True, I would have expected the dataframe to change. Am I doing something wrong, or is this a bug to report on github? I am using pandas version 0.23.0.
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/50839148

http://stackoverflow.com/comment/88437682
type: QuestionComment
has text: The code is incomplete. What is `strline`? Where are `nonterminals` and `TXLtoken` defined? Please try to create a [mcve].
comment on: http://stackoverflow.com/q/50711655
score: 0
type: Comment

http://stackoverflow.com/q/50780736
downvote count: 3
has answer: http://stackoverflow.com/a/50780757
has answer: http://stackoverflow.com/a/50780747
type: Question
accepted answer: http://stackoverflow.com/a/50780757
upvote count: 0
has title: How to Concatenate Row1 + Row2 with email extension? TypeError: can only concatenate list (not "str") to list
possible better answer: http://stackoverflow.com/a/50780747
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/88568176
has answer: http://stackoverflow.com/a/50780756
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/88568196
type: AnsweredQuestion
has body: I am new and have looked on this forum and online but cannot find a specific solution to my problem. Sorry if this seems easy for you guys! I have a .csv file that I want to eventually import. There are three columns: First_Name, Last_Name, and Email_Extension. Desired output format:First_Name.Last_Name@Email_Extension This is my code so far: First_Name =['Name1', 'Name2'] Last_Name = ['Last1', 'Last2'] Emails = First_Name + Last_Name Final = Emails + '@gmail.com' print(Final) Output should be: Name1.Last1@Gmail.com &amp; Name2.Last2@Gmail.com Thanks so much for your help! Also, any general tips and guidance/resource for data architecture is much appreciated!

http://stackoverflow.com/q/50833759
has body: I want to test some simple code for pep8 compliance using pytest pep8 in Ubuntu 18.04. The command I use in the terminal is my_name@my_name's-laptop:~/my_folder$ py.test --pep8 simple_flask.py But it gets stuck at 'collecting 1 item'. But if I press ctrl-c, it executes. I wonder what is wrong. My simple_flask.py code is from flask import Flask app = Flask(__name__) @app.route('/') def hello() -&gt; str: return 'Hi there from Flask!' app.run() Any suggestions on how to solve this?
type: UnansweredQuestion
tagged with: terminal
has comment: http://stackoverflow.com/comment/88672816
type: Question
linked to: http://stackoverflow.com/q/419163
duplicate of: http://stackoverflow.com/q/419163
tagged with: python
has comment: http://stackoverflow.com/comment/88679910
tagged with: pytest
tagged with: ubuntu-18.04
score: 0
has title: pytest pep8 compliance check gets stuck
tagged with: pep8
answer count: 0

http://stackoverflow.com/comment/88672370
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50817371
type: Comment
has text: @dabadaba yup... Use the answer below to convert model keys into numpy integer / slice keys.

http://stackoverflow.com/comment/88442042
comment on: http://stackoverflow.com/a/50716519
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172571/discussion-between-anton-vbr-and-constantin).
type: AnswerComment

http://stackoverflow.com/comment/88653424
type: Comment
has text: agree with @OndrejK. Your indentations aren't correct. The problem seems in the last line of your code. `(Levels, "{}".format(Levels()))` is a tuple and you are trying to call the tuple `( ... )()` which couldn't be done.
comment on: http://stackoverflow.com/q/50822916
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88692807
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50843606
type: Comment
has text: I've ended up simplifying this by doing `setattr(mymodule, "func1", lambda *a, **kw: 2)` Which was derived from what you showed. So thank you. Marking this as the answer but if someone comes along and shows a cleaner way of doing it, I'm liable to switch the accepted answer.

http://stackoverflow.com/comment/88509781
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50750387
has text: Note the top of this page, where it discusses the encoder and decoder. These are interfaces the model uses. You're asking to get into the data stream before this point, so you'll need to dig back to see where the encoder gets its dictionary, and then to see how you can affect that dictionary.

http://stackoverflow.com/q/50736310
has comment: http://stackoverflow.com/comment/88537724
tagged with: google-app-engine
accepted answer: http://stackoverflow.com/a/50957764
has title: How to PubSub from non-streaming Dataflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50957764
tagged with: google-cloud-dataflow
type: Question
has body: I want to notify to GAE when DataFlow job is finished. So, I tries to make the following pipeline: from apache_beam.io.gcp.pubsub import WriteStringsToPubSub ( p | ReadFromDatastore(google_cloud_options.project, query) ...snip... | 'send to pubsub' &gt;&gt; WriteStringsToPubSub(GCS_TOPIC) ) But the above code produces the following error: ValueError: PubSubPayloadSink is currently available for use only in streaming pipelines. How to notify the GAE app when job is finished? Should I use the GCPClinentLibrary? (from google.cloud import pubsub_v1)
tagged with: google-cloud-platform
score: 0
answer count: 1
tagged with: python

http://stackoverflow.com/a/50749379
type: AcceptedAnswer
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50749149
has body: JSON square brackets are for arrays, which correspond to Python lists. JSON curly braces are for objects, which correspond to Python dictionaries. So you need to create a list containing a dictionary, then convert that to JSON. incident_type = [{"name": "Phishing - General"}] incident_owner = 'Security Operations Center' payload = { 'name':name, 'discovered_date':'0', 'owner_id':incident_owner, 'description':description, 'exposure_individual_name':corpID, 'incident_type_ids':incident_type } body=json.dumps(payload) It's only slightly coincidental that the Python syntax for this is similar to the JSON syntax.
accepted answer of: http://stackoverflow.com/q/50749149
downvote count: 0

http://stackoverflow.com/a/50812212
score: 0
has body: Simply just use the in operator. print([11, 18] in A) Result: true
answers question: http://stackoverflow.com/q/50812153
type: Answer

http://stackoverflow.com/a/50723494
has body: The straightforward implementation using for loops would be: import math def correlation(x, y): x_bar = sum(x) / len(x) y_bar = sum(y) / len(y) var_x = sum((x_i - x_bar)**2 for x_i in x) var_y = sum((y_i - y_bar)**2 for y_i in y) assert len(x) == len(y) numerator = sum((x_i - x_bar) * (y_i - y_bar) for x_i, y_i in zip(x, y)) denominator = math.sqrt(var_x * var_y) return numerator / denominator if __name__ == "__main__": x = [...] y = [...] print(correlation(x, y)) When doing a lot of numeric calculations one usually uses the numpy module where this function is already defined: import numpy as np if __name__ == "__main__": x = np.array([...]) y = np.array([...]) print(np.corrcoef(x, y)[0, 1])
answers question: http://stackoverflow.com/q/50723319
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/50826232
tagged with: derivative
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89090276
tagged with: autograd
type: Question
upvote count: 2
tagged with: numerical-methods
has body: I'm a total neophyte when it comes to Autograd, so I feel like I may be doing something very obviously wrong. However, I've spent a full day struggling on this. I am trying to calculate the derivative of a function that includes a normal cdf. I had no success with Autograd, so I broke it up into smaller and smaller parts until I isolated the source of error as the Normal CDF. Here is a minimal working example: import autograd.numpy as np from autograd.misc.optimizers import adam, rmsprop, sgd from autograd import grad from autograd.scipy.stats import norm def test_func(x,t): return norm.cdf(x) grad_test = grad(test_func) def callback(params, t, g): print(params, " Gradient: ", g, " Derivative: ", norm.pdf(params)) print(adam(grad_test, 0.0 ,num_iters = 10, step_size= 0.1, callback = callback)) I know it doesn't make sense to optimize a CDF, I just did this to get the output from the callback, which is below: 0.0 Gradient: 0.24197072451914337 Derivative: 0.398942280401 -0.09999999586726883 Gradient: 0.26608524890906193 Derivative: 0.396952547641 -0.20013469787000787 Gradient: 0.2897227684832687 Derivative: 0.391032156046 -0.30048876968878535 Gradient: 0.31236074851454854 Derivative: 0.38133185077 -0.40113882898768705 Gradient: 0.33345215596996947 Derivative: 0.368102181121 -0.5021500752550674 Gradient: 0.35244319911051986 Derivative: 0.351686233767 -0.6035729426432459 Gradient: 0.3687944858147128 Derivative: 0.332508890217 -0.7054397817605528 Gradient: 0.38200507149861374 Derivative: 0.311062576619 -0.8077615706004915 Gradient: 0.391638389745137 Derivative: 0.287889684926 -0.910524672771251 Gradient: 0.3973485394632615 Derivative: 0.263562137446 The gradients calculated by Autograd dont match the theoretical derivative, represented by the normal PDF. Am I implementing this incorrectly? I feel it's unlikely that such a widely used package would have a hole like this. How can I use Autograd (or other packages in Python) in order to get efficient numerical derivatives o…
has title: Autograd fails to properly calculate Normal CDF derivative
favorite count: 0
answer count: 0
tagged with: differentiation
type: UnansweredQuestion

http://stackoverflow.com/comment/88425700
type: Comment
type: QuestionComment
has text: @bsam That still gives the same error.
comment on: http://stackoverflow.com/q/50708172
score: 0

http://stackoverflow.com/a/50771431
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50761829
has body: When you use PyYAML's load, you specify that everything in the YAML document you are loading is safe. That is why you need to use yaml.safe_load. In your case this leads to an error, because safe_load doesn't know how to construct pandas internals that have tags in the YAML document like: !!python/name:pandas.core.indexes.base.Index and !!python/tuple etc. You would need to provide constructors for all the objects, add these to the SafeLoader and then do a_series = yaml.load(f). Doing that can be a lot of work, especially since what looks like a small change to the data used in your series might require you to add constructors. You could dump the dict representation of your Series and load that back. Of course some information is lost in this process, I am not sure if that is acceptable: import sys import yaml from pandas import Series def series_representer(dumper, data): return dumper.represent_mapping(u'!pandas.series', data.to_dict()) yaml.add_representer(Series, series_representer, Dumper=yaml.SafeDumper) def series_constructor(loader, node): d = loader.construct_mapping(node) return Series(data) yaml.add_constructor(u'!pandas.series', series_constructor, Loader=yaml.SafeLoader) data = Series([1,2,3,4,5], index=['a', 'b', 'c', 'd', 'e']) with open('ex.yaml', 'w') as f: yaml.safe_dump(data, f) with open('ex.yaml') as f: s = yaml.safe_load(f) print(s) print(type(s)) which gives: a 1 b 2 c 3 d 4 e 5 dtype: int64 &lt;class 'pandas.core.series.Series'&gt; And the ex.yaml file contains: !pandas.series {a: 1, b: 2, c: 3, d: 4, e: 5} There are a few things to note: YAML documents are normally written to files with a .yaml extension. Using .py is bound to get you confused, or have you overwrite some program source files at some point. yaml.load() and yaml.safe_load() take a stream as first paramater you use them like: data = yaml.safe_load(stream) and not like: yaml.safe_load(data, stream) It would be better to have a two step constructor, which allows you to construct …
accepted answer of: http://stackoverflow.com/q/50761829
has comment: http://stackoverflow.com/comment/88639926
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88644899

http://stackoverflow.com/a/50751411
upvote count: 3
has comment: http://stackoverflow.com/comment/88510813
answers question: http://stackoverflow.com/q/50751356
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88510822
downvote count: 0
has body: It seems like you have most of this already done, and you already have a good grasp of how to partition each line into the two components you need, so you're real close! First, since the data is being read in as a string, you need to convert part of your data to integers: for line in file: tmp = line.split() name, scores = tmp[0], list(map(int, tmp[1:])) This will give us each name, along with a list of scores as integers. Now all you have to do is find the average: average = sum(scores)/len(scores) Let's tie it all together by assigning to a dictionary: dct[name] = average And we get: {'joe': 23.0, 'bill': 20.0, 'sue': 16.166666666666668, 'grace': 23.666666666666668, 'john': 35.2}
accepted answer of: http://stackoverflow.com/q/50751356
type: Answer
score: 3

http://stackoverflow.com/comment/88696585
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50845982
type: Comment
has text: Just a note (wasn't in the problem statement, but I thought I'd add it here), if I want only *unique* combinations, I can use your idea but define `roll_slices = set()` and then `df.rolling('3d')['a'].apply(lambda x: roll_slices.update(it.combinations(x, 2)) or 0)`. Cool idea!

http://stackoverflow.com/q/50785230
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88578076
tagged with: python
has answer: http://stackoverflow.com/a/50785568
tagged with: setuptools
has title: Force python installation into virtualenv
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88577510
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88578194
score: 1
tagged with: virtualenv
favorite count: 0
has body: I've got large python module that is particularly complex in terms of dependencies and on the Raspberry Pi it now conflicts with several core modules (pillow, pyserial, and a few others) which can't easily be overwritten. In general, installing into a virtualenv would be the best thing. But I've found that's a little beyond some users and as most users will simply use the CLI command that gets installed instead of the module API, I'd like to make things automatic. Is it possible, in any way, with setuptools to do the following? Automatically install virtualenv if not available Install module into virtualenv Install require dependencies into virtualenv Setup CLI command to run automatically from that virtualenv without first activating it

http://stackoverflow.com/a/50849593
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50845914
type: Answer
accepted answer of: http://stackoverflow.com/q/50845914
has body: This behavior is not due to an inherent limitation of Sphinx, restructuredText, or autodoc, but in fact a bug in the (current version of the) Napoleon extension for processing Google-style docstrings. Napoleon uses a regular expression to partition content on a colon, and it greedily consumes characters until it reaches the colon. The reason it works with the :code: role is that Napoleon detects those before partitioning, but it does not detect the inline formatting (note that the problem also occurs with other inline formatting patterns, such as *emphasis* or **strong**). One way to get around the bug, until it is fixed, is to place a colon before the inline literal: def function(a, b): """Put *a* and *b* in a dictionary. Returns: dict: ``{a: b}`` """ return {a: b}
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/a/50728650
has body: If you give the Text widget a fixed height and width and wrap it in a Frame with the same width and height and use grid_propagate(False), when the text is made bigger the Text widget stays the same size. import tkinter as tk def fontUp(): text.config(font = ("30")) root = tk.Tk() root.geometry("800x800") frm = tk.Frame(root, height = 500, width = 500) frm.grid(row = 0, column = 0) frm.grid_propagate(False) text = tk.Text(frm, height = 500, width = 500) text.grid(row = 0, column = 0) btn = tk.Button(root, text="Font bigger", command = fontUp) btn.grid(row = 2, column = 0)
accepted answer of: http://stackoverflow.com/q/50727128
score: 0
answers question: http://stackoverflow.com/q/50727128
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88629682
score: 1
has text: `deomcpose()` returns None and deletes the tag. Copy my code completely and print `print(new_data.get_text(' ', strip=True))`.
type: AnswerComment
comment on: http://stackoverflow.com/a/50812081
type: Comment

http://stackoverflow.com/comment/88558813
comment on: http://stackoverflow.com/q/50775830
score: 0
has text: I don't see the answer I'm looking for in that question and answer, I'm looking for an explanation of the different uses of `iter` and `__iter__()`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50842864
favorite count: 0
tagged with: python
tagged with: sublimetext3
tagged with: text
tagged with: getpass
type: UnansweredQuestion
upvote count: 1
type: Question
has title: Using getpass with Sublime Text
has body: Like the title says I am tryin gto use the getpass library with sublime text (and SublimeREPL.) When I run a simple piece of code, I get nothing but a blank screen in the sublime terminal and the REPL terminal. Is there any way to get getpass to work with sublime text? I ran the same code in powershell python and it worked just fine. import getpass psswd = getpass.getpass(prompt = 'Password:')
score: 1
has answer: http://stackoverflow.com/a/50842919
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/88542439
type: Comment
type: QuestionComment
has text: Possible duplicate of [Why does 2to3 change mydict.keys() to list(mydict.keys())?](https://stackoverflow.com/questions/27476079/why-does-2to3-change-mydict-keys-to-listmydict-keys)
score: 1
comment on: http://stackoverflow.com/q/50767506

http://stackoverflow.com/q/50854687
tagged with: python
has body: I am using SQLAlchemy through Flask-SQLAlchemy as the ORM for a web app. I'd like to automatically leading and trailing strip whitespace (e.g. str.strip) when assigning to any string field. One way to do this would be the following, but it would need to be specified for each and every string field: class User(db.Model): _email = db.Column('email', db.String(100), primary_key=True) @hybrid_property def email(self): return self._email @email.setter def email(self, data): self._email = data.strip() I would like to do this more generically for every String field (without having to write the above for each).
score: 2
downvote count: 0
tagged with: orm
tagged with: string-parsing
has answer: http://stackoverflow.com/a/50854876
tagged with: sqlalchemy
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88712692
has title: Stripping whitespace generically for all String fields - SQLAlchemy
linked to: http://stackoverflow.com/q/18413748
answer count: 1
tagged with: flask-sqlalchemy
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50845531
answer count: 2
has body: With a Python function in testreturn.py defined as: import sys def main(): sys.exit(1) When called from a bash function in scrip.sh defined as: #!/bin/bash function test() { python testreturn.py echo $? } Why does the following command: test Print 0 I would like the bash function to print the exit code of the python script.
downvote count: 0
favorite count: 0
tagged with: bash
tagged with: python
has comment: http://stackoverflow.com/comment/88699425
has comment: http://stackoverflow.com/comment/88694646
possible better answer: http://stackoverflow.com/a/50845573
upvote count: 3
has answer: http://stackoverflow.com/a/50845600
has answer: http://stackoverflow.com/a/50845573
type: AnsweredQuestion
score: 3
has title: Why does bash echo print 0 for a Python function that exits 1
type: Question
accepted answer: http://stackoverflow.com/a/50845600

http://stackoverflow.com/comment/88567686
score: 0
has text: test_url is just the call to the web service. What I really want to do is have a remote camera pass me an image which I want to use in facial recognition software. I can't seem to verify whether I am passing an image correctly because I can't recover it. I can't test either the post of the file or the corresponding read unless they both work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50780308

http://stackoverflow.com/comment/100043374
score: 6
has text: You can (and should, if the data are dynamic) add appropriate http headers to disable caching. Ultimately, if you need the data to be “realtime”, you should choose different approach – feed the data to the browser via websocket and plot them using JavaScript (d3.js or similar).
type: AnswerComment
comment on: http://stackoverflow.com/a/50728936
type: Comment

http://stackoverflow.com/q/50768000
has comment: http://stackoverflow.com/comment/88544449
linked to: http://stackoverflow.com/q/18478352
has comment: http://stackoverflow.com/comment/88544385
answer count: 2
downvote count: 1
has body: It detects collision most of times, but sometimes it doesn't. Here is collision checker: def collide_check(this, object_1): bullet_rect = this.image.get_rect().move(this.bullet_x, this.bullet_y) object_1_rect = object_1.image.get_rect().move(object_1.ice_x, object_1.ice_y) if bullet_rect.colliderect(object_1_rect): #consequences of collision
favorite count: 0
accepted answer: http://stackoverflow.com/a/50768199
possible better answer: http://stackoverflow.com/a/50768080
tagged with: python
tagged with: pygame
tagged with: collision
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50768199
linked to: http://stackoverflow.com/q/33922546
has title: PyGame: why isn't collision working well?
score: 1
tagged with: collision-detection
tagged with: sprite
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50768080

http://stackoverflow.com/a/50722701
accepted answer of: http://stackoverflow.com/q/50722329
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50722329
type: Answer
has body: Enclose the statement in parentheses. user_by_email = (session.query(User) .filter(Address.email=='one') #.options(joinedload(User.addresses)) .first())
upvote count: 5
score: 5

http://stackoverflow.com/comment/88415801
type: QuestionComment
has text: `header=None`...
score: 3
comment on: http://stackoverflow.com/q/50703192
type: Comment

http://stackoverflow.com/comment/88665146
has text: @MohamedThasinah Contours don't have to work on a border. They will work on the text too and they can use the text layout as a reference to make a box around it.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50830335
type: AnswerComment

http://stackoverflow.com/comment/88501931
has text: I just figured that what your example code does is assigning the value of the "...idp.strategy" property as-is for most of the cases, are there more potential exceptions to being a value of "" or completely different values that you default to "saml" ? What do you want as a result if you have 'saml/simpleSAMLphp' but PROXYING_MECHANISM is not 'ngrok', because that would result in 'saml'
comment on: http://stackoverflow.com/q/50746629
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88453485
type: Comment
comment on: http://stackoverflow.com/a/50722468
score: 0
type: AnswerComment
has text: The problem is for the code under the try I need to be able to try and except another find_element(). If I leave it as is when I get a no such found element exception it does to the first except and executes the code "do another thing" which is not what I want.

http://stackoverflow.com/comment/88529766
type: QuestionComment
comment on: http://stackoverflow.com/q/50705939
has text: The overwhelming answer I have found is that PdfPages does not allow for multiple figures on one page, so you have to use subplots.
score: 0
type: Comment

http://stackoverflow.com/q/50807088
score: 0
has title: Python Formatting SQL WHERE clause
answer count: 1
accepted answer: http://stackoverflow.com/a/50807163
linked to: http://stackoverflow.com/q/902408
tagged with: python
has comment: http://stackoverflow.com/comment/88620007
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50807163
has body: I'm having this function that communicates via pymysql to an SQL database stored to my localhost. I know there are similar posts about formatting an SQL section especially this one but could anyone suggest a solution? Always getting TypeError: can't concat tuple to bytes. I suppose it's sth with the WHERE clause. def likeMovement(pID): print("Give a rating for the movement with #id:%s" %pID) rate=input("Give from 0-5: ") userID=str(1) print(rate,type(rate)) print(pID,type(pID)) print(userID,type(userID)) cursor=con.cursor() sqlquery='''UDPATE likesartmovement SET likesartmovement.rating=%s WHERE likesartmovement.artisticID=? AND likesartmovement.userID=?''' % (rate,), (pID,userID) cursor.execute(sqlquery) TypeError: not all arguments converted during string formatting Thanks in advance!
tagged with: mysql
tagged with: formatting
type: Question
has comment: http://stackoverflow.com/comment/88620048

http://stackoverflow.com/comment/88506102
type: QuestionComment
has text: What is input? What is output? What is expected output?
comment on: http://stackoverflow.com/q/50749268
score: 1
type: Comment

http://stackoverflow.com/q/50809314
has title: Why isn't my python file getting all the submitted data?
score: 1
tagged with: cgi
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88625675
tagged with: python-2.7
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50809374
has body: This is my html code, its a form that records 10 responses and submits them to the python program predictions.py What is you favorite hobby: What is your favorite word: What is your dream job: Mac OS or Windows? Windows Mac OS Heavy rain or sunshine? Heavy rain Sunshine Amazon or Ebay? Amazon Ebay Youtube or Netflix? Youtube Netflix Laptop or Desktop Laptop Desktop Favorite Season Summer Winter Fall Spring Favorite Color Red Orange Yellow Green Blue Indigo Violet Pink White Black The python program is supposed to take all the submitted information assign them to variables. def getData(): formData = cgi.FieldStorage() color = formData.getvalue('color') season = formData.getvalue('season') computer = formData.getvalue('computer') video = formData.getvalue('video') shopping = formData.getvalue('shopping') weather = formData.getvalue('weather') os = formData.getvalue('os') favorite_word = formData.getvalue('favorite_word') hobby = formData.getvalue('hobby') job = formData.getvalue('job') But it is not working, I keep getting an internal server error. Heres the full python script: #!/usr/bin/python import cgi def getData(): formData = cgi.FieldStorage() color = formData.getvalue('color') season = formData.getvalue('season') computer = formData.getvalue('computer') video = formData.getvalue('video') shopping = formData.getvalue('shopping') weather = formData.getvalue('weather') os = formData.getvalue('os') favorite_word = formData.getvalue('favorite_word') hobby = formData.getvalue('hobby') job = formData.getvalue('job') outcomes = {-10: 'Your end is near', -9: 'I forsee a tragedy that will destroy your soul', -8: 'Consider checking for cancer', -7: 'Your oven might explode or something', -6: 'You are goign to get scammed', -5: 'You might break a bone or two', -4: 'You will have a bad case of food poisoning', -3: 'You failed that test you just took', -2: 'Your toilet is goign to clog', -1: 'You will lose 20 dollars', 0: 'Damn your life is boring', 1: 'You will find 20 dol…
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/q/50700007
type: Question
score: 0
has body: I'm currently trying to build a deep learning model for time series prediction. For the trainings data I don't only have the actual time series, but also some meta information for every time step of the series. I'm implementing the model using pytorch. My problem is, that I don't know how to use those meta information to build an embedding layer containing all those information, because it only can be 2d. I know that in keras, it is possible to fit the model when putting multiple time series in a list. But I'm not sure if pytorch has the same option? It should be the same idea as using word and character embeddings all at once for text classification/prediction. Does anyone have an idea? Thank you! :3
favorite count: 0
has title: Time series prediction (GRU) with several meta information
tagged with: pytorch
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88936421
has comment: http://stackoverflow.com/comment/88427500
downvote count: 1

templates
tags question: http://stackoverflow.com/q/50698816
tag name: templates
type: Tag
tags question: http://stackoverflow.com/q/50812937

http://stackoverflow.com/comment/88546817
comment on: http://stackoverflow.com/q/50769693
type: QuestionComment
type: Comment
score: 3
has text: I think what you're really looking for is `range(*data)`

http://stackoverflow.com/comment/88678420
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50837180
has text: What's it with the parentheses in your JSON example? That's not JSON. What do you want to express there?

http://stackoverflow.com/q/50757940
tagged with: python-multithreading
type: UnansweredQuestion
has title: python delay without blocking after condtion met with high precision
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88527693
has comment: http://stackoverflow.com/comment/88526390
type: Question
tagged with: delay
has comment: http://stackoverflow.com/comment/88631669
score: 0
has body: I need to execute a function in python after condition is met, but before executing the function there are a slight second delay without blocking another program in the loop, and the delay must be high precision. Is there any way to do that? i've tried using threading.Thread and threading.Timer but the delay is not that precise. Here is my code: count = 2500 delay = 0.5 # delay before executing function while True: # Another program here ....... if(count &lt;= 2000): if(found == 0): # Run once until count &gt;= 2000 again # Execute pressKey function startThread = threading.Timer(delay, pressKey).start() found = 1 if(count &gt;= 2000): if(found == 1): # Run once until count &lt;= 2000 again # Execute releaseKey function endThread = threading.Timer(delay, releaseKey).start() found = 0 Assume that the variable count is decreasing until 0 and increasing until 2500 sequencially, and the if condition is not just that two i mentioned, there are 6 more if condition similiar to the code above with different count variable.
tagged with: blocking

http://stackoverflow.com/comment/88600323
type: QuestionComment
has text: I have images from class B that are related to class B by the foreignkey. i wanted to get an image with other information from class A like user and title. when i try to run the function in `views.py` `picture = get_object_or_404(A, slug=slug)` I get an error that the `class A ` model has no attribute slug
type: Comment
comment on: http://stackoverflow.com/q/50797009
score: 0

http://stackoverflow.com/a/50722016
type: Answer
has body: https://github.com/Grasin98/recommender_live for basics of recommendation system.Hope you find it relevant. You can visit this. Yes, there are algorithms like grid search which can be helpful for finding best weight matrix. Grid search means you have a set of models (which differ from each other in their parameter values, which lie on a grid). What you do is you then train each of the models and evaluate it using cross-validation. You then select the one that performed best. To give a concrete example, if you're using a support vector machine, you could use different values for gamma and C. So, for example you could have a grid with the following values for (gamma, C): (1, 1), (0.1, 1), (1, 10), (0.1, 10). It's a grid because it's like a product of [1, 0.1] for gamma and [1, 10] for C. Grid-search would basically train a SVM for each of these four pair of (gamma, C) values, then evaluate it using cross-validation, and select the one that did best. For Gradient Descent: The first step of the procedure requires that the order of the training dataset is randomized. This is to mix up the order that updates are made to the coefficients. Because the coefficients are updated after every training instance, the updates will be noisy jumping all over the place, and so will the corresponding cost function. By mixing up the order for the updates to the coefficients, it harnesses this random walk and avoids it getting distracted or stuck. The learning can be much faster with stochastic gradient descent for very large training datasets and often you only need a small number of passes through the dataset to reach a good or good enough set of coefficients, e.g. 1-to-10 passes through the dataset. So according to me, there is know the Perfect method. It basically depends on a number of things. As you might know, this is the same for algorithm application SVM, Decision Tree, Random Forest, all give variation with respect to the situation. As per the second question is concerned, I no…
answers question: http://stackoverflow.com/q/50721518
score: 0

strftime
type: Tag
tags question: http://stackoverflow.com/q/50799656
tag name: strftime

http://stackoverflow.com/comment/88690698
comment on: http://stackoverflow.com/q/50843296
type: Comment
type: QuestionComment
score: 1
has text: What about `df['counts'] = df.groupby(['PatientNumber','year'])["month"].transform('nunique').reset_index(name='counts')`?

http://stackoverflow.com/q/50707139
upvote count: 1
possible better answer: http://stackoverflow.com/a/50707319
type: Question
has comment: http://stackoverflow.com/comment/88427638
has comment: http://stackoverflow.com/comment/88426577
has comment: http://stackoverflow.com/comment/88423895
has comment: http://stackoverflow.com/comment/88424528
linked to: http://stackoverflow.com/q/32040541
answer count: 2
has body: I've uploaded a json from the user and now I'm trying to compare that json to a schema using the jsonschema validator. I'm getting an error, ValidationError: is not of type u'object' Failed validating u'type' in schema This is my code so far: from __future__ import unicode_literals from django.shortcuts import render, redirect import jsonschema import json import os from django.conf import settings #File to store all the parsers def jsonVsSchemaParser(project, file): baseProjectURL = 'src\media\json\schema' projectSchema = project.lower()+'.schema' projectPath = os.path.join(baseProjectURL,projectSchema) filePath = os.path.join(settings.BASE_DIR,'src\media\json', file) actProjectPath = os.path.join(settings.BASE_DIR,projectPath) print filePath, actProjectPath schemaResponse = open(actProjectPath) schema = json.load(schemaResponse) response = open(filePath) jsonFile = json.load(response) jsonschema.validate(jsonFile, schema) I'm trying to do something similar to this question except instead of using a url I'm using my filepath. Also I'm using python 2.7 and Django 1.11 if that is helpful at all. Also I'm pretty sure I don't have a problem with my filepaths because I printed them and it outputted what I was expecting. I also know that my schema and json can be read by jsonschema since I used it on the command line as well. EDIT: that validation error seemed to be a fluke. the actual validation error I'm consistently getting is "-1 is not of type u'string'". The annoying thing is that's supposed to be like that. It is wrong that sessionid isn't a string but I want that to be handled by the jsonschema but I don't want my validation errors to be given in this format: . What I want to do is collect all validation errors in an array and then post it to the user in the next page.
has comment: http://stackoverflow.com/comment/88423810
downvote count: 0
has title: Trying to implement jsonschema with just filepaths
has comment: http://stackoverflow.com/comment/88424701
has answer: http://stackoverflow.com/a/50707319
favorite count: 0
has comment: http://stackoverflow.com/comment/88424056
has comment: http://stackoverflow.com/comment/88425909
has comment: http://stackoverflow.com/comment/88425039
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88424899
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88426899
has answer: http://stackoverflow.com/a/50708476
accepted answer: http://stackoverflow.com/a/50708476
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: file
has comment: http://stackoverflow.com/comment/88424276

http://stackoverflow.com/comment/88541525
has text: Ok. Then I would add logging on the server and client to trace where is this event getting lost. I honestly don't see anything wrong at first sight.
comment on: http://stackoverflow.com/q/50751685
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50715262
accepted answer: http://stackoverflow.com/a/50715584
tagged with: jupyter-notebook
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
tagged with: graphviz
downvote count: 0
answer count: 1
has body: Hello I'm now learning machine learning for class. I want to visualize the tree with graphviz by jupyter notebook. These are the errors that I have below: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) c:\users\asuspc\appdata\local\programs\python\python36-32\lib\site-packages\sklearn\utils\__init__.py in __getattr__(self, key) 60 try: ---&gt; 61 return self[key] 62 except KeyError: KeyError: 'dot' During handling of the above exception, another exception occurred: AttributeError Traceback (most recent call last) &lt;ipython-input-17-341e4ee6fe08&gt; in &lt;module&gt;() 4 from sklearn.tree import export_graphviz 5 from sklearn.datasets import load_iris ----&gt; 6 dot_data = tree.export_graphviz(clf, out_file=iris.dot) 7 graph = graphviz.Source(dot_data) 8 graph.render("iris") c:\users\asuspc\appdata\local\programs\python\python36-32\lib\site-packages\sklearn\utils\__init__.py in __getattr__(self, key) 61 return self[key] 62 except KeyError: ---&gt; 63 raise AttributeError(key) 64 65 def __setstate__(self, state): AttributeError: dot And these are the code now I'm working on: import graphviz import pydotplus from sklearn import tree from sklearn.tree import export_graphviz from sklearn.datasets import load_iris dot_data = tree.export_graphviz(clf, out_file=iris.dot) graph = graphviz.Source(dot_data) graph.render("iris") Already installed the prerequisites for jupyter notebook. I don't know why and how to solve the keyError or Attribute Errors. How can I solve this?
favorite count: 0
has title: How to draw a Graphviz graph in Jupyter Notebook?
tagged with: python
has answer: http://stackoverflow.com/a/50715584

http://stackoverflow.com/q/50835979
has body: I'd like to use multiple Hovertools in one plot together with Hovertool's names attribute to selectivly apply each tool. Take for instance hover1 = HoverTool(tooltips=[("group", "1")], names = ['line1']) hover2 = HoverTool(tooltips=[("group", "2")], names = ['lines2']) and the two data sources: source1 = ColumnDataSource(data=dict( xs=[[1, 3, 2], [3, 4, 6, 6]], ys=[[2, 1, 4], [4, 7, 8, 5]], )) source2 = ColumnDataSource(data=dict( xs=[[1, 3, 2], [6, 7, 9, 8]], ys=[[-1, 0, 1], [1, 1, 2, 1]] )) I'd though the following (using the bokeh.models API) should do what I want p = figure(plot_width=400, plot_height=400) l1 = MultiLine(xs='xs', ys='ys', name='lines1') l2 = MultiLine(xs='xs', ys='ys', name='lines2') p.add_tools(hover) p.add_tools(hover2) p.add_glyph(source1, l1) p.add_glyph(source2, l2) show(p) Alas the Hovertools in the resulting plot do not work (i.e. no tooltips are shown). Using the bokeh.plotting API as follows and everything works as expected: p = figure(plot_width=400, plot_height=400, tools=[hover, hover2]) p.multi_line(xs='xs', ys='ys', source=source1, name='lines1') p.multi_line(xs='xs', ys='ys', source=source2, name='lines2') show(p) Question: How does one replicate the result of the bokeh.plotting API with the bokeh.models API?
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50846581
has comment: http://stackoverflow.com/comment/88697540
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88677013
tagged with: python
tagged with: hover
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88676399
upvote count: 1
has answer: http://stackoverflow.com/a/50846581
tagged with: plot
type: Question
score: 1
tagged with: bokeh
linked to: http://stackoverflow.com/q/27545842
has comment: http://stackoverflow.com/comment/88676811
has title: Using multiple bokeh HoverTool instances together with the models API

http://stackoverflow.com/q/50729806
has answer: http://stackoverflow.com/a/50752420
score: 0
tagged with: python
tagged with: jupyter
tagged with: jupyter-notebook
type: AnsweredQuestion
has title: Showing Bokeh plots in Binder
possible better answer: http://stackoverflow.com/a/50752420
type: Question
tagged with: jupyter-lab
has body: I have a simple Jupyter Notebook that produces a bokeh plot from a pandas dataframe with some associated bokeh widgets. When I run it in both Jupyter Notebook and Lab, it outputs the plot and widgets and is interactive as designed. However, when I put those same files in a GitHub repo (https://github.com/deppen8/leiap_dashboard) and ran Binder, the output plot and widgets are not displayed. My requirements.txt is simple: pandas bokeh My postBuild is also simple: jupyter labextension install jupyterlab_bokeh jupyter trust survey_dashboard.ipynb Am I missing something in these files to make bokeh (with widgets) work with Binder? Or is there something fundamentally incompatible about the bokeh widgets?
has answer: http://stackoverflow.com/a/52825904
accepted answer: http://stackoverflow.com/a/52825904
tagged with: bokeh
answer count: 2

http://stackoverflow.com/comment/88547995
comment on: http://stackoverflow.com/a/50770150
score: 1
has text: @jerbear this is tough question `pd.wide_to_long(df,['var1','var2'],i='ID',j='drop',suffix='\w+').unstack(-2).T ` but you can do this
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88731345
comment on: http://stackoverflow.com/q/50850258
score: 0
type: Comment
type: QuestionComment
has text: @Alexandre Passos Thanks.. I have added the estimator for you..

http://stackoverflow.com/a/50764667
has body: what you are doing here don't make any sense in that point of execution all fields are empty False or an object. This search is done while you are executing the class statement so if you acces an atribute directly like that you get a False or an object of datetime class witch is not like standar datetime labrary. You can confirm what i'm saying by printing both field value before search. What you want exactly in that point we coulf help to rewrite your code. Edits* Dates in Odoo are a text. You are using Date field to look for datetimes I think Odoo will concatenate ' 00:00:00' to your value. If you choose the same date will always have record that are dated exactly at hout 00:00:00. You can change your value [.... '=&gt;', self.from_date + ' 00:00:00'), ...., self.to_date + ' 23:59:59')] And keep in mind that odoo deal with timezone let say that your region is GMT + 1, IF you choose 2018-01-01 00:00:00 in database the value will be converted to 2017-12-31 23:00:00 be carful with this facts Odoo is an international systems and datetimes are managed by Odoo on this base.
type: Answer
has comment: http://stackoverflow.com/comment/88630251
has comment: http://stackoverflow.com/comment/88629637
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88630374
accepted answer of: http://stackoverflow.com/q/50716575
has comment: http://stackoverflow.com/comment/88634236
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50716575

http://stackoverflow.com/a/50729651
accepted answer of: http://stackoverflow.com/q/50728621
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50728621
downvote count: 0
score: 4
has body: In your first case, parameter substitution does not work for table/column names. This is common to the vast majority of (if not all) database platforms. In your second case, SQL Server does not appear to support parameter substitution for DDL statements. The SQL Server ODBC driver converts the pyodbc parameter placeholders (?) to T-SQL parameter placeholders (@P1, @P2, ...) so the statement passed to SQL Server is CREATE TABLE table_2 (id int IDENTITY(1,1) PRIMARY KEY, obj varchar(@P1) NOT NULL specifically exec sp_prepexec @p1 output,N'@P1 int',N'CREATE TABLE table_2 (id int IDENTITY(1,1) PRIMARY KEY, obj varchar(@P1) NOT NULL',123 and when SQL Server tries to prepare that statement it expects a literal value, not a parameter placeholder. So, in both cases you will need to use dynamic SQL (string formatting) to insert the appropriate values.
type: AcceptedAnswer

http://stackoverflow.com/a/51018496
accepted answer of: http://stackoverflow.com/q/50714877
upvote count: 3
answers question: http://stackoverflow.com/q/50714877
score: 3
has body: Interpreter starts to interpret file line by line from the beginning. If it encounters function definition, it adds it into the globals dict. If it encounters function call, it searches it in globals dict and executes or fail. # foo.py def foo(): print "hello" foo() def test() print "test" print "global_string" if __name__ == "__main__": print "executed" else: print "imported" Output hello global_string executed Interpreter starts to interpret foo.py line by line from the beginning like first the function definition it adds to globals dict and then it encounters the call to the function foo() and execute it so it prints hello. After that, it adds test() to global dict but there's no function call to this function so it will not execute the function. After that print statement will execute will print global_string. After that, if condition will execute and in this case, it matched and will print executed.
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/50780402
tagged with: python
has title: Matrix-Vector Multiplication Python3
has comment: http://stackoverflow.com/comment/88567588
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88567639
has comment: http://stackoverflow.com/comment/88567568
has comment: http://stackoverflow.com/comment/88567572
downvote count: 2
has comment: http://stackoverflow.com/comment/88567549
type: Question
accepted answer: http://stackoverflow.com/a/50780575
has comment: http://stackoverflow.com/comment/88567979
score: -2
has body: This is the code I have written so far, but I'm not getting my desired output. I want to know what's missing in the code. Any help would be greatly appreciated. def matVec(matrix,vector): for i in range(len(matrix)): result = [] total = 0 for j in range(len(vector)): total += matrix[i][j] * vector[j] result.append(total) return result matrix_0 = [[1, 2, 3],[2, 3, 4]] vector_0 = [2, 2] print(matVec(matrix_0,vector_0)) link to code
has comment: http://stackoverflow.com/comment/88567594
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88567622
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50780575

http://stackoverflow.com/comment/88633779
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50814354
has text: Hi, changed to (`,`) but still not working. Thanks for help

xgboost
tags question: http://stackoverflow.com/q/50719204
tags question: http://stackoverflow.com/q/50831605
tags question: http://stackoverflow.com/q/50723605
tags question: http://stackoverflow.com/q/50731984
tag name: xgboost
type: Tag
tags question: http://stackoverflow.com/q/50711382
tags question: http://stackoverflow.com/q/50824326

search
tags question: http://stackoverflow.com/q/50797289
tags question: http://stackoverflow.com/q/50769864
tags question: http://stackoverflow.com/q/50761951
type: Tag
tags question: http://stackoverflow.com/q/50791087
tags question: http://stackoverflow.com/q/50794333
tags question: http://stackoverflow.com/q/50796746
tag name: search

http://stackoverflow.com/a/50851890
has body: Use Python's CSV library to read in your text file. This will give you a list of values for each row split based on where the commas are. Each switch entry appears to only contain two rows of information so these could be read in based on the number of elements found in each row as follows: import csv with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output: csv_input = csv.reader(f_input) csv_output = csv.writer(f_output) csv_output.writerow(['NAME', 'DESCR', 'PID', 'VID', 'SN']) for row in csv_input: if len(row) == 2: row1 = [v.split(':')[1].replace('"', '').strip() for v in row] elif len(row) == 3: row2 = [v.split(':')[1].replace('"', '').strip() for v in row] csv_output.writerow(row1 + row2) Giving you output.csv containing: NAME,DESCR,PID,VID,SN Chassis,Nexus5020 Chassis,N5K-C5020P-BF,V04,SSI13390FZT Chassis,Nexus5020 Chassis,N5K-C5020P-BF,V04,SSI13390FZT Chassis,Nexus5020 Chassis,N5K-C5020P-BF,V04,SSI13390FZT My output assumes that your file contains multiple similar entries. If chassis information is not needed: import csv with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output: csv_input = csv.reader(f_input) csv_output = csv.writer(f_output) csv_output.writerow(['PID', 'VID', 'SN']) for row in csv_input: if len(row) == 3: csv_output.writerow(v.split(':')[1].replace('"', '').strip() for v in row)
answers question: http://stackoverflow.com/q/50834357
has comment: http://stackoverflow.com/comment/88707215
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88707303
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50834357

amazon-elastic-beanstalk
tags question: http://stackoverflow.com/q/50757023
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/50839770
tags question: http://stackoverflow.com/q/50782433

loops
tags question: http://stackoverflow.com/q/50781119
tags question: http://stackoverflow.com/q/50724788
tags question: http://stackoverflow.com/q/50788871
tags question: http://stackoverflow.com/q/50708148
tags question: http://stackoverflow.com/q/50711558
tags question: http://stackoverflow.com/q/50801480
tags question: http://stackoverflow.com/q/50764929
tags question: http://stackoverflow.com/q/50722037
tags question: http://stackoverflow.com/q/50814689
tags question: http://stackoverflow.com/q/50750987
tags question: http://stackoverflow.com/q/50807582
tags question: http://stackoverflow.com/q/50779879
tags question: http://stackoverflow.com/q/50752304
type: Tag
tags question: http://stackoverflow.com/q/50779667
tags question: http://stackoverflow.com/q/50820945
tags question: http://stackoverflow.com/q/50699641
tags question: http://stackoverflow.com/q/50800042
tags question: http://stackoverflow.com/q/50725340
tags question: http://stackoverflow.com/q/50783616
tags question: http://stackoverflow.com/q/50839629
tags question: http://stackoverflow.com/q/50708172
tags question: http://stackoverflow.com/q/50779467
tag name: loops
tags question: http://stackoverflow.com/q/50784162
tags question: http://stackoverflow.com/q/50729869
tags question: http://stackoverflow.com/q/50764002
tags question: http://stackoverflow.com/q/50730172
tags question: http://stackoverflow.com/q/50715950
tags question: http://stackoverflow.com/q/50802957
tags question: http://stackoverflow.com/q/50801789
tags question: http://stackoverflow.com/q/50710290
tags question: http://stackoverflow.com/q/50745843
tags question: http://stackoverflow.com/q/50699111
tags question: http://stackoverflow.com/q/50748172
tags question: http://stackoverflow.com/q/50734412
tags question: http://stackoverflow.com/q/50769728
tags question: http://stackoverflow.com/q/50780029
tags question: http://stackoverflow.com/q/50819180
tags question: http://stackoverflow.com/q/50769558
tags question: http://stackoverflow.com/q/50719393

http://stackoverflow.com/comment/88424083
type: AnswerComment
type: Comment
has text: could not understand what you said, If you want to register `CustomUser` model as your user model you should set it is settings 'AUTH_USER_MODEL' `AUTH_USER_MODEL = 'app_name.model_name'`
comment on: http://stackoverflow.com/a/50707412
score: 0

http://stackoverflow.com/q/50792048
has comment: http://stackoverflow.com/comment/88590030
has answer: http://stackoverflow.com/a/50792096
has body: INSTEAD OF COMPLETELY DELETING THIS, I'M MAKING THIS EDIT SO PEOPLE WHO FIND THIS ARE ABLE TO FIND THE BEST SOLUTION. GO TO How to run a shell script in OS X by double-clicking? While using Python, I would like to be able to run a script without having to open or type into Terminal every time. For example, instead of going into Terminal and typing: python &lt;script-name&gt;.py or even ./script-name.py I would like to simply be able to click on an application or open a file that will automatically run the Terminal commands without actually having to open Terminal myself (or at least have Terminal open in the background) so that others (like my mother) can use this easily. Is anyone able to point me in a direction or help me out in figuring out if this is possible? Please do not hesitate to ask me questions. I appreciate any help at all. Thank you in advance!
duplicate of: http://stackoverflow.com/q/5125907
has comment: http://stackoverflow.com/comment/88590331
has comment: http://stackoverflow.com/comment/88590233
type: Question
linked to: http://stackoverflow.com/q/5125907
has comment: http://stackoverflow.com/comment/88589996
has comment: http://stackoverflow.com/comment/88590373
has comment: http://stackoverflow.com/comment/88590327
linked to: http://stackoverflow.com/q/41570359
has answer: http://stackoverflow.com/a/50792415
score: 0
answer count: 2
tagged with: macos
tagged with: terminal
type: UnansweredQuestion
has title: Running a Python script without opening Terminal
tagged with: python
has comment: http://stackoverflow.com/comment/88649455

http://stackoverflow.com/a/50712730
has body: try this, mask=df.duplicated(subset=['Product']) df.loc[mask,['Product','Price','Weight']]='' Output: Product Price Weight Range Count 0 A 40 20 1-3 20 1 4-7 23 2 B 20 73 1-3 54 3 4-7 43 4 8-15 34 5 &gt;=16 12 6 C 10 100 4-7 22 . pd.pivot_table(df,index=['Product','Price','Weight'],columns='Range',values='Count').reset_index() Output: Range Product Price Weight 1-3 4-7 8-15 &gt;=16 0 A 40 20 20.0 23.0 NaN NaN 1 B 20 73 54.0 43.0 34.0 12.0 2 C 10 100 NaN 22.0 NaN NaN
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50712636

http://stackoverflow.com/comment/88643889
score: 1
comment on: http://stackoverflow.com/q/50819267
has text: Oh and something to note is, that `zip` will turn the "inner" list into a tuple. eg: `[(Lon_0, Lat_0), (...), ... ]`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88689480
comment on: http://stackoverflow.com/q/50842554
score: 1
has text: Possible duplicate of [Renaming a virtualenv folder without breaking it](https://stackoverflow.com/questions/6628476/renaming-a-virtualenv-folder-without-breaking-it)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50752080
has body: I'm trying to pass values to a fixture because I basically have the same code for many tests but only some values changing, for what I understand pytest fixtures don't accept that but not really sure how to solve this , for example I have this: import pytest @pytest.fixture def option_a(): a = 1 b = 2 return print(a + b) @pytest.fixture def option_b(): a = 5 b = 3 return print(a + b) def test_foo(option_b): pass instead of choosing between fixture option a or option b , both do adding and the only thing that changes is the values , can I have one fixture where I can set which values I want to run on test_foo? thanks in advance.
type: AnsweredQuestion
score: 3
tagged with: pytest
downvote count: 0
linked to: http://stackoverflow.com/q/35777854
type: Question
linked to: http://stackoverflow.com/q/42228895
upvote count: 3
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88512152
has title: pytest fixture passing values
has answer: http://stackoverflow.com/a/50753221
accepted answer: http://stackoverflow.com/a/50753221
tagged with: python

http://stackoverflow.com/a/50785815
downvote count: 0
has body: Maybe you could use s="(1, 2, 3)" tuple(int(x) for x in s.strip('()').split(',')) Remove the '(' and ')' and then use tuple(). Thanks to @bla for pointing out that s.strip('()') can be used instead of s.replace('(').replace(')').
score: 3
has comment: http://stackoverflow.com/comment/88578730
has comment: http://stackoverflow.com/comment/88578094
has comment: http://stackoverflow.com/comment/88578244
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50785752

pip
tags question: http://stackoverflow.com/q/50749517
tags question: http://stackoverflow.com/q/50831127
tags question: http://stackoverflow.com/q/50816320
tags question: http://stackoverflow.com/q/50713726
tags question: http://stackoverflow.com/q/50845926
tags question: http://stackoverflow.com/q/50789823
tags question: http://stackoverflow.com/q/50709217
tags question: http://stackoverflow.com/q/50792179
tags question: http://stackoverflow.com/q/50704882
tags question: http://stackoverflow.com/q/50843769
tags question: http://stackoverflow.com/q/50829497
tags question: http://stackoverflow.com/q/50707658
tags question: http://stackoverflow.com/q/50713316
tags question: http://stackoverflow.com/q/50729803
tags question: http://stackoverflow.com/q/50776299
tags question: http://stackoverflow.com/q/50809096
tags question: http://stackoverflow.com/q/50782863
tags question: http://stackoverflow.com/q/50705231
tags question: http://stackoverflow.com/q/50725394
tags question: http://stackoverflow.com/q/50836535
tag name: pip
tags question: http://stackoverflow.com/q/50742538
tags question: http://stackoverflow.com/q/50777849
tags question: http://stackoverflow.com/q/50701322
tags question: http://stackoverflow.com/q/50698975
tags question: http://stackoverflow.com/q/50744001
tags question: http://stackoverflow.com/q/50803679
tags question: http://stackoverflow.com/q/50743951
tags question: http://stackoverflow.com/q/50821312
tags question: http://stackoverflow.com/q/50742839
tags question: http://stackoverflow.com/q/50743502
tags question: http://stackoverflow.com/q/50714458
tags question: http://stackoverflow.com/q/50791252
tags question: http://stackoverflow.com/q/50729548
tags question: http://stackoverflow.com/q/50840725
tags question: http://stackoverflow.com/q/50721944
tags question: http://stackoverflow.com/q/50847721
tags question: http://stackoverflow.com/q/50800665
tags question: http://stackoverflow.com/q/50843354
tags question: http://stackoverflow.com/q/50804087
type: Tag
tags question: http://stackoverflow.com/q/50755705
tags question: http://stackoverflow.com/q/50719066
tags question: http://stackoverflow.com/q/50845946
tags question: http://stackoverflow.com/q/50769629
tags question: http://stackoverflow.com/q/50790321
tags question: http://stackoverflow.com/q/50836237
tags question: http://stackoverflow.com/q/50812817
tags question: http://stackoverflow.com/q/50730946
tags question: http://stackoverflow.com/q/50772342
tags question: http://stackoverflow.com/q/50801820
tags question: http://stackoverflow.com/q/50737765
tags question: http://stackoverflow.com/q/50799143
tags question: http://stackoverflow.com/q/50774054
tags question: http://stackoverflow.com/q/50794064

http://stackoverflow.com/comment/88559863
type: Comment
comment on: http://stackoverflow.com/a/50773317
has text: I think you have not understood question or you have not paid attention. You are modifying input to function which just prints given strings as input. As I mentioned in question output to console can come from logging also
score: 0
type: AnswerComment

fortran
tags question: http://stackoverflow.com/q/50761252
tags question: http://stackoverflow.com/q/50734776
tags question: http://stackoverflow.com/q/50750872
type: Tag
tag name: fortran

http://stackoverflow.com/comment/102595309
has text: The result is incorrect, each column is exploded separately rather than in tandem with each other, producing more rows in the result than desired.
comment on: http://stackoverflow.com/a/57109769
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50763885
has comment: http://stackoverflow.com/comment/88536870
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/88536800
answer count: 0
has comment: http://stackoverflow.com/comment/88540721
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88537458
upvote count: 1
has comment: http://stackoverflow.com/comment/88536353
has comment: http://stackoverflow.com/comment/88537194
has comment: http://stackoverflow.com/comment/88537314
has title: socket.accept accepts 2 connections
has comment: http://stackoverflow.com/comment/88536724
type: Question
has comment: http://stackoverflow.com/comment/88540427
has comment: http://stackoverflow.com/comment/88537085
has comment: http://stackoverflow.com/comment/88540386
has body: I have a server\client communication organized via socket library in python. There are a lot of materials online how to use it and it seems to be pretty straightforward ref 1. There is always a while True loop that keeps accepting connections and my understanding is that it will accept only one at a time, service it and go to the next one in the queue. The depth of the queue is defined by socket.listen(N) where N is the depth. I create the socket server. self.sock = socket(AF_INET, SOCK_STREAM) self.sock.bind(('', port)) self.sock.listen(10) self.socket_port = port I have a while True loop that waits for the socket connection to come def run_socket(self): ''' creates a separete thread for server_thread function ''' start_new_thread(self.server_thread,()) def server_thread(self): self.is_running = True self.update_CAS() while self.is_running: self.client, self.addr = self.sock.accept() info( 'Client has connected: %r %r' % (self.client, self.addr )) ##Here I have code to service the incoming connection from the ###client. The client closes connection when it receives the ###response. THis section is not shown for simplicity. So this works well. However, I have gotten cases when 2 clients have connected within several milliseconds apart, see below. The second client was serviced correctly but the first one wasn't because the socket was overwritten by the second one. It took input from the second client and I need to have a server that can queue clients but will service only one client at a time. 2018-06-08 13:17:37,838 INFO: Client has connected: &lt;socket._socketobject object at 0x084B0E68&gt; ('128.231.5.169', 60915) 2018-06-08 13:17:37,838 INFO: input from the client: [4, [1000, 4000]] with client, addr = (&lt;socket._socketobject object at 0x084B0E68&gt;,('128.231.5.169', 60915)) 2018-06-08 13:17:37,854 INFO: checking buffer status True, nan 2018-06-08 13:17:37,854 DEBUG: Reply has been generated and sent back 2018-06-08 13:17:39,104 INFO: Client has connected: &…
downvote count: 0
has comment: http://stackoverflow.com/comment/88537134
favorite count: 0

http://stackoverflow.com/q/50773435
has answer: http://stackoverflow.com/a/50774058
tagged with: wxwidgets
has body: i am trying to write a simple code for timeout a session. my idea is that if user dont interact with the application for 5min, then a function will fireup and kill the application. But if user is active and interact with the application the kill function won't be able to run. Anyone help my simple wx here import wx class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Timeout", size=(500, 500)) panel = wx.Panel(self, wx.ID_ANY) self.toggleBtn = wx.Button(panel, wx.ID_ANY, "Enter") self.toggleBtn.Bind(wx.EVT_BUTTON, self.onToggle) def onToggle(self, event): print("you have a action") if __name__ == "__main__": app = wx.App(False) frame = MyForm().Show() app.MainLoop()
type: Question
has title: Python wx session timeoute
score: 0
tagged with: python
answer count: 1
tagged with: timeout
tagged with: wxpython
type: UnansweredQuestion

http://stackoverflow.com/a/50874487
score: 0
type: Answer
has body: This seems to work: # -*- coding: utf-8 -*- import sys # Don't use codecs in Python 3. f_in = open(r'af_massaged.txt', 'rU', encoding='utf8') raw = f_in.read() f_out = open(r'af_massaged_ascii.txt', 'w', encoding='cp1252', errors='replace') retval = [] for char in raw: codepoint = ord(char) if codepoint &lt; 0x80: # Basic ASCII. retval.append(str(char)) continue elif codepoint &gt; 0xeffff: continue # Characters in Private Use Area and above are ignored. elif codepoint &gt;= 128 and codepoint &lt;= 159: continue # Ignore control characters in Latin-1. # Don't use unichr in Python 3, chr uses unicode. Get character codes from here: https://en.wikipedia.org/wiki/List_of_Unicode_characters#Latin-1_Supplement # This was written on Windows 7 32 bit # For 160 to 255 Latin-1 matches unicode. elif codepoint &gt;= 160 and codepoint &lt;= 255: retval.append(str(char)) continue # – elif codepoint == 8211: retval.append(chr(45)) continue # ’ elif codepoint == 8217: retval.append(chr(180)) # 39 continue # “ elif codepoint == 8220: retval.append(chr(34)) continue # ” elif codepoint == 8221: retval.append(chr(34)) continue # € elif codepoint == 8364: retval.append('Euro') continue # Find missing mappings. else: print(char) print(codepoint) # Uncomment for debugging. #for i in range(128, 256): # retval.append(str(i) + ': ' + chr(i) + chr(13)) #print(''.join(retval)) f_out.write(''.join(retval))
accepted answer of: http://stackoverflow.com/q/50853004
answers question: http://stackoverflow.com/q/50853004
type: AcceptedAnswer

http://stackoverflow.com/comment/88700027
comment on: http://stackoverflow.com/q/50848070
score: 0
type: Comment
type: QuestionComment
has text: It sounds like you may have two versions of Python installed on your computer, a "System" python and a local python. What operating system are you using? What command did you use to install discord? What command are you using to execute your python script?

http://stackoverflow.com/q/50740071
score: 0
tagged with: hmmlearn
answer count: 1
has title: Gaussian hidden markov model
tagged with: python
has answer: http://stackoverflow.com/a/50776771
type: UnansweredQuestion
has body: I am following a tutorial from this link http://www.blackarbs.com/blog/introduction-hidden-markov-models-python-networkx-sklearn/2/9/2017 in order to implement hidden markov model in my example. I have 2 hidden states and 2 observed states . As I understand from the code in the tutorial first step in HMM is to estimate parameters of the model using maximum likelihood estimation model and then from the results of the parameters we can predict hidden states. So Vitebri algorithm is used in order to train the model to find the optimal parameters and then predict the observed states. Is it the case? I can share my code if it is more explicable.
type: Question

http://stackoverflow.com/comment/88534472
has text: I mean, what does your desired *dictionary* output look like?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50761806
score: 0

http://stackoverflow.com/comment/88662752
type: Comment
type: QuestionComment
has text: Show what you've attempted.
comment on: http://stackoverflow.com/q/50829219
score: 1

http://stackoverflow.com/comment/88674400
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50835156
has text: The vector doesn't *have to* store begin and end, it could very well store begin and size.

http://stackoverflow.com/a/50837518
has comment: http://stackoverflow.com/comment/88702966
has comment: http://stackoverflow.com/comment/88714793
has body: My guess is that the problem arises with df = df.merge occuring in the loop Never call DataFrame.append or pd.concat inside a for-loop. It leads to quadratic copying. Source: Why does concatenation of DataFrames get exponentially slower? Try adding all the dataframes to a list df_list and then concatenating them once at the end: import pandas as pd df_list = [] df_list.append(pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6]))) df_list.append(pd.DataFrame(dict(c=[1, 2, 3], d=[4, 5, 6]))) pd.concat(df, axis=1) Out[]: a b c d 0 1 4 1 4 1 2 5 2 5 2 3 6 3 6
type: Answer
has comment: http://stackoverflow.com/comment/88679754
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88680082
has comment: http://stackoverflow.com/comment/88705108
has comment: http://stackoverflow.com/comment/88679423
upvote count: 1
answers question: http://stackoverflow.com/q/50836908

http://stackoverflow.com/a/50756051
has comment: http://stackoverflow.com/comment/88531894
type: Answer
score: 8
has body: Clicking on a KeyboardButton will always result in sending a message containing the very same caption it holds. That's just how KeyboardButton in telegram works. So you would have to label your button "/rules". As an alternative you can use InlineKeyboardButton instead. You can chose any label text you wish and provide additional callback_data. Clicking inlineKeyboardButton will not print any message but instead a callback query will be sent to your bot's script. This query can then be answered any way you wish.
downvote count: 0
answers question: http://stackoverflow.com/q/50755566
upvote count: 8
has comment: http://stackoverflow.com/comment/122920654

http://stackoverflow.com/q/50826373
upvote count: 0
tagged with: mergesort
tagged with: sorting
favorite count: 0
type: Question
has body: I'm trying to define a function that takes an array, consisted of points with x and y coordinates, as input. I need 2 outputs: one array that has the points sorted by their x coordinates and another array that has the points sorted by their y coordinate. I'm doing it in python. Thanks.
has comment: http://stackoverflow.com/comment/88657541
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50826410
tagged with: python-3.x
downvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/88657515
has answer: http://stackoverflow.com/a/50826547
tagged with: algorithm
type: UnansweredQuestion
has title: Closest Pair Algorithm in Python: difficulty sorting by x and y coordinates

http://stackoverflow.com/q/50820962
upvote count: 1
answer count: 1
tagged with: flatten
has comment: http://stackoverflow.com/comment/88647254
favorite count: 0
linked to: http://stackoverflow.com/q/2158395
has answer: http://stackoverflow.com/a/50821063
accepted answer: http://stackoverflow.com/a/50821063
has comment: http://stackoverflow.com/comment/88647299
tagged with: python
linked to: http://stackoverflow.com/q/952914
type: AnsweredQuestion
tagged with: list
downvote count: 0
has body: I was working on an algorithm that 'flattens' a list, essentially removing any sublists within a list. For example, [2, 3, [3, 4]] should become [2, 3, 3, 4]. I wrote the following to do this: def flatten(l): total = [] for i in l: if i == int: total.append(i) elif i == list: for j in i: total.append(j): return total This algorithm yields an error, however. If someone could help that would be great. Also, if someone could show a recursive path to solve this problem so that lists of arbitrary 'depth' can be flattened (my current algorithm can only flatten a 2D array)
has comment: http://stackoverflow.com/comment/88647305
score: 1
has comment: http://stackoverflow.com/comment/88647199
has comment: http://stackoverflow.com/comment/88647174
has comment: http://stackoverflow.com/comment/88647446
type: Question
has comment: http://stackoverflow.com/comment/88647478
has comment: http://stackoverflow.com/comment/88647211
has title: How to flatten a 2 deep list, return a list without any sublists within
has comment: http://stackoverflow.com/comment/88647667

http://stackoverflow.com/comment/88435277
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50701137
type: Comment
has text: Discussion on meta about your reopening: https://meta.stackoverflow.com/q/369085/4909087

http://stackoverflow.com/q/50817880
has comment: http://stackoverflow.com/comment/88643398
type: Question
has answer: http://stackoverflow.com/a/50819721
has comment: http://stackoverflow.com/comment/88643820
has comment: http://stackoverflow.com/comment/88641448
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/html
has title: Python selenium won't wait for a list of divs to load
has comment: http://stackoverflow.com/comment/88642444
has comment: http://stackoverflow.com/comment/88641246
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88643962
tagged with: python
has comment: http://stackoverflow.com/comment/88642521
has body: I'm trying to use selenium to parse the following html page: Press me When I press the button on the page the div is filled with a series of "loading" divs: Press me Once the 's have loaded, the html looks like this: Press me Notice the class has changed. Basically I want to use a method in Python's selenium module to wait for the 's to load. My first thought was to wait for the classes to change from glyphicon.glyphicon-cog.spinner.ng-scope::before to glyphicon-chevron-right which signals that the divs have loaded. I use the following line of python code to do this: import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options 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 driver.wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, "glyphicon-chevron-right"))) Unfortunately, this does not seem to work, as the program terminates before the divs have loaded completely. Does anyone know of a way to leverage Python's selenium to wait for an arbitrary number of elements to load?
has comment: http://stackoverflow.com/comment/88641715
has answer: http://stackoverflow.com/a/50818391
has comment: http://stackoverflow.com/comment/88641591
has comment: http://stackoverflow.com/comment/88641668
has comment: http://stackoverflow.com/comment/88644356
tagged with: selenium

http://stackoverflow.com/comment/88615287
comment on: http://stackoverflow.com/q/50803705
has text: That answers the first of the 3 questions I asked.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50747023
answers question: http://stackoverflow.com/q/50746945
score: 1
downvote count: 0
has body: This is not a rounding issue, it is a default numeric type issue. Python 2.7 looks at the numbers and sees integers. Since all numbers involved are integers, 5/2 ==> 2 instead of 2.5, so ceil() is 2. Note that the / operator WILL do floating point division too, provided at least one value is floating point. So if x = 5.0 instead of 5 or if y = 2.0 instead of 2 then you will get 2.5 ==> ceil() = 3.
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88430187
comment on: http://stackoverflow.com/a/50710313
has text: Better to use [averageCharWidth](https://doc.qt.io/qt-5/qfontmetrics.html#averageCharWidth).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50826068
tagged with: python
accepted answer: http://stackoverflow.com/a/50827825
has body: I am trying to evaluate if a circle is contained within another shape (in this simple example I will use a square). import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib import path import matplotlib.patches as patches c = Circle((0, 0), radius=3) path_c = c.get_path() p = path.Path([(-2, -2), (-2, 2), (2, 2), (2, -2), (-2, -2)]) fig = plt.figure() ax = fig.add_subplot(111) patch = patches.PathPatch(p, facecolor='orange', lw=2) patch2 = patches.PathPatch(path_c, facecolor='blue', lw=2) ax.add_patch(patch) ax.add_patch(patch2) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) plt.show() print(p.contains_path(path_c)) The problem I'm having is that no matter what I input into Circle, it always make a circle at the origin with radius 1. This is only the case when I use get_path but that's the only way I can use contains.path on the circle object. Any thoughts on how I can check if a circle is contained inside another shape?
type: AnsweredQuestion
type: Question
tagged with: matplotlib
has title: Path containing path in matplotlib
has answer: http://stackoverflow.com/a/50827825
score: 0
answer count: 1
tagged with: path

http://stackoverflow.com/a/50787787
has comment: http://stackoverflow.com/comment/88613776
has comment: http://stackoverflow.com/comment/88588570
has comment: http://stackoverflow.com/comment/88636177
upvote count: 1
has body: I think you need a join and fillna print(df2.join(df1).fillna('')) 10.17 6.58 5.23 10.74 5.71 5.41 9.99 5.75 5.13 11.44 6.1 5.87 11.21 6.35 5.72 10.30 5.86 5.12
answers question: http://stackoverflow.com/q/50787196
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88613896

http://stackoverflow.com/comment/88658603
type: AnswerComment
comment on: http://stackoverflow.com/a/50826972
type: Comment
has text: I must have 50 reputation to comment on a question.
score: 0

http://stackoverflow.com/comment/88689333
comment on: http://stackoverflow.com/q/50842783
has text: A bag isn't a data-frame. Use the data-frame...
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88669475
has text: @MateenUlhaq I think this will die on the empty string at the end of the split.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50832667
score: 1

http://stackoverflow.com/a/55123333
answers question: http://stackoverflow.com/q/50714931
score: 1
upvote count: 1
downvote count: 0
has body: You don't install ipython kernel with python -m ipykernel install --user. That command, in fact, installs the kernel spec for the corresponding kernel. The kernel itself is installed from the ipykernel package. You did it during environment creation: conda create -n ipykernel_py2 python=2 ipykernel. The ipython kernel might be located in the environment, which is different from your Jupyter environment. That's absolutely normal. When you select it in Jupyter, the kernel spec will point to the kernel in a different environment, and it will be executed by the interpreter in that target environment. The execution context will be the one of the environment with the kernel, not of the environment with Jupyter.
type: Answer

http://stackoverflow.com/q/50744490
downvote count: 0
has comment: http://stackoverflow.com/comment/88496850
score: 1
tagged with: sorting
favorite count: 0
has comment: http://stackoverflow.com/comment/88499047
type: Question
has answer: http://stackoverflow.com/a/50744798
tagged with: input
tagged with: python
tagged with: list
has title: Return the difference between the largest and smallest values
has answer: http://stackoverflow.com/a/50745371
answer count: 2
upvote count: 1
has body: Given an array length 1 or more of ints, return the difference between the largest and smallest values in the list. Note: I don't want to use min and max function.. [10,3,5,6] - 7 , [7,2,10,9] - 8 our_list = [] numbers=int(input("enter numbers").strip()) our_list.append(numbers) our_list.sort() print (our_list) Here is my logic, first I will display the list of the inputted value and then I will use sort method to sort the list to find the min and max number from the list and then I will deduct from the max to min number but I am not able to achieve the result, Here is my code so far.. The above code is not even sorting the numbers thus not able to move ahead, please help.
possible better answer: http://stackoverflow.com/a/50745371
accepted answer: http://stackoverflow.com/a/50744798
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88496934

http://stackoverflow.com/a/50834670
has body: One way is the termios module (POSIX only): import time, termios, sys for n in range(5): time.sleep(1) # write now something, during the loop termios.tcflush(sys.stdin, termios.TCIOFLUSH) example = input('input something: ') print("you have written {}".format(example))
type: Answer
answers question: http://stackoverflow.com/q/50834669
score: 0

http://stackoverflow.com/comment/88493494
score: 0
comment on: http://stackoverflow.com/q/50723423
type: Comment
type: QuestionComment
has text: @denfromufa I am not sure how that would work since "import clr" fails and returns ModuleNotFoundError. The application exists so there is no way to get to a line "after" I import clr.

http://stackoverflow.com/q/50705372
possible better answer: http://stackoverflow.com/a/50705473
has body: I'm trying to extract the text inside from the following html structure: Text to extract I have the following BeautifulSoup code to do it: from bs4 import BeautifulSoup as bs soup = bs(html, "lxml") div = soup.find("div", {"class": "account-places"}) text = div.div.ul.li.next_sibling.get_text() But Beautiful Soup is throwing the error: 'NavigableString' object has no attribute 'get_text'. What am I doing wrong?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50705428
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50705473
has answer: http://stackoverflow.com/a/50705428
score: 8
favorite count: 0
tagged with: beautifulsoup
has title: Python Beautiful Soup 'NavigableString' object has no attribute 'get_text'
upvote count: 8

http://stackoverflow.com/q/50761157
has body: Why the code below throws undefined name sheetname? def PlotChart(charttype = 'line', sheetname = 'CA', values = '='+sheetname+'!$M$1:$M$400'): Any ways I can fix this?
has title: String concatenation inside function arguments
tagged with: string
has answer: http://stackoverflow.com/a/50761204
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/88529756
tagged with: python
has comment: http://stackoverflow.com/comment/88529783
linked to: http://stackoverflow.com/q/4575326
tagged with: xlsxwriter
has comment: http://stackoverflow.com/comment/88529730
type: Question
has comment: http://stackoverflow.com/comment/88529898
tagged with: function
has comment: http://stackoverflow.com/comment/88530760
upvote count: 2
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50761277

http://stackoverflow.com/comment/89509241
type: AnswerComment
comment on: http://stackoverflow.com/a/50824248
type: Comment
has text: if you want to reference JSON key file directly by file name: ServiceAccountCredentials.from_json_keyfile_name(<JSON file>, scopes) (btw --> scopes = https://www.googleapis.com/auth/chat.bot)
score: 0

http://stackoverflow.com/comment/88659780
score: 0
comment on: http://stackoverflow.com/q/50826119
type: QuestionComment
has text: The problem with the 1.5 result is that is essentially wrong. It shows a cartesian imshow plot within a circle, but it's not a polar plot. So I guess it makes sense that this is not possible any more. Are you trying to get the same (wrong) result from 1.5 or are you trying to plot an image in a polar plot as the `extent` suggests? In the latter case the use of `pcolormesh` is indeed the solution - not clear why you would not like to use it.
type: Comment

http://stackoverflow.com/q/50789425
has title: pandas groupby using dictionary values, applying sum
favorite count: 0
score: 5
tagged with: python
has answer: http://stackoverflow.com/a/50789506
has body: I have a defaultdict: dd = defaultdict(list, {'Tech': ['AAPL','GOOGL'], 'Disc': ['AMZN', 'NKE'] } and a dataframe that looks like this: AAPL AMZN GOOGL NKE 1/1/10 100 200 500 200 1/2/10 100 200 500 200 1/310 100 200 500 200 and the output I'd like is to SUM the dataframe based on the values of the dictionary, with the keys as the columns: TECH DISC 1/1/10 600 400 1/2/10 600 400 1/3/10 600 400 The pandas groupby documentation says it does this if you pass a dictionary but all I end up with is an empty df using this code: df.groupby(by=dd).sum() ##returns empty df
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50789469
possible better answer: http://stackoverflow.com/a/50789506
type: Question
upvote count: 5
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50789469
downvote count: 0

http://stackoverflow.com/comment/88510875
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50751454
type: Comment
has text: @abarnert using `yield` and doing the exact same thing in other scripts has worked fine for me so far!

http://stackoverflow.com/q/50746568
has comment: http://stackoverflow.com/comment/88508544
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48074094
tagged with: python-sphinx
has comment: http://stackoverflow.com/comment/88548599
has comment: http://stackoverflow.com/comment/88517655
tagged with: epydoc
linked to: http://stackoverflow.com/q/14606348
type: Question
has body: Epydoc, which has long since ceased development, used to offer an extremely powerful overview of a class or module. For example, this: Notice it shows the classes within the module with the first line or so of the doc-string. For functions it shows the function prototype as well with the start of the doc-string and optional arguments spelled out. This is incredibly useful when browsing the documentation because one can look in rationally named classes/modules and easily find an appropriate function or method. I'd like to have this similar feature in Sphinx but I cannot not find any example which demonstrates this. Frankly, I'm a little surprised because in all of the sea of praise of Sphinx, no one seems to care about this feature being absent, or at least absent as far as I can tell. Does anyone know if there is a way to replicate something like the shown image in Sphinx?
has title: Create class overview in sphinx like epydoc
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88517672
has comment: http://stackoverflow.com/comment/88508012

http://stackoverflow.com/a/61418787
answers question: http://stackoverflow.com/q/50722067
type: Answer
has body: Check for empty spaces space characters at the beginning or end of your file string.
has comment: http://stackoverflow.com/comment/108652054
score: 0

http://stackoverflow.com/comment/88562596
has text: @TudorPlugaru it only has one element I dont know why
type: Comment
comment on: http://stackoverflow.com/q/50777751
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88427768
comment on: http://stackoverflow.com/a/50704106
score: 0
type: AnswerComment
type: Comment
has text: Oh sorry. That was totally dumb of me. Didn't pay attention to that. That's the table name. Got it. I will give it a try and let you know.

http://stackoverflow.com/q/50722067
has answer: http://stackoverflow.com/a/61418787
possible better answer: http://stackoverflow.com/a/56152177
favorite count: 0
has answer: http://stackoverflow.com/a/50722438
answer count: 9
upvote count: 8
has body: Code: import pandas as pd train_df = pd.read_csv("train.csv") Error: FileNotFoundError Traceback (most recent call last) &lt;ipython-input-17-05c7c432b69f&gt; in &lt;module&gt;() 1 import pandas as pd 2 ----&gt; 3 train_df = pd.read_csv("../input/train.csv") /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 707 skip_blank_lines=skip_blank_lines) 708 --&gt; 709 return _read(filepath_or_buffer, kwds) 710 711 parser_f.__name__ = name /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds) 447 448 # Create the parser. --&gt; 449 parser = TextFileReader(filepath_or_buffer, **kwds) 450 451 if chunksize or iterator: /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, f, engine, **kwds) 816 self.options['has_index_names'] = kwds['has_index_names'] 817 --&gt; 818 self._make_engine(self.engine) 819 820 def close(self): /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in _make_engine(self, engine) 1047 def _make_engine(self, engine='c'): 1048 if engine == 'c': -&gt; 1049 self._engine = CParserWrapper(self.f, **self.options) 1050 else: 1051 if engine == 'python': /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, src, **kwds) 1693 kwds['allow_leading_cols'] = self.index_col is not False 1694 -&gt; 1695 …
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/50723391
score: 8
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88452466
has answer: http://stackoverflow.com/a/54523180
has answer: http://stackoverflow.com/a/63156239
has answer: http://stackoverflow.com/a/61357855
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50722155
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64555771
has title: File b'train.csv' does not exist even though file exist
has answer: http://stackoverflow.com/a/50723391
has answer: http://stackoverflow.com/a/56152177
has comment: http://stackoverflow.com/comment/88452502
downvote count: 0

http://stackoverflow.com/q/50854070
has comment: http://stackoverflow.com/comment/88711797
has title: Python on Php import troubles
type: UnansweredQuestion
tagged with: python
tagged with: php
tagged with: opencv
answer count: 0
has body: I'm calling a py script from php and everything seems ok untill I import cv2, then the troubles start. Situation: 1# I have a folder test/ with test.php and test_script.py. test.php: &lt;?php $command = escapeshellcmd( 'python test_script.py' ); $output = shell_exec($command); echo $output; test_script.py: import os import json import numpy as np import cv2 print('pol') 2# If I run it I visualize nothing in test/test.php; instead if I comment "import cv2" it runs perfectly visualizing "pol" as output. 3# The path variable called by php is the same called by cmd (yes, windows..) 4# in cmd I can easily call: &gt; python test_script.py and it works fine Specs Php:7.2.2 Python: 3.6.5 on Anaconda3 So, how can I make it work the same on php?? Why is not working even if in cmd it works? Thank you in advance Update #1 my sdout returns: Traceback (most recent call last): File "predict_test.py", line 10, in import cv2 ImportError: DLL load failed: Access is denied. but I already set Full control permissions by Users and System, on Anaconda3 folder.
score: 0
has comment: http://stackoverflow.com/comment/88710920
type: Question
tagged with: python-import
tagged with: shell-exec

http://stackoverflow.com/comment/88584537
has text: Possible duplicate of [MySQL: How to export and import a .sql file from command line?](https://stackoverflow.com/questions/11407349/mysql-how-to-export-and-import-a-sql-file-from-command-line)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50789094

http://stackoverflow.com/a/50707703
has body: I think you are looking for scipy.ndimage.measurements.label: from scipy.ndimage.measurements import label lb = label(my_bw_image) msks = [] for li in xrange(1, lb.max()+1): msks.append(lb==li) You should have all your masks in msks list.
type: Answer
answers question: http://stackoverflow.com/q/50706569
has comment: http://stackoverflow.com/comment/118576341
has comment: http://stackoverflow.com/comment/88430265
score: 0
has comment: http://stackoverflow.com/comment/88442002

http://stackoverflow.com/q/50701410
favorite count: 0
has comment: http://stackoverflow.com/comment/88430826
tagged with: python
has body: The readNetFromTensorflow function fails to load the tensorflow pre-trained model (.pb). Step 1: training the model of the tensorflow. Tensorflow model of linear regression codes as following: #!/usr/bin/python import tensorflow as tf import numpy as np x_ = tf.placeholder(np.float32, [None, 1], 'input') y_ = tf.placeholder(np.float32, [None, 1], 'label') #layer1 w1 = tf.Variable(tf.random_normal([1,3])) b1 = tf.Variable(tf.random_normal([3]) ) a1 = tf.add(b1,tf.matmul(x_,w1)) #layer2 w2 = tf.Variable(tf.random_normal([3,1])) b2 = tf.Variable(tf.random_normal([1]) ) a2 = tf.add(b2,tf.matmul(a1,w2),name="output") #global steps steps = 5000 x = [] y = [] for i in range(1,200,5): temp = (1.0 * i)/10 x.append([temp]) y.append([3. + 2. * temp]) x = np.array(x) y = np.array(y) #loss function loss = tf.reduce_mean(tf.reduce_sum(tf.square(a2-y_))) #optimizer optimizer = tf.train.GradientDescentOptimizer(0.00001).minimize(loss) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) length = len(x) #training... for i in range(steps): sess.run(optimizer,feed_dict={x_:x,y_:y}) result = sess.run(loss,feed_dict={x_:x,y_:y}) if i % 50 == 0: print("loss: ",result,"\tstep: ",i) saver = tf.train.Saver() saver.save(sess,"./model/model.ckpt") tf.train.write_graph(sess.graph.as_graph_def(), "./model/", "graph.pbtxt") print("predict...") pre = sess.run(a2,feed_dict={x_:[[0]]}) print("x = 2 pre: ",pre) Step 2: Save the model as the .pb file of the tensorflow. How to do that? Step 3: Load the .pb file by using the function readNetFromTensorflow of the opencv3.4.1 with C++. The codes like that: #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; #include &lt;opencv2/dnn.hpp&gt; #include &lt;opencv2/imgproc.hpp&gt; #include &lt;opencv2/highgui.hpp&gt; using namespace std; using namespace cv; using namespace dnn; std::vector&lt;std::string&gt; classes; int main(int argc,char**argv) { if(argc != 2) { cout&lt;&lt;"Usage: ./main [tensorflow modle path(.pb)…
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
has title: How to load the pre-trained model of the tensorflow by using the opencv dnn model
type: Question
tagged with: opencv
score: 1
has answer: http://stackoverflow.com/a/50715080
answer count: 1
has comment: http://stackoverflow.com/comment/88414014
downvote count: 0

http://stackoverflow.com/q/50852672
accepted answer: http://stackoverflow.com/a/50852707
upvote count: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50852707
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50852776
has title: Python: Assign value to a new column in Pandas as list using other columns
answer count: 3
tagged with: pandas
has body: I have below pandas dataframe: Name1 Name2 Score1 Score2 Bruce Jacob 3 4 Aida Stephan 0 1 I want to create a new column in the dataframe "list_score" which is a list of score 1 and 2 Expected result: Name1 Name2 Score1 Score2 list_score Bruce Jacob 3 4 [3,4] Aida Stephan 0 1 [0,1]
has answer: http://stackoverflow.com/a/50852776
tagged with: python
has answer: http://stackoverflow.com/a/50852734
score: 2

http://stackoverflow.com/comment/88704011
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50798830
has text: For above document structure, is there any other way to query instead of making it as nested object? Because I have some other data in the same document, which are not a nested object. But while I am doing simple search, it skips the nested documents.
score: 0

http://stackoverflow.com/q/50749602
accepted answer: http://stackoverflow.com/a/50749772
downvote count: 1
answer count: 1
has title: Adding two next rows data to the current row in Pandas
tagged with: dataframe
has body: I have a stock dataframe: Date Open High Low Close Volume 0 01.05.2018 1.20821 1.20821 1.20793 1.20794 138.96 1 01.05.2018 1.20794 1.20795 1.20787 1.20788 119.61 2 01.05.2018 1.20788 1.20793 1.20770 1.20779 210.42 3 01.05.2018 1.20779 1.20791 1.20779 1.20789 77.51 4 01.05.2018 1.20789 1.20795 1.20789 1.20792 56.97 I want to copy the next two rows to the current row. Or more clear, each row in the new dataframe should have the next two rows data.
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50749772
tagged with: dataset
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
score: -1

http://stackoverflow.com/comment/88540427
type: QuestionComment
has text: @Valentyn, you literally start a new thread with `start_new_thread(self.server_thread,())`.
comment on: http://stackoverflow.com/q/50763885
score: 0
type: Comment

http://stackoverflow.com/comment/88638486
score: 0
type: AnswerComment
has text: Oh, I completely missed that. If you want to put words instead of letters, use `text_file.readlines()` instead of `text_file.read()` - they both create iterable objects, but the former gives you a list of strings and the latter gives you a single string, and trying to iterate through that gives you single characters.
type: Comment
comment on: http://stackoverflow.com/a/50804569

http://stackoverflow.com/comment/88631905
type: QuestionComment
score: 0
type: Comment
has text: I think need `df = df3'time'.join(df3['proto'].str.split(',',expand=True))`
comment on: http://stackoverflow.com/q/50813368

http://stackoverflow.com/q/50826656
has answer: http://stackoverflow.com/a/72475174
downvote count: 0
has comment: http://stackoverflow.com/comment/88658563
favorite count: 0
has comment: http://stackoverflow.com/comment/88658136
has answer: http://stackoverflow.com/a/50826996
tagged with: typeerror
answer count: 3
has comment: http://stackoverflow.com/comment/88658402
has title: TypeError: '<' not supported between instances of 'NoneType' and 'str'
tagged with: python
has comment: http://stackoverflow.com/comment/88658541
upvote count: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88658466
tagged with: set
has comment: http://stackoverflow.com/comment/88658575
has body: I"m getting this error as I try to make a ttk.Combobox using the values of a set that I select from a .db file. for row in self.sql.execute("SELECT {0} FROM Songinfo".format(self.variable1.get())): self.List2.append(row) self.seen.add(row) self.Option2 = ttk.Combobox(self, values=sorted(self.seen), textvariable=self.variable2) self.Option2.grid(row=3, column=1) self.seen, when printed out returns something like: {('Heavy Metal',), ('Soundtrack',), ('Pop/Rock',), ('Metal',), ('Alternative',), ('Alternative &amp; Punk',), ('Rock',), ('Pop',), ('Classical Crossover',), (None,)} this is a set of genres. I'm getting that error and I'm not sure why, it wasn't an issue till recently, any help is appreciated, thanks.
score: 11
accepted answer: http://stackoverflow.com/a/50826996
has answer: http://stackoverflow.com/a/50826706
type: Question
has comment: http://stackoverflow.com/comment/88658525
possible better answer: http://stackoverflow.com/a/50826706

http://stackoverflow.com/comment/88556120
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50774293
type: Comment
has text: What did you enter?

http://stackoverflow.com/comment/88572951
comment on: http://stackoverflow.com/q/50783177
score: 1
has text: `cv2.imshow` is not implemented. Print the output of function `cv2.getBuildInformation()` and in the result search for `GUI`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50818539
has body: The data repeats for multiple participants (p), each with several trials of which half fall under two bin_trials (1 and 2). This is just a small sample. I know that last column is missing, it was just too much data for the question. p tr bin_trial cor_gaze_perc cor_gaze_key_perc 0 2 1 1 1.00 1.00 1 2 2 1 1.00 1.00 2 2 3 1 0.00 0.00 3 2 4 1 0.50 0.50 4 2 5 1 0.75 0.75 5 2 6 1 0.50 0.50 6 2 7 1 0.50 0.50 7 2 8 1 0.25 0.25 8 2 9 1 1.00 1.00 9 2 10 1 0.50 0.50 10 2 11 1 1.00 1.00 11 2 12 1 1.00 1.00 12 2 13 1 1.00 1.00 13 2 14 1 1.00 1.00 14 2 15 1 0.50 0.50 15 2 16 2 1.00 1.00 16 2 17 2 1.00 1.00 17 2 18 2 1.00 1.00 18 2 19 2 0.75 0.75 19 2 20 2 1.00 1.00 20 2 21 2 1.00 1.00 21 2 22 2 1.00 1.00 22 2 23 2 0.60 0.40 23 2 24 2 1.00 1.00 24 2 25 2 0.00 0.00 25 2 26 2 0.00 0.00 26 2 27 2 1.00 1.00 27 2 28 2 0.00 0.00 28 2 29 2 1.00 1.00 29 2 30 2 0.50 0.50 I want to achieve a plot that looks similar to this: I saw this previous answer Seaborn multiple barplots suggesting to use melt to then use the parameter hue. However, if I do that I need to compute ci's separately. Not to mention that it seems a bit of overkill, since the library can already aggregate data and calculate ci's automatically when the parameters are passed in a suitable way. I know that as a last resort I can use pivot_table to manually aggregate the data and compute the ci's. So my question boils down to is the hue approach the only way to do it? Or is there a way that will use the columns as per the given data and also compute the ci's on the fly when plotting?
linked to: http://stackoverflow.com/q/38807895
tagged with: python-2.7
has title: How to plot multiple groups of columns of a pandas dataframe side by side using Seaborn
tagged with: pandas
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88650531
accepted answer: http://stackoverflow.com/a/50985413
tagged with: seaborn
upvote count: 1
has comment: http://stackoverflow.com/comment/88651766
type: AnsweredQuestion
score: 1
tagged with: matplotlib
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50985413

http://stackoverflow.com/q/50847374
possible better answer: http://stackoverflow.com/a/69021164
accepted answer: http://stackoverflow.com/a/50847580
score: 44
upvote count: 44
type: Question
linked to: http://stackoverflow.com/q/15891038
has body: I have a pandas data frame with different data types. I want to convert more than one column in the data frame to string type. I have individually done for each column but want to know if there is an efficient way? So at present I am doing something like this: repair['SCENARIO']=repair['SCENARIO'].astype(str) repair['SERVICE_TYPE']= repair['SERVICE_TYPE'].astype(str) I want a function that would help me pass multiple columns and convert them to strings.
linked to: http://stackoverflow.com/q/19482970
has title: Convert multiple columns to string in pandas dataframe
tagged with: python-2.7
answer count: 3
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/50847580
favorite count: 0
has answer: http://stackoverflow.com/a/69021164
tagged with: python
has answer: http://stackoverflow.com/a/62038408
type: AnsweredQuestion

http://stackoverflow.com/q/50852056
has comment: http://stackoverflow.com/comment/88707030
has comment: http://stackoverflow.com/comment/88707123
upvote count: 0
answer count: 1
tagged with: imap
has comment: http://stackoverflow.com/comment/88706915
has comment: http://stackoverflow.com/comment/88707106
favorite count: 0
has comment: http://stackoverflow.com/comment/88707076
has body: This is my code currently, I am using Google Cloud SDK and Python 2.7: import webapp2 import smtplib import time import imaplib import email class ReadMail(webapp2.RequestHandler): def get(self): mail = imaplib.IMAP4_SSL(imap.gmail.com) mail.login('xxx@gmail.com','xxx') mail.select('inbox') type, data = mail.search(None, 'ALL') mail_ids = data[0] id_list = mail_ids.split() first_email_id = int(id_list[0]) latest_email_id = int(id_list[-1]) for i in range(latest_email_id,first_email_id, -1): typ, data = mail.fetch(i, '(RFC822)' ) for response_part in data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part[1]) email_subject = msg['subject'] email_from = msg['from'] self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello World?') self.response.write('From :') + email_from + '\n' self.response.write('Subject :') + email_subject + '\n' app = webapp2.WSGIApplication([ ('/', ReadMail), ], debug=True) However I get this error, and the web-page does not load (HTML 500 error): ERROR 2018-06-14 07:30:02,217 wsgi.py:279] Traceback (most recent call last): File "C:\Users\XXX\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 267, in Handle result = handler(dict(self._environ), self._StartResponse) TypeError: 'module' object is not callable INFO 2018-06-14 10:30:02,878 module.py:846] default: "GET / HTTP/1.1" 500 - INFO 2018-06-14 10:30:08,711 module.py:414] [default] Detected file changes: hello.pyc I see the issue is with calling the modules, but since I am completely new to python it is hard for me to understand how this works. Any help would be appreciated! EDIT If I remove the 'Request.Handler' from class ReadMail(webapp2.RequestHandler), I get this error instead: File "C:\Users\xxx\desktop\pythontest\demo\hello.py", line 8, in &lt;module&gt; class ReadMail(webapp2): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 argumen…
tagged with: python
tagged with: web
tagged with: gmail
type: UnansweredQuestion
tagged with: web-applications
downvote count: 1
has title: New to Python, trying to create a program that prints Gmail to a web page
has comment: http://stackoverflow.com/comment/88707182
score: -1
has answer: http://stackoverflow.com/a/50852334
type: Question

http://stackoverflow.com/a/50770205
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50768811
has comment: http://stackoverflow.com/comment/88560769
score: 1
accepted answer of: http://stackoverflow.com/q/50768811
has body: url('', TemplateView.as_view(template_name='index.html'), You are missing a closing ). It also appears that you url pattern is incorrect as well. Should be url(r'^$' , TemplateView.as_view(template_name='index.html')),
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50831317
duplicate of: http://stackoverflow.com/q/23479512
has comment: http://stackoverflow.com/comment/88666985
downvote count: 1
type: Question
has title: Stratified Sampling using R or Python
score: -1
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/50831830
tagged with: statistical-sampling
upvote count: 0
has body: I have a dataset with 400K observations and 250 features. I would like to perform the stratified sampling. I referred many links, but they are all after 1 or two variables examples including Target. Can anybody please help me how should be performing stratified sampling using R / Python. thanks in Adavance !
answer count: 1
favorite count: 0
tagged with: sampling
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23479512
tagged with: python

http://stackoverflow.com/comment/88517575
comment on: http://stackoverflow.com/q/50754417
has text: @WaketZheng the logic is already written in procedures and for this logic multiple tables are involved, that's why we are not using orm for this to reduce db hit like ORM->dB->ORM
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50722157
score: 0
has comment: http://stackoverflow.com/comment/88453058
answer count: 1
tagged with: knn
type: UnansweredQuestion
tagged with: python
has body: I was working with the K-nearest neighbors in Python tutorial on Dataquest. Have been working on the issues for months now and every time it's something new. I have gotten down to the last few lines of code but have not been able to figure out why the following error occurs every time I try to fit the model on the training data: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-59-0e474d4c7797&gt; in &lt;module&gt;() ----&gt; 1 knn.fit(train[x_columns], train[y_column]) C:\Users\aduran\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\neighbors\base.py in fit(self, X, y) 739 """ 740 if not isinstance(X, (KDTree, BallTree)): --&gt; 741 X, y = check_X_y(X, y, "csr", multi_output=True) 742 self._y = y 743 return self._fit(X) C:\Users\aduran\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_X_y(X, y, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator) 519 X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite, 520 ensure_2d, allow_nd, ensure_min_samples, --&gt; 521 ensure_min_features, warn_on_dtype, estimator) 522 if multi_output: 523 y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False, C:\Users\aduran\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 405 % (array.ndim, estimator_name)) 406 if force_all_finite: --&gt; 407 _assert_all_finite(array) 408 409 shape_repr = _shape_repr(array.shape) C:\Users\aduran\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\utils\validation.py in _assert_all_finite(X) 56 and not np.isfinite(X).all()): 57 raise ValueError("Input contains NaN, infinity" ---&gt; 5…
has comment: http://stackoverflow.com/comment/88453271
has comment: http://stackoverflow.com/comment/88453459
has answer: http://stackoverflow.com/a/61494159
has title: KNN- NBA players
type: Question

http://stackoverflow.com/comment/88453862
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50722532
has text: @Prateek I removed my comment as I could not edit it to correct that the simple removal of the backslash does not work in that case.
score: 0

http://stackoverflow.com/a/50834640
answers question: http://stackoverflow.com/q/50834506
has comment: http://stackoverflow.com/comment/88673906
has body: Instead of if x in range(0,101), you should use if x &gt;= 0 and x &lt;= 100 or as @mata suggested you could use if 0 &lt;= x &lt;= 100. x in range(0, 101) returns True only when x is an integer and lies between 0 and 100 (inclusive).
has comment: http://stackoverflow.com/comment/88673132
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88673317
has comment: http://stackoverflow.com/comment/88673318
has comment: http://stackoverflow.com/comment/88673493
upvote count: 1

http://stackoverflow.com/q/50804925
has comment: http://stackoverflow.com/comment/88643314
answer count: 0
score: 0
linked to: http://stackoverflow.com/q/41654949
has comment: http://stackoverflow.com/comment/88640850
type: Question
duplicate of: http://stackoverflow.com/q/41654949
has comment: http://stackoverflow.com/comment/88641197
tagged with: pandas
has title: Dataframe Format (background color of cells, Fonts, Font Size etc.)
has body: I have a CSV file and I have converted this CSV file to Excel via pandas and also plotted some graph on the Excel sheet. Now, I want to color some cells let's say B2: B6 grey color. I am unable to find solution to format these cells in dataframe. I tried to use: workbook = writer.book worksheet = writer.sheets['sheet1'] cellColor = workbook.add_format({'fg_color': '#808080'}) worksheet.set_column('B', None, cellColor) It will set the whole column B with grey color while I just want to set 6 cells of column B. If I use the following command it overwrites the cells with the red color and text disappear as well. worksheet.write('L2', None, cellColor)
type: UnansweredQuestion
tagged with: python
tagged with: excel

http://stackoverflow.com/q/50756732
favorite count: 0
has body: I was trying to create a model for character recognition. This model was working fine with 28*28 dataset and for characters from 0-9 but it training accuracy is dropping if changed to 64*64 and characters ranges from 0-9, a-z, A-Z. While iterating through accuracy it goes till 0.3 and then stays there afterwards. I tried to train with different dataset as well but the same thing is happening. Changing learning rate to 0.001 also does not help. Can anyone tell what is the issue with this? import numpy as np from PIL import Image import matplotlib.pyplot as plt import random as ran import os import tensorflow as tf def TRAIN_SIZE(num): images = np.load("data/train/images64.npy").reshape([2852,4096]) labels = np.load("data/train/labels.npy") print ('Total Training Images in Dataset = ' + str(images.shape)) print ('--------------------------------------------------') x_train = images[:num,:] print ('x_train Examples Loaded = ' + str(x_train.shape)) y_train = labels[:num,:] print ('y_train Examples Loaded = ' + str(y_train.shape)) print('') return x_train, y_train def TEST_SIZE(num): images = np.load("data/test/images64.npy").reshape([558,4096]) labels = np.load("data/test/labels.npy") print ('Total testing Images in Dataset = ' + str(images.shape)) print ('--------------------------------------------------') x_test = images[:num,:] print ('x_test Examples Loaded = ' + str(x_test.shape)) y_test = labels[:num,:] print ('y_test Examples Loaded = ' + str(y_test.shape)) print('') return x_test, y_test def display_digit(num): # print(y_train[num]) label = y_train[num].argmax(axis=0) image = x_train[num].reshape([64,64]) # plt.axis("off") plt.title('Example: %d Label: %d' % (num, label)) plt.imshow(image, cmap=plt.get_cmap('gray_r')) plt.show() def display_mult_flat(start, stop): images = x_train[start].reshape([1,4096]) for i in range(start+1,stop): images = np.concatenate((images, x_train[i].reshape([1,4096]))) plt.imshow(images, cmap=plt.get_cmap('gray_r')) plt.show() def g…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50757844
upvote count: 1
has title: training accuracy drops in tensorflow
tagged with: tensorflow
type: Question
tagged with: neural-network
answer count: 2
tagged with: deep-learning
has answer: http://stackoverflow.com/a/50758172
downvote count: 0
score: 1

http://stackoverflow.com/q/50716437
type: AnsweredQuestion
tagged with: python
favorite count: 0
has body: I have 2 dictionaries dict1 = {'color': {'attri': ['Black']}, 'diameter': {'attri': ['(300, 600)']}} dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}} I want to combine the 2 dictionaries such that dict3 = {'color': {'op': 'in', 'attri': ['Black']}, 'diameter': {'op': 'range', 'attri': ['(300,600)']}}
score: 4
linked to: http://stackoverflow.com/q/38987
type: Question
has title: How to combine the dictionaries in python
tagged with: django
has answer: http://stackoverflow.com/a/50716549
possible better answer: http://stackoverflow.com/a/50716504
has answer: http://stackoverflow.com/a/50716496
has answer: http://stackoverflow.com/a/50716504
upvote count: 4
answer count: 4
has comment: http://stackoverflow.com/comment/88441508
has answer: http://stackoverflow.com/a/50716568
downvote count: 0
has comment: http://stackoverflow.com/comment/88442336
accepted answer: http://stackoverflow.com/a/50716496

http://stackoverflow.com/q/50741330
tagged with: python
has answer: http://stackoverflow.com/a/56149336
tagged with: indexing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50743468
score: 21
possible better answer: http://stackoverflow.com/a/56149336
has body: I was confused by this, which is very simple but I didn't immediately find the answer on StackOverflow: df.set_index('xcol') makes the column 'xcol' become the index (when it is a column of df). df.reindex(myList), however, takes indexes from outside the dataframe, for example, from a list named myList that we defined somewhere else. However, df.reindex(myList) also changes values to NAs. A simple alternative is: df.index = myList I hope this post clarifies it! Additions to this post are also welcome!
type: Question
downvote count: 0
tagged with: reindex
has title: Difference between df.reindex() and df.set_index() methods in pandas
favorite count: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50743468
tagged with: python-3.x
has answer: http://stackoverflow.com/a/57521078
upvote count: 21

http://stackoverflow.com/a/50768245
score: 3
accepted answer of: http://stackoverflow.com/q/50767808
has body: As the comments have said: what you want is known as a "mixin" class. The usual naming convention for such a class is for it to end in "mixin", like so: class HealerMixin: def __init__(self, *args, **kwargs): if type(self) is HealerMixin: raise TypeError("HealerMixin cannot be instantiated") super().__init__(*args, **kwargs) def heal(self, target=None): if target is None: # heal self target = self.name self.cover() # this is ugly print('healing {!s}'.format(target)) class NameMixin: def __init__(self, name, *args, **kwargs): if type(self) is NameMixin: raise TypeError("NameMixin cannot be instantiated") self.name = str(name) super().__init__(*args, **kwargs) def __str__(self): return self.name If you include an __init__ method in your mixin, it's usually a good idea to include the (*args, **kwargs) signature in the __init__ method because this enables the mixin to work with any child class with any signature. class Wizard(NameMixin): def cover(self): print('{!s} Covering behind my robe'.format(self.name)) class Druid(HealerMixin, Wizard): pass class FlashyDruid(Druid): def __init__(self, name): super().__init__("~~***{!s}***~~".format(name)) def cover(self): """Overrides Wizard.cover()""" print('{!s} Covering behind my glittering robe'.format(self.name)) Maybe use it like this: &gt;&gt;&gt; Gob = FlashyDruid("Gob") &gt;&gt;&gt; Gob.cover() ~~***Gob***~~ Covering behind my glittering robe &gt;&gt;&gt; Buster = Druid("Buster") &gt;&gt;&gt; Buster.heal(Gob) Buster Covering behind my robe healing ~~***Gob***~~ Using super in your __init__ method makes it so that the class inheritance happens auto-magically. You do not have to manually think through the inheritance yourself. Note that it sometimes becomes important to inherit from a mixin class in the right order: mixins first, the base classes last (if there are any). If you do not, you will cause errors. For example in some cases the mixin will try to send arguments to classes that do not know what to do with them.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50767808
type: Answer
upvote count: 3

http://stackoverflow.com/comment/88534413
comment on: http://stackoverflow.com/q/50762877
type: Comment
type: QuestionComment
score: 0
has text: @deceze interesting that you said that. Yeah you could. But I was given that file with the expectation of there being a very specific number of inversions. As such, the order as provided is, indeed, important.

http://stackoverflow.com/a/50817009
has comment: http://stackoverflow.com/comment/88639001
has comment: http://stackoverflow.com/comment/88639090
accepted answer of: http://stackoverflow.com/q/50816947
has comment: http://stackoverflow.com/comment/88639266
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50816947
score: 0
type: Answer
has body: Your library is for Python 2, but you're trying to use it in Python 3. Search another library that can do the same thing, search if there's a Python 3 version or use it in Python 2.

http://stackoverflow.com/comment/88646422
comment on: http://stackoverflow.com/q/50820577
score: 0
type: Comment
type: QuestionComment
has text: Show us the code when you took each element of the list one at a time.

http://stackoverflow.com/comment/88472092
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50725416
has text: you can manage to install mpl_toolkits.basemap, put the problem in the question.

http://stackoverflow.com/comment/88647509
score: 0
comment on: http://stackoverflow.com/a/50820933
has text: @Aran-Fey Does the extraneous `__init__` just get thrown away? For my purposes, I might be OK with that overhead, as @FHTMitchell's form is syntactically exactly what I want.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88548681
has text: @eyllanesc and... also... now that I try, I realize I'm not sure how to update it past 8.5... googling it but it seems to be one of those "download this, issue these make commands, then totally update python" things that I'm hesitant to start since ... as I say above, I'd be surprised that a tutorial script this simple would require a specifically recent version of Tkinter...
comment on: http://stackoverflow.com/q/50770356
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88491932
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50741742
type: Comment
has text: You forgot to sum the columns of a given combination, your code right now is trying to assign the values of several columns of `df` into a single column of `new_df`

http://stackoverflow.com/q/50731160
has comment: http://stackoverflow.com/comment/88470058
has title: Improve CSV file write speed
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88470023
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88470116
has body: The code below works just fine. I'm wondering is there any way to improve the write speed of it. As it would currently take from 12 to 20 seconds to write the .csv file. import csv import os data = [...1000 item list, where each item is a dictionary with 8 values...] for candle in data: if os.path.isfile('data'+os.sep+i+os.sep+coin_symbol+'.csv'): H = [] H.append(candle['timestamp']) H.append(candle['open']) H.append(candle['close']) H.append(candle['min']) H.append(candle['max']) H.append(candle['volume']) H.append(candle['volumeQuote']) with open('data'+os.sep+i+os.sep+coin_symbol+'.csv', 'a', newline="") as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') csvwriter.writerow(H) else: H = [] H.append('TimeStamp') H.append('Open') H.append('Close') H.append('Min') H.append('Max') H.append('Volume') H.append('VolumeQuote') with open('data'+os.sep+i+os.sep+coin_symbol+'.csv', 'w', newline="") as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') csvwriter.writerow(H) H = [] H.append(candle['timestamp']) H.append(candle['open']) H.append(candle['close']) H.append(candle['min']) H.append(candle['max']) H.append(candle['volume']) H.append(candle['volumeQuote']) with open('data'+os.sep+i+os.sep+coin_symbol+'.csv', 'a', newline="") as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') csvwriter.writerow(H) For the Else statement, is there any way to write it differently?
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: performance
has answer: http://stackoverflow.com/a/50744545
score: 1

http://stackoverflow.com/comment/88634436
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50813892
type: AnswerComment
has text: Classifier get 5 row of a data as input, then It predict(classify) the 6th row label.

http://stackoverflow.com/q/50791696
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: git-commit
has answer: http://stackoverflow.com/a/50793725
has body: I've created a git post-commit hook in python and made a file executable and placed it into .git/post-commit. It works when I run it via Python. Now I want test it locally in git. How can I do that? I can't make a commit to git locally from my computer in an easy way, right? Should I copy the hook file to my server and make test commits to test it? Is there another way?
downvote count: 1
tagged with: git
type: Question
accepted answer: http://stackoverflow.com/a/50791745
tagged with: githooks
score: 1
upvote count: 2
has answer: http://stackoverflow.com/a/50791745
has title: How to test pre/post commit scripts in git?
answer count: 2
possible better answer: http://stackoverflow.com/a/50793725

http://stackoverflow.com/comment/88532950
score: 2
comment on: http://stackoverflow.com/q/50701786
has text: I'm voting to close this question as off-topic because the question is fundamentally flawed at its premise. It is based on a comparison of two metrics that are incomparable. Mathematical synesthesia. It is like asking why the color red doesn't sound like clapping.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50815219
tagged with: python-xarray
score: 0
has body: I'm receiving a StopIteration: error when attempting to use the groupby function in xarray. The error only occurs when attempting to loop through a list of files - if a single file path is input, no error is generated. I've also tried using xr.open_mfdataset to open the full directory of files, but this produced the same error. for path in in_files: ds = xr.open_dataset(path) ds['index'] = county_mask ds = ds.set_coords('index') ds = ds.where(ds['index'].isin(cotton_county_keys)) ds.groupby('index').mean('stacked_lat_lon').to_dataframe().reset_index() Produces the error: StopIteration Traceback (most recent call last) &lt;ipython-input-91-f26bf31efda5&gt; in &lt;module&gt;() 6 ds = ds.set_coords('index') 7 ds = ds.where(ds['index'].isin(cotton_county_keys)) ----&gt; 8 ds.groupby('index').mean('stacked_lat_lon').to_dataframe().reset_index() ~\AppData\Local\Continuum\anaconda3\lib\site-packages\xarray\core\common.py in wrapped_func(self, dim, keep_attrs, skipna, **kwargs) 52 return self.reduce(func, dim, keep_attrs, skipna=skipna, 53 numeric_only=numeric_only, allow_lazy=True, ---&gt; 54 **kwargs) 55 else: 56 def wrapped_func(self, dim=None, keep_attrs=False, **kwargs): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\xarray\core\groupby.py in reduce(self, func, dim, keep_attrs, **kwargs) 652 def reduce_dataset(ds): 653 return ds.reduce(func, dim, keep_attrs, **kwargs) --&gt; 654 return self.apply(reduce_dataset) 655 656 def assign(self, **kwargs): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\xarray\core\groupby.py in apply(self, func, **kwargs) 607 kwargs.pop('shortcut', None) # ignore shortcut if set (for now) 608 applied = (func(ds, **kwargs) for ds in self._iter_grouped()) --&gt; 609 return self._combine(applied) 610 611 def _combine(self, applied): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\xarray\core\groupby.py in _combine(self, applied) 611 def _combine(self, applied): 612 """Recombine the applied objects like the original.""" --&gt; 6…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88635339
has comment: http://stackoverflow.com/comment/88636585
answer count: 0
has comment: http://stackoverflow.com/comment/88637251
type: Question
has title: xarray StopIteration: error when running groupby in loop

http://stackoverflow.com/q/50838384
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50838787
has answer: http://stackoverflow.com/a/50838745
tagged with: machine-learning
has body: I have a file with lines of numbers represting vectors. I am trying to convert it into list of lists of floats. Right now, my problem is that it takes only the first row of each line. I have try to loop over each index, but I face an error of "can not convert string into float" Here is my code: with open(input_file) as f: content = f.readlines() content = [x.strip() for x in content] input_val_arr = list(map(float, [i.split(' ', 1)[0] for i in content])) input format: 0.03518 -0.02543 ... (dim = 100) 0.0025865 -0.01867 .... ... (dim = ALOT) desire output: [[ 0.03518 , -0.02543 ...] [0.0025865 -0.01867 ...] ... ]] I have tried to change my code to: with open(input_file) as f: content = f.readlines() input_val_arr = [] for index in range(x_dim): temp_list = list(map(float, [i.split(' ', 1)[index] for i in content])) input_val_arr.append(temp_list) And I get the following error: ValueError: could not convert string to float: '-0.02543 0.0025865 ...'
has answer: http://stackoverflow.com/a/50838787
type: Question
has comment: http://stackoverflow.com/comment/88680760
has answer: http://stackoverflow.com/a/50838786
accepted answer: http://stackoverflow.com/a/50838786
has answer: http://stackoverflow.com/a/50838954
upvote count: 1
downvote count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/88681212
has title: String List conversion to float python
has comment: http://stackoverflow.com/comment/88680690
has comment: http://stackoverflow.com/comment/88680603
tagged with: python
has comment: http://stackoverflow.com/comment/88680600
answer count: 4
has comment: http://stackoverflow.com/comment/88681432

http://stackoverflow.com/comment/88658898
has text: I think a hint can be a good answer. However, I'm not sure this answer does a very good job, because it changes a bunch of stuff that isn't relevant to the problem. Why keep track of a count and three indexes, when what the OP was doing with keeping two strings and comparing `len` was fine? Sure, this is a little more efficient, but it's hardly likely to matter here, and I think it's less readable and easier to make off-by-one errors this way. But, more importantly, it's different from the code the OP almost got right and presumably already understands.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50826972
type: Comment

http://stackoverflow.com/q/50821962
type: Question
has body: The file path column in my database is being cut off and I haven't been able to find any documentation saying how to specify the column width in python. I'm currently using pandas to print the database in the terminal. Database printout: Path Status Time 0 pytest_file.c Safe 2018-06-11 10:33:29 1 /Users/me/Documents/to_scan/SSpres... File Sent 2018-06-11 10:45:05 2 /Users/me/Downloads/SampleData/Eli... File Sent 2018-06-11 10:45:33 3 /Users/me/Downloads/SampleData/Eli... File Sent 2018-06-11 10:45:34 4 /Users/me/Downloads/SampleData/Lec... File Sent 2018-06-11 10:45:35 5 /Users/me/temp/ess-dive-volumes/var... Safe 2018-06-11 11:46:02 6 /Users/me/temp/ess-dive-volumes/var... Safe 2018-06-11 11:46:18 7 /Users/me/temp/ess-dive-volumes/var... Safe 2018-06-11 11:46:34 8 /Users/me/temp/ess-dive-volumes/var... Safe 2018-06-11 11:46:50 Code for printing database: con = sqlite3.connect(data_base) return pd.read_sql_query('''SELECT Path, Status, Time FROM files_db''', con) print(print_db(database))
accepted answer: http://stackoverflow.com/a/50823213
has title: How to format column width in SQLite3 using python?
tagged with: pandas
tagged with: sqlite
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/1751189
favorite count: 0
has comment: http://stackoverflow.com/comment/88648962
tagged with: python
has comment: http://stackoverflow.com/comment/88649009
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50823213
upvote count: 1

null
tags question: http://stackoverflow.com/q/50701018
tag name: null
tags question: http://stackoverflow.com/q/50783087
type: Tag

http://stackoverflow.com/comment/88660330
comment on: http://stackoverflow.com/a/50826714
type: AnswerComment
score: 0
type: Comment
has text: The main difference seems to be that `loadtxt` loads the file in 50,000 line chunks, and converts the strings with a specified `dtype`. `genfromtxt` splits all lines, and does the `dtype` conversion once, possibly using a dtype that it has deduced.

http://stackoverflow.com/comment/88483613
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50735140
has text: @Inian This is not a duplicate like you flagged it, it's not about determining the version but figuring out what happens to the version output of certain Python versions. I don't know how or I lack the rep to dispute the flag, so let's try this.

http://stackoverflow.com/comment/88615470
comment on: http://stackoverflow.com/a/50804541
score: 1
type: AnswerComment
type: Comment
has text: on those limit cases, you have to time both, and choose the fastest. But be careful that noone needs to increase the value, which would make the code slower (leave a big "warning" comment about this). The fastest may not be the same depending on the machine & python version.

http://stackoverflow.com/q/50749025
score: 1
accepted answer: http://stackoverflow.com/a/50749090
upvote count: 1
type: Question
tagged with: numpy
has title: Rescaling 2D numpy array as Dense representation
tagged with: rescale
answer count: 2
has body: I have a numpy array . I want rescale the elements in the array, so that the smallest number in array is represented by 1, and largest number in array is represented by the number of unique elements in array. For example A=[ [2,8,8],[3,4,5] ] would become [ [1,5,5],[2,3,4] ]
downvote count: 0
tagged with: dense-rank
favorite count: 0
has comment: http://stackoverflow.com/comment/116099659
possible better answer: http://stackoverflow.com/a/50749191
has answer: http://stackoverflow.com/a/50749191
tagged with: python
has answer: http://stackoverflow.com/a/50749090
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/36193225

http://stackoverflow.com/a/50702294
has comment: http://stackoverflow.com/comment/88420517
has comment: http://stackoverflow.com/comment/88420924
score: 0
has comment: http://stackoverflow.com/comment/88427367
has body: I understand that you're looking for some references to get yourself started, however you are asking on the wrong section of stack. You should be going to Stack Exchange and posting your question over there using the proper tags. Stack Overflow is typically used when you already have found the resources you're going to use, and you've encountered an error when trying to create or implement something using them But to get you started, I would suggest using PyUSB which is a python implementation of LibUSB
has comment: http://stackoverflow.com/comment/88417629
has comment: http://stackoverflow.com/comment/88452138
type: Answer
answers question: http://stackoverflow.com/q/50702056
has comment: http://stackoverflow.com/comment/88450572

http://stackoverflow.com/a/50843380
has body: In Python 3.6+, you can use formatted string literals, also known as f-strings: def formatter(x): return str(x) if x &gt;= 0 else f'({abs(x)})' for col in df.columns[1:]: df[col] = df[col].apply(formatter) print(df) Team Group1 Group2 Group3 0 green 1 5 (6) 1 blue (3) 10 5 2 red (7) 9 (8)
answers question: http://stackoverflow.com/q/50843251
accepted answer of: http://stackoverflow.com/q/50843251
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88690612
has comment: http://stackoverflow.com/comment/88690369
has comment: http://stackoverflow.com/comment/88690397
type: Answer

http://stackoverflow.com/a/50752443
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88513002
has body: You are passing a method to Backoff, assigning it as an instance variable, and then calling it. This not bound to an instance until it is being called in Backoff.__call__, where it is then bound to an instance of Backoff which does not have a formatter property. There might be a straightforward solution to this depending on what your instance method needs access to (i.e. if it only needs to reference a class or static method, it can just call the fully qualified name directly). However, if you need the instance method to reference an instance property, I would suggest not using a class decorator at all. Using a function decorator will not run into these issues, you can create a closure and return a function with the same call signature.
answers question: http://stackoverflow.com/q/50752354
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88512919
accepted answer of: http://stackoverflow.com/q/50752354

http://stackoverflow.com/a/50764756
answers question: http://stackoverflow.com/q/50764548
has body: The structure of your code is perfectly fine. Concatenating a list of dataframes is more efficient than repeatedly appending to an existing dataframe. Set dtype What you can try and optimize is reading your csv file, i.e. df = pd.read_csv(file). My only suggestion is to specify dtype parameter with a dictionary mapping column names to types. In particular, if you have columns with categorical data, map to 'category' to ensure you optimize memory usage. List comprehension + assign You mention more concise code. You can utilize pd.DataFrame.assign to create a new series and set it to your filename. In addition, you can use a list comprehension: dfs = [pd.read_csv(file).assign(variable=os.path.basename(file).split('_')[0]) \ for file in glob.glob(os.path.join('data','*.csv'))] finalDf = pd.concat(dfs, ignore_index=True) If you choose this method, you may lose readability, so document what you are doing.
score: 1
accepted answer of: http://stackoverflow.com/q/50764548
downvote count: 0
has comment: http://stackoverflow.com/comment/88553148
type: AcceptedAnswer
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88481228
type: QuestionComment
has text: You can create a list and append `car` inside the loop to the list
comment on: http://stackoverflow.com/q/50736550
score: 0
type: Comment

http://stackoverflow.com/comment/88467946
has text: Ah, missed that one. Thanks!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50730070

http://stackoverflow.com/q/50750156
has comment: http://stackoverflow.com/comment/89344994
has comment: http://stackoverflow.com/comment/88535779
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88525440
has title: Installing Pointcloud Library, Boost.Python, and Conda Python
tagged with: c++
has body: I have been trying for about a month now to install Pointcloud Library and Boost.Python with Conda Python all together for an application I am trying to port to Ubuntu 16.04 running in a Docker container. Everything builds and works fine in Windows, but each method I've tried in Ubuntu to install these libraries results in a failure in one way or another. I've searched, but nobody seems to be using all three of these dependencies. The application I'm porting is a set of Python modules and a few C++ functions. The Python code requires a fair bit of dependencies which are handled by building a Conda environment running Python 3.6. PCL and Boost.Python come into play because the library has C++ functions which use PCL which are then wrapped using Boost.Python to create a Python interface for the functions. I can get any 2/3 to work, but not all three together. I can provide the specific issues I face when I try each installation method if anybody is curious, but what I'm really wondering is if anybody else has successfully gotten these libraries to all work together on Ubuntu 16.04? I've seen people wrap PCL functions with Boost.Python, but the real kicker is that it all has to be done with Conda Python under the hood.
answer count: 0
tagged with: boost
type: Question
has comment: http://stackoverflow.com/comment/88535606
tagged with: point-cloud-library
tagged with: conda
score: 0

http://stackoverflow.com/q/50766976
tagged with: jupyter-notebook
favorite count: 0
has comment: http://stackoverflow.com/comment/88560003
has body: I'm a beginner in Tensor flow. I'm trying to feed my own data set by using tensor flow place holders. With a lot of research online I've figured out that using tf.data.DataSet is an ideal way to give our own data. But I'm just curious on how to solve the following issue:I'm using a glass identification data set with 10 independent variables and one dependent varible [https://archive.ics.uci.edu/ml/machine-learning-databases/glass/glass.data][1] here's a glimpse of my data: Id RI Na Mg Al Si K Ca Ba Fe Type count 213.000000 213.000000 213.000000 213.000000 213.000000 213.000000 213.000000 213.000000 213.000000 213.000000 213.000000 mean 108.000000 1.518353 13.406761 2.676056 1.446526 72.655023 0.499108 8.957934 0.175869 0.057277 2.788732 std 61.631972 0.003039 0.818371 1.440453 0.499882 0.774052 0.653035 1.426435 0.498245 0.097589 2.105130 min 2.000000 1.511150 10.730000 0.000000 0.290000 69.810000 0.000000 5.430000 0.000000 0.000000 1.000000 25% 55.000000 1.516520 12.900000 2.090000 1.190000 72.280000 0.130000 8.240000 0.000000 0.000000 1.000000 50% 108.000000 1.517680 13.300000 3.480000 1.360000 72.790000 0.560000 8.600000 0.000000 0.000000 2.000000 75% 161.000000 1.519150 13.830000 3.600000 1.630000 73.090000 0.610000 9.180000 0.000000 0.100000 3.000000 max 214.000000 1.533930 17.380000 3.980000 3.500000 75.410000 6.210000 16.190000 3.150000 0.510000 7.000000 Here's my code: r,c = data.shape n_inputs = c - 1 n_hidden1 = int(input('No. of nodes in hidden layer 1 \n')) n_hidden2 = int(input('No. of nodes in hidden layer 2 \n')) y_new = np.array(data['Type']-1) y_cat = to_categorical(y_new) n_outputs = y_cat.shape[1] #1.1) Using Place holders to define shape of the variables X = tf.placeholder(tf.float32, shape=(None, n_inputs), name="X") # We don't know no. of rows yet but we know the no. of columns given by n_inputs y= tf.placeholder(tf.int32, shape=(None), name="y") # 1.2) Using name scopes and creating each layer # A dense layer with sequential connections is cre…
type: UnansweredQuestion
tagged with: python
has title: How to use Tensorflow on our own data set
answer count: 0
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: neural-network
tagged with: deep-learning
downvote count: 0
score: 1

http://stackoverflow.com/comment/88660926
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50827626
type: QuestionComment
has text: What library are you using for the import, and what are you specifying as the delimiter?

http://stackoverflow.com/comment/107976994
type: AnswerComment
has text: `phd`'s comment in the actual question, solved my problem. Thanks
type: Comment
comment on: http://stackoverflow.com/a/51272019
score: 0

http://stackoverflow.com/comment/88438749
has text: `[x.split() for x in (s1, s2)]`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50715058
score: 2

http://stackoverflow.com/q/50767299
tagged with: python
has comment: http://stackoverflow.com/comment/88542411
has title: pandas.get_dummies converts float64
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88542536
type: Question
has answer: http://stackoverflow.com/a/50767707
has comment: http://stackoverflow.com/comment/88542441
has body: I'm using pandas.get_dummies to convert some of my categorical variables before using tpot. My problem is I have a continuous variable, time, for example, and it is being converted to categories even though it is a continuous variable. This doesn't seem to happen in all cases, but I can't figure out when it occurs. I tested the following: pd.isnull(my_dataframe).any() and all the categories say false print(type(features[0,5])) # the time category with my continuous variable and the output is &lt;class 'numpy.float64'&gt; However when I do df_dummies=pd.get_dummies(my_dataframe) df_dummies.columns It creates a column for each value of my time feature. Like this: 'Time (min)_2', 'Time (min)_3', 'Time (min)_4', 'Time (min)_5', 'Time (min)_6', 'Time (min)_10', 'Time (min)_15', 'Time (min)_16', 'Time (min)_20', 'Time (min)_25', 'Time (min)_30' Any ideas what could be wrong here?
has comment: http://stackoverflow.com/comment/88542169
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88542115

http://stackoverflow.com/comment/88531334
type: AnswerComment
has text: True. This was not intended and just resulted out of wanting to show the OP how to create an array in contrast to a list. So either just omit `res = np.zeros((20,200))`, or create an empty array and assign the values to it (as shown in my answer). Creating an empty array and assigning the values might be a tiny bit slower, BUT it makes it alot easier to find buggy calculations due to the given result shape.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50761025

http://stackoverflow.com/comment/88742346
type: QuestionComment
has text: Thanks for the hint. I was considering SO, since it might be tagged as [off topic](https://stats.meta.stackexchange.com/questions/5286/why-do-we-have-a-tensorflow-tag-if-questions-about-programming-are-off-topic?cb=1) in Cross Validated. Maybe I will ask there, too, if it remains unanswered
comment on: http://stackoverflow.com/q/50853136
type: Comment
score: 0

http://stackoverflow.com/q/50725476
tagged with: tkinter
has answer: http://stackoverflow.com/a/50726361
upvote count: 1
tagged with: python
downvote count: 1
has body: See pandas.read_excel(). I am creating a GUI with Tkinter that will automate the final scores for several characters. I am also fairly new to Tkinter. In my code, I am reading in several excel sheets that will be created into dataframes in order for me to do the appropriate calculations on each. One excel sheet that I will be reading in is an excel sheet that contains a list of characters that users of my code on my team can go in and edit/add new characters if need be. When they run the code, the analysis is updated with any edits/added characters. For this question, I will be using that as an example and call it filename. Ideally, I would like to create a browse button in Tkinter that will prompt the user to look for the excel file, then store the selected file in the variable filename for future use. My code will have pd.read_excel() embedded later, and I would like filename to be the excel file /io argument that will be read in. I am just wondering if this is possible. Looking at other attempts doesn't necessarily address what I am looking for either. This is also my first time using Tkinter as well, but here's sort of a draft (emphasis on draft!) of what I have so far: import tkinter as tk from tkinter import * class Automation: def __init__(self, master): self.master = master master.title("Test") self.label = Label(master, text="Welcome to the Score Automation.\nPlease select the ALC File containing all updated names.") self.label.pack() self.browse_button_characterlist = Button(master, text="Select File", command=self.askopenfile) self.browse_button_characterlist.pack() self.close_button = Button(master, text="Close", command=master.quit) self.close_button.pack() def askopenfile(self): root = tk.Tk() root.withdraw() filename = askopenfilename() print(filename) root = Tk() my_gui = Automation(root) root.mainloop() Filename is then stored as argument into pandas.read_excel() pd.read_excel(filename, usecols = "B", skiprows = range(0,4), skip_footer = 2) Any sugg…
type: AnsweredQuestion
score: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88460059
type: Question
accepted answer: http://stackoverflow.com/a/50726361
answer count: 1
has comment: http://stackoverflow.com/comment/88459549
has comment: http://stackoverflow.com/comment/88459249
tagged with: pandas
has comment: http://stackoverflow.com/comment/88459650
favorite count: 0
has title: Creating variable for argument io into pd.read_excel()

http://stackoverflow.com/comment/88663182
comment on: http://stackoverflow.com/a/50818567
has text: Yeah that worked. I couldn't make out from the documentation that AE title is an argument in the associate function, this makes a lot more sense. Thanks!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88413750
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50702150
score: 1
has text: `countplot` is a categorical plot. Category 0 is `736841.581944`, category 1 is `736842.457639` etc. So you cannot use a dateformatter on the axes which consists of `0,1,2,3 etc`. I suppose if you want to have dates on the axes you want a numeric bar plot? In that case use `plt.bar`.

http://stackoverflow.com/comment/98688951
type: AnswerComment
comment on: http://stackoverflow.com/a/50731254
type: Comment
score: 0
has text: what id set_index() throw "Index contains duplicate entries, cannot reshape". is there anyway around it?

http://stackoverflow.com/a/50796229
type: Answer
has body: Try this : print os.path.basename(filename) It will remove the path and give you the actual filename only. See Extract file name from path, no matter what the os/path format for more info.
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50796178
downvote count: 0
answers question: http://stackoverflow.com/q/50796178
type: AcceptedAnswer

http://stackoverflow.com/q/50775443
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Parse linked dataframes into json
score: 1
type: Question
downvote count: 0
favorite count: 0
tagged with: pandas
has body: I am looking for a way to parse these dataframes: Master: Name String Column_1 Column_2 0 Name_1 Value_1 Name_Other_Table_1 Name_Other_Table_2 1 Name_2 Value_2 Name_Other_Table_1 Name_Other_Table_2 Name_Other_Table_1: Name Sub_Columumn_1 Sub_Column_2 0 Name_1 Value_1_1 Name_Other_Table_3 1 Name_1 Value_1_2 Name_Other_Table_3 2 Name_2 Value_2_1 Name_Other_Table_3 3 Name_2 Value_2_2 Name_Other_Table_3 Name_Other_Table_2: Name Sub_Column_3 0 Name_1 A 1 Name_1 Z 2 Name_2 Z Name_Other_Table_3 Name Sub_Column_1 Sub_SubString 0 Name_1 Value_1_1 A 1 Name_1 Value_1_2 B Into a json that looks like this: [ { "Name": "Name_1", "String" : "Value_1", "Column_1": [ { "Sub_Columumn_1": "Value_1_1", "Sub_Sub_Column_1": [ { "Sub_SubString": "A" } ] }, { "Sub_Columumn_1": "Value_1_2", "Sub_Sub_Column_1": [ { "Sub_SubString": "B" } ] } ], "Column_2":[ { "Sub_Column_3": "A" }, { "Sub_Column_3": "Z" } ] },... A way to rephrase the question would be how do I get a hierarchical data structure out of a series of 'linked' tables? Originally this comes from an excel file and tables are linked via the name of the sheets.
answer count: 0

http://stackoverflow.com/q/50776076
answer count: 2
has comment: http://stackoverflow.com/comment/88559583
downvote count: 1
has title: Django 1 to Django 2 on_delete error
possible better answer: http://stackoverflow.com/a/63111357
has answer: http://stackoverflow.com/a/50776680
has answer: http://stackoverflow.com/a/63111357
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88559753
tagged with: workflow
favorite count: 0
has comment: http://stackoverflow.com/comment/88559377
type: Question
accepted answer: http://stackoverflow.com/a/50776680
has comment: http://stackoverflow.com/comment/88559538
has body: I believe this workflow was created for a previous Django version. Now when I am trying to upgrade it I get an error to add on_delete. Here is what I have done but it is still not working and I'm wondering what I am doing wrong. ORIGINAL class Task(AbstractEntity): request = ForeignKey(Request, related_name='tasks') assignee = ForeignKey(Group) updated_by = ForeignKey(User) activity_ref = CharField(max_length=100) status = CharField(verbose_name="Status", max_length=30, choices=TASK_STATUS) MY VERSION class Task(models.AbstractEntity): request = models.ForeignKey(Request, related_name='tasks', on_delete=models.CASCADE) assignee = ForeignKey(Group) updated_by = ForeignKey(User) activity_ref = CharField(max_length=100) status = CharField(verbose_name="Status", max_length=30, choices=TASK_STATUS) Then I get another error saying the model is not defined.
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88559588
upvote count: 3

http://stackoverflow.com/comment/88559353
comment on: http://stackoverflow.com/a/50776031
score: 0
has text: thanks for introducing str.ljust() I like your way of formatting title fields better, however your solution doesn't take into consideration that there might be 1 mode data or more than 2 --> .format(mode[0], mode[1])
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/95319932
score: 3
type: Comment
comment on: http://stackoverflow.com/a/54247498
has text: elaborate more on your answer.
type: AnswerComment

http://stackoverflow.com/a/50828419
has body: You need to drop the include() and just pass the urls directly: url(r'^dashboard/cod/', cod_app.urls), The urls property returns a 3-tuple, not a list of urlpatterns, and support for passing this to include() was dropped in Django 2.
type: Answer
has comment: http://stackoverflow.com/comment/88666621
score: 4
accepted answer of: http://stackoverflow.com/q/50818553
upvote count: 4
answers question: http://stackoverflow.com/q/50818553
type: AcceptedAnswer
downvote count: 0

jupyter
tags question: http://stackoverflow.com/q/50714931
tags question: http://stackoverflow.com/q/50774607
type: Tag
tags question: http://stackoverflow.com/q/50833685
tags question: http://stackoverflow.com/q/50785665
tags question: http://stackoverflow.com/q/50755706
tags question: http://stackoverflow.com/q/50750125
tags question: http://stackoverflow.com/q/50803679
tag name: jupyter
tags question: http://stackoverflow.com/q/50826136
tags question: http://stackoverflow.com/q/50717492
tags question: http://stackoverflow.com/q/50854931
tags question: http://stackoverflow.com/q/50729806
tags question: http://stackoverflow.com/q/50722270
tags question: http://stackoverflow.com/q/50816320

http://stackoverflow.com/q/50831551
tagged with: differential-evolution
has answer: http://stackoverflow.com/a/51003128
has answer: http://stackoverflow.com/a/50872377
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/8967055
possible better answer: http://stackoverflow.com/a/57874102
has body: I'm trying to model a biochemical process, and I structured my question as an optimization problem, that I solve using differential_evolution from scipy. So far, so good, I'm pretty happy with the implementation of a simplified model with 15-19 parameters. I expanded the model and now, with 32 parameters, is taking way too long. Not totally unexpected, but still an issue, hence the question. I've seen: - an almost identical question for R Parallel differential evolution - and a github issue https://github.com/scipy/scipy/issues/4864 on the topic but it would like to stay in python (the model is within a python pipeline), and the pull request did not lead to and officially accepted solution yet, although some options have been suggested. Also, I can't parallelize the code within the function to be optimised because is a series of sequential calculations each requiring the result of the previous step. The ideal option would be to have something that evaluates some individuals in parallel and return them to the population. Summing up: - Is there any option within scipy that allows parallelization of differential_evolution that I dumbly overlooked? (Ideal solution) - Is there a suggestion for an alternative algorithm in scipy that is either (way) faster in serial or possible to parallelize? - Is there any other good package that offers parallelized differential evolution funtions? Or other applicable optimization methods? - Sanity check: am I overloading DE with 32 parameter and I need to radically change approach? PS I'm a biologist, formal math/statistics isn't really my strenght, any formula-to-english translation would be hugely appreciated :) PPS As an extreme option I could try to migrate to R, but I can't code C/C++ or other languages.
tagged with: python
answer count: 4
tagged with: parallel-processing
type: AnsweredQuestion
tagged with: mathematical-optimization
has answer: http://stackoverflow.com/a/67376550
score: 6
has title: parallel/multithread differential evolution in python
tagged with: scipy
accepted answer: http://stackoverflow.com/a/51003128
type: Question
has answer: http://stackoverflow.com/a/57874102
upvote count: 6

http://stackoverflow.com/a/50746714
answers question: http://stackoverflow.com/q/50746629
has comment: http://stackoverflow.com/comment/88501873
upvote count: 1
type: Answer
downvote count: 0
has body: Probably something like this as per PEP8 if props.getProperty("app.auth.idp.strategy") == '' \ or props.getProperty("app.auth.idp.strategy") == 'saml/simpleSAMLphp' \ and PROXYING_MECHANISM == "ngrok": IDP_STRATEGY = "saml/simpleSAMLphp" elif props.getProperty("app.auth.idp.strategy") == 'saml/gsuite': IDP_STRATEGY = "saml/gsuite" elif props.getProperty("app.auth.idp.strategy") == 'saml/remote-simpleSAMLphp': IDP_STRATEGY = "saml/remote-simpleSAMLphp" else: IDP_STRATEGY = "saml"
score: 1
has comment: http://stackoverflow.com/comment/88501750
accepted answer of: http://stackoverflow.com/q/50746629
type: AcceptedAnswer

http://stackoverflow.com/comment/88495321
has text: FWIW: `'+'.join("'remap%s'" % i for i in range(1, 32))`. I'm really more worried what you're going to do with that odd string though…
comment on: http://stackoverflow.com/q/50743746
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50881584
type: Answer
score: 67
upvote count: 67
has comment: http://stackoverflow.com/comment/131008743
has body: This might not be obvious, but pd.Series.isin uses O(1)-look up per element. After an analysis, which proves the above statement, we will use its insights to create a Cython-prototype which can easily beat the fastest out-of-the-box-solution. Let's assume that the "set" has n elements and the "series" has m elements. The running time is then: T(n,m)=T_preprocess(n)+m*T_lookup(n) For the pure-python version, that means: T_preprocess(n)=0 - no preprocessing needed T_lookup(n)=O(1) - well known behavior of python's set results in T(n,m)=O(m) What happens for pd.Series.isin(x_arr)? Obviously, if we skip the preprocessing and search in linear time we will get O(n*m), which is not acceptable. It is easy to see with help of a debugger or a profiler (I used valgrind-callgrind+kcachegrind), what is going on: the working horse is the function __pyx_pw_6pandas_5_libs_9hashtable_23ismember_int64. Its definition can be found here: In a preprocessing step, a hash-map (pandas uses khash from klib) is created out of n elements from x_arr, i.e. in running time O(n). m look-ups happen in O(1) each or O(m) in total in the constructed hash-map. results in T(n,m)=O(m)+O(n) We must remember - the elements of numpy-array are raw-C-integers and not the Python-objects in the original set - so we cannot use the set as it is. An alternative to converting the set of Python-objects to a set of C-ints, would be to convert the single C-ints to Python-object and thus be able to use the original set. That is what happens in [i in x_set for i in ser.values]-variant: No preprocessing. m look-ups happen in O(1) time each or O(m) in total, but the look-up is slower due to necessary creation of a Python-object. results in T(n,m)=O(m) Clearly, you could speed-up this version a little bit by using Cython. But enough theory, let's take a look at the running times for different ns with fixed ms: We can see: the linear time of preprocessing dominates the numpy-version for big ns. The version with conversion …
accepted answer of: http://stackoverflow.com/q/50779617
has comment: http://stackoverflow.com/comment/88905795
answers question: http://stackoverflow.com/q/50779617
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88769039

http://stackoverflow.com/a/50785252
answers question: http://stackoverflow.com/q/50785197
has body: You can do this with NumPy by replacing unwanted numbers with NaN: import numpy as np df = pd.DataFrame(np.random.randint(-5, 6, (5, 5))) arr = df.values.astype(float) np.fill_diagonal(arr, np.nan) # exclude diagonal arr[arr &lt;= 0] = np.nan # filter for &gt; 0 print(arr) [[nan 2. 4. nan nan] [nan nan nan nan 3.] [nan nan nan nan nan] [ 2. nan 3. nan 4.] [nan 4. 1. nan nan]] nan_filter = ~np.isnan(arr) # aggregate indices with values res = np.hstack((np.argwhere(nan_filter), arr[nan_filter][:, None])) print(res) [[0. 1. 2.] [0. 2. 4.] [1. 4. 3.] [3. 0. 2.] [3. 2. 3.] [3. 4. 4.] [4. 1. 4.] [4. 2. 1.]]
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88579882
has comment: http://stackoverflow.com/comment/88578250
score: 2
downvote count: 0

http://stackoverflow.com/comment/110140332
type: Comment
comment on: http://stackoverflow.com/a/50939211
score: 0
type: AnswerComment
has text: @Parfait - Is it possible to add tags to ` `s and ` `s of the table rendered using `df.to_html()`?

http://stackoverflow.com/comment/88559552
has text: I honestly don't know why it behave like that.. maybe i made a mistake somewhere but I can still 'fix' it by substracting 1 to the value I get, if needed..
comment on: http://stackoverflow.com/a/50775978
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50823377
has body: You add tags while doing volume.create_snapshot replace if volume.create_snapshot(VolumeId=volume.volume_id, Description=description): print("Snapshot created with description [%s]" % description) with if volume.create_snapshot( VolumeId=volume.volume_id, Description=description, TagSpecifications=[ { 'ResourceType': 'snapshot', 'Tags': [ { 'Key': 'Owner', 'Value': 'RaGe' }, { 'Key': 'date', 'Value': datetime.datetime.now().strftime("%Y-%m-%d") } ] }, ] ): print("Snapshot created with description [%s]" % description) reference This results in:
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88657307
accepted answer of: http://stackoverflow.com/q/50822985
has comment: http://stackoverflow.com/comment/88662401
answers question: http://stackoverflow.com/q/50822985
type: Answer
has comment: http://stackoverflow.com/comment/88654879
score: 3
has comment: http://stackoverflow.com/comment/88662483
upvote count: 3
has comment: http://stackoverflow.com/comment/88655203

http://stackoverflow.com/comment/88480271
type: Comment
comment on: http://stackoverflow.com/q/50736287
has text: No, it's in a function called from a view, but not in the view.
score: 0
type: QuestionComment

http://stackoverflow.com/a/50779434
answers question: http://stackoverflow.com/q/50779391
upvote count: 2
type: Answer
score: 2
has body: Oh, this is a classic common error: while instruction_yes_no.lower() != "y" or "n": It's the same as while (instruction_yes_no.lower() != "y") or True: You want this instead: while instruction_yes_no.lower() != "y" and instruction_yes_no.lower() != "n": Or maybe this, it's shorter :) while instruction_yes_no.lower() not in ["y", "n"]:
downvote count: 0

http://stackoverflow.com/comment/88504787
has text: I am unable to convert your timestamps to datetime because of the hh:mm:ss are not valid. If you have them as datetimes, there is a much easier way to solve this.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50748560
score: 0

http://stackoverflow.com/q/50821588
answer count: 3
upvote count: 1
has title: python error message: TypeError: missing 1 required positional argument: 'self'
downvote count: 1
possible better answer: http://stackoverflow.com/a/50821724
favorite count: 0
has answer: http://stackoverflow.com/a/50821724
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88648368
has comment: http://stackoverflow.com/comment/88648420
has comment: http://stackoverflow.com/comment/88648511
accepted answer: http://stackoverflow.com/a/50821719
has comment: http://stackoverflow.com/comment/88648417
type: Question
has body: I'm trying to use a class, but I have this error: TypeError: search() missing 1 required positional argument: 'self' This is my code: class School: def search(self): ... # do some stuff harva = School() School.search()
has answer: http://stackoverflow.com/a/50821719
has answer: http://stackoverflow.com/a/54772924
score: 0

http://stackoverflow.com/comment/88616674
comment on: http://stackoverflow.com/a/50804894
type: Comment
has text: @ckuri That sounds exactly equivalent to [`add_done_callback`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Future.add_done_callback).
score: 1
type: AnswerComment

http://stackoverflow.com/q/50752844
has answer: http://stackoverflow.com/a/50752948
has body: I am trying to get the number of the files in a certain directory, but I want it to count only text file because I have another directory in the accounts and DS. Store file. What should I modify to only get the number of text files? list = os.listdir("data/accounts/") number_files = len(list) print(number_files)
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50752911
has answer: http://stackoverflow.com/a/50753101
linked to: http://stackoverflow.com/q/1320731
type: Question
has title: python count number of text file in certain directory
has answer: http://stackoverflow.com/a/50752899
score: 0

http://stackoverflow.com/a/72099912
type: Answer
has body: I had a similar problem with the mahotas module, which was because of the version. Un-installed and re-installed an older version resolved the problem
answers question: http://stackoverflow.com/q/50710203
score: 0

django-queryset
tags question: http://stackoverflow.com/q/50788123
tags question: http://stackoverflow.com/q/50808053
tags question: http://stackoverflow.com/q/50802451
tag name: django-queryset
tags question: http://stackoverflow.com/q/50793243
tags question: http://stackoverflow.com/q/50729034
type: Tag

http://stackoverflow.com/comment/88611892
type: AnswerComment
type: Comment
has text: @kwunlyou: If you found the answer to be helpful, you can [accept it](https://stackoverflow.com/help/someone-answers).
comment on: http://stackoverflow.com/a/50802283
score: 1

http://stackoverflow.com/comment/88618375
comment on: http://stackoverflow.com/q/50806104
has text: For a quick-and-dirty answer, assuming you have the outer span in a variable named `span`, you probably just want to iterate over [`span.stripped_strings`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#strings-and-stripped-strings), which should give you `1.338`, then `241`, then `USD`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88476634
score: 0
comment on: http://stackoverflow.com/q/50734412
has text: It would be helpful to know the desired output and what you want to do with those Jaccard coefficients.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88721802
type: QuestionComment
comment on: http://stackoverflow.com/q/50854898
score: 0
has text: I updated now! There are 3024 items in the table. The plot is showing with interval(0,500,1000 etc as you see) but I would like to get the ids(1,2,3,4...3024) and also for the y axis to see the items in cart
type: Comment

http://stackoverflow.com/q/50847329
answer count: 3
has answer: http://stackoverflow.com/a/50847424
favorite count: 0
has comment: http://stackoverflow.com/comment/88700308
has answer: http://stackoverflow.com/a/50847443
accepted answer: http://stackoverflow.com/a/50847441
has comment: http://stackoverflow.com/comment/88724425
tagged with: python
possible better answer: http://stackoverflow.com/a/50847424
tagged with: dictionary
upvote count: 3
has title: Replacing dictionary keys for values in another dictionary
downvote count: 1
score: 2
type: AnsweredQuestion
has body: I have a list of dictionaries with information I'd like to replace under the keys of each dictionary. So, I'm thinking of iterating through each dictionary and replacing the values. I have another dictionary with the values I'd like to replace as keys and the values which should be the final ones as values. It goes like this: listOfDicts = [{'value_1' : 'A', 'value-2' : 'B', 'valu&amp;_3' : 'C'}, {'value-1' : 'D', 'value_2' : 'E', 'value-3' : 'F'}, {'value_1' : 'G', 'value_2' : 'H', 'value_3' : 'I'}] Then I have another dictionary to use as basis for fixing this information: fixer = {'value-2' : 'value_2', 'value&amp;_3' : 'value_3', 'value-3' : 'value_3', ...} How could I make this replacement? - Edit: The desired output would be somethink like this: listOfDicts = [{ 'value_1' : 'A', 'value_2' : 'B', 'value_3' : 'C'}, {'value_1' : 'D', 'value_2' : 'E', 'value_3' : 'F'}, ...}
has answer: http://stackoverflow.com/a/50847441
has comment: http://stackoverflow.com/comment/88698187
type: Question

http://stackoverflow.com/a/50754911
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50754724
has comment: http://stackoverflow.com/comment/88517724
has body: Take just the lower triangular matrix if you only need a distinct set a = [1,2,10,20] [(a[i], a[j+i+1]) for i in range(len(a)) for j in range(len(a[i+1:]))] [(1, 2), (1, 10), (1, 20), (2, 10), (2, 20), (10, 20)]
type: Answer
has comment: http://stackoverflow.com/comment/88517624
has comment: http://stackoverflow.com/comment/88517646
score: 3

http://stackoverflow.com/a/50746397
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50746194
has body: If you're using a metaclass, that means you're changing the definition of a class, which indirectly affects the attributes of instances of that class. Assuming you actually want to do this: You're creating a custom __init__ method. As with normal instantiation, __init__ is called on an object that has been already created. Generally when you're doing something meaningful with metaclasses, you'll want to add to the class's dict before instantiation, which is done in the __new__ method to avoid issues that may come up in subclassing. It should look something like this: class D(type): def __new__(cls, name, bases, dct): for hook in R.registered_hooks: dct[hook.__qualname__] = hook return super(D, cls).__new__(cls, name, bases, dct) This will not modify the __dict__ of instances of that class, but attribute resolution for instances also looks for class attributes. So if you add foo as an attribute for E in the metaclass, E().foo will return the expected value even though it's not visible in E().__dict__.
score: 2

http://stackoverflow.com/a/50728943
accepted answer of: http://stackoverflow.com/q/50728329
has comment: http://stackoverflow.com/comment/88467104
score: 0
answers question: http://stackoverflow.com/q/50728329
has comment: http://stackoverflow.com/comment/88466218
has body: Let's say 'OK' is True and 'down' is False. Then you can do something like: string = "SomeString" variable = "SomeVariable" myList = [string[i]==variable[i] for i in range(min(len(string),len(variable)))] print(myList) And then you'll have a wanted list(assuming I understand what you want)
type: Answer
has comment: http://stackoverflow.com/comment/88465991
has comment: http://stackoverflow.com/comment/88467056
has comment: http://stackoverflow.com/comment/88467605
has comment: http://stackoverflow.com/comment/88467901
type: AcceptedAnswer

http://stackoverflow.com/q/50787003
has title: Python read from buffer
type: Question
has comment: http://stackoverflow.com/comment/88581024
has comment: http://stackoverflow.com/comment/88605570
score: 0
linked to: http://stackoverflow.com/q/13207678
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/88581275
has comment: http://stackoverflow.com/comment/88616476
answer count: 0
type: UnansweredQuestion
has body: i want a getch/cin like function in python that wont interrupt the program from running (wanna make flappyBird) return pressed key ascii code if anything pressed or returns nothing or a default value if no key pressed i am using getch but it waits till a key press while (1): speed = speed - gravity pressed_key = getch.getch() if ( pressed_key == ' ' ): speed = speed + force pressed_key = 'x' elif ( pressed_key == 'q' ): sys.exit() print (speed) sleep(sleep_time) this will be later a frame of the game xD

http://stackoverflow.com/comment/88622793
type: Comment
comment on: http://stackoverflow.com/a/50802077
type: AnswerComment
has text: Hi Lost , no luck , still same error. can you write full code for me please ?
score: 0

http://stackoverflow.com/comment/88668770
score: 0
type: Comment
type: QuestionComment
has text: I guess, what I'm trying to say is... imagine someone already quoted and escaped their arguments the way you did. I need to take that in and pass that on.
comment on: http://stackoverflow.com/q/50832080

http://stackoverflow.com/comment/88693660
has text: Does database file the same in both systems? Is there no exception?
comment on: http://stackoverflow.com/q/50844971
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88511844
type: QuestionComment
score: 2
has text: *Personally*, I've rarely found testing the internals of a method interesting or worth the time of building the test, and testing only the output (possibly with more robust test cases) is sufficient. This is especially true in the case that the method internals might be later refactored rendering your tests a waste.
comment on: http://stackoverflow.com/q/50751924
type: Comment

http://stackoverflow.com/comment/88610435
score: 0
type: AnswerComment
has text: Oh! It worked! Now I loaded the html into firefox how can I send a search query to google.com with this python?
type: Comment
comment on: http://stackoverflow.com/a/50801294

http://stackoverflow.com/q/50850796
has answer: http://stackoverflow.com/a/50851539
has answer: http://stackoverflow.com/a/50851529
score: -1
downvote count: 1
has body: I try a python code for signature recognition, and there is an import ffnet module (from ffnet import mlgraph, ffnet), but I got an error when I run it. The error is: ModuleNotFoundError: No module named 'ffnet' I have install the module, but still got that error Help me to fix this :)
type: Question
answer count: 2
upvote count: 0
has title: No module named 'ffnet' in Python
favorite count: 0
tagged with: installation
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88651326
has text: can you please share with us your input data?
comment on: http://stackoverflow.com/q/50822461
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50710412
has title: How to avoid select queries in loop or make it faster?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88430093
downvote count: 0
score: 1
tagged with: sqlalchemy
type: Question
has body: This part of my program executes too slow. There are measurements: ELEMENTS (pairs) ELAPSED TIME, s 12 0.31 4692 126.24 16770 462.55 I think, the problem is that I am making queries in loop or SQL query is too complicated. But I don't know how to avoid this situation. def set_major_minor_support(self, session, pairs): query = """ SELECT count_table.current_support::NUMERIC / receipt_count_table.receipt_count::NUMERIC FROM (SELECT COUNT(*) AS current_support FROM (SELECT cartitem_id, receipt_id FROM cartitem WHERE product_id = {major_id}) AS A INNER JOIN (SELECT cartitem_id, receipt_id FROM cartitem WHERE product_id = {minor_id}) AS B ON A.receipt_id = B.receipt_id ) AS count_table, (SELECT COUNT(*) AS receipt_count FROM receipt) AS receipt_count_table; """ for pair in pairs: major_id = pair.major_id minor_id = pair.minor_id current_query = query.format(major_id=major_id, minor_id=minor_id) result = session.execute(current_query).fetchone()[0] pair.support_major_minor = result print(pair.major_id, pair.support_major_minor) session.commit() return pairs If it is important, 'cartitem' has 100 000 rows.
tagged with: postgresql
has answer: http://stackoverflow.com/a/50710666
tagged with: sql
upvote count: 1
accepted answer: http://stackoverflow.com/a/50710666
has comment: http://stackoverflow.com/comment/88429852
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/a/50796539
has comment: http://stackoverflow.com/comment/88604869
has comment: http://stackoverflow.com/comment/88601806
has comment: http://stackoverflow.com/comment/88604391
has comment: http://stackoverflow.com/comment/88601633
has comment: http://stackoverflow.com/comment/88605447
score: 0
has comment: http://stackoverflow.com/comment/88603888
has comment: http://stackoverflow.com/comment/88612354
type: Answer
has comment: http://stackoverflow.com/comment/88633129
answers question: http://stackoverflow.com/q/50796357
has comment: http://stackoverflow.com/comment/88604452
has body: Use numpy.select with assign repeating conditions to variables like m1 for better performance: m1 = capacity1['value'] &lt; 80 m2 = capacity1['metric'].isin(['ENT_CORE','UTIL_CPU','ENT_CPU']) m3 = capacity1['metric'].isin(['FS_CACHE','FREE','PINNED','PAGE_OUT','PAGE_SPACE']) m4 = capacity1['metric'].isin(['REC_BYTES','TRANS_BYTES','REC_BYTESS','TRANS_BYTESS']) condlist = [m1 &amp; m2, m1 &amp; m3, m1 &amp; m4] choicelist = ["CPU", "MEMORY", "NETWORK"] capacity1['root_cause'] = np.select(condlist, choicelist, default="OTHER")
has comment: http://stackoverflow.com/comment/88611699

http://stackoverflow.com/a/50830175
has comment: http://stackoverflow.com/comment/88696744
has comment: http://stackoverflow.com/comment/88699098
has body: Use: df = (df.set_index('c') .stack() .str.split('\s+\+\s+', expand=True) .stack() .unstack(1) .ffill() .reset_index(level=1, drop=True) .reset_index() .reindex(columns=['a','b','c']) ) print (df) a b c 0 A1 L700 6 1 A3 L800 6 2 B4 G700 7 3 A4 G700 7 4 D2 G700 7 5 C2 L2600 8 6 C2 L900 8 Explanation: First set_index for split columns for split Reshape by stack for Series with MultiIndex Create DataFrame per rows by split by regex - nees escape + and for one or more whitespaces use \s+ Reshape by stack and unstack for second level to columns Forward fill NaNs by ffill Data cleaning by reset_index If order of columns important add reindex
accepted answer of: http://stackoverflow.com/q/50829764
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50829764
has comment: http://stackoverflow.com/comment/88665039
has comment: http://stackoverflow.com/comment/88699205
type: Answer
has comment: http://stackoverflow.com/comment/88699574
score: 1
has comment: http://stackoverflow.com/comment/88665186
upvote count: 1

http://stackoverflow.com/a/50757138
has body: I'd just assign the value to a variable on a previous line, if it would be the same from all three calls. As Hearner already wrote in the comments, your example is slightly confusing since you're not assigning the value of the ternary to anything, implying that fooB(x) is some function with side effects that you want to call, but not assign to a variable. In that case using the ternary operator isn't very pretty, I think. In the case that fooB(fooA()) returns some value you want to assign if the comparison is true, or else assign fooA(), then a = fooA() b = fooB(a) if a == bar else a is surely the way to go and not particularly inelegant. In the case that fooB is some function with side effects which you only want to call if the comparison is true, you could write e.g. a = fooA() a == bar and fooB(a) but not everyone likes that idiom so a = fooA() if a == bar: fooB(a) might be preferrable…
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50756723
type: Answer
downvote count: 0

data-fitting
tags question: http://stackoverflow.com/q/50822962
type: Tag
tag name: data-fitting

http://stackoverflow.com/comment/88507967
score: 0
type: QuestionComment
has text: @ThePoetCoder. The `limit=3` is exactly what I need. If there's lt 3 it fills up to how ever many there are
type: Comment
comment on: http://stackoverflow.com/q/50750030

http://stackoverflow.com/comment/88522932
score: 0
has text: Thank you now it works
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50754756

http://stackoverflow.com/comment/88631395
score: 0
comment on: http://stackoverflow.com/a/50812735
type: Comment
has text: @VasyaPravdin - What about my solution? Same error?
type: AnswerComment

http://stackoverflow.com/comment/88603490
comment on: http://stackoverflow.com/q/50798004
score: 0
type: Comment
has text: My actual problem related to the payment system. When I send a request(a single request with my payment related data ) to Third party payment. The third party provide 2 response 1) Instant response in my view (my_view) `i want to hold my_view until the second response not change the data.paymnet_status object field true of false` 2) Second in 3 min but different URL (This response will change `data.paymnet_status field value true or false`) In second response view when i try to get data id=20 its show object not found
type: QuestionComment

http://stackoverflow.com/comment/88579959
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50786529
has text: Yes, here it is: https://pastebin.com/bBUpb6cq

http://stackoverflow.com/comment/88630448
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50812347
has text: dears, thanks, but I cannot delete NaN, use dropna , thanks a lot !

http://stackoverflow.com/a/50821069
has comment: http://stackoverflow.com/comment/88647456
score: 14
has comment: http://stackoverflow.com/comment/88647484
accepted answer of: http://stackoverflow.com/q/50821008
downvote count: 0
has body: You need to break an internal Pandas security mechanism - aligning by index, which takes care of the data consistency. So assigning 1D Numpy array or a vanilla Python list would do the trick, because both of them don't have an index, so Pandas can't do alignment: df['B'] = df['B'].sort_values(ascending=False).values or df['B'] = df['B'].sort_values(ascending=False).tolist() both yield: In [77]: df Out[77]: A B 0 1 8 1 2 6 2 3 5 3 4 1
has comment: http://stackoverflow.com/comment/88648124
upvote count: 14
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50821008

http://stackoverflow.com/q/50827435
type: UnansweredQuestion
tagged with: h2o
type: Question
has body: I have successfully installed h2o package using pip. But I am having a weird problem when I try to import it using windows cmd it works well but it fails when I try to do it through anaconda prompt command, jyputer or Spyder ? I tried to restart them and run the command but still having the same problem. See this screenshoot below :
tagged with: python
has title: import h2o fails on anaconda cmd but works on windows cmd ?
score: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50827748
answer count: 1

http://stackoverflow.com/comment/88683627
score: 1
comment on: http://stackoverflow.com/q/50839949
type: QuestionComment
has text: you run your command prompt as admin and use python there
type: Comment

http://stackoverflow.com/q/50829011
tagged with: python
has answer: http://stackoverflow.com/a/50829073
accepted answer: http://stackoverflow.com/a/50829073
has answer: http://stackoverflow.com/a/50829065
type: AnsweredQuestion
type: Question
tagged with: debugging
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88662614
possible better answer: http://stackoverflow.com/a/50829065
tagged with: runtime-error
has title: Kindly help me debug this python program, with list iteration error
has body: Question : To find the percentage of 2 sentences matching. If 100%, Print "Exact Match!" Ignore the difference of 1 character between any 2 words being checked. (1 character error margin) Program : from difflib import SequenceMatcher def difWord(s1, s2): m = len(s1) n = len(s2) if abs(m - n) &gt; 1: return false count = 0 correct = 0 i = 0 j = 0 while i &lt; m and j &lt; n: if s1[i] != s2[j]: count+=1 if count==1: return true def seqMatch(a,b): rat = SequenceMatcher(None,a,b).ratio() if rat==1 : print("Exact Match!") else : print(rat*100) splitted1 = a.split() splitted2 = b.split() c=0 for x,y in splitted1.iteritems(),splitted2.iteritems() : if difWord(x,y) : c+=1; per = (count*100)/4 print(per) if __name__ == "__main__": a = "He is a boy" b = "She is a girl" c = "He is a boy" seqMatch(a,b) Error : Traceback (most recent call last): File "C:\Users\eidmash\Documents\Demo-Project\Day0.py", line 59, in &lt;module&gt; seqMatch(a,c) File "C:\Users\eidmash\Documents\Demo-Project\Day0.py", line 43, in seqMatch for x,y in splitted1.iteritems(),splitted2.iteritems() : AttributeError: 'list' object has no attribute 'iteritems'

http://stackoverflow.com/a/58792474
downvote count: 0
score: 13
has body: UPDATE: Use tf.data.experimental.cardinality(dataset) - see here. In case of tensorflow datasets you can use _, info = tfds.load(with_info=True). Then you may call info.splits['train'].num_examples. But even in this case it doesn't work properly if you define your own split. So you may either count your files or iterate over the dataset (like described in other answers): num_training_examples = 0 num_validation_examples = 0 for example in training_set: num_training_examples += 1 for example in validation_set: num_validation_examples += 1
upvote count: 13
answers question: http://stackoverflow.com/q/50737192
type: Answer

http://stackoverflow.com/q/50710297
tagged with: python
tagged with: opencv
upvote count: 0
downvote count: 1
type: Question
has body: How can I group the pixels with the same intensity or similar intensity in opencv Python. I am asked to find these pixels and connect the disconnected pixels with same intensities.
has comment: http://stackoverflow.com/comment/88430819
score: -1
has answer: http://stackoverflow.com/a/50710563
answer count: 1
has title: how to group the same or similar pixels in an image
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50789094
has comment: http://stackoverflow.com/comment/88585047
tagged with: cloud
has comment: http://stackoverflow.com/comment/88584730
has comment: http://stackoverflow.com/comment/88584537
linked to: http://stackoverflow.com/q/11407349
tagged with: amazon-web-services
has body: How do organizations plan to deploy/migrate their windows application in cloud? Assume the database is MySQL and backend in flask, PyQT as the frontend, how would one migrate? To get an idea of software, think of a payroll app created with Visual Basics.... Thanks!
score: 0
has title: Way to migrate windows app in cloud?
tagged with: migration
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: web-services
type: Question

http://stackoverflow.com/a/50857691
score: 0
answers question: http://stackoverflow.com/q/50832896
has body: You should not be calling subproccess the way you are doing most fundamentally because you are creating a security hole. A command could be passed to the endpoint you describe by making calling your endpoint with something like /ImageClassification/image.png;sudo rm -rf / or worse. To begin with, use the script instead of using a subprocess. Details depend on what is inside scripts.label_image but I guess it should look something like import scripts.label_image from flask import Flask, request from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class ImageClassification(Resource): def get(self, input_image): result = label_image( graph="tf_files/optimized_graph.pb", image=input_image ) return {'data': result} api.add_resource(ImageClassification, '/ImageClassification/&lt;input_image&gt;') if __name__ == '__main__': app.run() this assumes that the script label_image is a function of the form def label_image(graph, image): #... does stuff return result You might have to move some stuff from "D:/LH_data/LH_tensorflow/tensorflow-for-poets-2/" to your project folder so be able to import it in your flask application.
type: Answer

http://stackoverflow.com/comment/88564521
has text: Pywikibot is definitely the easiest/most versatile way, figuring out your problems with it might be easier. Most other API clients ([mwapi](https://pythonhosted.org/mwapi/) is also a nice one) just make it easy to send requests to the API but leave it to you to put together the request. So you'd have to look at the [docs](https://www.mediawiki.org/wiki/API:Edit) or the [API sandbox](https://en.wikipedia.org/wiki/Special:ApiSandbox).
comment on: http://stackoverflow.com/q/50724570
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88489172
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50723327
has text: Out: pandas.core.frame.DataFrame

http://stackoverflow.com/comment/88636288
comment on: http://stackoverflow.com/q/50815151
type: QuestionComment
score: 2
has text: As for passing content to a specific frame, I assume when you want to pass the data you know which one it is to be passed to - why not access the frame from the dictionary and don't call tkraise if you don't want to bring it to foreground?
type: Comment

http://stackoverflow.com/q/50760792
has answer: http://stackoverflow.com/a/50765618
type: Question
linked to: http://stackoverflow.com/q/3461869
tagged with: python
tagged with: plot
score: 0
tagged with: matplotlib
tagged with: linear-algebra
accepted answer: http://stackoverflow.com/a/50765618
tagged with: numpy
has title: Plotting a plane and its normal
has body: I have the normal of a plane and a point lying on it. I am trying to plot both of these out but I don't think this is coming out correctly and I cannot figure out why. Here is my code. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D point = np.array([1309.66102863, -531.22959263, 341.89779288]) normal = np.array([ 80.60165306, -32.69394323, 21.04172506]) # a plane is a*x+b*y+c*z+d=0 # [a,b,c] is the normal. Thus, we have to calculate # d and we're set d = -point.dot(normal) # create x,y xx, yy = np.meshgrid(range(1200,1400), range(-600,-400)) # calculate corresponding z z = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2] # plot the surface plt3d = plt.figure().gca(projection='3d') plt3d.plot_surface(xx, yy, z, alpha=0.2) plt3d.plot([point[0], point[0]+normal[0]], [point[1], point[1]+normal[1]], [point[2], point[2]+normal[2]]) plt.show() I modified it from this post. The result that I am getting looks like this - Clearly the normal is not perpendicular to the plane. However sometimes it works though, for example when I set point = np.array([1, 2, 3]) normal = np.array([1, 1, 2]) The plot that I am getting is Clearly this is much better. How is it not working in the first case?
type: AnsweredQuestion
answer count: 1

http://stackoverflow.com/comment/88623825
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50808799
has text: That's not the actual problem, that is a part of your solution.
type: QuestionComment

http://stackoverflow.com/comment/140190530
comment on: http://stackoverflow.com/a/63675145
type: AnswerComment
type: Comment
has text: Note that the trailing slash is important. The pattern `**` returns both files and directories in [Python 3.13 and newer](https://docs.python.org/3.13/library/pathlib.html#pattern-language).
score: 0

http://stackoverflow.com/comment/88655856
type: Comment
comment on: http://stackoverflow.com/a/50812426
score: 0
type: AnswerComment
has text: I don't think using `update_or_create` is appropriate here. The purpose of optimistic locking is to avoid overwriting existing entries (e.g. on version mismatch) not to create new ones when there's a mismatch.

http://stackoverflow.com/q/50762583
tagged with: python
type: AnsweredQuestion
tagged with: web-scraping
type: Question
has title: My Folium does not output anything, just a blank image
has answer: http://stackoverflow.com/a/50778340
score: 0
answer count: 1
has body: In the first image, I have a map when I enter a certain range of numbers. As you can see on the second map, it maps out blank. I tried out different range and some of them crashes and outputs a blank map. For example, 300th address does not work even if I put the range from 299 to 301 and 450 does not work either. There are certain addresses block me from mapping it out. I already set the data limit to max through terminal as well.
has comment: http://stackoverflow.com/comment/88563355
has comment: http://stackoverflow.com/comment/88532911
accepted answer: http://stackoverflow.com/a/50778340

http://stackoverflow.com/comment/88510911
score: 1
type: QuestionComment
has text: This question is too general and needs a lot of information you haven't provided. Curve fitting method really depends on the nature of your data and how the results will be used.
comment on: http://stackoverflow.com/q/50751520
type: Comment

http://stackoverflow.com/q/50851359
linked to: http://stackoverflow.com/q/9163940
has comment: http://stackoverflow.com/comment/88706525
has comment: http://stackoverflow.com/comment/88705525
has comment: http://stackoverflow.com/comment/88705749
has answer: http://stackoverflow.com/a/50851586
has title: Python @property setter not setting from instance call
downvote count: 0
has comment: http://stackoverflow.com/comment/88705524
tagged with: python-object
type: Question
tagged with: getter-setter
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1337935
has comment: http://stackoverflow.com/comment/88705962
has body: I have a class (simplified view): class Record(): OrderStatusMapping = dict(zip(['0', '1', '2'], ['NEWO', 'PARF', 'FILL'])) def __init__(self): self._OrderStatus = None @property def OrderStatus(self): return self.OrderStatusMapping.get(self._OrderStatus) @OrderStatus.setter def OrderStatus(self, value): self._OrderStatus = value Now this class is called from a different module and used as below: from core.record import Record r = Record() r.OrderStatus = '2' For some reason however when I later call r.OrderStatus call it returns '2' not 'FILL'. Debugging the variables in VisualStudio I can see that actually it appears when I call r.OrderStatus = '2' it never uses the @OrderStatus.setter but instead seems to make it's own variable OrderStatus on the fly, not using the setter and hence never setting self._OrderStatus. Am I doing something obviously bad in using getters and setters? Why are they not being called as they should be?
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88705837
accepted answer: http://stackoverflow.com/a/50851586
upvote count: 1
tagged with: python
answer count: 1

http://stackoverflow.com/comment/88418567
has text: PostScript is a programming language, and what you are describing is a **superscript** not a postscript.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50704350
type: QuestionComment

http://stackoverflow.com/q/50737813
has answer: http://stackoverflow.com/a/50756265
has comment: http://stackoverflow.com/comment/88486155
tagged with: foreign-keys
answer count: 3
has title: Django Access to Foreign Key data to set a field default value
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88484615
has answer: http://stackoverflow.com/a/50739871
type: UnansweredQuestion
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/88485005
has comment: http://stackoverflow.com/comment/88490805
has answer: http://stackoverflow.com/a/50738328
score: 1
tagged with: django-models
type: Question
has body: I have two models with their respective forms. One has a Foreign Key link to the other and from, here I would like to set some fields default data. class Lexicon(models.Model): [...] case_sensitive = models.BooleanField(default=True) invariant = models.NullBooleanField(default=False) diacritics = models.BooleanField(default=True) [...] class Meta: verbose_name = "lexicon" ordering = ["filename"] def __str__(self): return self.filename class Lexeme(models.Model): lexicon = models.ForeignKey(Lexicon, on_delete=models.CASCADE) case_sensitive = models.BooleanField(default=True) diacritics = models.BooleanField(default=True) [...] class Meta: verbose_name = "lexeme" I would like the Lexeme model fields "case_sensitive" and "diacritics" to default from Lexicon. I suppose the forms may be a better place to do this. Any idea ?
downvote count: 0

http://stackoverflow.com/q/50820074
has answer: http://stackoverflow.com/a/50820156
has comment: http://stackoverflow.com/comment/88645645
has comment: http://stackoverflow.com/comment/88645508
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50820252
score: 0
answer count: 3
downvote count: 1
has body: I have one script that contains a function I want to use in another, i.e. def main(): def ex(a,b): return a+b if __name__ == "__main__": main() Whenever I import this script into another, I get the error "module 'script' has not attribute 'ex'" : import script script.ex(4,5)
has title: Cannot import local python module
has answer: http://stackoverflow.com/a/50820308
type: UnansweredQuestion

http://stackoverflow.com/q/50708627
tagged with: python
has comment: http://stackoverflow.com/comment/88430045
has body: I have the below Django model. As you can see, the directory of each strain is dynamic, and the Photos_save model is inline to the strain model (it lets me save multiple photos for each strain). I would like to have a detailed view of each strain and the pictures associated with it. Could any of you help me with the views.py and HTML code required to accomplish this? I'm quite new to Django, and so far I have managed to display all of the information of the strain, including the photos, on the index page (but I want the users to be able to click on the name of each strain and see a detailed view). class Strain(models.Model): """; Model representing strains. """ type_strain = ( ('W', 'Wild Type'), ('G', 'GMO'), ('P', 'Prospected'), ) def strain_directory_path(instance, filename): return 'strain_{0}/{1}'.format(instance.strain_name, filename) strain_name = models.CharField(max_length=100, blank=False, null=True, default=None) strain_description = models.CharField(max_length=500, blank=True, null=True, default=None) data_of_generation = models.DateField(null=True, blank=True, default= None) strain_source = models.CharField(max_length=500, blank=True, null=True, default=None) strain_parent = models.ForeignKey('Strain', null=True, blank = True, on_delete= models.CASCADE, default= None) strain_type = models.CharField(max_length=1 , blank=True, null=True, default=None, choices= type_strain) class Photos_save(models.Model): import datetime def strain_directory_path(instance, filename): return 'strain_{0}/{1}'.format(instance.strain_name, filename) strain_name = models.ForeignKey(Strain, on_delete=models.CASCADE, default= None) upload_photo = models.FileField(upload_to= strain_directory_path, default= None) photo_description = models.CharField(max_length= 200, default= None, blank= True) photo_upload_date = models.DateField(blank=True, default=datetime.date.today) def __str__(self): """ String for representing the Model object. """ return '{0}'.format(self.strain_name) def g…
type: Question
has comment: http://stackoverflow.com/comment/88428462
score: 0
answer count: 0
has title: Displaying detailed data from multiple Django models in html
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88426890
tagged with: django

http://stackoverflow.com/comment/88637328
comment on: http://stackoverflow.com/q/50815015
score: 0
type: Comment
type: QuestionComment
has text: Can't you simply put your NumPy arrays into ordinary dicts? If indexing into a dict is too slow for you then you will need a solution that is fine-tuned to your particular data structures.

http://stackoverflow.com/q/50826644
possible better answer: http://stackoverflow.com/a/50827120
has answer: http://stackoverflow.com/a/65162290
upvote count: 11
favorite count: 0
tagged with: pytorch
accepted answer: http://stackoverflow.com/a/50829107
tagged with: python
type: AnsweredQuestion
tagged with: seq2seq
has body: I'm following Pytorch seq2seq tutorial and ittorch.bmm method is used like below: attn_applied = torch.bmm(attn_weights.unsqueeze(0), encoder_outputs.unsqueeze(0)) I understand why we need to multiply attention weight and encoder outputs. What I don't quite understand is the reason why we need bmm method here. torch.bmm document says Performs a batch matrix-matrix product of matrices stored in batch1 and batch2. batch1 and batch2 must be 3-D tensors each containing the same number of matrices. If batch1 is a (b×n×m) tensor, batch2 is a (b×m×p) tensor, out will be a (b×n×p) tensor.
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/50829107
has answer: http://stackoverflow.com/a/50827120
score: 11
has title: Why do we do batch matrix-matrix product?
answer count: 3
tagged with: deep-learning

http://stackoverflow.com/q/50755500
possible better answer: http://stackoverflow.com/a/50755594
has answer: http://stackoverflow.com/a/50755594
accepted answer: http://stackoverflow.com/a/50755564
answer count: 3
has body: I have list as : mylist = ['7','8,9','10', '11,12'] I want a list as : ['7','8','9','10','11','12'] Closest i was able to get was using this code : mylist = ['7','8,9','10', '11,12'] ab = [] for e in mylist: if ',' in e: ab.append(e.split(',')) mylist2 = [x for x in mylist if ',' not in x] print mylist2 #clean list merged = [] for f in ab: merged = mylist2 + f But, this omits the '8','9' sequence, how can i easily achieve this?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50755795
tagged with: python
has title: Generate a list from another list with comma separated values
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50755564
score: 3
tagged with: list
upvote count: 3
type: Question

http://stackoverflow.com/q/50845162
possible better answer: http://stackoverflow.com/a/50845293
tagged with: oop
has answer: http://stackoverflow.com/a/50845293
has comment: http://stackoverflow.com/comment/88693980
has comment: http://stackoverflow.com/comment/88693981
has answer: http://stackoverflow.com/a/50845325
accepted answer: http://stackoverflow.com/a/50845299
has body: I learned a little bit of OOP and file I/O. I tried to apply them to real-life by making my own code. Unfortunately, however, it doesn't run. Python never says there is an error. It is just executing command all day and saying please wait for the result. Here is my code: class CoursesTaken(): def __init__(self): self._courses = [] def read_file(self, file): line = file.readline().strip() while line != 0: course = tuple(line.split()) self._courses.append(course) def add_course(self, season, code, gpa): self._course = (season, code, gpa) self._courses.append(self._course) def total_courses(self): return self._courses def name_of_total_courses(self): result = [] for i in self._courses: name = i[1] result.append(name) return result if __name__ == '__main__': file = open('courses.txt') courses = CoursesTaken() courses.read_file(file) print(courses.name_of_total_courses) file.close() txt file is in this format: 2018S CSC111 A 2018S MAT101 B+ I have no idea how to improve my code.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88693963
has title: How to determine why my Python code takes infinite time to run
type: Question
tagged with: file-io
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50845299
score: 0
answer count: 3
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/88436914
has text: Quick question, if I want the 66% to be say 66.325% i.e. 3 d.p?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50713824

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

http://stackoverflow.com/q/50818373
upvote count: 1
downvote count: 1
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50818563
tagged with: sorting
has comment: http://stackoverflow.com/comment/88641773
score: 0
has answer: http://stackoverflow.com/a/50818488
favorite count: 0
has title: Sorting a list based on how another list was sorted. Python 3
has body: I've been struggling with sorting a list based on a previous sorted list in Python 3 for a while and though I would ask for help from you guys. Ok, so I have a list: list = ['A103', 'A101', 'C101', 'B101'] This list is sorted in an alphabetic and then numeric way with the following code: convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] list_sorted = sorted(list, key=alphanum_key) The new list, list_sorted looks like this: ['A101', 'A103', 'B101', 'C101']. Now to the tricky part, I have another list with values corresponding to the values in "list" which need to be sorted in the same way. Example: list = ['A103', 'A101', 'C101', 'B101'] rad = ['£', '$', '€', '@'] list_sorted =['A101', 'A103', 'B101', 'C101'] rad = ['$', '£', '@', '€']. All help is highly appreciated, thank you!
tagged with: python
accepted answer: http://stackoverflow.com/a/50818488
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/88641849
has answer: http://stackoverflow.com/a/50818563

amazon-web-services
tags question: http://stackoverflow.com/q/50829170
tags question: http://stackoverflow.com/q/50840025
tags question: http://stackoverflow.com/q/50758127
tags question: http://stackoverflow.com/q/50801311
tags question: http://stackoverflow.com/q/50824608
tags question: http://stackoverflow.com/q/50841190
tags question: http://stackoverflow.com/q/50781530
tags question: http://stackoverflow.com/q/50829647
tags question: http://stackoverflow.com/q/50711722
tags question: http://stackoverflow.com/q/50798071
tags question: http://stackoverflow.com/q/50735576
tags question: http://stackoverflow.com/q/50785308
tags question: http://stackoverflow.com/q/50733603
tags question: http://stackoverflow.com/q/50822985
tags question: http://stackoverflow.com/q/50788813
tags question: http://stackoverflow.com/q/50719584
tags question: http://stackoverflow.com/q/50738120
type: Tag
tags question: http://stackoverflow.com/q/50814024
tags question: http://stackoverflow.com/q/50711086
tags question: http://stackoverflow.com/q/50789094
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/50826073
tags question: http://stackoverflow.com/q/50818766
tags question: http://stackoverflow.com/q/50802418
tags question: http://stackoverflow.com/q/50783925
tags question: http://stackoverflow.com/q/50791452
tags question: http://stackoverflow.com/q/50834184
tags question: http://stackoverflow.com/q/50849255
tags question: http://stackoverflow.com/q/50854550
tags question: http://stackoverflow.com/q/50741636
tags question: http://stackoverflow.com/q/50763186
tags question: http://stackoverflow.com/q/50771544
tags question: http://stackoverflow.com/q/50776214
tags question: http://stackoverflow.com/q/50719575
tags question: http://stackoverflow.com/q/50778924
tags question: http://stackoverflow.com/q/50822222
tags question: http://stackoverflow.com/q/50798517
tags question: http://stackoverflow.com/q/50782433
tags question: http://stackoverflow.com/q/50800885
tags question: http://stackoverflow.com/q/50853835
tags question: http://stackoverflow.com/q/50826884
tags question: http://stackoverflow.com/q/50699149
tags question: http://stackoverflow.com/q/50801247
tags question: http://stackoverflow.com/q/50757023
tags question: http://stackoverflow.com/q/50739245
tags question: http://stackoverflow.com/q/50763441
tags question: http://stackoverflow.com/q/50750304
tags question: http://stackoverflow.com/q/50823252

http://stackoverflow.com/comment/88514514
has text: This can be improved by doing `while key1.count("_") != 4:` and remove `if key1.count("_") == 4:break` instead of `while 1:`
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50753084

http://stackoverflow.com/a/64757279
answers question: http://stackoverflow.com/q/50799143
type: Answer
score: 0
has body: You need to have the latest version of pip in order to install tensorflow or openCV. You can upgrade pip using the below command: python -m pip install --upgrade pip After upgrading Pip, it should work fine.

http://stackoverflow.com/comment/88711989
type: Comment
type: QuestionComment
has text: @NarenMurali I reopened and modified the tags. I suppose this has also already been asked for plotly, so maybe you find an existing duplicate.
comment on: http://stackoverflow.com/q/50826357
score: 0

http://stackoverflow.com/q/50699802
has comment: http://stackoverflow.com/comment/88412839
type: Question
score: 0
has body: I understand that ssh -t -q can help to skip banner messages in terms of bash scripting. But how do I skip the banner message while using subprocess.Popen to connect the remote machine via ssh? The problem is that the banner message is captured as an error message and it shows as ERROR [ &lt; banner message> ] ssh = subprocess.Popen(["ssh","%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = ssh.stdout.readlines() print "Executed on ", host if result == [ ] : error = ssh.stderr.readlines() print &gt;&gt;sys.stderr, "ERROR: %s" % error else: print result return
tagged with: banner
answer count: 1
accepted answer: http://stackoverflow.com/a/52478820
has comment: http://stackoverflow.com/comment/88410265
has title: How to skip banner message when using ssh inside python subprocess
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/88409007
tagged with: subprocess
has answer: http://stackoverflow.com/a/52478820
tagged with: skip
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88412437

http://stackoverflow.com/comment/88567316
comment on: http://stackoverflow.com/a/50753435
score: 0
type: Comment
has text: the issue from asterisk '*' (an Python3 feature) was indeed from Python version conflict. I modified some code logic and fixed a potential bug if you need more common stats like `mean`, `std` in the same Pivot table. it should be working now on Python 2.7.5 and Pandas 0.17.0.
type: AnswerComment

http://stackoverflow.com/comment/88462014
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50726818
type: QuestionComment
has text: if you concatenate what you have you'll get: ```"/mapr12.12.12/data/dir/var"```.

http://stackoverflow.com/comment/88507635
type: AnswerComment
type: Comment
has text: In regression, any categorical variable needs to use one level as a baseline against which the other levels are compared. That's how you get separate coefficients for each category level - the coefficient will indicate the predictive signal of that level, compared to whatever the baseline is. The baseline does not get compared to otself, so there is no coefficient for it. You can look into contrasts for more information (but further questions about this are more appropriate for CrossValidated than for StackOverflow).
comment on: http://stackoverflow.com/a/50733691
score: 0

http://stackoverflow.com/a/50735231
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/126853014
has body: I'm not sure, if you can do this with the css method, but with the xpath method you should be able to do: response.xpath("//a[@data-item-name]/@href")
answers question: http://stackoverflow.com/q/50734845
upvote count: 4
has comment: http://stackoverflow.com/comment/126545402

http://stackoverflow.com/comment/88466097
comment on: http://stackoverflow.com/a/50728889
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the response. Can you help clarify some things about the tool? I am not a systems engineer by any means (I'm just setting up tools for them). What is meant by "analysis and optimization"? Say I give OpenMDAO a plane wing, is it supposed to auto-magically find the absolute best solution for plane wing shape using libraries/solvers that are predefined for particular problems?

http://stackoverflow.com/q/50746726
type: Question
answer count: 2
score: 5
tagged with: python
tagged with: indexing
has title: How to use query method of pd.DataFrame objects with columns that have '-' hyphens in the label?
has comment: http://stackoverflow.com/comment/88501259
has answer: http://stackoverflow.com/a/50747014
has body: I want to grab all of the non-nan IDs for SWISS-PROT-ID field and also the values that are True for idx_filter field. There's a million other ways I can think about doing this but I have been encountering this type of reflex when dealing with more complicated queries in my dataframes. Is there a way to query dataframes that these types of names as the columns? data = {'BLATTNER-ID': {'G0-16600': 'b4714', 'G6866': 'b1615', 'G0-10751': 'b4712', 'G0-10752': 'b4713', 'G6335': 'b0608', 'G6177': 'b0307', 'G0-8892': 'b4599', 'G0-10596': 'b4605', 'EG12861': 'b1915', 'EG12303': 'b1100'}, 'NAME': {'G0-16600': 'ralA', 'G6866': 'uidC', 'G0-10751': 'agrA', 'G0-10752': 'agrB', 'G6335': 'ybdR', 'G6177': 'ykgF', 'G0-8892': 'yneM', 'G0-10596': 'ypaB', 'EG12861': 'yecF', 'EG12303': 'ycfH'}, 'SWISS-PROT-ID': {'G0-16600': np.nan, 'G6866': 'Q47706', 'G0-10751': np.nan, 'G0-10752': np.nan, 'G6335': 'P77316', 'G6177': 'P77536', 'G0-8892': 'A5A616', 'G0-10596': np.nan, 'EG12861': 'P0AD07', 'EG12303': 'P0AFQ7'}, 'idx_filter': {'G0-16600': False, 'G6866': True, 'G0-10751': False, 'G0-10752': False, 'G6335': True, 'G6177': False, 'G0-8892': False, 'G0-10596': True, 'EG12861': False, 'EG12303': False}} df = pd.DataFrame(data) # 1st tried this df.query("SWISS-PROT-ID and idx_filter").index # UndefinedVariableError: name 'SWISS' is not defined # 2nd tried escape characters df.query("SWISS\-PROT\-ID and idx_filter").index # UndefinedVariableError: name 'SWISS' is not defined # Expecting # ["G6335","G6866"] Versions: pandas: 0.22.0 # I don't want to upgrade b/c there is a serious bug in 0.23.0 that breaks one of my programs python: 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]
has answer: http://stackoverflow.com/a/64109337
upvote count: 5
tagged with: dataframe
linked to: http://stackoverflow.com/q/50697536
has comment: http://stackoverflow.com/comment/88501209
possible better answer: http://stackoverflow.com/a/64109337
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50747014

http://stackoverflow.com/q/50781673
has comment: http://stackoverflow.com/comment/88570505
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/88570429
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: I have a 2d array of the form: [[x1, y1, z1], [x1, y2, z2], ..., [x400, y400, z16000]] I want to convert it to a 2d array of the form: new_arr[x1][y1] = z1 Is there a way to generate this array in numpy? (without using python loops)
has title: convert 2d array to another 2d array using the first two columns as coordinates
has comment: http://stackoverflow.com/comment/88570146
has comment: http://stackoverflow.com/comment/88570884

http://stackoverflow.com/comment/88701493
type: Comment
has text: Ummm... I don't think string splicing in python works that way..Try it out on your ipython console..The last position is not included
type: AnswerComment
comment on: http://stackoverflow.com/a/50849215
score: 0

http://stackoverflow.com/q/50704509
has comment: http://stackoverflow.com/comment/88418610
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88418245
score: -1
type: Question
has title: python mock different instances
tagged with: python-mock
tagged with: mocking
has answer: http://stackoverflow.com/a/50704780
favorite count: 0
has body: I would like to know the difference between pg.connect and pg.connect() statements. pg is a psycopg2 mock object and when I display the dir, it shows connect as its method. class TestMock(unittest.TestCase): def setUp(self): pass def test_mock_calls(self): import pprint pg = mock.MagicMock(psycopg2) print 'pg() object ', pg() print 'dir of pg = ', pprint.pprint(dir(pg)) print 'dir of pg = ', pg.connect print 'dir of pg.connect = ', pprint.pprint(dir(pg.connect)) print 'dir of pg = ', pg.connect() print 'dir of pg.connect() = ', pprint.pprint(dir(pg.connect())) Updates:- One(pg.connect) is accessing the attribute and other one(pg.connect()) calling the function. Now, how can I set the return_value of the execute method? For example:- I need to mock the response of my execute method. so, it should be pg.connect().cursor().execute.side_effect = someexception()
has comment: http://stackoverflow.com/comment/88418216
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88418207
has comment: http://stackoverflow.com/comment/88419322
upvote count: 0
has comment: http://stackoverflow.com/comment/88418445

http://stackoverflow.com/q/50831605
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50833972
has title: Why two different AUC scores are produced when evaluated on same data and same algorithm
tagged with: auc
answer count: 1
downvote count: 0
tagged with: xgboost
favorite count: 0
has answer: http://stackoverflow.com/a/50833972
tagged with: python
has comment: http://stackoverflow.com/comment/88667690
has body: I am working on a classification problem whose evaluation metric in ROC AUC. So far I have tried using xgb with different parameters. Here is the function which I used to sample the data. And you can find the relevant notebook here (google colab) def get_data(x_train, y_train, shuffle=False): if shuffle: total_train = pd.concat([x_train, y_train], axis=1) # generate n random number in range(0, len(data)) n = np.random.randint(0, len(total_train), size=len(total_train)) x_train = total_train.iloc[n] y_train = total_train.iloc[n]['is_pass'] x_train.drop('is_pass', axis=1, inplace=True) # keep the first 1000 rows as test data x_test = x_train.iloc[:1000] # keep the 1000 to 10000 rows as validation data x_valid = x_train.iloc[1000:10000] x_train = x_train.iloc[10000:] y_test = y_train[:1000] y_valid = y_train[1000:10000] y_train = y_train.iloc[10000:] return x_train, x_valid, x_test, y_train, y_valid, y_test else: # keep the first 1000 rows as test data x_test = x_train.iloc[:1000] # keep the 1000 to 10000 rows as validation data x_valid = x_train.iloc[1000:10000] x_train = x_train.iloc[10000:] y_test = y_train[:1000] y_valid = y_train[1000:10000] y_train = y_train.iloc[10000:] return x_train, x_valid, x_test, y_train, y_valid, y_test Here are the two outputs that I get after running on shuffled and non shuffled data AUC with shuffling: 0.9021756235738453 AUC without shuffling: 0.8025162142685565 Can you find out what's the issue here ?
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/50719371
has comment: http://stackoverflow.com/comment/88454117
favorite count: 0
accepted answer: http://stackoverflow.com/a/50719601
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50719601
upvote count: 2
has body: is there a way to delete all files in a directory but only keep every x files ? I have a directory which contains images, for a scene taken with a frequency of 10 frames per second. I want to keep every 5th frame. Example: if the folder is containing images from 0-10 I want to keep the 5th and the 10th image, and delete the others
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/88450931
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88447135
tagged with: image
type: Question
answer count: 1
downvote count: 0
has title: Delete every x file in a directory - Python

http://stackoverflow.com/comment/88643097
has text: Thats pretty cool - thanks. I'll have a play, I'd like it to generate ['c', 'a'] - inverting the combinations.
comment on: http://stackoverflow.com/q/50817905
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50783396
has body: can you try to stringify the array and after this use json.loads ? $.post(data_send_url, { all_letters: JSON.stringify(["A","B","C"]) }, function(data, status){ alert(data); }); # and after this use json.loads import json print(json.loads(request.data['all_letters']))
has comment: http://stackoverflow.com/comment/88574469
type: Answer
has comment: http://stackoverflow.com/comment/88574934
has comment: http://stackoverflow.com/comment/88574874
has comment: http://stackoverflow.com/comment/88574815
accepted answer of: http://stackoverflow.com/q/50783006
downvote count: 0
has comment: http://stackoverflow.com/comment/88574413
score: 1
answers question: http://stackoverflow.com/q/50783006
has comment: http://stackoverflow.com/comment/88574830
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88574697
has comment: http://stackoverflow.com/comment/88574781
upvote count: 1

http://stackoverflow.com/a/50795345
upvote count: 2
type: Answer
score: 2
has body: No, now I understand... :-) If you have two fixed sets of sequences (i.e. 'upper' and 'lower') and you know that one legend entry is always representing one in each set, you could just Label the one set and color the other manually, so your code changes to: for j in range(k) p = plt.plot(lower_graphs[j, :], label=str(alphas_vis[i])) plt.plot(upper_graphs[j, :], c=p[0].get_c())) plt.legend() The other answer below is for the more general case, where you can arbitrarily set any sequence to an equal name like any other.
downvote count: 0
answers question: http://stackoverflow.com/q/50791422

http://stackoverflow.com/q/50806693
accepted answer: http://stackoverflow.com/a/50806763
answer count: 1
tagged with: string
has answer: http://stackoverflow.com/a/50806763
tagged with: python
tagged with: valueerror
type: AnsweredQuestion
type: Question
has body: I want to plot Ch and Pol strings but i can't convert them into a plotable variables Ch = '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22' Pol = '9 9 10 10 10 10 10 10 10 10 10 10 10 10 10 9 10 10 10 10 10 10' plt.plot(Ch,Pol) When i run it the result is: ValueError: Unrecognized character 9 in format string Please help
tagged with: arrays
has title: How can i plot 2 string variables Pol vs Ch
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/88638832
type: Comment
type: QuestionComment
has text: what about using `round` or `math.floor/math.ceil`?
comment on: http://stackoverflow.com/q/50816879
score: 0

http://stackoverflow.com/comment/88642780
score: 0
type: Comment
has text: @JoshPilson - Glad can help!
type: AnswerComment
comment on: http://stackoverflow.com/a/50818244

http://stackoverflow.com/comment/88532261
type: Comment
comment on: http://stackoverflow.com/a/50761328
score: 0
type: AnswerComment
has text: Yes, this is exactely what I need but when I put this solution inside my code I get a KeyError on the very first element. Regard this I edited OP in order to clarify my environment and my intent

http://stackoverflow.com/comment/88671620
comment on: http://stackoverflow.com/q/50833303
has text: @WillemVanOnsem Then increase upto 250.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50741335
tagged with: pandas
tagged with: python
tagged with: combinatorics
has comment: http://stackoverflow.com/comment/88492046
accepted answer: http://stackoverflow.com/a/50741633
has title: Calculating sum of a combination of columns in pandas, row-wise, with output file with the name of said combination
has comment: http://stackoverflow.com/comment/88490663
type: Question
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/50743493
has comment: http://stackoverflow.com/comment/88491081
has comment: http://stackoverflow.com/comment/88491160
has comment: http://stackoverflow.com/comment/88491859
has comment: http://stackoverflow.com/comment/88494609
has answer: http://stackoverflow.com/a/50741742
has comment: http://stackoverflow.com/comment/88492262
has answer: http://stackoverflow.com/a/50741633
has body: I am looking for a way of generating a csv file for a specific combination of data from columns in a dataframe. My data looks like this (except with 200 more rows) +-------------------------------+-----+----------+---------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+---------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+ | Species | OGT | Domain | A | C | D | E | F | G | H | I | K | L | M | N | P | Q | R | S | T | V | W | Y | +-------------------------------+-----+----------+---------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+---------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+ | Aeropyrum pernix | 95 | Archaea | 9.7659115711 | 0.6720465616 | 4.3895390781 | 7.6501943794 | 2.9344881615 | 8.8666657183 | 1.5011817208 | 5.6901432494 | 4.1428307243 | 11.0604191603 | 2.21143353 | 1.9387130928 | 5.1038552753 | 1.6855017182 | 7.7664358772 | 6.266067034 | 4.2052190807 | 9.2692433532 | 1.318690698 | 3.5614200159 | | Argobacterium fabrum | 26 | Bacteria | 11.5698896021 | 0.7985475923 | 5.5884500155 | 5.8165463343 | 4.0512504104 | 8.2643271309 | 2.0116736244 | 5.7962804605 | 3.8931525401 | 9.9250463349 | 2.5980609708 | 2.9846761128 | 4.7828063605 | 3.1262365491 | 6.5684282943 | 5.9454781844 | 5.3740045968 | 7.3382308193 | 1.2519739683 | 2.3149400984 | | Anaeromyxobacter dehalogenans | 27 | Bacteria | 16.0337898849 | 0.8860252895 | 5.1368827707 | 6.1864992608 | 2.9730203513 | 9.3167603253 | 1.9360386851 | 2.940143349 | 2.3473650439 | 10.898494736 | 1.6343905351 | 1.5247123262 | 6.3580285706 | 2.4715303021 | 9.2639057482 | 4.1890063803 | 4.3992339725 | 8.3885969061 | 1.2890166336 | 1.8265589289 …
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/50741742

http://stackoverflow.com/q/50733098
tagged with: web-scraping
type: Question
upvote count: 4
downvote count: 0
has body: Trying to scrape a list of "Name" column from this https://apps.neb-one.gc.ca/REGDOCS/Search/SearchAdvancedResults?p=4 here is my simple code: from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome(chrome_options=options) driver.get('https://apps.neb-one.gc.ca/REGDOCS/Search/SearchAdvancedResults? p=4') driver.implicitly_wait(5) rows = driver.find_elements_by_xpath('//*[@id="details- elements"]/table/tbody/tr') output = [] for row in rows: title = row.find_element_by_xpath('//*[@id="details- elements"]/table/tbody/tr/td[1]/details/summary/a').get_attribute('text') output.append(title) driver.close() print(output) It partly works. But for some reason the code will only return a list of 20 items (correct length), that consists of the Name (correct column) of the first row repeated (ugh...so close). Like this: ['Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5', 'Receipt - Accusé de réception - A6F0I5'] What simple thing am I overlooking?
score: 4
has answer: http://stackoverflow.com/a/50733200
answer count: 1
has title: Webscraping using python - Keep getting repeat 1st row values from jquery table
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50733200
type: AnsweredQuestion
tagged with: selenium

http://stackoverflow.com/a/50702652
has comment: http://stackoverflow.com/comment/88415163
has comment: http://stackoverflow.com/comment/88415174
answers question: http://stackoverflow.com/q/50702574
upvote count: 1
type: Answer
has body: A better way to do this would be to add a double_precision argument when saving: df a b c 0 0.2 0.245673 1.235 df.to_json(double_precision=3) '{"a":{"0":0.2},"b":{"0":0.246},"c":{"0":1.235}}' Note that 0.2 cannot be saved as 0.200 as long as you want the value to remain numeric. You can, however, convert to string. Example, df.applymap('{:.3f}'.format).to_json() '{"a":{"0":"0.200"},"b":{"0":"0.246"},"c":{"0":"1.235"}}'
downvote count: 0
score: 1

http://stackoverflow.com/q/50823134
has answer: http://stackoverflow.com/a/50823911
score: 0
has body: I am trying to open all files from a folder, store them in a dataframe and append each csv file with another csv file called Append.csv and am trying to write all the files with their names to a different folder. For example I have 5 csv files that are saved in a folder called CSV FILES FOLDER. These files are F1.csv, F2.csv, F3.csv, F4.csvand F5.csv. What I am trying to do is open each file using pandas and I do this in a for loop, Append.csv and now store it in a different folder called NEW CSV FILES FOLDER as : F1_APPENDED.csv F2_APPENDED.csv F3_APPENDED.csv F4_APPENDED.csv In other words, the _APPENDED is added with each file and then the file with the new name having _APPENDED is saved. I have already defined the path for this folder but cant save it. The code is as below : import pandas as pd import glob import os.path import pathlib path =r'C:\Users\Ahmed Ismail Khalid\Desktop\CSV FILES FOLDER' allFiles = glob.glob(path + "/*.csv") path1 = r'C:\Users\Ahmed Ismail Khalid\Desktop\Different Folder\Bitcoin Prices Hourly Based.csv' outpath = r'C:\Users\Ahmed Ismail Khalid\Desktop\NEW CSV FILES FOLDER' for f in allFiles: file = open(f, 'r') df1 = pd.read_csv(path1) df2 = pd.read_csv(f) output = pd.merge(df1, df2, how="inner", on="created_at") df3 = output.created_at.value_counts().rename_axis('created_at').reset_index(name='count') df3 = df3.sort_values(by=['created_at']) #print(df3,'\n\n') df3.to_csv(outpath+f, encoding='utf-8',index=False) #print(f,'\n\n') How can I do this? I tried to look up the official documentation but couldn't understand anything Any and all help would be appreciated Thanks
has comment: http://stackoverflow.com/comment/88651845
answer count: 1
has comment: http://stackoverflow.com/comment/88652089
has comment: http://stackoverflow.com/comment/88651394
type: UnansweredQuestion
has title: Python Fetching Name Of All CSV Files From Path And Writing Each To Different Folder
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
type: Question
has comment: http://stackoverflow.com/comment/88651947
tagged with: python

http://stackoverflow.com/q/50798806
has comment: http://stackoverflow.com/comment/88603873
downvote count: 3
has body: How can I run multiple python scripts one after another? At the moment I run one like so python script1.py. I've tried python script1.py script2.py and that doesn't work: only the first script is run. Also, I've tried using a single file like this; import script1 import script2 python script1.py python script2.py However this doesn't work either. Also i need HTML output at the end of execution..How can i achieve that?
answer count: 1
has answer: http://stackoverflow.com/a/50799110
accepted answer: http://stackoverflow.com/a/50799110
has comment: http://stackoverflow.com/comment/88603625
favorite count: 0
score: -3
has comment: http://stackoverflow.com/comment/88603617
tagged with: python
has comment: http://stackoverflow.com/comment/88604039
type: AnsweredQuestion
upvote count: 0
has title: How can I run multiple python scripts one after another?
has comment: http://stackoverflow.com/comment/88623758
has comment: http://stackoverflow.com/comment/88603646
type: Question

http://stackoverflow.com/comment/88736794
has text: Some constructive comments (hope you dont take offence) you should add some explanation to your answer, this will help the OP understand what you are proposing. Also from a readability point of view try adding some blank lines between some of the sections in your code, it will make it far easier to read (check [this](https://repl.it/repls/CautiousSeashellFiletype))and understand. Just flag this comment when you want it removed.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50852213

http://stackoverflow.com/q/50798071
tagged with: aws-lambda
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50799835
tagged with: amazon-s3
has title: Unable to get just subfolder objects from s3 aws
type: Question
has body: I am using this function to get data from S3: s3 = boto3.resource('s3') s3client = boto3.client('s3') Bucket = s3.Bucket('ais-django'); obj = s3.Object('ais-django', 'Event/') list = s3client.list_objects_v2(Bucket='ais-django' ,Prefix='Event/' ) for s3_key in list: filename = s3_key['Key'] When I use prefix for Event folder (path is like 'ais-django/Event/') it gives abnormal output like this: { 'IsTruncated': False, 'Prefix': 'Event/', 'ResponseMetadata': { 'HTTPHeaders': { 'date': 'Mon, 11 Jun 2018 12:42:35 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'x-amz-bucket-region': 'us-east-1', 'x-amz-request-id': '94ADDB21361252F3', 'server': 'AmazonS3', 'x-amz-id-2': 'IVuVQuB2V7nClm5FaX4FRbt6brS3gAiuwpERnZxknIWoZLH65LerURwmoynKW5sv37VP6FdbYho=' }, 'RequestId': '94ADDB21361252F3', 'RetryAttempts': 0, 'HostId': 'IVuVQuB2V7nClm5FaX4FRbt6brS3gAiuwpERnZxknIWoZLH65LerURwmoynKW5sv37VP6FdbYho=', 'HTTPStatusCode': 200 }, 'MaxKeys': 1000, 'Name': 'ais-django', 'KeyCount': 0 } while without prefix when I add like this: list = s3client.list_objects_v2(Bucket='ais-django' )[Contents] it gives list of all objects. So how I can get all objects in a specific folder ?
tagged with: amazon-web-services
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88606308

http://stackoverflow.com/comment/88666355
type: QuestionComment
comment on: http://stackoverflow.com/q/50830491
has text: @EvgenyPogrebnyak no imports. the next page code doesn't actually work since the next page element's `href` is generated dynamically with JS. the requests are in the `parse` method on the same level as the `for` loop and runs immediately after the `for` loop
score: 0
type: Comment

http://stackoverflow.com/a/50751502
has body: No imports, works on all inputs: &gt;&gt;&gt; pd.DataFrame([(key, var) for (key, L) in cols.items() for var in L], columns=['key', 'variable']) key variable 0 animals dog 1 animals cat 2 animals fish 3 colors red 4 colors black 5 colors blue 6 colors dog
type: Answer
downvote count: 0
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/50751184

http://stackoverflow.com/a/56464073
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50743723
downvote count: 0
type: Answer
has body: (Windows 10, Python 3.7) I had more issues than others, but this builds off of previous answers : Make sure that Microsoft Visual Studio C++ Compiler for Python is installed For Visual Studio C++ 14.0 (also required by Scrapy as of June 2019), use : https://wiki.python.org/moin/WindowsCompilers --> https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2017 --> https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community&amp;rel=16 Note : This may take a very long time to install, so be patient python -m pip install --upgrade pip setuptools wheel pip install six --upgrade Download EbookLib version 0.15: Unzip the .zip file To avoid encoding errors, edit the "long_description" variable assignment to be "long_description = open('README.md',encoding="utf-8").read()," Download Swig: http://www.swig.org/download.html Unzip the .zip file Copy the swig.exe file into the Python path : e.g. "C:\Users\username\AppData\Local\Programs\Python\Python37" Copy the "typemaps" folder into the python "Lib" folder : e.g. "C:\Program Files\swigwin-4.0.0\Lib\typemaps" --> "C:\Users\username\AppData\Local\Programs\Python\Python37\Lib\" Copy the "*.swg" files to the python "Lib" folder : e.g. "C:\Program Files\swigwin-4.0.0\Lib*.swg" --> "C:\Users\username\AppData\Local\Programs\Python\Python37\Lib\" Copy the all swig python files to the python "Lib" folder : e.g. "C:\Program Files\swigwin-4.0.0\Lib\python*" --> "C:\Users\username\AppData\Local\Programs\Python\Python37\Lib\" cd into the unzipped Ebooklib folder from the prompt : e.g. C:> cd "C:\Users\username\Desktop\ebooklib-0.15" run the installation for EbookLib : pip install . run the textract installation : pip install textract The output should be : C:\Users\username\Desktop\ebooklib-0.15&gt;pip install textract Collecting textract Requirement already satisfied: docx2txt==0.6 in c:\users\username\appdata\local\programs\python\python37\lib\site-packages (from textract) (0.6) Requirement al…

http://stackoverflow.com/q/50796622
has comment: http://stackoverflow.com/comment/89017284
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88599170
tagged with: cmake
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88648160
type: Question
has body: I'm attempting to compile TensorFlow on Windows 10 using the Cmake build (https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/cmake). The build fails with the error: "error MSB6006: "cmd.exe" e xited with code 1". (full error details below) The build configuration is as follows: OS: Windows 10 Python: 3.5.5 (Anaconda Python) Cmake: 3.11.3 Visual Studio 2015 Update 3 (14.0.25431.01) CUDA 9.2, cuDNN 7.1 GPU: Nvidia GeForce 940M TensorFlow 1.8 (Git tag v1.8.0) Steps to reproduce: git clone https://github.com/tensorflow/tensorflow cd tensorflow git checkout v1.8.0 cd tensorflow\contrib\cmake mkdir build cd build C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat amd64 cmake .. -A x64 -DCMAKE_BUILD_TYPE=Release ^ -DSWIG_EXECUTABLE=C:/Dev_Tools/TFBuild/tools/swigwin-3.0.12/swig.exe ^ -DPYTHON_EXECUTABLE=C:/Users/UAMARTH/AppData/Local/Continuum/anaconda3/envs/tfbuild/python.exe ^ -DPYTHON_LIBRARIES=C:/Users/UAMARTH/AppData/Local/Continuum/anaconda3/envs/tfbuild/libs/python35.lib ^ -Dtensorflow_ENABLE_GPU=ON ^ -Dtensorflow_CUDA_VERSION=9.2 ^ -Dtensorflow_CUDNN_VERSION=7 ^ -DCUDNN_HOME="C:\Dev_Tools\TFBuild\tools\cudnn-9.2-windows10-x64-v7.1" ^ -Dtensorflow_WIN_CPU_SIMD_OPTIONS=/arch:AVX MSBuild /p:Configuration=Release tf_python_build_pip_package.vcxproj The cmake command complete without errors. The MSBuild command builds for about four hand half hours and then produces the following error: "C:\Dev_Tools\TFBuild\tensorflow\tensorflow\contrib\cmake\build\tf_python_build_pip_package.vcxproj" (default target) ( 1) -&gt; "C:\Dev_Tools\TFBuild\tensorflow\tensorflow\contrib\cmake\build\tf_python_api.vcxproj" (default target) (259) -&gt; (CustomBuild target) -&gt; C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(171,5): error MSB6006: "cmd.exe" e xited with code 1. [C:\Dev_Tools\TFBuild\tensorflow\tensorflow\contrib\cmake\build\tf_python_api.vcxproj] 19591 Warning(s) 1 Error(s) Time Elapsed 04:30:49.38 Any id…
score: 0
has title: TensorFlow 1.8 Cmake build with GPU fails on Windows 10 with a MSB6006 error

http://stackoverflow.com/comment/88465116
score: 0
comment on: http://stackoverflow.com/q/50724366
type: QuestionComment
type: Comment
has text: `Vik-Pro:python_cheatsheets vik$ which pip /anaconda3/bin/pip Vik-MacBook-Pro:python_cheatsheets vik$ pip --version pip 10.0.1 from /anaconda3/lib/python3.6/site-packages/pip (python 3.6)` @DietrichEpp

http://stackoverflow.com/a/50786195
has body: I think need numpy.select for set values by conditions, also I try reassign same conditions to variables m1-m3 for better performance: m1 = (blackCondition &amp; whitePCondition) m2 = (blackCondition &amp; blackPCondition) m3 = (whiteCondition &amp; whitePCondition) #same like m1 #m4 = (whitePCondition &amp; blackCondition) c1 = m1 &amp; (close_gt_oP &amp; open_ge_cP) c2 = m1 &amp; (open_lt_cP &amp; close_le_oP) c5 = m2 &amp; (open_gt_oP &amp; close_ge_cP) c6 = m2 &amp; (close_lt_cP &amp; open_le_oP) c9 = m3 &amp; (close_gt_cP &amp; open_ge_oP) c10 = m3 &amp; (open_lt_oP &amp; close_le_cP) c13 = m1 &amp; (open_gt_cP &amp; close_ge_oP) c14 = m1 &amp; (close_lt_oP &amp; open_le_cP) c3 = m1 &amp; (close_gt_oP &amp; open_lt_cP) c4 = m1 &amp; (close_le_oP &amp; open_ge_cP) c7 = m2 &amp; (open_gt_oP &amp; close_lt_cP) c8 = m2 &amp; (open_le_oP &amp; close_ge_cP) c11 = m3 &amp; (close_gt_cP &amp; open_lt_oP) c12 = m3 &amp; (close_le_cP &amp; open_ge_oP) c15 = m1 &amp; (open_gt_cP &amp; close_lt_oP) c16 = m1 &amp; (open_le_cP &amp; close_ge_oP) Chain conditions by | for OR: cup = c1 | c5 | c9 | c13 cdown = c2 | c6 | c10 | c14 coutside = c3 | c7 | c11 | c15 cinside = c4 | c8 | c12 | c16 df['pos'] = np.select([cup, cdown, coutside, cinside], ['UP','DOWN','OUTSIDE','INSIDE'], default=None)
type: Answer
accepted answer of: http://stackoverflow.com/q/50785729
downvote count: 0
answers question: http://stackoverflow.com/q/50785729
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/88651155
has text: @pstatix Yes, it does.
comment on: http://stackoverflow.com/q/50823043
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88522273
type: QuestionComment
comment on: http://stackoverflow.com/q/50756723
has text: Like the other comments, keep it simple. As written in PEP 20: Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.
score: 0
type: Comment

http://stackoverflow.com/q/50798907
downvote count: 1
type: AnsweredQuestion
tagged with: ctypes
has title: Why does loading the libc shared library have "'LibraryLoader' object is not callable" error?
linked to: http://stackoverflow.com/q/50838633
accepted answer: http://stackoverflow.com/a/50799159
type: Question
answer count: 1
favorite count: 0
tagged with: linux
has body: From https://en.wikipedia.org/wiki/Foreign_function_interface the ctypes module can load C functions from shared libraries/DLLs on-the-fly and translate simple data types automatically between Python and C semantics as follows: import ctypes libc = ctypes.CDLL( '/lib/libc.so.6' ) # under Linux/Unix t = libc.time(None) # equivalent C code: t = time(NULL) print t On Lubuntu 18.04 $ whereis libc libc: /usr/lib/x86_64-linux-gnu/libc.a /usr/lib/x86_64-linux-gnu/libc.so /usr/share/man/man7/libc.7.gz $ locate libc.so /lib/i386-linux-gnu/libc.so.6 /lib/x86_64-linux-gnu/libc.so.6 /usr/lib/x86_64-linux-gnu/libc.so $ ls -l /usr/lib/x86_64-linux-gnu/libc.so -rw-r--r-- 1 root root 298 Apr 16 16:14 /usr/lib/x86_64-linux-gnu/libc.so I was wondering why loading the libc shared library has "'LibraryLoader' object is not callable" error? $ python3 --version Python 3.6.5 $ python3 &gt;&gt;&gt; import ctypes &gt;&gt;&gt; libc=ctypes.cdll("/usr/lib/x86_64-linux-gnu/libc.so") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'LibraryLoader' object is not callable &gt;&gt;&gt; libc=ctypes.cdll("/lib/x86_64-linux-gnu/libc.so.6") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'LibraryLoader' object is not callable &gt;&gt;&gt; libc=ctypes.cdll("/lib/i386-linux-gnu/libc.so.6") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'LibraryLoader' object is not callable See also https://unix.stackexchange.com/questions/449107/what-differences-and-relations-are-between-the-various-libc-so
tagged with: python
has answer: http://stackoverflow.com/a/50799159
upvote count: 2
score: 1
tagged with: libc
tagged with: dynamic-loading

http://stackoverflow.com/a/51060374
has comment: http://stackoverflow.com/comment/99824404
has comment: http://stackoverflow.com/comment/103855374
has comment: http://stackoverflow.com/comment/104720132
has comment: http://stackoverflow.com/comment/96737814
downvote count: 0
has comment: http://stackoverflow.com/comment/104698227
answers question: http://stackoverflow.com/q/50747947
upvote count: 48
has comment: http://stackoverflow.com/comment/104684154
has comment: http://stackoverflow.com/comment/96752625
has comment: http://stackoverflow.com/comment/107996141
has comment: http://stackoverflow.com/comment/96916407
has body: You could treat nn.Embedding as a lookup table where the key is the word index and the value is the corresponding word vector. However, before using it you should specify the size of the lookup table, and initialize the word vectors yourself. Following is a code example demonstrating this. import torch.nn as nn # vocab_size is the number of words in your train, val and test set # vector_size is the dimension of the word vectors you are using embed = nn.Embedding(vocab_size, vector_size) # intialize the word vectors, pretrained_weights is a # numpy array of size (vocab_size, vector_size) and # pretrained_weights[i] retrieves the word vector of # i-th word in the vocabulary embed.weight.data.copy_(torch.fromnumpy(pretrained_weights)) # Then turn the word index into actual word vector vocab = {"some": 0, "words": 1} word_indexes = [vocab[w] for w in ["some", "words"]] word_vectors = embed(word_indexes)
has comment: http://stackoverflow.com/comment/111161800
has comment: http://stackoverflow.com/comment/101211553
score: 48
type: Answer

http://stackoverflow.com/comment/88510525
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50751339
has text: Use `re.sub(rx, lambda x: x.group().replace(' ', '_'), s)`
score: 0

http://stackoverflow.com/a/50848562
type: Answer
downvote count: 0
score: 1
has body: You may want to try Seaborn because it looks like it is not a plotting issue but rather peripheral styling issue (all blacked out) in your environment. Once you installed Seaborn, insert a piece of code below to yours. import seaborn as sns sns.set_style("whitegrid") As a side note, if you wish to align the number of ticks in x axis to that of labels you have, replace your plotting part with the following: df1.plot() plt.xticks(range(df1.shape[0]), df1.index) Hope this helps.
answers question: http://stackoverflow.com/q/50749310
accepted answer of: http://stackoverflow.com/q/50749310
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50760322
has body: I am trying to webscrape this website, it's a bookmaker called matchpoint.com. My goal is to have a spreadsheet where I can see the odds without having to visit their site. My code prints the odds and the bet-text. But it doesn't sort the odds so it matches the bet-text. I've attached a picture below where you can see the page I'm scraping. For the first bet-text there are three odds and for another there are two odds attached to the text. I spent 3 days searching through stackoverflow and I haven't been able to move on from here. In: """ Soccer match results scraping object. """ from bs4 import BeautifulSoup import requests class scraper(): def __init__(self): print('__init__ called') def parsedata(self): self.url = "https://www.cashpoint.dk/en/?r=bets/xtra&amp;group=461392&amp;game=312004790" self.res = requests.get(self.url) self.soup = BeautifulSoup(self.res.text, "lxml") self.table = self.soup.find_all("table", class_="sportbet_extra_list_table") for self.items in self.table: self.odds = self.items.find("div", class_="sportbet_content_rate_right").get_text().strip() print(self.odds) self.text = self.items.find("td", class_="sportbet_extra_c1").get_text().strip() print(self.text) Scrape = scraper() Scrape.parsedata() Out: __init__ called 1,38 Hvem vinder kampen? 1,09 Dobbeltchance 1,12 Head to Head (penge tilbage ved uafgjort) 2,17 Handicap 0:1 4,25 Handicap 0:2 8,60 etc The website
possible better answer: http://stackoverflow.com/a/50760567
has answer: http://stackoverflow.com/a/50760567
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50791276
favorite count: 0
has title: Webscraping & beautifulsoup - sorting extracted odds and bet-text
tagged with: beautifulsoup
type: Question
answer count: 2
tagged with: python
tagged with: web-scraping
upvote count: 1
has answer: http://stackoverflow.com/a/50791276

mypy
tags question: http://stackoverflow.com/q/50804259
tags question: http://stackoverflow.com/q/50822164
type: Tag
tag name: mypy

http://stackoverflow.com/q/50797372
tagged with: validation
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88602100
score: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50810550
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88600816
tagged with: django
upvote count: 1
type: Question
has title: Django validate AuthenToken Manually in a Serializer
has body: So I have an app where I can book rooms. But I want to validate the user when he books a Room. I know that I can do that with the obtain_auth_token function. But I want to Validate the user myself with the token. So i am saving the token into the user when the user login to the site, and when the user want to book a room I'll give a token as a parameter to the booking view/serializer. Now I want to validate this token send with the booking request. Here is what my Serializer look like: class BuchungSerializer(ModelSerializer): """Serializer to map the Model instance into JSON format.""" token = serializers.CharField(required=True, allow_blank=False, write_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Buchung fields = ['id', 'user', 'time_choices', 'raum', 'platz', 'datum', 'token'] related_fields = ['user', 'raum', 'platz'] extra_kwargs = {"token": {"write_only": True}} username = serializers.CharField(source='user.username') def validate_token(self, value): user = Mitarbeiter.objects.filter(Q(username = username)) if user.exists() and user.count() == 1: user_obj = user.first() user_token = user_obj.usertoken token = Token.objects.get(key=value) if token == user_token: return value else: raise ValidationError("Token not Valid") else: raise ValidationError("User doesn't exist") def create(self, validated_data): reservation = Buchung( user=validated_data['user'], time_choices=validated_data['time_choices'], raum=validated_data['raum'], platz=validated_data['platz'], datum=validated_data['datum'], ) reservation.set_token(validated_data['token']) reservation.save() return reservation My View: class CreateBuchungView(generics.ListCreateAPIView): queryset = Buchung.objects.all() serializer_class = BuchungSerializer #permission_classes = [IsAuthenticated] def perform_create(self, serializer): """Save the post data when creating a new reservation.""" serializer.save() and my Model: class Buchung(models.Model): TIME_CHOICES…
accepted answer: http://stackoverflow.com/a/50810550
tagged with: django-serializer

http://stackoverflow.com/a/50714459
downvote count: 1
score: -1
upvote count: 0
type: Answer
has body: a = {'car':['A1', 'A2'], 'bike':['A0'], 'truck': ['A1']} def return_last(vehicle): return a[vehicle][-1] return_last('car')
answers question: http://stackoverflow.com/q/50714321

http://stackoverflow.com/a/50843802
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50843764
has body: You have not read your file to return a string you have a file object. To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string (''). See this page You just need to read it and it should work: file = open("products.txt","r") productsFile = file.read() print (productsFile.split(",")) Don't forget to close your file: file.close() Or better practice: with open("products.txt","r") as file: productsFile = file.read() This will automatically close the file for you. '_io.TextIOWrapper' is what is returned when you open a file (but have not read/written in it). You can test this by using the interactive interpreter: &gt;&gt;&gt;open('file.txt', 'r') &lt;_io.TextIOWrapper name='file.txt' mode='r' encoding='cp1252'&gt; You can determine three things from this: The name of the file. The encoding. the mode that open() has been set in. Here is a tutorial from the documentation on reading files.
type: Answer
upvote count: 1

http://stackoverflow.com/q/50740219
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50740417
score: 0
has body: I am new to Tensorflow so bear with me please, I am following this tutorial and come across an error that I do not know how to fix. Can anyone help me please? Thanks in advance. This is the code I try to execute: def train(): model = Model() with tf.Graph().as_default(): images, val_images, labels, val_labels = load_training_data() x = tf.placeholder(shape=[FLAGS.batch_size, IMAGE_SIZE, IMAGE_SIZE, 1], dtype=tf.float32, name='x') y = tf.placeholder(shape=[FLAGS.batch_size, NUM_LABELS], dtype=tf.float32, name='y') keep_prob = tf.placeholder(tf.float32, name='dropout_prob') global_step = tf.contrib.framework.get_or_create_global_step() logits = model.inference(x, keep_prob=keep_prob) loss = model.loss(logits=logits, labels=y) accuracy = model.accuracy(logits, y) summary_op = tf.summary.merge_all() train_op = model.train(loss, global_step=global_step) init = tf.global_variables_initializer() saver = tf.train.Saver() with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess: writer = tf.summary.FileWriter(FLAGS.summary_dir, sess.graph) print(writer) sess.run(init) for i in range(FLAGS.num_iter): offset = (i * FLAGS.batch_size) % (len(images) - FLAGS.batch_size) batch_x, batch_y = images[offset:(offset + FLAGS.batch_size), :], labels[ offset:(offset + FLAGS.batch_size), :] _, cur_loss, summary = sess.run([train_op, loss, summary_op], feed_dict={ x: batch_x, y: batch_y, keep_prob: 0.5 }) writer.add_summary(summary, i) print(i, cur_loss) if i % 1000 == 0: validation_accuracy = accuracy.eval(feed_dict={x: val_images, y: val_labels, keep_prob: 1.0}) print('Iter {} Accuracy: {}'.format(i, validation_accuracy)) if i == FLAGS.num_iter - 1: saver.save(sess, FLAGS.checkpoint_file_path, global_step) And this is the error log: TypeError Traceback (most recent call last) &lt;ipython-input-72-8d21e7b24473&gt; in &lt;module&gt;() 49 saver.save(sess, FLAGS.checkpoint_file_path, global_step) 50 ---&gt; 51 train() &lt;ipython-input-72-8d21e7b24473&gt; in train() 36 x: bat…
answer count: 1
tagged with: python
type: UnansweredQuestion
has title: Fetch argument None has invalid type <class 'NoneType'>
tagged with: kaggle

http://stackoverflow.com/comment/88591054
score: 0
type: AnswerComment
type: Comment
has text: Now a tried the quick-n-dirty method, but still can get it working. My module code is modified to 'move_right = False def keyboard_events(): global move_right for event in pygame.event.get(): It will not make continuous moving. Guess it's because
comment on: http://stackoverflow.com/a/50787869

http://stackoverflow.com/a/50786171
type: Answer
answers question: http://stackoverflow.com/q/50785479
accepted answer of: http://stackoverflow.com/q/50785479
has comment: http://stackoverflow.com/comment/91140075
has comment: http://stackoverflow.com/comment/91164077
has comment: http://stackoverflow.com/comment/91168087
has body: The main reason for the mistake is your start and end values. It forecasts the value for the first observation until the fifteenth. However, even if you correct that, Holt only includes the trend component and your forecasts will not carry the seasonal effects. Instead, use ExponentialSmoothing with seasonal parameters. Here's a working example for your dataset: import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.holtwinters import ExponentialSmoothing df = pd.read_csv('/home/ayhan/international-airline-passengers.csv', parse_dates=['Month'], index_col='Month' ) df.index.freq = 'MS' train, test = df.iloc[:130, 0], df.iloc[130:, 0] model = ExponentialSmoothing(train, seasonal='mul', seasonal_periods=12).fit() pred = model.predict(start=test.index[0], end=test.index[-1]) plt.plot(train.index, train, label='Train') plt.plot(test.index, test, label='Test') plt.plot(pred.index, pred, label='Holt-Winters') plt.legend(loc='best') which yields the following plot:
upvote count: 35
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91167988
score: 35
has comment: http://stackoverflow.com/comment/101743499

http://stackoverflow.com/q/50744488
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88496946
has comment: http://stackoverflow.com/comment/88496902
has comment: http://stackoverflow.com/comment/88496915
answer count: 0
has comment: http://stackoverflow.com/comment/88497023
type: Question
has body: The for loop has 3 iterations (and will be more soon). Is it possible to define a standard value for assign_organizer after the second loop? [...] name = ['Super Bowl 2018', 'Jon Summer 2019', 'Jon Summer 2020', ] slug = ['super-bowl-2018', 'jon-summer-2019', 'jon-summer-2020', ] first_organizer = Organizer.objects.all().first() last_organizer = Organizer.objects.all().last() assign_organizer = [first_organizer, last_organizer, ] for i in range(len(name)): Event.objects.create( organizer=assign_organizer[i], name=name[i], slug=slug[i], status='on_sale', short_description=lorem, additional_information=lorem_long, venue_name=lorem, venue_address=lorem, start_date='2018-05-26 18:12:58.556925+02', end_date='2018-05-26 18:12:58.556925+02', facebook_event_link=lorem, banner=lorem, ) __Update__: I now tried the solution suggested in the comments, however, I am not getting the expected outcome. (I now instead of having a default, just decided it's better to start at the beginning again.) Expected: TEST 1: A TEST 2: 1 Assigned: a1 TEST 1: B TEST 2: 2 Assigned: a2 TEST 1: C TEST 2: 3 Assigned: a1 Actual outcome: However, it is instead stopping after the second loop. test1 = ['A', 'B', 'C'] test2 = ['1', '2', '3'] assigned_raw = ['a1', 'a2'] assigned = itertools.chain(assigned_raw) for a, b, c in zip(test1, test2, assigned): print("TEST 1: ", a) print("TEST 2: ", b) print("Assigned: ", c)
has comment: http://stackoverflow.com/comment/88496866
has title: Python: Default value in for loop
score: 0
has comment: http://stackoverflow.com/comment/88496890
has comment: http://stackoverflow.com/comment/88498124
type: UnansweredQuestion

http://stackoverflow.com/q/50775354
tagged with: scrapy
has body: I'm trying to scrape applicant data from a table with Scrapy. I'm having two issues: 1) I want a CSV with each applicant on each row: 'username': ['clickclack123'],'lsat':['170'],'gpa':['3.57']... My code currently extracts all of the applicant data in one row, ignores null values, and iterates that extraction for the number of applicants on the page (100 identical rows where each row contains all of the data on the page): 'username': ['clickclack123','UM2014','3litersaday'... 2) The table contains a class of elements ('signifiers') which indicate applicant traits. I want to include an If statement to check the signifier and save each trait as True if applicable. I've included an If statement with this logic in lawschool.py (below), but it doesn't allow my spider to run. My thoughts &amp; attempts: For Issue #1, I've seen posts with similar issues, but those solutions haven't worked in this case because my data contains null values which I do not want ignored. I believe there's an issue with my For loop because it isn't iterating properly over each applicant, but I haven't been able to fix it. It currently extracts all of the data on the page into one row of my CSV, but iterates that extraction for the number of applicants on the page (100 identical rows where each row contains all of the data on the page). If I change extract() to extract_first(), the spider will only extract the data for the first applicant (100 identical rows where each row contains the data from the first applicant). For Issue #2, I'm not sure why my code doesn't run with this If statement and I've had to comment it out to troubleshoot Issue #1. lawschool.py import scrapy from ..items import ApplicantItem class LawschoolSpider(scrapy.Spider): name = "lawschool" start_urls = [ 'http://nyu.lawschoolnumbers.com/applicants', 'http://columbia.lawschoolnumbers.com/applicants' ] def parse(self, response): items = [] for applicant in response.xpath("//tr[@class='row']"): signifier = response.xpath("//sp…
has title: Scrapy spider does not iterate properly & has an If statement issue
type: Question
tagged with: for-loop
answer count: 1
has answer: http://stackoverflow.com/a/50776074
score: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/62565388
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50777999
has body: If you are using an RPi, there are many tutorials, but I assume you aren't using that. You might want to take a look at this video: https://www.youtube.com/watch?v=icniGw3Euq4

http://stackoverflow.com/a/50818525
accepted answer of: http://stackoverflow.com/q/50816375
has comment: http://stackoverflow.com/comment/120320108
type: AcceptedAnswer
has body: Your area you look at is simply much larger than your input points. This doesn't matter for 'nearest' as this always puts the nearest value to a certain coordinate. But 'linear' and 'cubic' do not extrapolate but fill the values which are not within the input area with nan by default. See also the docs of griddata: fill_value : float, optional Value used to fill in for requested points outside of the convex hull of the input points. If not provided, then the default is nan. This option has no effect for the ‘nearest’ method. Best understandable when plotted by imshow: plot created with: import numpy as np from scipy.interpolate import griddata x = np.array([0.03,0.05,0.033]) y = np.array([0.004,0.01,0.02]) z = np.array([1,2,3]) xy = np.zeros((2,np.size(x))) xy[0] = x xy[1] = y xy = xy.T grid_x, grid_y = np.mgrid[0.0:0.09:250*1j, 0.0:0.03:250*1j] #generating the grid fig, axs = plt.subplots(3) for i, i_type in enumerate(['cubic', 'nearest', 'linear']): #, cubic grid_z = griddata(xy, z, (grid_x, grid_y), method=i_type) #check if there is a nan in the z grid: axs[i].imshow(grid_z) axs[i].set_title(i_type) plt.tight_layout()
answers question: http://stackoverflow.com/q/50816375
type: Answer
has comment: http://stackoverflow.com/comment/121718426
has comment: http://stackoverflow.com/comment/88643870
upvote count: 10
downvote count: 1
score: 9

http://stackoverflow.com/q/50709439
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50709506
type: Question
has comment: http://stackoverflow.com/comment/88429677
tagged with: virtualenvwrapper
has title: mkvirtualenv not creating virtualenv when specifying python version
tagged with: python-2.7
answer count: 1
tagged with: virtualenv
score: 0
linked to: http://stackoverflow.com/q/39814281
tagged with: python
has comment: http://stackoverflow.com/comment/88428736
has body: I currently have Python 2.7 and 3.6 installed locally. I installed virtualenv and virtualenvwrapper with pip3. When I do not specify the the python version (i.e. $ mkvirtualenv hello) everything goes smoothly and I get the following output: "Using base prefix '/home/rishi_gurnani/python' New python executable in /home/rishi_gurnani/.virtualenvs/hello/bin/python3.6 Also creating executable in /home/rishi_gurnani/.virtualenvs/hello/bin/python Installing setuptools, pip, wheel...done. virtualenvwrapper.user_scripts creating /home/rishi_gurnani/.virtualenvs/hello/bin/predeactivate virtualenvwrapper.user_scripts creating /home/rishi_gurnani/.virtualenvs/hello/bin/postdeactivate virtualenvwrapper.user_scripts creating /home/rishi_gurnani/.virtualenvs/hello/bin/preactivate virtualenvwrapper.user_scripts creating /home/rishi_gurnani/.virtualenvs/hello/bin/postactivate virtualenvwrapper.user_scripts creating /home/rishi_gurnani/.virtualenvs/hello/bin/get_env_details" However, when I specify that I want python2.7 (i.e. $ mkvirtualenv -p python2.7 hello2) I get: "Running virtualenv with interpreter /home/rishi_gurnani/python/bin/python2.7" So no virtualenv is being created anywhere. In other words, I'm only able to create a virtualenv with Python 3.6. but I would also like to create one which uses 2.7 instead.
tagged with: python-3.x

http://stackoverflow.com/comment/88559013
score: 0
has text: Can you give us the location of the pictures relative to the scripts in your filesystem?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50775649

http://stackoverflow.com/q/50840664
has body: I'm manipulating data with pandas and having some trouble when using for loops. Basically, I'm dealing with some time series with prices, and I have to calculate the percentage change in daily prices; I only need to work with these values, and only for the last 750 days. Say I have three data frames, one for each product A, B, and C, which include only date and daily price. I've written this: import pandas as pd products= [A, B, C] for df in products: df["change"] = df["price"].pct_change() df.drop(index = [0], columns="price", inplace = True) df = df.iloc[-751:-1] Now, this works properly except for the final line in the for loop. Instead of overwriting the original data frame for A, B, and C, it only modifies the dataframe currently under the label df; this shows in the variable list, where df is the only data frame with 750 rows, all the others have what they originally had minus the one dropped. Any idea on how to fix this? On a similar note, I've got a question about memory usage. For things like this, say I want to run regressions or do some analysis of the data, which would be better, keeping each product in a separate data frame, or merging them into one big data frame? And does panda have regression-style functionalities, or would it be better to use some other library, like numpy? Thanks a lot in advance!
type: Question
tagged with: pandas
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50841082
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/50841827
tagged with: dataframe
type: UnansweredQuestion
tagged with: time-series
upvote count: 0
has title: Python - Pandas manipulating data frames in loops
favorite count: 0

http://stackoverflow.com/comment/88562851
type: QuestionComment
comment on: http://stackoverflow.com/q/50777729
score: 0
has text: How do you define a word?
type: Comment

http://stackoverflow.com/comment/88663216
comment on: http://stackoverflow.com/a/50828055
score: 0
type: Comment
type: AnswerComment
has text: I just added the setup code I used and it works perfectly for me on pandas 0.23. What version of pandas are you running?

http://stackoverflow.com/comment/88543845
type: AnswerComment
has text: What do you mean by work? Were devolving an app for the athletic department at our university so the data is extremely sensitive as it relates to student athletes and theird private information.
comment on: http://stackoverflow.com/a/50767333
type: Comment
score: 0

http://stackoverflow.com/comment/88418328
has text: Because it's easier to resume execution with a coroutine (and they're easier to write since the system mostly takes care of maintaining state for you.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50704483

http://stackoverflow.com/a/50837239
has comment: http://stackoverflow.com/comment/88679929
has body: There are a few problems with your code: Your filename does not end with .py, but Python modules are expected to. You can fix this by setting suffix='.py' in NamedTemporaryFile(). __import__() is not the right way to load a module from a full path. See here: How to import a module given the full path? You do not flush after writing and before importing, so even if Python does find the file, it may well be empty. Add tmp.flush() after writing to fix this.
answers question: http://stackoverflow.com/q/50836941
has comment: http://stackoverflow.com/comment/88678573
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/88678413
type: Answer

http://stackoverflow.com/comment/88460754
comment on: http://stackoverflow.com/a/50725148
type: AnswerComment
has text: {{ total_likes }} in html ?
score: 0
type: Comment

http://stackoverflow.com/a/50832583
has body: I add some fix to my gist for working when the length of the message to encrypt don't mach with a multiple of 16 chars.
answers question: http://stackoverflow.com/q/50784981
score: 0
type: Answer

http://stackoverflow.com/a/53600756
type: Answer
answers question: http://stackoverflow.com/q/50779720
has body: Perhaps the limitation is system or text expression specific. Since I am able to execute the command locally. http://blog.johnmuellerbooks.com/2013/06/14/limitations-of-the-findstr-utility/ There is a real limit on the length of your search string. The utility appears to have a search string length limitation.
accepted answer of: http://stackoverflow.com/q/50779720
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50780111
tagged with: python-3.x
has title: Keyboard input in Pygame not working
has body: I'm trying to create a virtual synthesizer with pygame and some other libraries. The note can be played in two ways: by clicking a button on the screen or by pressing keys on the keyboard. The keyboard input does not work while clicking on the screen does. The following code is the Pygame loop where both the input types have been specified. for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = True if event.type == pygame.K_ESCAPE: crashed = True if pygame.mouse.get_pos()[0] in range(0, 50) and pygame.mouse.get_pos()[1] in range(400, 450) and event.type == pygame.MOUSEBUTTONDOWN: button(sineCod, (0, 255, 0)) wave_1 = 0 # sine elif pygame.mouse.get_pos()[0] in range(100, 150) and pygame.mouse.get_pos()[1] in range(400, 450) and event.type == pygame.MOUSEBUTTONDOWN: button(sawCod, (0, 255, 0)) wave_1 = 1 # saw elif pygame.mouse.get_pos()[0] in range(200, 250) and pygame.mouse.get_pos()[1] in range(400, 450) and event.type == pygame.MOUSEBUTTONDOWN: button(squareCod, (0, 255, 0)) wave_1 = 2 # saw elif pygame.mouse.get_pos()[0] in range(300, 350) and pygame.mouse.get_pos()[1] in range(400, 450) and event.type == pygame.MOUSEBUTTONDOWN: button(triangleCod, (0, 255, 0)) wave_1 = 3 elif pygame.key.get_focused() is True: print("Receiving Keyboard Focus") if event.type == pygame.locals.KEYDOWN: if event.key == pygame.locals.K_w: # C play(frequencies[0]) if event.key == pygame.locals.K_2: # C# play(frequencies[1]) if event.key == pygame.K_w: # D play(frequencies[2]) if (pygame.mouse.get_pos()[0] in range(40) and pygame.mouse.get_pos()[1] in range( 190)) or (pygame.mouse.get_pos()[0] in range(75) and pygame.mouse.get_pos()[1] in range(190, 320)) and event.type == pygame.MOUSEBUTTONDOWN: # C play(frequencies[0]) elif pygame.mouse.get_pos()[0] in range(75, 150) and pygame.mouse.get_pos()[1] in range( 320) and event.type == pygame.MOUSEBUTTONDOWN: # D play(frequencies[2]) elif pygame.mouse.get_pos()[0] in range(150, 225) and pygame.mouse.get_pos()[1] in range( …
tagged with: python
tagged with: pygame
type: AnsweredQuestion
score: 3
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51128932
upvote count: 5
answer count: 1
accepted answer: http://stackoverflow.com/a/51128932
favorite count: 0

http://stackoverflow.com/comment/88805118
comment on: http://stackoverflow.com/q/50765195
score: 0
type: Comment
type: QuestionComment
has text: Sadly, as far as I know there is no way at the current moment to do that. Sorry that I was not able to provide a helpful way to solve your problem. But things you could do instead would be to : log all activities and processes occurring in your system and to test arguments passed. Both are vital for security and enterprise level coding and skills you definitely should develop towards.

http://stackoverflow.com/comment/88579073
score: 0
type: Comment
type: QuestionComment
has text: By "runs correctly" you mean it does not produce an error? That would be exactly done with the code you have and something like `@pytest.mark.parametrize('a,b,c,d', listofparameterlists)`. Possibly, calling `fig.canvas.draw()` instead of `plt.show()` is more efficient.
comment on: http://stackoverflow.com/q/50774928

http://stackoverflow.com/a/53776413
has body: Although the examples are in .nrrd, PyRadiomics uses SimpleITK for image operations. This allows PyRadiomics to support a whole range of image formats, including .nii.gz. You don't have to convert them.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50845524
type: Answer
upvote count: 1

http://stackoverflow.com/q/50762466
tagged with: pytorch
score: 1
upvote count: 1
type: Question
tagged with: neural-network
accepted answer: http://stackoverflow.com/a/50763021
tagged with: deep-learning
answer count: 1
has body: Building a GAN to generate images. The images have 3 color channels, 96 x 96. The images that are generated by the generator at the beginning are all black, which is an issue given that is statistically highly unlikely. Also, the loss for both networks is not improving. I have posted the entire code below, and commented to allow it to be easily read. This is my first time building a GAN and I am new to Pytorch so any help is very appreciated! import torch from torch.optim import Adam from torch.utils.data import DataLoader from torch.autograd import Variable import numpy as np import os import cv2 from collections import deque # training params batch_size = 100 epochs = 1000 # loss function loss_fx = torch.nn.BCELoss() # processing images X = deque() for img in os.listdir('pokemon_images'): if img.endswith('.png'): pokemon_image = cv2.imread(r'./pokemon_images/{}'.format(img)) if pokemon_image.shape != (96, 96, 3): pass else: X.append(pokemon_image) # data loader for processing in batches data_loader = DataLoader(X, batch_size=batch_size) # covert output vectors to images if flag is true, else input images to vectors def images_to_vectors(data, reverse=False): if reverse: return data.view(data.size(0), 3, 96, 96) else: return data.view(data.size(0), 27648) # Generator model class Generator(torch.nn.Module): def __init__(self): super(Generator, self).__init__() n_features = 1000 n_out = 27648 self.model = torch.nn.Sequential( torch.nn.Linear(n_features, 128), torch.nn.ReLU(), torch.nn.Linear(128, 256), torch.nn.ReLU(), torch.nn.Linear(256, 512), torch.nn.ReLU(), torch.nn.Linear(512, 1024), torch.nn.ReLU(), torch.nn.Linear(1024, n_out), torch.nn.Tanh() ) def forward(self, x): img = self.model(x) return img def noise(self, s): x = Variable(torch.randn(s, 1000)) return x # Discriminator model class Discriminator(torch.nn.Module): def __init__(self): super(Discriminator, self).__init__() n_features = 27648 n_out = 1 self.model = torch.nn.Sequential( torch.nn.Linear(n_fea…
downvote count: 0
has title: Debugging GAN covergence
favorite count: 0
tagged with: python
tagged with: generative-adversarial-network
has answer: http://stackoverflow.com/a/50763021
type: AnsweredQuestion

http://stackoverflow.com/a/50745329
has comment: http://stackoverflow.com/comment/88498443
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/88499870
score: 8
has comment: http://stackoverflow.com/comment/88500759
answers question: http://stackoverflow.com/q/50745248
has comment: http://stackoverflow.com/comment/88498546
accepted answer of: http://stackoverflow.com/q/50745248
has body: Since Python 3.5+, you can use unpacking in a list declaration. Use that inside a list-comprehension: lst = [['a', [0, 1]], ['b', [2, 3]], ['c', [4, 5]]] new_lst = [[x, *more] for x, more in lst] print(new_lst) # [['a', 0, 1], ['b', 2, 3], ['c', 4, 5]]
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88634682
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50814675
has text: Edit your post, delete all the code, copy/paste it again, then select the _whole_ code snippet and click the "code" button (the one labeled "{}") in the editor's toolbar. Double check (in the preview) that everything's ok, submit, done.

http://stackoverflow.com/comment/88474464
score: 0
comment on: http://stackoverflow.com/q/50724680
type: Comment
type: QuestionComment
has text: Gotcha, I solve it finally, thanks @TomDalton

http://stackoverflow.com/q/50807274
type: Question
has answer: http://stackoverflow.com/a/50807642
has answer: http://stackoverflow.com/a/50807298
has body: I have a list of integers: lists = [8,7,2] I want it to be: result = 872 I can do it in the following way: result = 0 for count, i in enumerate(reversed(lists)): result += i*(10**count) It works. but I think there should be another better and faster way. Thanks in advance
accepted answer: http://stackoverflow.com/a/50807298
has title: Convert list of integers to an integer python
upvote count: 1
possible better answer: http://stackoverflow.com/a/50807324
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50807324
has answer: http://stackoverflow.com/a/50808413
tagged with: python
answer count: 4
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/88648051
type: AnswerComment
type: Comment
has text: Thanks @anishtain4 . Indeed the function is periodic. My input is real, so I am using `numpy.fft.rfft`.
comment on: http://stackoverflow.com/a/50820234
score: 0

http://stackoverflow.com/a/50849660
downvote count: 0
answers question: http://stackoverflow.com/q/50849639
type: Answer
has body: Try changing: file.write(input('Entrer la première chaîne (minimum 4 caractères):')) file.write(input('Entrer la deuxième chaîne (minimum 1 caractères):')) To: file.write(input('Entrer la première chaîne (minimum 4 caractères):')+'\n') file.write(input('Entrer la deuxième chaîne (minimum 1 caractères):')+'\n') You will need to manually handle the newline characters on the end of each line. Also remember to close your file pointer file with file.close() once your done using it to ensure a clean exit.
score: 1
upvote count: 1

http://stackoverflow.com/q/50841829
has comment: http://stackoverflow.com/comment/88687746
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50842248
favorite count: 0
tagged with: pandas
tagged with: python
has body: I have a dataframe that looks like this: allHoldingsFund BrokerBestRate notional_current DistanceBestRate 0 CITI 7.859426e+05 0.023194 1 WFPBS 3.609674e+06 -0.023041 2 WFPBS 1.488828e+06 -0.023041 3 JPM 3.484168e+05 -0.106632 4 CITI 6.088499e+05 0.023194 5 WFPBS 8.665558e+06 -0.023041 6 WFPBS 4.219563e+05 -0.023041 I am trying to do a sum product and a group by in one go (without creating an extra column of sum product) I have tried this line of code allHoldingsFund.groupby(['BrokerBestRate'])['notional_current']*['DistanceBestRate'].sum() how can I do a sum product and then aggregate it using group by? Desired output BrokerBestRate product of (notional_current and DistanceBestRate) CITI 654654645665466 JPM 453454534545367 WFPBS 345345345345435 Many Thanks
upvote count: 6
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50842292
accepted answer: http://stackoverflow.com/a/50842248
score: 6
type: Question
has comment: http://stackoverflow.com/comment/88687451
has comment: http://stackoverflow.com/comment/88687907
has comment: http://stackoverflow.com/comment/88687940
possible better answer: http://stackoverflow.com/a/50842292
tagged with: group-by
tagged with: sum
has title: Sum product and groupby

http://stackoverflow.com/q/50741393
has comment: http://stackoverflow.com/comment/88492283
answer count: 0
has comment: http://stackoverflow.com/comment/88490325
type: UnansweredQuestion
has body: [EDITED] Hello guys, I am trying to learn tensorflow to build a specific application, so I was trying to recreate this example(https://medium.com/@curiousily/human-activity-recognition-using-lstms-on-android-tensorflow-for-hackers-part-vi-492da5adef64) I found on the internet. Building the model: N_CLASSES = 6 N_HIDDEN_UNITS = 64 def create_LSTM_model(inputs): W = { 'hidden': tf.Variable(tf.random_normal([N_FEATURES, N_HIDDEN_UNITS])), 'output': tf.Variable(tf.random_normal([N_HIDDEN_UNITS, N_CLASSES])) } biases = { 'hidden': tf.Variable(tf.random_normal([N_HIDDEN_UNITS], mean=1.0)), 'output': tf.Variable(tf.random_normal([N_CLASSES])) } X = tf.transpose(inputs, [1, 0, 2]) X = tf.reshape(X, [-1, N_FEATURES]) hidden = tf.nn.relu(tf.matmul(X, W['hidden']) + biases['hidden']) hidden = tf.split(hidden, N_TIME_STEPS, 0) # Stack 2 LSTM layers lstm_layers = [tf.contrib.rnn.BasicLSTMCell(N_HIDDEN_UNITS, forget_bias=1.0) for _ in range(2)] lstm_layers = tf.contrib.rnn.MultiRNNCell(lstm_layers) outputs, _ = tf.contrib.rnn.static_rnn(lstm_layers, hidden, dtype=tf.float32) # Get output for the last time step lstm_last_output = outputs[-1] return tf.matmul(lstm_last_output, W['output']) + biases['output'] Creating placeholders for our model: tf.reset_default_graph() X = tf.placeholder(tf.float32, [None, N_TIME_STEPS, N_FEATURES], name="input") Y = tf.placeholder(tf.float32, [None, N_CLASSES]) pred_Y = create_LSTM_model(X) pred_softmax = tf.nn.softmax(pred_Y, name="y_") L2_LOSS = 0.0015 l2 = L2_LOSS * \ sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = pred_Y, labels = Y)) + l2 LEARNING_RATE = 0.0025 optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(loss) correct_pred = tf.equal(tf.argmax(pred_softmax, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, dtype=tf.float32)) The problem is with the model training: N_EPOCHS = 50 BATCH_SIZE = 1024 saver = tf.t…
tagged with: tensorflow
type: Question
has title: Tensorflow loss and accuracy don't change among epochs
score: 0
has comment: http://stackoverflow.com/comment/88655219
tagged with: python

http://stackoverflow.com/comment/88521970
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50742331
has text: If you add that as an answer with an explanation as to _why_ it fixes it, I'll accept yours as the answer.

http://stackoverflow.com/a/50825480
type: Answer
answers question: http://stackoverflow.com/q/50825208
accepted answer of: http://stackoverflow.com/q/50825208
score: 15
has comment: http://stackoverflow.com/comment/126517785
upvote count: 15
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/126524458
has body: From documentation of numpy.copy: This is equivalent to: &gt;&gt;&gt; np.array(a, copy=True) Also, if you look at the source code: def copy(a, order='K'): return array(a, order=order, copy=True) Some timings: In [1]: import numpy as np In [2]: a = np.ascontiguousarray(np.random.randint(0, 20000, 1000)) In [3]: %timeit b = np.array(a) 562 ns ± 10.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [4]: %timeit b = np.array(a, order='K', copy=True) 1.1 µs ± 10.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [5]: %timeit b = np.copy(a) 1.21 µs ± 9.28 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [6]: a = np.ascontiguousarray(np.random.randint(0, 20000, 1000000)) In [7]: %timeit b = np.array(a) 310 µs ± 6.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [8]: %timeit b = np.array(a, order='K', copy=True) 311 µs ± 2.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [9]: %timeit b = np.copy(a) 313 µs ± 4.33 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [10]: print(np.__version__) 1.13.3 It is unexpected that simply explicitly setting parameters to their default values changes the speed of execution of np.array(). On the other hand, maybe just processing these explicit arguments adds enough execution time to make a difference for small arrays. Indeed, from the source code for the numpy.array(), one can see that there are many more checks and more processing being performed when keyword arguments are provided, for example, see goto full_path. When keyword parameters are not set, the execution skips all the way down to goto finish. This overhead (of additional processing of keyword arguments) is what you detect in timings for small arrays. For larger arrays this overhead is insignificant in comparison to the actual time of copying the arrays.
has comment: http://stackoverflow.com/comment/102758502

http://stackoverflow.com/comment/88419459
type: QuestionComment
has text: a user can only have one account, so what´s the point?
comment on: http://stackoverflow.com/q/50704809
score: 0
type: Comment

http://stackoverflow.com/comment/88483488
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50737695
has text: Is there any reason why you're using `ZlibCodec` and not `ZlibStream`?
score: 0

http://stackoverflow.com/comment/88668875
type: Comment
type: QuestionComment
has text: "as-is" and "as they are" *where*, though? Are you just copying and pasting them from something into your terminal?
score: 0
comment on: http://stackoverflow.com/q/50832080

http://stackoverflow.com/comment/88460736
type: Comment
comment on: http://stackoverflow.com/a/50725532
type: AnswerComment
has text: Here is problem you need convert string to dictionaries before creating `DataFrame`, so `json_normalize(df['metadata'])` cannot work.
score: 0

http://stackoverflow.com/a/50825690
has comment: http://stackoverflow.com/comment/88656298
answers question: http://stackoverflow.com/q/50825652
score: 1
accepted answer of: http://stackoverflow.com/q/50825652
type: Answer
has comment: http://stackoverflow.com/comment/88656365
upvote count: 1
has body: add a break once the book has been found, and declare a True or False to a variable that detects if it's been found: def prompt_read_book(): book_to_search = input("Write the NAME of the book you want to mark as 'READ':\n") found = False for book in database.books: if book_to_search.lower() == book["name"]: print(f"The book '{book_to_search}' is now marked as READ") book["read"] = True print("-" * 40) found = True break if not found: print(f"Sorry but the book {book_to_search} is not in the database") print("-" * 40) EDIT: i just edited my answer since i misread the last part. now it will only print the "Sorry but..." if it wasn't found.
has comment: http://stackoverflow.com/comment/88656253
has comment: http://stackoverflow.com/comment/88656764
has comment: http://stackoverflow.com/comment/88658407
downvote count: 0
has comment: http://stackoverflow.com/comment/88656213
type: AcceptedAnswer

http://stackoverflow.com/comment/88549592
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50770699
has text: The response body is mainly a javascript link and ` You need to enable JavaScript to run this app buddy `, so you I think you will need to run the javascript to get the data you want.
score: 0

http://stackoverflow.com/a/50779859
has body: You can consider functools.partialmethod, which allows you to specify any number of args or kwargs: from functools import partialmethod mappings = {'Jets Fans': partialmethod(BaseFilter.for_jets_fans, 'Jets'), 'Patriots Fans': partialmethod(BaseFilter.for_patriots_fans, 'Patriots'), 'NFC Fans': partialmethod(BaseFilter.for_team_fans, 'Bears', 'Packers')}
accepted answer of: http://stackoverflow.com/q/50779810
type: AcceptedAnswer
upvote count: 2
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50779810

http://stackoverflow.com/comment/88471924
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50731742
type: QuestionComment
has text: @abarnert when I was swimming thru a sea of docs, I saw a table with several functions reporting results for different OS in millisecs, microsecs, etc. So, what I meant was "fractions of a second" seemed unusually vague for docs that are often very, very precise.

http://stackoverflow.com/a/50781174
has body: I'll write a small snippet, extend it to your wish. First, create a file named 'scoreboard.txt' in the same folder as your game. Do the following to get the details before starting the game. f = open('scoreboard.txt', 'r') name = f.readline() high_score = int(f.readline()) f.close() Check if they've got a highscore and get username (new_name) too: if current_score &gt; high_score: f = open('scoreboard.txt', 'w') f.write(new_name + '\n' + str(current_score)) f.close() NOTE: For the first time, fill the file with some random data like 'BOB' (press enter key), '24'. Hope it helps! Comment if there's any doubts!
has comment: http://stackoverflow.com/comment/88569628
answers question: http://stackoverflow.com/q/50780831
score: 0
has comment: http://stackoverflow.com/comment/88570057
has comment: http://stackoverflow.com/comment/88569468
has comment: http://stackoverflow.com/comment/88569475
type: Answer
has comment: http://stackoverflow.com/comment/88570779

http://stackoverflow.com/comment/88692804
type: Comment
has text: Can you post the expected output?
comment on: http://stackoverflow.com/q/50844688
score: 0
type: QuestionComment

http://stackoverflow.com/a/50811187
type: Answer
has body: conda upgrade --all Upgrade your library and restart your notebook.This will do the work.
answers question: http://stackoverflow.com/q/50810519
score: 0
has comment: http://stackoverflow.com/comment/88629577

http://stackoverflow.com/q/50773103
answer count: 1
tagged with: javascript
accepted answer: http://stackoverflow.com/a/50773771
score: 0
has body: I'm making automation script in python using selenium so i want to visible textarea box because i want to put it into some arguments and i'm using this code: element = driver.find_element_by_id('g-recaptcha-response') driver.execute_script("arguments[0].style.display = '';", element) driver.execute_script("arguments[0].style.margin = '100px 200px';", element) but above code is not working for me as you can see here: Could you please tell me how I can show textarea box? Link to the page.
tagged with: python
has title: how i can visible textarea box using javascript
tagged with: selenium
has answer: http://stackoverflow.com/a/50773771
type: AnsweredQuestion
tagged with: captcha
type: Question
tagged with: automation

http://stackoverflow.com/comment/88624133
comment on: http://stackoverflow.com/q/50808996
score: 0
type: Comment
type: QuestionComment
has text: the class attribute should be one of "starting-price", "age-weight" etc., i think

http://stackoverflow.com/q/50853691
possible better answer: http://stackoverflow.com/a/50853968
has comment: http://stackoverflow.com/comment/88753569
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50854403
linked to: http://stackoverflow.com/q/36522220
has body: I need to find the index of the first occurrence of three consecutive negative numbers. In the normal Python way I would do it like this: a = [1,-1,1,-1,1,-1,1,-1,-1,-1,1,-1,1] b=0 for i,v in enumerate(a): if v&lt;0: b+=1 else: b=0 if b==3: break indx = i-2 Anyone has an idea how to do it in a smarter NumPy way?
type: Question
tagged with: numpy
tagged with: algorithm
has answer: http://stackoverflow.com/a/50853968
tagged with: arrays
has title: NumPy - catching the index of first three consecutive negative numbers
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50854917
accepted answer: http://stackoverflow.com/a/50854917
has comment: http://stackoverflow.com/comment/88711705
has comment: http://stackoverflow.com/comment/88710256
favorite count: 0
has comment: http://stackoverflow.com/comment/88741992
has comment: http://stackoverflow.com/comment/88753550

http://stackoverflow.com/q/50721525
tagged with: parsing
has answer: http://stackoverflow.com/a/50721734
tagged with: python
linked to: http://stackoverflow.com/q/973473
answer count: 4
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50721801
has comment: http://stackoverflow.com/comment/88456466
has body: File Structure I have a folder, called test_folder, which has several subfolders (named different fruit names, as you'll see in my code below) within it. In each subfolder, there is always a metadump.xml file where I am extracting information from. Current Stance I have been able to achieve this on an individual basis, where I specify the subfolder path. import re in_file = open("C:/.../Downloads/test_folder/apple/metadump.xml") contents = in_file.read() in_file.close() title = re.search('&lt;dc:title rsfieldtitle="Title" rsembeddedequiv="Name" rsfieldref="8" rsfieldtype="0"&gt;(.+?)&lt;/dc:title&gt;', contents).group(1) print(title) Next Steps I would like to perform the following function on a larger scale by simply referencing the parent folder C:/.../Downloads/test_folder and making my program find the xml file for each subfolder to extract the desired information, rather than individually specifying every fruit subfolder. Clarification Rather than simply obtaining a list of subfolders or a list of xml files within these subfolders, I would like physically access these subfolders to perform this text extraction function from each xml file within each subfolder. Thanks in advance for your help.
type: Question
has title: Accessing text file within subfolder
has comment: http://stackoverflow.com/comment/88452775
tagged with: subdirectory
has answer: http://stackoverflow.com/a/50722510
accepted answer: http://stackoverflow.com/a/50722510
score: 0
has comment: http://stackoverflow.com/comment/88452239
has comment: http://stackoverflow.com/comment/88451831
has answer: http://stackoverflow.com/a/50721801
has answer: http://stackoverflow.com/a/50721824
tagged with: directory

http://stackoverflow.com/q/50710037
tagged with: reshape
tagged with: python
type: AnsweredQuestion
tagged with: pytorch
score: 1
accepted answer: http://stackoverflow.com/a/50710801
upvote count: 1
has title: How reshape 3D tensor of shape (3, 1, 2) to (1, 2, 3)
type: Question
possible better answer: http://stackoverflow.com/a/50710120
has body: I intended (Pdb) aa = torch.tensor([[[1,2]], [[3,4]], [[5,6]]]) (Pdb) aa.shape torch.Size([3, 1, 2]) (Pdb) aa tensor([[[ 1, 2]], [[ 3, 4]], [[ 5, 6]]]) (Pdb) aa.view(1, 2, 3) tensor([[[ 1, 2, 3], [ 4, 5, 6]]]) But what I really want is tensor([[[ 1, 3, 5], [ 2, 4, 6]]]) How? In my application, I am trying to transform my input data of shape (L, N, C_in) to (N, C_in, L) in order to use Conv1d, where L: sequence length N: batch size C_in: number of channels in the input, I also understand it as the dimensionality of the input at each position of a sequence. I am also wondering the input of Conv1d doesn't have the same input shape as GRU?
has answer: http://stackoverflow.com/a/50710120
answer count: 2
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/50710801
favorite count: 0
tagged with: tensor

http://stackoverflow.com/a/50763015
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50762877
type: AcceptedAnswer
downvote count: 0
has body: Surely there is a better, built in method that reads in a file and does these modifications automatically, right? Since your file constains a lot of lines, it's a good idea to read the content line by line instead of whole content. But you can simplify this by using a list comprehension. with open('/Users/macroot/Desktop/data.txt') as f: array = [int(line) for line in f] Also, if you're using numpy library you can apply array = np.genfromtxt('/Users/macroot/Desktop/data.txt', dtype=np.int32) which returns a generator.
accepted answer of: http://stackoverflow.com/q/50762877
type: Answer
has comment: http://stackoverflow.com/comment/88534597

http://stackoverflow.com/q/50793468
type: AnsweredQuestion
tagged with: twitter
has title: how to get Twitter username from a tweet- PYTHON
has answer: http://stackoverflow.com/a/50793971
answer count: 1
favorite count: 0
tagged with: python
tagged with: tweepy
accepted answer: http://stackoverflow.com/a/50793971
score: 2
upvote count: 3
has body: I am new at tweepy, I was able to fetch data from twitter with following script : import tweepy from tweepy import OAuthHandler access_token="---------" access_token_secret="----------" consumer_key="---------" consumer_secret="-------" auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) public_tweets = api.home_timeline() print("public_tweets.text") now want to fetch the username of the twitting person as well fetched tweets as example: "USERNAME": " --------------TWEET----------" Thank You in advance
downvote count: 1
type: Question

http://stackoverflow.com/q/50727212
type: Question
accepted answer: http://stackoverflow.com/a/50727305
has title: Pandas change rows in DataFrame without assignment
has body: Say we have a Python Pandas DataFrame: In[1]: df = pd.DataFrame({'A': [1, 1, 2, 3, 5], 'B': [5, 6, 7, 8, 9]}) In[2]: print(df) A B 0 1 5 1 1 6 2 2 7 3 3 8 4 5 9 I want to change rows that match a certain condition. I know that this can be done via direct assignment: In[3]: df[df.A==1] = pd.DataFrame([{'A': 0, 'B': 5}, {'A': 0, 'B': 6}]) In[4]: print(df) A B 0 0 5 1 0 6 2 2 7 3 3 8 4 5 9 My question is: Is there an equivalent solution to the above assignment that would return a new DataFrame with the rows changed, i.e. a stateless solution? I'm looking for something like pandas.DataFrame.assign but which acts on rows instead of columns.
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50727305
score: 1
upvote count: 1

http://stackoverflow.com/a/50830758
type: Answer
downvote count: 0
score: 1
has body: This question is totally solvable in Python. In my case, the only thing I need is testing whether the JSON string can be transferred across programs without saving a file, like I indicated in the title. What I need is subprocess module in second.py to execute first.py in a subprocess, and then pipe the results for subsequent procedures. import json import subprocess import re # Get stdout from first.py raw_result = subprocess.run(["python", "first.py"], stdout=subprocess.PIPE) # Capture the JSON string material_str = re.search(r".+({.+})", str(raw_result.stdout)).group(1) # Load the JSON string as a dictionary material = json.loads(material_str) # Make juice def blender(material): serving = material["fruit"] + " juice" return serving print(blender(material)) By executing python second.py and entering "Apple", it returns "Apple juice" perfectly.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50742621
answers question: http://stackoverflow.com/q/50742621

http://stackoverflow.com/comment/88595689
type: AnswerComment
comment on: http://stackoverflow.com/a/50746320
type: Comment
has text: @Peslier53, You can use `'first'`, `'last'`, `'max'`, `'min'`, etc. It should be intuitive.
score: 0

http://stackoverflow.com/q/50822565
has comment: http://stackoverflow.com/comment/88659660
has body: I have a pandas dataframe (df) Parameter Date Concentration Unit Prescribed Standard Exceeding Standard? (Yes/No) Remarks 1 NaN 02/01/2017 26.10 Âµg/m3 NaN NaN NaN 2 NaN 03/01/2017 30.27 Âµg/m3 NaN NaN NaN 3 NaN 04/01/2017 36.36 Âµg/m3 NaN NaN NaN 4 NaN 05/01/2017 33.41 Âµg/m3 NaN NaN NaN I am trying to plot the timeseries plot of Date vs Concentration I converted the dates to datetime object using .to_datetime() Parameter Date Concentration Unit Prescribed Standard Exceeding Standard? (Yes/No) Remarks 1 NaN 2017-01-02 26.10 Âµg/m3 NaN NaN NaN 2 NaN 2017-01-03 30.27 Âµg/m3 NaN NaN NaN 3 NaN 2017-01-04 36.36 Âµg/m3 NaN NaN NaN 4 NaN 2017-01-05 33.41 Âµg/m3 NaN NaN NaN The time series plot is easily done using: plt.plot(df["Date"][:322], df["Concentration"][:322], "+", color="red", linewidth=0.5) But if I try to change the xlabels to anything else, say month names, plt.xticks(["Jan", "Feb","Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"])]) I get an error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~/.local/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in _convert_listlike(arg, box, format, name, tz) 302 try: --&gt; 303 values, tz = tslib.datetime_to_datetime64(arg) 304 return DatetimeIndex._simple_new(values, name=name, tz=tz) pandas/_libs/tslib.pyx in pandas._libs.tslib.datetime_to_datetime64() TypeError: Unrecognized value type: &lt;class 'str'&gt; During handling of the above exception, another exception occurred: OutOfBoundsDatetime Traceback (most recent call last) ~/.local/lib/python3.6/site-packages/pandas/plotting/_converter.py in _convert_1d(values, unit, axis) 310 try: --&gt; 311 values = tools.to_datetime(values) 312 if isinstance(values, Index): ~/.local/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin) 379 elif is_list_like(ar…
tagged with: datetime
accepted answer: http://stackoverflow.com/a/50840152
tagged with: python
has title: Unable to set plt.xticks in matplotlib
has comment: http://stackoverflow.com/comment/88660090
type: Question
type: AnsweredQuestion
tagged with: time-series
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50840152
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/88673526
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50834762
score: 0
has text: It looks to me that the counting is probably the problem. Perhaps you should try to solve the problem at the database side, by making a table that stores the aggregate, and periodically updates it.

http://stackoverflow.com/comment/88584415
type: QuestionComment
score: 2
has text: Is your requirement just that URLs containing `'wikipedia'` in them go first? Are there any other sorting requirements?
comment on: http://stackoverflow.com/q/50788921
type: Comment

http://stackoverflow.com/q/50826007
accepted answer: http://stackoverflow.com/a/50826195
upvote count: 1
type: Question
has title: Collapse 3 Text Colums into 1 within a wide Pandas DataFrame
has answer: http://stackoverflow.com/a/50826244
has body: I have a dataset with one data type spread across multiple columns. I'd like to reduce these to a single column. I have a function that accomplishes this, but its a cumbersome process and I'm hoping there's a cleaner way to accomplish this. Here's a toy sample of my data: UID COMPANY EML MAI TEL 273 7UP nan nan TEL 273 7UP nan MAI nan 906 WSJ nan nan TEL 906 WSJ EML nan nan 736 AIG nan MAI nan What I'd like to get to: UID COMPANY CONTACT_INFO 273 7UP MT 906 WSJ ET 736 AIG M I've solved this by writing a function that converts EML, MAI or TEL to a prime number, aggregates the results then converts the sum into the constituent contact types. This works, and is reasonably quick. Here's a sample: def columnRedux(df): newDF = df.copy() newDF.fillna('-', inplace=True) newDF['CONTACT_INFO'] = newDF['EML'] + newDF['MAI'] + newDF['TEL'] newDF.replace('EML--', 7, inplace=True) newDF.replace('-MAI-', 101, inplace=True) newDF.replace('--TEL', 1009, inplace=True) small = newDF.groupby(['UID', 'COMPANY'], as_index=False)['CONTACT_INFO'].sum() small.replace(7, 'E', inplace=True) small.replace(101, 'M', inplace=True) small.replace(108, 'EM', inplace=True) small.replace(1009, 'T', inplace=True) small.replace(1016, 'ET', inplace=True) small.replace(1110, 'MT', inplace=True) small.replace(1117, 'EMT', inplace=True) return small df1 = pd.DataFrame( {'EML' : [np.nan, np.nan, np.nan, 'EML', np.nan, np.nan, 'EML', np.nan, np.nan, 'EML', 'EML', np.nan], 'MAI' : [np.nan, 'MAI', np.nan, np.nan, 'MAI', np.nan, np.nan, np.nan, 'MAI', np.nan, np.nan, 'MAI'], 'COMPANY' : ['7UP', '7UP', 'UPS', 'UPS', 'UPS', 'WSJ', 'WSJ', 'TJX', 'AIG', 'CDW', 'HEB', 'HEB'], 'TEL' : ['TEL', np.nan, 'TEL', np.nan, np.nan, 'TEL', np.nan, 'TEL', np.nan, np.nan, np.nan, np.nan], 'UID' : [273, 273, 865, 865, 865, 906, 906, 736, 316, 458, 531, 531]}, columns=['UID', 'COMPANY', 'EML', 'MAI', 'TEL']) cleanDF = columnRedux(df1) My issue is that I have several data sets, each with its own set of "wide" columns. Some have 5+ …
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/50826792
possible better answer: http://stackoverflow.com/a/50826244
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50826195
favorite count: 0
tagged with: reduction
tagged with: pandas
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50739700
has comment: http://stackoverflow.com/comment/88487603
has comment: http://stackoverflow.com/comment/88489496
score: 0
has body: In SQLite, you can implement the logic as: with t as ( select t1.contract_ref, t1.transaction_date, sum(t1.amount) as amount from t1 group by t1.contract_ref, t1.transaction_date ) select t.*, (select sum(t2.amount) from t t2 where t2.contract_ref = t.contract_ref and t2.transaction_date &lt;= t.transaction_date ) as running_amount from t;
type: Answer
answers question: http://stackoverflow.com/q/50739607

http://stackoverflow.com/comment/88557205
score: 0
type: AnswerComment
type: Comment
has text: you can make it a bit shorter `df = {'mail1@m.com' : ['text1', 'text2']}`
comment on: http://stackoverflow.com/a/50774965

http://stackoverflow.com/comment/88690629
type: QuestionComment
has text: Why exactly can't you cast the iterable to a list?
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50843490

http://stackoverflow.com/q/50716186
score: 1
has comment: http://stackoverflow.com/comment/88441045
tagged with: face-recognition
has body: I'm currently working in a face recognition project using OpenCV and python. The thing is, that the accuracy of the face recognition is not so good, so I'm thinking about adding more images in the data path, with different lighting, backgrounds etc in order to improve it. The problem here is that whenever I use cv2.imwrite("data/User."+str(face_ID)+"."+str(count)+".jpg", gray[y:y+h, x:x+w]) it overwrites the previous saved images in the path. I works fine, but I just want to do something like appending the new images to the path, every time I run the function. Here is the data generator section. def data_generator(): count = 0 # asking user for data input face_ID = input("[INFO] Please enter user ID and press &lt;return&gt; ") print("[INFO] Thank you\n Now please look at the camera and wait.") # start the video capture cap = cv2.VideoCapture(0) try: while True: # Here we detect the face ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detecting faces faces = detector.detectMultiScale(gray, scaleFactor = 1.3, minNeighbors = 5, minSize= (20, 20) ) for (x, y, w, h) in faces: cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2) roi_gray = gray[y:y+h, x:x+w] roi_img = img[y:y+h, x:x+w] count += 1 cv2.imwrite("data/User."+str(face_ID)+"."+str(count)+".jpg", gray[y:y+h, x:x+w]) cv2.imshow('img', img) k = cv2.waitKey(10) &amp; 0xff if k == 27: break elif count &gt;= 30: break except KeyboardInterrupt: pass print("[INFO] Data gathered.") print("[INFO] Saving Data.") print("[INFO] Exiting program and cleanup stuff") cap.release() cv2.destroyAllWindows()
has answer: http://stackoverflow.com/a/50717852
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88441913
has comment: http://stackoverflow.com/comment/88441647
has title: Adding to the Face Recognition data path new images , and not overwriting them
tagged with: python
has comment: http://stackoverflow.com/comment/94646427
upvote count: 1
type: Question
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50717852

http://stackoverflow.com/a/50849804
score: 1
upvote count: 1
has body: Replace the third line with this: height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()])) It works by removing all alphabets before converting to float.
has comment: http://stackoverflow.com/comment/88702971
has comment: http://stackoverflow.com/comment/88702626
accepted answer of: http://stackoverflow.com/q/50849790
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88702597
type: Answer
answers question: http://stackoverflow.com/q/50849790

http://stackoverflow.com/q/50748511
favorite count: 0
has answer: http://stackoverflow.com/a/50749634
tagged with: element
has body: Using python, I would like to count the occurrence of a lists elements for each row in a dataframe, and aggregate each elements occurrence. Here is the dataframe I am working with: #Cluster_number_1 Cluster Type: terpene #Cluster_number_2 Cluster Type: nrps #Cluster_number_3 Cluster Type: terpene #Cluster_number_4 Cluster Type: nrps #Cluster_number_5 Cluster Type: nrps #Cluster_number_6 Cluster Type: nrps #Cluster_number_7 Cluster Type: t1pks #Cluster_number_8 Cluster Type: other #Cluster_number_9 Cluster Type: t1pks #Cluster_number_10 Cluster Type: nrps The corresponding list: cluster_type = ["t1pks", "nrps", "terpene", "other"] Desired output: BGC_Class Count t1pks 2 nrps 5 terpene 2 other 1 To help explain, borrowing from unix $ variables: file = "cluster_counts.txt" cluster_count = open(file, "w") cluster_count.write(+$1+"\t"+$2"\n") Where $1 is the first element in the list, and $2 is the number of times it occurs, across all rows. The dataframes won't exceed 100 lines, so efficiency is no issue. Best, B.D. I found something to get me started here How to count the occurrences of a list item?. &gt;&gt;&gt; l = ["a","b","b"] &gt;&gt;&gt; [[x,l.count(x)] for x in set(l)] [['a', 1], ['b', 2]] However this only counts the occurrences of elements within the list containing it. I don't know how to count the occurrence of my lists elements in the dataframe.
tagged with: python
has comment: http://stackoverflow.com/comment/88504529
tagged with: list
has title: Pandas dataframe: Count occurrence of list element in dataframe rows
upvote count: 3
type: UnansweredQuestion
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/50748533
tagged with: dataframe
linked to: http://stackoverflow.com/q/2600191
score: 0
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/50852003
answers question: http://stackoverflow.com/q/50851878
score: 0
type: Answer
has body: Lists have an index method, like so: wordlist = ['zebra', 'piano', 'fly'] deflist = ['is an animal','is a musical instrument','is an insect'] request = input("Word: ") if request in wordlist: print(deflist[wordlist.index(request)]) However this is inefficient as it iterates over the list twice

http://stackoverflow.com/comment/88551872
type: QuestionComment
comment on: http://stackoverflow.com/q/50772096
score: 0
has text: `/mnt/c/Users/myusername/AppData/Local/Programs/Python/Python36-32/python.exe /mnt/c/Users/myusername/AppData/Local/Programs/Python/Python36-32/python3.dll /mnt/c/Users/myusername/AppData/Local/Programs/Python/Python36-32/python36.dll /usr/share/man/man1/python.1.gz`
type: Comment

http://stackoverflow.com/comment/88697142
score: 1
has text: Or you could just do `a.get('f', lambda: 'None')()`. But I think the `KeyError` handling is more readable, even if a bit more verbose.
type: AnswerComment
comment on: http://stackoverflow.com/a/50846646
type: Comment

http://stackoverflow.com/comment/88456085
comment on: http://stackoverflow.com/q/50723687
type: Comment
type: QuestionComment
has text: I see no underscores in your data. In your example please explain how floor `2` maps to Totalfloor `1`, floor `1-2` maps to Totalfloor `2`, and floor `-1` maps to Totalfloor `1`.
score: 1

http://stackoverflow.com/a/50807495
has body: If I understand correctly, you can do this: # Set the multiple that you want the size of each group to be: n = 2 # Groupby ID, then apply .head() to get the size you want: df.groupby('ID').apply(lambda x: x.head(len(x) - len(x) % n)).reset_index(drop=True) Time ID X_Pos Y_Pos 0 1 1 150 300 1 2 1 160 310 2 4 2 300 439 3 5 2 200 500 4 6 3 500 320 5 7 3 400 230 6 8 3 500 540 7 9 3 450 600 Note that this is essentially equivalent to your attempt with iloc, and there is no need for the round_down function: df.groupby('ID').apply(lambda x: x.iloc[:len(x)-len(x)%n]).reset_index(drop=True) Both of those will take the beginning of the data of each group, up to the nearest multiple of n. If instead, you want random data (instead of the beginning of the data) for each group, but for the size of each group to still be a multiple of n, use sample instead of head/iloc: df.groupby('ID').apply(lambda x: x.sample(len(x) - len(x) % n)).reset_index(drop=True) Time ID X_Pos Y_Pos 0 2 1 160 310 1 1 1 150 300 2 4 2 300 439 3 5 2 200 500 4 9 3 450 600 5 10 3 400 600 6 8 3 500 540 7 6 3 500 320
accepted answer of: http://stackoverflow.com/q/50807175
answers question: http://stackoverflow.com/q/50807175
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/88535680
type: QuestionComment
has text: The `grad_input` tensor is `None`. Check if `X` is actually linked to the subgraph computing the loss
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50761702

http://stackoverflow.com/comment/88421118
score: 2
has text: Your title mentions `os.rename`, but your code only has `os.remove`. Is that intentional?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50705982

http://stackoverflow.com/comment/88637858
has text: I am using 2.7, is that a problem? Official apache documentation mentions that it is available only for 3.5 and above.
comment on: http://stackoverflow.com/a/50794028
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88601006
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50797289
has text: +Sijan Bhandari I'm sorry, I can't, it's private. They are about 50 rows and 50 columns (roughly) of ASCII characters. I could generate some spoof data, but I don't see why it is necessary.
score: 0

http://stackoverflow.com/q/50715058
answer count: 1
has comment: http://stackoverflow.com/comment/88438774
has body: I want to use a list comprehension to achieve the same results as below. Can anyone help? s1 = "one two three four" s2 = "five six seven eight" my_list = [] l1 = s1.split() l2 = s2.split() my_list.append(l1) my_list.append(l2) print(my_list) It outputs: [['one', 'two', 'three', 'four'], ['five', 'six', 'seven', 'eight']]
has title: How to use list comprehensions for this code
linked to: http://stackoverflow.com/q/6696027
has answer: http://stackoverflow.com/a/50715091
duplicate of: http://stackoverflow.com/q/6696027
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88438771
tagged with: list-comprehension
type: Question
has comment: http://stackoverflow.com/comment/88438749

http://stackoverflow.com/q/50804420
has comment: http://stackoverflow.com/comment/88614890
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88614945
has title: Run code alongside a Flask application
type: Question
has answer: http://stackoverflow.com/a/50809310
downvote count: 2
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/88615960
tagged with: flask
has comment: http://stackoverflow.com/comment/88623318
has comment: http://stackoverflow.com/comment/88616334
tagged with: python
favorite count: 0
has body: I've written a web interface for my python application. This functions beautifully when running export FLASK_APP=main.py followed by flask run. Now I want the actual application to also run, so the interface can be useful. The code below is my main.py, where I call the flask applications factory function. from webinterface import create_app if __name__ == '__main__': create_app() while(True): # Some code logging different things I want to do stuff inside the infinite loop, however when I try to run the application, it either runs only the web interface or the infinte loop, depending if I start it using flask run or python main.py. How do I best accomplish this?
upvote count: 0

http://stackoverflow.com/q/50754836
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88522917
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88518027
tagged with: python
has comment: http://stackoverflow.com/comment/88517517
has comment: http://stackoverflow.com/comment/101409591
has body: I am facing a rather strange issue. I'm trying to run a .js script inside a python script. In my .js script I convert .pdf to json and then call this .js script inside .py script which converts this json to .xlsx. But using Popen to execute the .js script the error appears : "[WinError 2] The system cannot find the file specified". I've rechecked the error location almost 10 times now. I've checked the cwd too its correct. Everything's is in place except this error. Please help me. :( import pandas as pd from subprocess import Popen, PIPE import os cwd = os.getcwd() bankType = "parsePmc" parser_path = os.path.join(cwd, "parse_pmc_bank_pdf.js") input_file_path = os.path.join(cwd, "bs.pdf") output_file_path = os.path.join(cwd, "bs_excel.xlsx") print(parser_path) print(input_file_path) print(output_file_path) #parser_path = parser_path.replace("\\","\\\\") #(Even this doesn't work.) print(parser_path) args = ["node", parser_path, input_file_path, output_file_path] #I've even checked it using with str() for the paths. print(os.getcwd()) p = Popen(args, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() print(stdout) if bool(stderr): print(stderr) else: df = pd.read_json(output_file_path) if df.empty: print("EMPTY XLSX") else: df.to_excel(output_file_path, sheet_name='Raw') [Error:] --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) &lt;ipython-input-40-e3dffdd7e5db&gt; in &lt;module&gt;() 1 args = ["node", str(parser_path)] 2 print(os.getcwd()) ----&gt; 3 p = Popen(args, stdout=PIPE, stderr=PIPE) 4 stdout, stderr = p.communicate() 5 print(stdout) C:\ProgramData\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors) 705 c2pread, c2pwrite, 706 errread, errwrite, --&gt; 707 restore_signals, start_new…
tagged with: subprocess
answer count: 0
has title: python : [WinError 2] The system cannot find the file specified
type: Question
tagged with: popen
tagged with: file-not-found
has comment: http://stackoverflow.com/comment/88520015
has comment: http://stackoverflow.com/comment/88520318
score: 0
has comment: http://stackoverflow.com/comment/101413489

http://stackoverflow.com/comment/88484753
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50736486
has text: That's true, you can edit those details in if you want, or i'll do it later (on mobile now)
score: 0

http://stackoverflow.com/a/50736445
answers question: http://stackoverflow.com/q/50735576
type: Answer
accepted answer of: http://stackoverflow.com/q/50735576
score: 1
upvote count: 1
has body: No, there is noparameter for restore-db-instance-from-db-snapshot to change the backup period. The RestoreDBClusterFromSnapshot documentation shows the BackupRetentionPeriod as an Output, but not an Input. It appears to use the same value as the cluster when the Snapshot was made.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50787904
accepted answer: http://stackoverflow.com/a/50787954
favorite count: 0
has answer: http://stackoverflow.com/a/69109523
tagged with: flask-wtforms
tagged with: python
possible better answer: http://stackoverflow.com/a/69109523
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13798313
type: Question
has title: How to override the html default "Please fill out this field" when validation fails in Flask?
upvote count: 12
tagged with: wtforms
has body: I have a Flask-WTF form with with DataRequired validators and related error messages. However, the Chrome browser seems to ignore my error messages and just displays "Please fill out this field". How do I get Flask to override this and show my messages? from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired class SignupForm(FlaskForm): first_name = StringField('First Name', validators=[DataRequired(message='Hey, put in your first name!')]) last_name = StringField('Last Name', validators=[DataRequired("What, you can't remember your last name?")]) email = StringField('Email', validators=[DataRequired('Gonna need your email address!')]) password = PasswordField('Password', validators=[DataRequired('Really need a password, Dude!')]) submit = SubmitField('Sign Up')
tagged with: flask
has answer: http://stackoverflow.com/a/50787954
score: 12
answer count: 2
downvote count: 0

http://stackoverflow.com/a/50750857
answers question: http://stackoverflow.com/q/50749845
has comment: http://stackoverflow.com/comment/88523603
type: Answer
upvote count: 1
has body: Your code works, after replacing -iterations by --iterations and calling it like this: python toy_script.py -b0.3 -k20 (tested on Windows)
score: 1
accepted answer of: http://stackoverflow.com/q/50749845
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88547887
type: Comment
comment on: http://stackoverflow.com/a/50770175
has text: it seems to me that in your windows configuration you have not enabled the visibility of the extensions, and instead of having the file somefile.txt you have a file called somefile.txt.txt
type: AnswerComment
score: 0

http://stackoverflow.com/q/50719584
has comment: http://stackoverflow.com/comment/88448305
has comment: http://stackoverflow.com/comment/88450329
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88448058
score: 1
tagged with: java
type: Question
has body: I have created a serverless function in Java and need to call a python script from this function. I included the script within the zip file and deployed in AWS. When running my function I am getting: Caused by: java.io.IOException: Cannot run program "python": error=2, No such file or directory I searched a bit and found that AWS has support for Python Lambdas but in my case I need to call a python script from a Java Lambda. Is this supported from AWS or is there any trick I can do ?
has title: How to call python from Java serverless function in AWS
upvote count: 1
tagged with: amazon-web-services
favorite count: 0
tagged with: serverless-framework
has comment: http://stackoverflow.com/comment/88448960
tagged with: python

http://stackoverflow.com/comment/88575785
comment on: http://stackoverflow.com/q/50784647
score: 0
has text: `a = b` does not copy the data from `b` to a new location in `a`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88484737
comment on: http://stackoverflow.com/q/50733466
type: QuestionComment
has text: thanks @raviraja for the info, I think I am on the right track now, I am going to make multiple dataframes and concatenate them into one single frame and then use 'to_sql' to transfer this data frame to MySQL server.
score: 0
type: Comment

http://stackoverflow.com/comment/88627140
type: Comment
has text: https://stackoverflow.com/questions/15269161/in-python-how-to-join-a-list-of-tuples-into-one-list
comment on: http://stackoverflow.com/q/50810879
score: 0
type: QuestionComment

http://stackoverflow.com/q/50786034
accepted answer: http://stackoverflow.com/a/50827140
tagged with: python
type: AnsweredQuestion
has title: TensorBoard recording stats separate from training
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50827140
has comment: http://stackoverflow.com/comment/88583207
has comment: http://stackoverflow.com/comment/88581639
score: 0
tagged with: tensorboard
answer count: 1
has body: I'm trying to use TensorBoard to display some graphs of a neural network training run. (That is, graphs of test and validation accuracy during training, not just of the network structure.) There is some example code As well as some questions on this site, all of which seem to follow the same pattern as the example code. That is, the pattern always revolves around something like summary, _ = sess.run([merged, train_step], ... So basically, the operations of running a training step and recording statistics for graph display, are being conflated. This is fine as far as it goes, but I'm trying to retrofit the graph to an existing program that inevitably does things in a slightly different way, so the example code won't work as is. What I really want to do is isolate some code that just records the statistics, separate from existing code to do the training. How do you record statistics for TensorBoard, within the main training loop, but separate from the code that does the training?

http://stackoverflow.com/a/50834663
has comment: http://stackoverflow.com/comment/88675030
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50834560
has comment: http://stackoverflow.com/comment/88675562
has body: You cannot "expand" a tuple obviously since tuples are immutables, but you can create a new tuple by concatenating two or more tuples: &gt;&gt;&gt; t1 = (1, 2, 3) &gt;&gt;&gt; t2 = (0, 0, 0) &gt;&gt;&gt; t = t1 + t2 &gt;&gt;&gt; t (1, 2, 3, 0, 0, 0)
downvote count: 0
type: Answer

http://stackoverflow.com/a/50849881
has body: I think that the simplest way of finding all pixels that fall within the contour is as follows. The contour is described by a set of non-integer points. We can think of these points as vertices of a polygon, the contour is a polygon. We first find the bounding box of the polygon. Any pixel outside of this bounding box is not inside the polygon, and doesn't need to be considered. For the pixels inside the bounding box, we test if they are inside the polygon using the classical test: Trace a line from some point at infinity to the point, and count the number of polygon edges (line segments) crossed. If this number is odd, the point is inside the polygon. It turns out that Matplotlib contains a very efficient implementation of this algorithm. I'm still getting used to Python and Numpy, this might be a bit awkward code if you're a Python expert. But it is straight-forward what it does, I think. First it computes the bounding box of the polygon, then it creates an array points with the coordinates of all pixels that fall within this bounding box (I'm assuming the pixel centroid is what counts). It applies the matplotlib.path.contains_points method to this array, yielding a boolean array mask. Finally, it reshapes this array to match the bounding box. import math import matplotlib.path import numpy as np x_pixel_nos = [...] y_pixel_nos = [...] # Data from https://gist.github.com/sdoken/173fae1f9d8673ffff5b481b3872a69d temp_list = [] for a, b in zip(x_pixel_nos, y_pixel_nos): temp_list.append([a, b]) polygon = np.array(temp_list) left = np.min(polygon, axis=0) right = np.max(polygon, axis=0) x = np.arange(math.ceil(left[0]), math.floor(right[0])+1) y = np.arange(math.ceil(left[1]), math.floor(right[1])+1) xv, yv = np.meshgrid(x, y, indexing='xy') points = np.hstack((xv.reshape((-1,1)), yv.reshape((-1,1)))) path = matplotlib.path.Path(polygon) mask = path.contains_points(points) mask.shape = xv.shape After this code, what is necessary is to locate the bounding box within th…
has comment: http://stackoverflow.com/comment/88956924
has comment: http://stackoverflow.com/comment/88949483
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50847827
has comment: http://stackoverflow.com/comment/88955570
accepted answer of: http://stackoverflow.com/q/50847827
score: 5
has comment: http://stackoverflow.com/comment/88949002
upvote count: 5

http://stackoverflow.com/q/50810864
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88654487
tagged with: swig
score: 1
has body: I am trying to access a C++ function from python by using SWIG for wrapping. The function uses two arrays as inputs of length cL and another as output of some smaller length. The SWIG .i file is : %module polcvx %include "typemaps.i" %apply int *INPUT {int *cL}; %typemap(in) float r[cL] (float temp[cL]) { int i; if (!PySequence_Check($input)) { PyErr_SetString(PyExc_ValueError, "Expected a sequence"); SWIG_fail; } if (PySequence_Length($input) != cL) { PyErr_SetString(PyExc_ValueError, "Size mismatch. Expected more or less elements than 4th argument"); SWIG_fail; } for (i = 0; i &lt; cL; i++) { PyObject *o = PySequence_GetItem($input, i); } $1 = temp; } %typemap(in) float t[cL] (float temp1[cL]) { int i; if (!PySequence_Check($input)) { PyErr_SetString(PyExc_ValueError, "Expected a sequence"); SWIG_fail; } if (PySequence_Length($input) != cL) { PyErr_SetString(PyExc_ValueError, "Size mismatch. Expected more or less elements than 4th argument"); SWIG_fail; } for (i = 0; i &lt; cL; i++) { PyObject *o = PySequence_GetItem($input, i); } $2 = temp1; } %typemap(in, numinputs=0) int *hull[ANY] (int temp2[ANY]) { $3 = &amp;temp2; } %typemap(argout) int *hull[ANY] { int i; $result = PyList_New($3_dim0); for (i = 0; i &lt; $3_dim0; i++) { PyObject *o = PyFloat_FromDouble((double) $3[i]); PyList_SetItem($result, i, o); } } %{ #define SWIG_FILE_WITH_INIT #include "cvxp.hpp" %} int cvx( int hull[],float r[], float t[], int cL); and implemented in python as import _polcvx rad=[10,5,2,20,15,7,10,45,12] theta=[0.5236 , 0.7854 , 1.5708 , 2.6180 , 2.9671 , 3.3161 , 4.0143 , 4.7124 , 6.1087] l=len(rad) ls=[] i=_polcvx.cvx(5,rad2,theta,l) I am getting an error in python Traceback (most recent call last): File "E:\Hull\cpp and py conversion\CvxPolar.py", line 65, in &lt;module&gt; i=_polcvx.cvx(ls,rad2,theta,l) TypeError: in method 'cvx', argument 1 of type 'int []' Since the function uses pointer to access array variable, cant figure out the correct configuration to be done in .i file.
has comment: http://stackoverflow.com/comment/88663739
has title: multiple array input and array output: SWIG C++ to python
tagged with: arrays
downvote count: 0
tagged with: inout
favorite count: 0
has comment: http://stackoverflow.com/comment/88856098
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/88650439
has comment: http://stackoverflow.com/comment/88712978

http://stackoverflow.com/comment/88692146
type: QuestionComment
comment on: http://stackoverflow.com/q/50844354
has text: Traceback (most recent call last): File "C:\Python notes\func-2.py", line 3, in <module> subprocess.check_output(a) File "C:\Python27\lib\subprocess.py", line 212, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "C:\Python27\lib\subprocess.py", line 390, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 640, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified
score: 0
type: Comment

http://stackoverflow.com/q/50852405
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/88707634
score: 0
has comment: http://stackoverflow.com/comment/88707935
has answer: http://stackoverflow.com/a/50852872
has body: I'm finding that when adding a series, based on the same time-period, to an existing dataframe it gets imported as NaNs. The dataframe has a field column, but I don't understand why that should change anything. To see the steps of my code, you can review the attached image. Hope that someone can help! Illustration showing how the dataframe that the series is inserted into and how it gets read as NaN
has comment: http://stackoverflow.com/comment/88708430
tagged with: dataframe
type: UnansweredQuestion
tagged with: pandas
has title: Pandas series inserted into dataframe are read as NaN
tagged with: series
has comment: http://stackoverflow.com/comment/88707470
type: Question
tagged with: python
answer count: 1

http://stackoverflow.com/comment/88572904
has text: thanks Attersson. Am I right to say if I use .map(str), I will get low performance but if I use .astype(str) I will get relatively good because latter is just one operation?
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50782999

http://stackoverflow.com/q/50835383
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88674838
type: Question
tagged with: java
has comment: http://stackoverflow.com/comment/88676728
has title: Running Java code from IntelliJ which runs python code and needs virtualenv
has body: I'm running (and debugging) Java code from IntelliJ. This code runs some python code which needs to be run from a specific Virtualenv. I couldn't find an option to set up a virtualenv from IntelliJ IDEA, there is any workaround I could go for? Any help is appreciated, Thanks a lot
tagged with: intellij-idea
has comment: http://stackoverflow.com/comment/88675442
tagged with: virtualenv
tagged with: python

http://stackoverflow.com/comment/88472891
type: QuestionComment
has text: Since you didn’t test your input, I copied and pasted it into an online validator, and it’s not valid JSON. So that’s your answer. What you do about it depends on a number of things you haven’t told us. How much control do you have over the code that generates this corrupt not-quite-JSON? If you can fix that, or get it fixed, that will be orders of magnitude easier and better than trying to parse garbage. If you can’t, then it depends on how much data you have to scan and/or code you can read to reverse engineer the garbage, how close to 100% your garbage-processing has to be, etc.
comment on: http://stackoverflow.com/q/50731989
score: 0
type: Comment

http://stackoverflow.com/q/50832315
tagged with: ironpython
answer count: 1
has answer: http://stackoverflow.com/a/50985689
has comment: http://stackoverflow.com/comment/88672453
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88858273
accepted answer: http://stackoverflow.com/a/50985689
favorite count: 0
has title: ValueError: The name 'Subject identification [Individual/Pool]' already exists in the column collection. Parameter name: value
type: Question
tagged with: spotfire
tagged with: python
has body: The code below is returning an error: I didn't find this error googlying.. import datetime from Spotfire.Dxp.Data import IndexSet from Spotfire.Dxp.Data import RowSelection from Spotfire.Dxp.Data import IndexSet, DataValueCursor, RowSelection from Spotfire.Dxp.Data.DataType import DateTime dictTable = Document.Data.Tables['Column renaming mapping'] dictionary = dict() key = 0 value = 0 colNum = 0 cursorKeys = DataValueCursor.CreateFormatted(dictTable.Columns['PDW short name']) cursorValues = DataValueCursor.CreateFormatted(dictTable.Columns['PDW long name']) rowCount = dictTable.RowCount rowsToInclude = IndexSet(rowCount,True) for row in dictTable.GetRows(rowsToInclude,cursorKeys,cursorValues): rowIndex = row.Index key = cursorKeys.CurrentValue print key val = cursorValues.CurrentValue print val dictionary[key] = val for table in Document.Data.Tables: for col in table.Columns: if col.Name in dictionary: col.Name = dictionary[key] Certainly I do something wrong. My goal is to iterate tru all the tables and modify the naming of some columns. I want them modified as per table I called discTable. Adding full error plus print results as per what code generates. TSRECID TS Record ID STUDYKEY PDW unique ID INSERTDT Record entry date UPDATEDT Record update date AUDITID Transaction unique ID SPONSOR Sponsor PSMSNAME Preclinical Study Management System STUDYID Study ID STUDYTITLE Study title PROJID PIMS project ID PROJDESC PIMS project description ETHICPROJ PIMS ethical project STUDYCAT PIMS study category STUDYTP PIMS study type PROTSTATUS PIMS protocol status STDPROTID PIMS standard protocol ID RATIONALE Scientific Rationale PRIMOBJECTIVE Primary objective SECOBJECTIVE Secondary objective NBSUBJECTS Number of subjects SUBLVLID Subject identification [Individual/Pool] Traceback (most recent call last): File "Spotfire.Dxp.Application.ScriptSupport", line unknown, in ExecuteForDebugging File "&lt;string&gt;", line 31, in &lt;module&gt; File "Spotfire.Dxp.Data", line unknown, i…
upvote count: 2

http://stackoverflow.com/q/50785533
has body: I'm trying to make a flexible argument parser which takes strings, finds arguments within them and creates a dictionary like this: message = "--mass=12" physics = comparse(message, "mass", "int", 10, "this is your mass attribute") Produces: {'mass': 12} I'm unable to update and add more arguments/keys (like if I wanted to add a 'vel' variable) to the dictionary. Unfortunately, I'm new to Python classes and although the parser detects the first argument, I'm unable to add to the dictionary. Here's my program: import shlex class comparse(object): def __init__(self, message, attribute, var_type, default, help_txt): self.data = {} #This is the "data" dictionary that this function will ultimately return. self.message = message self.attribute = attribute self.var_type = var_type self.default = default self.help_txt = help_txt #Remove unwanted symbols (e.g. "=", ":", etc.) self.message = self.message.replace("=", " ") self.message = self.message.replace(":", " ") self.args = shlex.split(self.message) def parse(self): try: options = {k.strip('-'): True if v.startswith('-') else v for k,v in zip(self.args, self.args[1:]+["--"]) if k.startswith('-') or k.startswith('')} if (self.var_type == "int"): self.data[self.attribute] = int(options[self.attribute]) #Updates if "attribute" exists, else adds "attribute". if (self.var_type == "str"): self.data[self.attribute] = str(options[self.attribute]) #Updates if "attribute" exists, else adds "attribute". except: if self.attribute not in self.message: if (self.var_type == "int"): self.data[self.attribute] = int(self.default) #Updates if "x" exists, else adds "x". if (self.var_type == "str"): self.data[self.attribute] = str(self.default) #Updates if "x" exists, else adds "x". return self.data def add_argument(self): self.data.update(self.data) message = "-mass: 12 --vel= 18" physics = comparse(message, "mass", "int", 10, "this is your mass attribute") comparse.add_argument(message, "vel", "int", 10, "this is your velocity attribute") p…
has answer: http://stackoverflow.com/a/50785561
has title: How to get class method to update dictionary?
has answer: http://stackoverflow.com/a/50785761
accepted answer: http://stackoverflow.com/a/50785761
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50785561
type: Question
tagged with: oop
score: 0
answer count: 2

http://stackoverflow.com/q/50835541
has answer: http://stackoverflow.com/a/50837681
has comment: http://stackoverflow.com/comment/88678729
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88678263
tagged with: unicode
has title: Python: How do I interact with unicode filenames on Windows? (Python 2.7)
tagged with: windows
answer count: 1
accepted answer: http://stackoverflow.com/a/50837681
has comment: http://stackoverflow.com/comment/88678368
favorite count: 0
has comment: http://stackoverflow.com/comment/88678517
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88675674
tagged with: ntfs
has body: My problem: Start with US Windows 10 install Create a Japanese filename in Windows explorer Open the Python shell, and os.listdir('.') The listed filename is full of question marks. os.path.exists() unsurprisingly reports file not found. NTFS stores the filename as Unicode. I'm sure if I used the win32api CreateFile() series of functions I will get my Unicode filename back, however those APIs are too cumbersome (and not portable). I'd prefer that I get utf-8 encoded filenames, or the Unicode bytes from the FS directory structure, but in default mode this doesn't seem to happen. I have tried playing around with setlocale() but I haven't stumbled upon the correct arguments to make my program work. I do not want to (and cannot) install additional code pages onto the Windows machine. This needs to work with a stock install of Windows. Please note this has nothing to do with the console. A repr() shows that the ? chars that end up in the filename listed by os.listdir('.') are real question marks and not some display artifact. I assume they have been added by the API that listdir() uses under the hood.

http://stackoverflow.com/comment/88651338
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50822222
has text: does your machine is an ec2 instance? then you can assign a role to the instance and aws-sdk will acquire temporary credentials by itself (using metadata services)
score: 0

http://stackoverflow.com/q/50774845
tagged with: stream
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88722323
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Turning Python generator inside out for GRPC Streaming Endpoint
tagged with: python
has comment: http://stackoverflow.com/comment/88731610
tagged with: generator
has comment: http://stackoverflow.com/comment/88738008
answer count: 0
tagged with: grpc
score: 1
has body: I have a GRPC server that streams back items to a client. The generation of these items however also depends on async events and various stuff. So I want to allow other components to call the grpc component and pass data to the client via a call. The data then gets sent to the open grpc connection. This is what I have: class SubmitService(ptac_grpc.SubmitServiceServicer): _order_gen: Generator = None def sendOrder(self, msg: ptac_pb2.PBOrder): if SubmitService._order_gen is not None: SubmitService._order_gen.send(msg) else: log.error("could not send order to server, no generator present") def getOrders(self, request, context): """DO NOT CALL from python. This is the API to the adapter""" SubmitService._order_gen = self._inside_out_gen() for msg in SubmitService._order_gen: yield msg def _inside_out_gen(self) -&gt; Generator: while True: #turning a generator inside out yield (yield) My GRPC Endpoint is called getOrders. It is called by the connecting client. The code above assumes there is just the one client for now. Would it work?

http://stackoverflow.com/comment/88574733
comment on: http://stackoverflow.com/q/50783894
score: 0
has text: provide screenshots of how it looks.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88579807
type: Comment
type: QuestionComment
has text: Use range(0,len(your list), n) for instance.
comment on: http://stackoverflow.com/q/50786744
score: 0

http://stackoverflow.com/comment/88418529
type: QuestionComment
has text: With `df['price'].replace(',','', inplace = True)` , you are replacing `inplace`, which does not return anything.
score: 1
comment on: http://stackoverflow.com/q/50704445
type: Comment

http://stackoverflow.com/comment/88508479
comment on: http://stackoverflow.com/q/50750101
type: QuestionComment
has text: Have you declared @Result before trying to set it?
score: 0
type: Comment

http://stackoverflow.com/a/64368235
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/113825023
type: Answer
answers question: http://stackoverflow.com/q/50718623
has body: Thanks @AntonvBR. Below code worked for me with python 3.7.3 import requests files = {('files', ('aug_template.csv', aug_annotation_df.to_csv()))} response = requests.post(url=UPLOAD_URL, params=params, files=files, data=body)
upvote count: 1

http://stackoverflow.com/q/50841204
has comment: http://stackoverflow.com/comment/88686122
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1894269
tagged with: python
has body: I currently have a string x = ([15, 16, 17, 18, 19, 20, 21, 22, 23], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]). My goal is to convert this entire string into two lists, capturing each numerical value within the list as its own item. x.split(",") returns ['([15', ' 16', ' 17', ' 18', ' 19', ' 20', ' 21', ' 22', ' 23'] and "".join(x) returns '([15 16 17 18 19 20 21 22 23' - neither of which are the result I am looking for. The end result should be two lists, with each number in the list an individual item in numerical format. Does anyone know the best way to accomplish this in python?
has title: Converting string to list Python
type: Question
has answer: http://stackoverflow.com/a/50841260
duplicate of: http://stackoverflow.com/q/1894269
has answer: http://stackoverflow.com/a/50841265
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50841313

http://stackoverflow.com/comment/88580507
comment on: http://stackoverflow.com/q/50786266
score: 0
type: Comment
type: QuestionComment
has text: Nope the dataframes are of unequal dimensions (both unequal rows and/or unequal columns)

http://stackoverflow.com/a/50846646
has body: Your dictionary values are functions. However, you need to remember to actually call your function: a.get('f', 'None')() The result, as expected, is seeing "foo" printed: foo Notice the parentheses () to indicate we want to run the function. To discover what's happening you can also check the type of a['f']: print(type(a['f'])) &lt;class 'function'&gt; The method above, however, is inadvisable, because you can't call None if your key does not exist. In this case, you can catch KeyError: def call_func(dispatcher, key): try: dispatcher[key]() except KeyError: return 'None' call_func(a, 'f') In practice, you will have functions with return statements, to avoid the inconsistency of having a function either print something (and return None) or return a string.
has comment: http://stackoverflow.com/comment/88697142
upvote count: 5
has comment: http://stackoverflow.com/comment/88696834
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50846592
type: Answer
answers question: http://stackoverflow.com/q/50846592

http://stackoverflow.com/comment/88582000
comment on: http://stackoverflow.com/q/50787621
type: Comment
type: QuestionComment
has text: [Related](https://pint.readthedocs.io/en/latest/index.html). Also, if parsing is ambiguous, you can use the implied conversion rate to hopefully rule out some options.
score: 0

http://stackoverflow.com/q/50787516
type: Question
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50788372
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50788092
tagged with: python
has body: I have a pandas data frame that looks like this. set language group version metric_1 metric_2 metric_3 X English 1 A 100 20 5 X French 2 A 90 10 10 X English 1 B 80 30 15 X French 2 B 70 20 20 Y English 1 A 200 20 30 Y French 2 A 180 30 20 Y English 1 B 160 10 10 Y French 2 B 140 20 5 I want to summarize the metrics with all the combinations of the experiment attributes - set, language, group &amp; version. So the summary data frame will look like this. set language group version metric_1 metric_2 metric_3 X 800 140 80 Y 1000 140 80 English 1200 200 80 French 600 80 80 1 1050 120 60 2 750 160 100 A 850 140 80 B 950 140 80 X English 500 100 40 X French 300 40 40 Y English 700 100 40 Y French 300 40 40 X 1 350 60 30 X 2 450 80 50 Y 1 700 60 30 Y 2 300 80 50 X A 350 70 40 X B 450 70 40 Y A 500 70 40 Y B 500 70 40 English 1 ... English 2 ... French 1 ... French 2 ... English A ... English B ... French A ... French B ... 1 A ... 1 B ... 2 A ... 2 B ... X English 1 ... X English 2 ... X French 1 ... X French 2 ... Y English 1 ... Y English 2 ... Y French 1 ... Y French 2 ... X English A ... X English B ... X French A ... X French B ... Y English A ... Y English B ... Y French A ... Y French B ... X 1 A ... X 1 B ... X 2 A ... X 2 B ... Y 1 A ... Y 1 B ... Y 2 A ... Y 2 B ... English 1 A ... English 1 B ... English 2 A ... English 2 B ... French 1 A ... French 1 B ... French 2 A ... French 2 B ... I know I can do this brute force with using the different combinations with groupby and concatenating all of those into a single data frame. This can potentially extend to many more attributes, so I'm trying to find a solution that is more scalable. I've been reading about functions available through itertools, but not sure how they would apply. Appreciate any ideas / directions on this. Thanks!
type: AnsweredQuestion
has title: Getting sum of metrics for combinations of multiple columns
has answer: http://stackoverflow.com/a/50788372
has answer: http://stackoverflow.com/a/50788092

http://stackoverflow.com/comment/88597436
type: Comment
has text: However, this is the most difficult way to do this. Thanks for your answer, and thanks for your effort.
comment on: http://stackoverflow.com/a/50791914
score: 0
type: AnswerComment

http://stackoverflow.com/q/50730622
has comment: http://stackoverflow.com/comment/88469382
has comment: http://stackoverflow.com/comment/88469471
has comment: http://stackoverflow.com/comment/88469477
score: 0
has comment: http://stackoverflow.com/comment/88468976
tagged with: python
has comment: http://stackoverflow.com/comment/88469459
answer count: 0
has title: How to extract values of maximum displacement in abaqus?
type: UnansweredQuestion
has body: square_odb_Path='squaremodalanalysis.odb' squareodb=session.openodb(name=square_odb_Path) max_displacement=0 for x in range(len(squareodb.steps['Loading Step'].frames[-1]\.fieldoutputs['U'].values[0].instance.nodes)): Getting error in line 4!
has comment: http://stackoverflow.com/comment/88479450
tagged with: session
has comment: http://stackoverflow.com/comment/88469473
has comment: http://stackoverflow.com/comment/88479417
type: Question

http://stackoverflow.com/a/50845572
upvote count: 2
has comment: http://stackoverflow.com/comment/88719118
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88725120
has comment: http://stackoverflow.com/comment/88720432
accepted answer of: http://stackoverflow.com/q/50841994
answers question: http://stackoverflow.com/q/50841994
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88696020
has body: A quick pure-Python solution would be: import json with open('path/to/my/file.json','rb') as fh: lines = [json.loads(l) for l in fh.readlines()] # [{'tax_pd': '200003', 'ein': '720378282'}, {'tax_pd': '200012', 'ein': '274027765'}, {'tax_pd': '200012', 'ein': '042746989'}, {'tax_pd': '200012', 'ein': '205993971'}] Looking at your data, you don't have unique keys to do key:value by tax_pd and ein. Assuming there will be collisions, you could do the following: myresults = {} for line in lines: # I'm assuming we want to use tax_pd as the key, and ein as the value, but this can be extended to other keys # This will return None if the tax_pd is not already found if not myresults.get(line.get('tax_pd')): myresults[line.get('tax_pd')] = [line.get('ein')] else: myresults[line.get('tax_pd')] = list(set([line.get('ein'), *myresults[line.get('tax_pd')])) #results #{'200003': ['720378282'], '200012': ['205993971', '042746989', '274027765']} This way you have unique keys, with lists of corresponding unique ein values. Not completely sure if that's what you're going for or not. set will automatically dedup a list, and the wrapping list reconverts the data type You can then lookup by the tax_id explicitly: myresults.get('200012') # ['205993971', '042746989', '274027765'] EDIT: To read from the cloud storage, the code snippet here translated to be a bit easier to use: with gcs.open(filename) as fh: lines = fh.read().split('\n') You can set up your gcs object using their api docs

http://stackoverflow.com/comment/88769125
has text: @IgnacioVazquez-Abrams. The attribute controls what comes in with a star import. It's sometimes useful to import only a part of the public API that way. Nothing to do with C functions at all really.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50844948

http://stackoverflow.com/q/50796930
type: Question
answer count: 2
has title: Size and percentage of elements
downvote count: 0
possible better answer: http://stackoverflow.com/a/50797255
has answer: http://stackoverflow.com/a/50797255
has comment: http://stackoverflow.com/comment/88599987
tagged with: pandas
has body: I'm reading a CSV file with pandas and after I read the file I'd like to calculate 2 things: Number of items % of items For example if my data is [X,X,Y,Z,Z,X,X,Y,Z,Y] , I want my output to be X 4 40.0 Y 3 30.0 Z 3 30.0 I tried the following but it only outputs the sums train = pd.read_csv("./../input/train.csv") grouped = train.groupby([x ,y]).size() And this only calculates the percentages: train = pd.read_csv("./../input/train.csv") grouped = grouped.groupby(level=[0]).apply(lambda x: x / x.sum()) How can I get both?
tagged with: python
has answer: http://stackoverflow.com/a/50797066
favorite count: 0
upvote count: 2
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88600035
accepted answer: http://stackoverflow.com/a/50797066

http://stackoverflow.com/comment/88564019
type: Comment
has text: That would probably be because you're drawing the rectangle to the same image that's being evaluated by your code (in the cv2.rectangle call). You should create a separate variable for visualization.
comment on: http://stackoverflow.com/a/50776426
score: 1
type: AnswerComment

http://stackoverflow.com/q/50777479
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88562040
tagged with: valueerror
favorite count: 0
has comment: http://stackoverflow.com/comment/88562612
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88561953
has answer: http://stackoverflow.com/a/50779406
has title: Retaining leading zeros when typecasting int to string
downvote count: 3
has comment: http://stackoverflow.com/comment/88561939
has comment: http://stackoverflow.com/comment/88562170
has comment: http://stackoverflow.com/comment/88562002
type: Question
has comment: http://stackoverflow.com/comment/88562018
has comment: http://stackoverflow.com/comment/88561912
has comment: http://stackoverflow.com/comment/88566376
has comment: http://stackoverflow.com/comment/88562089
score: -2
has comment: http://stackoverflow.com/comment/88562022
tagged with: string
has comment: http://stackoverflow.com/comment/88561911
has body: I am writing a code in which I break a number into 2 parts, left half and right half. For example 5105 is broken into 51 and 05. For this I write simple code as follows number_xs= str(x) Now the problem is when pass 05 into x. number_xs is only 5. I want it to be 05 as I convert that 0 back to int and pass it somewhere else in code. Right now it takes a bank and throws me an error ValueError: invalid literal for int() with base 10: Further note that I wont know in advance that it is one zero or 2 or 3. say number can be 0075 and want 2 zeros to be there when I typecast. Further posting portion of code def ABC (x): # Dividing number into 2 equal half number_xs= str(x) l_x=len(number_xs)/2 a,b=number_xs[:l_x],number_xs[l_x:] print a a=int(a) b=int(b) #print a #print b Thanks in advance Aashish
tagged with: type-conversion
has comment: http://stackoverflow.com/comment/88562212

http://stackoverflow.com/a/50744149
type: Answer
score: 4
has body: Remove namespace/name from the include: urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] Then set app_name in blog/urls.py: app_name = 'blog' urlpatterns =[ path('', views.list_of_post,name='list_of_post'), path('&lt;slug:slug&gt;/', views.list_of_post,name='post_detail') ] You can read more about this change in the Django 1.9 release notes. As of Django 2.0, you can't set namespace in the include unless app_name is set.
answers question: http://stackoverflow.com/q/50743989
accepted answer of: http://stackoverflow.com/q/50743989
upvote count: 4
has comment: http://stackoverflow.com/comment/88500299
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88498974

http://stackoverflow.com/comment/88459428
score: 0
type: QuestionComment
type: Comment
has text: I also found [this page](http://www.magben.de/?h1=mathematik_fuer_ingenieure_mit_python&h2=kugelflaechenfunktionen) which plots some nice spherical harmonics.
comment on: http://stackoverflow.com/q/50725416

http://stackoverflow.com/comment/88506525
score: 0
has text: Will there always only be one attribute for each class?
comment on: http://stackoverflow.com/q/50749462
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88529608
comment on: http://stackoverflow.com/q/50760319
has text: Why do you pass ord and chr as arguments?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50742713
type: Answer
answers question: http://stackoverflow.com/q/50742667
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50742667
score: 3
has comment: http://stackoverflow.com/comment/88493118
has body: strptime should work: import datetime s = '201806070908' dt = datetime.datetime.strptime(s, '%Y%m%d%M%S') datetime.datetime(2018, 6, 7, 0, 9, 8) You can test that this worked: &gt;&gt;&gt; dt.day 7 &gt;&gt;&gt; dt.month 6 &gt;&gt;&gt; dt.year 2018 &gt;&gt;&gt; dt.minute 9 &gt;&gt;&gt; dt.second 8
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88493314
downvote count: 0
has comment: http://stackoverflow.com/comment/88493141
has comment: http://stackoverflow.com/comment/88493762

http://stackoverflow.com/comment/88644324
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50796354
type: Comment
has text: Thank you jezrael this one works. Thank you very much, i really appreciate your help. Thank you

http://stackoverflow.com/q/50752791
tagged with: python-3.x
upvote count: 20
has body: When I run the test cases in python with "python normalizer/setup.py test " I am getting the below exception ResourceWarning: unclosed file &lt;_io.TextIOWrapper name='/Users/workspace/aiworkspace/skillset-normalization-engine/normalizer/lib/resources/skills.taxonomy' mode='r' encoding='utf-8'&gt; In code I am reading a big file like below: def read_data_from_file(input_file): current_dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) file_full_path = current_dir+input_file data = open(file_full_path,encoding="utf-8") return data What am I missing?
tagged with: io
has comment: http://stackoverflow.com/comment/88513600
tagged with: python
linked to: http://stackoverflow.com/q/21057942
type: AnsweredQuestion
downvote count: 0
tagged with: file
type: Question
score: 20
has title: Python 3: ResourceWarning: unclosed file <_io.TextIOWrapper name='PATH_OF_FILE'
has answer: http://stackoverflow.com/a/50752843
accepted answer: http://stackoverflow.com/a/50752843
answer count: 1
linked to: http://stackoverflow.com/q/1369526
favorite count: 0

http://stackoverflow.com/q/50700155
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50700374
has body: I'm looping through the following JSON: "item 1": { "property 1": "value 1", "property 2": "value 2", "property 3": "value 3" }, "item 2": { "property 1": "value 1", "property 2": "value 2", "property 3": "value 3" } I'd like to make a dictionary with the values of the first two keys — property 1, property 2 — for each item (i.e. excluding property 3). The code that follows achieves the desired result, but only stores the most recent sequence: for i in JSON: value 1 = i["value 1"] value 2 = i["value 2"] ... JSON = json.dumps({'property 1':value 1,'property 2':value 2...}) return json.loads(JSON) &gt;&gt; "item 2": { "property 1": "value 1", "property 2": "value 2" ... # returns item 2, but I'd like item 1 also How do I store each the output of each item without overwriting the other?
type: Question
tagged with: python-3.6
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/50700258
accepted answer: http://stackoverflow.com/a/50700258
upvote count: 1
possible better answer: http://stackoverflow.com/a/50700374
has title: Generating dictionary in for loop returning last iteration
tagged with: sequence
favorite count: 0
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/50768023
type: Question
has answer: http://stackoverflow.com/a/51616840
tagged with: dialogflow-es
answer count: 3
has title: Google App Engine: from six.moves import http_client no module named moves
downvote count: 0
tagged with: gcloud
favorite count: 0
has answer: http://stackoverflow.com/a/55751654
has answer: http://stackoverflow.com/a/50770475
tagged with: google-app-engine
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/100501123
upvote count: 2
type: UnansweredQuestion
has body: Okie dokie, I'm trying to get Google's Dialogflow python API working with Google App Engine, and I seem to be running into issues when I run the application. I have pip installed dialogflow to a lib folder and added the lib folder through the app.yaml file. I keep running into an error where it says that it can't find 'six.moves.' Very new to this (app engine in general), so please tell me if I have something setup wrong. I've read a few other threads with no luck. This won't work locally or deployed. below are my app.yaml file: runtime: python27 api_version: 1 threadsafe: true service: basic-npl-ui handlers: - url: /img static_dir: img - url: /javascript static_dir: javascript - url: /css static_dir: css - url: /.* script: main.app env_variables: GAE_USE_SOCKETS_HTTPLIB: 'anyvalue' libraries: - name: jinja2 version: latest - name: webapp2 version: latest - name: ssl version: latest - name: grpcio version: latest and here's my error log (local development): Traceback (most recent call last): File "/Users/AVD1WIP/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/Users/AVD1WIP/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/Users/AVD1WIP/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/main.py", line 28, in &lt;module&gt; from src.dialog_response_util import DialogflowResponseUtil File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/src/dialog_response_util.py", line 2, in &lt;module&gt; import dialogflow File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/lib/dialogflow/__init__.py", line 17, in &lt;module&gt; from dialogflow_v2 import AgentsClient File "/Us…

http://stackoverflow.com/comment/88703921
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50823022
has text: Maybe, I'm not aware about python and OPC-UA modul.
score: 0

http://stackoverflow.com/comment/88596298
comment on: http://stackoverflow.com/q/50795204
has text: So far your script constructs the string `'../Documents and Settings/USERNAME/Desktop'` and does not even store it. There is no attempt to open or even write a file.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/68829170
has body: I had the same problem when I tried to integrate flask into IIS. python installation path was in "C:\Program files" folder and the error occurred because the path has a space (between Program and files). I just reinstalled python on a directory without spaces (e. g. C:\Python_39) and everything worked fine.
type: Answer
answers question: http://stackoverflow.com/q/50827406
score: 0

http://stackoverflow.com/a/67492466
has body: As @hoefling mentioned, the two lifecycles are incompatible... but that can be hacked around if you're not aiming for drop-in compatibility. import pytest from pytestqt.plugin import QtBot from unittest import TestCase from myproject import custom_widget @pytest.fixture(scope="class") def qtbot_adapter(qapp, request): """Adapt qtbot fixture for usefixtures and unittest.TestCase""" request.cls.qtbot = QtBot(request) def with_updown(function): """Wrapper to bodge setUp/tearDown into fixtures+TestCase""" def test_wrapper(self, *args, **kwargs): __tracebackhide__ = True if callable(getattr(self, 'up', None)): self.up() try: function(self, *args, **kwargs) finally: if callable(getattr(self, 'down', None)): self.down() test_wrapper.__doc__ = function.__doc__ return test_wrapper @pytest.mark.usefixtures("qtbot_adapter") class MyTestCase(TestCase): def up(self): self.widget = custom_widget.CustomWidget() self.widget.show() @with_updown def test_some_property(self): with self.qtbot.waitSignal(self.widget.my_signal, timeout=300): self.widget.do_thing() self.assertEqual(self.widget.get_thing(), 'foo')
downvote count: 0
has comment: http://stackoverflow.com/comment/138615673
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50710028
score: 1

http://stackoverflow.com/a/50780485
upvote count: 2
has body: def runs(nums, n): idx = np.flatnonzero(np.ediff1d(nums, n + 1, n + 1) &gt; n) return [nums[i1:i2] for i1, i2 in zip(idx[:-1], idx[1:])] Then, &gt;&gt;&gt; runs(nums, 3) [[1, 2, 3, 6, 7, 8, 10, 12, 14], [18], [25, 28, 31], [39]]
answers question: http://stackoverflow.com/q/50780322
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/88675950
comment on: http://stackoverflow.com/q/50835245
type: Comment
type: QuestionComment
has text: @syntonym, yep I have used `vline`
score: 0

http://stackoverflow.com/comment/88697485
type: Comment
comment on: http://stackoverflow.com/a/50845561
score: 1
type: AnswerComment
has text: Yes--as I mentioned in the answer @ALollz. Although, technically it is a NumPy array of python datetime.date objects.

http://stackoverflow.com/comment/123527677
type: AnswerComment
has text: This is a very helpful and detailed answer with well-written code, thanks!
type: Comment
comment on: http://stackoverflow.com/a/50751932
score: 0

http://stackoverflow.com/comment/88650271
has text: I've never tried it and it would make for a pretty surprising UI. If you can make your cell activatable, just do this instead.
comment on: http://stackoverflow.com/a/50752275
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50755384
score: 5
accepted answer of: http://stackoverflow.com/q/50755209
answers question: http://stackoverflow.com/q/50755209
has body: This is unnecessarily complicated -- we can boil down your question to a few lines: default = "Before" def foo(bar=default): print(bar) foo() # "Before" default = "After" foo() # "Before" The behavior it seems you expect is that after default = "After", calling foo() will print "After". But it continues to print "Before". Python will evaluate the default argument for a function once and "lock it in". Reassigning the name of default to something else later has no effect (as we see in the snippet above). Instead, you can use an approach that's commonly suggested when people want lists as default arguments: default = "Before" def foo(bar=None): if bar is None: bar = default print(bar) foo() # "Before" default = "After" foo() # "After" In this case, you're not trying to change the default argument, but rather change what is assigned to bar when no argument is specified. Each time you call foo() with no argument, it'll be assigned None and then the logic inside the function will look up and use the value of the global default.
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer

http://stackoverflow.com/comment/88611014
type: QuestionComment
has text: exactly one of the list, one or more, all?
score: 0
comment on: http://stackoverflow.com/q/50802451
type: Comment

http://stackoverflow.com/comment/88570895
score: 1
comment on: http://stackoverflow.com/q/50782030
has text: Can you please refer to the paper/report that shows that this method of taking the hidden states from encoder to decoder works (improves anything)? As far as I know, there is a weight tying method where the decoder weights is the transpose of the encoder (in dense layers, there are more adaptation when gating using LSTMs). This is used for regularization and indeed reported to be improving results in NLP problems. Usually used in the embedding layers.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50831646
tagged with: timestamp
type: AnsweredQuestion
has body: Problem: I want to generate epoch start and end time for last calender week. Suppose today in GMT is GMT: Wednesday, June 13, 2018 7:38:21 AM I need to generate start epoch and end epoch time for GMT for last week in calender which is not 7 days before today. It means today epoch 1528875278 - 604800 is not correct. What i requres is something like this. start: 1527964200,endtime:1528568999 Which actually translates to start : Saturday, June 2, 2018 6:30:00 PM end : Saturday, June 9, 2018 6:29:59 PM What i tried: import time today_time = int(time.time()) start_time = int(time.time()) - 604800 +/- some_bias end_time = int(time.time()) - 604800 +/- some_bias Can anyone help me here?
has answer: http://stackoverflow.com/a/50831961
type: Question
score: 0
answer count: 1
has title: Epoch time for last calender week
tagged with: epoch
tagged with: python
accepted answer: http://stackoverflow.com/a/50831961

http://stackoverflow.com/a/50840266
has body: If you started airflow without a fernet key, it wouldn't allow any connection to be encrypted. If you had a fernet key, added/edited any connections, they will be encrypted with that key. If you change the key in any way, those connections won't be decryptable. If you currently have connections encrypted with different fernet keys the only solution is migrating the keys created with one to the other. Or just delete them and recreate them assuming you still have the values handy.
has comment: http://stackoverflow.com/comment/88687390
has comment: http://stackoverflow.com/comment/88686307
type: Answer
answers question: http://stackoverflow.com/q/50838838
has comment: http://stackoverflow.com/comment/88687251
has comment: http://stackoverflow.com/comment/88687152
has comment: http://stackoverflow.com/comment/88687533
has comment: http://stackoverflow.com/comment/88686156
has comment: http://stackoverflow.com/comment/88686408
has comment: http://stackoverflow.com/comment/88686183
has comment: http://stackoverflow.com/comment/88687558
has comment: http://stackoverflow.com/comment/88688158
has comment: http://stackoverflow.com/comment/88684261
has comment: http://stackoverflow.com/comment/88688135
score: 0
has comment: http://stackoverflow.com/comment/88684811
has comment: http://stackoverflow.com/comment/88686130
has comment: http://stackoverflow.com/comment/88687625

http://stackoverflow.com/comment/88528192
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50759886
has text: The SELECT appears to be redundant
type: Comment

http://stackoverflow.com/comment/88529623
comment on: http://stackoverflow.com/q/50761015
has text: This is two separate questions: [Converting a string time to a python datetime object](https://stackoverflow.com/questions/466345/converting-string-into-datetime) and [Finding the difference between two datetime objects](https://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python).
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/88642036
type: QuestionComment
type: Comment
has text: You may want to ignore stdout but not stderr. Separating the streams allows you to do just that, whether logging, parsing program output, etc.
comment on: http://stackoverflow.com/q/50818465
score: 0

http://stackoverflow.com/comment/88634236
has text: Converte your dates to date time by just adding the hour part. And be careful with timezone good luck. Check my edits
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50764667

http://stackoverflow.com/comment/88612517
score: 0
comment on: http://stackoverflow.com/q/50803272
type: Comment
has text: @TomKarzes I tried that too, but the loop runs correctly but still gives me the unrounded number 38 instead of 40 @.@
type: QuestionComment

http://stackoverflow.com/a/50774611
has body: when you use virtualenv you don't need to type ver. of python. I think python3.6 is /usr/bin/python3.6 just type: python manage.py createsuperuser
has comment: http://stackoverflow.com/comment/88556187
type: Answer
answers question: http://stackoverflow.com/q/50774504
score: 0

http://stackoverflow.com/q/50822461
has answer: http://stackoverflow.com/a/50822601
tagged with: python
has answer: http://stackoverflow.com/a/50823891
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88651326
tagged with: match
type: Question
has comment: http://stackoverflow.com/comment/88651760
has comment: http://stackoverflow.com/comment/88652783
has title: Match to re-code letters and numbers in python (pandas)
accepted answer: http://stackoverflow.com/a/50823891
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 2
tagged with: pandas
has body: I have a variable that is mixed with letters and numbers. The letters range from A:Z and the numbers range from 2:8. I want to re-code this variable so that it is all numeric with the letters A:Z now becoming numbers 1:26 and the numbers 2:8 becoming numbers 27:33. For example, I would like this variable: Var1 = c('A',2,3,8,'C','W',6,'T') To become this: Var1 = c(1,27,28,33,3,23,31,20) In R I can do this using 'match' like this: Var1 = as.numeric(match(Var1, c(LETTERS, 2:8))) How can I do this using python? Pandas? Thank you
possible better answer: http://stackoverflow.com/a/50822601

http://stackoverflow.com/comment/88606133
has text: Anything will work, looking for the simplest approach. Sending an attachments has issues, I believe because of company policy. Thank you
comment on: http://stackoverflow.com/q/50799091
score: 0
type: Comment
type: QuestionComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/50728057
tags question: http://stackoverflow.com/q/50813024
tags question: http://stackoverflow.com/q/50854078
tags question: http://stackoverflow.com/q/50787607
tags question: http://stackoverflow.com/q/50826136
type: Tag
tags question: http://stackoverflow.com/q/50717534
tags question: http://stackoverflow.com/q/50743724
tags question: http://stackoverflow.com/q/50813779
tags question: http://stackoverflow.com/q/50817121
tags question: http://stackoverflow.com/q/50711159
tags question: http://stackoverflow.com/q/50778410
tags question: http://stackoverflow.com/q/50699698
tags question: http://stackoverflow.com/q/50787884
tags question: http://stackoverflow.com/q/50811545
tags question: http://stackoverflow.com/q/50841137
tags question: http://stackoverflow.com/q/50732381
tags question: http://stackoverflow.com/q/50822383

http://stackoverflow.com/comment/88567535
comment on: http://stackoverflow.com/q/50780308
score: 0
type: Comment
type: QuestionComment
has text: The file already exists locally, so why do you need to copy it at all? Does the server response contain a modified version of the file?

http://stackoverflow.com/comment/88462065
type: QuestionComment
has text: Note the scaling of your secondary y-axis it doesn't start at zero.
comment on: http://stackoverflow.com/q/50723259
score: 0
type: Comment

http://stackoverflow.com/q/50745840
has title: Kivy Treeview Position Issues
type: Question
score: 0
answer count: 1
has body: I am trying to create a layout with 2 sections that have a label over each and a view below (TreeView on the left and a window showing details on the right, e.g. "click on this node and see details"). I've got the labels sized and positioned, but when I add the TreeView, instead of fitting under the label, it pushes both labels over, no matter the position. Here's the current result: My main.py file-- from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.treeview import TreeView, TreeViewLabel class MainScreen(BoxLayout): def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) bridge_view = TreeView(root_options=dict(text='Clients'), hide_root=False, indent_level=4, pos_hint={"x": 0, "y": 0}, size_hint=(0.1, 0.5)) clients = {'client1': 'Connection A', 'client2': 'Connection B'} for client in clients.keys(): node = bridge_view.add_node(TreeViewLabel(text=client)) bridge_name = clients[client] bridge = bridge_view.add_node(TreeViewLabel(text=bridge_name), node) self.add_widget(bridge_view) class ConnectionApp(App): def build(self): self.title = 'My Support App' return MainScreen() if __name__ == '__main__': ConnectionApp().run() This is my kv file-- &lt;Label&gt;: font_size: 30 &lt;MainScreen&gt;: Label: text: "Connections" size_hint: 0.1, 0.5 pos_hint: {"left": 0.2, "top": 1.2} color: 1,0,1,1 outline_color: 1,0,1,1 Label: text: "Modules" size_hint: 0.1, 0.5 pos_hint: {"right": 0.2, "top": 1.2} Another thing that seems strange to me was how I had to use pos_hint to get my label spacing to work. As I understand it, these values should be on a scale between 0-1. A tutorial I read indicated as much-- Pos_hint gives a hint at the position, which is measured relatively between 0 and 1, where 1 is "completely" something and 0 is "not" something. Does anyone know why it took using a value greater than 1 for "top" to get these labels at the top? I'm guessing this may be a hint as to why my layout isn'…
tagged with: python
tagged with: kivy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50750184
accepted answer: http://stackoverflow.com/a/50750184
tagged with: treeview

http://stackoverflow.com/comment/88688292
comment on: http://stackoverflow.com/q/50842285
type: Comment
type: QuestionComment
has text: general question of programming/algorithms, not at all related to python, browse through the questions before posting
score: 0

http://stackoverflow.com/comment/88466021
comment on: http://stackoverflow.com/q/50728615
has text: Glad to hear it. Happy coding!
score: 0
type: Comment
type: QuestionComment

pandas-groupby
tags question: http://stackoverflow.com/q/50729226
tags question: http://stackoverflow.com/q/50728667
tags question: http://stackoverflow.com/q/50850055
tags question: http://stackoverflow.com/q/50831217
tags question: http://stackoverflow.com/q/50815893
tags question: http://stackoverflow.com/q/50800409
tags question: http://stackoverflow.com/q/50739645
tags question: http://stackoverflow.com/q/50807175
tags question: http://stackoverflow.com/q/50757265
tags question: http://stackoverflow.com/q/50778694
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/50761170
tags question: http://stackoverflow.com/q/50756697
tags question: http://stackoverflow.com/q/50848201
tags question: http://stackoverflow.com/q/50746261
type: Tag
tags question: http://stackoverflow.com/q/50730702
tags question: http://stackoverflow.com/q/50709114
tags question: http://stackoverflow.com/q/50747681
tags question: http://stackoverflow.com/q/50750918
tags question: http://stackoverflow.com/q/50804263
tags question: http://stackoverflow.com/q/50727342
tags question: http://stackoverflow.com/q/50817966
tags question: http://stackoverflow.com/q/50839737
tags question: http://stackoverflow.com/q/50778770
tags question: http://stackoverflow.com/q/50702709
tags question: http://stackoverflow.com/q/50731887
tags question: http://stackoverflow.com/q/50761069
tags question: http://stackoverflow.com/q/50798446
tags question: http://stackoverflow.com/q/50844829
tags question: http://stackoverflow.com/q/50782385
tags question: http://stackoverflow.com/q/50731253

http://stackoverflow.com/a/51139858
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50801015
has body: Try date format 07/02/2018(Month/Date/Year) Just like Daniel suggested (but with format): url = '{}?date__lt={}'.format(reverse('admin:events_event_changelist'), datetime.date.today().strftime('%m/%d/%Y'))

http://stackoverflow.com/comment/88652182
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50823217
has text: @pstatix, Sure, I upvoted yours, it works. But I think it's more readable to add a function to the namespace.
type: AnswerComment

http://stackoverflow.com/q/50773233
score: 1
has body: I have a task, which must be optimally solved. I have 50 categories and 10,000 stores that can have products from these categories, but all this in 3 columns id_store category qnty 1 1 50 1 2 32 1 15 44 2 1 333 2 4 33 2 5 15 2 15 12 2 35 14 3 3 14 .... It is necessary to make a matrix out of this, where row - id_store, and columns - category, and their intersection - qnty: id_shop/category 1 2 3 4 ...15 16... 35 36 1 50 32 0 0 44 0 0 0 2 333 0 0 33 12 0 14 0 3 0 0 14 0 0 0 0 0
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/50773297
tagged with: python
has answer: http://stackoverflow.com/a/50773508
answer count: 2
possible better answer: http://stackoverflow.com/a/50773508
upvote count: 1
tagged with: scipy
accepted answer: http://stackoverflow.com/a/50773297
has title: Data vectorization (get_dummies 3 columns to matrix)
tagged with: numpy
type: AnsweredQuestion
tagged with: vector
downvote count: 0

http://stackoverflow.com/comment/88496902
comment on: http://stackoverflow.com/q/50744488
has text: And you probably better use `zip` here.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50795365
downvote count: 0
has body: The solution is to connect the valueChanged signal of the verticalScrollBar() to a slot where the other verticalScrollBar() moves, but this could generate an infinite loop so to avoid it you must use blockSignals() as shown below: import sys from functools import partial from PyQt4 import QtGui,QtCore def move_scrollbar(vs, value): vs.blockSignals(True) vs.setValue(value) vs.blockSignals(False) def window(): app = QtGui.QApplication(sys.argv) win = QtGui.QWidget() main_horizontal = QtGui.QHBoxLayout() verti_1 = QtGui.QVBoxLayout() verti_2 = QtGui.QVBoxLayout() list1 = QtGui.QListWidget() for i in range(20): list1.addItem(str(i)) list2 = QtGui.QListWidget() for i in range(20): list2.addItem("name" + str(i)) verti_1.addWidget(list1) verti_2.addWidget(list2) vs1 = list1.verticalScrollBar() vs2 = list2.verticalScrollBar() vs1.valueChanged.connect(partial(move_scrollbar, vs2)) vs2.valueChanged.connect(partial(move_scrollbar, vs1)) main_horizontal.addLayout(verti_1) main_horizontal.addLayout(verti_2) win.setLayout(main_horizontal) win.resize(400,200) win.show() sys.exit(app.exec_()) if __name__ == "__main__": window()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50794761
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50794761

http://stackoverflow.com/q/50800904
type: AnsweredQuestion
downvote count: 3
tagged with: image-processing
upvote count: 1
has answer: http://stackoverflow.com/a/50841220
type: Question
has comment: http://stackoverflow.com/comment/88684191
has title: Automatically generating start and goal positions for a maze
accepted answer: http://stackoverflow.com/a/50841220
answer count: 1
linked to: http://stackoverflow.com/q/12995434
favorite count: 0
has body: The code below is a maze solver (taken from this answer). It uses Start and Goal positions that were manually entered, and I need to change these coordinates each time I change the image to be solved. Thus, I want to find a way to automatically generate these positions based on the image (it is a binary image, 0 means an empty square and 1 represents a wall). My idea so far is to make a 'walk' outside the maze wall to determine these positions. The algorithm would visit each square and if its a zero than it would be considered as an entry/exit point. So my question is: Does anyone know a way to visit all the squares of the outside wall to determine the entry and the goal positions? Or any other idea that would help me solve this problem? import sys import png from PIL import Image # using an A* Algorithm to solve the maze def AStar(start, goal, neighbor_nodes, distance, cost_estimate): def reconstruct_path(came_from, current_node): path = [] while current_node is not None: path.append(current_node) current_node = came_from[current_node] return list(reversed(path)) g_score = {start: 0} f_score = {start: g_score[start] + cost_estimate(start, goal)} openset = {start} closedset = set() came_from = {start: None} while openset: current = min(openset, key=lambda x: f_score[x]) if current == goal: return reconstruct_path(came_from, goal) openset.remove(current) closedset.add(current) for neighbor in neighbor_nodes(current): if neighbor in closedset: continue if neighbor not in openset: openset.add(neighbor) tentative_g_score = g_score[current] + distance(current, neighbor) if tentative_g_score &gt;= g_score.get(neighbor, float('inf')): continue came_from[neighbor] = current g_score[neighbor] = tentative_g_score f_score[neighbor] = tentative_g_score + cost_estimate(neighbor, goal) return [] def is_blocked(p): x,y = p pixel = path_pixels[x,y] if any(c &lt; 225 for c in pixel): return True def von_neumann_neighbors(p): x, y = p neighbors = [(x-1, y), (x, y-1), (x+1, y), (x, y+…
tagged with: maze
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/88684345
has comment: http://stackoverflow.com/comment/88608446

http://stackoverflow.com/a/50826972
has comment: http://stackoverflow.com/comment/88658898
downvote count: 0
has comment: http://stackoverflow.com/comment/88658615
has body: Your code doesn't really make any sense for what you need to do. Your code will only find the longest substring in alphabetical order starting from index 0. Meaning when it reaches the end of the first longest substring 0 through whatever, it'll stop and won't look further. s = 'vwjxxumjb' count = 1 longest = 1 end = 0 for a in range(len(s) - 1): if s[a] &lt;= s[a + 1]: # is s[a] greater than or = to the next char in string? count += 1 # if it is, +1 to count if count &gt; longest: # if count is greater than longest (longest is current longest) continue, otherwise keep counting longest = count # new longest is the current count because it is longest end = a + 1 # since end is in this if block, it counts the iteration where count was last greater than the longest else: # when count is never greater than longest again the longest will be the length of the longest string count = 1 start = end - longest + 1 """ end is the last position in the longest string longest is length of the string so the end - longest characters = the start of string which is """ print('Longest substring in alphabetical order is: ' + s[start:end + 1]) #prints the letters in s from position Start to End + 1 (+1 end does not include the index that it is given) Edit: A complete answer to make Delirious Lettuce happy.
has comment: http://stackoverflow.com/comment/88658555
has comment: http://stackoverflow.com/comment/88658732
type: Answer
has comment: http://stackoverflow.com/comment/88658582
score: 1
has comment: http://stackoverflow.com/comment/88658663
has comment: http://stackoverflow.com/comment/88658577
upvote count: 1
answers question: http://stackoverflow.com/q/50826898
has comment: http://stackoverflow.com/comment/88658738
has comment: http://stackoverflow.com/comment/88658603

http://stackoverflow.com/comment/88684101
score: 0
type: Comment
has text: But did they want to fill on the left or on the right? And with a literal `'0'` or with the null byte `b'\0'`?
comment on: http://stackoverflow.com/a/50840102
type: AnswerComment

http://stackoverflow.com/a/50803252
accepted answer of: http://stackoverflow.com/q/50803109
answers question: http://stackoverflow.com/q/50803109
has body: Demo: &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; conn = sqlite3.connect('d:/temp/test.sqlite') &gt;&gt;&gt; df.to_sql('new_table_name', conn, if_exists='replace', index=False) &gt;&gt;&gt; pd.read_sql('select * from new_table_name', conn) Fu val 0 aed 544.8 1 jfn 5488.0 2 vivj 89.3 3 vffv 87.5
type: AcceptedAnswer
downvote count: 0
score: 32
type: Answer
upvote count: 32

http://stackoverflow.com/comment/88611910
type: QuestionComment
has text: @MarkSetchell This should be a pure Python function callable from part of a larger Python program. Unless there is something I am missing, command line tools are not applicable here.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50801935

http://stackoverflow.com/a/50735907
score: 0
answers question: http://stackoverflow.com/q/50735703
type: Answer
has body: You can try like this: import random as rand import string string.letters='rps' comp = rand.choice(string.letters) user = input("enter r for rock,p for paper,s for scissors\n") print(comp) if comp==user: print("its a tie") elif comp == 'r' and user == 'p': print(" congrats you won ") elif comp == 'r' and user == 's': print("sorry you lost") elif comp == 'p' and user == 'r': print("sorry you lost") elif comp == 'p' and user == 's': print("congrats you won") elif comp == 's' and user == 'p': print("sorry you lost") elif comp == 's' and user == 'r': print("congrats you won") Explanation: The characters are need to be used with quotes. Otherwise the python take that as variables. As quotes are not used it raised the error NameError: name 'r' is not defined

http://stackoverflow.com/q/50719025
upvote count: 0
answer count: 1
has body: I have so far created 2 model which takes 2 different train datasets and compare the 2 datasets and give the resultant output by calling the model weights i get after training the models. Now i want to stitch/overlap the 2 images (say: image 1 of model1 train dataset and frame1 of image 1 of model2 train dataset). What i mean is get the RGB channel from both the image, combine it and save it as single image. I can create 6 channels (RGB+RGB) but I don't know how can i combine them as one and save them. Here is the code for calling 2 model weights and do the prediction. model1 = create_model() model1.load_weights('model1.h5') print ('model1 loaded successfully') model2 = create_model() model2.load_weights('model2.h5') print ('model2 loaded successfully') import numpy as np from keras.preprocessing import image i = 1 while (i &lt; 11): test_image1 = image.load_img('dataset/test_set/'+str(i)+'.jpg', target_size = (64, 64)) test_image2 = image.load_img('dataset2/test_set/'+str(i)+'.jpg', target_size = (64, 64)) test_image1 = image.img_to_array(test_image1) test_image2 = image.img_to_array(test_image2) test_image1 = np.expand_dims(test_image1, axis = 0) test_image2 = np.expand_dims(test_image2, axis = 0) result = model1.predict(test_image1) print ("result1=", result) result2 = model2.predict(test_image2) print ("result2=", result2)
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: how can i train a model with 2 images stitched/overlap together?
has answer: http://stackoverflow.com/a/50771742
downvote count: 1
tagged with: tensorflow
type: Question
score: -1

http://stackoverflow.com/comment/88479141
comment on: http://stackoverflow.com/q/50735669
score: 0
type: QuestionComment
type: Comment
has text: Take a look at your condition. Your value cant be 0 and larger or equal to 100 in the same time ->> empty. Are You maybe trying to do an OR operation? Change & to |.

http://stackoverflow.com/a/50796465
has body: This error message... selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element ...implies that the WebDriver instance i.e. the driver was unable to focus on the element identified through your Locator Strategy. Your main issue is, you are trying to invoke send_keys() on an element with the Locator Strategy as: driver.find_element_by_xpath('//*[@id="computer"]') This Locator Strategy identifies a List element which is as follows: &lt;li id="computer" style="width:160px !important;" class="computer firstUpload" data-api="" data-value="upload" title="Computer"&gt;&lt;/li&gt; &lt;li&gt; tags doesn't accepts any character sequence. Only &lt;input&gt; tag accepts character sequence. So when you tried to invoke send_keys() driver was unable to set focus on the element. Hence image uploading fails. Element Snapshot:
score: 1
answers question: http://stackoverflow.com/q/50794314
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88599940
type: Answer
has comment: http://stackoverflow.com/comment/88600090
accepted answer of: http://stackoverflow.com/q/50794314
upvote count: 1

http://stackoverflow.com/q/50714931
has answer: http://stackoverflow.com/a/55123333
type: Question
tagged with: anaconda
tagged with: ipython
has body: I wanted to install both Python 2 and Python 3 kernels for my Jupyter notebook, so I followed the instructions here http://ipython.readthedocs.io/en/stable/install/kernel_install.html using conda. I initially had only Python 3 kernel running, so I installed Python 2 with: conda create -n ipykernel_py2 python=2 ipykernel source activate ipykernel_py2 python -m ipykernel install --user Now I have a new environment ipykernel_py2 on Anaconda, and I have Python 2 kernel available on Jupyter. However, I realised that even on the original base (root) environment, I still have Python 2 available. Now I am a little confused, as I recall this is installing a new conda environment, and I should only have access to the Python 2 kernel when in the ipykernel_py2 environment. When I use the Python 2 kernel in Jupyter, it acts as if it is in its own environment: the packages like pandas/matplotlib I installed in the original base(root) environment are not installed in the Python 2 kernel environment. Could someone explain to me, why the Python 2 kernel is accessible even outside the ipykernel_py2 environment? Has it got something to do with the kernel spec file that is installed? (mentioned on the link).
upvote count: 2
has title: iPython kernels and Anaconda environments
answer count: 1
tagged with: jupyter
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50854360
answer count: 1
tagged with: arguments
has comment: http://stackoverflow.com/comment/88711813
has body: Pls help me im stuck def printdata(something): for i in something + "_raw": something + "_raw_names" = i.findAll("div",{"itemprop":"name"}) something + "_name" = something + "_raw_names"[0].text print("Name: " + something + "_name") I want that printdata(bodies) is doing this: for i in bodies_raw: bodies_raw_names = i.findAll("div",{"itemprop":"name"}) bodies_name = bodies_raw_names[0].text print("Name: " + bodies_name) If u have a solution pls tell me because im struggling with this way too long
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88711658
has comment: http://stackoverflow.com/comment/88716035
has comment: http://stackoverflow.com/comment/88711535
tagged with: python
has title: Argument in a for loop
score: -5
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/50854496
upvote count: 0
tagged with: function
downvote count: 5

http://stackoverflow.com/q/50836003
has comment: http://stackoverflow.com/comment/88676257
type: Question
upvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88675836
has title: How to convert 01/01/2012 01:00:00 to utc?
downvote count: 0
tagged with: utc
has body: I have tried to convert my time data so that that my python script can read this data. I have tried Time.append(row[1]) Time = Time[1:] Time = [str (i) for i in Time] datetime_Time = datetime.datetime ("%Y%m%d %I:%M:%S") #pharsing the time print (Time) I have tried passing the data as a float and as an integer too.But as my data uses "/" and :, this therefore is causing an error and would appreciate if anyone could show me how to read this data
has comment: http://stackoverflow.com/comment/88676131
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50836118
accepted answer: http://stackoverflow.com/a/50836118

http://stackoverflow.com/a/62545592
downvote count: 0
score: 1
has body: You can access through the RTSP protocol, which needs a different syntax depending on the brand of the DVR. Here is an example for a Hikvision DVR: con = 'rtsp://USER:PASSWORD@IP:PORT/(h264/MPEG-4)/ch(CHANNEL)/(main/sub)/av_stream' cap = cv2.VideoCapture(con) And here an example for a Dahua DVR: con = 'rtsp://IP:PORT/cam/realmonitor?channel=CHANNEL&amp;subtype=ENCODING&amp;authbasic=LOGIN' cap = cv2.VideoCapture(con) Usually the port value is 554
type: Answer
answers question: http://stackoverflow.com/q/50753995
upvote count: 1

http://stackoverflow.com/q/50757928
score: -1
has comment: http://stackoverflow.com/comment/88523432
answer count: 1
accepted answer: http://stackoverflow.com/a/50758353
favorite count: 0
has body: GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "whats up",) GREETING_RESPONSES = ["sup bro", "hey", "*nods*", "hey you get my snap?"] def check_for_greeting(sentence): for word in sentence.words: if word.lower() in GREETING_KEYWORDS: return random.choice(GREETING_RESPONSES) user= input("&gt;&gt;&gt; ") check_for_greeting(user) AttributeError: 'str' object has no attribute 'words'. sentence.words is not proper. How to get the GREETING_RESPONSES if user is giving input in GREETING_KEYWORDS. I am using python 3.5
has comment: http://stackoverflow.com/comment/88523790
tagged with: python
has comment: http://stackoverflow.com/comment/88523446
type: AnsweredQuestion
downvote count: 2
has title: Python. AttributeError: 'str' object has no attribute for the words
upvote count: 1
has answer: http://stackoverflow.com/a/50758353
type: Question
tagged with: attributeerror

http://stackoverflow.com/a/50749772
has comment: http://stackoverflow.com/comment/88507636
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50749602
answers question: http://stackoverflow.com/q/50749602
has comment: http://stackoverflow.com/comment/88507619
has body: Use pd.concat pd.concat({i: df.shift(-i) for i in range(3)}, axis=1) Generalized n = 3 pd.concat({i: df.shift(-i) for i in range(n)}, axis=1).iloc[:len(df) - n + 1]
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88507518

http://stackoverflow.com/a/52468403
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/92027873
score: 1
answers question: http://stackoverflow.com/q/50810656
upvote count: 2
has comment: http://stackoverflow.com/comment/92063256
has comment: http://stackoverflow.com/comment/92221718
has body: I believe the correct route would be completely different than what you are doing right now. Each project should be stored in a different Git repository, share modules should be added as git submodules. Once those projects will get larger and more complex (and they probably will), it would be easier to manage them separately. In short Projects structure should be: Project_1 |- utils &lt;submodule&gt; |- storage.py |- geometry.py |- main.py Project_2 |- utils &lt;submodule&gt; |- storage.py |- geometry.py |- main.py Working with submodules ### Adding a submodule to an existing git directory git submodule add &lt;git@github ...&gt; &lt;optional path/to/submodule&gt; ### Pulling latest version from master branch for all submodules git submodule update --recursive --remote ### Removing submodule from project # Remove the submodule entry from .git/config git submodule deinit -f path/to/submodule # Remove the submodule directory from the project's .git/modules directory rm -rf .git/modules/path/to/submodule # Remove the entry in .gitmodules and remove the submodule directory located at path/to/submodule git rm -f path/to/submodule Further reading https://git-scm.com/book/en/v2/Git-Tools-Submodules

http://stackoverflow.com/comment/88620617
type: Comment
type: QuestionComment
has text: Please add the content of the "ma.txt" file directly to the post, otherwise we can't copy and paste it. Also, what's `MazeV`?
comment on: http://stackoverflow.com/q/50805165
score: 1

http://stackoverflow.com/q/50823934
tagged with: python
has comment: http://stackoverflow.com/comment/88654332
has comment: http://stackoverflow.com/comment/88653062
has comment: http://stackoverflow.com/comment/88653121
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50824109
score: 0
linked to: http://stackoverflow.com/q/14117415
has body: I'm writing a simple script that will be used parse the contents of a JSON file stored on AWS CloudWatch. I've added an argument parser to the script that will accept user input, and allow the user to either print the output of the file to the screen (in a predetermined fashion), or allow them to output the contents to a local JSON file. Here's a snippet of what's stumping me: import argparse parser = argparse.ArgumentParser(description="Process a log file") parser.add_argument('-o', '--output', choices=[???, 'print'], default='print', help='Specify logfile output path or print to screen') args = parser.parse_args() My question stems from the parser.add_argument line, specifically the choices argument. I'd like to allow two inputs for this flag, those being either print or some valid path on their local machine. I'd like the choice that's currently marked by question marks to be a PATH that Python can recognize. Is there a way, using argparse, to specify that one of of the arguments to a flag must be a PATH? Search results have been, so far, inconclusive. Thanks in advance!
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50824113
has title: Forcing an argument to be a valid path
linked to: http://stackoverflow.com/q/9532499
possible better answer: http://stackoverflow.com/a/50824113
tagged with: argparse
has answer: http://stackoverflow.com/a/50824109
tagged with: path

http://stackoverflow.com/q/50700546
type: UnansweredQuestion
has body: This is a weird problem that I am facing in my Django application. Configuration : Python 3.6 Django 2.0.6 DB : Djongo (MongoDB connector : Djongo repository) I have overwritten the create_superuser to: def create_superuser(self, email, is_staff, password): user = self.model( email=email, is_staff=True, is_active=True, ) user.set_password(password) user.save(using=self._db) return user I am able to create the superuser successfully but I am not able to login into the admin page. Following is my traceback: Internal Server Error: /admin/login/ Traceback (most recent call last): File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 398, in login return LoginView.as_view(**defaults)(request) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/utils/decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wra…
has title: Unusual error in Django. Cannot login into admin after creating superuser
has answer: http://stackoverflow.com/a/51457304
score: 2
downvote count: 0
type: Question
tagged with: python
favorite count: 0
tagged with: djongo
tagged with: python-3.x
upvote count: 2
tagged with: django
answer count: 1

http://stackoverflow.com/a/50753090
downvote count: 0
has comment: http://stackoverflow.com/comment/88564698
has comment: http://stackoverflow.com/comment/88558056
score: 1
accepted answer of: http://stackoverflow.com/q/50743706
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50743706
has comment: http://stackoverflow.com/comment/88547586
upvote count: 1
type: Answer
has body: In Windows, file type associatons are per-extension. Any file with the same extension is treated the same. That's the whole idea behind them. In principle, you can change the .py type association to run some program that would check if it runs this particular file and do a different thing. A much easier, more manageable and predictable way to go would be to place a shortcut rather than the program onto the desktop that would run anything you need -- in this case, "path\to\python.exe" "path\to\your_program.py". That's the whole idea behind shortcuts btw. The file itself can be placed to some other user-writable place like %APPDATA%\&lt;your_project_name&gt; which is the standard location for application data.

http://stackoverflow.com/comment/88486962
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50739630
type: Comment
has text: see edit. is that they way you want it? I also added tabs in the first option.

http://stackoverflow.com/comment/88623098
comment on: http://stackoverflow.com/q/50800333
score: 0
type: QuestionComment
has text: This is a big ugly bad solution, but what about use replace `'{"key": "{\"subKey\":\"subValue\"}"}'.replace('"', "'").replace("\'", '"')`?
type: Comment

http://stackoverflow.com/a/50721919
score: 1
upvote count: 2
downvote count: 1
has body: Or, without regex: def remove_digits(s): return ''.join([x for x in s if not x.isdigit()]) def is_combined(s): return any(x.isalpha() for x in s) and any(x.isdigit() for x in s) ' '.join([remove_digits(x) if is_combined(x) else x for x in test.split()])
type: Answer
answers question: http://stackoverflow.com/q/50721670

http://stackoverflow.com/a/54247711
answers question: http://stackoverflow.com/q/50727668
has body: After some digging around, it seems that rollback is the perfect method for this. (If we'd wanted the next Friday instead of the previous Friday we could use rollforward.) There are two ways to create the offset object with a frequency of W-FRI: # Method 1 &gt;&gt;&gt; from pandas.tseries.offsets import Week &gt;&gt;&gt; w_fri = Week(weekday=4) # Mon == 0, Tue == 1, ..., Sun = 6 &gt;&gt;&gt; w_fri &lt;Week: weekday=4&gt; # Method 2 &gt;&gt;&gt; from pandas.tseries.frequencies import to_offset &gt;&gt;&gt; w_fri = to_offset('W-FRI') &gt;&gt;&gt; w_fri &lt;Week: weekday=4&gt; Then to do the rollback, &gt;&gt;&gt; w_fri.rollback(pd.Timestamp('2019-1-17')) # A Thursday Timestamp('2019-01-11 00:00:00') &gt;&gt;&gt; w_fri.rollback(pd.Timestamp('2019-1-18')) # A Friday Timestamp('2019-01-18 00:00:00') More info here
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50727668

http://stackoverflow.com/comment/88624554
type: Comment
comment on: http://stackoverflow.com/a/50809466
has text: It's not a desired answer. please look the first column. 1001 should come in last two rows.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88549464
score: 0
type: Comment
type: QuestionComment
has text: @MadPhysicist Thank you.(which ipython → /Library/Frameworks/Python.framework/Versions/3.6/bin/ipython).I confirmed the version of python after starting "jupyter".(python -V → Python 2.7.10)
comment on: http://stackoverflow.com/q/50770394

http://stackoverflow.com/q/50708148
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50708395
favorite count: 0
tagged with: python
upvote count: 3
has title: How to assign a column value based on number of rows in that group
accepted answer: http://stackoverflow.com/a/50708395
tagged with: loops
type: AnsweredQuestion
score: 3
has body: Create some test data: import pandas as pd import numpy as np ID = pd.DataFrame(np.random.randint(0,1000000,size=(100, 1)), columns=['ID']) Prob = pd.DataFrame(np.random.randint(0, 100,size=(100, 1)), columns=['Probability'])/100 cuts = [{'flag': 'L', 'cut': 44}, {'flag': 'M', 'cut': 31}, {'flag': 'H', 'cut': 25}] cuts = pd.DataFrame(cuts) df = pd.concat([ID.reset_index(drop=True), Prob], axis=1) df = df.sort_values(by=['Probability']) df["flag"] = np.nan I have two datasets I am working with, one is a list of probabilities from a predictive model, the other is a list of cut points calculated based on the length of the list it's given. I would like to find an efficient way to assign these values to the 'flag' column of df. For this example, the first 44 rows would be assigned 'L', the next 31 rows will be assigned 'M' and the last 25 rows will be assigned 'H' My environment is with many more different flag values and millions of rows but for simplicity I am using 100 rows and 3 flags in the example. How do I assign these flags using 'the next x number of rows' and not the index or some other reference key?

http://stackoverflow.com/comment/89471463
type: AnswerComment
type: Comment
has text: I would like to express this problem in the SMTLib Format and evaluate it using Z3. edge("som1","som3"). egde("som2","som4"). egde("som4","som1"). egde("som3","som4"). path(x,y) :- edge(x,y). % x and y are strings path(x,z) :- edge(x,y), edge(y,x). :-path(x,y), path(y,x). %cyclic path. My question is how to write the rule (or query) which detect the existence of a cycle in the relation path (this rule in basic datalog : " :- path(x,y), path(y,x)" ).
score: 0
comment on: http://stackoverflow.com/a/50801235

http://stackoverflow.com/a/50787095
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50787078
answers question: http://stackoverflow.com/q/50787078
type: Answer
score: 1
has body: Try from PIL import Image (note the capital 'I' in Image).
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/88689579
type: Comment
has text: Hi, this answered my question. Thank you very much!
comment on: http://stackoverflow.com/a/50842937
score: 0
type: AnswerComment

http://stackoverflow.com/a/50845614
has body: First off, I love this problem! Code Wars Kata are a LOT of fun, especially when you figure them out on you own ;) That said, you are stuck and I am going to help you out; but instead of copy-pasting my solution in here, I'm going to tell you what I did and let you learn from it at your own pace. Let's take a look at just one of the test cases - Main Game 3 - in a little more detail. You mentioned that the inputs for the test cases were not available, but adding print(board) print(attacks) to the top of our function tells us everything we need to know. Here is the game board: 0 0 1 0 0 1 0 2 0 0 2 0 and here are our attack points: [3, 4], [2, 1], [2, 2] Now for a description of what I did to solve this problem (PLEASE do not feel like you have to do things this way, you are MORE than welcome to take what I've told you and continue working on the problem without reading further). First thing I did was loop through both rows and columns and made a dictionary containing every located ship, their location, and that cell's hit/miss status (0 for "not hit" and 1 for "hit"). I see this is something you are trying to do with ship_lengths (or at least I think that's what your trying to do), but you've made it more complicated by splitting up the data. By building a dictionary, I can keep everything in one place (the ship number, its location, and it hits); Here is what my dictionary looks like using this example: {'1': [[3, 3, 0], [3, 4, 0]], '2': [[2, 1, 0], [2, 2, 0]]} After this I loop through my attacks list and compare it to every element in my dictionary, if the X values and the Y values line up, I change that third value from a 0 to a 1 (Hit!). When I'm done looping through that attacks list I go back through my dictionary and looks for "hits" and "sinks", if every element under a ships index has a 1 in that third element its a sink, otherwise just a hit (or miss if all indexes are 0). - Code Wars Kata can be really fun - and really frustrating. Sometimes when you hav…
has comment: http://stackoverflow.com/comment/88703911
answers question: http://stackoverflow.com/q/50844692
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50844692
upvote count: 1
score: 1

http://stackoverflow.com/comment/88672355
comment on: http://stackoverflow.com/a/50822002
type: AnswerComment
has text: Oh I got it. Thank you very much.
score: 0
type: Comment

http://stackoverflow.com/comment/88418885
type: Comment
type: QuestionComment
has text: Thanks so much @coldspeed . if you dont mind how to repeat the user id value to all the rows?
score: 0
comment on: http://stackoverflow.com/q/50704571

http://stackoverflow.com/comment/88525755
score: 0
type: Comment
has text: List comprehension is working. But as you explained for IndexError if I use range(len(lst)-1) I am getting desired result. Why didn't here the IndexError came as here too elements are getting deleted.
type: AnswerComment
comment on: http://stackoverflow.com/a/50758107

http://stackoverflow.com/a/50789579
score: 2
upvote count: 2
downvote count: 0
has body: This looks like a good candidate for a management command. In your app folder, create the folder structure management/commands and add a file my_command.py (you should pick a better name that reflects what your command actually does). In that file would be something like the following: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): # your code here You would then be able to run it as python manage.py mycommand.
type: Answer
answers question: http://stackoverflow.com/q/50789513

http://stackoverflow.com/q/50842485
has comment: http://stackoverflow.com/comment/88688868
score: 2
has comment: http://stackoverflow.com/comment/88688624
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/42382263
upvote count: 2
linked to: http://stackoverflow.com/q/26886653
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88692652
has title: Having trouble applying Re module on a Series
has answer: http://stackoverflow.com/a/50861202
has comment: http://stackoverflow.com/comment/88688753
type: Question
has body: I have trouble applying the following to my series. Data['Notes'] 0 2018-06-07 09:38:14Z -- legal -- As per ... 1 2018-06-05 12:48:26Z -- name -- Holdin... 2 2018-06-05 17:15:48Z -- filing -- Answe... 3 2018-06-11 08:34:53Z -- name -- lvm i... 4 2018-05-11 08:31:26Z -- filed -- summo... 5 2018-06-01 16:07:11Z -- Name Rogers -- sent ... import re keywords = {'file', 'filing', 'legal'} max_words_after = 5 key_re = re.compile(fr""" (?:{'|'.join([w for w in keywords])}) #keyword options group \s((?:[\s]?[A-Za-z\']+[\s]?) #capture word. include with line-breaks {{1,{max_words_after}}}) #1 to max_words_after """, re.VERBOSE|re.IGNORECASE ) for f in data['Notes']: data['Result'] = key_re.findall(f) In response, all I get is "ValueError: Length of values does not match the length of index." Please tell me how I can get a result for every index position and append it to a new series within the data frame.
downvote count: 0
has comment: http://stackoverflow.com/comment/88688762
has comment: http://stackoverflow.com/comment/88688794

http://stackoverflow.com/comment/88599648
comment on: http://stackoverflow.com/q/50796114
score: 0
has text: You're opening your file using `open()` and made the error of not closing your file director. Python has got a method to handle files correctly. Check out how to use `with` keyword, here it would give you : `with open(file, 'r') as file_obj:`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88656384
type: Comment
type: QuestionComment
has text: Do you have the SA account password? Is your windows account a sysadmin on the server? can you connect SSMS using the Python credentials? What rights does the Python account have?
comment on: http://stackoverflow.com/q/50821476
score: 0

http://stackoverflow.com/comment/88551822
has text: [Nope](https://stackoverflow.com/questions/45830838/determine-the-shuffled-indices-of-two-lists-arrays) :)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50770151
type: Comment

http://stackoverflow.com/comment/88472921
type: AnswerComment
has text: It's perfectly valid to have an array at the top level.
comment on: http://stackoverflow.com/a/50732101
type: Comment
score: 2

http://stackoverflow.com/q/50843769
has body: I've been trying to install pysha3 and merkletools for the blockcerts cert-issuer quickstart, but I keep getting essentially the same type 1 error when I try to pip install. I read on a separate post that I should try upgrading setup tools pip install --upgrade setup tools and install ez_setup pip install ez_setup Both of these worked, and pip install also worked when I ran "pip install pyethereum," but I still keep getting the same error codes when I try to install pysha and merkletools. For "pip install pysha3" I get the error: Command "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 -u -c "import setuptools, tokenize;file='/private/var/folders/q0/h9rx8b3s14g_33ng9xz31ykw0000gn/T/pip-install-tvsl7vp1/pysha3/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/q0/h9rx8b3s14g_33ng9xz31ykw0000gn/T/pip-record-n8e9n_dm/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/q0/h9rx8b3s14g_33ng9xz31ykw0000gn/T/pip-install-tvsl7vp1/pysha3/ For pip install merkletools==1.0.3 I get: Command "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 -u -c "import setuptools, tokenize;file='/private/var/folders/q0/h9rx8b3s14g_33ng9xz31ykw0000gn/T/pip-install-m87p6nra/pysha3/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/q0/h9rx8b3s14g_33ng9xz31ykw0000gn/T/pip-record-b8x3lh7l/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/q0/h9rx8b3s14g_33ng9xz31ykw0000gn/T/pip-install-m87p6nra/pysha3/ It looks like the pip that's being called when I run pip install and pip --version are two separate things. When I run pip --version it says pip 10.0.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/pyt…
has comment: http://stackoverflow.com/comment/88735623
upvote count: 1
answer count: 1
tagged with: macos
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88732013
has title: error code 1 on pip install pysha3, merkletools
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50914472
tagged with: python
has comment: http://stackoverflow.com/comment/88833220
downvote count: 0
has comment: http://stackoverflow.com/comment/88730917
score: 1
has comment: http://stackoverflow.com/comment/88822435
tagged with: pip
type: Question

http://stackoverflow.com/q/50752494
score: -2
answer count: 1
has body: I'm new to coding and python. I've taken an intro comp sci class but I still feel out of my depth when trying to understand most code so please forgive me if this question seems poorly placed. I'm taking an algorithms class on Edx, which has an automatic grader. Starter code is provided for each problem and contains a section like the one below. This section is particularly difficult for me to understand. I believe what will be fed into the function I write is a list that will look like this [1:2,4:6,7:10], but I'm not really sure. I'm hoping someone could help me understand this code, so I can design a function around the data. if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] m = data[1] starts = data[2:2 * n + 2:2] ends = data[3:2 * n + 2:2] points = data[2 * n + 2:] #use fast_count_segments cnt = naive_count_segments(starts, ends, points) for x in cnt: print(x, end=' ') Further, I don't really understand how to test this code on my own computer so that I can figure it out on my own. Any help would be much appreaciated. Thanks in advance.
downvote count: 3
upvote count: 1
linked to: http://stackoverflow.com/q/509211
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/50752529
has title: data[2:2 * n + 2:2] in relation to the code below
type: Question
duplicate of: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/88513029

http://stackoverflow.com/q/50778096
has answer: http://stackoverflow.com/a/50778134
has answer: http://stackoverflow.com/a/50778131
has comment: http://stackoverflow.com/comment/88617096
type: Question
linked to: http://stackoverflow.com/q/773
answer count: 2
tagged with: for-loop
has title: Grouping string into substrings
tagged with: python-itertools
tagged with: group-by
score: 0
has body: I need some explanation as to how this code works. I do not understand the need for 'str' and 'grp' within the for loop. What are they keeping track of? from itertools import groupby print(["".join(grp) for str, grp in groupby('aaacaccccccbbbb')])
has comment: http://stackoverflow.com/comment/88563110
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50846303
score: 1
has comment: http://stackoverflow.com/comment/88698552
has body: For skip-gram you need to feed the input-label pair as the current word and its context word. The context word for each input word is defined within a window of the text phrases. Consider the following text phrase: "Here's looking at you kid". For a window of 3, and for the current word at, you have two context words looking and you. So the input label pairs are {at, looking}, {at, you}, which you convert them into a number representation. In the above code, the array list example is given as: ex. [[181, 152], [152, 165], [165, 208], [208, 41]], which means current word and its context is defined for the next word and not for the previous word. The architecture looks something like below: Now you have these pairs generated, get them in batches and train them. Its ok to have uneven size batches, but make sure that your loss is average loss and not a sum loss.
upvote count: 1
has comment: http://stackoverflow.com/comment/88698508
accepted answer of: http://stackoverflow.com/q/50840321
has comment: http://stackoverflow.com/comment/88698152
answers question: http://stackoverflow.com/q/50840321
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88697936

http://stackoverflow.com/comment/88576963
score: 0
comment on: http://stackoverflow.com/q/50784406
type: Comment
type: QuestionComment
has text: How many observations do you have per panel entity? The problem is that in short panels, the entity fixed effects cannot be estimated consistently. What are the units in "real life", specifically is the correlation within entities but not across entities?

http://stackoverflow.com/q/50796559
type: Question
has title: Map column if string contain values from other column in Pandas
tagged with: dataframe
has answer: http://stackoverflow.com/a/50796654
tagged with: contains
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/50796654
tagged with: python
has body: I have two dataframes, first is: df1 col_one col_two ABBC1 (1, 2, 3) DFFG2 (3, 5, 1) JJKS3 (5, 2, 5) df2 col_1 operate ABBC1 1 to 2, JJKS3 3 to 5 operate JJKS3, FOM Desired output df2: col_1 col_2 operate ABBC1, to 2 (1, 2, 3) operate JJKS3, FOM (5, 2, 5) I have tried multiple ways but the closest I get is: for values, map_col in df1'col_one', 'col_two'.values: for val in df2['col_1']: if ("%s" %values) in df2['col_1'] : df2['col_2'] = "%s" %(map_col,) And I thought this will be good, but I got exactly the same values for all rows. Any help is welcomed. Thanks
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50744601
has comment: http://stackoverflow.com/comment/88497069
score: 1
has body: You can simply use replace as the following: my_str = 'define_your_string_here' to_be_replaced = [':','\"','{','}'] for rep in to_be_replaced: my_str = my_str.replace(rep, '')
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50744484
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50744484
has comment: http://stackoverflow.com/comment/88497007
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88743650
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50853253
has text: @user6703592 After correcting the indentation, your `plt.close` is redundant, because `plt.show` is blocking and you will execute `plt.close` anyhow, when you close the shown figure. This destroys the figure instance. To my surprise, you can still access the data from `fig`, which includes saving `fig`. But you can't modify it, because matplotlib considers this application destroyed. This doesn't solve your problem at all but as it is stated now, I can't replicate your error message.
type: AnswerComment

http://stackoverflow.com/a/50734157
type: Answer
has comment: http://stackoverflow.com/comment/88488780
score: 3
has comment: http://stackoverflow.com/comment/88496701
answers question: http://stackoverflow.com/q/50734036
has comment: http://stackoverflow.com/comment/88488731
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50734036
has comment: http://stackoverflow.com/comment/88477599
has comment: http://stackoverflow.com/comment/88494063
type: AcceptedAnswer
downvote count: 0
has body: I believe need merge_asof: print(pd.merge_asof(df1,df2,right_index=True,left_index=True)) Rubbish_x Rubbish_y 2010-02-01 0.446505 NaN 2010-02-08 0.474330 0.606826 Or parameter method='nearest' to reindex: df2 = df2.reindex(df1.index, method='nearest') print (df2) Rubbish 2010-02-01 0.415248 2010-02-08 0.415248 print(pd.merge(df1,df2,right_index=True,left_index=True,how='outer')) Rubbish_x Rubbish_y 2010-02-01 0.431966 0.415248 2010-02-08 0.279121 0.415248
has comment: http://stackoverflow.com/comment/88477510
has comment: http://stackoverflow.com/comment/88477382

http://stackoverflow.com/comment/88648609
comment on: http://stackoverflow.com/q/50821728
has text: Don't forget that you still need to reference `self` inside your `arr4tmpl` method -- so `arr_path.extend(...)` should likely be `self.arr_path.extend(...)`, etc.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51085910
answers question: http://stackoverflow.com/q/50836608
downvote count: 0
has body: Here's a simple solution to calculate the accuracy and plot confusion matrix for the input in the format mentioned in the question. from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score file=open("results.txt","r") result=[] actual=[] i = 0 for line in file: i+=1 sent=line.split("\t") sent[0]=int(sent[0]) sent[1]=int(sent[1]) result.append(sent[1]) actual.append(sent[0]) cnf_mat=confusion_matrix(actual,result) print cnf_mat print('Test Accuracy:', accuracy_score(actual,result))
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/50821560
has body: I am receiving: RecursionError: maximum recursion depth exceeded in comparison on the for loop in the first definition. I have no idea what is going on or what I am doing wrong. Any help would be greatly appreciated. My code: initialbudget=3329 annualInterestRate=0.2 flat= 50 def formula(flat): ''' input flat rate return low or correct ''' balance=initialbudget for i in range(1, 13): balance=(balance-flat)*(1+annualInterestRate/12.0) if balance==0: return ('correct') elif balance&gt;0: return ('low') def rateFinder(initialbudget): ''' input starting balance return Flat rate needed to pay off balance in 12 months ''' flat=0 while formula(flat) != ('high'): if formula(flat)==('correct'): return('Lowest Payment:'+ ' ' + str(flat)) else: flat+=10 return(rateFinder(flat)) print(rateFinder(initialbudget))
downvote count: 0
has answer: http://stackoverflow.com/a/50888399
has comment: http://stackoverflow.com/comment/88648357
accepted answer: http://stackoverflow.com/a/50888399
has comment: http://stackoverflow.com/comment/88649233
favorite count: 0
possible better answer: http://stackoverflow.com/a/50824716
has title: Beginner python difficulties with for loop+recursive loop
has comment: http://stackoverflow.com/comment/88649146
tagged with: python
has comment: http://stackoverflow.com/comment/88648614
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88648323
upvote count: 2
has comment: http://stackoverflow.com/comment/88648422
type: Question
has comment: http://stackoverflow.com/comment/88648402
has answer: http://stackoverflow.com/a/50824716
has comment: http://stackoverflow.com/comment/88648445
answer count: 2

http://stackoverflow.com/comment/88532468
comment on: http://stackoverflow.com/q/50742538
type: QuestionComment
score: 6
has text: Ok, so `setuptools` should be installed now - can you confirm you have the `pkg_resources.py` module? Run `ls /usr/lib/python2.6/site-packages/pkg_resources.py; echo $?`, if this command outputs 0, remove the `pkg_resources` package: `sudo rm -rf /usr/lib/python2.6/site-packages/pkg_resources/`. **Remove the dir only when the pkg_resources module is found!** After that, `pip` should work again: run smth like `pip list` to check that.
type: Comment

http://stackoverflow.com/comment/132436094
score: 0
type: AnswerComment
has text: @mozway Correct.
comment on: http://stackoverflow.com/a/50788670
type: Comment

http://stackoverflow.com/q/50770868
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50781432
has body: As part of an exercise using some Quandl stock exchange data I was asked to calculate the largest change in closing price between two trading days for a particular stock in 2017. I came up with different approaches and timed them. I was expecting itertools.islice to be faster and it wasn't. (My expectations were being set by this SO answer) To add an additional detail, I want to print out which two trading dates the largest change occurred between so I need the date info also - initially I only found solutions with a for loop for that. A couple of questions: Did I approach the timing correctly - ensuring the only thing in the cell is the code I wanted to time etc? Is the main reason for my results that I only have 255 items in my dict so local resources aren't taxed and loading the full list is trivial? I was working in an Jupyter notebook which is available here - this question is related to Q5. My data is a dict of namedtuples: {'2017-12-28': Tradeday(date='2017-12-28', open=51.65, high=51.82, low=51.43, close=51.6, change=None, traded_vol=40660.0, turn_over=2099024.0, last_price=None, d_trad_unit=None, d_turnover=None), '2017-12-29': Tradeday(date='2017-12-29', open=51.76, high=51.94, low=51.45, close=51.76, change=None, traded_vol=34640.0, turn_over=1792304.0, last_price=None, d_trad_unit=None, d_turnover=None)} Which I then sorted into an OrderedDict: o_data = OrderedDict(sorted(data.items(), key=lambda t:t[0])) Method 4 - flatten data into list of (k,v) tuples and iterate over a range: od_list = list(o_data.items()) max_change, max_st, max_ed = 0, '', '' for i in range(len(o_data)-1): change = abs(od_list[i][1].close-od_list[i+1][1].close) if change &gt; max_change: max_change, max_st, max_ed = change, od_list[i][1].date, od_list[i+1][1].date Using %%timeit on the cell I got these results: 117 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) Method 5 - using enumerate and avoiding making a list in memory mx, st, en = 0, '', '' for i, v in e…
type: Question
upvote count: 4
has title: Best way to calculate max diff's between items in a dictionary
linked to: http://stackoverflow.com/q/10058140
score: 4
has comment: http://stackoverflow.com/comment/88549328
has comment: http://stackoverflow.com/comment/88569594
has comment: http://stackoverflow.com/comment/88549314
has comment: http://stackoverflow.com/comment/88549423
has comment: http://stackoverflow.com/comment/88549246
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50781432
tagged with: python

http://stackoverflow.com/q/50768511
has comment: http://stackoverflow.com/comment/88545059
type: AnsweredQuestion
has body: I have a question about sklearn's linear regression model.. I want to fit a Linear Regression using multiple features. Right now my X is a np.matrix and my Y is a np.array. My X looks like this (printed) X.shape -> (21, 3): [[ 8.68269590e-03 -2.83226292e-03 1.91826382e-01] [ 5.85903392e-03 -5.68809929e-03 2.21862758e-01] [ 2.90920454e-03 -1.24549359e-03 1.71619892e-01] [ 7.71491867e-04 1.74288704e-03 2.70315213e-03] [-2.44583484e-03 -4.73496469e-05 -1.25966777e-01] [-4.16023564e-03 -2.09644321e-03 -4.91722645e-02] [-3.22298365e-03 -3.55366669e-03 -1.67993225e-02] [-2.79712919e-03 -1.94070947e-03 -1.70873725e-01] [-2.76366703e-03 -4.98257755e-04 -2.52336769e-01] [-3.65153430e-03 -3.89128554e-03 -2.03762730e-01] [-6.07841812e-03 -8.89479214e-03 -1.54953118e-01] [-7.55809682e-03 -1.13395249e-02 -2.29260955e-01] [-7.46617379e-03 -5.70467322e-03 -2.01416145e-01] [-7.82348527e-03 3.58732358e-04 -1.47799157e-01] [-8.68110057e-03 -3.98060036e-05 -1.17156978e-01] [-9.13439934e-03 3.21795372e-03 -4.17922611e-02] [-6.64659597e-03 5.79326182e-03 -7.08715900e-02] [-3.28840696e-03 2.57177260e-03 -1.34971930e-01] [-1.38119572e-04 2.25318751e-03 -6.03902835e-02] [ 4.53278359e-03 2.40625868e-03 1.38175436e-01] [ 5.95225669e-03 1.00742943e-03 1.75614285e-01]] And my Y looks like this (printed) Y.shape -> (21, 1): [[ 0.00472189] [ 0.00134158] [-0.01183452] [-0.00712723] [ 0.01007362] [ 0.00373918] [-0.00832614] [-0.02623798] [-0.00381873] [ 0.0068726 ] [-0.01438412] [ 0.00898785] [ 0.0100893 ] [-0.00321919] [ 0.00827624] [ 0.00486361] [-0.01065365] [ 0.00741757] [ 0.01037663] [ 0.00230243] [-0.00169308]] However, sklearn is throwing the following exception: ValueError: shapes (1,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0) I have googled and tried multiple things, but no success. I come from a different programming background so python is kind of new to me. Could you guys point me in the right direction to solve this error? EDIT: My code: training_chart = self.prices[-self.TRAININ…
has comment: http://stackoverflow.com/comment/88544603
score: 0
has answer: http://stackoverflow.com/a/50768873
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88544962
tagged with: scikit-learn
tagged with: data-science
has comment: http://stackoverflow.com/comment/88545000
accepted answer: http://stackoverflow.com/a/50768873
answer count: 1
has title: Linear Regression (sklearn) fitting data shape error
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/88689474
has text: What is the relationship between `A` and `file_number`?
comment on: http://stackoverflow.com/q/50833671
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88448715
has text: show us the code. if you don't have any make an attempt. From the sounds of it regex is not needed for this problem
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50720128
type: Comment

http://stackoverflow.com/comment/88698411
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50840015
has text: Where would I set it to?

http://stackoverflow.com/comment/103855374
score: 5
type: AnswerComment
has text: Yes, `nn.Embedding` is also a model parameter layer, which is by default trainable, and you can also make it untrainable by freezing its gradient.
comment on: http://stackoverflow.com/a/51060374
type: Comment

http://stackoverflow.com/a/50717302
answers question: http://stackoverflow.com/q/50717209
has comment: http://stackoverflow.com/comment/88443233
score: 0
has body: Have you tried retrieving your User model with get_user_model? from django.contrib.auth import get_user_model User = get_user_model()
type: Answer

http://stackoverflow.com/a/50723684
downvote count: 0
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50723049
type: Answer
answers question: http://stackoverflow.com/q/50723049
has body: The following should work. cols = [0, 5, 8, 9] def filter_cols(ws): for row in ws.iter_rows(max_col=10): cells = [cell.value for (idx, cell) in enumerate(row) if ( idx in cols and cell.value is not None)] yield cells

http://stackoverflow.com/q/50721732
upvote count: 4
answer count: 1
downvote count: 0
tagged with: gitlab-ci
favorite count: 0
has title: Get Gitlab's Continuous Integration to compile a Python extension written in C
accepted answer: http://stackoverflow.com/a/50724144
linked to: http://stackoverflow.com/q/19383887
tagged with: python
tagged with: gitlab
type: AnsweredQuestion
has body: Context I have a Python project for which I wrap some C/C++ code (using the excellent PyBind library). I have a set of C and Python unit tests and I've configured Gitlab's CI to run them at each push. The C tests use a minimalist unit test framework called minunit and I use Python's unittest suite. Before running the C tests, all the C code is compiled and then tested. I'd like to also compile the C/C++ wrapper for Python before running the Python tests, but have a hard time to do it. Question in a few words Is there a standard/good way to get Gitlab-CI to build a Python extension using setuptools before running unit-tests? Question with more words / Description of what I tried To compile the C/C++ wrapper locally, I use setuptools with a setup.py file including a build_ext command. I locally compile everything with python setup.py build_ext --inplace (the last arg --inplace will just copy the compiled file to the current directory). As far as I know, this is quite standard. What I tried to do on Gitlab is to have a Python script (code below) that will run a few commands using os.system command (which appears to be bad practice...). The first command is to run a script building and running all C tests. This works but I'm happy to take recommendations (should I configure Gitlab CI to run C tests separately?). Now, the problem comes when I try to build the C/C++ wrapper, with os.system("cd python/ \npython setup.py build_ext --inplace"). This generates the error File "setup.py", line 1, in &lt;module&gt; from setuptools import setup, Extension ImportError: No module named setuptools So I tried to modify my gitlab's CI configuration file to install python-dev. My .gitlab-ci.yml looks like test: script: - apt-get install -y python-dev - python run_tests.py But, not being sudo on the gitlab's server, I get the following error E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied). Anyone knows a way around that, or a better way to tackle this probl…
tagged with: setuptools
type: Question
tagged with: python-unittest
has answer: http://stackoverflow.com/a/50724144
score: 4

http://stackoverflow.com/a/50725449
answers question: http://stackoverflow.com/q/50725340
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88459269
has comment: http://stackoverflow.com/comment/88459390
has body: You don't need two loops, just one. while True: if move == 1: rando.Moves.move1(player) elif move == 2: rando.Moves.move2(player) elif move == 3: rando.Moves.move3(player) else: print("You ran out of time and died") break ... Your code was just breaking out of the inner loop, not the outer loop.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88664179
comment on: http://stackoverflow.com/a/50813794
type: Comment
score: 0
has text: yes i forgot to mention that one line where i added that merged to final model. i have edited the question please suggest the way to do that.
type: AnswerComment

http://stackoverflow.com/a/50766961
downvote count: 0
has comment: http://stackoverflow.com/comment/88583122
has comment: http://stackoverflow.com/comment/88542521
score: 3
has comment: http://stackoverflow.com/comment/88581898
type: AcceptedAnswer
upvote count: 3
answers question: http://stackoverflow.com/q/50754020
has comment: http://stackoverflow.com/comment/88549502
type: Answer
has body: Don't invert! With n=4 %timeit soln = A.LUsolve(b) 697 µs ± 12.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) With n=10 %timeit soln = A.LUsolve(b) 431 ms ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
accepted answer of: http://stackoverflow.com/q/50754020

http://stackoverflow.com/q/50755540
has title: Using CreateChatRequest occurs Not enough users (to create a chat, for example)
has answer: http://stackoverflow.com/a/50806530
tagged with: telegram
type: Question
answer count: 2
tagged with: python
has body: telethon vaersion: 0.19.1.4 Python version : 3.6. When using CreateChatRequest to create a group, it occurs error like this: CreateChatRequest occurs Not enough users (to create a chat, for example). And my code like this: user = InputUser(user_id=12345, access_hash=12345678901234) client(CreateChatRequest([user], title=title)) user_id and access_hash is correct, but I'm confused about the error message.
score: 0
tagged with: telethon
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88538934
has answer: http://stackoverflow.com/a/67375320

http://stackoverflow.com/comment/89040583
type: Comment
comment on: http://stackoverflow.com/a/50750630
type: AnswerComment
has text: @AbidAbdulGafoor This example looks completely different from the one in the original post. I think it would be better to ask a new question.
score: 0

http://stackoverflow.com/comment/88585660
type: AnswerComment
comment on: http://stackoverflow.com/a/50789767
type: Comment
has text: Thanks for the upvote, and I appreciate the fact that you've answered. Please keep it up, and keep learning. +1
score: 0

http://stackoverflow.com/a/50837260
has comment: http://stackoverflow.com/comment/88681584
has comment: http://stackoverflow.com/comment/88678670
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88678445
has body: if i get you right. try type(ser) that way you will know the type of 'ser', if it's an iterable(list, tuple,etc...), you can try: for s in ser: print s time.sleep(1) hope this help.
answers question: http://stackoverflow.com/q/50836594

http://stackoverflow.com/comment/88553148
has text: Thank you. I wasn't aware assign could be set like that as a chain and wrap all into a list comprehension . Also thanks for the dtype mapping parameter for optimisation.
comment on: http://stackoverflow.com/a/50764756
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/50805556
downvote count: 0
favorite count: 0
answer count: 1
tagged with: python
tagged with: gensim
has answer: http://stackoverflow.com/a/50811902
score: 16
has title: Understanding parameters in Gensim LDA Model
accepted answer: http://stackoverflow.com/a/50811902
upvote count: 16
tagged with: parameters
tagged with: lda
type: AnsweredQuestion
type: Question
has body: I am using gensim.models.ldamodel.LdaModel to perform LDA, but I do not understand some of the parameters and cannot find explanations in the documentation. If someone has experience working with this, I would love further details of what these parameters signify. Specifically, I do not understand: random_state update_every chunksize passes alpha per_word_topics I am working with a corpus of 500 documents which are roughly around 3-5 pages each (I unfortunately cannot share a snapshot of the data because of confidentiality reasons). Currently I have set num_topics = 10 random_state = 100 update_every = 1 chunksize = 50 passes = 10 alpha = 'auto' per_word_topics = True but this is solely based off of an example I saw and I am not sure how generalizable that is to my data.

http://stackoverflow.com/a/50780257
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/50780209
downvote count: 0
has comment: http://stackoverflow.com/comment/88567347
type: Answer
has body: Simply multiply by 4, round, then divide by 4.
has comment: http://stackoverflow.com/comment/88567473

http://stackoverflow.com/q/50771343
tagged with: python-requests
has answer: http://stackoverflow.com/a/79540196
type: Question
has answer: http://stackoverflow.com/a/76560599
upvote count: 5
has body: I was trying to download pictures from websites like 'http://xxx.jpg'. The code: headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'} url='http://xxx.jpg' response = requests.get(url,headers=headers) downloadFunction() The error writes: requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) Error occurred at the first request, so it wasn't the request frequency which had caused the error. And I could still open the websites using a browser, so I just needed the code to act more like a browser. How can I achieve that besides setting the user-agent?
has comment: http://stackoverflow.com/comment/96224680
answer count: 6
tagged with: web-crawler
score: 5
has answer: http://stackoverflow.com/a/56130961
downvote count: 0
has answer: http://stackoverflow.com/a/70087585
favorite count: 0
has comment: http://stackoverflow.com/comment/88550647
has title: Python3 requests ConnectionResetError(10054) when opening a picture
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/56201675
has answer: http://stackoverflow.com/a/78788362
has comment: http://stackoverflow.com/comment/96224559
has comment: http://stackoverflow.com/comment/88551042

http://stackoverflow.com/comment/88591754
type: Comment
comment on: http://stackoverflow.com/q/50792833
score: 0
has text: Is this helpful : https://code-maven.com/serialize-datetime-object-as-json-in-python
type: QuestionComment

http://stackoverflow.com/a/50753082
has comment: http://stackoverflow.com/comment/88514170
has comment: http://stackoverflow.com/comment/88515435
accepted answer of: http://stackoverflow.com/q/50752668
has comment: http://stackoverflow.com/comment/88515170
has comment: http://stackoverflow.com/comment/88515251
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88515165
has comment: http://stackoverflow.com/comment/88515061
has comment: http://stackoverflow.com/comment/88514226
score: 4
has comment: http://stackoverflow.com/comment/88545208
has comment: http://stackoverflow.com/comment/88515090
type: Answer
has comment: http://stackoverflow.com/comment/88514167
upvote count: 4
has comment: http://stackoverflow.com/comment/88514246
has comment: http://stackoverflow.com/comment/88514230
has comment: http://stackoverflow.com/comment/88515231
has comment: http://stackoverflow.com/comment/88514118
has body: You can do this safely by using in-built operator package, and using globals from operator import sub, add, truediv, mul import re def string_eval(str_): operators = {'-': sub, '+': add, '/': truediv, '*': mul} pattern = re.compile(r'(.*?)\s*([*\/+-])\s*(.*)') splited = re.search(pattern, str_).groups() if len(splited) == 3: a, ope, b = splited val_a = globals()[a] val_b = globals()[b] return operators[ope](val_a, val_b) Now for this to work you have to declare the variables first &gt;&gt;&gt; a = 45 &gt;&gt;&gt; b = 25 &gt;&gt;&gt; string_eval('a - b') 20 &gt;&gt;&gt; string_eval('a * b') 1125
has comment: http://stackoverflow.com/comment/88515153
has comment: http://stackoverflow.com/comment/88515192
has comment: http://stackoverflow.com/comment/88514272
has comment: http://stackoverflow.com/comment/88515144
has comment: http://stackoverflow.com/comment/88514121
answers question: http://stackoverflow.com/q/50752668
downvote count: 0

http://stackoverflow.com/comment/88485546
type: Comment
has text: I have seen this for .net version but got a bit confused. So thought if there was a simpler way to find the version. Plus I also need help with powershell and firmware
type: QuestionComment
comment on: http://stackoverflow.com/q/50738757
score: 0

http://stackoverflow.com/comment/88683077
comment on: http://stackoverflow.com/q/50839433
has text: @jiggy357, you can checkout my answer. also, post your expected output back to the question with formatting, so that everyone can have a look at it.
score: 0
type: Comment
type: QuestionComment

ubuntu-18.04
tags question: http://stackoverflow.com/q/50833759
tags question: http://stackoverflow.com/q/50787607
type: Tag
tag name: ubuntu-18.04

http://stackoverflow.com/comment/88607731
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50800487
has text: I have one script with this working but only sending one line each time, and I have like, 700000 lines to send and we cant wait that many time so I have to send multiple lines. the script is similar. cursor.execute("INSERT INTO LogTbl (all the fields) VALUES (all the %s)", (all the variables)) (the variables are the same as the row =(...))

http://stackoverflow.com/comment/88728988
type: QuestionComment
has text: Did you get this sorted? And was the answer any help?
score: 0
comment on: http://stackoverflow.com/q/50844586
type: Comment

http://stackoverflow.com/q/50724788
has answer: http://stackoverflow.com/a/50724935
accepted answer: http://stackoverflow.com/a/50724935
has comment: http://stackoverflow.com/comment/88458034
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88457927
upvote count: 1
tagged with: python
has title: Loops that store different variables per iteration?
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88458064
tagged with: loops
has body: Is there a way I can shorten this code to perhaps use a loop that stores different variables each time it is run? I need it to store different variables rather than overwriting the same variable in the loop. As of right now they code is very lengthy and ends after five iterations, as coded, before displaying my end results. Any help would be much appreciated, thank you! while True: opps = float(input("Number of opportunities: ")) sales = float(input("Quantity of of sales: ")) addon = float(input("Addon $ amount: ")) total = float(input("Sales dollar amount: ")) cra = (sales / opps) * 100 addonp = (addon / total) * 100 print("Results:\n" + "CRA %: " + str(cra) + "%\n" + "Addon %: " + str(addonp) + "%\n") ans = 'y' ans = str(input("Continue? (Y/N)")) if ans in ['y', 'Y', 'yes', 'Yes', 'YES']: opps2 = float(input("Number of opportunities: ")) sales2 = float(input("Quantity of of sales: ")) addon2 = float(input("Addon $ amount: ")) total2 = float(input("Sales dollar amount: ")) cra2 = (sales2 / opps2) * 100 addonp2 = (addon2 / total2) * 100 print("Results:\n" + "CRA %: " + str(cra2) + "%\n" + "Addon %: " + str(addonp2) + "%\n") ans = 'y' ans = str(input("Continue? (Y/N)")) if ans in ['y', 'Y', 'yes', 'Yes', 'YES']: opps3 = float(input("Number of opportunities: ")) sales3 = float(input("Quantity of of sales: ")) addon3 = float(input("Addon $ amount: ")) total3 = float(input("Sales dollar amount: ")) cra3 = (sales3 / opps3) * 100 addonp3 = (addon3 / total3) * 100 print("Results:\n" + "CRA %: " + str(cra3) + "%\n" + "Addon %: " + str(addonp3) + "%\n") ans = 'y' ans = str(input("Continue? (Y/N)")) if ans in ['y', 'Y', 'yes', 'Yes', 'YES']: opps4 = float(input("Number of opportunities: ")) sales4 = float(input("Quantity of of sales: ")) addon4 = float(input("Addon $ amount: ")) total4 = float(input("Sales dollar amount: ")) cra4 = (sales4 / opps4) * 100 addonp4 = (addon4 / total4) * 100 print("Results:\n" + "CRA %: " + str(cra4) + "%\n" + "Addon %: " + str(addonp4) + "%\n") …
type: Question

http://stackoverflow.com/q/50778180
possible better answer: http://stackoverflow.com/a/50778225
has answer: http://stackoverflow.com/a/50778219
has answer: http://stackoverflow.com/a/50778225
type: AnsweredQuestion
type: Question
answer count: 2
tagged with: validation
has title: How to only validate integers without using a loop and exiting when the input is not correct?
accepted answer: http://stackoverflow.com/a/50778219
linked to: http://stackoverflow.com/q/23294658
tagged with: python
has body: I'm trying to get this simple code to only accept integers and numbers from (0,100). I dont want to use a loop to validate my inputs and want them to exit with only "invalid input". I'm stuck with this part because I cant seem to exit without the ("Letter grade: ") part when I dont have a valid input... and the message wont appear when I enter letters. Here's what I have so far... I'm a beginner so it'll be great if someone could help me:) def convert_grade_to_letter(number_grade): letter_grade = '' if number_grade &gt;= 90 and number_grade &lt;= 100: letter_grade = 'A' elif number_grade &gt;= 80: letter_grade = 'B' elif number_grade &gt;= 70: letter_grade = 'C' elif number_grade &gt;= 60: letter_grade = 'D' elif number_grade &lt; 60 and number_grade &gt;= 0: letter_grade = 'F' else: print("invalid input") return letter_grade def main(): number_grade = int(input("Input number grade: ")) letter_grade = convert_grade_to_letter(number_grade) print("Letter grade: " + letter_grade) main()
duplicate of: http://stackoverflow.com/q/23294658
tagged with: integer
score: 0

http://stackoverflow.com/a/50799896
score: 4
has comment: http://stackoverflow.com/comment/88605788
has comment: http://stackoverflow.com/comment/88605708
type: Answer
answers question: http://stackoverflow.com/q/50799740
has body: This behaviour is documented here; you are running the Python shell in interactive mode. Note, quoted below for posterity: All error messages are written to the standard error stream; normal output from executed commands is written to standard output.
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/50722037
has title: Iterate four lists in different loop python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/88452701
has answer: http://stackoverflow.com/a/50723016
type: Question
has answer: http://stackoverflow.com/a/50723799
accepted answer: http://stackoverflow.com/a/50723799
has body: I have these four prob. lists: x1 = [1,0,0] ; prob. of No goal scored per timeslot. x2 = [0,1,0] ; prob. of Home Team scoring per timeslot. x3 = [0,0,1] ; prob. of Away Team scoring per timeslot. y = [0.97, 0.02, 0.01]; constant prob. per timeslot. I want the sum of squared difference (sse) of x1 and y until a goal is scored. Then the sse is calculated by x2 or x3 and y depending on who scored first. Then it loops back to x1 and y until a goal is scored again by either Team and so on... Here is what I have attempted so far. Total timeslot = 15. Order of timeslot Home_Goal_timeslot = 8th, 14th. i.e. at two different timeslots. Away_Goal_timeslot = 11th No_Goal = 12. i.e. number of timeslots 12 x1 = np.array([1,0,0]) x2 = np.array([0,1,0]) x3 = np.array([0,0,1]) y = np.array([0.97, 0.02, 0.01]) def sum_squared_diff(x1, x2, x3, y, k): for k in range(15): if k == 'No_Goal': return sum((x1 - y)**2) elif k == 'Home_Goal': return sum((x2 - y)**2) else: return sum((x3 - y)**2) sum_squared_diff(x1, x2, x3, y, k=15) Out[1912]: 1.9213999999999998 print(sum((x1 - y)**2)**12, sum((x2 - y)**2)**2, sum((x3 - y)**2)**1) 5.669391237529683e-35 3.6153219599999997 1.9213999999999998 add up to 5.5367219599999995 Why is the above solutions are different? I prefer to add the sse after each timeslot and make a note when a goal is scored. So I can go back and add/subtract some infinitesimal epsilon to y values and measure the test... This is the out come i want 0.0014000000000000017, 0.0014000000000000017, 0.0014000000000000017, 0.0014000000000000017, 0.0014000000000000017, 0.0014000000000000017, 0.0014000000000000017, 0.0014000000000000017, 1.9014, 0.0014000000000000017, 0.0014000000000000017, 1.9213999999999998, 0.0014000000000000017, 0.0014000000000000017, 1.9014
has comment: http://stackoverflow.com/comment/88452944
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/50723016
tagged with: iteration
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88459443

http://stackoverflow.com/q/50822924
tagged with: image
type: Question
has body: I have two images, one overlay and one background. I want to create a new image, by editing overlay image and manipulating it to show only the pixels which have blue colour in the background image. I dont want to add the background, it is only for selecting the pixels. Rest part should be transparent. Any hints or ideas please? PS: I edited result image with paint so its not perfect. Image 1 is background image. Image 2 is overlay image. Image 3 is the check I want to perform. (to find out which pixels have blue in background and making remaining pixels transparent) Image 4 is the result image after editing.
upvote count: 1
has title: Edit image pixel by pixel - Python
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50855536
tagged with: python
has answer: http://stackoverflow.com/a/50855536
downvote count: 0
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/88464006
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50727897
type: AnswerComment
has text: Nope. It's called exactly once per input element. In `for elem in it:`, the iterator (`it`) has already advanced beyond the first `k` elements thanks to the earlier `zip`.

http://stackoverflow.com/comment/88430093
comment on: http://stackoverflow.com/q/50710412
has text: Meanwhile: you've already written a complicated nested `SELECT`, so presumably you know how to use the `IN` operator with a list instead of `=` with a value; the only tricky bit is how to group the results so you get `major_id, minor_id, count` rows. If you can get everything working up to that point, then you'll have a more specific question to ask.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/50872899
type: AcceptedAnswer
type: Answer
has body: Thanks to the comment, hpaulj! I think that nargs=argparse.REMAINDER is my best option here, as it separates the target appication's arguments from my wrapper's arguments. This way I don't have to worry about that the wrapper's arguments clash with the arguments I merely wish to pass on. import argparse parser = argparse.ArgumentParser() parser.add_argument('--verbose', action='store_true') parser.add_argument('rest_args', nargs=argparse.REMAINDER) args = parser.parse_args() print(args) So when calling wrapper.py -- -i 1 -name "Mike Wazowski" --verbose I get: Namespace(rest_args=['-i', '1', '-name', 'Mike Wazowski', '--verbose'], verbose=False) And if calling wrapper.py --verbose -- -i 1 -name "Mike Wazowski" --verbose I get: Namespace(rest_args=['-i', '1', '-name', 'Mike Wazowski', '--verbose'], verbose=True) Note, the -- is actually optional in the above examples and will yield the same results.
accepted answer of: http://stackoverflow.com/q/50832080
score: 0
answers question: http://stackoverflow.com/q/50832080

http://stackoverflow.com/comment/88458621
type: QuestionComment
has text: python is already installed
comment on: http://stackoverflow.com/q/50722920
score: 0
type: Comment

http://stackoverflow.com/comment/88590361
score: 0
type: Comment
type: QuestionComment
has text: @Lemayzeur it works for me Thank you I really appreciate your help
comment on: http://stackoverflow.com/q/50789153

http://stackoverflow.com/comment/88556985
type: Comment
has text: This does not consider the frequency of values in the output at all. The question is specific on that.
score: 1
comment on: http://stackoverflow.com/a/50775020
type: AnswerComment

http://stackoverflow.com/comment/88676593
score: 0
type: Comment
has text: @FHTMitchell alright so I tried [this](https://gist.github.com/kpagcha/afbe8c399c7fdce0de65acb62d899a02) however weirdly enough when trying to set a value `arr = IndexedArray(models1, models2); arr[m1, m2] = N;` for some **weird** reason while `key` should be `(m1, m2)`, it is magically transformed to `(0, 0)` by `__setitem__`. What's happening here?
type: QuestionComment
comment on: http://stackoverflow.com/q/50817371

http://stackoverflow.com/a/50819419
has body: Code: import re text = "This is line ABC XYZ. This is something. This is ABC XYZ. foo. This is ABC XYZ. foo" x = re.split("(ABC XYZ)",text) c=0 for i,s in enumerate(x): if re.match('(ABC XYZ)',x[i]): c+=1 x[i] = str(c)+' '+x[i] x = ''.join(x) # This is line 1 ABC XYZ. This is something. This is 2 ABC XYZ. foo. This is 3 ABC XYZ. foo You can use more optimized ways of doing this, however this would help you understand it better.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50819002

http://stackoverflow.com/a/50833260
has comment: http://stackoverflow.com/comment/88670454
upvote count: 1
has comment: http://stackoverflow.com/comment/88670684
score: 1
answers question: http://stackoverflow.com/q/50832601
downvote count: 0
has body: I can't think of a solution in sklearn so here's one in pandas # Data predictions Out[]: A B C D E G H L N P R S U V LABEL 0 0.718363 0.5 0.403466 0.5 0.5 0.458989 0.5 0.850190 0.620878 0.182169 0.483631 0.432915 0.328495 0.5 A 1 0.677776 0.5 0.366128 0.5 0.5 0.042405 0.5 0.894200 0.510644 0.015789 0.523462 0.547838 0.691239 0.5 L 2 0.682019 0.5 0.074347 0.5 0.5 0.562217 0.5 0.417786 0.539949 0.799223 0.603212 0.620806 0.335204 0.5 G 3 0.482981 0.5 0.065436 0.5 0.5 0.112383 0.5 0.743659 0.604382 0.246766 0.399070 0.341081 0.229407 0.5 P 4 0.700207 0.5 0.515825 0.5 0.5 0.078089 0.5 0.437839 0.249892 0.064734 0.822834 0.769277 0.512239 0.5 U # Check if the label is in the top 3 (one line solution) predictions.apply(lambda row: row['LABEL'] in list(row.drop('LABEL').sort_values().tail(3).index), axis=1) Out[]: 0 True 1 True 2 False 3 False 4 False Here is what is happening: # List the top 3 results: predictions.apply(lambda row: list(row.drop('LABEL').sort_values().tail(3).index), axis=1) Out[]: 0 [N, A, L] 1 [A, U, L] 2 [S, A, P] 3 [V, N, L] 4 [A, S, R] # Then check if the 'LABEL' is inside this list You could ask this question on Cross Validated as they will use sklearn extensively
type: Answer

http://stackoverflow.com/a/50832872
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50832334
has body: Another approach based on splitting every character of the number treated as string: df = pd.DataFrame([12, 24, 36, 48], columns=['A']) values = df['A'].values split = [list(str(el)) for el in values] out = pd.DataFrame(split, columns=['B', 'C']).astype(int) which gives: out B C 0 1 2 1 2 4 2 3 6 3 4 8
upvote count: 2

http://stackoverflow.com/comment/88585915
type: QuestionComment
has text: @Georgy , thx for the link, the generator solution is time saving for a large given_num or n, considering I am working on a optimization problem.
score: 0
comment on: http://stackoverflow.com/q/50756944
type: Comment

http://stackoverflow.com/comment/88552947
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50772639
type: QuestionComment
has text: But probably what you actually want is a *database* if you think you're going to be changing the data a lot.

http://stackoverflow.com/a/50805691
type: Answer
answers question: http://stackoverflow.com/q/50805607
score: 0
upvote count: 1
downvote count: 1
has body: Since you are gathering values inside the function, there is no need to pass them as arguments. def multiply_two_numbers(): x = input("Enter a number: ") y = input("Enter another number: ") return x*y &gt;&gt;&gt; multiply_two_numbers() Enter a number: 10 Enter another number: 12.5 125.0

http://stackoverflow.com/comment/88604040
type: AnswerComment
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172897/discussion-between-nikhil-wagh-and-jorge-peris).
score: 0
comment on: http://stackoverflow.com/a/50798358

http://stackoverflow.com/q/50795543
has answer: http://stackoverflow.com/a/50796235
has title: read images which start with certain string opencv - python
favorite count: 0
type: Question
tagged with: python
tagged with: computer-vision
tagged with: opencv
has body: I have a folder which is containing thousands of images. I want to read only the images which start with a certain string, let's say input, how can I do this exactly ? I am using opencv, so this is how I read all images inputA_path = os.path.join(inputA_dir, '*g') inputFilesA =glob.glob(inputA_path) for f1 in inputFilesA: inputA = cv2.imread(f1)
upvote count: 2
has comment: http://stackoverflow.com/comment/88598031
accepted answer: http://stackoverflow.com/a/50796235
answer count: 1
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/q/50827249
has body: I have .csv file looking like this: https://gyazo.com/746719669f079b0b0c22965b63e52910, I have to open this file and proccess data few million times, my code was working with with open() as f: but then I realized it might be super slow since it opens file every time, so I tried to put that data into variable and just use it later, problem is data disappears after first read, here is my code: import csv TEST = open("C:/Users/Krzysztof/Documents/SO.csv") CCSSVV = csv.DictReader(TEST, delimiter=";") def printdate(FILE): print("start") for LINE in FILE: print(LINE["MATCH DATE"]) print("end") printdate(CCSSVV) printdate(CCSSVV) printdate(CCSSVV) I wanted output to look like: start 25.05.2018 25.05.2018 25.05.2018 end start 25.05.2018 25.05.2018 25.05.2018 end start 25.05.2018 25.05.2018 25.05.2018 end but instead it's start 25.05.2018 25.05.2018 25.05.2018 end start end start end
duplicate of: http://stackoverflow.com/q/3906137
type: Question
has title: Python - CSV empty after first read
has comment: http://stackoverflow.com/comment/88659102
duplicate of: http://stackoverflow.com/q/36572993
score: 0
duplicate of: http://stackoverflow.com/q/36561963
tagged with: http://stackoverflow.com/tag/csv
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88659130
answer count: 0
duplicate of: http://stackoverflow.com/q/11150155
has comment: http://stackoverflow.com/comment/88659116
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/3906137

http://stackoverflow.com/comment/88651263
has text: @FHTMitchell First of all, thank you for your ans. It helps. I used numpy array because I have been using this all the time. Can you suggest why list and .append would be more convenient? Is it about the computation time?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50820379

http://stackoverflow.com/comment/88848476
has text: In case the number of *distinct* points is large, building an index can boost performance, since then the database almost instantly knows what rows have a given amount of points (compare it with a dictionary lookup over linear search).
comment on: http://stackoverflow.com/q/50834762
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50776223
has comment: http://stackoverflow.com/comment/88560223
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88561771
has comment: http://stackoverflow.com/comment/88559625
has comment: http://stackoverflow.com/comment/88560731
downvote count: 0
has body: If you are uncomfortable asking them for database as roganjosh suggested :) use Selenium. Write in Python a script that controls Web Driver and repeatedly sends requests to all possible combinations. The script is pretty simple, just a nested loop for each type of parameter/drop down. If you are sure that value of each type do not depend on each other, check what request is sent to the server. If it is simple URL encoded, like age=...&amp;sex=...&amp;..., then Selenium is not needed. Just generate such URLa for all possible combinations and call the server.
accepted answer of: http://stackoverflow.com/q/50776071
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50776071
score: 1

http://stackoverflow.com/q/50708063
has comment: http://stackoverflow.com/comment/90839409
has answer: http://stackoverflow.com/a/50708216
tagged with: headless
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50708675
answer count: 4
favorite count: 0
type: Question
has title: Headless Chrome Browser - Using Selenium and ChromeDriver
tagged with: python
has answer: http://stackoverflow.com/a/51941728
has body: Running latest version of all features (chrome version 66, selenium version 3.12, chromedriver version 2.39, python version 3.6.5) I have tried all of the solutions that I have found online but nothing seems to be working. I have automated something using Selenium for Chrome and it does exactly what I need it to do. The last thing I need to to is hide the browser because I do not need to see the UI. I have attempted to make the browser headless using the following code but when I do the program crashes. I have also tried to alter the window size to 0x0 and even tried the command: options.set_headless(headless=True) instead but nothing seems to work. NOTE: I am running on Windows and have also tried with the command: options.add_argument('--disable-gpu')
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/52631557
score: 0
tagged with: selenium
upvote count: 1
tagged with: google-chrome
downvote count: 1

http://stackoverflow.com/comment/88642998
type: Comment
type: QuestionComment
has text: You should decorate it with `@can_access()`.
comment on: http://stackoverflow.com/q/50818916
score: 0

http://stackoverflow.com/q/50708074
has comment: http://stackoverflow.com/comment/88441537
has answer: http://stackoverflow.com/a/50718056
tagged with: machine-learning
downvote count: 1
has comment: http://stackoverflow.com/comment/88431400
type: Question
has title: How to see how far "off" my machine learning prediction is?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50718056
score: -1
upvote count: 0
answer count: 1
tagged with: scikit-learn
has body: So I've essentially got a machine learning algorithm that has an accuracy of 20%. This is not that high, but I would like to know how close my algorithm is on average. So if it predicted a value of 69 and the real value in the testing-data was 68 and it had that "margin"-of-error throughout then I would be fine with using it for the purpose that I am using it for, which is filling in missing data in a data-set. Is there some easy way to do this? Snippet of my code: def predict_score_industry(df): coi = ['score_teaching', 'score_research', 'score_citation', 'score_int_outlook', ] not_nans = df['score_industry'].notnull() df_notnans = df[not_nans] x = np.array(df_notnans[coi]) y = np.array(df_notnans['score_industry']) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25) clf = LinearRegression() clf.fit(x_train, y_train) print("score_industry: ", clf.score(x_test, y_test)) df_nans = df.loc[~not_nans].copy() df_nans['score_industry'] = clf.predict(df_nans[coi]) df.score_industry.fillna(df_nans.score_industry, inplace=True) return df It basically takes all unfilled values and predicts them, the dataframe it reads in looks like this: &gt; print(df.info()) Data columns (total 15 columns): university_name 2884 non-null object country 2884 non-null object ranking 2884 non-null int64 no_student 2884 non-null int64 no_student_p_staff 2884 non-null float64 pct_intl_student 2884 non-null float64 year 2884 non-null int64 score_overall 2884 non-null float64 score_teaching 2884 non-null float64 score_research 2884 non-null float64 score_citation 2884 non-null float64 score_industry 2884 non-null float64 score_int_outlook 2884 non-null float64 male 2884 non-null float64 female 2884 non-null float64
tagged with: python
favorite count: 0

http://stackoverflow.com/q/50843303
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50843432
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/50843468
has comment: http://stackoverflow.com/comment/88690337
has comment: http://stackoverflow.com/comment/88690224
upvote count: 0
favorite count: 0
tagged with: python-3.x
has body: Here is my code: for i in range(len(sys.argv)): if sys.argv[i] == "--width": if math.isnan(sys.argv[i+1]): print("Width specified ({0}) is not a valid integer!".format(sys.argv[i+1])) sys.exit() else: width = int(sys.argv[i+1]) Here is my input: python3 main.py --width 1280 --height 720 I expect the width and height variable to be set to 1280 and 720, respectively. Instead, this is what I get: Traceback (most recent call last): File "main.py", line 8, in &lt;module&gt; if sys.argv[i] == "--width": TypeError: list indices must be integers or slices, not str I am somewhat experienced with command-line Python, however this is my first time creating a PyQt app, and using sys.argv in particular. Why do I get this error, and how can I fix it? Thanks.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88690199
has title: python - TypeError: list indices must be integers or slices, not str

http://stackoverflow.com/comment/88500407
type: Comment
has text: Thank you! But below is simpler and worked exactly like it should.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50746376

http://stackoverflow.com/a/50785810
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50784021
has body: The dataset just stores the word indices as a sequence of integers as you discovered. Hidden in the keras.datasets.imdb module is another function that retrieves the dictionary mapping word indices back to words; unfortunately it is not clearly documented. You can use that to convert indices back to words to find what the sentences look like. There is already a nice blog post on how to use pre-trained word vectors with the Embedding layer in Keras. You can load the vectors based on the dictionary mapping you get for IMDb dataset as the indices might not match.

http://stackoverflow.com/a/50733489
has comment: http://stackoverflow.com/comment/88475036
has comment: http://stackoverflow.com/comment/88476504
has comment: http://stackoverflow.com/comment/88476747
has comment: http://stackoverflow.com/comment/88476434
has comment: http://stackoverflow.com/comment/88474894
has comment: http://stackoverflow.com/comment/88477044
has comment: http://stackoverflow.com/comment/88475749
has comment: http://stackoverflow.com/comment/88474795
type: Answer
has comment: http://stackoverflow.com/comment/88475090
has body: After reviewing the code @Waffle linked, the following seem to be the important classes. The first represents nodes in a linked list, and the second is a container class for nodes allowing easy representations of empty lists. The goal is to implement LinkedList.swap_front_back() in a way that mutates the represented list in-place. class Node: def __init__(self, value=None, next=None): self.value = value self.next = next class LinkedList: def __init__(self): self.head = None self.tail = None self.size = 0 def swap_front_back(self): """TODO: Magic happens here""" Since Python has an implicit return of None, using returns as a way of breaking out a function even if it supposedly "doesn't return anything" is a safe exit strategy. Hence, the following couple lines gets rid of the smallest edge cases: if self.size &lt; 2: return The strategy I proposed for swapping the list in-place involved a second-to-last element, and all kinds of bad things happen if that happens to be the first element. In other words, we unfortunately have to deal with the case of a linked list of size 2 as a special case (for this implementation). if self.size == 2: self.head, self.tail = self.tail, self.head self.head.next = self.tail self.tail.next = None return In the general case, we need to change where the second-to-last element of the linked list points. If this doesn't happen the linked list becomes a cycle, and all kinds of bad things happen in algorithms which expect the list to end. current = self.head while current.next.next is not None: current = current.next Once the second-to-last element is found, we can go through with the actual pointer manipulations. current.next.next = self.head.next # Now the former last element points to the second element # A-&gt;B-&gt;C-&gt;D-&gt;B current.next = self.head # Now the second-to-last element points to the previous head # A-&gt;B-&gt;C-&gt;A D-&gt;B self.head.next = None # We don't want circles, so we eliminate A being first and last # D-&gt;B-&…
answers question: http://stackoverflow.com/q/50732993
has comment: http://stackoverflow.com/comment/88476854
has comment: http://stackoverflow.com/comment/88476299
has comment: http://stackoverflow.com/comment/88476395
has comment: http://stackoverflow.com/comment/88476591
has comment: http://stackoverflow.com/comment/88474723
has comment: http://stackoverflow.com/comment/88475185
has comment: http://stackoverflow.com/comment/88475373
has comment: http://stackoverflow.com/comment/88476349
has comment: http://stackoverflow.com/comment/88474828
has comment: http://stackoverflow.com/comment/88474923
has comment: http://stackoverflow.com/comment/88475637
has comment: http://stackoverflow.com/comment/88475055
has comment: http://stackoverflow.com/comment/88474836
has comment: http://stackoverflow.com/comment/88474970
score: 0
has comment: http://stackoverflow.com/comment/88476749
has comment: http://stackoverflow.com/comment/88477015

http://stackoverflow.com/q/50787915
tagged with: python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50787952
tagged with: list
has answer: http://stackoverflow.com/a/50788079
upvote count: 1
tagged with: indexing
possible better answer: http://stackoverflow.com/a/50787946
has title: Python 3: Function "A list with the strings and their index"
has answer: http://stackoverflow.com/a/50787946
answer count: 4
has body: Write a function, which would return a list with the strings and their index. e.g. ['good', 'morning'] -> ['0 - good', '1 - morning'] I tried this: def add_index(list_a): x = [] for word in list_a: x = [list_a.index(word) for word in list_a] return x However, the return is [0, 1], not what I am looking for.
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50787942
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50787952

http://stackoverflow.com/q/50725416
has comment: http://stackoverflow.com/comment/88459428
tagged with: plot
tagged with: spherical-coordinate
has body: Does anyone know of a good and simple way to do it? An online tool or a Python script would be great. So far, the best I have found is: https://tex.stackexchange.com/questions/268830/drawing-spherical-harmonic-density-plots-on-the-surface-of-a-sphere-in-tikz-pgfp However, I could not install mpl_toolkits.basemap and then the nice script is halted.
tagged with: matplotlib
has title: Handy way to plot surface spherical harmonics?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92554209
tagged with: python
linked to: http://stackoverflow.com/q/49158505
has comment: http://stackoverflow.com/comment/88472092
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/49158505

bokeh
tags question: http://stackoverflow.com/q/50729418
tags question: http://stackoverflow.com/q/50759158
tags question: http://stackoverflow.com/q/50782293
type: Tag
tags question: http://stackoverflow.com/q/50747006
tags question: http://stackoverflow.com/q/50835245
tags question: http://stackoverflow.com/q/50823204
tags question: http://stackoverflow.com/q/50853416
tags question: http://stackoverflow.com/q/50729353
tags question: http://stackoverflow.com/q/50750359
tags question: http://stackoverflow.com/q/50729806
tags question: http://stackoverflow.com/q/50840609
tags question: http://stackoverflow.com/q/50804495
tags question: http://stackoverflow.com/q/50819338
tags question: http://stackoverflow.com/q/50824852
tags question: http://stackoverflow.com/q/50835979
tags question: http://stackoverflow.com/q/50715776
tags question: http://stackoverflow.com/q/50817533
tags question: http://stackoverflow.com/q/50826750
tags question: http://stackoverflow.com/q/50725715
tags question: http://stackoverflow.com/q/50772959
tags question: http://stackoverflow.com/q/50840847
tag name: bokeh
tags question: http://stackoverflow.com/q/50759458

http://stackoverflow.com/q/50723203
accepted answer: http://stackoverflow.com/a/50723546
type: Question
tagged with: numpy
has title: Numpy: How to prevent circular looping to highest value when subtracting from the least value
downvote count: 0
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50723278
has answer: http://stackoverflow.com/a/50723283
linked to: http://stackoverflow.com/q/37822375
possible better answer: http://stackoverflow.com/a/50723278
upvote count: 1
tagged with: python
has body: image = cv2.imread('black.jpg')[:,:,0] # let's just take the red channel alone for brevity print(image[75:85,155:165]) # print middle 10x10 # output: [[0,0,0,....],...] I want subtract 1 from all pixel intensity. And yes, I definitely do not want 0s to become 255s. I just want them to stay as 0. print(image[75:85,155:165]-1) # output: [[255,255,255,....],...] print(np.array(image[75:85,155:165])-1) # output: [[255,255,255,....],...] print(np.array(image[75:85,155:165], dtype='float32')-1) # output: [[-1.,-1.,-1.,....],...] I can convert the last one back to uint8 after .clip(0,255) but that doesn't feel like the right way of doing it. Is there a way to directly do it (without casting and if conditions which might not be efficient for parallel processing)?
has answer: http://stackoverflow.com/a/50723546
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/88671280
comment on: http://stackoverflow.com/q/50833570
type: QuestionComment
has text: then which one to download I am new to python please help me to install.
type: Comment
score: 0

http://stackoverflow.com/comment/88701628
type: QuestionComment
has text: What is your entry, a .txt file? if so, you could share the file.
score: 0
comment on: http://stackoverflow.com/q/50849260
type: Comment

http://stackoverflow.com/comment/88425693
type: QuestionComment
has text: That require me to explain alot....but this is a part of large project and it need to be done like this
comment on: http://stackoverflow.com/q/50708170
score: 0
type: Comment

http://stackoverflow.com/comment/88669229
score: 0
type: Comment
has text: if you have new questions, post them but don't put everything into comments - this question here is answered. https://stackoverflow.com/questions/15315452/selecting-with-complex-criteria-from-pandas-dataframe
comment on: http://stackoverflow.com/a/50830956
type: AnswerComment

http://stackoverflow.com/a/50847791
type: Answer
has body: The reason your program never exits is that you're waiting on cat, except cat is waiting for an EOF that never comes. when you call subprocess.Popen(['cat'], stdin=r).wait(), it reads from the file descriptor and prints it to stdout because you didn't redirect stdout. This is why you still see '123' on the screen. Consider either of these options instead: Use a queue: import threading from Queue import Queue q= Queue() def producer(): print '--producer started' q.put('123') print '--producer finished' def consumer(): print '--receiver started' print q.get() print '--receiver finished' threading.Thread(target=producer).start() threading.Thread(target=consumer).start() or use os.pipe but use read and write instead import os, subprocess, threading (r, w) = os.pipe() def producer(): print '--producer started' os.write(w, '123') print '--producer finished' os.close(w) print '--write pipe closed' def consumer(): print '--receiver started' print os.read(r, 3) print '--receiver finished' os.close(r) print '--read pipe closed' threading.Thread(target=producer).start() threading.Thread(target=consumer).start()
upvote count: 1
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/50847096

http://stackoverflow.com/q/50783518
has answer: http://stackoverflow.com/a/50783625
score: -1
linked to: http://stackoverflow.com/q/2835559
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I want to parse JSON file and get two fields from the JSON and put them in a dictionary. For example: { "food": [{ "name": "pasta", "type": "blabla", "sauce": [{ "name": "cream", "url": "http://www...." } ] }, { "name": "pizza", "type": "bla", "sauce": [{ "name": "Tomato", "url": "http://www...." } ] } ] } And I want to get: {pasta: cream, pizza: Tomato}
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has title: How to parse JSON and put 2 fields in dictionary in Python?
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/2835559

http://stackoverflow.com/comment/88660997
type: QuestionComment
comment on: http://stackoverflow.com/q/50827970
has text: what does intLength[m] hold. Is intLength[0]=31 and IntLength[1]=28 (and 29 in a leap year?). It feels like the way it is written now, a January date has day added in twice.
score: 1
type: Comment

http://stackoverflow.com/a/50757683
answers question: http://stackoverflow.com/q/50757595
score: 1
has comment: http://stackoverflow.com/comment/88522955
upvote count: 1
type: AcceptedAnswer
has body: you could use strip(), as: file_stuff = map(lambda s: s.strip(), file_stuff) print(file_stuff) // ['John Smith', '', 'Gardener', '', 'Age 27', '', 'Englishman'] use filter if you want to remove empty items from list, like file_stuff = filter(None, map(lambda s: s.strip(), file_stuff))
has comment: http://stackoverflow.com/comment/88523112
has comment: http://stackoverflow.com/comment/88522962
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50757595

http://stackoverflow.com/q/50837012
linked to: http://stackoverflow.com/q/20109391
type: Question
has title: Pandas rolling min max
upvote count: 2
score: 0
tagged with: pandas
answer count: 1
has body: How findout the one which comes first among max and min in a rolling window of size n on dataframe and store the quantified values(lets say 1 if max comes first and 0 if min comes first) ?
favorite count: 0
downvote count: 2
tagged with: rolling-computation
tagged with: python
has comment: http://stackoverflow.com/comment/88677647
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50838046
accepted answer: http://stackoverflow.com/a/50838046

http://stackoverflow.com/a/64801864
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50837602
upvote count: 2
has body: With regards to the following error: ImportError: cannot import name 'moduleTNC' It can be solved by renaming moduletnc.cp36-win_amd64.pyd with moduleTNC.cp36-win_amd64.pyd in: AppData\Roaming\Python\Python36\site-packages\scipy\optimize

http://stackoverflow.com/q/50741927
has comment: http://stackoverflow.com/comment/88491338
answer count: 1
has body: I'm just starting with django even if i'm no new to python, so i'm creating a testing project just to explore django features, workflow and so on. I already made apps (like the usual polls, books, etc), but now i would like to make an app that gives only functionality with no model nor pages (views and templates): a simple app with some function to be called from the main django project or other apps. I used the startapp command to crete all the boilerplate, but i cannot understand where to write my code, since it's not a model nor a template etc. Anyone has already faced this scenario? Thanks in advance to anyone who can point me in the right direction. EDIT 1: I start to think that maybe an app is not exactly what i need, to explain better let's think about an app that provide functionality for e.g. simple interface to web rest api interact with local installed software manipulate custom file format etc So in fact is much more a library, but every django tutorial i found were about basic books/polls apps, so maybe there is a dedicated approach to my use case but i never stumbled upon it.
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50742095
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88491518
upvote count: 0
has comment: http://stackoverflow.com/comment/88491457
type: Question
downvote count: 2
score: -2
tagged with: django-apps
has title: Create django app for functionality only
linked to: http://stackoverflow.com/q/4479901

http://stackoverflow.com/comment/88577656
score: 0
type: Comment
has text: Haha, exactly, but even better is what Matteo just befor me, 1e-12, which is the smalest number possible before 0 !
comment on: http://stackoverflow.com/a/50785346
type: AnswerComment

http://stackoverflow.com/q/50821180
tagged with: class-attributes
has title: What happens when calling a unbound function during class definition
type: Question
has answer: http://stackoverflow.com/a/50821323
has comment: http://stackoverflow.com/comment/89841483
has body: I am trying to initialize a class attribute by calling a function. Please see below. This code works as expected meanwhile it makes me confused. To my understanding getmemtoto is a so-called unbound function which need to be called with a instance of class T. How could it be called during the class definition? class T: def getmemtot(): output=shell(r"sed -r -n -e 's/^MemTotal:\s*([[:digit:]]+)\s*kB/\1/ p' /proc/meminfo") return int(output) MEMTOT=T.getmemtot() If I tried to call getmemtot directly I got below errors: &gt;&gt;&gt; T.getmemtot() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method getmemtot() must be called with T instance as first argument (got nothing instead) &gt;&gt;&gt; getmemtot() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'getmemtot' is not defined
score: 0
has comment: http://stackoverflow.com/comment/88647691
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50709980
has body: You should use the "len > 0" condition. This code should work for any list or tuple length : def summary(xs): for tup in xs: prod = [a*a for a in tup if len(tup)&gt;0] print(sum(prod)) Note that I defined a "prod" list in order to use "sum" so that it is not calculated the hard way. It replaces your "x* x + y* y + z* z" and works for any tuple length.
score: 0
answers question: http://stackoverflow.com/q/50709759
type: Answer
has comment: http://stackoverflow.com/comment/88429423

http://stackoverflow.com/comment/88736105
type: AnswerComment
comment on: http://stackoverflow.com/a/50845537
type: Comment
has text: @AlexGap Consider showing us the desired output, what do you mean by "select". Do you mean print the list, or store it as a variable? More context required...
score: 0

http://stackoverflow.com/q/50789031
tagged with: async-await
type: Question
tagged with: infinite-loop
has answer: http://stackoverflow.com/a/50800121
tagged with: python-3.5
has body: I've been trying trying with no luck to create a endless chain of client instances. I'm developing an asyncio app, this app among many others things, like running a server with loop.create_server(), needs every 10 seconds to connect to a list of servers, send some data and then disconnect. I keep getting 2 errors: "runtimeError: Event loop is running." or "asyncio > Task was destroyed but it is pending!" The code down below works. import asyncio from tcp.client import Client def send_to_peers(data): for index in range(1, 3): #this for-loop just for simulating a list of peers try: loop = asyncio.get_event_loop() coro = loop.create_connection(lambda: Client(), '127.0.0.1', 10000 + index) _, proto = loop.run_until_complete(coro) msg = data + "-" + str(index) + "\n" proto.transport.write(str.encode(msg)) proto.transport.close() except ConnectionRefusedError as exc: print(exc) def infinite(): for index in range(5): #again this should be a While True: #there should be here an asyncio.sleep(10) send_to_peers(str(index)) infinite() But when I call it from the main_loop things start to break. async def infinite_loop(): for index in range(5): print("loop n " + str(index)) task = asyncio.Task(send_to_peers(str(index))) await asyncio.sleep(10) task.cancel() with suppress(asyncio.CancelledError): await task main_loop = asyncio.get_event_loop() main_loop.run_until_complete(infinite_loop()) main_loop.run_forever() I've tried to giving the main_loop to send_to_peers , giving it to the Client(loop) class,I tried to stoop &amp; close the loop, delete the task, use weird combination of ensure_future but nothing works. I googled as much as I could, I read it is not good to nest infinite loops but i didn't find any other way. My last hope is to use threading but even if I think it will work, it won't be an elegant solution, nor the right one. I'm used to work with Node so please excuse me if i made a silly mistake, I thought that after 2 weeks i could make it but here I am. I would real…
tagged with: python-asyncio
upvote count: 1
has title: asyncio - launching infinite loop.create_connection()
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50800121
score: 1

feature-selection
tags question: http://stackoverflow.com/q/50782187
tags question: http://stackoverflow.com/q/50796024
type: Tag
tags question: http://stackoverflow.com/q/50812539
tag name: feature-selection

http://stackoverflow.com/a/50809162
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50809140
answers question: http://stackoverflow.com/q/50809140
has body: Instead of class objects you should use instance objects when working with forms. So it should be user_form.is_valid() and profile_form.is_valid() user_form = RegistrationForm(request.POST) profile_form = employeeForm(request.POST or None,request.FILES or None) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.refresh_from_db() profile_form = employeeForm(request.POST, instance=user.employeemodel) profile_form.full_clean() profile_form.save() return redirect('emp_list') Same for the save() method: user = user_form.save()
type: Answer

http://stackoverflow.com/q/50714496
score: 0
has comment: http://stackoverflow.com/comment/88437805
has comment: http://stackoverflow.com/comment/88439650
type: UnansweredQuestion
tagged with: web-crawler
has body: import urllib def get_page(url): try: import urllib return urllib.urlopen(url).read() except: return "" def get_next_target(seed): start_link = seed.find('&lt;a href=') if start_link == -1: return 0, 0 start_quote = seed.find('"', start_link) end_quote = seed.find('"', start_quote + 1) url = seed[start_quote + 1 : end_quote ] return url, end_quote def get_all_links(seed): links = [] while True: url, remaining_page = get_next_target(seed) if url: links.append(url) seed = seed[remaining_page : ] else: break return links def crawl_web(seed): tocrawl = [seed] crawled = [] while tocrawl: page = tocrawl.pop() if page not in crawled: crawled.append(page) f = urllib.urlopen(page) content = f.read() tocrawl = tocrawl + get_all_links(content) print crawled crawl_web('https://en.wikipedia.org/wiki/Software_engineering') I am trying to build a web crawler but the above code renders the following error: click here for viewing the error Please help!!
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88439550
tagged with: python
has title: Python: [Errno ftp error] [ Errno 111] connection refused

http://stackoverflow.com/comment/88619957
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50769835
has text: Not sure if you can directly test using json like that. You can use flatc to generate a python API from the flatbuffer and then use the python API to feed in the same data to both TF and TFLite models and check the answers back.
score: 0

http://stackoverflow.com/comment/88520032
has text: @data83 My point is, I don’t think you want to return the list here at all. The caller still has access to `x.array`. And the usual Python idiom is that if the main point of a function is to mutate your self or a parameter, you return `None`, as explained somewhere in the official FAQ, but I’m no longer in front of my computer.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50754696
type: AnswerComment

http://stackoverflow.com/comment/88741992
score: 0
type: QuestionComment
has text: Did either of the posted solutions work for you?
type: Comment
comment on: http://stackoverflow.com/q/50853691

charts
tags question: http://stackoverflow.com/q/50826357
type: Tag
tags question: http://stackoverflow.com/q/50748569
tag name: charts
tags question: http://stackoverflow.com/q/50787196

http://stackoverflow.com/a/50788031
upvote count: 1
has body: Its not that opencv requires it, Its that whoever compiled the binary of opencv you are using compiled it against libavcodec56. Easiest fix is to compile it yourself. Also, how can I installed both libavcodec56 and libavcodec57 on my machine ? Don't. just compile and link against the same version.
downvote count: 0
answers question: http://stackoverflow.com/q/50786055
has comment: http://stackoverflow.com/comment/88582496
type: Answer
has comment: http://stackoverflow.com/comment/88582529
score: 1

http://stackoverflow.com/comment/88425745
comment on: http://stackoverflow.com/q/50708170
has text: about the subs of sympy, its much slower compared to this
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/75432901
has body: The solution that worked for me is to use pandas or awswrangler to read just zero rows of data and then dump that data in Redshift (This will create the table schema automatically in AWS Redshift). (Copy command can't create its own table as I searched for it everywhere but in vain.) And, then Run the copy command. Please find the working code below. Parameters: s3_bucket,s3_prefix and destination schema + destination table df = wr.s3.read_csv("s3://"+ s3_bucket + '/' + s3_prefix,nrows=0) df = df.applymap(str) df.to_sql( destination_table, redshift_eng, schema = destination_schema ,if_exists = 'append',index = False ,method = 'multi') s = f"""copy {destination_schema}.{destination_table} from 's3://{s3_bucket}/{s3_prefix}' iam_role 'Your_IAM_Role' EMPTYASNULL IGNOREHEADER 1 format as csv;""" redshift_conn.execute(s)
answers question: http://stackoverflow.com/q/50818766
score: 0
type: Answer

http://stackoverflow.com/comment/88488780
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50734157
has text: problems is: in general I will not know whether the first index in df1 is later or earlier than df2
score: 0

http://stackoverflow.com/comment/88711535
comment on: http://stackoverflow.com/q/50854360
type: Comment
type: QuestionComment
score: 3
has text: Its impossible the way you are trying to approach it ! You cannot modify the `variable's` name at runtime. I would suggest to use a dictionary instead.

http://stackoverflow.com/comment/88681573
has text: Almost perfect, problem is it igonre the sign of the number
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50838786
type: AnswerComment

http://stackoverflow.com/comment/88589724
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50791742
has text: When Aran-Fey changed `@wraps` to`@wraps(f)` and the functions anow appear as methods as I wanted. Why ?
score: 0

http://stackoverflow.com/q/50767714
has comment: http://stackoverflow.com/comment/88543761
has comment: http://stackoverflow.com/comment/88691807
has comment: http://stackoverflow.com/comment/88542893
has comment: http://stackoverflow.com/comment/88542951
answer count: 0
has body: I am having trouble using XPath Selector in ElementTree. Is there a way to dynamically change how data is being extracted using the example below. Let's say I am parsing through a file and I want to extract all the text within the target. Is there a way to use one call to use one "child".find(.//target/*) call that when looping through would both get the text in /target/p/em, /target/, /target/*, /target/** In my real problem I have a ton of different data and want to be able to add it to a dictionary to reference it later ie page_values = { 'first': child.find('.//first-name').text or "", 'last': child.find('.//last-name').text or "", 'biography': child.find('.//biography').text or "" } and I run into problems when the biography has tons of formatting applied to it so I would have to call it like 'biography': child.find('.//biography/p/em').text or "" and the next time through the loop I would need to call it like 'biography': child.find(.//biography/).text or "" Sample code: XML text vs text
type: Question
has comment: http://stackoverflow.com/comment/88543127
has comment: http://stackoverflow.com/comment/88543075
tagged with: python-2.7
score: 0
tagged with: elementtree
has title: ElementTree XPath - Getting all tags
tagged with: xpath
has comment: http://stackoverflow.com/comment/88543198
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88637395
has text: The file is in bytes or is it the escaped string? Have you tried printing it?
comment on: http://stackoverflow.com/q/50816228
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88586886
has text: `df.dot(df.columns+",").str[:-1].replace('',np.nan)` replacing empty with NaN
type: AnswerComment
comment on: http://stackoverflow.com/a/50789941
score: 0
type: Comment

http://stackoverflow.com/q/50794860
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50905604
type: Question
has body: I have a dataframe containing clinical readings of hospital patients, for example a similar dataframe could look like this heartrate pid time 0 67 151 0.0 1 75 151 1.2 2 78 151 2.5 3 99 186 0.0 In reality there are many more columns, but I will just keep those 3 to make the example more concise. I would like to "expand" the dataset. In short, I would like to be able to give an argument n_times_back and another argument interval. For each iteration, which corresponds to for i in range (n_times_back + 1), we do the following: Create a new, unique pid [OLD ID | i] (Although as long as the new pid is unique for each duplicated entry, the exact name isn't really important to me so feel free to change this if it makes it easier) For every patient (pid), remove the rows with time column which is more than the final time of that patient - i * interval. For example if i * interval = 2.0 and the times associated to one pid are [0, 0.5, 1.5, 2.8], the new times will be [0, 0.5], as final time - 2.0 = 0.8 iterate Since I realize that explaining this textually is a bit messy, here is an example. With the dataset above, if we let n_times_back = 1 and interval=1 then we get heartrate pid time 0 67 15100 0.0 1 75 15100 1.2 2 78 15100 2.5 3 67 15101 0.0 4 75 15101 1.2 5 99 18600 0.0 For n_times_back = 2, the result would be heartrate pid time 0 67 15100 0.0 1 75 15100 1.2 2 78 15100 2.5 3 67 15101 0.0 4 75 15101 1.2 5 67 15102 0.0 6 99 18600 0.0 n_times_back = 3 and above would lead to the same result as n_times_back = 2, as no patient data goes below that point in time I have written code for this. def expand_df(df, n_times_back, interval): for curr_patient in df['pid'].unique(): patient_data = df[df['pid'] == curr_patient] final_time = patient_data['time'].max() for i in range(n_times_back + 1): new_data = patient_data[patient_data['time'] &lt;= final_time - i * interval] new_data['pid'] = patient_data['pid'].astype(str) + str(i).zfill(2) new_data['pid'] = new_data['pid'].astype(i…
has title: Pandas: duplicating dataframe entries while column higher or equal to 0
has comment: http://stackoverflow.com/comment/88597008
has comment: http://stackoverflow.com/comment/88596242
score: 0
accepted answer: http://stackoverflow.com/a/50905604
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/88549178
has text: This should be working if it's the exact value of the class attribute in the given element ([docs here](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class)). Can you provide some of the input html?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50770699
type: QuestionComment

http://stackoverflow.com/q/50774763
type: Question
tagged with: numpy
answer count: 2
has body: I have an array and I want to loop through its values to update it as follows: import numpy as np arr=np.ones((5,7)) for i in range(1,arr.shape[0]-1): for j in range(1,arr.shape[1]-1): arr[i,j]=arr[i+1,j]+arr[i,j+1] The result is, as desired, [[1. 1. 1. 1. 1. 1. 1.] [1. 2. 2. 2. 2. 2. 1.] [1. 2. 2. 2. 2. 2. 1.] [1. 2. 2. 2. 2. 2. 1.] [1. 1. 1. 1. 1. 1. 1.]] However, for-loops are quite slow and I'd like to know if there is a way to make this more efficient. Edit: The input is not always np.ones((5,7)), it will be something more heterogeneous in general.
score: 0
has title: Numpy array: efficiently assign values
has answer: http://stackoverflow.com/a/50775060
possible better answer: http://stackoverflow.com/a/50775146
tagged with: python
has answer: http://stackoverflow.com/a/50775146
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50775060
has comment: http://stackoverflow.com/comment/88556649

http://stackoverflow.com/comment/88594421
type: Comment
has text: Tried the `.collect()` method. Getting this error: `py4j.protocol.Py4JJavaError: An error occurred while calling o86.get. : java.util.NoSuchElementException: spark.sql.execution.pandas.respectSessionTimeZone`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50794028

http://stackoverflow.com/q/50699641
accepted answer: http://stackoverflow.com/a/50699679
tagged with: python-2.7
answer count: 2
downvote count: 0
score: 1
has body: I have this question about loops. Imagine You have this data array: list = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1] How would You write a loop which checks if the previous number is lower, and the next after the checked one (Condition looks like this [5,6,5]). So the loop will get to number 9 and print it or save it, whatever.
favorite count: 0
possible better answer: http://stackoverflow.com/a/50700064
has answer: http://stackoverflow.com/a/50700064
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: list
tagged with: loops
has title: Checking loop in Python
type: Question
has answer: http://stackoverflow.com/a/50699679

http://stackoverflow.com/a/50736355
score: 2
upvote count: 2
has body: There is a nice article about this here. But to better understand, I've made a small modification in your function to better visualize the problem. def funn(arg1, arg2=[]): print(id(arg2)) arg2.append(arg1) print(arg2) funn(1) # here you will get printed an id of arg2 funn(2, [3, 4]) # here it's a different id of arg2 because it's a new list funn(5) # here you will see that the id of the arg2 is the same as in the first function call.
has comment: http://stackoverflow.com/comment/88480740
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50736210

http://stackoverflow.com/comment/88632992
has text: You are trying to decorate a method and use it as wrapper of mock? Why you don't you just define the `return_value` to return you want?
type: QuestionComment
comment on: http://stackoverflow.com/q/50721500
type: Comment
score: 0

http://stackoverflow.com/q/50774697
tagged with: email
has body: I have put together a code to send emails to multiple recipients. However each recipient receives all mails instead of his own. Dataframe: email content mark@gmail.com Hi Mark, bla bla eve@gmail.com Hi Eve, bla bla john@gmail.com Hi, John bla bla for content in df['content']: for email in df['email']: message = MIMEMultipart() message['Subject'] = "Subject" message['From'] = 'my email' message['Reply-to'] = 'my email' message['To'] = '{}'.format(email) text = MIMEText(mail) message.attach(text) server = smtplib.SMTP ('smtp.gmail.com',587) server.ehlo() server.starttls() server.login(login, password) server.sendmail(message['From'], message['To'], message.as_string()) server.quit()
has answer: http://stackoverflow.com/a/50774965
type: UnansweredQuestion
tagged with: python
has title: Send individual emails to multiple recipients
linked to: http://stackoverflow.com/q/16476924
has comment: http://stackoverflow.com/comment/88556349
type: Question
tagged with: smtplib
tagged with: for-loop
has answer: http://stackoverflow.com/a/50774986
has comment: http://stackoverflow.com/comment/88556945
score: 0
has answer: http://stackoverflow.com/a/50775071
answer count: 3
tagged with: pandas

http://stackoverflow.com/q/50701460
favorite count: 0
accepted answer: http://stackoverflow.com/a/50701486
upvote count: 2
has body: I have the following dataframe: RawTimes_df = ETime XTime 0 2018-05-21 04:48:22 2018-05-21 05:52:45 1 2018-05-21 02:18:20 2018-05-21 03:19:53 2 2018-05-21 11:02:31 2018-05-21 12:17:57 3 2018-05-21 06:08:15 2018-05-21 07:08:12 4 NA 2018-05-21 16:14:16 5 2018-05-21 03:38:12 2018-05-21 04:39:05 6 2018-05-21 17:43:06 2018-05-21 18:59:38 7 2018-05-21 08:52:32 NA 8 2018-05-21 02:27:44 2018-05-21 03:33:08 9 2018-05-21 12:01:12 NA 10 2018-05-21 10:21:10 2018-05-21 11:26:45 11 NA 2018-05-21 21:27:38 12 2018-05-21 18:02:19 2018-05-21 19:07:31 13 2018-05-21 05:07:28 2018-05-21 06:07:51 14 NA 2018-05-21 13:10:22 15 2018-05-21 11:05:19 2018-05-21 12:17:31 16 2018-05-21 02:27:08 2018-05-21 03:33:54 17 2018-05-21 02:12:01 2018-05-21 03:18:11 18 2018-05-21 11:07:23 2018-05-21 12:21:30 19 2018-05-21 12:31:53 NA 20 2018-05-21 06:19:52 NA I am trying to replace the entries that are "NA" with the corresponding value from the other column. So for row 4 I want ETime to be the same as the relevant row 4 XTime "2018-05-21 16:14:16" and then row 9 XTime to be "2018-05-21 12:01:12" etc... Desired output: ETime XTime 0 2018-05-21 04:48:22 2018-05-21 05:52:45 1 2018-05-21 02:18:20 2018-05-21 03:19:53 2 2018-05-21 11:02:31 2018-05-21 12:17:57 3 2018-05-21 06:08:15 2018-05-21 07:08:12 4 2018-05-21 16:14:16 2018-05-21 16:14:16 5 2018-05-21 03:38:12 2018-05-21 04:39:05 6 2018-05-21 17:43:06 2018-05-21 18:59:38 7 2018-05-21 08:52:32 2018-05-21 08:52:32 8 2018-05-21 02:27:44 2018-05-21 03:33:08 9 2018-05-21 12:01:12 2018-05-21 12:01:12 10 2018-05-21 10:21:10 2018-05-21 11:26:45 11 2018-05-21 21:27:38 2018-05-21 21:27:38 12 2018-05-21 18:02:19 2018-05-21 19:07:31 13 2018-05-21 05:07:28 2018-05-21 06:07:51 14 2018-05-21 13:10:22 2018-05-21 13:10:22 15 2018-05-21 11:05:19 2018-05-21 12:17:31 16 2018-05-21 02:27:08 2018-05-21 03:33:54 17 2018-05-21 02:12:01 2018-05-21 03:18:11 18 2018-05-21 11:07:23 2018-05-21 12:21:30 19 2018-05-21 12:31:53 2018-05-21 12:31:53 20 2018-05-21 06:19:52 2018-05-21 06:19:52…
tagged with: python
tagged with: na
type: AnsweredQuestion
score: 2
tagged with: dataframe
type: Question
downvote count: 0
has title: Python: replace "NA" in column with value from corresponding row value of another column (and vice versa)
tagged with: pandas
has answer: http://stackoverflow.com/a/50701486
answer count: 1

http://stackoverflow.com/q/50766100
tagged with: kivy
has body: This is my Custom Widget:- &lt;Entry@Widget&gt;: size_hint: (1, None) height: sp(100) canvas.before: Color: rgba: 1, 1, 1, .65 Rectangle: pos: self.pos size: self.size canvas: Color: rgba: 1, 1, 1, 1 Rectangle: size: sp(30), sp(30) pos: self.right-sp(50), self.center_y source: root.status Label: id: first_letter text: root.name[0] color: 41/255, 128/255, 185/255, 1 pos: root.pos font_size: sp(50) Label: text: root.name[1:] color: 41/255, 128/255, 185/255, 1 pos: first_letter.x+sp(70), first_letter.y+sp(40) font_size: sp(30) size_hint_x: None width: sp(200) halign: 'left' texture_size: self.size text_size: self.size Label: text: root.date color: 17/255, 80/255, 122/255, 1 pos: root.x+sp(50), root.y-sp(10) font_size: 10 and there is main screen:- class Entry(Widget): name = StringProperty('Example') date = StringProperty('00/00/0000') status = StringProperty('static/right.png') def on_touch_down(self, touch): super(Entry, self).on_touch_down(touch) popup = Mypopup(name=self.name) popup.open() return True class MainScreen(FloatLayout): def __init__(self, **kargs): super(MainScreen, self).__init__(**kargs) layout = GridLayout(cols=1, spacing=10, size_hint_y=None) layout.bind(minimum_height=layout.setter('height')) for i in range(10): layout.add_widget(Entry(name='Facebook', date='12/12/2012', status='static/right.png')) for i in range(10): layout.add_widget(Entry(name='Facebook', date='12/12/2012', status='static/wrong.png')) scroll = ScrollView(size_hint=(1, None), height=Window.height) scroll.add_widget(layout) self.add_widget(scroll) When i run it in my computer it gives output:- after packagaing it in apk and install it seems like:- I want this to look same as in my computer.
tagged with: kivy-language
score: 1
has title: Why kivy giving diffrent result after apk packaging?
upvote count: 1
type: Question
tagged with: buildozer
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51412441
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50780209
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88567460
score: 6
has answer: http://stackoverflow.com/a/50780257
has answer: http://stackoverflow.com/a/50780415
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33019698
tagged with: rounding
has comment: http://stackoverflow.com/comment/88567358
has title: Round to nearest 0.25 without banker's rounding in Python 3
type: Question
tagged with: decimal
answer count: 2
has body: I would like to round a series of number like this: 0 -&gt; 0 0.1 -&gt; 0 0.125 -&gt; 0.25 0.25 -&gt; 0.25 I have heard that I can use round(x*4)/4 to find the nearest 0.25 unit. However, there will be some problems at the boundary with this function 0.125 -&gt; 0 (with round(x*4)/4) Is there anyway I can do the above rounding correctly? Thanks
possible better answer: http://stackoverflow.com/a/50780257
has comment: http://stackoverflow.com/comment/88567350
has comment: http://stackoverflow.com/comment/88567911
upvote count: 7
downvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50780415
favorite count: 0

http://stackoverflow.com/comment/88573148
comment on: http://stackoverflow.com/a/50779751
type: AnswerComment
score: 0
type: Comment
has text: The data is complete, but just don't know why there is a u' in every elements.

country
tag name: country
type: Tag
tags question: http://stackoverflow.com/q/50819677

http://stackoverflow.com/q/50745849
has comment: http://stackoverflow.com/comment/88530391
upvote count: 1
tagged with: tensorflow-probability
has comment: http://stackoverflow.com/comment/88529721
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88501561
has answer: http://stackoverflow.com/a/50766096
score: 1
has title: Specifying a DirichletMultinomial in tensorflow probability
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50766096
has body: This is probably quite basic, but I can't figure it out -- I have a 100x5 matrix y that is generated from a Dirichlet-Multinomial and I want to infer the parameters gamma using tensorflow probability. Below is the model I implemented (for simplicity I'm assuming that gamma is the same for all 5 classes for now): def dirichlet_multinomial_model(S, p, N, tau): gamma = ed.Gamma(2.0, 3.0, name='gamma') y = ed.DirichletMultinomial(500, tf.ones(5)*gamma, name='y') return y log_joint = ed.make_log_joint_fn(dirichlet_multinomial_model) def target_log_prob_fn(gamma): return log_joint( S=S, p=p, N=N, tau=tau, gamma=gamma, y=y) When I try to sample from this using HMC, I get the following error: ValueError: Incompatible shape for initialization argument 'value'. Expected (5,), got (100, 5). So specifying a length-5 vector of gammas seems to have resulted in the program expecting my data to be of shape 5x1. I cannot work out how to specify the model correctly -- any pointers would be appreciated.
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/a/65415643
score: 0
has body: In my case, it's that I have both python2 and python3 installed, and "python" refers to py2. "python -m unittest -v" always return "Ran 0 test" which is fixed by "python3 -m unittest -v"
type: Answer
answers question: http://stackoverflow.com/q/50775010

http://stackoverflow.com/comment/88699205
comment on: http://stackoverflow.com/a/50830175
type: Comment
has text: @jezrael - it occurs on .unstack(1)
type: AnswerComment
score: 0

http://stackoverflow.com/a/50735728
downvote count: 0
upvote count: 8
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88479190
type: Answer
has body: For you actual input the correct output is empty DataFrame. The conditions (data['Value2'] == 0) &amp; (data['Value2'] &gt;= 100) can't be simultaneous true. Use or operator instead. (data['Value2'] == 0) | (data['Value2'] &gt;= 100) Output Date Value1 Value2 02-01-01 02 00 04-01-01 04 101
accepted answer of: http://stackoverflow.com/q/50735669
score: 8
answers question: http://stackoverflow.com/q/50735669

http://stackoverflow.com/q/50729644
tagged with: python
type: AnsweredQuestion
tagged with: thread-synchronization
type: Question
has comment: http://stackoverflow.com/comment/88467170
has answer: http://stackoverflow.com/a/50836546
score: 4
upvote count: 4
has title: where can I find the source code for python Low-level threading API _thread extension module?
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88467384
has body: Specifically the source code of lock, which is implemented directly by the _thread extension module.
accepted answer: http://stackoverflow.com/a/50836546

http://stackoverflow.com/q/50709874
score: 3
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/50943700
has comment: http://stackoverflow.com/comment/88509486
downvote count: 0
has comment: http://stackoverflow.com/comment/88542484
has comment: http://stackoverflow.com/comment/88439085
has comment: http://stackoverflow.com/comment/88872613
has comment: http://stackoverflow.com/comment/88462538
has comment: http://stackoverflow.com/comment/88518647
has body: I'm trying to write a script that will convert each email element of an .mbox file into a .csv file. I specifically need the following elements, but if there was a way to "write for each element," that'd be preferred: To, From, CC'd, BCC'd, Date, Subject, Body I found a script online that looks to be the start of what I need, and the documentation about the email module, but I can't find any specifics on how to identify the different attribute options (to, from, cc'd, etc.) how to write them as unique cell values in a .csv. Here is sample code I found: import mailbox import csv writer = csv.writer(open("clean_mail_B.csv", "wb")) for message in mailbox.mbox('Saks.mbox'): writer.writerow([message['to'], message['from'], message['date']])
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: email
favorite count: 0
tagged with: mbox
has answer: http://stackoverflow.com/a/50943700
tagged with: python
has title: Python 3.6 Mbox to CSV
type: AnsweredQuestion

http://stackoverflow.com/a/50787029
accepted answer of: http://stackoverflow.com/q/50786266
score: 2
has body: Regarding the rule of saving data frames independently and not using SQL solution (or another database format) it could be the following code: import csv import pandas as pd def saver(dictex): for key, val in dictex.items(): val.to_csv("data_{}.csv".format(str(key))) with open("keys.txt", "w") as f: #saving keys to file f.write(str(list(dictex.keys()))) def loader(): """Reading data from keys""" with open("keys.txt", "r") as f: keys = eval(f.read()) dictex = {} for key in keys: dictex[key] = pd.read_csv("data_{}.csv".format(str(key))) return dictex (...) dictex = loader()
upvote count: 2
has comment: http://stackoverflow.com/comment/115088361
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50786266
type: Answer

http://stackoverflow.com/a/50790604
has comment: http://stackoverflow.com/comment/88587217
type: Answer
has comment: http://stackoverflow.com/comment/88587200
answers question: http://stackoverflow.com/q/50790554
has body: Building on ravi's answer, you can make your code more efficient by using this: def getlist(a): d_list = [] b = int(a) + 7 d_list = [str(b), str(b + 9), str(b + 2*9), str(b + 3*9)] return d_list The str(b), str(b+9), etc... casts your values as strings as they are put into the list, which is more efficient than iterating through your c list with a for loop and then appending those new values to d_list.
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/50841724
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88690400
tagged with: python
tagged with: regex
downvote count: 2
type: Question
score: -2
has comment: http://stackoverflow.com/comment/88687317
has comment: http://stackoverflow.com/comment/88690609
has title: regex python pattern error
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50843616
has comment: http://stackoverflow.com/comment/88690767
favorite count: 0
tagged with: hex
has comment: http://stackoverflow.com/comment/88690804
has body: I am using the following regular expression pattern for searching in a text file : hexadecimal numbers (to find : 1a2bc3d4e5 or 2369.235.26.158963 or Aaa4 ) only letters "a" or spaces. There may be "a", spaces or a mixture of two but nothing else. : Below my regex for hexadecimal numbers : matches = re.compile(' 0[xX][0-9a-fA-F]+ ') Below my regex for second pattern : matches = re.compile(r'^[a| ]*$') Unfortunately, it does not work. Thanks in advance for your help
has comment: http://stackoverflow.com/comment/88689073

http://stackoverflow.com/q/50746932
tagged with: http://stackoverflow.com/tag/html
tagged with: python
upvote count: 4
has body: I have the following situation, I have this model: class Profile(models.Model): DEVELOPER = 1 MARKETER = 2 ACADEMIC = 3 INFLUENCER = 4 COMMUNITY_MEMBER = 5 ROLE_CHOICES = ( (DEVELOPER, 'Developer'), (MARKETER, 'Marketer'), (ACADEMIC, 'Academic'), (INFLUENCER, 'Influencer'), (COMMUNITY_MEMBER, 'Community Member'), ) user = models.OneToOneField(User) account_type = models.ForeignKey(AccountType, default=AccountType.FREE) role = models.PositiveIntegerField(choices=ROLE_CHOICES, null=True, blank=True) github_profile = models.URLField(blank=True, null=True) linkedin_profile = models.URLField(blank=True, null=True) And now what I want to do is that if the user clicks in the dropwdown the Developer option, the github_profile should appear, otherwise it should keep hide. Right now, looks like this, and the Github Link fields should be hide: And this is my html: What best describes you? Choose an option {% for index, value in roles_form.fields.roles.choices %} {{ value }} {% endfor %} GitHub Profile (optional) I know this is a conditional thing, however I'm brand new in Django and I'm not pretty sure how to achieve it. EDIT: I did the following function: $('select').on('change', function() { var value = $(this).val(); if (value == 1) { $('#github_link').show(); } else if (value != 1) { $('#github_link').hide(); } }) It works but I got the following feedback: Here you have hardcoded the value "1", but if the positioning on this list changes, then this behavior will break. Instead, you should reference the variable {{ model.profile.DEVELOPER }} which will yield the current value of the variable DEVELOPER, even if it changes.
has comment: http://stackoverflow.com/comment/88502025
downvote count: 0
has comment: http://stackoverflow.com/comment/88502091
tagged with: django
type: Question
has title: Click in a dropdown option and show an specific field in Django
has answer: http://stackoverflow.com/a/50747281
tagged with: if-statement
has comment: http://stackoverflow.com/comment/88506857
has comment: http://stackoverflow.com/comment/88507103
score: 4
linked to: http://stackoverflow.com/q/26589481
has comment: http://stackoverflow.com/comment/88502122
has comment: http://stackoverflow.com/comment/88501992
answer count: 1
has comment: http://stackoverflow.com/comment/88507048
has comment: http://stackoverflow.com/comment/88501701
favorite count: 0
type: UnansweredQuestion

file-io
tags question: http://stackoverflow.com/q/50845162
type: Tag
tags question: http://stackoverflow.com/q/50832957
tag name: file-io
tags question: http://stackoverflow.com/q/50753594

http://stackoverflow.com/comment/88474272
comment on: http://stackoverflow.com/a/50733196
has text: You cannot just flip the head and the tail in a singly linked list.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88466612
has text: You can provide a default value for `k` if you want. What do you expect to happen?
type: Comment
comment on: http://stackoverflow.com/a/50723953
score: 0
type: AnswerComment

http://stackoverflow.com/a/50795522
type: AcceptedAnswer
has body: Just after I submitted this question, I finally found what I was looking for in the manual: Block Assignments. {% from "lib.jinja" import some_macro %} {% set content %} Some content {% endset %} {{ some_macro(self.some_macro(content)) }} The set and endset tags solve my problem.
accepted answer of: http://stackoverflow.com/q/50795367
type: Answer
answers question: http://stackoverflow.com/q/50795367
has comment: http://stackoverflow.com/comment/88596847
score: 0
has comment: http://stackoverflow.com/comment/88597000

http://stackoverflow.com/a/50834176
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50833933
type: Answer
has body: you can use Counter to calculate the summs from collections import Counter c = Counter() for d in list1: cur, v = d.get('currency'), d.get('value') c.update({cur: v}) print(c) Counter({'EUR': 43, 'USD': 22, 'GBP': 13}) and after generate the output: list2 = [{'currency': cur, 'value': v} for cur, v in c.items()] print(list2) [{'currency': 'USD', 'value': 22}, {'currency': 'GBP', 'value': 13}, {'currency': 'EUR', 'value': 43}]
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50833933
upvote count: 1

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/50703203
type: Tag

http://stackoverflow.com/q/50740039
answer count: 0
downvote count: 0
tagged with: setup.py
score: 1
has body: I'm trying to set sub-packages for a python project. Please refer to the structure below. The main setup.py will call "setup.py" in each sub packages. my_project ├── my_sub_package1 │ ├── foo2.py │ ├── foo.py │ └── setup.py ├── my_sub_package2 │ ├── bar2.py │ ├── bar.py │ └── setup.py └── setup.py [main] With this structure, in other projects, if the user only needs a sub_package, the user can choose to install "my_sub_package1" only, instead of installing the whole package (which can become bulky over time as number of packages increases). Does anyone know if this is the correct way of doing it? Thanks!
type: Question
upvote count: 1
favorite count: 0
tagged with: python-3.x
has title: Configure python sub-packages
type: UnansweredQuestion
tagged with: package
tagged with: python

http://stackoverflow.com/a/50717831
has body: I fiddled a little with the backend (changed it to redis:// and it worked), in tasks.py: app = Celery('tasks', backend='redis://', broker='redis://localhost') Looking a little further into the docs I found: The RPC result backend (rpc://) is special as it doesn’t actually store the states, but rather sends them as messages. This is an important difference as it means that a result can only be retrieved once, and only by the client that initiated the task. Two different processes can’t wait for the same result.
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50717604
answers question: http://stackoverflow.com/q/50717604

http://stackoverflow.com/q/50801480
tagged with: pandas
type: AnsweredQuestion
tagged with: python
score: 0
answer count: 2
tagged with: loops
possible better answer: http://stackoverflow.com/a/50801578
has answer: http://stackoverflow.com/a/50801578
has answer: http://stackoverflow.com/a/50801515
has title: Loop to remove the same letter of each row
accepted answer: http://stackoverflow.com/a/50801515
has body: In Python, if I want to add a letter in each row of a column, I use this: df = df.assign(Meses=[f'M{i}' for i in df.Meses]) Meses 1 M1 2 M2 3 M3 4 M4 5 M5 6 M6 7 M7 8 M8 9 M9 10 M10 11 M11 How can I do the opposite (remove the "m" of each row of a certain column)?
type: Question

http://stackoverflow.com/q/50831842
answer count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88668157
has comment: http://stackoverflow.com/comment/88668396
has comment: http://stackoverflow.com/comment/88668785
accepted answer: http://stackoverflow.com/a/50832162
type: AnsweredQuestion
has body: I have 2 inputs to type and I want to loop through them if the user would enter incorrect input. What I did is I set while True and then try and except and then continue. However in case of second input if the input is wrong then whole loop is repeated from the start - that is from the first input. I would like it to be repeated from the second input. The only thing that I can think of is to put break in the code after first correct input and then set another while True for the second input. What are better ways to do this? while True: try: a = int(input("Type positive integer: ")) except ValueError: print(" Enter a positive NUMBER!") continue if a &lt;= 0: print("Input can't be 0 or negative!") continue else: try: b = int(input("Type second positive integer: ")) except ValueError: print(" Enter a positive NUMBER!") continue if b &lt;= 0: print("Input can't be 0 or negative!") continue else: break
has comment: http://stackoverflow.com/comment/88667874
possible better answer: http://stackoverflow.com/a/50832177
has answer: http://stackoverflow.com/a/50832239
has answer: http://stackoverflow.com/a/50832703
has answer: http://stackoverflow.com/a/50832162
type: Question
has comment: http://stackoverflow.com/comment/88668262
has comment: http://stackoverflow.com/comment/88668046
score: 0
has title: Way to loop from the middle of the while loop
has answer: http://stackoverflow.com/a/50832177
tagged with: python

yarnpkg
tags question: http://stackoverflow.com/q/50731830
type: Tag
tag name: yarnpkg

http://stackoverflow.com/comment/88658812
type: Comment
comment on: http://stackoverflow.com/a/50826081
type: AnswerComment
has text: @yakobyd Which he does... look through his code. Specifically, his `game_loop` function
score: 0

http://stackoverflow.com/comment/88525229
comment on: http://stackoverflow.com/q/50736689
score: 0
type: Comment
type: QuestionComment
has text: @Shaumux its `TIME_ZONE = 'UTC'` I just need to convert to IST for my one specific datetime object not to the whole project wide setting

http://stackoverflow.com/comment/88572193
score: 0
comment on: http://stackoverflow.com/q/50782731
has text: Side note: you can more efficiently construct `a` by `three = np.arange(3.0); np.array([np.repeat(three, 3), np.tile(three, 3)]).T`.
type: Comment
type: QuestionComment

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/50796024
tags question: http://stackoverflow.com/q/50853136
tags question: http://stackoverflow.com/q/50760834
tags question: http://stackoverflow.com/q/50824326

http://stackoverflow.com/comment/88594982
comment on: http://stackoverflow.com/q/50792915
score: 0
type: Comment
type: QuestionComment
has text: I have changed the videowriter fourcc to 'MJPG' and now it works..

http://stackoverflow.com/a/50701884
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88413203
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50701772
has body: One way using itertools.cycle: from itertools import cycle lst = [0, 1, 2] res1 = cycle(lst + lst[-2:0:-1]) In [143]: [next(q.res1) for _ in range(10)] Out[143]: [0, 1, 2, 1, 0, 1, 2, 1, 0, 1] Thanks to @Chris_Rands for pointing out that the list comprehension can be replaced nicely with list(itertools.islice(res1, 10)).

http://stackoverflow.com/q/50719496
has title: Django custom user with tuple as username
upvote count: 1
answer count: 1
has body: I have a solid level on Django, but can't find how to solve this one properly : I created an API that will be used in multiple mobile projects. So I implemented an Application model that I pass when I log in. I also created a custom user model : class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) username = None email = models.EmailField('email address', unique=True) application = models.ForeignKey(Application, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: unique_together = ('email', 'application') I'm using djangorestframework-jwt. So I've an API call that needs an email, password and an Application (apikey as a string FYI) to get a token. Everything is working fine, except that in this configuration, I'm not able to create another user with the same email but a different Application. Because my EmailField is my USERNAME_FIELD. Is there any solution that would avoid me to rewrite everything ? The best thing I have in mind is to add a field (for example a CharField) that would be unique (for example the combinaison of user.id + apikey) that would be filled automatically on creation. But then when I use ./manage.py createsuperuser, django would ask me to fill the field manually. Not a big deal but if you have a better/proper way I'd be glad !
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50719704
tagged with: authentication
type: Question

http://stackoverflow.com/comment/88594019
has text: I just put an "if ascending:" before the if/else part and an "else:" after and copied the whole thing with if teilliste1[x] < teilliste2[y]. It worked in 2 separate functions but here, it messes up the sorting of the second list.
comment on: http://stackoverflow.com/q/50793753
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88669893
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50832814
has text: What is meant by "sorted list[names] of Revenue(sum of all months) generating mid" ? Can you be more explicit here by giving some example output you want? Actually, it would be better if you could simplify the problem and remove things specific to your variable names. It is not too hard to sort by the sum of all month's revenues, but *what* exactly do you want sorted? Like, what are the things in that sorted list?
type: Comment

http://stackoverflow.com/comment/88419166
has text: I would like to animate it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50704472

http://stackoverflow.com/comment/88547452
score: 0
type: AnswerComment
has text: `strip()` just removes any surrounding whitespace, why would it break it into words? You're thinking of `.split()`
type: Comment
comment on: http://stackoverflow.com/a/50769937

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/50767064
tags question: http://stackoverflow.com/q/50749937
tags question: http://stackoverflow.com/q/50755803
tags question: http://stackoverflow.com/q/50837766
type: Tag
tags question: http://stackoverflow.com/q/50844668
tags question: http://stackoverflow.com/q/50712197
tags question: http://stackoverflow.com/q/50742939
tags question: http://stackoverflow.com/q/50819445
tags question: http://stackoverflow.com/q/50711655
tags question: http://stackoverflow.com/q/50735871
tags question: http://stackoverflow.com/q/50849032
tags question: http://stackoverflow.com/q/50763695
tags question: http://stackoverflow.com/q/50721525
tags question: http://stackoverflow.com/q/50774222
tag name: xml
tags question: http://stackoverflow.com/q/50720246
tags question: http://stackoverflow.com/q/50709755
tags question: http://stackoverflow.com/q/50708574
tags question: http://stackoverflow.com/q/50852653
tags question: http://stackoverflow.com/q/50760564
tags question: http://stackoverflow.com/q/50747158
tags question: http://stackoverflow.com/q/50840170
tags question: http://stackoverflow.com/q/50744650
tags question: http://stackoverflow.com/q/50815485
tags question: http://stackoverflow.com/q/50827221
tags question: http://stackoverflow.com/q/50780510
tags question: http://stackoverflow.com/q/50852723
tags question: http://stackoverflow.com/q/50771453

http://stackoverflow.com/q/50805355
accepted answer: http://stackoverflow.com/a/50805410
has comment: http://stackoverflow.com/comment/88616746
tagged with: web-scraping
upvote count: 1
tagged with: python
tagged with: scrapy
type: AnsweredQuestion
has title: How to Scrape JSON Data Using Scrapy
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88617680
has body: I'm using scrapy and I'm trying to test my selector using scrapy shell but nothing is working. I'm trying to scrape the JSON data on this website. https://web.archive.org/web/20180604230058/https://api.simon.com/v1.2/tenant?mallId=231&amp;key=40A6F8C3-3678-410D-86A5-BAEE2804C8F2&amp;lw=true I've tried to scrape the data using the selector response.css("body &gt; pre::text").extract() However, this doesn't seem to be working. Not sure what's wrong... Ideally, I just want to get all the "Name: XXX" elements from the JSON data. So If you know how to select those specifically, that would be very helpful as well! Currently my code looks like this # -*- coding: utf-8 -*- import scrapy # needed to scrape import sys # need to import xlrd sys.path.extend("/Users/YoungFreeesh/anaconda3/lib/python3.6/site- packages/") # needed to import xlrd import xlrd # used to easily import xlsx file class AmazonbotSpider(scrapy.Spider): name = 'ArchiveSpider' allowed_domains = ['web.archive.org'] start_urls =['https://web.archive.org/web/20180604230058/https://api.simon.com/v1.2/tenant?mallId=231&amp;key=40A6F8C3-3678-410D-86A5-BAEE2804C8F2&amp;lw=true'] def parse(self, response): print(response.body)
type: Question
linked to: http://stackoverflow.com/q/52779161
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88616806
has answer: http://stackoverflow.com/a/50805410
tagged with: python-3.6
favorite count: 0

http://stackoverflow.com/a/50782784
has body: You can check length of values in column Date and if higher as 7 replace by NaN by where, last forward fill missing values by ffill (fillna with method ffill): df['Date'] = df['Date'].where(df['Date'].str.len() &gt; 7).ffill() #similar idea #df['Date'] = df['Date'].mask(df['Date'].str.len().isin([4,5])).ffill() print (df) Date Team 1 Team 2 Score1 Score2 0 1-Oct-17 1 NaN 2 NaN 1 1-Oct-17 Chicago Cubs Cincinnati Reds 1 3.0 2 1-Oct-17 Kansas City Royals Arizona Diamondbacks 2 14.0 3 1-Oct-17 St.Louis Cardinals Milwaukee Brewers 1 6.0 4 30-Sep-17 1 NaN 2 NaN 5 30-Sep-17 St.Louis Cardinals Milwaukee Brewers 7 6.0 6 30-Sep-17 Chicago Cubs Cincinnati Reds 9 0.0 7 30-Sep-17 San Francisco Giants San Diego Padres 2 3.0 8 30-Sep-17 Boston Red Sox Houston Astros 6 3.0 9 29-Sep-17 1 NaN 2 NaN 10 29-Sep-17 Chicago Cubs Cincinnati Reds 5 4.0 11 29-Sep-17 New York Yankees Toronto Blue Jays 4 0.0 12 29-Sep-17 Kansas City Royals Detroit Tigers 1 4.0 13 29-Sep-17 Chicago White Sox Los Angeles Angels 5 4.0 Another idea is convert values to datetimes and compare 0:00 times: from datetime import time df['Date'] = pd.to_datetime(df['Date'] ) df['Date'] = df['Date'].where(df['Date'].dt.time == time(0,0)).ffill() print (df) Date Team 1 Team 2 Score1 Score2 0 2017-10-01 1 NaN 2 NaN 1 2017-10-01 Chicago Cubs Cincinnati Reds 1 3.0 2 2017-10-01 Kansas City Royals Arizona Diamondbacks 2 14.0 3 2017-10-01 St.Louis Cardinals Milwaukee Brewers 1 6.0 4 2017-09-30 1 NaN 2 NaN 5 2017-09-30 St.Louis Cardinals Milwaukee Brewers 7 6.0 6 2017-09-30 Chicago Cubs Cincinnati Reds 9 0.0 7 2017-09-30 San Francisco Giants San Diego Padres 2 3.0 8 2017-09-30 Boston Red Sox Houston Astros 6 3.0 9 2017-09-29 1 NaN 2 NaN 10 2017-09-29 Chicago Cubs Cincinnati Reds 5 4.0 11 2017-09-29 New York Yankees Toronto Blue Jays 4 0.0 12 2017-09-29 Kansas City Royals Detroit Tigers 1 4.0 13 2017-09-29 Chicago White Sox Los Angeles Angels 5 4.0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50782766
type: Answer
accepted answer of: http://stackoverflow.com/q/50782766
downvote count: 0
score: 1

http://stackoverflow.com/comment/88748204
has text: Please don't ask such questions, we are not here to write code for you, better hire a freelance developer on Upwork. Or Let us know at which line of code you got stuck.
score: 0
comment on: http://stackoverflow.com/q/50842356
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50794559
type: Answer
answers question: http://stackoverflow.com/q/50701772
has body: I also found that the index can also be calculated using index = (time-1)%(2*length-2)
score: 0

http://stackoverflow.com/comment/88521353
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50756758
has text: Your output has `count` / `sum` rows *and* `count` / `sum` columns. Are you sure this is what you want?
score: 0

http://stackoverflow.com/a/50836786
downvote count: 0
has body: pd.read_csv is a function. You call a function in Python by using parenthesis. You should use pd.read_csv(CSVFILE) instead of pd.read_csv[CSVFILE].
has comment: http://stackoverflow.com/comment/88678366
has comment: http://stackoverflow.com/comment/88677616
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88677536
has comment: http://stackoverflow.com/comment/88677432
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50836608
answers question: http://stackoverflow.com/q/50836608

http://stackoverflow.com/comment/88693961
comment on: http://stackoverflow.com/a/50845148
score: 0
type: AnswerComment
type: Comment
has text: Yeah I'm getting the same error. What do you think is causing it? Is there anything I can do on the client side?

http://stackoverflow.com/q/50830592
accepted answer: http://stackoverflow.com/a/50831231
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have a dataframe with 5 columns, each column containing lists of variable lengths. This is what a row in my dataframe looks like: A B 1 [aircrafts, they, agreement, airplane] [are, built, made, built] Now I would like to 'unpack' or 'unstack' these lists so that each cell only contains one value (one word). In the unpacking process, the words in cells from one column should be combined pairwise with the corresponding value in the next column. The result would then be: A B 1 aircrafts are 2 they built 3 agreement made 4 airplane built For reference, my full dataframe looks as follows: obj rel1 \ 0 [Boeing] [sells] 1 [aircrafts, they, agreement, airplane] [are, built, made, built] 2 [exception, these] [are, are] 3 [sales, contract] [regulated, consist] 4 [contract] [stipulates] 5 [acquisition] [has] 6 [contract] [managed] 7 [employee] [act] 8 [salesperson, Boeing] [change, ensures] 9 [airlines, airlines] [related, have] 10 [Boeing] [keep] dep1 rel2 \ 0 [aircrafts] [to] 1 [] [on, with] 2 [] [of, of, for] 3 [] [by, of, with, of, of] 4 [elements] [across, as] 5 [details] [of, as, of, for] 6 [] [by] 7 [] [as, for] 8 [] [Given, of, over, for] 9 [company] [to, for] 10 [track, aircrafts] [of, between, to, of] dep2 0 [companies] 1 [demand, customer] 2 [airplanes, scope, case] 3 [means, contracts, companies, acquisitions, ai... 4 [acquisitions, conditions] 5 [airplane, model, airplane, options] 6 [salesperson] 7 [salesperson, contracts] 8 [term, contracts, time, client] 9 [other, example] 10 [relationships, companies, airlines, buyer] How can I perform the 'unpacking' and rearranging operations in python? It would be great if these operations could be performed on the dataframe itself. If this proves to be difficult or impossible, is there a way I could rearrange the data in the lists before combining them into a dataframe? Thank you very much for any help or advice.
favorite count: 0
has comment: http://stackoverflow.com/comment/88666029
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/50831231
type: Question
has title: How to 'unstack' all lists in columns of dataframe and combine results pairwise?
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88665443
has comment: http://stackoverflow.com/comment/88666450

http://stackoverflow.com/q/50702986
answer count: 2
upvote count: 9
has comment: http://stackoverflow.com/comment/116789377
has title: pandas rolling() function with monthly offset
downvote count: 0
has body: I'm trying to use the rolling() function on a pandas data frame with monthly data. However, I dropped some NaN values, so now there are some gaps in my time series. Therefore, the basic window parameter gives a misleading answer since it just looks at the previous observation: import pandas as pd import numpy as np import random dft = pd.DataFrame(np.random.randint(0,10,size=len(dt)),index=dt) dft.columns = ['value'] dft['value'] = np.where(dft['value'] &lt; 3,np.nan,dft['value']) dft = dft.dropna() dft['basic'] = dft['value'].rolling(2).sum() See, for example the 2017-08-31 entry, which sums 3.0 and 9.0, but the previous entry is 2017-03-31. In [57]: dft.tail() Out[57]: value basic 2017-02-28 8.0 12.0 2017-03-31 3.0 11.0 2017-08-31 9.0 12.0 2017-10-31 7.0 16.0 2017-11-30 7.0 14.0 The natural solution (I thought) is to use a '2M' offset, but it gives an error: In [58]: dft['basic2M'] = dft['value'].rolling('2M').sum() ...&lt;output omitted&gt;... ValueError: &lt;2 * MonthEnds&gt; is a non-fixed frequency If I move the Daily offset, I can get it to work, but this seems like an odd workaround: In [59]: dft['basic32D'] = dft['value'].rolling('32D', min_periods=2).sum() In [61]: dft.tail() Out[61]: value basic basic32D 2017-02-28 8.0 12.0 12.0 2017-03-31 3.0 11.0 11.0 2017-08-31 9.0 12.0 NaN 2017-10-31 7.0 16.0 NaN 2017-11-30 7.0 14.0 14.0 I also tried converting to a PeriodIndex: dfp = dft.to_period(freq='M') but this gives the same error: dfp['basic2M'] = dfp['value'].rolling('2M').sum() and this is very unexpected: dfp['basic32Dp'] = dfp['value'].rolling('32D', min_periods=2).sum() In [68]: dfp Out[68]: value basic basic32D basic32Dp 2016-02 9.0 NaN NaN NaN 2016-03 3.0 12.0 12.0 12.0 2016-04 7.0 10.0 10.0 19.0 2016-05 3.0 10.0 10.0 22.0 2016-06 4.0 7.0 7.0 26.0 2016-07 7.0 11.0 11.0 33.0 2016-08 3.0 10.0 10.0 36.0 2016-09 9.0 12.0 12.0 45.0 2016-11 5.0 14.0 NaN 50.0 2017-01 4.0 9.0 NaN 54.0 2017-02 8.0 12.0 12.0 62.0 2017-03 3.0 11.0 11.0 65.0 2017-08 9.0 12.0 NaN 74…
has answer: http://stackoverflow.com/a/66057187
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/88415707
has comment: http://stackoverflow.com/comment/88415825
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70780955
tagged with: rolling-computation
tagged with: python
tagged with: window-functions
score: 9
type: Question

http://stackoverflow.com/comment/88420144
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50705362
has text: According to [the docs](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc32300.1600/doc/html/san1390612441960.html), `-6` means “Miscellaneous user error”. Not very helpful, but that’s all anyone can tell you without debugging the stored procedure and how you’re calling it, which is impossible since you haven’t given that to us.

http://stackoverflow.com/comment/88436964
has text: One thing to know sir: they both work identically `following-sibling` and `following` in this case. Can you give me a clue why?
type: Comment
comment on: http://stackoverflow.com/a/50714099
type: AnswerComment
score: 0

http://stackoverflow.com/q/50745179
favorite count: 0
duplicate of: http://stackoverflow.com/q/53549960
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: How can I change the color of margin ticks of a matplotlib 3d plot?
downvote count: 1
has body: See the following code: from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt #creates a spiral N = 100 t = np.linspace(0,20,N) z = 0.5*t phi = 2*np.pi/10*t x = np.cos(phi) y = np.sin(phi) fig = plt.figure(facecolor="black") ax = fig.gca(projection='3d') plt.gca().patch.set_facecolor("black") ax.tick_params(axis='x',colors='white') ax.tick_params(axis='y',colors='white') ax.tick_params(axis='z',colors='white') ax.w_xaxis.line.set_color("white") ax.w_yaxis.line.set_color("white") ax.w_zaxis.line.set_color("white") ax.plot(x, y, z, c='blue') plt.show() It creates the following plot: How can I change the color of the ticks that I have surrounded by red? (all at once)
score: 1
tagged with: matplotlib
type: Question
tagged with: 3d
linked to: http://stackoverflow.com/q/53549960

http://stackoverflow.com/a/63841538
downvote count: 0
has body: This is what you can do .gitlab-ci.yml stages: - Lint Lint: stage: Lint allow_failure: true script: - chmod +x lint.sh - ./lint.sh lint.sh #! /bin/sh pip install pycodestyle current_branch="$CI_BUILD_REF_NAME" echo $current_branch all_changed_files=$(git diff --name-only origin/master origin/$current_branch) echo "Checking changes!" for each_file in $all_changed_files do # Checks each newly added file change with pycodestyle pycodestyle $each_file error_count=$(pycodestyle $each_file --count | wc -l) if [ $error_count -ge 1 ]; then exit 1 fi if [ $error_count -eq 0 ]; then exit 0 fi done echo "Completed checking"
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50741264

http://stackoverflow.com/q/50800056
answer count: 1
downvote count: 0
has title: Pytorch in-place concatenation and conversion to tensor from numpy
has body: Suppose I have a list of tensors of the same size which could be concatenated along a dimension, say 0. Do any of the commands torch.cat or torch.stack or any numpy commands do the concatenation in-place? Also, if I want to convert a numpy ndarray to tensor. If I do the following, are two copies existing in the memory at any given time? I am dealing with a massive dataset so big only one copy of it can exist in the memory at any given time. # initially data is a huge ndarray data = torch.Tensor(data)
has comment: http://stackoverflow.com/comment/88626331
tagged with: python
favorite count: 0
tagged with: pytorch
upvote count: 2
has comment: http://stackoverflow.com/comment/88611262
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50803814
has comment: http://stackoverflow.com/comment/88607545
score: 2
type: Question
tagged with: numpy

http://stackoverflow.com/comment/88472640
comment on: http://stackoverflow.com/a/50732262
type: Comment
score: 0
has text: Thanks @coldspeed How can i directly convert this series to dataframe as shown in the table in the post? thank you so much for your advice.
type: AnswerComment

http://stackoverflow.com/comment/115711320
type: QuestionComment
score: 0
has text: I am having the same issue. If I figure it out Ill post my solution.
comment on: http://stackoverflow.com/q/50786696
type: Comment

http://stackoverflow.com/comment/88473467
score: 0
type: Comment
has text: Hmm when I do this, the context_object_name doesn't display any information. For example, when I do user_profile.username to display the profile's username, it shows up as blank
comment on: http://stackoverflow.com/a/50732792
type: AnswerComment

http://stackoverflow.com/comment/88526526
has text: Opps sorry my bad. I have updated the question description. I was working with other files so i forgot to edit the script.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50759525

http://stackoverflow.com/a/50846923
answers question: http://stackoverflow.com/q/50767910
upvote count: 2
downvote count: 0
has body: It's not the most elegant (it requires you to navigate between VBA and Python), but you can use the win32com library to tap into the MS Word functionality. This of course requires a Windows machine with MS Office installed. import win32com.client as win32 msword = win32.gencache.EnsureDispatch('Word.Application') doc = msword.Documents.Add doc.Sections(1).Footers(1).Range.Text = r'Text to be included' doc.Sections(1).Footers(1).PageNumbers.Add()
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88729686
has comment: http://stackoverflow.com/comment/88698633

http://stackoverflow.com/a/50783910
has comment: http://stackoverflow.com/comment/88578391
type: Answer
has comment: http://stackoverflow.com/comment/88574743
answers question: http://stackoverflow.com/q/50783778
score: 0
has body: Use cProfile, it'll display everything your function is doing(calling, etc). And, compare this: import cProfile cProfile.run('fibonacci_power(150)') #compare it to cProfile.run('fibonacci_mem(150)') To this: import cProfile cProfile.run('fibonacci_power(15000)') #compare it to cProfile.run('fibonacci_mem(15000)') As you can see, NumPy uses so many things to do task because matrix method is more complex. Your code is simpler, it just use few built-in things. NumPy is used to do more complex things, and it would be slower compared to little function that you wrote if 'n' is small number. Just see cProfile explanation, it will be clearer. Of course, for big numbers and long run, NumPy is faster.

http://stackoverflow.com/comment/88612890
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50803356
has text: please indent and format your code
type: Comment

http://stackoverflow.com/comment/88527692
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50758779
has text: i have suggested him/her to use pandas because it's easier for a beginner.
type: Comment

http://stackoverflow.com/q/50708380
has answer: http://stackoverflow.com/a/50708720
tagged with: python
linked to: http://stackoverflow.com/q/3535881
has answer: http://stackoverflow.com/a/50709025
has comment: http://stackoverflow.com/comment/88426699
upvote count: 1
tagged with: logging
has comment: http://stackoverflow.com/comment/88427077
has comment: http://stackoverflow.com/comment/88426302
has comment: http://stackoverflow.com/comment/88426212
linked to: http://stackoverflow.com/q/36616739
has body: I was wondering if there was away to redirect both the input and output of a python script to a file so that they were interlaced. Essentially say I have the following code: x = 1 print("hello, world") print(x) x = 2 print(x) def myfun(Val): return(Val+1) myfun(7) I would be looking for the following to be displayed in an output file x = 1 print("hello, world") "hello, world" print(x) 1 x = 2 print(x) 2 def myfun(Val): return(Val+1) myfun(7) 8 Things that I have already looked at include: simple file redirecting python myfile.py &gt; output.log however this doesn't capture the input The trace module python -m trace myfile.py however this displays way way way too much information and bloats the runtime. I couldn't find any obvious way of limiting this to just the top level code (not every module and function call) Jupyter notebooks - I appreciate that these clearly display input and output however I really want to keep this to command line executable scripts with basic ascii python files. Ideally I was hoping to find either some sort of bash wizardry with re-directs, a python command line option or a common python module that is able to handle this, but so far no luck :( EDIT: As a further clarifying example essentially I am trying to re-create the following functionality from R. Say we have the R program myprog.R as: myfun &lt;- function(x){ x + 1 } y &lt;- myfun(7) print("hello,world!") print(y) y + 1 Then running from the command line R CMD BATCH myprog.R produces the file myprog.Rout which looks like myfun &lt;- function(x){ x + 1 } y &lt;- myfun(7) print("hello,world!") [1] "hello,world!" print(y) [1] 8 y + 1 [1] 9
has comment: http://stackoverflow.com/comment/88426161
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3906232
answer count: 4
has answer: http://stackoverflow.com/a/50708764
downvote count: 0
has answer: http://stackoverflow.com/a/50708972
has title: How to display python input code along side output
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/88534371
comment on: http://stackoverflow.com/a/50760514
type: AnswerComment
score: 0
has text: Correct. But it was an exercise I was given to complete whereby the days had to be represented by the numbers given in the list and return the 2n"th day using the allocated number. Believe it or not I passed the exercise with the code I cobbled together but I was aware it was cumbersome and kept thinking there must be a more elegant and flexible way to accomplish the goal. It wasn't a great exercise but it did get me thinking about iterating over all items in a list from a chosen index which meant i learnt something useful anyway.
type: Comment

http://stackoverflow.com/q/50779426
type: Question
upvote count: 2
tagged with: django
answer count: 1
has body: I'm trying to add or remove a row into DB, using a button click that redirects back to the same page,, here are my files views.py def favorite_item (request, pk): favitem = get_object_or_404(Item, pk=pk) userfav = Favorite.objects.filter(user=request.user) for items in userfav: if items.item == favitem: items.delete() else: items = Favorite(item=favitem, user=request.user) items .save() return redirect('') urls.py path('&lt;int:pk&gt;/favorite_item/', views.favorite_item, name='favorite_item'), html &lt;a href="{% url 'favorite_item' dress.id %}"&gt; &lt;img src="{% static 'img/gold_star.png' %}"&gt;&lt;/a&gt; but whenever I click it I get the error : error Reverse for '' not found. '' is not a valid view function or pattern name. Entire Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/3/favorite_item/ Django Version: 2.0.5 Python Version: 3.6.5 Installed Applications: ['django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fostania_web_app.apps.FostaniaWebAppConfig'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\…
has title: Reverse for '' not found. '' is not a valid view function or pattern name
has answer: http://stackoverflow.com/a/50779575
has comment: http://stackoverflow.com/comment/88565752
score: 2
downvote count: 0
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88565856
favorite count: 0
accepted answer: http://stackoverflow.com/a/50779575

http://stackoverflow.com/comment/88454344
has text: (And you're right, you can do an ARP cache poisoning attack with a request or a reply, both should work.)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50710239
type: AnswerComment

http://stackoverflow.com/comment/88441036
score: 0
type: Comment
has text: This has worked really well- I've made one change to my original data in that I resampled from second-to-second to minute-by-minute so that peaks are much more noticeable. As I don't really need the data to be second by second, it makes life much easier!
comment on: http://stackoverflow.com/a/50703940
type: AnswerComment

http://stackoverflow.com/comment/88492039
has text: @Carcigenicate Hmmm... yes you're right it doesn't work now. I don't know why it seemed to work. Thanks anyway.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50741881
score: 0

http://stackoverflow.com/q/50744693
has comment: http://stackoverflow.com/comment/88574694
tagged with: mapping
answer count: 0
has body: In ruby, the array function has at least two methods for map. The first map, creates a copy of the array, with the function operated on. The original array is unchanged. The second, map!, changes the array itself, and does not create a copy. This can be beneficial if one has a huge array. Is that possible in Python 3.4? Thanks.
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88497094
tagged with: python
has comment: http://stackoverflow.com/comment/88497386
has comment: http://stackoverflow.com/comment/88498373
has comment: http://stackoverflow.com/comment/88497398
has title: destructive map operator for python 3.4
type: Question
has comment: http://stackoverflow.com/comment/88497090
has comment: http://stackoverflow.com/comment/88497520
has comment: http://stackoverflow.com/comment/88497135
tagged with: operators
tagged with: python-3.x

http://stackoverflow.com/q/50841201
has body: New to Swift and Mac OS development I was following the tutorial here: https://www.raywenderlich.com/165853/menus-popovers-menu-bar-apps-macos I want a simple menu app that will let me launch certain python scripts. Here is the code I am using to launch the python script @objc func launchPythonScript(_ sender: Any?) { let task = Process() task.launchPath = "/usr/local/bin/python" task.arguments = ["-c", "\"print 'hello world'\""] task.launch() task.waitUntilExit() } for some reason when I click the button to launch it doesn't error out but goes into a debug mode where I see assembly statements and the error: Thread 1: EXC_SOFTWARE (code=131072, subcode=0x0) Any ideas on how I can solve this? I must be doing something simple wrong.
has comment: http://stackoverflow.com/comment/88693701
has comment: http://stackoverflow.com/comment/88693742
score: 0
has title: Swift - Mac OS - Trying to launch a Python script from a menu app results in failure
tagged with: macos
has comment: http://stackoverflow.com/comment/88686084
has comment: http://stackoverflow.com/comment/88686132
type: UnansweredQuestion
tagged with: xcode
tagged with: python
tagged with: swift
answer count: 0
type: Question

http://stackoverflow.com/comment/88829177
score: 0
has text: Yes... that sounds to be an option... Will try and get back.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50861147

http://stackoverflow.com/comment/88502670
has text: Exactly what I needed. Thank you.
comment on: http://stackoverflow.com/q/50747459
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50757497
has answer: http://stackoverflow.com/a/50758540
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/71666401
has answer: http://stackoverflow.com/a/62139106
has answer: http://stackoverflow.com/a/68442767
tagged with: async-await
type: Question
has answer: http://stackoverflow.com/a/75041852
has answer: http://stackoverflow.com/a/65299937
linked to: http://stackoverflow.com/q/73361664
has body: I've read many examples, blog posts, questions/answers about asyncio / async / await in Python 3.5+, many were complex, the simplest I found was probably this one. Still it uses ensure_future, and for learning purposes about asynchronous programming in Python, I would like to see an even more minimal example, and what are the minimal tools necessary to do a basic async / await example. Question: is it possible to give a simple example showing how async / await works, by using only these two keywords + code to run the async loop + other Python code but no other asyncio functions? Example: something like this: import asyncio async def async_foo(): print("async_foo started") await asyncio.sleep(5) print("async_foo done") async def main(): asyncio.ensure_future(async_foo()) # fire and forget async_foo() print('Do some actions 1') await asyncio.sleep(5) print('Do some actions 2') loop = asyncio.get_event_loop() loop.run_until_complete(main()) but without ensure_future, and still demonstrates how await / async works.
accepted answer: http://stackoverflow.com/a/53420574
has answer: http://stackoverflow.com/a/72336804
has answer: http://stackoverflow.com/a/66888341
tagged with: python-asyncio
has title: Simplest async/await example possible in Python
downvote count: 0
answer count: 10
tagged with: asynchronous
favorite count: 0
linked to: http://stackoverflow.com/q/37278647
tagged with: python-3.x
score: 290
linked to: http://stackoverflow.com/q/33357233
has answer: http://stackoverflow.com/a/53420574
upvote count: 290
has answer: http://stackoverflow.com/a/64508472
tagged with: python
possible better answer: http://stackoverflow.com/a/50758540

http://stackoverflow.com/comment/88418890
has text: To associate strings with values, use a dictionary.
score: 1
comment on: http://stackoverflow.com/q/50704710
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50785206
answers question: http://stackoverflow.com/q/50785174
downvote count: 0
has body: Try the following using zip: message = [1,2,3,4] people = ['A','B','C','D'] for x,y in zip(message,people): print(x,y) #Prints 1 A 2 B 3 C 4 D You can run Live
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/50808134
has answer: http://stackoverflow.com/a/50810041
favorite count: 0
has answer: http://stackoverflow.com/a/50808290
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/50808290
answer count: 2
has body: I have a tensor input of size BxHxWx3 and another tensor params of size Bx3. here is B is the batch size. I want to params into a tensor of size BxHxWx3? So that I can multiply the two tensors. Any suggestions on how should I go about this? (At a high level, what i want to do is multiply each pixel in a set of images by a value defined for each channel)
downvote count: 0
has title: expanding dimensions and replicating data in tensorflow
possible better answer: http://stackoverflow.com/a/50810041

http://stackoverflow.com/comment/88613629
score: 0
comment on: http://stackoverflow.com/q/50803535
has text: You can also rename the column before merging, so that you don't wind up with both key columns after the merge.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88616548
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50804635
has text: hey it's giving me an error: '_csv.reader' object has no attribute 'fieldnames'

http://stackoverflow.com/q/50853561
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50853619
type: Question
tagged with: testing
tagged with: series
has title: What is the best way to check correct dtypes in a pandas dataframe as part of testing?
answer count: 2
tagged with: pandas
tagged with: types
accepted answer: http://stackoverflow.com/a/50853619
downvote count: 0
has body: Before pre-processing and training a model on some data, I want to check that each feature (each column) of a dataframe is of the correct data type. i.e. if a dataframe has columns col1, col2, col3, they should have types int, float, string respectively as I have defined them (col1 can't be of type string, the order matters). What is the best way to do this if The columns have various types - int, float, timestamp, string There are too many columns (>500) to manually write out / label each column data type Something like types = df.dtypes # returns a pandas series if types != correct_types: raise TypeError("Some of the columns do not have the correct type") Where correct_types are the known data types of each column - these would need to be in the same order as types to ensure each column type is correctly matched. It would also be good to know which column is throwing the error (so maybe a for loop over the columns is more appropriate?) Is there any way to achieve this, and if so what is the best way to achieve this? Maybe I am looking at the issue the wrong way - more generally, how do I ensure that the columns of df are of the correct data type as I have defined them?
favorite count: 0
possible better answer: http://stackoverflow.com/a/78505711
tagged with: python
has answer: http://stackoverflow.com/a/78505711
has comment: http://stackoverflow.com/comment/88709832

http://stackoverflow.com/q/50828939
has body: I have a Flask application that I am using with SQLAlchemy. I don't want to use the Flask-SQLAlchemy extension. If I use a "real" database for testing and just set up environment variables that point to the test instance of the database, everything works well. However, I've run into a problem if I want to point to an in-memory sqlite database for testing. In that case I can set up the data in my test, but when I use the test_client to execute a given route in my application, it can't find my database tables on the "server side" as it were - i.e. in the hello.py code shown further down. There must be a way to configure the test_client for this to work, but I can't seem to quite figure out how to do it. Here are the snippets of code that may be relevant (db.py): import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker engine = create_engine(os.environ['SQLALCHEMY_URL']) Session = scoped_session(sessionmaker(bind=engine)) Here I am setting up the scoped_session so that my database access will be thread-local. The code that bootstraps my application (__init__.py): from flask import Flask from .db import Session from .hello import hello_blueprint app = Flask(__name__) app.register_blueprint(hello_blueprint) @app.teardown_appcontext def cleanup(resp_or_exc): Session.remove() Here I'm setting up my app and registering the cleanup callback each time Flask pops the application context. An example route in a blueprint (hello.py): import json from flask import Blueprint from .db import Session from .models import Message hello_blueprint = Blueprint('hello', __name__) @hello_blueprint.route('/messages') def messages(): values = Session.query(Message).all() results = [] for value in values: results.append({ 'message': value.message }) return (json.dumps(results), 200, { 'content_type': 'application/json' }) Here I'm using the scoped session to get some data from the database. The definition of my Message mod…
tagged with: sqlite
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88686127
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50843587
has comment: http://stackoverflow.com/comment/88698824
has title: How to "inject" in-memory SQLAlchemy sqlite3 database into Flask test_client?
score: 2
has comment: http://stackoverflow.com/comment/88670696
tagged with: sqlalchemy
type: Question
tagged with: flask

http://stackoverflow.com/comment/105986872
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/59932470
has text: I had the same error, you can use this code above which worked for me very well or you can use pd.cut which is also an effective one. Thank you
score: 0

http://stackoverflow.com/a/50762395
type: Answer
downvote count: 0
has body: The method align returns a tuple according to the documentation: Returns: (left, right) : (DataFrame, type of other) Aligned objects (left, right) is a tuple
score: 1
has comment: http://stackoverflow.com/comment/88532656
accepted answer of: http://stackoverflow.com/q/50762252
answers question: http://stackoverflow.com/q/50762252
upvote count: 1
type: AcceptedAnswer

django-admin-filters
tags question: http://stackoverflow.com/q/50799470
tag name: django-admin-filters
type: Tag

http://stackoverflow.com/q/50778858
tagged with: python
has comment: http://stackoverflow.com/comment/88565930
answer count: 0
type: UnansweredQuestion
has body: Not sure if my python question is titled correctly, but I get a NameError: global name 'someOtherClass' is not defined error when I try to call a method that uses a module imported through the __init__ function of my class. class myClass def __init__(self): if is_64b: exit() else: import someOtherClass def myMethod(self, param1, param2, param3): return someOtherClass.someMethod(param1, param2, param3) from myFolder.myClassFileName import myClass myObj = myClass() value = myObj.myMethod(p1, p2, p3)
type: Question
linked to: http://stackoverflow.com/q/3913217
has comment: http://stackoverflow.com/comment/88565921
has comment: http://stackoverflow.com/comment/88564626
tagged with: import
tagged with: class
duplicate of: http://stackoverflow.com/q/3913217
score: 0
has comment: http://stackoverflow.com/comment/88565946
has title: How to make import in class gobal in python?

http://stackoverflow.com/comment/88514272
type: Comment
has text: @abarnert great suggestion! Hopefully Bijoy will integrate it. Also I agree with you about [].
comment on: http://stackoverflow.com/a/50753082
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88438284
score: 1
comment on: http://stackoverflow.com/a/50714698
has text: `eval` itself isn't buggy, but it can introduce a huge security risk into your code. If you aren't worried about this code being exposed to malicious inputs, go ahead and use it. This is pretty hacky though.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88589049
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50791020
type: Comment
has text: Your second code block recurses "forever" (until it hits the interpreter's recursion limit and an exception is raised), because when the `wrapper` function calls `test_function` by name, it's actually calling itself. The original `test_function` gets replaced by the wrapper, thanks to the decorator syntax. If you want to access the original function, you should use the reference that was passed as an argument to the decorator (i.e. `func`). It's also worth noting that you don't *need* to use a wrapper function in a decorator. You can return the same function you were passed if you want.

http://stackoverflow.com/comment/88711328
comment on: http://stackoverflow.com/q/50854146
type: Comment
type: QuestionComment
score: 0
has text: I'm sorry my bad

http://stackoverflow.com/a/66195998
downvote count: 0
type: Answer
has body: You can also use the following: temp_rdd = sc.parallelize(schema) temp_rdd.coalesce(1).saveAsPickleFile("s3a://path/to/destination_schema.pickle")
answers question: http://stackoverflow.com/q/50816767
upvote count: 1
score: 1

http://stackoverflow.com/q/50825936
linked to: http://stackoverflow.com/q/42497340
tagged with: python
has answer: http://stackoverflow.com/a/59824816
has title: Confusion matrix on images in CNN keras
possible better answer: http://stackoverflow.com/a/50826215
type: AnsweredQuestion
tagged with: conv-neural-network
upvote count: 14
has comment: http://stackoverflow.com/comment/88694727
has answer: http://stackoverflow.com/a/50826215
type: Question
has comment: http://stackoverflow.com/comment/88657010
tagged with: keras
has answer: http://stackoverflow.com/a/50843465
answer count: 3
score: 14
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50843465
has body: I have trained my model(multiclass classification) of CNN using keras and now I want to evaluate the model on my test set of images. What are the possible options for evaluating my model apart from the accuracy, precision and recall? I know how to get the precision and recall from a custom script. But I cannot find a way to get the confusion matrix for my 12 classes of images. Scikit-learn shows a way, but not for images. I am using model.fit_generator () Is there a way to create confusion matrix for all my classes or finding classification confidence on my classes? I am using Google Colab, though I can download the model and run it locally. Any help would be appreciated. Code: train_data_path = 'dataset_cfps/train' validation_data_path = 'dataset_cfps/validation' #Parametres img_width, img_height = 224, 224 vggface = VGGFace(model='resnet50', include_top=False, input_shape=(img_width, img_height, 3)) #vgg_model = VGGFace(include_top=False, input_shape=(224, 224, 3)) last_layer = vggface.get_layer('avg_pool').output x = Flatten(name='flatten')(last_layer) xx = Dense(256, activation = 'sigmoid')(x) x1 = BatchNormalization()(xx) x2 = Dropout(0.3)(x1) y = Dense(256, activation = 'sigmoid')(x2) yy = BatchNormalization()(y) y1 = Dropout(0.6)(yy) x3 = Dense(12, activation='sigmoid', name='classifier')(y1) custom_vgg_model = Model(vggface.input, x3) # Create the model model = models.Sequential() # Add the convolutional base model model.add(custom_vgg_model) model.summary() #model = load_model('facenet_resnet_lr3_SGD_sameas1.h5') def recall(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return pre…
has comment: http://stackoverflow.com/comment/88657494
favorite count: 0

http://stackoverflow.com/a/50754475
upvote count: 8
has comment: http://stackoverflow.com/comment/88613378
has body: Since I don't have the data, I generated it using following script. I have assumed your data has 3 columns - Date, ExtendedPrice, CompanyNo. I have generated first a random data of 10K rows and then summarized it at CompanyNo, day, month, year level. import pandas as pd import random CopmanyList = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15'] df = pd.DataFrame({'base' : ["2017-01-01" for t in range(10000)], 'Date' : [random.randint(0, 1035) for t in range(10000)], 'ExtendedPrice' : [random.random() for t in range(10000)], 'CompanyNo' : [CopmanyList[random.randint(0, 15)] for t in range(10000)]}) df['base'] = pd.to_datetime(df['base']) df["Date2"] = df.apply(lambda x: x["base"] + timedelta(days=x['Date']), axis=1) df.drop(['base', 'Date'], axis=1, inplace=True) df.set_index('Date2', inplace=True) df['month'] = df.index.month df['year'] = df.index.year df['day'] = df.index.day source1=df.groupby(['year','month','day', 'CompanyNo'], as_index = False)['ExtendedPrice'].sum() source =source1[source1['year']== dt.now().year] sourcex = source[source['month'] ==1] sourcex = sourcex[sourcex['CompanyNo'].isin(['01'])] sourcex.sort_values(by='day', inplace=True) Now, what you want to accomplish is that given a day and set of company names, you need to publish a bar chart of some type of aggregation of ExtendedPrice, i.e. say there are 2 rows for company '01' and '02' (which are selected), and for month 2 (that is also selected by a slider) for current year, the ExtendedPrice value for these two is say 100, and 200. In case we want to show a sum, you need to show 300 in barchart. This summary, you need to calculate dynamically. There are two ways to accomplish it. 1. Bokeh Callbacks This will use native python functions, but you need to run it with bokeh serve , e.g bokeh serve --show &lt;filename.py&gt;. See the code below, a native python function compsel is filtering pandas dataframe and summarizing it and replacing the chart…
answers question: http://stackoverflow.com/q/50747006
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/50747006
type: AcceptedAnswer
downvote count: 0

object-detection-api
tags question: http://stackoverflow.com/q/50807254
tag name: object-detection-api
type: Tag

http://stackoverflow.com/comment/88565554
comment on: http://stackoverflow.com/a/50778544
score: 0
type: AnswerComment
has text: @littlejiver Yes, that probably does :) Please see my recent edit.
type: Comment

http://stackoverflow.com/q/50834924
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88674396
tagged with: python
has body: I've been having some issues with this piece of code, and I cannot figure out why. When I run: try: r = requests.get('https://httpbin.org/get', timeout=10, headers={'Cache-Control': 'nocache', 'Pragma': 'nocache'}) r.raise_for_status() return r.json() except (requests.exceptions.RequestException, ValueError): return False NOTE: Host changed for privacy, the actual service is way more erratic/buggy. I will occasionally get this error: requests.exceptions.ReadTimeout: HTTPConnectionPool(host='https://httpbin.org/get', port=80): Read timed out. (read timeout=10) I can't understand what has gone wrong; I seem to be properly catching requests.exceptions.RequestException which is a superset/parent of requests.exceptions.ReadTimeout.. EDIT: It seems updating requests has fixed it.
has answer: http://stackoverflow.com/a/50835280
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88674656
tagged with: python-requests
has title: requests.exceptions.ReadTImeout not caught
type: Question
score: 5
upvote count: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/50835280

http://stackoverflow.com/comment/88607865
score: 0
has text: Looks like you might need to show what the DAG looks like `/var/lib/airflow/dags/dag_file.py` - are you able to redact any confidential information and post the contents of that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50790965

http://stackoverflow.com/comment/88534857
comment on: http://stackoverflow.com/a/50762573
type: Comment
score: 0
type: AnswerComment
has text: Does it work for `idx = np.array([[1],[1]])` ?

http://stackoverflow.com/a/54536499
downvote count: 0
has body: I managed to make it work with the mouse library. Instead of using mouse.move(x,y,absolute,duration) I used mouse._os_mouse.move_to(x,y) and mouse._os_mouse.move_relative(x,y). Take into account that if you want a smooth effect you'll have to implement it yourself using something like time.sleep(s).
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50712139
score: 2

http://stackoverflow.com/a/50726427
answers question: http://stackoverflow.com/q/50726374
has body: Use the csv reader object. Ex: with open("tweet-corpus.csv", "r") as csv_file: reader = csv.reader(csv_file) for row in reader: lang_tags = row[0] or with open("tweet-corpus.csv", "r") as csv_file: reader = csv.DictReader(csv_file) for row in reader: lang_tags = row['YOURCOL_NAME'] tweets = row['YOURCOL_NAME']
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50726374
type: Answer
has comment: http://stackoverflow.com/comment/88461278
score: 2
upvote count: 2

http://stackoverflow.com/comment/88650222
type: Comment
has text: @JacobIRR seems to be slightly faster, but there's still a noticeable delay, which appears when I enter that in an interactive shell as well. There might also just be a delay inherent to excel-python communication. Thanks for your suggestion, though
type: QuestionComment
comment on: http://stackoverflow.com/q/50821864
score: 0

http://stackoverflow.com/q/50826256
score: 7
has comment: http://stackoverflow.com/comment/88657532
has comment: http://stackoverflow.com/comment/88657513
upvote count: 7
accepted answer: http://stackoverflow.com/a/50826519
has comment: http://stackoverflow.com/comment/88657670
type: Question
has comment: http://stackoverflow.com/comment/88657367
tagged with: anaconda
has answer: http://stackoverflow.com/a/74805307
tagged with: pydicom
has comment: http://stackoverflow.com/comment/88657827
has comment: http://stackoverflow.com/comment/88657776
has comment: http://stackoverflow.com/comment/88657468
linked to: http://stackoverflow.com/q/28390961
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88657344
has title: How to Install a Package in PyCharm when project interpreter is set to conda, and the package is not provided/listed by conda?
has body: I installed pycharm on my computer. I set the project interpreter to acaconda3/bin/python because that is the python3 interpreter I used on my computer before installing pycharm. I was able to install all packages I need using pycharm's package installer except for pydicom which is not provided by anaconda. However, pydicom, one of the packages I need for my project, is not provided by conda and hence does not show up in the list of available packages when I search. How do I install this package that is not available with conda?
tagged with: python
possible better answer: http://stackoverflow.com/a/67208852
has answer: http://stackoverflow.com/a/63585286
answer count: 4
has answer: http://stackoverflow.com/a/50826519
has answer: http://stackoverflow.com/a/67208852
type: AnsweredQuestion
tagged with: pycharm

http://stackoverflow.com/a/50802476
accepted answer of: http://stackoverflow.com/q/50802385
answers question: http://stackoverflow.com/q/50802385
type: Answer
has body: open the csv to write outside the for-loop Ex: def get_list(): global productId askkeyword = input('please enter keyword') data = abc.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'], askkeyword, pageSize='40') with open('data.csv', 'w', newline='') as csvfile: fieldnames = ['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for product in data['products']: productId = product['productId'] productTitle = product['productTitle'] salePrice = product['salePrice'] originalPrice = product['originalPrice'] imageUrl = product['imageUrl'] writer.writerow({'productId': productId, 'productTitle': productTitle, 'salePrice': salePrice, 'originalPrice': originalPrice, 'imageUrl': imageUrl })
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50724859
tagged with: python
has answer: http://stackoverflow.com/a/50914921
upvote count: 3
answer count: 2
has title: Call Local CSS files in Dash App
has body: I am attempting to run the Dash Vanguard demo app while hosting the 4 css files locally. I have successfully been able to use a workaround and locally host a single css file in Dash, but have not been able to simultaneously call all 4. This is the current Vanguard dash app with the css files externally hosted: external_css = ["https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css", "https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css", "//fonts.googleapis.com/css?family=Raleway:400,300,600", "https://codepen.io/bcd/pen/KQrXdb.css", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"] for css in external_css: app.css.append_css({"external_url": css}) My attempt at hosting css files locally: app.scripts.config.serve_locally = True app.css.config.serve_locally = True .... app.layout = html.Div([ html.Link(href='/assets/skeleton.min.css', rel='stylesheet'), html.Link(href='/assets/skelly.css', rel='stylesheet'), html.Link(href='/assets/normalize.min.css', rel='stylesheet'), html.Link(href='/assets/font.css', rel='stylesheet'), dcc.Location(id='url', refresh=False), html.Div(id='page-content') ]) .... @app.server.route('/assets/&lt;path:path&gt;') def static_file(path): static_folder = os.path.join(os.getcwd(), 'assets') return send_from_directory(static_folder, path) The app currently loads without any styling. Not sure why it won't load even one of the css files.
has answer: http://stackoverflow.com/a/50780436
tagged with: plotly
type: UnansweredQuestion
tagged with: plotly-dash
downvote count: 0
favorite count: 0
type: Question
score: 3

http://stackoverflow.com/comment/88490544
has text: @ReezalAQ This link might help you a bit to understand functions in python: https://www.tutorialspoint.com/python/python_functions.htm
comment on: http://stackoverflow.com/a/50740857
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50807933
has comment: http://stackoverflow.com/comment/88622077
has comment: http://stackoverflow.com/comment/88624327
has comment: http://stackoverflow.com/comment/88622013
score: -1
has body: I am trying to use numpy concatenate and am running into a strange error. I would like to understand why this fails: a = np.arange(0,3) b = np.arange(3,6) c = np.array([a,b]) np.concatenate(c, axis=1) AxisError: axis 1 is out of bounds for array of dimension 1 ...but this succeeds: np.concatenate([c], axis=1) and also this succeeds: grid = np.array([[0,1,2], [3,4,5]]) print(grid) np.concatenate([grid,grid], axis=1)
type: Question
tagged with: numpy
upvote count: 0
accepted answer: http://stackoverflow.com/a/50808015
favorite count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88621657
tagged with: python
has comment: http://stackoverflow.com/comment/88622001
has title: Issue with Numpy Concatenate?
has comment: http://stackoverflow.com/comment/88621563
downvote count: 1
has answer: http://stackoverflow.com/a/50808015
type: AnsweredQuestion

http://stackoverflow.com/q/50770370
tagged with: python
type: UnansweredQuestion
has title: pandas.groupby.nsmallest drops multiindex when dataframe is presorted
linked to: http://stackoverflow.com/q/41949697
has answer: http://stackoverflow.com/a/57574587
has body: I am using pandas (0.22.0, python version 3.6.4) .groupby with the .nsmallest method to find the smallest items in each group of a dataframe. Here is an example dataframe: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'a': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar', 'qux', 'qux', 'qux'], 'b': ['baz', 'baz', 'baz', 'bat', 'baz', 'baz', 'bat', 'bat', 'bat', 'baz', 'bat', 'bat'], 'c': [1, 3, 2, 5, 6, 4, 9, 12, 7, 10, 8, 11]}) I want the three smallest values in column 'c' for each 'a'/'b' pair. The expression I am using to get the n-smallest values for each group in the 'c' column is as follows: &gt;&gt;&gt; (df.groupby(['a', 'b'])['c'].apply(lambda x: x.nsmallest(3)) .reset_index(level=['a', 'b'])) This returns the following data frame, as expected: a b c 8 bar bat 7 6 bar bat 9 7 bar bat 12 5 bar baz 4 4 bar baz 6 3 foo bat 5 0 foo baz 1 2 foo baz 2 1 foo baz 3 10 qux bat 8 11 qux bat 11 9 qux baz 10 But a strange thing happens if the data frame is sorted from smallest to largest on column 'c' first: &gt;&gt;&gt; df2 = df.sort_values('c', ascending=True) &gt;&gt;&gt; (df2.groupby(['a', 'b'])['c'].apply(lambda x: x.nsmallest(3)) .reset_index(level=['a', 'b'])) This returns: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-10-2afabcab898a&gt; in &lt;module&gt;() 1 (df2.groupby(['a', 'b'])['c'].apply(lambda x: x.nsmallest(3)) ----&gt; 2 .reset_index(level=['a', 'b'])) 3 ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in reset_index(self, level, drop, name, inplace) 1048 else: 1049 df = self.to_frame(name) -&gt; 1050 return df.reset_index(level=level, drop=drop) 1051 1052 def __unicode__(self): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in reset_index(self, level, drop, inplace, col_level, col_fill) 3339 if not isinstance(level, (tuple, list)): 3340 level = [level] -&gt; 3341 level = [se…
type: Question
upvote count: 4
answer count: 1
downvote count: 0
score: 4
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/88521584
score: 0
type: AnswerComment
has text: show url do you try, i don't understand how do you catch the error
type: Comment
comment on: http://stackoverflow.com/a/50756319

http://stackoverflow.com/comment/88657947
type: Comment
type: QuestionComment
has text: is the "next" button generated dynamically?? if not, why not use a Scrapy to traverse from page to page?
comment on: http://stackoverflow.com/q/50788131
score: 0

http://stackoverflow.com/a/50800088
has comment: http://stackoverflow.com/comment/88606313
score: 0
has body: From what i understood from the question you want to fetch the Salarie based on the employee's id Then this should work fine to load data from Salarie table class EmployeDetailView(DetailView): model = Employe def employeDetailView(self,request,pk,salaire__matriculeemp): try: employe=Employe.objects.get(pk=pk) salaire=get_object_or_404(matriculeemp=employe) #Book.objects.filter(publisher__name='BaloneyPress').count() #albumgroupe= Album.objects.filter(nomgroupe__nomgroupe__contains=request.POST['searchgroupe']) except Employe.DoesNotExist: raise ("Book does not exist") return render( request, 'Compta-IMC/employe_detail.html', context={'employe':employe, 'salaire':salaire} ) Let me know if this works
answers question: http://stackoverflow.com/q/50799885
type: Answer

http://stackoverflow.com/a/50741230
score: 0
type: AcceptedAnswer
has body: A = {"day1": ['A', 'B', 'C']} B = [['A','B'], ['A','C'], ['B','C']] vals = A['day1'] connections = [] for val in vals: connections_to_val = [(val, x) for x in vals if (val != x and (x, val) not in connections)] connections.extend(connections_to_val)
has comment: http://stackoverflow.com/comment/88490450
type: Answer
has comment: http://stackoverflow.com/comment/88531434
accepted answer of: http://stackoverflow.com/q/50740762
answers question: http://stackoverflow.com/q/50740762

http://stackoverflow.com/a/50758844
answers question: http://stackoverflow.com/q/50758165
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50758165
score: 6
has comment: http://stackoverflow.com/comment/117592951
has comment: http://stackoverflow.com/comment/117622502
upvote count: 6
type: AcceptedAnswer
has body: It's to do with NumPy's broadcasting rules. Quoting the NumPy manual: When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when they are equal, or one of them is 1 The first statement throws an error because NumPy looks at the only dimension, and (5000,) and (500,) are inequal and cannot be broadcast together. In the second statement, train.reshape(-1,1) has the shape (5000,1) and test.reshape(-1,1) has the shape (500,1). The trailing dimension (length one) is equal, so that's ok, but then NumPy checks the other dimension and 5000 != 500, so the broadcasting fails here. In the third case, your operands are (5000,) and (500,1). In this case NumPy does allow broadcasting. The 1D-array is extended along the trailing length-1 dimension of the 2D-array. FWIW, the shape and broadcasting rules can be a bit tricky sometimes, and I've often been confused with similar matters.
type: Answer

http://stackoverflow.com/comment/88640422
has text: I finally understood that you meant, but if i do that i have all the salarie of the database for an employe, if i wanted to have just the last salarie for an employe, how i can do ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50800263
type: Comment

http://stackoverflow.com/a/50853354
type: Answer
has comment: http://stackoverflow.com/comment/88711069
accepted answer of: http://stackoverflow.com/q/50852786
has body: This is more or less your script should look like. Use session to handle the cookies automatically. Fill in the username and password fields manually. import requests from bs4 import BeautifulSoup logurl = "https://login.flash.co.za/apex/f?p=pwfone:login" posturl = 'https://login.flash.co.za/apex/wwv_flow.accept' with requests.Session() as s: s.headers = {"User-Agent":"Mozilla/5.0"} res = s.get(logurl) soup = BeautifulSoup(res.text,"lxml") values = { 'p_flow_id': soup.select_one("[name='p_flow_id']")['value'], 'p_flow_step_id': soup.select_one("[name='p_flow_step_id']")['value'], 'p_instance': soup.select_one("[name='p_instance']")['value'], 'p_page_submission_id': soup.select_one("[name='p_page_submission_id']")['value'], 'p_request': 'LOGIN', 'p_arg_names': soup.select_one("[name='p_arg_names']")['value'], 'p_t01': 'username', 'p_arg_names': soup.select_one("[name='p_arg_names']")['value'], 'p_t02': 'password', 'p_md5_checksum': soup.select_one("[name='p_md5_checksum']")['value'], 'p_page_checksum': soup.select_one("[name='p_page_checksum']")['value'] } r = s.post(posturl, data=values) print r.content
has comment: http://stackoverflow.com/comment/88710595
has comment: http://stackoverflow.com/comment/88710857
has comment: http://stackoverflow.com/comment/88711364
upvote count: 1
has comment: http://stackoverflow.com/comment/88709726
has comment: http://stackoverflow.com/comment/88746160
score: 1
answers question: http://stackoverflow.com/q/50852786
has comment: http://stackoverflow.com/comment/88710092
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88710833
downvote count: 0
has comment: http://stackoverflow.com/comment/88709852
has comment: http://stackoverflow.com/comment/88709372

http://stackoverflow.com/comment/89074017
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50741787
type: Comment
has text: send your email address

http://stackoverflow.com/q/50778991
has answer: http://stackoverflow.com/a/50779111
upvote count: 2
type: Question
linked to: http://stackoverflow.com/q/48541444
has title: Suppress one csv file against another where values contain specific strings
accepted answer: http://stackoverflow.com/a/50779111
answer count: 1
downvote count: 0
tagged with: suppression
has comment: http://stackoverflow.com/comment/88564911
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I am trying to remove all the lines in file1.csv that contain the strings from file2.csv with python. I want it to search for all the values in column1 of file1.csv and remove entire rows where column1 contains in its value same string as in file2.csv. I know grep -v in bash can do same thing with just one command. However, I need to suppress file1.csv against over 40,000 possible strings in file2.csv. Bash takes forever and even crashes when executing this command. Does anyone know a solid script that can do what grep -v does in python but when suppressing against a file with thousands of strings? Just to make sure it's clear: File1.csv: column1,column2,column3 www.gamai4xheifw.com,4410,22 www.vfekjfwo11k.com,772,100 www.gosi4xnbdn.com,1793,39 www.tum33kkwfl.com,1100,2 www.eei4xelwf.com,9982,14 File2.csv: column1 i4x File3.csv: column1,column2,column3 www.vfekjfwo11k.com,772,100 www.tum33kkwfl.com,1100,2 But, again, I need it in python because the number of the strings in file2.csv is over 40,000.
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/50854266
type: Answer
accepted answer of: http://stackoverflow.com/q/50853821
upvote count: 14
has comment: http://stackoverflow.com/comment/88712894
has comment: http://stackoverflow.com/comment/88713155
has comment: http://stackoverflow.com/comment/88712745
has body: The documentation could be a bit clearer on this, it only states iter(object[, sentinel]) ... The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned. What is maybe not said perfectly clearly is that what the iterator yields is whatever the callable returns. And since your callable is a class (with no arguments), it returns a new instance of the class every iteration. One way around this is to make your class callable and delegate it to the __next__ method: class DoubleIt: def __init__(self): self.start = 1 def __iter__(self): return self def __next__(self): self.start *= 2 return self.start __call__ = __next__ i = iter(DoubleIt(), 16) print(next(i)) # 2 print(list(i)) # [4, 8] This has the dis-/advantage that it is an infinite generator that is only stopped by the sentinel value of iter. Another way is to make the maximum an argument of the class: class DoubleIt: def __init__(self, max=10): self.start = 1 self.max = max def __iter__(self): return self def __next__(self): if self.start &lt; self.max: self.start *= 2 return self.start else: raise StopIteration i = iter(DoubleIt(max=16)) print(next(i)) # 2 print(list(i)) # [4, 8, 16] One difference to note is that iter stops when it encounters the sentinel value (and does not yield the item), whereas this second way uses &lt;, instead of &lt;= comparison (like your code) and will thus yield the maximum item.
has comment: http://stackoverflow.com/comment/88711944
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88712063
has comment: http://stackoverflow.com/comment/88712532
score: 14
answers question: http://stackoverflow.com/q/50853821
has comment: http://stackoverflow.com/comment/88712446

http://stackoverflow.com/a/50742637
upvote count: 1
has body: I was able to get most of what I wanted by configuring the axes tick params for the y axis: ax.tick_params(axis='y', pad=0, left=True, length=6, width=1, direction='inout') and the marker decorations below the theta tick labels with the decorate_ticks function (as shown in the code and the result). However, it appears the center marker is always the color and style of the last theta grid marker. I've noted this in a comment inside of the decorate_ticks function. If you know of a way to style the center marker differently, please let me know how. import numpy as np import matplotlib.pyplot as plt class Radar(object): def __init__(self, fig, titles, label, rect=None): if rect is None: rect = [0.05, 0.15, 0.95, 0.75] self.n = len(titles) self.angles = [a if a &lt;=360. else a - 360. for a in np.arange(90, 90+360, 360.0/self.n)] self.axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i) for i in range(self.n)] self.ax = self.axes[0] # Show the labels self.ax.set_thetagrids(self.angles, labels=titles, fontsize=14, weight="bold", color="black") for ax in self.axes[1:]: ax.patch.set_visible(False) ax.grid(False) ax.xaxis.set_visible(False) self.ax.yaxis.grid(False) for ax, angle in zip(self.axes, self.angles): ax.set_rgrids(range(1, 6), labels=label, angle=angle, fontsize=12) # hide outer spine (circle) ax.spines["polar"].set_visible(False) ax.set_ylim(0, 6) ax.xaxis.grid(True, color='black', linestyle='-') # draw a line on the y axis at each label ax.tick_params(axis='y', pad=0, left=True, length=6, width=1, direction='inout') def decorate_ticks(self, axes): for idx, tick in enumerate(axes.xaxis.majorTicks): # print(idx, tick.label._text) # get the gridline gl = tick.gridline gl.set_marker('o') gl.set_markersize(15) if idx == 0: gl.set_markerfacecolor('b') elif idx == 1: gl.set_markerfacecolor('c') elif idx == 2: gl.set_markerfacecolor('g') elif idx == 3: gl.set_markerfacecolor('y') elif idx == 4: gl.set_markerfacecolor('r') # this doesn't get used. The cente…
type: Answer
answers question: http://stackoverflow.com/q/50704932
downvote count: 0
score: 1

http://stackoverflow.com/comment/88687083
type: Comment
comment on: http://stackoverflow.com/q/50825707
type: QuestionComment
has text: Just tried updating again. This, among other things popped up: `Requirement already up-to-date: matplotlib in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages` Still same result
score: 0

http://stackoverflow.com/comment/117650656
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50824493
type: Comment
has text: Suggest retitling because the doesn't reflect what was really asked, and the answers don't answer the question in the title. That means this comes up in searches for the question in the title, but this page does not answer that question.

http://stackoverflow.com/comment/88513524
comment on: http://stackoverflow.com/a/50752131
type: Comment
has text: If it doesn't need what I'm going to give it then it's never going to work anyway. I'm not writing code to use every function ever. I'm writing code that doesn't care what function it uses so long as it works with what I give it. My code is not going to make up new arguments to pass just because the function you pass me demands it. Do that and you deserve the error you get.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50743855
possible better answer: http://stackoverflow.com/a/50789194
type: Question
has body: I need to count the percentage of each group(from A to G) and use six different columns to divide by the same one(like G representing the total). And then I need to count calculate something called HHI. My equation has a "1-" in front of the sigma sign. Thus, I need to square those columns and then add them up and then use 1 minus the addition. I need to keep those columns of percentage in my dataframe. Please help me to simplify the following code: df = pd.DataFrame(np.random.randn(20, 7), columns=list("ABCDEFG")) #percentage df["pct_A"] = df_race.A / df_race.G df["pct_B"] = df_race.B / df_race.G df["pct_C"] = df_race.C / df_race.G df["pct_D"] = df_race.D / df_race.G df["pct_E"] = df_race.E / df_race.G df["pct_F"] = df_race.F / df_race.G #HHI Index df["hhi"] = 1-(df.pct_A**2 + df.pct_B**2 + df.pct_C**2 + df.pct_D**2 + df.pct_E**2 + df.pct_F**2)
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50789194
has answer: http://stackoverflow.com/a/50744665
accepted answer: http://stackoverflow.com/a/50744665
has title: simplify summation computation (sigma sign) in pandas
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50750052
upvote count: 4
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has title: TfidfVectorizer on large corpus with generators
tagged with: tfidfvectorizer
has body: I have large corpus splitted into 5K files , I am trying to generate a IDF based vocabulary using TF-IDF trasform. Here is the code: Basically I have a iterator which loops through a directory for .tsv files, reading each file and yield. import sys reload(sys) sys.setdefaultencoding('utf-8') import pandas as pd import numpy as np import os import pickle from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) def make_corpus(): inputFeatureFiles = [x for x in os.listdir('C:\Folder') if x.endswith("*.tsv")] for file in inputFeatureFiles: filePath= 'C:\\' + os.path.splitext(file)[0] + ".tsv" with open(filePath, 'rb') as infile: content = infile.read() yield content corpus = make_corpus() vectorizer = TfidfVectorizer(stop_words='english',use_idf=True, max_df=0.7, smooth_idf=True) vectorizer.fit_transform(corpus) This generates below error : c:\python27\lib\site-packages\sklearn\feature_extraction\text.pyc in _count_vocab(self, raw_documents, fixed_vocab) 809 vocabulary = dict(vocabulary) 810 if not vocabulary: --&gt; 811 raise ValueError("empty vocabulary; perhaps the documents only" 812 " contain stop words") 813 ValueError: empty vocabulary; perhaps the documents only contain stop words I also tried this : corpusGenerator= [open(os.path.join('C:\CorpusFiles\',f)) for f in os.listdir('C:\CorpusFiles')] vectorizer = TfidfVectorizer(stop_words='english',use_idf=True,smooth_idf=True, sublinear_tf=True, input="file", min_df=1) feat = vectorizer.fit_transform(corpusGenerator) and get below error: [Errno 24] Too many open files: 'C:\CorpusFiles\file1.tsv' what is the best way to use TFIDFVectorizer on large corpus? I also tried appending a constant string to each yield string to avoid the first error but that also did not fix it. Appreciate any help !
tagged with: python
tagged with: generator
score: 4
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92014509
tagged with: corpus
type: Question
has answer: http://stackoverflow.com/a/64368688

http://stackoverflow.com/comment/88599562
score: 1
comment on: http://stackoverflow.com/q/50796170
has text: a) strings can not be modified in Python, you have to construct a new one. b) for any serious date or time calculation use a proper library. `datetime` is built-in, but there are others like for example `arrow` as well.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50761328
answers question: http://stackoverflow.com/q/50761242
has comment: http://stackoverflow.com/comment/88532904
score: 1
has comment: http://stackoverflow.com/comment/88532261
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88532777
type: Answer
has comment: http://stackoverflow.com/comment/88546168
accepted answer of: http://stackoverflow.com/q/50761242
has body: Is this what you want: def myfunc(): a=0 b=0 c=1 l = [a,b,c] d=locals() for element,i in list(zip(l,['a','b','c'])): d[i]=d[i]+1 print(d['a']) print(d['b']) print(d['c']) myfunc() Output: 1 1 2
downvote count: 0

http://stackoverflow.com/a/50841388
score: 0
has comment: http://stackoverflow.com/comment/88784065
has comment: http://stackoverflow.com/comment/88878148
has comment: http://stackoverflow.com/comment/88783509
has body: Try with just google-oauthlib-tool --client-secrets credentials.json --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless With the good path for json file.
answers question: http://stackoverflow.com/q/50826289
type: Answer
has comment: http://stackoverflow.com/comment/88783519
has comment: http://stackoverflow.com/comment/88904594
has comment: http://stackoverflow.com/comment/88783967
has comment: http://stackoverflow.com/comment/88794987
has comment: http://stackoverflow.com/comment/88783530
has comment: http://stackoverflow.com/comment/88794348

http://stackoverflow.com/comment/88418159
score: 0
type: Comment
type: AnswerComment
has text: The problem is I have to compare these times with times from another source. It is quite uncomfortable to then deal with a time carrying the 1st Jan 1900 information.... as the other times surely will not have it.
comment on: http://stackoverflow.com/a/50703619

http://stackoverflow.com/q/50819549
has comment: http://stackoverflow.com/comment/88847637
has title: Dateframe interpolate not working in Panda + multidimensional interpolation
type: Question
has comment: http://stackoverflow.com/comment/88854823
has comment: http://stackoverflow.com/comment/88666751
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88661312
has comment: http://stackoverflow.com/comment/88856132
tagged with: pandas
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/50906084
accepted answer: http://stackoverflow.com/a/50906084
favorite count: 0
has comment: http://stackoverflow.com/comment/88647960
has body: multidimensional interpolation with dataframe not working import pandas as pd import numpy as np raw_data = {'CCY_CODE': ['SGD','USD','USD','USD','USD','USD','USD','EUR','EUR','EUR','EUR','EUR','EUR','USD'], 'END_DATE': ['16/03/2018','17/03/2018','17/03/2018','17/03/2018','17/03/2018','17/03/2018','17/03/2018', '17/03/2018','17/03/2018','17/03/2018','17/03/2018','17/03/2018','17/03/2018','17/03/2018'], 'STRIKE':[0.005,0.01,0.015,0.02,0.025,0.03,0.035,0.04,0.045,0.05,0.55,0.06,0.065,0.07], 'VOLATILITY':[np.nan,np.nan,0.3424,np.nan,0.2617,0.2414,np.nan,np.nan,0.215,0.212,0.2103,np.nan,0.2092,np.nan] } df_volsurface = pd.DataFrame(raw_data,columns = ['CCY_CODE','END_DATE','STRIKE','VOLATILITY']) df_volsurface['END_DATE'] = pd.to_datetime(df_volsurface['END_DATE']) df_volsurface.interpolate(method='akima',limit_direction='both') Output: CCY_CODE END_DATE STRIKE VOLATILITY 0 SGD 3/16/2018 0.005 NaN 1 USD 3/17/2018 0.01 NaN 2 USD 3/17/2018 0.015 0.3424 3 USD 3/17/2018 0.02 0.296358 4 USD 3/17/2018 0.025 0.2617 5 USD 3/17/2018 0.03 0.2414 6 USD 3/17/2018 0.035 0.230295 7 EUR 3/17/2018 0.04 0.220911 8 EUR 3/17/2018 0.045 0.215 9 EUR 3/17/2018 0.05 0.212 10 EUR 3/17/2018 0.55 0.2103 11 EUR 3/17/2018 0.06 0.209471 12 EUR 3/17/2018 0.065 0.2092 13 USD 3/17/2018 0.07 NaN Expected Result: CCY_CODE END_DATE STRIKE VOLATILITY 0 SGD 3/16/2018 0.005 NaN 1 USD 3/17/2018 0.01 Expected some logical value 2 USD 3/17/2018 0.015 0.3424 3 USD 3/17/2018 0.02 0.296358 4 USD 3/17/2018 0.025 0.2617 5 USD 3/17/2018 0.03 0.2414 6 USD 3/17/2018 0.035 0.230295 7 EUR 3/17/2018 0.04 0.220911 8 EUR 3/17/2018 0.045 0.215 9 EUR 3/17/2018 0.05 0.212 10 EUR 3/17/2018 0.55 0.2103 11 EUR 3/17/2018 0.06 0.209471 12 EUR 3/17/2018 0.065 0.2092 13 USD 3/17/2018 0.07 Expected some logical value Linear interpolation methods gives copy last available values to all backward and forward missing value without considering ccy_code df_volsurface.interpolate(method='linear',limit_direction='both') Output: CCY_CODE END_…
tagged with: python
has comment: http://stackoverflow.com/comment/88852540
type: AnsweredQuestion
tagged with: interpolation
downvote count: 0
has comment: http://stackoverflow.com/comment/88812032
has comment: http://stackoverflow.com/comment/88780039
score: 1

http://stackoverflow.com/a/50911731
downvote count: 0
answers question: http://stackoverflow.com/q/50838525
upvote count: 8
type: AcceptedAnswer
has body: I had the exact same issue. The problem is not the query itself, it's that you are most likely reusing the same QueryJobConfig. When you perform a query, unless you set a destination, BigQuery stores the result in an anonymous table which is stated in the QueryJobConfig object. If you reuse this configuration, BigQuery tries to store the new result in the same anonymous table, hence the error. I don't particularly like this behaviour, to be honest. You should rewrite your code like that: def get_data_from_bq(product_ids): format_strings = ','.join([("\"" + str(_id) + "\"") for _id in product_ids]) query = "select productId, eventType, count(*) as count from [xyz:xyz.abc] where productId in (" + format_strings + ") and eventTime &gt; CAST(\"" + time_thresh +"\" as DATETIME) group by eventType, productId order by productId;" query_job = bigquery_client.query(query, job_config=QueryJobConfig()) return query_job.result() Hope this helps!
score: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/50838525

http://stackoverflow.com/a/50744924
answers question: http://stackoverflow.com/q/50742503
type: Answer
has body: Thank you @ImportanceOfBeingErnest for pointing out that this is not really possible. Here is one workaround, that kind of works, by checking the number of lines the text is broken up into, and multiplying by the approximate line-height. This works when automatically inserted breaks are mixed with manually (i.e. there is an "\n" in the text), but will be off by a number of pixels. Any more precise suggestions welcome. def get_text_height(fig, obj): """ Get the approximate height of a text object. """ fig.canvas.draw() # Draw text to find out how big it is t = obj.get_text() r = fig.canvas.renderer w, h, d = r.get_text_width_height_descent(t, obj._fontproperties, ismath=obj.is_math_text(t)) num_lines = len(obj._get_wrapped_text().split("\n")) return (h * num_lines) text = "I'm a long text that will be wrapped automatically by Matplotlib, using wrap=True" obj = fig.suptitle(text, wrap=True) height = get_text_height(fig, obj) print(height) # 28 &lt;-- Close enough! (In reality 30)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50742503
score: 0

http://stackoverflow.com/a/50742171
has body: I just ended up drawing a border around each cell. I used this for reference: Applying borders to a cell in OpenPyxl My initial concern was that I would have to draw each side of the box individually and I didn't want my code to drone on, but creating one full border and then applying it was fine.
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50729188
answers question: http://stackoverflow.com/q/50729188

http://stackoverflow.com/q/50742839
tagged with: pip
type: Question
possible better answer: http://stackoverflow.com/a/63356126
score: 4
tagged with: conda
tagged with: proxy
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/63356126
tagged with: requirements
has comment: http://stackoverflow.com/comment/90145158
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/51629346
accepted answer: http://stackoverflow.com/a/51629346
has comment: http://stackoverflow.com/comment/90000134
has title: How to use the proxy provided in .condarc for pip packages in the environment.yml?
type: AnsweredQuestion
has body: I have to use a proxy, which I have configured in the .condarc file, for conda work, which works perfectly fine. However when I'm setting up a new python environment with an environment.yml file, which could look like this: name: Test channels: - intel - defaults dependencies: - pypdf2=1.26.0=py36_1 - mkl=2018.0.2=1 - pip: - adjusttext==0.7.2 prefix: C:\ProgramData\Anaconda3\envs\Test Pip doesn't use the provided proxy to install those packages, so I get an error. How can I get pip to use that proxy as well?

http://stackoverflow.com/comment/88555735
type: AnswerComment
comment on: http://stackoverflow.com/a/50774173
has text: ./run.sh: line 12: syntax error near unexpected token `list' ./run.sh: line 12: `list = 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95;'
score: 0
type: Comment

http://stackoverflow.com/comment/88620863
type: Comment
has text: What version of Python, and what version of iTunes?
type: QuestionComment
comment on: http://stackoverflow.com/q/50807548
score: 0

http://stackoverflow.com/comment/88572619
has text: Did you tried `request.data[all_letters]` ? Or `json.loads` ?
score: 0
comment on: http://stackoverflow.com/q/50783006
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50741980
type: Question
has body: I'm using selenium to control Firefox, and load my default profile successfully(I can change my search engine or add page to my bookmark manually, then close it, and I can see the change in my program's opening Firefox) So I think my loading profile is all right. But what I want to do is to make 'open new link in new tab instead of new window' true in Firefox's options. And it went wrong. I found that my Firefox opened manually was different from my program's opening Firefox on tab options page. Look at the tabs, they have different options. And my setting on the first browser about tabs can't convert to the second one. How to fix it? Thanks for advance. self.window.driver = webdriver.Firefox(executable_path=self.window.driverPath,firefox_profile=self.window.profile)
tagged with: firefox
downvote count: 0
score: 1
has title: Having loaded profile, selenium opened Firefox but partial options still wrong
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88491520
answer count: 0
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/88491655

http://stackoverflow.com/q/50787607
has body: How can I install spyder 2 in Ubuntu 18.04? When I type this in the terminal: sudo apt-get install spyder it installs spyder 3.
tagged with: ubuntu-18.04
type: UnansweredQuestion
has title: Spyder 2 in Ubuntu 18.04
score: 1
favorite count: 0
tagged with: linux
type: Question
tagged with: spyder
tagged with: python
has answer: http://stackoverflow.com/a/50787763
upvote count: 2
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/50787723

http://stackoverflow.com/comment/88667874
comment on: http://stackoverflow.com/q/50831842
type: QuestionComment
type: Comment
has text: There is no better way to do that.
score: 0

http://stackoverflow.com/comment/88620784
has text: That was indeed the answer, thank you for your help.
type: Comment
comment on: http://stackoverflow.com/q/50807455
score: 0
type: QuestionComment

http://stackoverflow.com/q/50794420
has comment: http://stackoverflow.com/comment/88600187
downvote count: 5
has comment: http://stackoverflow.com/comment/88599435
has title: Python regular expressions - how to capture the rest of text which is uncaptured
has comment: http://stackoverflow.com/comment/88594864
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50796871
accepted answer: http://stackoverflow.com/a/50796871
upvote count: 1
has comment: http://stackoverflow.com/comment/88594769
has body: Dear Community members! I am struggling to figure out regex problem. Objective is to split the text in separate parts with keyword (consectetur|tempor incididunt|proident|consequat) as a separator and add keyword to the text part captured. Start capturing new group again until another keyword is spotted. Unfortunatly, I am stuck to find a solution for capturing the last bit of text, which has no keywords and has to be added to the end of last capture group or new group. Is that even possible to solve using regex? Please, pay attention to links at the bottom Regular expression: (.*?)(consectetur|tempor incididunt|proident|consequat) Text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Desired outcome: Match 1 Lorem ipsum dolor sit amet, consectetur Match 2 adipiscing elit, sed do eiusmod tempor incididunt Match 3 ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat Match 4 . Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum. Below, I have attached supporting information with what I have so far: Screenshot of above-mentioned problem <a href="https://pythex.org/?regex=(.*%3F)(consectetur%7Ctempor%20incididunt%7Cproident%7Cconsequat)&amp;test_string=Lorem%20ipsum%20dolor%20sit%20amet%2C%20consectetur%20adipiscing%20elit%2C%20sed%20do%20eiusmod%20tempor%20incididunt%20ut%20labore%20et%20dolore%20magna%20aliqua.%20Ut%20enim%20ad%20mini…
tagged with: regex
favorite count: 0
score: -4
tagged with: python
tagged with: text
type: AnsweredQuestion

http://stackoverflow.com/comment/88709646
type: AnswerComment
type: Comment
has text: Hi. I have not idea how to do that. Any guidance would be appreciated. Thanks
comment on: http://stackoverflow.com/a/50853187
score: 0

http://stackoverflow.com/q/50761668
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am working on a project which includes images which are in (.img) formats. These images are easily open in Erdas or Qgis but I need to view them via python scripts. Is it possible to view image with the help of gdal? If yes, How?
has title: How to view .img file in python?
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50846383
tagged with: image-processing
has comment: http://stackoverflow.com/comment/88696310
type: Question
has comment: http://stackoverflow.com/comment/88551648
upvote count: 2
tagged with: gdal
tagged with: geospatial
answer count: 1
tagged with: raster
has comment: http://stackoverflow.com/comment/88536208

http://stackoverflow.com/comment/88679935
type: Comment
comment on: http://stackoverflow.com/a/50783905
score: 0
type: AnswerComment
has text: yw! If i may add, if you're going to use this productively with a lot of invites, you should probably subtract the invites covered by `inviters` before passing them to the nested call to avoid overhead lookups

http://stackoverflow.com/comment/88650439
type: Comment
type: QuestionComment
has text: So `cL` specifies the length of 3 arrays?
comment on: http://stackoverflow.com/q/50810864
score: 0

http://stackoverflow.com/comment/88669773
score: 0
has text: @andrewnagyeb Funny, that indicated to me he wanted to skip the trial-and-error and go for the best approach on first try.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50832601

http://stackoverflow.com/comment/88495476
has text: The location of the python file that's trying to read it is in the stacktrace. You could check that file out for context that could lead to the location of the README
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50743723

http://stackoverflow.com/q/50743724
tagged with: python
tagged with: anaconda
has answer: http://stackoverflow.com/a/50743901
type: Question
has title: How to read a file on Anaconda, using macOS?
tagged with: conda
score: 0
tagged with: spyder
answer count: 1
has body: I'm trying to open a .tnt format file on spyder(Anaconda) using the nmrglue module. import nmrglue as ng dic, data = ng.tecmag.read("~/Desktop/Spectra001.tnt") I'm using the appropiate commands as stated in their manual (pg. 85) - https://media.readthedocs.org/pdf/nmrglue/latest/nmrglue.pdf, but spyder can't read or even find the file. Can someone help me understand what I'm doing wrong?
type: UnansweredQuestion

http://stackoverflow.com/comment/88614059
comment on: http://stackoverflow.com/a/50803827
score: 0
has text: `item.select("td")[-1].text.strip() for item in items` means *return the list of the text nodes of each last "td" node from each "tr" node*. `if item.select("a[href^='mailto:']") or "Raison" in item.text` means *return not from every "tr" node, but only from those who has required link or contains substring "Raison"*. As we know that there are only two nodes that could met our condition, we can simply assign `raison, email = [first_item, second_item]`
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88614896
comment on: http://stackoverflow.com/q/50801820
has text: Even if you can't upgrade the system pip, you still can upgrade the packages inside the venv, including pip. `source venvname && pip install --upgrade pip`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50707750
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
upvote count: 2
has body: When I add a number of inlines to my django admin as shown below the Add another {model name} disappears. If I check the javascript console I see that I am getting the following error: Uncaught TypeError: Cannot read property 'fn' of undefined at inlines.js:20 at inlines.js:295 Here's my Django admin: @admin.register(models.Paper) class PaperAdmin(BaseLiteratureAdmin): class EditedPaperAdminInline(admin.StackedInline): model = models.EditedPaper extra = 0 class SupplementaryInformationAdminInline(admin.StackedInline): model = models.SupplementaryInformation extra = 0 class PaperNotesAdminInline(BaseNotesAdminInline): exclude = tuple( i for i in BaseNotesAdminInline.exclude if i != 'paper' ) class ReferencedPaperInline(admin.StackedInline): model = models.Paper.referenced_papers.through extra = 0 fk_name = 'from_paper' verbose_name = "Referenced Paper" verbose_name_plural = "Referenced Papers" inlines = ( EditedPaperAdminInline, # problem PaperNotesAdminInline, # ok single/together ReferencedPaperInline, # ok single/together SupplementaryInformationAdminInline, # problem ) Here's what I'd like to see: Here's what I'm seeing: And I found the solution--it's to change the order of the inlines in the inlines list, like so: inlines = ( PaperNotesAdminInline, # ok single/together ReferencedPaperInline, # ok single/together EditedPaperAdminInline, # problem SupplementaryInformationAdminInline, # problem ) The #comments next to each inline note that the PaperNotesAdminInline and ReferencedPaperInline are both 'OK' in that the Add another {model name} link still appears if they are included. The other two inlines, if added in order shown in the admin model definition, result in the JavaScript error and the links disappearing for each inline. However, if I change the order to the second inlines list, everything loads correctly. What is going on here?
type: Question
has answer: http://stackoverflow.com/a/50871534
tagged with: javascript
has title: Django Admin StackedInline Not Loading Add Another model, Uncaught TypeError: Cannot read property 'fn' of undefined
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88704787
type: QuestionComment
comment on: http://stackoverflow.com/q/50849686
has text: duplicate of [How to take partial screenshot with Selenium WebDriver in python?](https://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python)
score: 0
type: Comment

http://stackoverflow.com/a/50714558
has body: I think what you need is a Session then you can do something like this- @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST'] session['username'] = request.form['user'] return redirect(url_for('home')) And in route for home use- @app.route('/home') def home(): if 'username' in session: return render_template("index.html", name=session['username']) Hope this helps
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50708061

http://stackoverflow.com/comment/88707345
type: AnswerComment
comment on: http://stackoverflow.com/a/50851889
type: Comment
has text: Also $EDITOR $AIRFLOW_HOME/airflow.cfg didn't work for me. I had to do cd airflow and then nano airflow.cfg
score: 0

http://stackoverflow.com/comment/88410251
type: AnswerComment
comment on: http://stackoverflow.com/a/50700330
type: Comment
score: 2
has text: Or just `tuple(x.replace('(', '') for x in b)`

http://stackoverflow.com/comment/88658084
score: 0
type: Comment
has text: What happened when you tried it? 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) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here.
type: QuestionComment
comment on: http://stackoverflow.com/q/50818965

http://stackoverflow.com/q/50748727
linked to: http://stackoverflow.com/q/40255096
has comment: http://stackoverflow.com/comment/88505065
has comment: http://stackoverflow.com/comment/88505379
has comment: http://stackoverflow.com/comment/88505333
score: 0
has comment: http://stackoverflow.com/comment/88504989
has title: python newbie: for j in range
has answer: http://stackoverflow.com/a/50749410
accepted answer: http://stackoverflow.com/a/50749410
has comment: http://stackoverflow.com/comment/88504948
tagged with: self
tagged with: python
has body: I am new to learn python these days. While reading a book, I found a line of code that I can't understand. Please see line 46 under print_progression() method, print(' '.join(str(next(self)) for j in range(n))). class Progression: '''Iterator producing a generic progression. Default iterator produces the whole number, 0, 1, 2, ... ''' def __init__(self, start = 0): ''' Initialize current to the first value of the progression. ''' self._current = start def _advance(self): ''' Update self.current to a new value. This should be overriden by a subclass to customize progression. By convension, if current is set to None, this designates the end of a finite progression. ''' self._current += 1 def __next__(self): ''' Return the next element, or else raise StopIteration error. ''' # Our convention to end a progression if self._current is None: raise StopIteration() else: # record current value to return answer = self._current # advance to prepare for next time self._advance() # return the answer return answer def __iter__(self): ''' By convention, an iterator must return itself as an iterator. ''' return self def print_progression(self, n): ''' Print next n values of the progression. ''' print(' '.join(str(next(self)) for j in range(n))) class ArithmeticProgression(Progression): # inherit from Progression pass if __name__ == '__main__': print('Default progression:') Progression().print_progression(10) '''Output is Default progression: 0 1 2 3 4 5 6 7 8 9 10''' I have no idea how next(self) and j works. I think it should be str(Progression.next()). (solved) I cannot find j anywhere. What is j for? Why not using while loop such as while Progression.next() &lt;= range(n)? For my final thought, it should be print(' '.join(str(next(self)) while next(self) &lt;= range(n))) Save this newbie. Thanks in advance!
has comment: http://stackoverflow.com/comment/88505245
has comment: http://stackoverflow.com/comment/88505147
possible better answer: http://stackoverflow.com/a/50749048
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50749048
linked to: http://stackoverflow.com/q/920645
type: Question
tagged with: iterator
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/88505363

http://stackoverflow.com/comment/88416892
comment on: http://stackoverflow.com/q/50703721
has text: Had no idea. That would be best. Thanks
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50852957
type: UnansweredQuestion
tagged with: datetime
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/50853086
duplicate of: http://stackoverflow.com/q/4039879
has comment: http://stackoverflow.com/comment/88708741
has comment: http://stackoverflow.com/comment/88709898
has comment: http://stackoverflow.com/comment/88708717
has body: How to calculate two datetime's month difference? If I have two datetime, such as: 2017.01.01 and 2018.04.01, the months difference is 15. (2017.01.01 ~ 2018.04.01) But how can I calculate it?
score: 0
has title: How to calculate two datetime's month difference?
answer count: 1

http://stackoverflow.com/a/62807504
has body: Use decode() correctly: either in two steps (if you want to reuse blah): blah = blah.decode() splitblah = blah.split("\n") # other code that uses blah or inline (if you need it for single use): splitblah = blah.decode().split("\n") Your issue with using decode() was that you did not use its return value. Note that decode() does not change the object (blah) to assign or pass it to something: # WRONG! blah.decode() SEE ALSO: decode docs.
answers question: http://stackoverflow.com/q/50829364
type: Answer
upvote count: 10
score: 10
downvote count: 0

http://stackoverflow.com/q/50703912
accepted answer: http://stackoverflow.com/a/50704404
tagged with: django-rest-framework
has body: I have a django rest framework project already going with some models already created, and I am trying to add django-modeltranslation to the project. I followed the process as specified in django-modeltranslation documentation, but applications stop working after making migrations with django-modeltranslation modifications. Everytime I try to access de database, wether through the admin page or the django rest framework page, I get an error with the applications I have added transalation.py file to. Applications without it continue working. This is my model: class Country(models.Model): name = models.CharField(max_length=40, unique=True, verbose_name=_('Name')) code = models.CharField(max_length=5, verbose_name=_('Code')) calling_code = models.CharField(max_length=3, null=True, blank=True, verbose_name=_('Calling code')) class Meta: verbose_name = _('Country') verbose_name_plural = _('Countries') def __str__(self): return self.name This is my translation.py @register(models.Country) class CountryTranslationOptions(TranslationOptions): fields = ('name',) And this is the whole traceback of the error I get: Internal Server Error: /es/general/countries/ Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line…
has comment: http://stackoverflow.com/comment/88417367
answer count: 1
has title: django-modeltranslation causes django unable to access database
tagged with: django-modeltranslation
score: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50704404
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88417985
type: Question
has comment: http://stackoverflow.com/comment/88417866

http://stackoverflow.com/comment/88571007
comment on: http://stackoverflow.com/a/50782032
score: 0
type: AnswerComment
type: Comment
has text: no, EvilHappyHippo stated that the chars were given in the form `\u00e4`

http://stackoverflow.com/a/50856683
accepted answer of: http://stackoverflow.com/q/50853900
type: Answer
score: 1
upvote count: 1
has body: As suspected in the comment, you have some problem with Unicode characters. You can use this to encode properly the characters: function b64EncodeUnicode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode(parseInt(p1, 16)); })); } console.log(b64EncodeUnicode('lögin:password')); Check this post for more details about this!
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50853900

http://stackoverflow.com/a/50777988
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50770410
type: AcceptedAnswer
downvote count: 0
has body: @SantoshGupta7: I assure you that your data are not being eliminated. It appears that way because the DataFrameGroupBy.head function preserves the original order of the dataframe. If you call .count() or any other aggregation function on your groupby object, you will see all of your data are still there. To approximate the .head() behavior you're expecting, you can do the following: rr = pd.read_csv('refinedRatings.csv') rrgb = rr.groupby('user_id') print(rrgb.apply(lambda x: x.head(200))) Unnamed: 0 user_id book_id rating user_id 1 0 0 1 258 5 59 78 1 1796 5 148900 230483 1 4691 4 148901 230485 1 2063 4 148902 230489 1 11 5 148903 230490 1 1644 5 148904 230492 1 136 5 148905 230493 1 6665 4 148906 230495 1 35 5 148907 230496 1 33 4 148908 230500 1 10 4 148909 230502 1 4 5 148910 230505 1 1521 5 148911 230506 1 70 5 148912 230509 1 36 4 148913 230512 1 32 4 You'll notice that the "user_id" column is still present. That's down to the particular nature of the groupby.head function and/or the fact that you haven't yet performed any aggregation on the data. Please see https://github.com/pandas-dev/pandas/issues/17775 for a discussion of the "head" issue.
type: Answer
accepted answer of: http://stackoverflow.com/q/50770410

http://stackoverflow.com/comment/88687317
type: QuestionComment
has text: Remove the spaces from the first RE. Also, your sample numbers (1a2b,..., etc) do not have a 0x at the start.
comment on: http://stackoverflow.com/q/50841724
score: 0
type: Comment

http://stackoverflow.com/q/50840105
has answer: http://stackoverflow.com/a/50841254
has title: Multiprocessing Pool apply_async's workers and callback aren't called when executing in the inner scope
type: UnansweredQuestion
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/46266803
has body: Here is the code I have: import pandas as pd import multiprocessing as mp CPU = 4 inp = pd.DataFrame({ 'col': ['a', 'b'] }) def test(dataframe): df = dataframe.copy() def worker(data): print('worker') def callback(data): print('callback') pool = mp.Pool(CPU) for idx, row in df.iterrows(): print((idx, row['col'])) pool.apply_async(worker, args=[(idx, row['col'])], callback=callback) pool.close() pool.join() return df test(inp) It works as expected if I run in the upper scope (without enclosing in the test function), but after enclosing it in another function - they just are not called. Here is output I receive with test function: (0, 'a') (1, 'b') Without: (0, 'a') (1, 'b') worker worker callback callback So the question is - how can I make it work inside another function?
duplicate of: http://stackoverflow.com/q/46266803
tagged with: python-multiprocessing
score: 0
answer count: 1
tagged with: process-pool
tagged with: python

http://stackoverflow.com/comment/88529435
type: AnswerComment
has text: I think OP needs `result.group(1)` and `result.group(2)`
comment on: http://stackoverflow.com/a/50761002
type: Comment
score: 0

http://stackoverflow.com/comment/88603487
has text: use [`zip(*[iter(it)] * 2)`](https://stackoverflow.com/a/2631256/6597761)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50798493

linear-algebra
tags question: http://stackoverflow.com/q/50705891
type: Tag
tags question: http://stackoverflow.com/q/50753477
tags question: http://stackoverflow.com/q/50700256
tag name: linear-algebra
tags question: http://stackoverflow.com/q/50760792
tags question: http://stackoverflow.com/q/50770569

http://stackoverflow.com/comment/88418993
type: QuestionComment
score: 0
has text: The first step you should do to debug this is put in some print statements in `randomize` to verify that the values you're _assuming_ you're getting and computing are what you're _actually_ getting and computing.
comment on: http://stackoverflow.com/q/50704612
type: Comment

http://stackoverflow.com/q/50706279
upvote count: 2
has title: Plotting a graph in python using igraph
tagged with: python
tagged with: plot
tagged with: igraph
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89515143
type: Question
linked to: http://stackoverflow.com/q/21976889
tagged with: graph
has answer: http://stackoverflow.com/a/51268474
answer count: 1
downvote count: 0
has body: My code is of the form as shown below. How can i output the communities object in a graph ? I tried using plot(communities) but i got does not support plotting. import igraph as ig from edgeboost.EdgeBoost import CommunityEdgeBoost G = ig.Graph.Erdos_Renyi(200,0.1) #creates EdgeBoost object ... edgeBooster = CommunityEdgeBoost(lambda x:x.community_multilevel(),"common_neighbors",numIterations = 10) #detect communities ... communities = edgeBooster.detect_communities(G) print communities [[0, 34, 55, 57, 94, 136, 191, 105, 116, 124, 170], [1, 24, 36, 98, 100, 142, 150, 173, 38, 43, 44, 51, 66, 69, 84, 97, 141, 155, 185], [2, 74, 83, 6, 31, 48, 109, 113, 121, 127, 160, 163, 174, 175], .....]
favorite count: 0
accepted answer: http://stackoverflow.com/a/51268474

http://stackoverflow.com/comment/88611658
type: AnswerComment
has text: @JasonMond just the same, stdin or IPC. `multiprocessing` uses `pickle` under the hood, so it's as simple as `pickle.dump(args,process.stdin)` and `.load(sys.stdin)` on the other end (`sys.stdin.buffer` in Py3 to read in binary mode).
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50785581

http://stackoverflow.com/comment/88651851
type: QuestionComment
comment on: http://stackoverflow.com/q/50822925
score: 0
has text: ......I'm embarassed, I didn't think the ordering would matter but of course it does. Thank you and I'm sorry for wasting your time
type: Comment

http://stackoverflow.com/q/50767199
type: AnsweredQuestion
tagged with: tkinter
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50767382
accepted answer: http://stackoverflow.com/a/50767382
type: Question
has body: I'm creating a Scale slider that will be used to select a Hue. I am wondering if I can set the trough to be more than one color, so it would look something like the google color slider. I'm aware of the troughcolor config option for Scale, but it only accepts one color. I have a Hue2RGB function that will make getting the color gradient easy, but I need a way to color the trough pixel-by-pixel. I've seen this answer, but the poster doesn't explain how they get the color on the trough in the first place. For those more familiar with Tkinter, could I subclass Scale and and override some sort of draw_trough function?
linked to: http://stackoverflow.com/q/30688639
upvote count: 1
has comment: http://stackoverflow.com/comment/88542645
answer count: 1
favorite count: 0
tagged with: colors
tagged with: slider
has title: Python Tkinter: Change scale trough to be multicolor gradient
tagged with: python

http://stackoverflow.com/comment/88563272
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50778163
has text: The alternative (edit: meaning `set.intersection`) is not lazy, so I would prefer using `any`.
type: AnswerComment

http://stackoverflow.com/a/50782754
score: 13
downvote count: 0
has comment: http://stackoverflow.com/comment/88572053
type: Answer
has body: Similar to daveruinseverything's answer, I'd solve this with a Counter, but make use of its update method. Let signals be your list of dicts. &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; c = Counter() &gt;&gt;&gt; for d in signals: ... c.update(d) ... &gt;&gt;&gt; c Counter({'signal_4': 27, 'signal_7': 24, 'signal_1': 21, 'signal_3': 18, 'signal_10': 15, 'signal_2': 15, 'signal_9': 12, 'signal_6': 9, 'signal_5': 6, 'signal_8': 3}) For Op's sake, can you briefly describe what's happening here? A Counter works similar to a dict, but its update method adds values to the values of pre-existing keys instead of overriding them.
upvote count: 13
answers question: http://stackoverflow.com/q/50782327

http://stackoverflow.com/a/50754806
has comment: http://stackoverflow.com/comment/88525369
downvote count: 0
answers question: http://stackoverflow.com/q/50734776
type: Answer
has body: Consider what the where statement in your fortran code implies: "assign to each element of z_ocean, where the corresponding element value from mldclim[i, :, :] is greater than the element value in z_ocean, the element value from mldclim[i, :, :]" Edit: I modified the definition above to better reflect the fact that this is an elementwise operation, as stated in a comment by @francescalus Looking at the documentation for numpy.where(), it can be used as where(*condition*, *value if true*, *value if false*). So in your case, something like this: z_ocean = np.where(mldclim[i, :, :] &gt; z_ocean, mldclim[i, :, :], z_ocean) Here are examples in python (note that I've swapped around index order in python for direct comparison) import numpy as np nstep_yr = 2 # initialize randomly # mldclim = np.random.rand(nstep_yr, 3, 3) - 0.5 # use these values for fortran comparison mldclim = np.reshape([ 0.09911714, 0.18911965, 0.30409478, -0.08548523, \ -0.03652424, -0.18361127, 0.49970408, -0.04139379, \ -0.03451338, -0.24631131, 0.35726568, -0.30630386, \ 0.26184705, 0.01286879, -0.21745516, 0.46137956, \ 0.40410629, 0.29996342], (nstep_yr, 3, 3) ) # initialize and make a copies for testing... z_ocean = np.zeros((3,3)) z_ocean_1 = np.copy(z_ocean) z_ocean_2 = np.copy(z_ocean) for i in range(nstep_yr): # "direct translation" of your fortran code z_ocean = np.where(mldclim[i, :, :] &gt; z_ocean, mldclim[i, :, :], z_ocean) # loop based version of @francescalus' comment z_ocean_1 = np.maximum(z_ocean_1, mldclim[i, :, :]) # loop free version of @francescalus' comment z_ocean_2 = np.maximum(z_ocean_2, np.max(mldclim, axis=0)) # check that all solutions are the same assert np.allclose(z_ocean, z_ocean_1) and np.allclose(z_ocean, z_ocean_2) print(z_ocean.ravel()) and fortran (replicating your original code sample) program test implicit none integer, parameter :: nstep_yr = 2 real :: mldclim(3,3,nstep_yr) real :: z_ocean(3,3) integer :: i mldclim = reshape([ 0.09911714, 0.18911965, 0.304094…
has comment: http://stackoverflow.com/comment/88520963
upvote count: 1
score: 1

http://stackoverflow.com/comment/88526276
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50759281
type: AnswerComment
has text: The fact it's a windows filesystem is mostly irrelevant - you cannot `open()` a directory in Linux either (but the error message is more accurate: "[Errno 21] Is a directory")

http://stackoverflow.com/comment/88455401
score: 0
type: AnswerComment
has text: That helped. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/50722947

http://stackoverflow.com/a/50825327
has comment: http://stackoverflow.com/comment/88717099
answers question: http://stackoverflow.com/q/50822739
type: Answer
downvote count: 0
has body: Your problem has the exact same origin as it is written in the pandas documentation you linked. Look at the minimal example they provided there: def do_something(df): foo = df'bar', 'baz' # Is foo a view? A copy? Nobody knows! # ... many lines here ... foo['quux'] = value # We don't know whether this will modify df or not! return foo The problem is that foo might either be a copy of the dataframe df or a view. If it is a view, then changes on foo will also affect the original dataframe df. If foo is a copy, then the line foo['quux'] = value will have no effect on df. How does this now translate to your problem? You start with creating a dataframe from a *.csv file: raw_data = pd.read_csv("IMF and BBG Fair Values.csv") Then you select the columns "IMF_VALUE", "BBG_FV", "IMF_DATE" from the dataframe raw_data in the following way: ISO_TH = raw_data"IMF_VALUE", "BBG_FV", "IMF_DATE" Now, this looks very similar to the second line from the documentation: foo = df'bar', 'baz' Is your ISO_TH a view or a copy of raw_data? We don't now! So what happens if we change a column of ISO_TH? Does raw_data also change or not? We don't now and hence the warning. Toy example: import pandas as pd import numpy as np raw_data=pd.DataFrame([[np.inf,22,333,44], [3,4,5,2],[1,2,3,4],[np.inf,0,0,0]],columns=["BBG_FV", "IMF_VALUE", "IMF_DATE", "unused"]) ISO_TH = raw_data"IMF_VALUE", "BBG_FV", "IMF_DATE" # if we now change ISO_TH, we get a warning ISO_TH.IMF_VALUE=[0,0,0,0] # SettingWithCopyWarning The fact that you create an intermediate object filtered_TH from ISO_TH changes nothing here. How can we solve this? Easy, we read the docs and do what is written there! ISO_TH = raw_data.loc[:,["IMF_VALUE", "BBG_FV", "IMF_DATE"]] And continue as before. Additional information: What rules does Pandas use to generate a view vs a copy?
has comment: http://stackoverflow.com/comment/88724514
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88691295
has comment: http://stackoverflow.com/comment/88694413

http://stackoverflow.com/a/50735552
has body: Try setting python version as an environmental variable. npm config --global set python /usr/bin/python2.7 You can read more about this in this issue
type: Answer
has comment: http://stackoverflow.com/comment/88484123
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50731830
answers question: http://stackoverflow.com/q/50731830
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50702224
tagged with: python
has title: Filter out rows of panda-df by comparing to list
answer count: 1
score: 8
linked to: http://stackoverflow.com/q/17071871
duplicate of: http://stackoverflow.com/q/19960077
has answer: http://stackoverflow.com/a/50702262
has comment: http://stackoverflow.com/comment/88413772
duplicate of: http://stackoverflow.com/q/17071871
has body: The following problem occurs often. Say I have a dataframe, where one column can take a discrete value: df = pd.DataFrame({'col1': [1, 2,3,4,5,6,7], 'col2': ["A", "B", "A", "C", "B", "A", "D"]}) In this case col2 can take values A, B or C. I only want to rows where col2 is not equal to A or B. I thought the following syntax would work, df["col2"] not in ["A", "B"] However, this gives me the error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Is there a neat way to filter those rows out?
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
favorite count: 0
upvote count: 8
accepted answer: http://stackoverflow.com/a/50702262
type: Question

http://stackoverflow.com/q/50849653
has title: python: function with parameters and gather input then print return value
has comment: http://stackoverflow.com/comment/88702111
has answer: http://stackoverflow.com/a/50849750
tagged with: python
favorite count: 0
downvote count: 5
type: UnansweredQuestion
has body: I'm currently going through beginner Python course in EDX and need help on one of its Required Coding Activity. Program: fishstore() create and test fishstore() fishstore() takes 2 string arguments: fish &amp; price fishstore returns a string in sentence form gather input for fish_entry and price_entry to use in calling fishstore() print the return value of fishstore() example of output: Fish Type: Guppy costs $1
upvote count: 0
score: -5
has answer: http://stackoverflow.com/a/57974216
type: Question
answer count: 2

http://stackoverflow.com/q/50805994
answer count: 2
possible better answer: http://stackoverflow.com/a/59743097
tagged with: pyspark
score: 0
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/50898254
has comment: http://stackoverflow.com/comment/88720345
has comment: http://stackoverflow.com/comment/88618392
has comment: http://stackoverflow.com/comment/88617985
has title: Pyspark: How to create a flag for the first time a variable is seen
tagged with: python
has body: I have a set of variables that that a timestamp and a session. How would I make a New Session Indicator that is 1 for the first time a session is seen and 0 for every instance of that session thereafterwards. For instance... from pyspark.sql import functions as F df = sqlContext.createDataFrame([ ("a", "44", "2018-01-08 09:01:01.085193"), ("a", "44", "2018-01-08 09:01:01.086280"), ("a", "44", "2018-01-08 09:01:01.087681"), ("a", "95", "2018-01-15 12:01:01.544710"), ("a", "95", "2018-01-15 13:01:01.545991"), ], ["person_id", "session_id", "timestamp"]) df = df.withColumn('unix_ts',F.unix_timestamp(df.timestamp, 'yyyy-MM-dd HH:mm:ss')) df = df.withColumn("DayOfWeek",F.date_format(df.timestamp, 'EEEE')) df.show() Yields +---------+----------+--------------------+----------+---------+ |person_id|session_id| timestamp| unix_ts|DayOfWeek| +---------+----------+--------------------+----------+---------+ | a| 44|2018-01-08 09:01:...|1515423661| Monday| | a| 44|2018-01-08 09:01:...|1515423661| Monday| | a| 44|2018-01-08 09:01:...|1515423661| Monday| | a| 95|2018-01-15 12:01:...|1516039261| Monday| | a| 95|2018-01-15 13:01:...|1516042861| Monday| +---------+----------+--------------------+----------+---------+ I want to have add a column giving this output: +---------+----------+--------------------+----------+---------+----------+ |person_id|session_id| timestamp| unix_ts|DayOfWeek| FirstInd | +---------+----------+--------------------+----------+---------+----------+ | a| 44|2018-01-08 09:01:...|1515423661| Monday| 1 | | a| 44|2018-01-08 09:01:...|1515423661| Monday| 0 | | a| 44|2018-01-08 09:01:...|1515423661| Monday| 0 | | a| 95|2018-01-15 12:01:...|1516039261| Monday| 1 | | a| 95|2018-01-15 13:01:...|1516042861| Monday| 0 | +---------+----------+--------------------+----------+---------+----------+
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50898254
has answer: http://stackoverflow.com/a/59743097
type: Question

http://stackoverflow.com/q/50816879
has body: I am trying to automate my iPad to tap different coordinate points with Appium. I am using the command below: self.driver.execute_script('mobile: tap', {x:, y:}) This command requires that the x and y variable be an integer, but I want to be able to randomize the numbers that could be x and y with random.randint, but it insist that it will only accept an integer. Is there a way to do this?
tagged with: mobile
has comment: http://stackoverflow.com/comment/88639215
has comment: http://stackoverflow.com/comment/88638976
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/88639046
type: Question
tagged with: automation
tagged with: appium
tagged with: ios
has comment: http://stackoverflow.com/comment/88638832
has title: How to implement random.randint for appium 'mobile': 'tap'

http://stackoverflow.com/q/50779544
has title: 'Friend' has no attribute 'META' error unknown reason - django
tagged with: django-templates
tagged with: django-views
has body: I have a view and template that create queries that search through objects in the database. I also have lists that will create a list of usernames based on different querysets. I pass the searched queryset and two lists which are pending and friends. I then check to see if the usernames in the search query are located in the list. if they in the list it will display a different message depending on the list it is located in. if it is not located in any list, it will display a different message. error + trace: AttributeError at /search/ 'Friend' object has no attribute 'META' Request Method: POST Request URL: http://127.0.0.1:8000/search/ Django Version: 2.0.5 Exception Type: AttributeError Exception Value: 'Friend' object has no attribute 'META' Exception Location: /Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/template/context_processors.py in debug, line 40 Python Executable: /Users/omarjandali/anaconda3/envs/MySplit/bin/python Python Version: 3.6.2 Python Path: ['/Users/omarjandali/Desktop/mysplit/mysplit', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python36.zip', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/lib-dynload', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages'] here is the code: if request.method == "POST": search = request.POST['search'] searched = User.objects.filter(username__contains = search).all() searched |= User.objects.filter(first_name__contains = search).all() searched |= User.objects.filter(last_name__contains = search).all() requester = Friend.objects.filter(user = user).filter(requested = True).all() requested = Friend.objects.filter(friend = user.username).filter(requested = True).all() friended = Friend.objects.filter(user = user).filter(accepted = True).all() friender = Friend.objects.filter(friend = user.username).filter(accepted = True).all() pending = [] for request in requester: pending.append(request.frien…
type: Question
has comment: http://stackoverflow.com/comment/88566525
score: 0
answer count: 1
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/50783555
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/88678263
comment on: http://stackoverflow.com/q/50835541
score: 0
type: Comment
type: QuestionComment
has text: @MelvinAbraham Yes.

http://stackoverflow.com/comment/88639578
type: QuestionComment
has text: But does odoo run your method when clicking the button? Did you try to change other field? Maybe 'school_name' it is computed or related?
comment on: http://stackoverflow.com/q/50815485
score: 0
type: Comment

http://stackoverflow.com/q/50825707
type: UnansweredQuestion
tagged with: python
has title: Label and tick marks disappear when using log scale in matplotlib python
has comment: http://stackoverflow.com/comment/88735501
tagged with: plot
has comment: http://stackoverflow.com/comment/88734645
linked to: http://stackoverflow.com/q/39026653
has comment: http://stackoverflow.com/comment/88688456
has answer: http://stackoverflow.com/a/50826003
tagged with: matplotlib
has body: I need the y-axis of my graph to be on a log scale. When I do so, however, the y-axis' label, tick marks, and title disappear. plt.figure(2) plt.semilogy(data2[0, :, 0], sli) plt.xlabel('n-value') plt.ylabel('Intensity') plt.title('Intensity vs. n-shell') plt.show() The sli values range from 1.0e-21 to 1.0e-8 When I zoom in far enough though, the label and title actually return but not the tick marks. Don't know if that matters, but thought I'd include it. Thanks Edit: As it turns out, the code works fine, just not on my mac laptop. I tested the code on a friends computer running ubuntu and it worked perfectly. So, I guess my log scales don't like macs. Still, anybody have any suggestions? "Update" for @ImportanceOfBeingErnest Nothing has changed. Graph produced from my code run with updated mplib Graph produced from @Engineero 's code run with updated mplib
has comment: http://stackoverflow.com/comment/88660202
has comment: http://stackoverflow.com/comment/88687083
has comment: http://stackoverflow.com/comment/88687755
has comment: http://stackoverflow.com/comment/88661011
has comment: http://stackoverflow.com/comment/88671762
type: Question
has comment: http://stackoverflow.com/comment/88660623
tagged with: logarithm
has comment: http://stackoverflow.com/comment/88736331
score: 0
tagged with: scale
answer count: 1
has comment: http://stackoverflow.com/comment/88660735

http://stackoverflow.com/q/50841165
type: UnansweredQuestion
downvote count: 2
upvote count: 7
has answer: http://stackoverflow.com/a/50841635
has comment: http://stackoverflow.com/comment/88687896
linked to: http://stackoverflow.com/q/216972
type: Question
has answer: http://stackoverflow.com/a/50841867
has body: Sometimes it's nice to be able to use a dictionary like an object (so that you don't have to always write mydict['blah']. Instead, you can write mydict.blah In Python 3, there are new rules about overriding/wrapping a python dictionary. In Python2, it was enough to wrap the __getattr__ and __setattr__ methods. When you wrap these things, you get some nice capabilities to add some special handling when a certain attribute was added (e.g. you could clean/filter data in/out of a dict). A situation where this is helpful is in a Flask template (an HTML template). Using a __getattr__ filter, you can format data as it leaves the dict. This way, in the template (where Python expressions can look a little complex) you can keep things simple in there by just writing mymodel.blah and knowing that the text coming out of blah is already the way you want it. In Python3 wrapping a dict is a little messy. I"m not sure how to make it work now. Here are two rough implementations that are not working well: # messed up Python3 wrapped dictionary (sets work, but gets do not) class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self self.clean_strings() def clean_strings(self): for key, value in self.items(): self[key] = string_empty_to_none(value) def __getattr__(self, name): #this never gets called in Python 3 return self[name] Here's another one: # sets don't work - Always throws: TypeError: 'AttrDict' object does not support item assignment class AttrDict(): def __init__(self, *args, **kwargs): self.data = dict() self.data.__init__(*args, **kwargs) self.clean_strings() def clean_strings(self): for key, value in self.data.items(): self.data[key] = string_empty_to_none(value) def __getattr__(self, attr): if attr in self.data: return self.data[attr] else: raise AttributeError("--%r object has no attribute %r" % (type(self).__name__, attr)) def __setattr__(self, name, value): if name == 'data': super(AttrDict, self).__…
score: 5
favorite count: 0
has answer: http://stackoverflow.com/a/58285216
answer count: 3
tagged with: python
tagged with: dictionary
has title: How to correctly wrap a dict in Python 3?
tagged with: python-3.x

http://stackoverflow.com/comment/88609546
score: 0
type: Comment
has text: Thank you! Will digest this (never seen yield from before). Hate to bother you more but while you are here, what can I add to this function to make it only give Trues for consecutive values that aren't 0?
type: AnswerComment
comment on: http://stackoverflow.com/a/50801727

http://stackoverflow.com/comment/88611693
type: QuestionComment
comment on: http://stackoverflow.com/q/50802824
has text: Why do you want to use `list comprehension` here? It is basically used to create new lists. You can use it but you shouldn't. It will also have the same for loops with condition.
score: 6
type: Comment

http://stackoverflow.com/comment/88567450
type: QuestionComment
type: Comment
has text: No problem, thanks for providing more info. If each line ends with E, how do you know when to stop reading new lines from the serial port? From your code above, it looks a lot like only the last line ends with E.
score: 0
comment on: http://stackoverflow.com/q/50780220

http://stackoverflow.com/comment/88511106
has text: From a quick glance, you have at least two `def printcoords` definitions in your code. Which one are you expecting to run?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50751630
score: 0

http://stackoverflow.com/q/50824438
has comment: http://stackoverflow.com/comment/88654153
has comment: http://stackoverflow.com/comment/88653867
has answer: http://stackoverflow.com/a/50824625
tagged with: centos
score: 0
has comment: http://stackoverflow.com/comment/88654082
answer count: 1
has comment: http://stackoverflow.com/comment/88653910
has title: Flattening the list in python
tagged with: python-3.x
has body: I have a list called normalized_rec, it has: normalized_rec = [['rchan', 'pts/9', '10.40.91.236', 'Thu', 'Feb', '15', '00:00:00', '2018', '-', 'Tue', 'Feb', '15', '16:57:02', '2018', '(00:03)', [['rchan', 'pts/9', '10.40.91.236', 'Wed', 'Feb', '14', '00:00:00', '2018', '-', 'Wed', 'Feb', '14', '23:59:59', '2018', '(00:03)'], 'rchan', 'pts/9', '10.40.91.236', 'Thu', 'Feb', '15', '00:00:00', '2018', '-', 'Tue', 'Feb', '15', '16:57:02', '2018', '(00:03)']], [['rchan', 'pts/9', '10.40.91.236', 'Tue', 'Feb', '13', '16:53:42', '2018', '-', 'Tue', 'Feb', '13', '23:59:59', '2018', '(00:03)'], ['rchan', 'pts/9', '10.40.91.236', 'Thu', 'Feb', '15', '00:00:00', '2018', '-', 'Tue', 'Feb', '15', '16:57:02', '2018', '(00:03)', [['rchan', 'pts/9', '10.40.91.236', 'Wed', 'Feb', '14', '00:00:00', '2018', '-', 'Wed', 'Feb', '14', '23:59:59', '2018', '(00:03)'], 'rchan', 'pts/9', '10.40.91.236', 'Thu', 'Feb', '15', '00:00:00', '2018', '-', 'Tue', 'Feb', '15', '16:57:02', '2018', '(00:03)']]], ['cwsmith', 'pts/6', '10.40.43.94', 'Tue', 'Feb', '13', '16:51:47', '2018', '-', 'Tue', 'Feb', '13', '16:56:13', '2018', '(00:04)'], ['mlee18', 'pts/6', '10.40.43.94', 'Tue', 'Feb', '13', '16:50:20', '2018', '-', 'Tue', 'Feb', '13', '16:51:27', '2018', '(00:01)'], ['hfang', 'pts/4', '24.114.50.50', 'Tue', 'Feb', '13', '16:31:38', '2018', '-', 'Tue', 'Feb', '13', '17:48:39', '2018', '(01:17)'], ['bigia', 'pts/8', '24.114.50.50', 'Tue', 'Feb', '13', '19:28:43', '2018', '-', 'Tue', 'Feb', '13', '20:28:31', '2018', '(00:59)'], ['rchan', 'pts/2', '10.40.105.130', 'Tue', 'Feb', '13', '16:22:00', '2018', '-', 'Tue', 'Feb', '13', '16:45:00', '2018', '(00:23)'], ['asmith', 'pts/2', '10.43.115.162', 'Tue', 'Feb', '13', '16:19:29', '2018', '-', 'Tue', 'Feb', '13', '16:22:00', '2018', '(00:02)'], ['tsliu2', 'pts/4', '10.40.105.130', 'Tue', 'Feb', '13', '16:17:21', '2018', '-', 'Tue', 'Feb', '13', '16:30:10', '2018', '(00:12)'], ['mshana', 'pts/13', '10.40.91.247', 'Tue', 'Feb', '13', '16:07:5…
has comment: http://stackoverflow.com/comment/88653874
tagged with: python
linked to: http://stackoverflow.com/q/952914
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/50824625
type: Question
has comment: http://stackoverflow.com/comment/88659514
has comment: http://stackoverflow.com/comment/88654226

http://stackoverflow.com/a/50819719
upvote count: 3
has comment: http://stackoverflow.com/comment/88644911
score: 3
has comment: http://stackoverflow.com/comment/112039131
type: AcceptedAnswer
has body: You could parse the lines in the file to a new file, replacing the characters as you go. This swaps single quotes for &amp;apos;, and then double quotes for single. with open('file1.xml') as fp_in: with open('file2.xml') as fp_out: for line in fp_in: fp_out.write(line.replace("'", '&amp;apos;').replace('"', "'"))
downvote count: 0
answers question: http://stackoverflow.com/q/50819445
type: Answer
accepted answer of: http://stackoverflow.com/q/50819445

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/50781084
tags question: http://stackoverflow.com/q/50805355
tags question: http://stackoverflow.com/q/50844230
tags question: http://stackoverflow.com/q/50711739
tags question: http://stackoverflow.com/q/50796212
tags question: http://stackoverflow.com/q/50707913
tags question: http://stackoverflow.com/q/50795928
tags question: http://stackoverflow.com/q/50709437
tags question: http://stackoverflow.com/q/50700585
tags question: http://stackoverflow.com/q/50810190
tags question: http://stackoverflow.com/q/50742621
tags question: http://stackoverflow.com/q/50843586
tags question: http://stackoverflow.com/q/50847058
tags question: http://stackoverflow.com/q/50829366
tags question: http://stackoverflow.com/q/50730315
tags question: http://stackoverflow.com/q/50793321
tags question: http://stackoverflow.com/q/50841994
tags question: http://stackoverflow.com/q/50786561
tags question: http://stackoverflow.com/q/50780606
tags question: http://stackoverflow.com/q/50794434
tags question: http://stackoverflow.com/q/50830903
tags question: http://stackoverflow.com/q/50730818
tags question: http://stackoverflow.com/q/50795055
tags question: http://stackoverflow.com/q/50743376
tags question: http://stackoverflow.com/q/50782318
tags question: http://stackoverflow.com/q/50840778
tags question: http://stackoverflow.com/q/50817496
tags question: http://stackoverflow.com/q/50808720
tags question: http://stackoverflow.com/q/50707139
tags question: http://stackoverflow.com/q/50822463
type: Tag
tags question: http://stackoverflow.com/q/50733805
tags question: http://stackoverflow.com/q/50846431
tags question: http://stackoverflow.com/q/50794146
tags question: http://stackoverflow.com/q/50843824
tags question: http://stackoverflow.com/q/50830618
tags question: http://stackoverflow.com/q/50792833
tags question: http://stackoverflow.com/q/50707239
tags question: http://stackoverflow.com/q/50731989
tags question: http://stackoverflow.com/q/50783518
tags question: http://stackoverflow.com/q/50710251
tags question: http://stackoverflow.com/q/50750861
tags question: http://stackoverflow.com/q/50832814
tags question: http://stackoverflow.com/q/50850120
tags question: http://stackoverflow.com/q/50782383
tags question: http://stackoverflow.com/q/50809943
tags question: http://stackoverflow.com/q/50779567
tags question: http://stackoverflow.com/q/50807817
tags question: http://stackoverflow.com/q/50736874
tags question: http://stackoverflow.com/q/50847060
tags question: http://stackoverflow.com/q/50853858
tags question: http://stackoverflow.com/q/50779557
tags question: http://stackoverflow.com/q/50786175
tags question: http://stackoverflow.com/q/50788082
tags question: http://stackoverflow.com/q/50748753
tags question: http://stackoverflow.com/q/50819224
tags question: http://stackoverflow.com/q/50723226
tags question: http://stackoverflow.com/q/50791275
tags question: http://stackoverflow.com/q/50757430
tags question: http://stackoverflow.com/q/50708061
tag name: json
tags question: http://stackoverflow.com/q/50833184
tags question: http://stackoverflow.com/q/50846418
tags question: http://stackoverflow.com/q/50831165
tags question: http://stackoverflow.com/q/50755977
tags question: http://stackoverflow.com/q/50799076
tags question: http://stackoverflow.com/q/50724369
tags question: http://stackoverflow.com/q/50801202
tags question: http://stackoverflow.com/q/50826609
tags question: http://stackoverflow.com/q/50741843
tags question: http://stackoverflow.com/q/50715123
tags question: http://stackoverflow.com/q/50831840
tags question: http://stackoverflow.com/q/50759458
tags question: http://stackoverflow.com/q/50754643
tags question: http://stackoverflow.com/q/50783006
tags question: http://stackoverflow.com/q/50828886
tags question: http://stackoverflow.com/q/50778569
tags question: http://stackoverflow.com/q/50752320
tags question: http://stackoverflow.com/q/50763186
tags question: http://stackoverflow.com/q/50837752

http://stackoverflow.com/comment/88726873
comment on: http://stackoverflow.com/q/50845646
type: Comment
score: 0
has text: In matplotlib 2.2.2 you need to use `plt.xkcd` inside a context, see [official example](https://matplotlib.org/gallery/showcase/xkcd.html). This will solve the "run this in script"-problem.
type: QuestionComment

optimization
tags question: http://stackoverflow.com/q/50737705
tags question: http://stackoverflow.com/q/50808414
tags question: http://stackoverflow.com/q/50718293
tags question: http://stackoverflow.com/q/50815015
tags question: http://stackoverflow.com/q/50797596
tags question: http://stackoverflow.com/q/50816594
tags question: http://stackoverflow.com/q/50749481
tags question: http://stackoverflow.com/q/50799903
tags question: http://stackoverflow.com/q/50739860
tags question: http://stackoverflow.com/q/50753594
tags question: http://stackoverflow.com/q/50772362
tags question: http://stackoverflow.com/q/50735112
tags question: http://stackoverflow.com/q/50743411
tags question: http://stackoverflow.com/q/50784474
tags question: http://stackoverflow.com/q/50726104
tags question: http://stackoverflow.com/q/50723432
tags question: http://stackoverflow.com/q/50774022
tags question: http://stackoverflow.com/q/50841770
tags question: http://stackoverflow.com/q/50727616
tags question: http://stackoverflow.com/q/50787624
tags question: http://stackoverflow.com/q/50770569
tags question: http://stackoverflow.com/q/50763783
tag name: optimization
tags question: http://stackoverflow.com/q/50793435
tags question: http://stackoverflow.com/q/50786498
tags question: http://stackoverflow.com/q/50713833
tags question: http://stackoverflow.com/q/50783355
tags question: http://stackoverflow.com/q/50790266
tags question: http://stackoverflow.com/q/50760278
tags question: http://stackoverflow.com/q/50800858
type: Tag

http://stackoverflow.com/a/50807161
has body: dir has always helped me, esp when dealing with not so well documented interfaces. Unlike ndarray. dir(np.array([])) ['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_wrap__', '__class__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__delslice__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__', '__ilshift__', '__imod__', '__imul__', '__index__', '__init__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setslice__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofi…
answers question: http://stackoverflow.com/q/50764517
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88632202

http://stackoverflow.com/comment/88660441
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50827704
has text: I would want to have the function returning the wanted value. At the 8th sequence, I would like it to do nothing.
score: 0

http://stackoverflow.com/q/50844230
tagged with: http://stackoverflow.com/tag/json
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/88716922
linked to: http://stackoverflow.com/q/5631078
downvote count: 0
tagged with: jsonb
upvote count: 3
tagged with: postgresql
has comment: http://stackoverflow.com/comment/88696653
favorite count: 0
has body: I'm trying to get a sql statement for inserting JSONB but I get a Not Implemented Error. I am using sqlalchemy 1.2.8 and python 3.6.4. The following is the code I'm using: import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.dialects.postgresql import JSONB tbl = sa.table('test', sa.Column('a', sa.types.Integer, primary_key=True), sa.Column('b', sa.types.Text, primary_key=True), sa.Column('j', JSONB)) a=1 b="bar" j = {"a1":"foo1", "b1":"bar1"} str(tbl.insert().values(a=a, b=b, j=j).compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True})) I get error: /usr/local/lib/python3.6/site-packages/sqlalchemy/sql/compiler.py in render_literal_value(self, value, type_) 1293 else: 1294 raise NotImplementedError( -&gt; 1295 "Don't know how to literal-quote value %r" % value) 1296 1297 def _truncate_bindparam(self, bindparam): NotImplementedError: Don't know how to literal-quote value {'a1': 'foo1', 'b1': 'bar1'} Any assistance is greatly appreciated!
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 3
has title: SQLAlchemy Postgres can't compile JSONB insert instruction

http://stackoverflow.com/a/60673209
upvote count: 14
has comment: http://stackoverflow.com/comment/108169934
score: 14
downvote count: 0
has body: Essentially, the pandas.to_html() just exports a plain HTML table. You can insert the table wherever you want in the body and control the style via CSS in the style section. &lt;html&gt; &lt;head&gt; &lt;style&gt; table, th, td {{font-size:10pt; border:1px solid black; border-collapse:collapse; text-align:left;}} th, td {{padding: 5px;}} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; { pandas.to_html() } &lt;/body&gt; &lt;/html&gt;
answers question: http://stackoverflow.com/q/50807744
has comment: http://stackoverflow.com/comment/126603246
type: Answer

http://stackoverflow.com/q/50750555
type: Question
has body: Is there a way to use the Django timestamp without using a model? I want to write the timestamp to a file. The reason I want to use the Django one and not datetime or time from python is because I already set the Time Zone for it in settings so it would be more convenient if I could just use that.
has comment: http://stackoverflow.com/comment/88509105
score: 3
has title: Django timestamp
answer count: 2
has comment: http://stackoverflow.com/comment/88509275
downvote count: 0
possible better answer: http://stackoverflow.com/a/50750674
favorite count: 0
tagged with: time
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50750670
accepted answer: http://stackoverflow.com/a/50750670
type: AnsweredQuestion
upvote count: 3
tagged with: file
has answer: http://stackoverflow.com/a/50750674

http://stackoverflow.com/q/50713721
has body: I am looking to get percentages of done trades to total trades per month. Previously my data was only for a single month and solved by: total_trades = df['state'].count() RFQ_Hit_Rate = done_trades / total_trades RFQ_Hit_Rate = round(RFQ_Hit_Rate, 6) There are now 12 months of data so I need to update the code. New data dfHit_Rate_All = df'Year_Month','state'.copy() dfHit_Rate_All = dfHit_Rate_All.groupby(['Year_Month','state']).size().reset_index(name='count') Year_Month state Counts 2017-11 Customer Reject 1 2017-11 Customer Timeout 2 2017-11 Dealer Reject 3 2017-12 Dealer Timeout 4 2017-12 Done 5 2017-12 Done 6 2018-01 Tied Covered 7 2018-01 Tied Done 8 2018-01 Tied Traded Away 9 2018-02 Traded Away 10 2018-02 Done 11 2018-02 Customer Reject 12 For each month find the total trades, the total Done Trades and calculate the ratio. Note any string with 'Done' in it is a done trade i.e. [df['state'].str.contains('Done'): Year_Month Total_state_count Total_state_count_Done Done_To_Total_Ratio 2017-11 6 0 0% 2017-12 15 11 73% 2018-01 24 8 33% 2018-02 33 11 33%
has answer: http://stackoverflow.com/a/50713824
accepted answer: http://stackoverflow.com/a/50713824
tagged with: python
downvote count: 0
score: 1
type: AnsweredQuestion
tagged with: group-by
type: Question
has title: Pandas GroupBy each month then subtotal counts based on string in a column
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88488300
type: AnswerComment
has text: yes, location coordinates are always in order and can be repeated as object can go back to previous position and the pivoting is done from the current position ( which was on the target coordinates) and the next position ( which is also in the target coordinates) and this continues until all coordinates are checked :). Thank you again
comment on: http://stackoverflow.com/a/50739932
score: 0
type: Comment

http://stackoverflow.com/comment/88581996
score: 0
type: Comment
has text: If your problem is solved you should accept the answer :)
type: AnswerComment
comment on: http://stackoverflow.com/a/50787797

http://stackoverflow.com/a/50782088
score: 3
has body: You can use pandas' round() method. print(df2['t_stamp'].dt.round('min').dt.strftime('%Y-%m-%d %H:%M')) 0 2017-11-07 12:31 1 2017-11-07 14:19 2 2017-11-07 12:32 Name: t_stamp, dtype: object
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50781973
type: Answer
answers question: http://stackoverflow.com/q/50781973

http://stackoverflow.com/comment/88538125
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50753692
has text: actually i forgot a return statement *facepalm*, the variable expression actually still works but I still changed it to `redirect_uri`

http://stackoverflow.com/q/50784367
has answer: http://stackoverflow.com/a/50786771
downvote count: 0
answer count: 1
tagged with: msys
favorite count: 0
tagged with: python-3.x
tagged with: msys2
tagged with: python
has body: I need to install the Python development tools on MSYS2. My Python installation works (by either calling python3.6 or python3: $ python3.6 Python 3.6.5 (default, Apr 16 2018, 10:17:38) [GCC 7.3.0 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; Setuptools is installed: $ pip3 install setuptools Requirement already satisfied: setuptools in /usr/lib/python3.6/site-packages (36.4.0) I have tried to install as it suggested in How to install python developer package?. MSYS2 does not have yum so I used pacman: $ pacman -S python-devel error: target not found: python-devel $ pacman -S python3-devel error: target not found: python3-devel $ pacman -S python3.6-devel error: target not found: python3.6-devel $ pacman -S python-dev error: target not found: python-dev $ pacman -S python3-dev error: target not found: python3-dev $ pacman -S python3.6-dev error: target not found: python3.6-dev So far this has all failed. How can I get the Python development tools?
linked to: http://stackoverflow.com/q/6230444
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50786771
tagged with: installation
score: 9
type: Question
upvote count: 9
has title: How to install Python Development tools on MSYS2

http://stackoverflow.com/comment/129444780
type: Comment
score: 3
comment on: http://stackoverflow.com/a/58805490
type: AnswerComment
has text: Consider `itertools.product` for that deeply nested loop.

openshift
tags question: http://stackoverflow.com/q/50749683
tag name: openshift
type: Tag
tags question: http://stackoverflow.com/q/50788794
tags question: http://stackoverflow.com/q/50842083

http://stackoverflow.com/q/50719835
has comment: http://stackoverflow.com/comment/88448093
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50719934
type: Question
has answer: http://stackoverflow.com/a/50719934
score: 0
has title: Replacing numbers in various formats with a word
answer count: 2
has answer: http://stackoverflow.com/a/50719878
has body: I have a long sentence and I want to replace all numbers with a particular word. The numbers come in different formats, e.g., 36 010616 010516 - 300417 01-04 2011 12 Is there function in Python for replacing these types of occurences with a word (say, "integer"), or how does the regex look for these? Example: "This is a 10 sentence with date 010616 and intervals 06-08 200-209 01 - 09 in years 2012 26" should become "This is a NUMBER sentence with date NUMBER and intervals NUMBER NUMBER NUMBER in years NUMBER NUMBER"
accepted answer: http://stackoverflow.com/a/50719878
tagged with: python

http://stackoverflow.com/comment/88554232
type: AnswerComment
comment on: http://stackoverflow.com/a/50751419
type: Comment
has text: @guru, Sorry , I'm not sure. You might have to give a minimal example of data *which demonstrates how you get the error*. Otherwise, we may just be guessing.
score: 0

http://stackoverflow.com/q/50843369
favorite count: 0
accepted answer: http://stackoverflow.com/a/50843805
tagged with: oracle-sqldeveloper
has title: SQLAlchemy - get date that table was created
has body: I'm connecting to an Oracle database from sqlalchemy and I want to know when the tables in the database were created. I can access this information through the sql developer application so I know that it is stored somewhere, but I don't know if its possible to get this information from sqlalchemy. Also if its not possible, how should I be getting it?
tagged with: oracle-database
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: oracle11g
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/88690493
has answer: http://stackoverflow.com/a/50843805
downvote count: 0
answer count: 1

http://stackoverflow.com/a/50808589
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50808468
has body: commands.cooldown's second argument, per takes an interval in seconds, you can easily convert your desired hours and minutes into seconds by multiplying by their equivalent in seconds (1 min = 60 sec, 1 hour = 3600 sec). You can also create a wrapper function that does the converting for you: def cooldown(rate, per_sec=0, per_min=0, per_hour=0, type=commands.BucketType.default): return commands.cooldown(rate, per_sec + 60 * per_min + 3600 * per_hour, type) @bot.command(pass_context=True) @cooldown(1, per_min=5, per_hour=1, type=commands.BucketType.user) async def ping(ctx): msg = "Pong {0.author.mention}".format(ctx.message) await bot.say(msg) This will initiate a cooldown of 1 hour and 5 minutes.
has comment: http://stackoverflow.com/comment/88624192
has comment: http://stackoverflow.com/comment/88623056
upvote count: 3

http://stackoverflow.com/a/50803981
answers question: http://stackoverflow.com/q/50802082
score: 0
type: Answer
has body: Here is yet another approach. The two main insights are as follows: We can start by intersecting each list in df2 with values of df1. This way we can avoid considering redundant subsets of each row of df2. After step 1, df2 may contain duplicated sets. Collecting the duplicated may speed up the remaining computation. The remaining task is to consider every subset of df1 and count the number of occurrences. import pandas as pd import numpy as np from itertools import combinations from collections import Counter df1 = pd.DataFrame({"subject": ["a", "b", "c"]}) df2 = pd.DataFrame( { "subject_list": [ ["a", "b", "c", "x", "y", "z", "1", "2", "3"], ["b", "c"], ["a", "b"], ["b", "c"], ["c"], ] } ) s1 = set(df1.subject.values) def all_combs(xs): for k in range(1, len(xs) + 1): yield from combinations(xs, k) def count_combs(xs): return Counter(all_combs(xs)) res = ( df2.subject_list.apply(s1.intersection) .apply(frozenset) .value_counts() .reset_index() ) # (b, c) 2 # (c, b, a) 1 # (c) 1 # (b, a) 1 res2 = res["index"].apply(df1.subject.isin).mul(res.subject_list, axis=0) res2.columns = df1.subject # subject a b c # 0 0 2 2 # 1 1 1 1 # 2 0 0 1 # 3 1 1 0 res3 = pd.Series( { "_".join(comb): res2[comb][(res2[comb] &gt; 0).all(1)].sum(0).iloc[0] for comb in map(list, all_combs(df1.subject.values)) } ) # a 2 # b 4 # c 4 # a_b 2 # a_c 1 # b_c 3 # a_b_c 1 # dtype: int64

http://stackoverflow.com/a/50762852
score: 1
has body: itertools islice + cycle You can use itertools to create an iterator. This is a lazy solution which requires you to call next on the iterator over a specified range. from itertools import islice, cycle c = islice(cycle(days), 5, None) for _ in range(len(days)): print(next(c)) 5 6 0 1 2 3 4 Only recommended for small iterables: Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88536103
has comment: http://stackoverflow.com/comment/88534800
has comment: http://stackoverflow.com/comment/88534767
answers question: http://stackoverflow.com/q/50755708
downvote count: 0

http://stackoverflow.com/comment/88681115
comment on: http://stackoverflow.com/a/50838435
type: AnswerComment
score: 0
type: Comment
has text: I think yes, it is `rolling`

http://stackoverflow.com/comment/88579867
has text: @quamrana That is true, however, in the shared code self.training_data is being defined inside a method(train_on_data), so if there is an invocation of that variable in any other method without running train_on_data first, it would give error
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50786640
type: AnswerComment

http://stackoverflow.com/q/50722972
accepted answer: http://stackoverflow.com/a/50724511
type: AnsweredQuestion
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/65509804
type: Question
has answer: http://stackoverflow.com/a/65509804
answer count: 2
has body: I would like to change the color of the regression lines to a different one. I found a similar question regarding a joint plot, however, as far as I know it is not analogical to the pairplot. I am attaching an example: import seaborn as sns; sns.set(style="ticks", color_codes=True) iris = sns.load_dataset("iris") g = sns.pairplot(iris, kind="reg")
has answer: http://stackoverflow.com/a/50724511
downvote count: 0
has title: Change the regression line colour of Seaborn's pairplot
favorite count: 0
tagged with: seaborn
score: 13
tagged with: python
upvote count: 13

http://stackoverflow.com/comment/88707931
has text: Here html_text is raw html text that is retrieved from the crawl response. And also `re.findall()` can't parse a BeautifulSoup object, so no need to convert the raw html to BeautifulSoup type.
type: Comment
comment on: http://stackoverflow.com/a/50851014
score: 0
type: AnswerComment

http://stackoverflow.com/a/51024298
has body: You may replace orderData = json.dumps({'symbol': pair, 'side': side, 'quantity': quantity, 'price': price}) to: orderData = json.dumps({'symbol': pair.lower(), 'side': side, 'quantity': quantity, 'price': price}) because symbol is required to be sent as lowercase.
score: 0
answers question: http://stackoverflow.com/q/50751319
type: Answer

http://stackoverflow.com/a/50803359
score: 1
accepted answer of: http://stackoverflow.com/q/50802082
has body: Here is the solution I attempted. Starting with the two dataframes that you have, you can use itertools to get all the possible combinations of the elements of df1 two by two: import itertools df1 = pd.DataFrame({"subject": ["a", "b", "c"]}) df2 = pd.DataFrame({"subject_list": [["a", "b", "c"], ["b", "c"], ["a", "b"], ["b", "c"], ["c"]]}) # Create a new dataframe with one column that has the possible two by two combinations from `df1` df_combinations = pd.DataFrame({'combination': list(itertools.combinations(df1.subject, 2))}) Then loop through the new dataframe, df_combinations in this case, to find out how many times each combination occurs in df2: for index, row in df_combinations.iterrows(): df_combinations.at[index, "number of occurrences"] = df2["subject_list"].apply(lambda x: all(i in x for i in row['combination'])).sum() The main difference in this step with respect to your original solution is that I am not using x.count but rather all since this one guarantees that only instances where both values are present will be counted. Finally df_combinations is: combination number of occurrences 0 (a, b) 2.0 1 (a, c) 1.0 2 (b, c) 3.0
answers question: http://stackoverflow.com/q/50802082
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88440396
comment on: http://stackoverflow.com/q/50711786
score: 0
type: Comment
type: QuestionComment
has text: Thank you...This worked for me

http://stackoverflow.com/comment/88615607
type: Comment
type: QuestionComment
has text: MinMaxScaler is never going to return an int unless there are only two values given. Are you looking to just have the label encoder as an int? Does astype accomplish what you need?
score: 0
comment on: http://stackoverflow.com/q/50804025

http://stackoverflow.com/comment/88533247
type: Comment
comment on: http://stackoverflow.com/a/50728741
type: AnswerComment
score: 0
has text: I want to remove borders from the new image. is this possible ?

http://stackoverflow.com/q/50810656
linked to: http://stackoverflow.com/q/19917492
has answer: http://stackoverflow.com/a/52550961
tagged with: python
has answer: http://stackoverflow.com/a/52535667
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91878959
tagged with: pycharm
tagged with: directory-structure
has answer: http://stackoverflow.com/a/52519816
tagged with: import
has comment: http://stackoverflow.com/comment/92027990
has answer: http://stackoverflow.com/a/52533264
type: Question
possible better answer: http://stackoverflow.com/a/52468403
has comment: http://stackoverflow.com/comment/91879053
linked to: http://stackoverflow.com/q/4383571
upvote count: 12
answer count: 6
has answer: http://stackoverflow.com/a/52468403
score: 12
accepted answer: http://stackoverflow.com/a/52526281
has body: My team has a folder of several small projects in python3. Amongst them, we have a utility folder with several utility functions, that are used throughout the projects. But the way to import it is very uncomfortable. This is the structure we use: temp_projects util storage.py geometry.py project1 project1.py project2 project2.py The problem is that the import in the projects looks terrible: sys.path.insert(1, os.path.join(sys.path[0], '..')) import util.geometry util.geometry.rotate_coordinates(....) Also, pycharm and other tools are having trouble understanding it and to supply completion. Is there some neater way to do that? Edit: All of the projects and utils are very much work-in-progress and are modified often, so I'm looking for something as flexible and comfortable as possible
downvote count: 0
favorite count: 0
has title: Python folder structure for project directory and easy import
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52526281

http://stackoverflow.com/q/50714395
type: Question
has body: I need to implement GPR (Gaussian process regression) in Python using the scikit-learn library. My input X has two features. Ex. X=[x1, x2]. And output is one dimension y=[y1] I want to use two Kernels; RBF and Matern, such that RBF uses the 'x1' feature while Matern use the 'x2' feature. I tried the following: import numpy as np from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import Matern as M, RBF as R X = np.matrix([[1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.], [1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.],[1.,2], [3.,4], [5.,1], [6.,5],[4, 7.],[ 9,8.]]).T y=[0.84147098, 0.42336002, -4.79462137, -1.67649299, 4.59890619, 7.91486597, 0.84147098, 0.42336002, -4.79462137, -1.67649299, 4.59890619, 7.91486597, 0.84147098, 0.42336002, -4.79462137, -1.67649299, 4.59890619, 7.91486597] kernel = R(X[0]) * M(X[1]) gp = GaussianProcessRegressor(kernel=kernel) gp.fit(X, y) But this gives an error ValueError: Found input variables with inconsistent numbers of samples: [2, 18] I tried several methods but could not find a solution. Really appreciate if someone can help.
accepted answer: http://stackoverflow.com/a/50731449
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88470115
answer count: 1
has comment: http://stackoverflow.com/comment/88470400
favorite count: 0
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/88470341
upvote count: 7
tagged with: gaussian-process
has comment: http://stackoverflow.com/comment/88470426
type: AnsweredQuestion
score: 7
has title: Gaussian process with 2D feature array as input - scikit-learn
has answer: http://stackoverflow.com/a/50731449

http://stackoverflow.com/q/50754730
tagged with: dataframe
has answer: http://stackoverflow.com/a/50754881
type: Question
answer count: 2
has title: How do I filter data by timestamp one day backward
has body: Here's my filter criteria (one day backward), called this df customer_id timestamp 1 2018-06-03 17:56:52 2 2018-06-03 18:42:51 Here's the main dataset, called this df2 transaction_id customer_id timestamp 1 1 2018-06-02 09:56:23 2 1 2018-06-03 02:56:52 3 1 2018-06-03 12:56:52 4 2 2018-06-03 12:40:51 5 2 2018-06-03 18:40:51 6 2 2018-06-03 18:48:50 What I want is transaction_id customer_id timestamp 2 1 2018-06-03 02:56:52 3 1 2018-06-03 12:56:52 4 2 2018-06-03 12:40:51 5 2 2018-06-03 18:40:51 This because for customer_id = 1 the filter criteria should be start from 2018-06-02 17:56:52 to 2018-06-03 17:56:52 and This because for customer_id = 2 the filter criteria should be start from 2018-06-02 18:42:51 to 2018-06-03 18:42:51
tagged with: filter
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50754863
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50754863
score: 1
possible better answer: http://stackoverflow.com/a/50754881

http://stackoverflow.com/comment/88488069
has text: I see. You should probably add this more clearly to the body of your question; will get back to you in a sec. Also, are you always going to consider df points in order?
comment on: http://stackoverflow.com/a/50739932
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/57238735
has body: here is the problem of your code when defining tuples with a single value you have to put "," at the end of the value otherwise python won't recognize it as a tuple for example: a = ('value1') #is a string not a tuple a = ('value1',) #is a tuple here is what your code should look like: from django.contrib.postgres.indexes import BrinIndex class Measurement(models.Model): class Meta: indexes = ( BrinIndex(fields=['time']), # "," is added here ) time = models.DateTimeField( 'Time of measurement', null=True )
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50801196
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88631242
comment on: http://stackoverflow.com/a/50812735
has text: @VasyaPravdin, I suggest you copy-paste the above code in a fresh Python session without making any changes. If it works, then there's a problem with how you are adapting the code to your application.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50836071
has title: python : function type parameter
has comment: http://stackoverflow.com/comment/88676114
has comment: http://stackoverflow.com/comment/88675844
has comment: http://stackoverflow.com/comment/88676030
tagged with: python
has body: Is there a way to enforce the type of a variable in a python function ? Or at least, give an indication of what it should be ? I already saw things like : var -&gt; int But I don't know the name of that syntax, nor its use. Thanks
accepted answer: http://stackoverflow.com/a/50836230
upvote count: 2
has comment: http://stackoverflow.com/comment/88675889
downvote count: 1
type: Question
tagged with: parameters
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50836230
tagged with: types
answer count: 1
has comment: http://stackoverflow.com/comment/88711523
linked to: http://stackoverflow.com/q/14379753
score: 1
has comment: http://stackoverflow.com/comment/88676129
favorite count: 0

http://stackoverflow.com/q/50726520
has comment: http://stackoverflow.com/comment/88461613
has answer: http://stackoverflow.com/a/50726681
has comment: http://stackoverflow.com/comment/88461446
tagged with: pythonpath
downvote count: 0
score: 1
favorite count: 0
tagged with: python-2.7
type: Question
tagged with: python
tagged with: macos
has body: I have an issue where somewhere along the line i've installed python3 and it has overwritten the default python path which is for 2.7. So when I go to terminal and type in "python" it loads version 3.6.5 instead of 2.7. If i type in "python2.7 to explicitly run python i get an error saying its pointing to the 3.6 site-packages instead of 2.7. derekchan@PandaMacPro:~/python$ python2.7 Your PYTHONPATH points to a site-packages dir for Python 3.x but you are running Python 2.x! PYTHONPATH is currently: "/usr/local/lib/python3.6/site-packages" You should unset PYTHONPATH to fix this. I've viewed other threads on this issue but it doesnt solve or help my problem. Is this a simple PYTHONPATH issue? I just want to be able to type in "python" and it load version 2.7 instead of version 3 and not have issue with the conflicting python packages.
tagged with: python-3.x
upvote count: 1
answer count: 1
has title: How to have two PYTHONPATHS for version 2 and 3
has comment: http://stackoverflow.com/comment/88461505
has comment: http://stackoverflow.com/comment/88461563
type: UnansweredQuestion

http://stackoverflow.com/comment/88517811
score: 1
type: AnswerComment
has text: @abarnert, even for debugging purposes, the function is rather meaningless, if the sorted array is not returned. I do not understand what you mean by the 'function that mutate objects inplace', can you give an example? That may be a class method, but rather pointless for a standalone sort function. When added a return value, the original sort gives wrong recursion, that is probably why the OP seeks a class, but rather wrongly. btw, print(sort(x)) is proper direction for this function, considering you would not call list.sort() a function, but rather a method.
type: Comment
comment on: http://stackoverflow.com/a/50754703

http://stackoverflow.com/comment/88579317
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50785389
type: Comment
has text: Thanks for your input! I tried this and I'm getting an error from MongoDB: The positional operator did not find the match needed from the query. Unexpanded update: MESSAGES.CHANNELS.$.COUNT I would like it to insert the array element if it doesn't exist already, can this be done? (I've specified upsert=true)

http://stackoverflow.com/q/50810174
score: 1
type: Question
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50845606
tagged with: google-cloud-ml
has answer: http://stackoverflow.com/a/60384189
has title: Unable to make predictions on google cloud ml, whereas same model is working on the local machine
tagged with: python
type: UnansweredQuestion
tagged with: machine-learning
tagged with: tensorflow
has body: I am trying to train a machine learning model usinf tensorflow library in the google cloud. I am able to train the model in the cloud after creating a bucket. I am facing the issue when I am tring to make predictions using the existing model. The code and the data is available in the following Github directory. https://github.com/terminator172/game-price-predictions The tensorflow version on the cloud is 1.8 and the tensorflow version on my system is also 1.8 I tried to make predictions by giving the following input "gcloud ml-engine predict --model=earnings --version=v8 --json-instances=sample_input_prescaled.json" It errored out with the following error "{ "error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.FAILED_PRECONDITION, details=\"Attempting to use uninitialized value output/biases4\n\t [[Node: output/biases4/read = IdentityT=DT_FLOAT, _output_shapes=[[1]], _device=\"/job:localhost/replica:0/task:0/device:CPU:0\"]]\")" }"

http://stackoverflow.com/q/50784981
accepted answer: http://stackoverflow.com/a/50785023
favorite count: 0
tagged with: python
tagged with: php
tagged with: aes
has title: AES-128-CBC don't work on the same way with LUA, PYTHON and PHP
type: AnsweredQuestion
score: 1
has body: I have an ESP8266 with Nodemcu and an AM2320 sensor. I am sending temperature and humidity in JSON format in plain text to my HTTP server for collecting datas with PHP and SQLITE3. That's working right. But I wish to encrypt my datas with AES-CBC I encrypt measures on the ESP8266 with crypto.encrypt() function and 'AES-CBC' method like this example: https://nodemcu-firmware.readthedocs.io/en/latest/en/modules/crypto/#cryptoencrypt I do the same encryption on my PC with Python 3 . The resulting string matches with the result on the ESP8266 and LUA 5.1 Next I do the same encryption on my PC but with PHP 7.1 Alas, the resulting string don't match with the previous results. I am using the 'AES-128-CBC' method on openssl_encrypt() function. I put the script in the three languages in a gist on Github.com : https://gist.github.com/bazooka07/bed368d313e218fcba332cb2127c70b1 That's wrong in PHP ? Can You help me ?
upvote count: 1
has answer: http://stackoverflow.com/a/50785023
type: Question
possible better answer: http://stackoverflow.com/a/50832583
tagged with: nodemcu
has answer: http://stackoverflow.com/a/50832583
tagged with: esp8266
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/88614557
type: QuestionComment
type: Comment
has text: This is, unfortunately, a fact. See my answer.
score: 0
comment on: http://stackoverflow.com/q/50803502

http://stackoverflow.com/comment/91557421
comment on: http://stackoverflow.com/q/50716249
has text: I ran into the same problem. Were you able to solve this?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88519905
type: QuestionComment
comment on: http://stackoverflow.com/q/50756085
score: 6
has text: Use a loop instead of the comprehension!
type: Comment

http://stackoverflow.com/q/50784257
upvote count: 5
downvote count: 0
tagged with: pandas
answer count: 1
has title: Pandas rolling apply: pass in a two-dimensional array
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I have a pandas dataframe that I wish to perform some rolling calculations on. This is not a simple formula so there's nothing built in. For purposes of a minimal verifiable complete example, let us assume that the dataframe is. df = pd.DataFrame({'a': [1.1, 2.1, 3.1, 4.1, 6.1, 8.1], 'b': [2.2, 3.2, 4.2, 5.2, 7.2, 9.2]}) to which I am applying the following (again simplified for debugging and illustrative purposes). def func(arr): print(arr) return 0 The print(arr) is to see what is being fed in. So the requirement is I wish to take a rolling window of size 4 of both column a and b at the same time. So the array dimensions should be 4 x 2. I tried df_res = df.rolling(window=4, center=False).apply(lambda x: func(x)) The print(arr) gives [ 1.1 2.1 3.1 4.1] [ 2.1 3.1 4.1 6.1] [ 3.1 4.1 6.1 8.1] [ 2.2 3.2 4.2 5.2] [ 3.2 4.2 5.2 7.2] [ 4.2 5.2 7.2 9.2] and df_res gives a b 0 NaN NaN 1 NaN NaN 2 NaN NaN 3 0.0 0.0 4 0.0 0.0 5 0.0 0.0 which is just feeding a 4 x 1 array for column a and b separately. According to this StackOverflow answer, apply a function on rolling window in Dataframe where whole dataframe is passed to function, the suggestion is to use min_periods and axis=1. df_res = df.rolling(window=4, min_periods=2, axis=1, center=False).apply(lambda x: func(x)) But this too is not what I require. The print(arr) gives. [ 1.1 2.2] [ 2.1 3.2] [ 3.1 4.2] [ 4.1 5.2] [ 6.1 7.2] [ 8.1 9.2] and the df_res is of the form a b 0 NaN 0.0 1 NaN 0.0 2 NaN 0.0 3 NaN 0.0 4 NaN 0.0 5 NaN 0.0 So what happened is that it is feeding in a 2 x 1 array. How can I get pandas to do a rolling window size of 4 and across both columns so that what gets fed in is a 4 x 2 array?
linked to: http://stackoverflow.com/q/43420909
tagged with: python
has answer: http://stackoverflow.com/a/76234564
type: Question
score: 5

http://stackoverflow.com/comment/88705290
has text: from flask import make_response, render_template, request
type: QuestionComment
comment on: http://stackoverflow.com/q/50851054
score: 0
type: Comment

observers
tags question: http://stackoverflow.com/q/50831859
type: Tag
tag name: observers

http://stackoverflow.com/a/50843683
answers question: http://stackoverflow.com/q/50843586
upvote count: 4
downvote count: 0
score: 4
has body: in your code, response is a bytestring that contains the data serialized in the json format. When you do json.dump you're serializing the string to json. You end up with a json formatted file containing a string, and in that string you have another json data, so, json inside json. To solve that you have to decode (deserialize) the bytestring data you got from the internet, before reencoding it to json to write in the file. response = json.load(urllib2.urlopen(url)) that will convert the serialized data from the web into a real python object.
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88691346
accepted answer of: http://stackoverflow.com/q/50843586

http://stackoverflow.com/q/50733978
tagged with: python
has body: If I have a dataframe as following, id price 01 10 02 5 03 0.1 04 100 05 1000 How could I get a new dataframe containing only price greater than $10 (including) and smaller than $100 (including) like this. Thanks. id price 01 10 04 100
linked to: http://stackoverflow.com/q/31617845
type: Question
duplicate of: http://stackoverflow.com/q/31617845
has answer: http://stackoverflow.com/a/50733993
score: 0
tagged with: pandas
answer count: 1
type: UnansweredQuestion
has title: select rows greater and smaller than two numbers with Pandas

http://stackoverflow.com/a/50733025
has comment: http://stackoverflow.com/comment/88489405
answers question: http://stackoverflow.com/q/50732229
has comment: http://stackoverflow.com/comment/88512784
type: AcceptedAnswer
score: 0
type: Answer
has body: You are doing most of the thing correctly. I will suggest the following changes in your code. model = tf.matmul(X, theta) + b Try this with a learning rate 0.001 and epoch 1000 and please report the result. In your case where you are doing model = tf.matmul(tf.transpose(theta), tf.transpose(X)) + b you are making a mistake. First part of the right side is of size (1, m) and the second part is of size (m, 1). Then you are getting a some result because of broadcasting that you are not expecting. That is why you are seeing very bad results with a learning rate of 0.01 or 0.1. My second suggestion is remove the break criterion. if errors[len(errors)-1] &gt; errors[len(errors)-2]: break Stochastic gradients are noisy. There is no proof that you will always reduce the cost if you go into the less gradient direction (may be it is true for this convex problem but I have to think). from sklearn.datasets import load_boston import numpy as np import pandas as pd import tensorflow as tf from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt from sklearn.metrics import r2_score from sklearn.preprocessing import MinMaxScaler rate = 0.1 epochs = 100 errors = [] def load_data(): boston = load_boston() bos = pd.DataFrame(boston.data) output = pd.DataFrame(boston.target) return [bos, output] xS, yS = load_data() x_train, x_test, y_train, y_test = train_test_split(xS, yS, test_size=0.2) m = len(y_train) scaler = MinMaxScaler() scaler.fit(x_train) x_train = scaler.transform(x_train) x_test = scaler.transform(x_test) theta = tf.Variable(tf.zeros([len(xS.columns), 1])) X = tf.placeholder(tf.float32, shape=[m, len(xS.columns)]) y = tf.placeholder(tf.float32, shape=[m, 1]) b = tf.Variable(tf.zeros([1])) model = tf.matmul(X, theta) + b cost = tf.reduce_sum(tf.square(y-model))/(2*m) optimizer = tf.train.GradientDescentOptimizer(rate).minimize(cost) init = [tf.global_variables_initializer(), tf.local_variables_initializer()] with tf.Session() as sess: sess.run(i…
has comment: http://stackoverflow.com/comment/88546432
accepted answer of: http://stackoverflow.com/q/50732229

http://stackoverflow.com/q/50729353
tagged with: flask
has title: Flask Templating Causing Duplicate HTML
has comment: http://stackoverflow.com/comment/88466671
type: Question
tagged with: twitter-bootstrap
tagged with: python
answer count: 1
score: 0
tagged with: bokeh
has body: For some reason when I use child templating with blocks in Flask, my HTML content is being rendered as duplicates. I am using Bootstrap and Bokeh to make graph visualizations. Each of the divs in my Dashboard.html child template are being rendered with duplicates. Does anyone know why this may be the case? Did I set up the templating incorrectly? Below is my layout.html file: Layout.html Embed Demo {% block body %}{% endblock %} This is my child template file: Dashboard.html {% extends "layout.html" %} {% block body %} {% for plot in plots %} {% for part in plot %} {% endfor %} {% endfor %} {% endblock %} Here is my Flask server: Server.py import random from flask import Flask, render_template from bokeh.plotting import figure from bokeh.embed import components app = Flask(__name__, static_folder='../static/dist', template_folder='../static/client') @app.route('/dashboard/') def show_dashboard(): plots = [] plots.append(make_plot()) return render_template('dashboard.html', plots=plots) def make_plot(): plot = figure(plot_height=300, sizing_mode='scale_width') x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = [2**v for v in x] plot.line(x, y, line_width=4) script, div = components(plot) return script, div if __name__ == '__main__': app.run(debug=True)
has answer: http://stackoverflow.com/a/50752466
type: UnansweredQuestion

http://stackoverflow.com/q/50834389
downvote count: 0
favorite count: 0
has title: Change date format of ipywidgets.DatePicker
has comment: http://stackoverflow.com/comment/98857362
tagged with: datepicker
has comment: http://stackoverflow.com/comment/98855877
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 11
tagged with: ipywidgets
has comment: http://stackoverflow.com/comment/89124269
upvote count: 11
has body: How to change format of dates for DatePicker from ipywidgets? Default format is 'mm/dd/yyyy' and I want to set it to 'yyyy-mm-dd'?
type: Question
has comment: http://stackoverflow.com/comment/89111577

http://stackoverflow.com/a/50778272
has comment: http://stackoverflow.com/comment/88563398
accepted answer of: http://stackoverflow.com/q/50778190
answers question: http://stackoverflow.com/q/50778190
has comment: http://stackoverflow.com/comment/88563521
upvote count: 2
has comment: http://stackoverflow.com/comment/88563452
type: AcceptedAnswer
type: Answer
has body: Another solution might look like this: import numpy as np import pandas as pd raw_data = pd.read_csv('ex1data1.txt', header= None, names= ['x1','y']) raw_data.insert(loc=0, column='x0', value=1.0) print(raw_data)
score: 2
has comment: http://stackoverflow.com/comment/88563458
downvote count: 0

http://stackoverflow.com/comment/88578451
score: 0
type: Comment
type: QuestionComment
has text: I don't understand independently from the html code, why when I run the code it can't go on and give me the error. I think that if the condition inside the if is false, the program should go inside the else.
comment on: http://stackoverflow.com/q/50785305

http://stackoverflow.com/a/68147157
has body: am not sure but You can save your current cookies using pickle, For example: import pickle from selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.google.com") pickle.dump( driver.get_cookies() , open("cookies.pkl","wb")) after that add them back using this code: import pickle from selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.google.com") cookies = pickle.load(open("cookies.pkl", "rb")) for cookie in cookies: driver.add_cookie(cookie)
upvote count: 1
answers question: http://stackoverflow.com/q/50792181
downvote count: 1
type: Answer
score: 0

http://stackoverflow.com/a/50725593
has body: Well, you should calculate an error function which measures how good your fit actually is. There are many different error functions you could use but for the start the mean-squared-error should work (if you're interested in further metrics, have a look at http://scikit-learn.org/stable/modules/model_evaluation.html). You can manually implement mean-squared-error, once you determined the coefficients for your regression problem: from sklearn.metrics import mean_squared_error f = lambda x: a * np.exp(b * x) + c mse = mean_squared_error(y_data, f(x_data))
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50725227

http://stackoverflow.com/q/50706220
has answer: http://stackoverflow.com/a/50706580
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has title: How to get the model loss in sklearn
has body: Whenever an sklearn model is fit to some data, it minimizes some loss function. How can I obtain the model loss using that loss function? e.g. model = sklearn.linear_model.LogisticRegression().fit(X_train,y_train) model.get_loss(X_train, y_train) #gives the loss for these values model.get_loss(X_test, y_test) #gives the loss for other values Note that the .score method does NOT do this thing.
upvote count: 8
answer count: 1
tagged with: python
score: 8
accepted answer: http://stackoverflow.com/a/50706580
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/89207305
type: Comment
type: QuestionComment
score: 0
has text: If you're still watching this - there's a good example here: https://stackoverflow.com/questions/39048984/tensorflow-how-to-write-op-with-gradient-in-python/39984513#39984513
comment on: http://stackoverflow.com/q/50720041

http://stackoverflow.com/a/50843311
type: Answer
has body: Try Labeling should give the end result as expected dbobject.query.with_entities(dbobject.id.label('id'), dbobject.name.label('name'), dbobject.version.label('version'))
score: 1
upvote count: 1
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50838394
answers question: http://stackoverflow.com/q/50838394

http://stackoverflow.com/comment/88669218
type: Comment
comment on: http://stackoverflow.com/q/50832526
has text: Possible duplicate of [C# Parallel.Foreach equivalent in Python](https://stackoverflow.com/questions/29236642/c-sharp-parallel-foreach-equivalent-in-python)
score: 1
type: QuestionComment

http://stackoverflow.com/a/50711699
has comment: http://stackoverflow.com/comment/88432289
score: 2
answers question: http://stackoverflow.com/q/50711647
downvote count: 0
has comment: http://stackoverflow.com/comment/88432295
type: Answer
has body: Stephen Rauch has a nice idea. Here's a slightly more concise version of what he's written using dict.get. matches = {'num': 'numerical', 'cat': 'categorical'} result = {k : matches.get(k[:3], 'unknown') for k in items} print(result) {'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical', 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'} If you want to drop values that do not match, make a slight modification: result = {k : matches[k[:3]] for k in items if k[:3] in matches} Here's my take on it. Sort items first, and then find the index of discontinuity. items.sort() for i, l in enumerate(items): if l.startswith('num'): break result = dict.fromkeys(items[:i], 'categorical') result.update(dict.fromkeys(items[i:], 'numerical')) This works best for two classes of values only. print(result) {'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical', 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'}
upvote count: 2
has comment: http://stackoverflow.com/comment/88432300

http://stackoverflow.com/comment/88581186
type: Comment
score: 0
has text: Thank you a lot, it seems adapting the code won't be the solution then haha
type: AnswerComment
comment on: http://stackoverflow.com/a/50787258

http://stackoverflow.com/comment/88594440
has text: what is `type(session['attributes']['startDate'])`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50793347
type: Comment

http://stackoverflow.com/comment/88542000
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50767064
has text: Thanks. but how do I send the file now. It is still requiring an argument which I am unsure what to give.

http://stackoverflow.com/q/50714130
has comment: http://stackoverflow.com/comment/88437653
favorite count: 0
has comment: http://stackoverflow.com/comment/88437227
type: Question
tagged with: regex
score: 1
has answer: http://stackoverflow.com/a/50714574
has comment: http://stackoverflow.com/comment/88437266
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/88437705
accepted answer: http://stackoverflow.com/a/50714574
has title: Reading the contents inside the comment lines using Regular expression
type: AnsweredQuestion
has body: I have a string as /* @TS 1 This is the comment for method1 /* @TS 2 This is the comment for method2*/ I need to map each index value(1,2) to that content like Eg 1 -> This is the comment for method1 I wrote the below Python Program using the regular Expression regex = r"/\*([^*]|[\r\n]|(\*([^/]|[\r\n])))*\*/" Is there any regular expression that will group number as one group and content after(:) as one group?
downvote count: 0

http://stackoverflow.com/q/50842779
tagged with: tkinter
has body: Here I have a basic OptionsMenu and a list with lists inside of it for my Menu options. What I need to do is display only the first item of the sub lists in the options menu but when that item is selected to pass the 2nd item in the sub list to a function. Currently I can display all of the sub list and pass all of the sub list to a function. The main problem I am having is trying to display JUST the first item "ID 1" or "ID 2" in the drop down menu. import tkinter as tk root = tk.Tk() def print_data(x): print(x[1]) example_list = [["ID 1", "Some data to pass later"], ["ID 2", "Some other data to pass later"]] tkvar = tk.StringVar() tkvar.set('Select ID') sellection_menu = tk.OptionMenu(root, tkvar, *example_list, command=print_data) sellection_menu.config(width=10, anchor='w') sellection_menu.pack() root.mainloop() This is what I get: What I want: As you can see in the 2nd image only the "ID 1" is displayed in the menu and the data for that ID is printed to console. I cannot find any documentation or post abut this issue so it may not be possible.
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50848116
tagged with: optionmenu
type: Question
has title: OptionsMenu display only first item in each list?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50848116

http://stackoverflow.com/comment/88573052
type: Comment
has text: Great; if you found the answer helpful, you [can accept it](https://stackoverflow.com/help/someone-answers).
comment on: http://stackoverflow.com/a/50782994
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88522156
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50757265
has text: Add as a text instead of images
type: Comment

http://stackoverflow.com/a/53756024
downvote count: 0
has comment: http://stackoverflow.com/comment/136442849
has body: In linear regression with categorical variables you should be careful of the Dummy Variable Trap. The Dummy Variable trap is a scenario in which the independent variables are multicollinear - a scenario in which two or more variables are highly correlated; in simple terms one variable can be predicted from the others. This can produce singularity of a model, meaning your model just won't work. Read about it here Idea is to use dummy variable encoding with drop_first=True, this will omit one column from each category after converting categorical variable into dummy/indicator variables. You WILL NOT lose and relevant information by doing that simply because your all point in dataset can fully be explained by rest of the features. Here is complete code on how you can do it for your jobs dataset So you have your X features: Age, Gender, Job, Classification And one numerical features that you are trying to predict: Wage First you need to split your initial dataset on input variables and prediction, assuming its pandas dataframe it would look like this: Input variables (your dataset is bit different but whole code remains the same, you will put every column from dataset in X, except one that will go to Y. pd.get_dummies works without problem like that - it will just convert categorical variables and it won't touch numerical): X = jobs'Age','Gender','Job','Classification' Prediction: Y = jobs['Wage'] Convert categorical variable into dummy/indicator variables and drop one in each category: X = pd.get_dummies(data=X, drop_first=True) So now if you check shape of X (X.shape) with drop_first=True you will see that it has 4 columns less - one for each of your categorical variables. You can now continue to use them in your linear model. For scikit-learn implementation it could look like this: from sklearn import linear_model from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = .20, random_state = 40) regr…
type: Answer
has comment: http://stackoverflow.com/comment/119813175
upvote count: 21
score: 21
answers question: http://stackoverflow.com/q/50733014

http://stackoverflow.com/comment/88435131
has text: That being said, Python will only run that loop once. The first import from tasker may be slow, but the second and following shouldn't be.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50712801
type: Comment

logging
tags question: http://stackoverflow.com/q/50793098
tags question: http://stackoverflow.com/q/50824566
tags question: http://stackoverflow.com/q/50750717
tag name: logging
tags question: http://stackoverflow.com/q/50708380
tags question: http://stackoverflow.com/q/50714316
tags question: http://stackoverflow.com/q/50740484
tags question: http://stackoverflow.com/q/50777664
tags question: http://stackoverflow.com/q/50714720
tags question: http://stackoverflow.com/q/50843636
tags question: http://stackoverflow.com/q/50806677
tags question: http://stackoverflow.com/q/50779021
tags question: http://stackoverflow.com/q/50766079
tags question: http://stackoverflow.com/q/50805474
tags question: http://stackoverflow.com/q/50725250
tags question: http://stackoverflow.com/q/50817817
tags question: http://stackoverflow.com/q/50779419
type: Tag
tags question: http://stackoverflow.com/q/50823062
tags question: http://stackoverflow.com/q/50782240

http://stackoverflow.com/q/50827574
tagged with: statistics
upvote count: 2
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: I have a pandas groupby object that returns the counts of each gene type, roughly as shown below (column headers formatted manually for clarity): counts = df.groupby(["ID", "Gene"]).size() counts ID Gene Count 1_1_1 SMARCB1 1 smad 12 1_1_10 SMARCB1 2 smad 17 1_1_100 SMARCB1 3 I need to get the within group zscore, and then return the Gene with the highest zscore. I've tried the following, but it seems to be calculating zscores across the whole dataset and does not return the correct zscore: zscore = lambda x: (x - x.mean()) / x.std() counts = df.groupby(["ID", "Match"]).size().pipe(zscore) I've tried with transform and gotten the same results. I tried: counts = match_df.groupby(["ID", "Match"]).size().apply(zscore) Which gives me the following error: 'int' object has no attribute 'mean' Whatever I try, it doesn't give the correct output. The zscores for the first two lines should be [-1,1] in which case I would return the row for 1_1_1 SMARCB1. Etc. Thanks! Update Thanks to help from @ZaxR and switching to numpy mean and standard deviation, I was able to solve this as shown below. This solution also provides a summary dataframe of the raw counts and zscores for each gene: # group by id and gene match and sum hits to each molecule counts = df.groupby(["ID", "Match"]).size() # calculate zscore by feature for molecule counts # features that only align to one molecule are given a score of 1 zscore = lambda x: (x - np.mean(x)) / np.std(x) zscores = counts.groupby('ID').apply(zscore).fillna('1').to_frame('Zscore') # group results back together with counts and output to # merge with positions and save to file zscore_df = zscores.reset_index() zscore_df.columns = ["ID", "Match", "Zscore"] count_df = counts.reset_index() count_df.columns = ["ID", "Match", "Counts"] zscore_df["Counts"] = count_df["Counts"] # select gene with best zscore meeting threshold max_df = zscore_df[zscore_df.groupby('ID')['Zscore'].transform(max) \ == zscore_df['Zscore']]
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50828055
accepted answer: http://stackoverflow.com/a/50828055
type: Question
has title: Pandas groupby: get best zscore for counts() of each group
has comment: http://stackoverflow.com/comment/88659725
has comment: http://stackoverflow.com/comment/88659802
tagged with: group-by
has comment: http://stackoverflow.com/comment/88659748
has comment: http://stackoverflow.com/comment/88659739

http://stackoverflow.com/q/50725737
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/88498528
linked to: http://stackoverflow.com/q/22181384
type: Question
tagged with: javascript
tagged with: flask
has comment: http://stackoverflow.com/comment/88459733
score: 0
has comment: http://stackoverflow.com/comment/88459749
answer count: 1
has title: Sending data back from Javascript to Python
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50726737
has body: I am very new to Python / Flask / Javascript, and would appreciate it if someone could help me with this. I am trying to pass a string value from Javascript back to Python but it does not seem to work. My code is as follows: Javascript (partial code): var bounds = '8.3,9,34.3,15.9'; $.post("/receiver", { bbox_bounds: bounds }); In Python: from flask import Flask, request #Create the Flask app app = Flask(__name__) @app.route('/receiver', methods = ['POST']) def receiver(): bbounds = request.form('bbox_bounds') print "Bounds: " + bbounds return bbounds if __name__ == '__main__': app.run(port=5000) Sorry, the above is bad, but I am really a beginner. Thank you.

http://stackoverflow.com/comment/88475498
has text: I guess, printed that way, it won't line up in columns like you showed.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50733181
type: AnswerComment

http://stackoverflow.com/q/50775830
has comment: http://stackoverflow.com/comment/88558852
answer count: 0
score: 1
has title: Confused about __iter__(self) and iter()
has body: I have a class like this class MyClass: def __init__(self): self.test = [1,2,3] Now I want to iterate over the test property like this: a = MyClass() for i in a: print(I) So I've added another method to the class: def __iter__(self): return self.test Which doesn't work, unless I instead do this: return iter(self.test) I thought the for loop implicitly calls iter() behind the scenes and it's obviously capable of iterating over a normal list if I would do for i in a.test so obviously I'm not understanding something about using those functions. Would love some clarification
duplicate of: http://stackoverflow.com/q/48124461
type: Question
has comment: http://stackoverflow.com/comment/88558897
has comment: http://stackoverflow.com/comment/88558973
has comment: http://stackoverflow.com/comment/88558777
duplicate of: http://stackoverflow.com/q/9884132
has comment: http://stackoverflow.com/comment/88558754
linked to: http://stackoverflow.com/q/35657927
has comment: http://stackoverflow.com/comment/88558813
upvote count: 1
linked to: http://stackoverflow.com/q/48124461
downvote count: 0
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/9884132
duplicate of: http://stackoverflow.com/q/13054057
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88558934
tagged with: python
has comment: http://stackoverflow.com/comment/88558746
has comment: http://stackoverflow.com/comment/88558905

http://stackoverflow.com/comment/88452397
type: Comment
type: QuestionComment
has text: The file is called creds.pyc. You may want to read the python documentation on that. From what I can tell, this is an encrypted file.
comment on: http://stackoverflow.com/q/50721915
score: 0

http://stackoverflow.com/q/50778216
has comment: http://stackoverflow.com/comment/88563617
has title: call python method in parallel from a loop
has comment: http://stackoverflow.com/comment/88563365
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88563428
tagged with: parallel-processing
tagged with: multiprocessing
type: Question
has body: I have a method 1 in which loop is running and calling another method 2 but i want to know that how i can call method 2 in parallel as it is performing some sequential steps and call-1 of method 2 should be seprate from call-2 of method 2 ... so on here is my code Method 2 def upload_image(img): sess = requests.Session() sess.verify = False start_upload_response = requests.post('https://awsimgproc.com/start_upload', data={"album_id36": 1}, verify=False) start_upload_response.raise_for_status() result = start_upload_response.json() our_upload = result['upload_id36'] url = 'https://awsimgproc.com/uploadImage' files = {'file': open(img, 'rb')} data = {'upload_id36':our_upload} # This makes the post requests async global api_response api_response.append(grequests.post(url,data=data,files=files)) Method 1 def image_generator(): # Change here the location of iamge file image_file_location = "/home/gaurav/Pictures/sofa-3" extension = ".jpg" i=1 img = Image.open(image_file_location + extension) start_time = datetime.now() # can change minutes as per need i.e for how much you need run test suite end_time = start_time + timedelta(minutes=1) while start_time &lt; end_time: # change current image and randomly roating the image rotated_image = img.rotate(random.randint(1,1000)) new_image_loaction = image_file_location+str(i)+extension rotated_image.save(new_image_loaction) # upload the newly rotated image upload_image(new_image_loaction) # uncomment this line to add sleep to your method # time.sleep(random.randint(1,5)) start_time = datetime.now() i += 1
has answer: http://stackoverflow.com/a/50778635
score: 0
answer count: 1

http://stackoverflow.com/a/50739730
type: Answer
answers question: http://stackoverflow.com/q/50739290
score: 0
has body: Take a look into this example: a = ["some text", 'some more text', 'yet some more text'] b = ["another some text", "another some more text", "yet another some more text"] c = ["third text 1", "third text 2", "third text 3"] print('\n'.join(a)) print('\n'.join(b)) # COMBINED MAGIC: print('\n'.join(map(lambda x: ('{:30}'*len(x)).format(*x).strip(), zip(a, b, c)))) First two prints are equal to yours. As for the last one step-by-step: zip N ( in this case N = 3 ) lists with strings into single one where each element is a tuple of corresponding elements from a, b, c lists For each tuple we create formatter template using the lenght of each tuple. Pass unpacked tuple to format function Join with newline symbol Print Output from the last print call: some text another some text third text 1 some more text another some more text third text 2 yet some more text yet another some more text third text 3

http://stackoverflow.com/q/50749588
has comment: http://stackoverflow.com/comment/88533646
has comment: http://stackoverflow.com/comment/88515585
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/88533888
has body: So I've made a airline twitter sentiment analysis script using this as reference: https://github.com/sunilpankaj/Twitter-US-Airline-Sentiment/blob/master/Cleaning%20data%20and%20prediction.ipynb It's been trained and optimized and I have around a 78.6% accuracy on the commonly used CrowdFlower airline twitter data set. I now have a new set of recent tweets that have been processed to remove stopwords, other symbols, etc., and put into a .csv file. It looks like this: southwestairlin look oper agent appli sanfrancisco job check job busi consult sale analyt southwestairlin dalla sr citrix engin need dalla appli southwestairlin job check job euc system engin southwestairlin dalla southwestairlin look station administr denver appli job new job open southwestairlin atlanta appear technician southwestairlin hire train schedul dalla appli job rt riski busi fli faa lower hire standard faa deltaairlin jetblu southwestairlin Each new line represents a different tweet. I now want to input this data into the classifier I already trained using the CrowdFlower dataset, have it identify the sentiment of the tweet and write the sentiments to a new .csv file similar to this: Positive Neutral Neutral Negative How would I go about doing this? Sorry for the bad formatting, this is my first time posting. I can also post some code if it would help. My entire code: Code Part 1 Code Part 2
has answer: http://stackoverflow.com/a/50749741
downvote count: 3
tagged with: twitter
tagged with: machine-learning
type: Question
upvote count: 0
has title: Issues running my New Data on -Tweet Sentiment Analysis
tagged with: sentiment-analysis
has comment: http://stackoverflow.com/comment/88515538
answer count: 1
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/88515609

http://stackoverflow.com/comment/88522951
comment on: http://stackoverflow.com/q/50756288
has text: That (x,1) is not 1D is very confusing for a " python-foreigner" :-) I learn every day. Cheers
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88422587
comment on: http://stackoverflow.com/q/50706431
has text: Please add that to your question so that readers don't have to read the comments to fully understand the problem statement.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50726856
type: Answer
has body: You can achieve using tensorflow broadcasting feature: #[[a1-b1 a1-b2 a1-b3 a1-b4 …] #[a2-b1 a2-b2 a2-b3 a2-b4 …] #[a3-b1 a3-b2 a3-b3 a3-b4 …] #…] # Subtract a and b transpose c = a - tf.transpose(b) Output: #[[ 0. -1. -2. -3.] #[ 1. 0. -1. -2.] #[ 2. 1. 0. -1.] #[ 3. 2. 1. 0.]] # for input: a:[[1],[2],[3],[4]],b:[[1],[2],[3],[4]] #[[tf.pow(a1,b1) tf.pow(a1,b2) tf.pow(a1,b3) tf.pow(a1,b4) …] #[tf.pow(a2,b1) tf.pow(a2,b2) tf.pow(a2,b3) tf.pow(a2,b4) …] #[tf.pow(a3,b1) tf.pow(a3,b2) tf.pow(a3,b3) tf.pow(a3,b4) …] #…] #form (i,j) index matrices and then apply tf.pow i = tf.tile(a, [1, tf.shape(b)[0]]) j = tf.transpose(tf.tile(b, [1, tf.shape(a)[0]])) power = tf.pow(i,j) Output: # index i index j #[[1., 1., 1., 1.], [[1., 2., 3., 4.] #[2., 2., 2., 2.], [1., 2., 3., 4.] #[3., 3., 3., 3.], [1., 2., 3., 4.] #[4., 4., 4., 4.] [1., 2., 3., 4.]] #Output #[[ 1. 1. 1. 1.] #[ 2. 4. 8. 16.] #[ 3. 9. 27. 81.] #[ 4. 16. 64. 256.]]
answers question: http://stackoverflow.com/q/50714585
score: 1
accepted answer of: http://stackoverflow.com/q/50714585
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50772176
favorite count: 0
upvote count: 5
tagged with: angle
has comment: http://stackoverflow.com/comment/88572660
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/55517186
downvote count: 0
has comment: http://stackoverflow.com/comment/88572368
has title: Calculate the angle between the rows of two matrices in numpy
linked to: http://stackoverflow.com/q/2827393
type: Question
tagged with: numpy
score: 5
tagged with: vector
accepted answer: http://stackoverflow.com/a/50772253
has body: I have two matrices consisting of 3d vectors (numpy 1D arrays) and I need to calculate the angle between the vectors, row-wise, and return the results in a 1d array. I know how to calculate the angle between two 1d vectors. What is the the proper way to do this? *** The resulting angles are in degrees not radians. By now I have this: import numpy as np A = np.array([[1,0,0], [0,1,0], [0,0,1]]) B = np.array([[1,0,1], [1,1,0], [0,1,0]]) def angle(V1,V2): """ angle between vectors V1 and V2 in degrees using angle = arccos ( V1 dot V2 / norm(V1) * norm(V2) ) *180/np.pi """ cos_of_angle = V1.dot(V2) / (np.linalg.norm(V1) * np.linalg.norm(V2)) return np.arccos(np.clip(cos_of_angle,-1,1)) * 180/np.pi Note the scaling term 180/np.pi for the conversion from rad to deg. I would like to have an array: C = [ angle(A[0],B[0]) , angle(A[1],B[1])...... and so on] Really appreciated if someone could help.
has answer: http://stackoverflow.com/a/55517186
answer count: 2
tagged with: matrix
has answer: http://stackoverflow.com/a/50772253

http://stackoverflow.com/q/50737444
has title: Can't shuffle rows of list of lists by copying (Python)
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88482692
answer count: 0
has comment: http://stackoverflow.com/comment/88482617
type: Question
has comment: http://stackoverflow.com/comment/88484437
has body: I want to shuffle/permute the rows of a list of lists (2D array) target in Python. I create the list train and then shuffle it by np.random.shuffle(), and use it to permute indices of rows of target in the same order. I know I can't just write new_list = old_list to copy one list to other , so (I think) I used a proper way to copy target to cop by cop = [row[:] for row in target] mentioned here on SO. But even after running the code below I can't figure out why cop changes value during the loop. As a result, target isn't what I expect. Code I am attempting: import numpy as np train = [0, 1, 2, 3, 4] print("train: ", train) target = np.hstack([np.arange(5).reshape(5,1), np.arange(100, 105).reshape(5,1), np.arange(200, 205).reshape(5,1)]) print(target) np.random.shuffle(train) print("Shuffled train: ", train) cop = [row[:] for row in target] for i in range(len(train)): print(train[i], '-----', cop[train[i]], '-------', cop) target[i] = list(cop[train[i]]) print("Target: ", target) print("Cop: ", cop) Sample output: train: [0, 1, 2, 3, 4] [[ 0 100 200] [ 1 101 201] [ 2 102 202] [ 3 103 203] [ 4 104 204]] Shuffled train: [4, 3, 2, 0, 1] 4 ----- [ 4 104 204] ------- [array([ 0, 100, 200]), array([ 1, 101, 201]), array([ 2, 102, 202]), array([ 3, 103, 203]), array([ 4, 104, 204])] 3 ----- [ 3 103 203] ------- [array([ 4, 104, 204]), array([ 1, 101, 201]), array([ 2, 102, 202]), array([ 3, 103, 203]), array([ 4, 104, 204])] 2 ----- [ 2 102 202] ------- [array([ 4, 104, 204]), array([ 3, 103, 203]), array([ 2, 102, 202]), array([ 3, 103, 203]), array([ 4, 104, 204])] 0 ----- [ 4 104 204] ------- [array([ 4, 104, 204]), array([ 3, 103, 203]), array([ 2, 102, 202]), array([ 3, 103, 203]), array([ 4, 104, 204])] 1 ----- [ 3 103 203] ------- [array([ 4, 104, 204]), array([ 3, 103, 203]), array([ 2, 102, 202]), array([ 4, 104, 204]), array([ 4, 104, 204])] Target: [[ 4 104 204] [ 3 103 203] [ 2 102 202] [ 4 104 204] [ 3 103 203]] Cop: [array([ 4, 104, 204]), array([ 3, 103, 203]…
tagged with: copy
score: 0
linked to: http://stackoverflow.com/q/6532881

http://stackoverflow.com/comment/88565604
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50779346
has text: It looks like you are accessing rows. Do you mean columns?

http://stackoverflow.com/q/50820693
tagged with: python
has body: I have some trouble trying to understand how to use the threading module in python 3. Origin: I wrote a python script to do some image processing on every frame of a camera stream in a for loop. Therefor I wrote some functions which are used inside the main script. The main script/loop isn´t encapsulated inside a function. Aim: I want the main loop to run the whole time. The result of the processing of the latest frame have to be send to a socket client only if the client sends a request to the server socket. My idea was to use two threads. One for the image processing and one for the server socket which listens for a request, takes the latest image processing result and sends it to the client socket. I saw different tutorials how to use threading and understand the workflow in general, but not how to use it to cope with this particular case. So I hope for your help. Below there is the rough structure of the origin script: import cv2 import numpy import json import socket from threading import Thread def crop(image, coords): ... def cont(image): ... # load parameters a = json_data["..."] # init cam camera = PiCamers() # main loop for frame in camera.capture_continuous(...): ####### # some image processing ####### result = (x, y, z) Thank you in advance for your ideas! Greetings
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50820819
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python-multithreading
tagged with: sockets
has title: How to execute processing task and socket communication concurrently in python 3?

http://stackoverflow.com/comment/88692309
type: Comment
has text: Just call `soup.get_text()`
type: QuestionComment
comment on: http://stackoverflow.com/q/50844331
score: 0

http://stackoverflow.com/a/50806988
has comment: http://stackoverflow.com/comment/88701205
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50806354
answers question: http://stackoverflow.com/q/50806354
type: Answer
has body: Why not to do this manually in your original dataset? Assuming you are using pd.DataFrame you can do the following: import numpy as np import pandas as pd from sklearn.preprocessing import Imputer df = pd.DataFrame({'A': [1, 2, 3, 8], 'B': [1, 2, 5, 3]}) df_new = df.replace([1, 2], np.nan) df_imp = Imputer().fit_transform(df_new) This results in df_imp: array([[ 5.5, 4. ], [ 5.5, 4. ], [ 3. , 5. ], [ 8. , 3. ]]) If you want to make this a part of a pipeline, you would just need to implement a custom transformer with a similar logic.

http://stackoverflow.com/comment/88666130
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50830500
has text: A quick bash solution which explains the core concept: `tac | sed '/^-/q' | tac` - print the file lines in reverse, print up to the first line starting with a `-`, reverse the lines again.

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/50741330
tags question: http://stackoverflow.com/q/50796039
type: Tag

http://stackoverflow.com/comment/88424880
type: Comment
comment on: http://stackoverflow.com/q/50707719
type: QuestionComment
score: 0
has text: Any help will be appreciated since I am not getting if there is any syntactical error or not

syntax-error
tags question: http://stackoverflow.com/q/50798112
type: Tag
tags question: http://stackoverflow.com/q/50802020
tags question: http://stackoverflow.com/q/50822383
tag name: syntax-error
tags question: http://stackoverflow.com/q/50829278
tags question: http://stackoverflow.com/q/50779389

http://stackoverflow.com/comment/88469323
comment on: http://stackoverflow.com/q/50709896
score: 0
has text: @Oleg according to the [documentation](http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.read_sql.html), that argument must be a `sqlalchemy` engine object or a DBAPI2 object (which will only work for sqlite connections). This is what the documentation states, so I think that is a good bet as to what will work...
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88422729
has text: Can you post a more minimal example along with a desired output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50706677
score: 3

http://stackoverflow.com/comment/88502974
comment on: http://stackoverflow.com/q/50746748
score: 0
type: Comment
type: QuestionComment
has text: The other question I asked didn't use the method I wanted. I have to use this specific method unfortunately. No offense to the people answering my question and I apologize for the redundant questions. Also, I came up with another question that i couldn't solve on my own, so im asking it here again.The other question was about the syntax error reagrding axis=1 and this one is about using the x0 and x1 values in my txt file for the step function plot diagram.

http://stackoverflow.com/q/50750368
answer count: 3
tagged with: sql
linked to: http://stackoverflow.com/q/902408
has answer: http://stackoverflow.com/a/50750400
linked to: http://stackoverflow.com/q/43123408
favorite count: 0
duplicate of: http://stackoverflow.com/q/902408
has comment: http://stackoverflow.com/comment/88508627
has comment: http://stackoverflow.com/comment/88508868
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50750397
linked to: http://stackoverflow.com/q/10950362
has body: When I run the following: table = cfg_pre + '_' + cfg_tbl check_data = 'SELECT COUNT(*) FROM X WHERE TABLE_NM = {}'.format(table) I get the following: SELECT COUNT(*) FROM X WHERE TABLE_NM = ABC_123 What I need is: SELECT COUNT(*) FROM X WHERE TABLE_NM = 'ABC_123' Otherwise the SQL won't execute. Any ideas?
has comment: http://stackoverflow.com/comment/88508555
score: 1
has answer: http://stackoverflow.com/a/50750419
has title: Adding single quotes in string around curly braces - Python
downvote count: 1
has comment: http://stackoverflow.com/comment/88508539
type: Question
tagged with: string
has comment: http://stackoverflow.com/comment/88508536
has comment: http://stackoverflow.com/comment/88508503

http://stackoverflow.com/a/50809764
downvote count: 0
score: 5
type: AcceptedAnswer
has body: After a little bit of search, I found it's an issue with Nginx config. The nginx config I posted does not allow websockets. The following change needs to be done: location / { uwsgi_pass home; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; include /Users/pranavprakash/workspace/SomeDashboardProject/uwsgi_params; } More details available at the Nginx blog post
answers question: http://stackoverflow.com/q/50808651
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50808651

http://stackoverflow.com/comment/88564354
type: AnswerComment
type: Comment
has text: @beta, This could be a version issue. In v0.23, I see `as_index` fail versus `reset_index` working.
comment on: http://stackoverflow.com/a/50778725
score: 0

http://stackoverflow.com/a/50747581
type: Answer
has comment: http://stackoverflow.com/comment/88503782
accepted answer of: http://stackoverflow.com/q/50747481
score: 1
upvote count: 1
has body: You can simplify this best function by factoring out the code to score a word. I'm not sure exactly what you're trying to do, so this might be oversimplified for your actual problem, but it should be enough to get you going: def score(word): dic = {'D':2, 'C':2, 'L':2, 'P':2, 'B':3, 'N':3, 'F':4, 'G':4, 'H':4, 'V':4, 'J':5, 'Q':6, 'X':8, 'Y':8, 'Z':8} total = 0 for char in word: total += dic.get(char.upper(), 0) return total Now, if you have a list of words, you can use that score function as a key function and just pass it to max: def best(lista): return max(lista, key=score)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50747481

http://stackoverflow.com/comment/88644880
has text: Thanks, I edited it. But the code is still not working.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50819519

http://stackoverflow.com/a/50798859
score: 0
type: Answer
has body: Quick one using list comrehension key_word=['one', 'two'] lst=['one1', 'one2', 'two1', 'two2', 'two3', 'one3'] print("\n".join(sorted([x for x in lst if key_word[0] in x or key_word[1] in x])))
answers question: http://stackoverflow.com/q/50699111

http://stackoverflow.com/q/50827588
tagged with: list
accepted answer: http://stackoverflow.com/a/50841041
downvote count: 1
type: Question
score: -1
tagged with: for-loop
has comment: http://stackoverflow.com/comment/88659702
upvote count: 0
answer count: 1
has body: I have 3 great lists and I would like to make 1: 1: 1 relationships with them. To be clearer I will show the lists: lstA= [[[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (16, 0)], [(8, 1), (9, 1), (10, 1), (16, 0)], [(11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 0)]], [[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (17, 0)], [(8, 1), (9, 1), (10, 1), (17, 0)], [(11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (17, 0)]], [[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (18, 0)], [(8, 1), (9, 1), (10, 1), (18, 0)], [(11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (18, 0)]], [[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (19, 0)], [(8, 1), (9, 1), (10, 1), (19, 0)], [(11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (19, 0)]]] lstB= [[[1, 1, 1, 1, 1, 1, 1, 1, -2], [1, 1, 1, -1], [1, 1, 1, 1, 1, -1]], [[1, 1, 1, 1, 1, 1, 1, 1, -2], [1, 1, 1, -1], [1, 1, 1, 1, 1, -1]], [[1, 1, 1, 1, 1, 1, 1, 1, -3], [1, 1, 1, -1], [1, 1, 1, 1, 1, -2]], [[1, 1, 1, 1, 1, 1, 1, 1, -3], [1, 1, 1, -1], [1, 1, 1, 1, 1, -2]]] lstC= [[[8], [3], [5]], [[8], [3], [5]], [[8], [3], [5]], [[8], [3], [5]]] Each of these lists consists of 4 lists, which at the same time, are composed of 3 lists. I need to match and print each element of a list with the one corresponding to the same position of the other lists: As an example, the first matched element will be: [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (16, 0)]), [1, 1, 1, 1, 1, 1, 1, 1, -2], [8] The second matched element will be: [(8, 1), (9, 1), (10, 1), (16, 0)], [1, 1, 1, -1], [3] Any suggestions to make this?
has title: Python matching
has answer: http://stackoverflow.com/a/50841041
favorite count: 0
has comment: http://stackoverflow.com/comment/88659704
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88534515
type: Comment
comment on: http://stackoverflow.com/a/50763243
type: AnswerComment
has text: mar = 10 should return 6?
score: 0

http://stackoverflow.com/q/50807744
has comment: http://stackoverflow.com/comment/88878316
has answer: http://stackoverflow.com/a/76232679
possible better answer: http://stackoverflow.com/a/60673209
has answer: http://stackoverflow.com/a/54064241
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/73576635
answer count: 8
upvote count: 63
type: AnsweredQuestion
score: 62
has comment: http://stackoverflow.com/comment/88621307
tagged with: dataframe
has answer: http://stackoverflow.com/a/60673209
has answer: http://stackoverflow.com/a/70962962
has comment: http://stackoverflow.com/comment/88621337
has answer: http://stackoverflow.com/a/62153724
has answer: http://stackoverflow.com/a/50939211
accepted answer: http://stackoverflow.com/a/50939211
has title: Apply CSS class to Pandas DataFrame using to_html
has body: I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame. "classes : str or list or tuple, default None CSS class(es) to apply to the resulting html table" from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html I am able to render a styled DataFrame like this (for example): df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B']) myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render() with open('myhtml.html','w') as f: f.write(myhtml) How can I style html output from a DataFrame using "classes" with "to_html" like this: df.to_html('myhtml.html',classes=&lt;something here&gt;)
favorite count: 0
has answer: http://stackoverflow.com/a/70569004
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/88422085
type: QuestionComment
type: Comment
has text: I use cache indeed, just omitted it from the code samples
score: 0
comment on: http://stackoverflow.com/q/50706311

http://stackoverflow.com/a/56461718
has comment: http://stackoverflow.com/comment/133744400
score: 7
has body: Are you trying to install shap - a library for explaining Machine Learning models? If so use pip install shap See the shap documentation for more info: https://pypi.org/project/shap/
has comment: http://stackoverflow.com/comment/100149732
has comment: http://stackoverflow.com/comment/120302224
answers question: http://stackoverflow.com/q/50731984
has comment: http://stackoverflow.com/comment/120322425
upvote count: 7
type: Answer
downvote count: 0

http://stackoverflow.com/q/50790655
tagged with: gio
tagged with: python
has title: Using GTK/GIO async reads in Python
tagged with: gtk
score: 1
upvote count: 1
has body: I'm trying to do asynchronous reads with GTK/GIO in Python, but while the read itself works okay (in that the callback is called only after the wanted number of bytes has been input), I haven't been able to find any way to actually access the result. Given this code: from gi.repository import Gtk, GLib, Gio import sys def callback(stream, task): result = stream.read_all_finish(task) print(stream, task, task.get_user_data(), task.get_task_data(), result, buf) Gtk.main_quit() buf = bytearray(4) stream = Gio.UnixInputStream.new(sys.stdin.fileno(), False) stream.read_all_async(buf, GLib.PRIORITY_DEFAULT, None, callback) Gtk.main() When run, it'll wait until at least 4 bytes have been input, so a single a&lt;return&gt; will not cause it to exit, but a second one will. The print will result in something like: &lt;Gio.UnixInputStream object at 0x7f1045dc3708 (GUnixInputStream at 0x1b8c160)&gt; &lt;Gio.Task object at 0x7f1045dc3bd0 (GTask at 0x1b8e860)&gt; 28890912 28207104 (True, bytes_read=4) bytearray(b'\x00\x00\x00\x00') In other words... get_user_data() and get_task_data() seem to be of no help, since they return integers (whose meaning I have no clue about) The return value from read_all_finish() seems to be of no help, since it's just a success/fail bool plus a bytes_read integer field The buffer that we gave to read_all_async() seems to be of no help, since it remains unchanged, even though one might expect it to hold the result of the read... I've also tried... Inspecting the same things before the read_all_finish() call, just in case that call did something like clear the buffer for some reason - no dice, that gives the same result Using array('b', [0]*4) instead of the bytearray - that gives the same effect as well Using an integer count in place of buf (because it seems that an older version of the API worked that way) - that just results in TypeError: Must be sequence, not int Using a file instead of stdin - no change Using read_async()/read_finish() instead - …
type: Question
has answer: http://stackoverflow.com/a/50790656
answer count: 1
downvote count: 0
tagged with: gtk3
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/50837678
type: Answer
has body: Uninstalled both 2.7 and 3, and uninstalled mercurial then brew install-ed both python@2 and python@3.
score: 0
answers question: http://stackoverflow.com/q/50836237

http://stackoverflow.com/comment/88549305
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50770785
type: AnswerComment
has text: It works very well. I really thank you very much. You explain very clearly. Really thank you

http://stackoverflow.com/comment/88680068
score: 1
has text: You may need to pass `day_first=True` to `pd.to_datetime`.
type: Comment
comment on: http://stackoverflow.com/q/50838170
type: QuestionComment

http://stackoverflow.com/comment/88698492
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50846441
has text: The right plot shows roughly 1000 boxplots. They are so thin they might appear as lines.
score: 1

http://stackoverflow.com/q/50784137
has answer: http://stackoverflow.com/a/50784333
type: AnsweredQuestion
downvote count: 0
tagged with: flask
favorite count: 0
type: Question
tagged with: python
tagged with: python-3.x
score: 15
accepted answer: http://stackoverflow.com/a/50784333
linked to: http://stackoverflow.com/q/34457981
has comment: http://stackoverflow.com/comment/88575338
has body: I have a very simple code here: from flask import Flask app = Flask(__name__) if __name__ == '__main__': app.run(debug=True) I have run it the first time and it worked, then ctrl+c didn't work so I just killed python terminal myself. Then I tried to run it again and I get an error: * Serving Flask app "untitled1" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3/dist- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "/usr/lib/python3/dist- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 88, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) File "/home/teoman/Desktop/flaskapp/untitled1.py", line 13, in &lt;module&gt; app.run(debug=True) File "/home/teoman/.local/lib/python3.5/site-packages/flask/app.py", line 943, in run run_simple(host, port, self, **options) File "/home/teoman/.local/lib/python3.5/site- packages/werkzeug/serving.py", line 795, in run_simple s.bind(get_sockaddr(hostname, port, address_family)) OSError: [Errno 98] Address already in use I have found similar questions asked but I couldn't understand it because of the solutions were also complicated, I'm very new to Flask app (like ten minutes), I use Linux Mint MATE. NOTE: localhost:5000 works fine still I do not have any python command-lines open working Flask app.
answer count: 1
duplicate of: http://stackoverflow.com/q/34457981
has comment: http://stackoverflow.com/comment/88575561
has title: Flask: OSError: [Errno 98] Address already in use - but why?
upvote count: 15

http://stackoverflow.com/a/50742641
answers question: http://stackoverflow.com/q/50727595
upvote count: 11
type: AcceptedAnswer
has body: At a first glance to your code trial it seems there is a minor bug in the value of the argument executable_path. Instead of hromedriver.exe it should have been: # Windows OS driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe') # Linux OS driver = webdriver.Chrome(executable_path='/path/to/chromedriver') This error message... selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver.exe ...implies that the the program/script was unable to initiate/spawn the ChromeDriverService through chromedriver.exe. The potential reason for the error can be: Due to missing the entry 127.0.0.1 localhost in /etc/hosts Solution Windows OS - Add 127.0.0.1 localhost to /etc/hosts Mac OSX - Ensure the following entries: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost fe80::1%lo0 localhost References As per the discussion in selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service geckodriver: Selenium does not require 127.0.0.1 localhost to be explicitly set in the host file. However it is mandatory requirement to map localhost to the IPv4 local loopback (127.0.0.1) The mechanism of this mapping does not have to be through the hosts file always. On Windows OS systems it is not mapped in the hosts file at all (resolving localhost is done by the DNS resolver). TL;DR How to reset the Hosts file back to the default
has comment: http://stackoverflow.com/comment/134579217
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/88497150
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50727595

http://stackoverflow.com/q/50798515
tagged with: knn
has title: How to return 'faiss' unique vector id on 'add_with_ids' trained index?
has answer: http://stackoverflow.com/a/51878585
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/122153372
has body: I'm using Facebook's faiss index with custom indexes using the add_with_ids method. In inference time I use distance, ID = model.search() which returns the custom ID it was trained with. Is it possible to return also a unique id without retraining? Or just return the actual closest vector? Thank you!
upvote count: 1
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/a/50771019
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50761646
type: Answer
answers question: http://stackoverflow.com/q/50761646
has body: The Loader was the problem, the request was correct, I've try all the loaders from Three.js, only THREE.ObjectLoader() finnaly worked is used https://threejs.org/editor/ to make a scene.json file
score: 0

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/50709874
type: Tag
tags question: http://stackoverflow.com/q/50724300
tags question: http://stackoverflow.com/q/50719857
tags question: http://stackoverflow.com/q/50834357
tags question: http://stackoverflow.com/q/50782385
tags question: http://stackoverflow.com/q/50711558
tags question: http://stackoverflow.com/q/50767668
tags question: http://stackoverflow.com/q/50827916
tags question: http://stackoverflow.com/q/50719722
tags question: http://stackoverflow.com/q/50711969
tags question: http://stackoverflow.com/q/50785498
tag name: csv
tags question: http://stackoverflow.com/q/50767758
tags question: http://stackoverflow.com/q/50749955
tags question: http://stackoverflow.com/q/50789526
tags question: http://stackoverflow.com/q/50831315
tags question: http://stackoverflow.com/q/50708269
tags question: http://stackoverflow.com/q/50706513
tags question: http://stackoverflow.com/q/50729511
tags question: http://stackoverflow.com/q/50810204
tags question: http://stackoverflow.com/q/50722088
tags question: http://stackoverflow.com/q/50823134
tags question: http://stackoverflow.com/q/50728574
tags question: http://stackoverflow.com/q/50767257
tags question: http://stackoverflow.com/q/50731160
tags question: http://stackoverflow.com/q/50854622
tags question: http://stackoverflow.com/q/50779879
tags question: http://stackoverflow.com/q/50745365
tags question: http://stackoverflow.com/q/50732536
tags question: http://stackoverflow.com/q/50805095
tags question: http://stackoverflow.com/q/50847000
tags question: http://stackoverflow.com/q/50759046
tags question: http://stackoverflow.com/q/50772596
tags question: http://stackoverflow.com/q/50725635
tags question: http://stackoverflow.com/q/50802385
tags question: http://stackoverflow.com/q/50811671
tags question: http://stackoverflow.com/q/50826895
tags question: http://stackoverflow.com/q/50722067
tags question: http://stackoverflow.com/q/50751687
tags question: http://stackoverflow.com/q/50808519
tags question: http://stackoverflow.com/q/50751330
tags question: http://stackoverflow.com/q/50821934
tags question: http://stackoverflow.com/q/50786798
tags question: http://stackoverflow.com/q/50773564
tags question: http://stackoverflow.com/q/50837353
tags question: http://stackoverflow.com/q/50794024
tags question: http://stackoverflow.com/q/50741843
tags question: http://stackoverflow.com/q/50800042
tags question: http://stackoverflow.com/q/50712919
tags question: http://stackoverflow.com/q/50782566
tags question: http://stackoverflow.com/q/50851490
tags question: http://stackoverflow.com/q/50727479
tags question: http://stackoverflow.com/q/50715173
tags question: http://stackoverflow.com/q/50741918
tags question: http://stackoverflow.com/q/50776914
tags question: http://stackoverflow.com/q/50703192
tags question: http://stackoverflow.com/q/50831039
tags question: http://stackoverflow.com/q/50703425
tags question: http://stackoverflow.com/q/50759525
tags question: http://stackoverflow.com/q/50821092
tags question: http://stackoverflow.com/q/50712345
tags question: http://stackoverflow.com/q/50822660
tags question: http://stackoverflow.com/q/50704236
tags question: http://stackoverflow.com/q/50843859
tags question: http://stackoverflow.com/q/50726374
tags question: http://stackoverflow.com/q/50760799
tags question: http://stackoverflow.com/q/50772112
tags question: http://stackoverflow.com/q/50720753
tags question: http://stackoverflow.com/q/50844968
tags question: http://stackoverflow.com/q/50780220
tags question: http://stackoverflow.com/q/50711335
tags question: http://stackoverflow.com/q/50708959
tags question: http://stackoverflow.com/q/50764860
tags question: http://stackoverflow.com/q/50849207
tags question: http://stackoverflow.com/q/50809450
tags question: http://stackoverflow.com/q/50728223
tags question: http://stackoverflow.com/q/50701023
tags question: http://stackoverflow.com/q/50778481
tags question: http://stackoverflow.com/q/50836608

http://stackoverflow.com/a/50805651
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50805089
has comment: http://stackoverflow.com/comment/88617517
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50805089
has body: Still not sure what you mean by "efficient way". Try below solution and let me know in case some improvements required: driver.get("http://urbantoronto.ca/database/") # Use @id of filter as key, @ids of check-box as values filters = {"filter_status": ["pre_construction", "under_construction", "complete"], "filter_project_type": ["condo", "hotel", "institutional"]} for filter_item in filters: driver.find_element_by_id("%s_arrow" % filter_item).click() for checkbox in filters[filter_item]: driver.find_element_by_id(filter_item).find_element_by_id("check_%s" % checkbox).click()
type: Answer
score: 1

http://stackoverflow.com/comment/88470992
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50731575
has text: Huh. I didn't know you could do this for any property. Cool. It's still (in my view) excessive typing but it works.
score: 0

http://stackoverflow.com/comment/88561813
has text: Im not having any luck getting that to work. it says `& unexpected at this time` Ive figured out the first part, but what does |& do? and grep is unix right? im trying to run this in windows shell
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50776805
type: Comment

http://stackoverflow.com/comment/88567473
type: Comment
comment on: http://stackoverflow.com/a/50780257
type: AnswerComment
score: 0
has text: Biting the bullet, this one is on me and not a dupe in fact. Then again, advice still stands... kinda? Anyway, you may need to modify this answer to address OP's question.

http://stackoverflow.com/comment/88563163
comment on: http://stackoverflow.com/a/50778138
type: Comment
has text: I would say it's not quite ethical to post an answer, that has been already posted 10 minutes ago without any significant difference.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50738397
has comment: http://stackoverflow.com/comment/88484472
type: Question
has answer: http://stackoverflow.com/a/67238855
has body: I need to make tag author in this line This is your random {} pick, token = "xxxxxxxxxxxxxxxxxxxxxxxx" prefix = "?" import discord from discord.ext import commands from discord.ext.commands import Bot import random bot = commands.Bot(command_prefix=prefix) bot.remove_command("help") @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') answers = ["apple", "ball", "cat", "dog", "elephant", "frog", "gun"] @bot.command() async def choose(k : int): """Chooses between multiple choices.""" if 0 &lt;= k &lt;= 10: await bot.say("This is your random {} pick, {}".format(k, ctx.message.author.mention)) embed = discord.Embed(description='\n'.join(random.choices(answers, k=k))) await bot.say(embed=embed) else: await bot.say("Invalid number") bot.run(token) getting error like this while command used. Ignoring exception in command choose Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "E:\Test.py", line 25, in choose await bot.say("This is your random {} pick, {}".format(k, ctx.message.author.mention)) NameError: name 'ctx' is not defined The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands yield from command.invoke(ctx) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 374, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'ctx' is not defined
answer count: 2
tagged with: discord.py
score: 0
tagged with: python
tagged with: discord
linked to: http://stackoverflow.com/q/50722715
possible better answer: http://stackoverflow.com/a/67238855
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50742239
accepted answer: http://stackoverflow.com/a/50742239
has title: Mention Author Python Bot

http://stackoverflow.com/comment/88592617
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50793063
has text: please see [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)
type: Comment

http://stackoverflow.com/comment/88473114
type: Comment
has text: Could you print `allIndices.shape` ; `type(g)` and `type(el)`?
comment on: http://stackoverflow.com/a/50732453
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88559880
score: 0
type: Comment
type: QuestionComment
has text: @HarisNadeem I need the max amount of memory I can have to be running these projects, and virtual machines I've found run slow and are a slight hassle to set up. I'd rather do it just right on my computer where all my commands and things I'm used to are right here.
comment on: http://stackoverflow.com/q/50772096

http://stackoverflow.com/comment/88421596
type: Comment
comment on: http://stackoverflow.com/a/50705552
score: 0
type: AnswerComment
has text: Can you try this code : rdr = csv.reader((line.replace('\0','') for line in source),delimiter=',') Also can you share the line in the data which is causing error

iptables
type: Tag
tags question: http://stackoverflow.com/q/50732261
tag name: iptables

http://stackoverflow.com/comment/88467097
comment on: http://stackoverflow.com/q/50729511
type: QuestionComment
type: Comment
has text: Dear sir, please assign the result back to a column.
score: 0

http://stackoverflow.com/a/50792441
type: Answer
answers question: http://stackoverflow.com/q/50792344
has body: Using an extra variable you can achieve this : some_list = ["item1", "item2", "item3", "item4", "item5"] flag = False for item in some_list: # If it came to item3 and it's interrupted. How can I know that? if item==some_list[2]: flag=True break Checking value of flag variable you can check whether the loop is interrupted or not. Note : You can use for/else statement in Python: some_list = ["item1", "item2", "item3", "item4", "item5"] for item in some_list: # If it came to item3 and it's interrupted. How can I know that? if item==some_list[2]: break else: #this block will execute if your loop ends without interruption print("The loop completed without any interruption)
score: 0

http://stackoverflow.com/comment/88639894
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50817415
score: 0
has text: what is you error? can you post that as well?

http://stackoverflow.com/comment/88606115
type: QuestionComment
comment on: http://stackoverflow.com/q/50793126
has text: I am not sure if I understood your problem. What do you mean by several boards? What exactly do you want to find? Anyway, your image seems very noise. Can't you change colors or apply a noise reduction filter?
score: 1
type: Comment

http://stackoverflow.com/comment/88468862
has text: Thank you for your comment. 2. I want to remove such characters. 1. After manually removing the characters in my example, Amazon MTurk accept my CSV file. So I think some of them are more than three bytes.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50730466
score: 0

http://stackoverflow.com/q/50774662
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/88558464
tagged with: conda
has answer: http://stackoverflow.com/a/62154827
linked to: http://stackoverflow.com/q/38066873
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Can run Tensorflow within conda env, but then cannot access other anacona modules (matplotlib, pandas etc)
has comment: http://stackoverflow.com/comment/88556290
has answer: http://stackoverflow.com/a/50774822
downvote count: 1
tagged with: anaconda
has body: I have created a conda environment named tensorflow, and installed tensorflow within this environment following the official install guide (https://www.tensorflow.org/install/install_linux#installing_with_anaconda) When I activate the virtual environment I can import tensorflow, but cannot import other modules from anaconda such as pandas or matplotlib. Do I need to re-install all the modules that I want again within the tensorflow environment? If so, should I use conda rather than pip to install them? Is there an easier way to do this? Thanks for the help, I'm quite new to virtual environments.
tagged with: tensorflow
type: Question
answer count: 2

http://stackoverflow.com/comment/88467093
comment on: http://stackoverflow.com/q/50729574
score: 0
type: Comment
type: QuestionComment
has text: I know, this is the short version of my actual program.

http://stackoverflow.com/comment/88550271
score: 1
comment on: http://stackoverflow.com/q/50771322
has text: It is a list of two strings, not a set.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88477720
type: QuestionComment
has text: yeah, sphinx accuracy is bad, there are some methods to improve sphinx accuracy using dictionaries etc.
comment on: http://stackoverflow.com/q/50734535
score: 0
type: Comment

http://stackoverflow.com/a/50817116
downvote count: 0
answers question: http://stackoverflow.com/q/50817015
has body: Try this: class Foo(object): def __init__(self, msg): self._msg = msg def __call__(self): return self._msg foo = Foo('hello') print(foo()) # Prints 'hello' Foo.__call__ = lambda _: 'bye' #Notice the capital F, this is the class not the instance print(foo()) # Prints 'bye' The last call should print 'bye' like you expect. When you call an instance's functions, it's actually referring to the class functions (where they are defined)
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/50779304
has comment: http://stackoverflow.com/comment/88606630
accepted answer of: http://stackoverflow.com/q/50776985
has comment: http://stackoverflow.com/comment/88584740
upvote count: 6
answers question: http://stackoverflow.com/q/50776985
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88584879
type: Answer
has body: Understanding the error message: ValueError: endog and exog matrices are different sizes Okay, not too bad. The endogenous matrix and exogenous matrix are of different sizes. And the module provides this page which tells that endogenous are the factors within the system and exogenous are factors outside it. Some debugging Check what shapes we are getting for our arrays. To do that we need to take apart that oneliner and print of the .shape of the arguments or maybe print the first handful of each. Also, comment out the line throwing the error. So there, we discover that we get: chunk [490] factor [1000 4] chunk [510] factor [1000 4] Oh! There it is. We were expecting factor to be chunked too. It should be [490 4] the first time and [510 4] the second time. Note: since the categories are assigned randomly, this will differ each time. So basically we have just too much info in that function. We can use the chunk to see what factors to chose, filter the factors to be just those and then everything will work. Looking over the function definitions in the docs: class statsmodels.regression.linear_model.OLS(endog, exog=None, missing='none', hasconst=None, **kwargs) We are just passing two arguments and the rest are optional. Let's look at the two we are passing. endog (array-like) – 1-d endogenous response variable. The dependent variable. exog (array-like) – A nobs x k array where nobs is the number of observations and k is the number of regressors... Ah, endog and exog again. endog is 1d array-like. So far so good, shape 490 works. exog nobs? Oh, its number of observations. So it's a 2d array and in this case, we need shape 490 by 4. This specific issue: beta_exposure should be: def beta_exposure(chunk, factors=None): factors = factors.loc[factors.index.isin(chunk.index)] return sm.OLS(np.asarray(chunk), np.asarray(factors)).fit().params The issue is that you are applying beta_exposures to each part of the list (it is randomized, so let's say 490 elements for Financial a…
has comment: http://stackoverflow.com/comment/88584639
downvote count: 0
score: 6

http://stackoverflow.com/comment/97387459
score: 1
comment on: http://stackoverflow.com/a/53950575
type: AnswerComment
type: Comment
has text: Thanks @user985366. This was the only way I've found to enable CORS for a `flask_restplus` route that uses [response marshalling](https://flask-restplus.readthedocs.io/en/stable/marshalling.html)

http://stackoverflow.com/comment/88592421
has text: How do you launch your application? What's your current behavior?
comment on: http://stackoverflow.com/q/50793098
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88470233
has text: Please post pictures if you want to make it hard for people to answer your questions.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50731253

http://stackoverflow.com/comment/88554832
type: Comment
comment on: http://stackoverflow.com/q/50773874
has text: `np.round_(..)` because the method you are calling belongs to `np` - not to the ndarray `a` - you do not need to memorize them, you can look them up: https://docs.scipy.org/doc/numpy-1.13.0/reference/ - methods need () , properties do not.
score: 0
type: QuestionComment

http://stackoverflow.com/a/69294222
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50726713
downvote count: 0
has body: Values of lambda that are very close to one will show those terms that have the highest ratio between frequency of the terms for that specific topic and the overall frequency of the terms from the corpus I don't agree with Ledian K's sentence above. The paper he linked helped explain how to interpret the bars though. Relevance in that paper is a weighted average of 2 terms. The single variable lambda controls the weighting. The 2 terms contains 2 ideas: pw: empirical distribution of a term in the corpus phikw: probability of term given a topic The gray/blue (color depending on version) bar represents idea 1. The red bar represents idea 2. The 1st term in the weighted average is log(idea2)--&gt; log(phikw) The 2nd term in the weighted average is log(idea2/idea1) --&gt; log(phikw/pw) Lambda = 1 means the relevance is defined entirely by the 1st term, which only contains idea2. Lambda = 0 means the relevance is defined entirely by the 2nd term which contains idea2 divided by idea 1 (the lift, also referenced in that paper as Taddy(2011)) Graphically Interpretations lambda = 1 means the bars are sorted by red bar width, nevermind what the blue bars are, meaning the lift over marginal (sum across topics) term probabilities are ignored. You can also observe that the blue bar widths are the same no matter what topic circle you click, because they are a corpus-wide property, independent of topics. lambda = 0 means the bars are sorted by the ratio of red bar coverage over blue bar (with a maximum ratio at 1 meaning red bar completely covers blue). As lambda increases, you will see more blue bar not being covered by red. I'm guessing the lengths of bars do not match the frequencies seen from Dictionary.cfs because of the smoothing mentioned in the paper. Also addressed here: https://pyldavis.readthedocs.io/en/latest/history.html The downside is that the blue bar widths do not necessarily match the user-supplied term frequencies exactly – in fact, the new version of LDAvis ign…
type: Answer

http://stackoverflow.com/comment/88533257
type: Comment
type: QuestionComment
score: 0
has text: Please provide the full stacktrace
comment on: http://stackoverflow.com/q/50762741

http://stackoverflow.com/comment/88724027
score: 1
comment on: http://stackoverflow.com/q/50848661
type: QuestionComment
has text: Ticket in PyCharms' issue tracker: PY-30459.
type: Comment

http://stackoverflow.com/q/50779557
duplicate of: http://stackoverflow.com/q/45360615
has comment: http://stackoverflow.com/comment/88566097
type: Question
tagged with: http://stackoverflow.com/tag/json
has body: I'm trying to make a save/load function to try and save/load the positions of blocks on-screen. These blocks are stored in a pygame Group called blocks. Here is the portion of the code I use to save with json: blocks_json_str = json.dumps(blocks, sort_keys = True, indent = 4) os.path.join(saves_path, "inventory", "inventory.txt").write_text(blocks_json_str) ..and here is the code to load the data: assert json.loads((os.path.join(saves_path, "inventory", "inventory.txt")).read_text()) == blocks However, I get this error: TypeError: Object of type 'Group' is not JSON serializable Is there a good way to save/load Groups with JSON? If there is, what is it? If there's not, what is a good alternative for saving Groups?
has comment: http://stackoverflow.com/comment/88566086
has title: How can I use JSON to save/load pygame.Group() objects?
type: UnansweredQuestion
tagged with: python
tagged with: pygame
linked to: http://stackoverflow.com/q/45360615
answer count: 0
score: 0
tagged with: save

http://stackoverflow.com/q/50847904
has answer: http://stackoverflow.com/a/50848412
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50848412
accepted answer: http://stackoverflow.com/a/50847920
has title: Dropping selected rows in Pandas with duplicated columns
score: 0
answer count: 2
has body: Suppose I have a dataframe like this: fname lname email Joe Aaron Joe Aaron some@some.com Bill Smith Bill Smith Bill Smith some2@some.com Is there a terse and convenient way to drop rows where {fname, lname} is duplicated and email is blank?
tagged with: pandas
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50847920
type: AnsweredQuestion

http://stackoverflow.com/a/67526111
has body: There doesn't seem to be a built in way but you can do this: import cProfile import pstats p = cProfile.Profile() s = p.run("1+1") pstats.Stats(s).sort_stats(2).print_stats()
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50731065
upvote count: 2

http://stackoverflow.com/comment/88479228
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50713180
has text: I am copying from one database to another. When i used sqlplus or toad, i had issues with certain datasets and found that i can overcome them using this script.
score: 0

groovy
tags question: http://stackoverflow.com/q/50715123
type: Tag
tag name: groovy

http://stackoverflow.com/q/50775312
has answer: http://stackoverflow.com/a/50776578
answer count: 2
downvote count: 0
favorite count: 0
has title: Filtering outliers from DataFrame
has comment: http://stackoverflow.com/comment/88557736
has comment: http://stackoverflow.com/comment/88557896
tagged with: python
has comment: http://stackoverflow.com/comment/88557903
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88557799
score: 1
tagged with: outliers
has answer: http://stackoverflow.com/a/50775883
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88558022
tagged with: filtering
linked to: http://stackoverflow.com/q/23199796
accepted answer: http://stackoverflow.com/a/50775883
has comment: http://stackoverflow.com/comment/88557588
has comment: http://stackoverflow.com/comment/88557887
possible better answer: http://stackoverflow.com/a/50776578
tagged with: dataframe
has body: I have a big problem filtering my data. I've read a lot here on stackoverflow and ion other pages and tutorials, but I could not solve my specific problem... The first part of my code, where I load my data into python looks as follow: import numpy as np import pandas as pd import matplotlib.pyplot as plt from arch import arch_model spotmarket = pd.read_excel("./data/external/Spotmarket_dhp.xlsx", index=True) r = spotmarket['Price'].pct_change().dropna() returns = 100 * r df = pd.DataFrame(returns) The excel table has 43.000 values in one column and includes the hourly prices. I use this data to calculate the percentage change from hour to hour and the problem is, that there are sometimes big changes between 1000 to 40000%. The dataframe looks as follow: df Out[12]: Price 1 20.608229 2 -2.046870 3 6.147789 4 16.519258 ... 43827 -16.079874 43828 -0.438322 43829 -40.314465 43830 -100.105374 43831 700.000000 43832 -62.500000 43833 -40400.000000 43834 1.240695 43835 52.124183 43836 12.996778 43837 -17.157795 43838 -30.349971 43839 6.177924 43840 45.073701 43841 76.470588 43842 2.363636 43843 -2.161042 43844 -6.444781 43845 -14.877102 43846 6.762918 43847 -38.790036 [43847 rows x 1 columns] I wanna exclude this outliers. I've tried different ways like calculating the meanand the std and exclude all values which are + and - three times the std away from the mean. It works for a small part of the data, but for the complete data, the mean and std are both NaN. Has someone an idea, how I can filter my dataframe?

http://stackoverflow.com/q/50792640
accepted answer: http://stackoverflow.com/a/50792876
type: AnsweredQuestion
has title: How to extract data from a website's search bar using python?
possible better answer: http://stackoverflow.com/a/50792909
has answer: http://stackoverflow.com/a/50792909
type: Question
answer count: 2
score: 2
downvote count: 0
has body: I want to extract data from a website that contains the names of many doctors and hospitals I want to do some evaluations so I decided to use the search bar but unfortunately cannot seem to get my desired result! How can I do that? from bs4 import BeautifulSoup import requests import urllib.request types_of_doctor = ['dermatologist', 'gynecologist', 'paediatric-surgeon', 'cardiologist', 'diabetologists', 'eye-specialist'] def search(): for query in types_of_doctor: # Constracting http query url = 'http://health.hamariweb.com/doctors/' + query r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') Doctors_name = soup.findAll('a', {"class" : "NormalText"}) for doctors in Doctors_name: print(doctors.text) links = soup.select('a') header = types_of_doctor filename = 'AllNames.csv' f = open(filename, 'w') for head in header: f.write(head+'\t') for doctors in Doctors_name: print(doctors.text) f.write(doctors.text) search()
favorite count: 0
tagged with: beautifulsoup
upvote count: 2
has answer: http://stackoverflow.com/a/50792876
tagged with: python

http://stackoverflow.com/q/50757761
score: 4
has title: OpenAI Gradient Checkpointing with Tensorflow Eager Execution
answer count: 1
downvote count: 0
favorite count: 0
tagged with: tensorflow-gradient
tagged with: gradient-descent
type: UnansweredQuestion
tagged with: python
has body: I have recently switched to Tensorflow Eager (currently working with TF 1.8.0) and like it a lot. However, I now have quite a large model which does not fit into my GPU Memory (GTX 1080Ti, 12GB VRAM) when run with the Gradient Tape which is needed to calculate the gradients in TF. The forward pass (i.e. without using Gradient Tape) works fine. I thought about using the Gradient Checkpointing from OpenAI with the hope that this would help. However, simply using it as described in their Git does not seem to help within Eager Execution, i.e. import tensorflow as tf import tensorflow.contrib.eager as tfe import memory_saving_gradients tf.__dict__["gradients"] = memory_saving_gradients.gradients_memory # using gradients_memory or gradients_speed does not change anything # tf.__dict__["gradients"] = memory_saving_gradients.gradients_speed [...] with tfe.GradientTape() as g: output = run_large_model() loss = calculate_loss_on_output(output) grads = g.gradient(full, model.variables) optimizer.apply_gradients(zip(grads, model.variables)) runs out of memory, independent of using gradient checkpointing or not. My guess is that the gradient tape still stores all variables and the required information for the backward pass and the gradient checkpointing has no effect because TF in Eager mode doesn't actually construct a graph (from what I understand - or at least it's a different graph). Do you have any experience or any idea how this could be solved or what I need to do to use the gradient checkpointing also in TF Eager mode?
has answer: http://stackoverflow.com/a/50761998
tagged with: tensorflow
type: Question
upvote count: 4

http://stackoverflow.com/comment/88419066
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50704571
has text: Add `.reset_index()`
type: Comment

http://stackoverflow.com/q/50798353
has comment: http://stackoverflow.com/comment/88603474
has body: I have a User model, which generated the bellow table: in it the id is increase from 1. I have used my system in a spell, now I want to change the id of some user instance and start at 10000. in the database I can not change, it will report error: Cannot delete or update a parent row: a foreign key constraint fails (`qy`.`usermanage_user_groups`, CONSTRAINT `usermana_user_id_53f44f10_fk_qy_adm` FOREIGN KEY (`user_id`) REFERENCES `usermanage_user` (`id`)) Is it possible to change the id? if there is some related factors, how can I solved it one by one, such as usermanage_user_groups?
tagged with: mysql
has title: How can I change the initial value of `id` field?
has comment: http://stackoverflow.com/comment/88602555
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88602576
favorite count: 0
has answer: http://stackoverflow.com/a/50959783
has answer: http://stackoverflow.com/a/50798939
type: Question
tagged with: sql
has comment: http://stackoverflow.com/comment/88603139
score: 1
has comment: http://stackoverflow.com/comment/88602684
answer count: 3
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50798834
has comment: http://stackoverflow.com/comment/88602666

http://stackoverflow.com/q/50820844
has body: I've a string of dictionary as following: CREDENTIALS = "{\"aaaUser\": {\"attributes\": {\"pwd\": \"cisco123\", \"name\": \"admin\"}}}" Now I want to format this string to replace the pwd and name dynamically. What I've tried is: CREDENTIALS = "{\"aaaUser\": {\"attributes\": {\"pwd\": \"{0}\", \"name\": \"{1}\"}}}".format('password', 'username') But this gives following error: traceback (most recent call last): File ".\ll.py", line 4, in &lt;module&gt; CREDENTIALS = "{\"aaaUser\": {\"attributes\": {\"pwd\": \"{0}\", \"name\": \"{1}\"}}}".format('password', 'username') KeyError: '"aaaUser" It is possible by just loading the string as dict using json.loads()and then setting the attributes as required, but this is not what I want. I want to format the string, so that I can use this string in other files/modules. ' What I'm missing here? Any help would be appreciated.
has comment: http://stackoverflow.com/comment/88647421
has comment: http://stackoverflow.com/comment/88647366
type: Question
has answer: http://stackoverflow.com/a/50820971
linked to: http://stackoverflow.com/q/5466451
has comment: http://stackoverflow.com/comment/88646989
has comment: http://stackoverflow.com/comment/88647049
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88647635
has comment: http://stackoverflow.com/comment/88647491
has title: Format String of Dictionary
accepted answer: http://stackoverflow.com/a/50820971
tagged with: string
has comment: http://stackoverflow.com/comment/88647012
has answer: http://stackoverflow.com/a/50821398
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88647095
has comment: http://stackoverflow.com/comment/88646982
linked to: http://stackoverflow.com/q/50764286
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88647512
has comment: http://stackoverflow.com/comment/88647486
possible better answer: http://stackoverflow.com/a/50821398

http://stackoverflow.com/comment/114976498
has text: assuming mask is a numpy array, aren't you adding ann[0] twice? https://stackoverflow.com/questions/15579260/how-to-combine-multiple-numpy-masks
type: AnswerComment
comment on: http://stackoverflow.com/a/50827192
score: 4
type: Comment

http://stackoverflow.com/q/50801202
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I have a json sample like this: {"ratings": [{ "TERM": "movie1", "Rating": "3.5", "source": "15786" }, { "TERM": "movie2", "Rating": "3.5", "source": "15786" }, { "TERM": "Movie1", "Rating": "3.0", "source": "15781" } ]} Now I want to create a new json file out of this and logic to filter is to ignore a json object if TERM is already present once. So, for this sample the output will be {"ratings": [{ "TERM": "movie1", "Rating": "3.5", "source": "15786" }, { "TERM": "movie2", "Rating": "3.5", "source": "15786" } ]} As movie1 is is already present in index 0 we want to ignore index 2. I came up with this below logic which works fine for small samples. I have a sample with json array size of 10 milliion and this below code takes 2+days to complete. I am wondering if there is much more efficient way to do this: import json import io input1 = "movies.json" res=[] resTerms = [] with io.open(input1, encoding="utf8") as json_data: d = json.load(json_data) print(len(d['ratings'])) for x in d['ratings']: if x['TERM'].lower() not in resTerms: res.append(x) resTerms.append(x['TERM'].lower()) final ={} final["ratings"] = res output = "myFileSelected.json" with io.open(output, 'w') as outfile: json.dump(final, outfile)
type: Question
has answer: http://stackoverflow.com/a/50801745
has title: Efficient way to filter a json array of json objects in python
downvote count: 0
has comment: http://stackoverflow.com/comment/88608384
answer count: 1
has comment: http://stackoverflow.com/comment/94250316
favorite count: 0
accepted answer: http://stackoverflow.com/a/50801745

http://stackoverflow.com/q/50826609
tagged with: unicode
favorite count: 0
score: 0
has body: I've got a large json formatted string that I'm trying to convert into a python dictionary, but all of the keys and values are in unicode so they have a leading u in the string. When attempting to use json.loads() it complains that ValueError: Expecting property name: line 1 column 2 (char 1) because of the u. I have: x = "{u'abc': [{u'xyz': u'XYZ'}, {u'lmno': u'LMNO'}], u'def': u'DEF'}" json.loads(x) --&gt; ValueError I want: x = "{u'abc': [{u'xyz': u'XYZ'}, {u'lmno': u'LMNO'}], u'def': u'DEF'}" z = x.strip_unicode() r = json.loads(z) # r = {'abc': [{'xyz':'XYZ'}, {'lmno': 'LMNO'}], 'def': 'DEF'} So is there something like strip_unicode or maybe a different function from json where it can handle the leading u?
has comment: http://stackoverflow.com/comment/88723843
has comment: http://stackoverflow.com/comment/88657944
has comment: http://stackoverflow.com/comment/88658004
tagged with: python
has comment: http://stackoverflow.com/comment/88657982
has comment: http://stackoverflow.com/comment/88657971
answer count: 0
has comment: http://stackoverflow.com/comment/88657953
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88657918
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88657983
has comment: http://stackoverflow.com/comment/88659393
has comment: http://stackoverflow.com/comment/88658148
has comment: http://stackoverflow.com/comment/88662391
has comment: http://stackoverflow.com/comment/88658509
has comment: http://stackoverflow.com/comment/88662426
has title: json.loads with a unicode string

http://stackoverflow.com/comment/88679861
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50838011
score: 0
has text: Show your full code.

http://stackoverflow.com/q/50728464
has body: In Python, what is the difference between "*largs" and "*args" or "*kwargs" as an argument? Thank you in advance.
has comment: http://stackoverflow.com/comment/88464963
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: In Python, what is the difference between "*largs" and "*args" or "*kwargs"?
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/3394835
score: 1
duplicate of: http://stackoverflow.com/q/3394835
type: Question
duplicate of: http://stackoverflow.com/q/36901
has comment: http://stackoverflow.com/comment/88464950
has comment: http://stackoverflow.com/comment/88464912
has comment: http://stackoverflow.com/comment/88465003
upvote count: 1

http://stackoverflow.com/comment/88714915
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50841498
has text: To clarify my strategy: batch samples are contiguous by design (please see my original post edited) but I'm checking to be sure about that! (thanks for suggestion). I evaluated the hypotesis of differentiate signals before (to make them stationary) but this changes a lot my NN working strategy and it causes very lower performances...
score: 0

http://stackoverflow.com/comment/88609917
type: Comment
has text: @AntonvBR I'm not the best with descriptions, but did try :)
comment on: http://stackoverflow.com/a/50801863
score: 1
type: AnswerComment

http://stackoverflow.com/q/50751234
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50927582
type: Question
has comment: http://stackoverflow.com/comment/88510346
accepted answer: http://stackoverflow.com/a/50751396
score: 0
has comment: http://stackoverflow.com/comment/88510604
has answer: http://stackoverflow.com/a/50927582
answer count: 3
has answer: http://stackoverflow.com/a/50751396
tagged with: nested
has body: I am manipulating some data with Python that consists exclusively of part numbers and their relationship (parent/child) to other parts. The parts are on many levels of the bill of materials (BOM). What is the best way to store this data within Python? Originally, I used nested dictionaries as shown below with generic part numbers for readability (actual part names are random characters). However, I don't think storing data (part names) as a dictionary key is a good way to do this because it makes retrieving the part names difficult. &gt;&gt;&gt; BOM = {} &gt;&gt;&gt; BOM['Part 1'] = {} &gt;&gt;&gt; BOM['Part 1']['Part 1.1'] = {} &gt;&gt;&gt; BOM['Part 1']['Part 1.1']['Part 1.1.1'] = {} &gt;&gt;&gt; BOM['Part 1']['Part 1.2'] = {} &gt;&gt;&gt; BOM['Part 1']['Part 1.3'] = {} &gt;&gt;&gt; BOM['Part 2'] = {} &gt;&gt;&gt; BOM['Part 2']['Part 2.1'] = {} &gt;&gt;&gt; BOM['Part 2']['Part 2.2'] = {} &gt;&gt;&gt; BOM['Part 2']['Part 2.2']['Part 2.2.1'] = {} &gt;&gt;&gt; print(BOM) {'Part 1': {'Part 1.1': {'Part 1.1.1': {}}, 'Part 1.2': {}, 'Part 1.3': {}}, 'Part 2': {'Part 2.1': {}, 'Part 2.2': {}, 'Part 2.2.1': {}}} If not nested dictionaries, how should I store the parts? Or should I be using nested dictionaries differently?
has answer: http://stackoverflow.com/a/50751327
has title: Store a bill of materials in Python
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/88693909
comment on: http://stackoverflow.com/q/50844431
has text: It seems redundant to wrap `'long,'` in parens, since `type(('long,'))` yields `str`. Not a tuple since it doesn't have a trailing comma. It still seems a bit unclear regarding missing input data, since your `Joint_probas` looks like a tuple of tuples, and `Probas` is a single tuple, rather than dictionaries. Can you give us the dictionary structure of `Joint_probas`?
score: 0
type: Comment
type: QuestionComment

apache-spark
tags question: http://stackoverflow.com/q/50715173
tags question: http://stackoverflow.com/q/50722909
tags question: http://stackoverflow.com/q/50703852
tags question: http://stackoverflow.com/q/50708155
tags question: http://stackoverflow.com/q/50828011
tags question: http://stackoverflow.com/q/50778357
tags question: http://stackoverflow.com/q/50729345
tags question: http://stackoverflow.com/q/50752787
tags question: http://stackoverflow.com/q/50805994
tags question: http://stackoverflow.com/q/50762559
tags question: http://stackoverflow.com/q/50816767
tags question: http://stackoverflow.com/q/50758115
tags question: http://stackoverflow.com/q/50847041
tags question: http://stackoverflow.com/q/50804431
tag name: apache-spark
tags question: http://stackoverflow.com/q/50790837
tags question: http://stackoverflow.com/q/50838620
tags question: http://stackoverflow.com/q/50749596
tags question: http://stackoverflow.com/q/50754517
tags question: http://stackoverflow.com/q/50741418
tags question: http://stackoverflow.com/q/50763533
tags question: http://stackoverflow.com/q/50751687
tags question: http://stackoverflow.com/q/50844769
tags question: http://stackoverflow.com/q/50730082
tags question: http://stackoverflow.com/q/50725635
tags question: http://stackoverflow.com/q/50848977
tags question: http://stackoverflow.com/q/50722920
type: Tag
tags question: http://stackoverflow.com/q/50755127
tags question: http://stackoverflow.com/q/50721831
tags question: http://stackoverflow.com/q/50762320
tags question: http://stackoverflow.com/q/50822294

http://stackoverflow.com/a/51214316
score: 0
has body: Not sure if you still need this answered, but I came across this same error today. For me, the cause was not having pdftk installed on my machine. It looks like this library requires the server version found here: https://www.pdflabs.com/tools/pdftk-server/ Also, the default path is /usr/bin/pdftk, so you may have to add the PDFTK_PATH environment variable to make it work.
answers question: http://stackoverflow.com/q/50807174
type: Answer

http://stackoverflow.com/q/50782664
has comment: http://stackoverflow.com/comment/88571870
has body: I am new to django. Is there any way to load javascript in .py files? I need to access a json, defined in one of my .js files in the middle of one of my functions in a .py file. How is that possible? update: json in my chart-options.js file is: var theme = { exporting: { enabled: false }, lang: { thousandsSep: thousand_separator_symbol, decimalPoint: ".", numericSymbols: null }, . . . . and in my function in views.py: . . options = get_default_options() // here I need to access the theme and have chart_options = theme from .js options.update(chart_options) . . . . tnx
tagged with: python
has title: load javascript in views
has comment: http://stackoverflow.com/comment/88572277
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88572119
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/88571969
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50782937

http://stackoverflow.com/q/50807815
favorite count: 0
tagged with: python-3.x
has title: Trying to return relevant information from a list of lists based on user input
tagged with: python
accepted answer: http://stackoverflow.com/a/50807973
has body: I'm very new to Python, and I just can't get the hang of functions yet. I have a list of lists that has 3 products, their inventory, and their price. products = [['milk', 'eggs','bread'], [10,15,20], [3.50, 2.00, 2.50]] I want to create a function so that the user input can choose which product they want information about, and if they want the inventory number, the price, or both. def return_information(): Does this require a ton of nested if statements or am I overthinking it in that way? Should my user input statements take place within this first function or do they belong in a main function where I execute the whole program?
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50807973
type: Question
has comment: http://stackoverflow.com/comment/88621498
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/88700935
score: 0
type: AnswerComment
type: Comment
has text: Thanks a lot for you help that actually I wanted you save my live you are a hero without cap
comment on: http://stackoverflow.com/a/50844156

http://stackoverflow.com/q/50735507
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50735822
tagged with: large-files
has answer: http://stackoverflow.com/a/50735822
linked to: http://stackoverflow.com/q/10801760
has answer: http://stackoverflow.com/a/50736212
accepted answer: http://stackoverflow.com/a/50735943
type: Question
score: 4
has comment: http://stackoverflow.com/comment/88478934
upvote count: 4
has comment: http://stackoverflow.com/comment/88479171
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50735943
favorite count: 0
has body: This is follow up question to Compare two large files which is answerd by phihag I want to display the count of lines which are different after comparing two files. Want to display if after program completion as a message by saying count of lines are in difference. My try: with open(file2) as b: blines = set(b) with open(file1) as a: with open(file3, 'w') as result: for line in a: if line not in blines: result.write(line) lines_to_write = [] with open(file2) as b: blines = set(b) with open(file1) as a: lines_to_write = [l for l in a if l not in blines] print('count of lines are in difference:', len(lines_to_write))
has title: Python : Compare two large files
tagged with: python
tagged with: large-data

http://stackoverflow.com/comment/88529746
has text: Traceback (most recent call last): File "delete.py", line 16, in <module> File "site-packages\win10toast\__init__.py", line 127, in show_toast File "site-packages\win10toast\__init__.py", line 93, in _show_toast File "site-packages\pkg_resources\__init__.py", line 1225, in resource_filename File "site-packages\pkg_resources\__init__.py", line 436, in get_provider File "site-packages\pkg_resources\__init__.py", line 984, in require
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50758709
type: Comment

http://stackoverflow.com/q/50853397
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 3
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/88709578
has comment: http://stackoverflow.com/comment/88709647
type: Question
has comment: http://stackoverflow.com/comment/88712375
has body: I am trying to install django-rest-swagger into a virtual machine but it is giving error Failed Building wheel for simplejson i tried searching for some solution but as far as i was able to understand is that there is some dependency on visual studio... i have microsoft visual studio 2015 installed on my system I am attaching the installation report and see just before the error its written unable to find specified path and there is a path for library of visual studio
has comment: http://stackoverflow.com/comment/88710644
has title: unable to install django-rest-swagger
has comment: http://stackoverflow.com/comment/88714043
downvote count: 0
has comment: http://stackoverflow.com/comment/88712975
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/88709594
linked to: http://stackoverflow.com/q/47551274
favorite count: 0
has comment: http://stackoverflow.com/comment/88710412
tagged with: django-rest-swagger

http://stackoverflow.com/comment/88482541
score: 0
type: QuestionComment
has text: No wonder you can't use your python code in Julia without declaring all the paths & installing required dependencies
type: Comment
comment on: http://stackoverflow.com/q/50736394

http://stackoverflow.com/comment/88433324
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50712197
has text: Can you paste your XML here so that it's easier for others to try?

http://stackoverflow.com/a/51331196
accepted answer of: http://stackoverflow.com/q/50828262
score: 0
has body: Another more forward-looking solution is to use spaCy to build the model instead of textblob or nltk. This is new to me, but seems a lot easier to use and more powerful: https://spacy.io/usage/spacy-101#section-lightning-tour "spaCy is the Ruby of Rails of natural language processing." import spacy import random nlp = spacy.load('en') # loads the trained starter model here train_data = [("Uber blew through $1 million", {'entities': [(0, 4, 'ORG')]})] # better model stuff with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != 'ner']): optimizer = nlp.begin_training() for i in range(10): random.shuffle(train_data) for text, annotations in train_data: nlp.update([text], [annotations], sgd=optimizer) nlp.to_disk('/model')
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/103113718
answers question: http://stackoverflow.com/q/50828262

http://stackoverflow.com/a/50847468
answers question: http://stackoverflow.com/q/50846719
downvote count: 1
upvote count: 5
score: 4
has body: We can only assume that you refer to non-ASCI as 'special' characters. To remove all non-ASCI characters in a pandas dataframe column, do the following: df['clean_titles'] = df['titles'].str.replace(r'[^\x00-\x7f]', '') Note that this is a scalable solution as it works for any non-ASCI char.
type: Answer

http://stackoverflow.com/comment/96673542
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50754111
has text: That's not the reason why it's not working. numpy won't add the two arrays together

http://stackoverflow.com/comment/88622827
has text: install pyserial
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50808574

http://stackoverflow.com/a/50750549
downvote count: 0
has body: Since this seems to be the solution: You simply have one SSH connection to the machine that calls a single script: ssh me@raspi "bash ~/caller.sh" That script will call all of your functions: #!/usr/bin/env bash python script1.py &amp; python script2.py &amp; python script3.py &amp; python script4.py &amp; The &amp; at the end of the line means that the command for that line will be run in the background and bash will not wait for that line to finish before starting the next one. The &amp; on the last command is optional depending on whether you want to be returned to the command prompt immediately or not. For your comment, writes to stdout are not suppressed; you will see output from all 4 python scripts intermingled based on how far through each script it is.
answers question: http://stackoverflow.com/q/50749840
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50749840
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/a/50752860
type: Answer
has comment: http://stackoverflow.com/comment/88533230
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/50752668
has body: In Python 3.6+, you can use literal string interpolation. a = 3 b = 7 print(f'{a * b}') # prints: '21'
upvote count: 3

http://stackoverflow.com/comment/88672861
comment on: http://stackoverflow.com/a/50834244
type: AnswerComment
has text: @Anush I believe pandas 0.23.1 has just been released which probably has the fix.
score: 0
type: Comment

http://stackoverflow.com/q/50824974
answer count: 1
favorite count: 0
has body: I just want that when I type my name inside the entry box then appears in another entry with some add text. The idea is type in the entry below and after that it showed in the big entry.I was looking for this solution, but just found place in Label. I don't want in Label. The window is more big, must drag to show the entry. There's is a picture that i use in this script: from tkinter import * from PIL import Image, ImageTk root = Tk() cat = Entry(root) cat.place(x=48, y=25, width= 350, height=140) user = Entry(root) user.place(x=75, y=550) btn = Button(root, text='START') btn.place(x=220, y=410) root.mainloop() # Ok, It works the way you told me,thank you! But now i'm facing another problem. The problem is when i insert the function of the game in the second window. I tested in one window and it works, but when i place the function in the second window gives an error when i press the "Start" button: '''user_try = int(txt.get()) NameError: name 'txt' is not defined''' When i press reset button gives another error: '''user_try = int(txt.get()) NameError: name 'txt' is not defined''' So i know that is missing definition, but i don't know how to make a reference for this command that it's in the second window. Like i said running with just one window the program works. Maybe i should make using class, i don't know, but i wish to make this way that i started. However if there's no other way to do as i'm doing, let's go. I just simplify the script here, actualy the main script is more bigger, so my idea is when open the program, there is a window and the user read the instructions about the game and proceed open the second window. The window have pictures and some hidden buttons in the next picture, so there will be an interactivity with the environment. The guess number is just the beggining. After that there will be new challeges. I'm very excited doing this, but i'm stuck in this point. The part one i finished, the pictures, the hidden buttons it's exacly the way i wan…
tagged with: python
tagged with: tkinter-entry
tagged with: tkinter
has answer: http://stackoverflow.com/a/50825530
has comment: http://stackoverflow.com/comment/88655607
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has title: How to get the entry text and display in another entry?
type: Question
score: 0

http://stackoverflow.com/comment/88463070
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50725148
has text: @user: see update, your current template however contains a queryset. This is typically not a good idea to do at the template layer.
type: Comment

http://stackoverflow.com/comment/88600106
has text: Sounds like a fun project. Go ahead and try it out. Let us know if you have a specific answerable question, and we'll help you out then :-)
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/50797087

http://stackoverflow.com/comment/88498662
type: QuestionComment
comment on: http://stackoverflow.com/q/50745062
has text: What's a `CreatePDF`?
score: 0
type: Comment

http://stackoverflow.com/q/50833119
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/50833469
favorite count: 0
has title: Slicing with Multindexing with Pandas
possible better answer: http://stackoverflow.com/a/50833216
upvote count: 1
has answer: http://stackoverflow.com/a/50833216
type: AnsweredQuestion
has body: I am trying to slice using Multindexing in both axes simultaneously but I get an exception: multi_index_0 = pd.MultiIndex.from_product([['A', 'B', 'C'], ['a' , 'b']], names=['first', 'second']) multi_index_1 = pd.MultiIndex.from_product([['D', 'E'], ['c' , 'd']], names=['first', 'second']) df = pd.DataFrame(np.random.randn(6, 4), multi_index_0, multi_index_1) Now, I want to slice rows ['A', 'b] and ['B', 'a'], and columns ['D', 'c'] and ['E', 'd']. I have tried unsuccessfully the following: df.loc[['A', 'b'], ['B', 'a']], [['D', 'c'], ['E', 'd']] rerurns empty dataframe df.loc[['A', 'B'], ['b', 'a']], [['D', 'E'], ['c', 'd']] returns empty dataframe df.loc[([['A', 'B'], ['b', 'a']]), ([['D', 'E'], ['c', 'd']])] TypeError: '['A', 'B']' is an invalid key df.loc[([['A', 'b'], ['B', 'a']]), ([['D', 'c'], ['E', 'd']])] TypeError: '['A', 'b']' is an invalid key
score: 1
tagged with: multi-index
tagged with: slice
has answer: http://stackoverflow.com/a/50833469
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50853133
has comment: http://stackoverflow.com/comment/88711300
answer count: 0
score: 1
upvote count: 1
has body: I'm trying to run the following script on OpenCV 3.4.1, Python 3.6.5, but I keep getting the error: line 41, in &lt;module&gt; for i in range(defects.shape[0]): AttributeError: 'NoneType' object has no attribute 'shape' I've tried changing for i in range(defects.shape[0]) to for i in len(defects) but that leads to the error: TypeError: object of type 'NoneType' has no len() I'm not experienced with Python or OpenCV, so any help will be appreciated!! Here is the script: import cv2 import numpy as np cap = cv2.VideoCapture(0) while( cap.isOpened() ) : ret,img = cap.read() gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) ret,thresh1 = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) drawing = np.zeros(img.shape,np.uint8) max_area=0 for i in range(defects.shape[0]): cnt=contours[i] area = cv2.contourArea(cnt) if(area&gt;max_area): max_area=area ci=i cnt=contours[ci] hull = cv2.convexHull(cnt) moments = cv2.moments(cnt) if moments['m00']!=0: cx = int(moments['m10']/moments['m00']) # cx = M10/M00 cy = int(moments['m01']/moments['m00']) # cy = M01/M00 centr=(cx,cy) cv2.circle(img,centr,5,[0,0,255],2) cv2.drawContours(drawing,[cnt],0,(0,255,0),2) cv2.drawContours(drawing,[hull],0,(0,0,255),2) cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True) hull = cv2.convexHull(cnt,returnPoints = False) if(1): defects = cv2.convexityDefects(cnt,hull) mind=0 maxd=0 for i in range(defects.shape[0]): s,e,f,d = defects[i,0] start = tuple(cnt[s][0]) end = tuple(cnt[e][0]) far = tuple(cnt[f][0]) dist = cv2.pointPolygonTest(cnt,centr,True) cv2.line(img,start,end,[0,255,0],2) cv2.circle(img,far,5,[0,0,255],-1) print(i) i=0 cv2.imshow('output',drawing) cv2.imshow('input',img) k = cv2.waitKey(10) if k == 27: break
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/88709638
has comment: http://stackoverflow.com/comment/88710067
tagged with: contour
downvote count: 0
has comment: http://stackoverflow.com/comment/88709344
favorite count: 0
has title: OpenCV Script: AttributeError: 'NoneType' object has no attribute 'shape'
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88470268
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50731229
has text: Does this work? https://gist.github.com/jlln/338b4b0b55bd6984f883
score: 1

http://stackoverflow.com/q/50751132
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51891938
has body: When trying to run my code in Pycharm i get this error: from .gurobipy import * ImportError: libgurobi80.so: cannot open shared object file: No such file or directory In the regular python terminal i can import gurobipy with no problem. How can Pycharm be fixed? I've read the install instructions and posted the following 3 lines at the end of the bashrc file with a text editor. export GUROBI_HOME="/opt/gurobi800/linux64" export PATH="${PATH}:${GUROBI_HOME}/bin" export LD_LIBRARY_PATH="${GUROBI_HOME}/lib" Reinstalling PyCharm (even switching to EDU and Professional) as well as reinstalling Ubuntu did not change the error. Please help.
has title: Gurobipy ImportError in PyCharm
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55318554
has answer: http://stackoverflow.com/a/51231940
type: Question
has comment: http://stackoverflow.com/comment/88510062
tagged with: gurobi
has comment: http://stackoverflow.com/comment/123504777
linked to: http://stackoverflow.com/q/42798173

http://stackoverflow.com/q/50807114
has answer: http://stackoverflow.com/a/50833346
type: UnansweredQuestion
has title: How to sync 2 streams from separate sources
tagged with: python
tagged with: video
tagged with: gstreamer
has body: Can someone point me the right direction to where I can sync up a live video and audio stream? I know it sound simple but here is my issue: We have 2 computers streaming to a single computer across multiple networks (which can be up to hundreds of miles away). All three computers have their system clocks synchronized using NTP Video computer gathers video and streams UDP to the Display computer Audio computer gathers audio and also streams to the Display computer There is an application which accepts the audio stream. This application does two things (plays the audio over the speakers and sends network delay information to my application). I am not privileged to the method which they stream the audio. My application displays the video and two other tasks (which I haven't been able to figure out how to do yet). - I need to be able to determine the network delay on the video stream (ideally, it would be great to have a timestamp on the video stream from the Video computer which is related to that system clock so I can compare that timestamp to my own system clock). - I also need to delay the video display to allow it to be synced up with the audio. Everything I have found assumes that either the audio and video are being streamed from the same computer, or that the audio stream is being done by gstreamer so I could use some sync function. I am not privileged to the actual audio stream. I am only given the amount of time the audio was delayed getting there (network delay). So intermittently, I am given a number as the network delay for the audio (example: 250 ms). I need to be able to determine my own network delay for the video (which I don't know how to do yet). Then I need to compare to see if the audio delay is more than the video network delay. Say the video is 100ms ... then I would need to delay the video display by 150ms (which I also don't know how to do). ANY HELP is appreciated. I am trying to pick up where someone else has left off in this design so it hasn…
tagged with: ntp
type: Question
score: 0
tagged with: udp
answer count: 1

http://stackoverflow.com/comment/88622619
has text: the typo is here not in install. My fault.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50808322
type: QuestionComment

http://stackoverflow.com/comment/88459524
comment on: http://stackoverflow.com/q/50725227
score: 0
type: Comment
type: QuestionComment
has text: Do your data points have error bars? If so, are they gaussian errors?

http://stackoverflow.com/q/50815307
tagged with: cursive
downvote count: 0
tagged with: ocr
favorite count: 0
has title: Extract character images from cursive continuous handwritten image
type: UnansweredQuestion
tagged with: python
has body: I am trying to extract individual character as an image from below I have a python code, which is able to extract each line and words in order. But, it is not able to identify and extract each character. Below is the python code that I am using, import cv2 import numpy as np image = cv2.imread("ConnectedCharacters.tif") image = cv2.resize(image,None,fx=.5, fy=.5, interpolation = cv2.INTER_CUBIC) cv2.imshow('orig',image) #grayscale gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # original_resized = cv2.resize(gray, (0,0), fx=.2, fy=.2) cv2.imshow('gray',gray) cv2.waitKey(0) #Remove Salt and pepper noise saltpep = cv2.fastNlMeansDenoising(gray,None,9,13) # original_resized = cv2.resize(saltpep, (0,0), fx=.2, fy=.2) cv2.imshow('Grayscale',saltpep) cv2.waitKey(0) #blur blured = cv2.blur(saltpep,(3,3)) # original_resized = cv2.resize(blured, (0,0), fx=.2, fy=.2) cv2.imshow('blured',blured) cv2.waitKey(0) #binary ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV) # original_resized = cv2.resize(thresh, (0,0), fx=.2, fy=.2) cv2.imshow('Threshold',thresh) cv2.waitKey(0) #dilation kernel = np.ones((5,500), np.uint8) img_dilation = cv2.dilate(thresh, kernel, iterations=1) # original_resized = cv2.resize(img_dilation, (0,0), fx=.2, fy=.2) cv2.imshow('dilated',img_dilation) cv2.waitKey(0) #find contours im2,ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #sort contours sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[1]) for i, ctr in enumerate(sorted_ctrs): # Get bounding box x, y, w, h = cv2.boundingRect(ctr) # Getting ROI roi = image[y:y+h, x:x+w] # # show ROI cv2.imshow('Line no:' +str(i),roi) cv2.waitKey(0) im = cv2.resize(roi,None,fx=4, fy=4, interpolation = cv2.INTER_CUBIC) ret_1,thresh_1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY_INV) # original_resized = cv2.resize(thresh, (0,0), fx=.2, fy=.2) # cv2.imshow('Threshold_1',thresh_1) # cv2.waitKey(0) kernel = np.ones((10, 20), np.uint8) words = cv2…
tagged with: opencv
score: 4
has comment: http://stackoverflow.com/comment/88660717
answer count: 0
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/17262452

http://stackoverflow.com/comment/88558565
has text: @SimonMourier thanks!
comment on: http://stackoverflow.com/q/50770172
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50705748
answer count: 2
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/50705845
has comment: http://stackoverflow.com/comment/88420709
has comment: http://stackoverflow.com/comment/88420707
has body: I'm trying to extract file name from a long string. So I used following code to extract the index of last "\" so that I can use substring z='C:\\MLE\\input\\images\\044c0912-68d1-11e8-8db8-0242ac110002.jpg' a=z.rindex('\') But It's giving error message SyntaxError: EOL while scanning string literal Can you suggest me what wrong I'm doing? I'm using python 3.6
favorite count: 0
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50705845
has comment: http://stackoverflow.com/comment/88420743
has title: SyntaxError: EOL while scanning string literal while finding last occurance
possible better answer: http://stackoverflow.com/a/50705898
has comment: http://stackoverflow.com/comment/88420727
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50705898
has comment: http://stackoverflow.com/comment/88420731
type: Question

http://stackoverflow.com/a/50826003
downvote count: 0
has comment: http://stackoverflow.com/comment/88657973
type: Answer
has comment: http://stackoverflow.com/comment/88657899
answers question: http://stackoverflow.com/q/50825707
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88657559
has body: Try using axis.set_yscale with axis.tick_params. Something like: fig = plt.figure(2) axis = fig.add_subplot(111) axis.plot(data2[0, :, 0], sli) axis.set_yscale('log', nonposy='clip') axis.tick_params(axis='y', which='minor', colors='black') axis.set_xlabel('n-value') axis.set_ylabel('Intensity') axis.set_title('Intensity vs. n-shell') plt.show() Basically use the axis API. This is the only way I was ever able to get minor log-scale tick marks to work for me the way that I wanted...
has comment: http://stackoverflow.com/comment/88657615

http://stackoverflow.com/comment/117618864
has text: @CharlieParker: this would flatten the tensor (similar to [`torch.flatten(correct)`](https://pytorch.org/docs/stable/generated/torch.flatten.html)), i.e., returning a tensor with a single dimension containing all the elements. E.g., running `x.view(-1)` after the commands in my answer would return `tensor([0., 1., 2., 3., 4., 5.])`, i.e., a tensor with a single dimension, of size 6.
type: AnswerComment
score: 4
type: Comment
comment on: http://stackoverflow.com/a/50793899

http://stackoverflow.com/comment/88799708
score: 0
comment on: http://stackoverflow.com/q/50777849
type: Comment
type: QuestionComment
has text: basically the workflow is that you recreate `conda` list of packages with `conda` and `pip` generated files with with `pip`, rarely you have a setup where you do have `conda` installed and no `pip` available to generate `requirements.txt`

http://stackoverflow.com/a/50844539
has body: You need to add the path of your pip installation to your PATH system variable. Type echo $PATH$ to check if it already there or not.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88692619
answers question: http://stackoverflow.com/q/50844210

http://stackoverflow.com/a/50808738
answers question: http://stackoverflow.com/q/50808684
score: 1
downvote count: 0
type: Answer
upvote count: 1
has body: Use list comprehensions. &gt;&gt;&gt; a = [3, 2, 1, 0, 5, 4] &gt;&gt;&gt; b = [(a[x], a[x+1]) for x in range(len(a))] &gt;&gt;&gt; print b [(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]

http://stackoverflow.com/a/50830098
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/50830059
accepted answer of: http://stackoverflow.com/q/50830059
downvote count: 0
has body: Use Regex. Ex: import pandas as pd df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]}) df["B"] = df["A"].str.extract("(\d*\.?\d+)", expand=True) print(df) Output: A B 0 hellothere_3.43 3.43 1 hellothere_3.9 3.9
type: AcceptedAnswer
score: 10

http://stackoverflow.com/comment/88496324
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50741835
has text: This is a very valid question, why it was downvoted and flagged to be closed?. And no reasons given.

http://stackoverflow.com/comment/88605866
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50799619
has text: in C `wchart_t` is compiler dependent so that probably has to do with the reason you're getting an error. My guess is that clion is more strict on checking whether something is within range Unicode. `21bae0` is beyond the range of Unicode characters as the error suggests.

http://stackoverflow.com/comment/88495821
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50743881
has text: Edited off. My list is too long -- when editing it, didn't see the first 2 points are incorrect:)

http://stackoverflow.com/comment/88689503
score: 0
has text: I don't know what that means.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50842956

http://stackoverflow.com/comment/88645900
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50820220
has text: @Nicholas, this is an interesting question but make sure you provide an [mcve](https://stackoverflow.com/help/mcve) so we can see what you've acomplished so far and at what point you've got stuck. Otherwise people will start downvoting you... Here's a motivational thumb up :)

http://stackoverflow.com/comment/88614990
type: Comment
comment on: http://stackoverflow.com/q/50803690
score: 1
has text: In JS that would be `Array.from(f())` or `[...f()]`. Read about iterables and iterators (note the difference) [on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). It has examples, syntaxes, ... etc.
type: QuestionComment

http://stackoverflow.com/comment/88695568
has text: Thanks for the reply. I have changed the manifest to use a release buildpack (https://github.com/cloudfoundry/buildpack-python.git#v1.6.17) and am using the runtime.txt (python-3.5.x). Also, I am using only temporary file to write into, like so - `tmp_dir = '$HOME/tmp/textfiles'` and I am able to run it locally (via Postman) using Python 3.x. However, in CF the error `Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ygzuah5g/logging/` still persists while using any python-3.x runtime. Any further ideas on how to go about this would be helpful!
comment on: http://stackoverflow.com/a/50838187
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/104591456
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/59182212
score: 1
has text: This works for Python 3.7 as well (from Microsoft Store), cheers. I enabled the aliases after installation, I'm then able to run `python` without issues.

http://stackoverflow.com/q/50853316
tagged with: cmd
favorite count: 0
has title: Error " Could not find a version that satisfies the requirement PIL" when using pip install
has body: When trying to install PIL I keep getting the error "Could not find a version that satisfies the requirement PIL (from versions: ) No matching distribution found for PIL". I've tried uninstalling and reinstalling PIL as suggested in the post ImportError: No module named PIL but in this case having PIL previously incorrectly installed isn't the issue.
tagged with: python
accepted answer: http://stackoverflow.com/a/50853647
type: AnsweredQuestion
tagged with: python-imaging-library
upvote count: 5
linked to: http://stackoverflow.com/q/37311359
type: Question
score: 5
linked to: http://stackoverflow.com/q/8863917
duplicate of: http://stackoverflow.com/q/37311359
downvote count: 0
answer count: 1
tagged with: failed-installation
has answer: http://stackoverflow.com/a/50853647

http://stackoverflow.com/q/50786298
possible better answer: http://stackoverflow.com/a/50786342
tagged with: python-3.6
has title: How to show that a program is being processed?
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50786342
score: 0
has body: I made a program on checking if an user-input number is prime or not. However, when I enter large numbers, it takes a considerable amount of time. What sort of code would help to show the user that the number is being checked upon, something similar to a loader, unless the result has been determined? The code is as follows: from math import sqrt as s from time import time as t def check_prime(p): prime = [p] start = t() if p &gt; 3: for i in range(2, int(s(p)) + 1): if p % i == 0: end = t() print('Time taken is', end - start, 'seconds') prime.remove(p) break else: continue else: pass try: end except: end = t() print('Time taken is', end - start, 'seconds') if p in prime: if p == 2 or p == 3 or (p != 1 and p &gt; 0): return(f'{p} is a prime number') elif p &lt;= 0: return(f'{p} is not in the domain of prime or composite numbers') else: return('1 is neither prime nor composite') else: return(f'{p} is NOT a prime number') while True: p = input('&gt; ') print(check_prime(int(p)))
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50786508
accepted answer: http://stackoverflow.com/a/50786508

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/50734957
tags question: http://stackoverflow.com/q/50820366
tags question: http://stackoverflow.com/q/50818904
type: Tag

http://stackoverflow.com/a/50825184
score: 0
answers question: http://stackoverflow.com/q/50825066
has comment: http://stackoverflow.com/comment/88655352
has comment: http://stackoverflow.com/comment/88655196
type: Answer
has body: You could use the json module: import json json_s = json.loads('{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}') json_s['responseData']['id'] = '38' # Or str(json_s['responseData']['id']) print(json_s) Or in this case it is a valid dictionary so you could use eval(): json_s = '{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}' a = eval(json_s) a['responseData']['id'] = '38' # Or str(a['responseData']['id']) print(a) If you want to convert the dictionary in json_s and a back to a string then just use str(json_s) and str(a) respectively. See the documentation for the use of eval(). Otherwise to keep away from eval() use the ast module. As described here: Convert a String representation of a Dictionary to a dictionary?

http://stackoverflow.com/a/50753549
answers question: http://stackoverflow.com/q/50753522
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88515244
accepted answer of: http://stackoverflow.com/q/50753522
has comment: http://stackoverflow.com/comment/88515046
type: Answer
has body: The best way to use df.apply is to not use df.apply. (df == df.max()).astype(int) 0 1 2 0 0 0 1 1 0 1 0 2 1 0 0
has comment: http://stackoverflow.com/comment/88515112
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88515045
has comment: http://stackoverflow.com/comment/88515190
has comment: http://stackoverflow.com/comment/88515116

http://stackoverflow.com/q/50802824
favorite count: 0
has answer: http://stackoverflow.com/a/50803074
type: Question
possible better answer: http://stackoverflow.com/a/50803263
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50803263
has comment: http://stackoverflow.com/comment/88611738
downvote count: 2
answer count: 3
accepted answer: http://stackoverflow.com/a/50803074
tagged with: list
has comment: http://stackoverflow.com/comment/88611828
linked to: http://stackoverflow.com/q/5753597
has comment: http://stackoverflow.com/comment/88611746
has answer: http://stackoverflow.com/a/50803126
has title: Find common elements in two list
has comment: http://stackoverflow.com/comment/88611693
has comment: http://stackoverflow.com/comment/88611843
has body: I have two list : list_1 = ['rwww corp\pan 2323 2018-23-23 0% c:\program files\pa.txt', 'rwww corp\pand 2323 2018-23-23 0% c:\program files\monkey.txt'] list_2 = ['c:\program files\pa.txt'] I would like to find if list_2 element is there in list_1, if yes, then print that. In this case, list_2 element is at index 0 for list_1, how can i use one liner to achieve this? I have a boring way of doing this by using two for-loops: for e in list_1: for k in list_2: if k in e: print e
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/88729313
has text: Thanks, Levent. As for your last comment, I tried my little example to try the Wikipedia example of https://en.wikipedia.org/wiki/Satisfiability_modulo_theories#SMT_for_undecidable_theories to evaluate a transcendental function via an external program and it didn't work, so thus the genesis of the question :-).
comment on: http://stackoverflow.com/a/50728892
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/73968036
has body: Any context manager created with contextlib.contextmanager is also a decorator, as described here: https://docs.python.org/3/library/contextlib.html#using-a-context-manager-as-a-function-decorator Context managers can be used to wrap code with setup and teardown steps. Decorators are a more general construct with allow us to modify functions many ways, including by wrapping them with setup/teardown logic. So it seems pretty natural to ask: why can't we use a context manager as a decorator? We can, and in fact contextlib has already done it for you. If we write a context manager like so: from contextlib import contextmanager @contextmanager def my_context(): print("setup") yield print("teardown") We can use it as a context manager in a with block or we can use it as a decorator: def foo(): with my_context(): print("foo ran") @my_context() def bar(): print("bar ran") >>> foo() setup foo ran teardown >>> bar() setup bar ran teardown Which should you use? Use a with block when your enclosed code needs access to the object returned by the context manager, e.g. file handling: with open("my_file.txt") as file: file.read() # needs access to the file object Use as a decorator when an entire function needs to be wrapped in a context and doesn't need any context variables: @contextmanager def suppress_all_exceptions(): try: yield except: pass @suppress_all_exceptions() def div_by_zero(): print("hi") x = 1 / 0 # exception suppressed Note: the same functionality can also be achieved by subclassing contextlib.ContextDecorator: class MyContext(contextlib.ContextDecorator): def __enter__(): ... def __exit__(*errs): ...
score: 5
answers question: http://stackoverflow.com/q/50823473
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88564190
comment on: http://stackoverflow.com/q/50778615
score: 0
type: Comment
type: QuestionComment
has text: @coldspeed I know what you're trying to say but I just prefer this way.

http://stackoverflow.com/a/50795492
has body: You have to access the variable through self, if you do not, you will be creating a new local variable other than the one you want to access. class Controller(BoxLayout): random_string = StringProperty("hola") def do_action(self): self.random_string="h22l" print(self.random_string) def do_action2(self): self.random_string="hl2332323" print(self.random_string)
accepted answer of: http://stackoverflow.com/q/50795266
has comment: http://stackoverflow.com/comment/88597296
answers question: http://stackoverflow.com/q/50795266
has comment: http://stackoverflow.com/comment/88597201
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50825957
type: AnsweredQuestion
has body: I am trying to add a css file to my Django app, eventually in production but right now I can't even get it to run the local server using runserver. Whenever I load the page that should use the css file, I get the error "GET /static/ldap/style.css HTTP/1.1" 404 1666, with some variation on the filepath and error code, as I have tried a whole lot of combinations. Some other errors that I have gotten are "GET /static/style.css HTTP/1.1" 404 1651 Not Found: /ldap/style.css [12/Jun/2018 15:07:07] "GET /ldap/style.css HTTP/1.1" 404 2804 My current setup is attempting to copy the official docs from the tutorial and the suggested doc in the settings.py file. I have: in my settings.py: STATIC_URL = '/static/' , in my search.html: {% load static %} &lt;link rel="stylesheet" type="text/css" href="{% static 'ldap/style.css' %}"&gt; And the file structure of my project root folder is thus (I am trying to implement this in the ldap application, to be clear): ├── conf ├── db.sqlite3 ├── djangoWrapper │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── templates │ │ └── djangoWrapper │ │ └── index.html │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── ldap │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── static │ │ └── ldap │ │ └── style.css │ ├── templates │ │ └── ldap │ │ ├── apiOffline.html │ │ ├── index.html │ │ ├── results.html │ │ └── search.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── openshift ├── README.md ├── requirements.txt ├── runserver.sh └── static └── admin Are there any good ideas about what might be the problem here? I have tried following a lot of other related posts (like this) but none of them have worked, which might be related to the fact that none of them had the same error code (404 1666 and 404 1651) that I am having. I can give more information upon request, any help is appreciated. Thank you.
linked to: http://stackoverflow.com/q/24199029
type: Question
has comment: http://stackoverflow.com/comment/88678995
answer count: 2
has answer: http://stackoverflow.com/a/50826221
accepted answer: http://stackoverflow.com/a/50826221
score: 0
has title: Static CSS files with Django Application Error
possible better answer: http://stackoverflow.com/a/50826160
has comment: http://stackoverflow.com/comment/88656781
has answer: http://stackoverflow.com/a/50826160
tagged with: django
tagged with: python
tagged with: css

http://stackoverflow.com/comment/88446389
comment on: http://stackoverflow.com/a/50718495
type: AnswerComment
has text: Thanks for the idea of multiple encoding. this .xlsx decodes by 'iso-8859-1' but when i encode by utf-8 the output is just some random bytes which i don't understand. I've tried different encoding but still no luck. can you please try decoding this file? [test.xlsx](https://drive.google.com/open?id=10GDlEFpZmOSHAh-kMVEKmL2TZl4IBmkM)
score: 0
type: Comment

http://stackoverflow.com/comment/88682589
type: QuestionComment
has text: (`For` should be `for` , `If` should be `if` all lowercase)
comment on: http://stackoverflow.com/q/50839396
score: 1
type: Comment

http://stackoverflow.com/q/50706764
downvote count: 1
has answer: http://stackoverflow.com/a/50706797
has body: For example Hello World Hello World Hello World Hello World I have tried doing this but it doesn't work: for i in range(4): print(""*i, "Hello World")
type: Question
has comment: http://stackoverflow.com/comment/88422643
has comment: http://stackoverflow.com/comment/88422647
has answer: http://stackoverflow.com/a/50706849
score: 0
has answer: http://stackoverflow.com/a/50706788
answer count: 3
has title: Creating a loop that outputs an extra space for each line
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88422660
upvote count: 1
tagged with: python

http://stackoverflow.com/a/69451981
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50821312
has body: If you have multiple versions of python installed and you want to upgrade pip pip install --upgrade pip how do you know which python version will be affected? it depends on path variable for the shell. You might also get warning in this case. To avoid this confusion use -m then it looks in variable sys.path. This is another advantage of -m. # importing module import sys # printing all directories for # interpreter to search sys.path
upvote count: 2

http://stackoverflow.com/comment/88459438
score: 0
type: Comment
type: QuestionComment
has text: Fair enough, but this function is smooth and quadratic, there are no bumps and no local minima...
comment on: http://stackoverflow.com/q/50723432

http://stackoverflow.com/q/50714321
has comment: http://stackoverflow.com/comment/88437911
answer count: 3
has comment: http://stackoverflow.com/comment/88437424
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50715341
has comment: http://stackoverflow.com/comment/88437437
has answer: http://stackoverflow.com/a/50714459
tagged with: list
has answer: http://stackoverflow.com/a/50716556
linked to: http://stackoverflow.com/q/8331469
downvote count: 3
upvote count: 1
has body: I have a list with [vehicle name, number] a=[["car","A1"],["car","A2"],["truck","A1"]] I need a function such that if i specify car it should return "A2" the last number in that vehicle name. If i specify bike it should return "A0" I tried writing something but keep getting an error list index out of range EDIT: here's the full list format ["vehicle","color","vehicle_num","status(True/False)","code"] vehicle and color is given and last vehicle_num should be found, if vehicle,color doesn't exist return "A0" The number system starts from "A1",.........."An" n varies according to the vehicle,color list is already sorted
has title: Search a 2 dimensional python list for last occurrence in a particular column
type: Question
score: -2

http://stackoverflow.com/comment/88514317
has text: Great, glad it worked. If you want to "accept" my answer, press the check mark by the left-hand side of it. We'll both be rewarded on SO if you do that. You don't have to accept my answer if you think there's a better one, and that'd be fine. But please accept an answer so that the question is closed.
comment on: http://stackoverflow.com/a/50752976
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88745199
comment on: http://stackoverflow.com/a/50853488
score: 0
type: AnswerComment
type: Comment
has text: Thanks for your comment :) I'll try it

http://stackoverflow.com/a/57118744
downvote count: 1
has body: As Saleh mentioned, once you get the shape_id, you can modify table cells like this: For slide 0 and shape with id = 6, changing the first cell (0,0), to Pina Colada: Presentation('yourpowerpoint.pptx').slides[0].shapes[6].table.cell(0,0).text= 'Pina Colada'
answers question: http://stackoverflow.com/q/50841229
type: Answer
score: 6
upvote count: 7

http://stackoverflow.com/comment/88479940
has text: Have you tried importing tensorflow in another environment? Like in a simple terminal or another IDLE?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50736134
type: QuestionComment

http://stackoverflow.com/q/50745368
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50745435
tagged with: django
tagged with: python
has body: I want to show some specific fields in my template from the value of another field. I'm rendering fields manually. models.py OPTIONS = ( ('YES', 'Yes'), ('NO', 'No'), ) question = models.CharField( max_length=3, choices=OPTIONS, verbose_name="Are you employed now?") company_name = models.CharField( max_length=30, blank=True) info.html &lt;strong&gt;{{ form.question.label_tag }}&lt;/strong&gt; {{ form.question }} {% if form.question.value == "YES" %} &lt;!-- I want to do something like this and then rendering others fields --&gt; &lt;strong&gt;{{ form.company_name.label_tag }}&lt;/strong&gt; {{ form.company_name }} {% endif %} The if statement above doesn't work for me, is there a way to get that? Thanks a lot.
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88501314
has title: How to get field value in template Django

http://stackoverflow.com/q/50751330
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88510533
has comment: http://stackoverflow.com/comment/88512228
type: Question
score: 0
has title: How can I substitute placeholders in a txt file template using data from a csv?
answer count: 1
has answer: http://stackoverflow.com/a/50752333
accepted answer: http://stackoverflow.com/a/50752333
has comment: http://stackoverflow.com/comment/88510516
has body: I have a project that I've been working on for my intro computer science class and I'm not quite sure what I'm doing wrong in my current implementation. I'm supposed to read data from a CSV, which includes data of customers of a fictional travel company. I'm then supposed to open a .txt file template and replace the placeholders (in the format placeholder) with the data on the CSV, then save a new txt file for each customer with the proper replacement. As if I am sending a new email to each customer in the CSV. I was able to load the CSV and put the data in the CSV into an array, while the headers of the CSV (which are identical to the placeholders, just not in double brackets) are in a list: file_obj = open(PATH_SAVE_DIR + csv_filename, newline='') reader = csv.DictReader(file_obj) headers = reader.fieldnames # list of headers file_obj.close() customerdata = [] with open(PATH_SAVE_DIR + csv_filename, 'r') as inf: reader = csv.reader(inf) row = next(reader) for row in reader: customerdata.append(row) This gives me the following array, with the data from the CSV: [['James', 'Butt', '6649 N Blue Gum St', 'New Orleans', 'Orleans', 'LA', '70116', '504-621-8927', 'jbutt@gmail.com', 'gold'], ['Josephine', 'Darakjy', '4 B Blue Ridge Blvd', 'Brighton', 'Livingston', 'MI', '48116', '810-292-9388', 'josephine_darakjy@darakjy.org', 'silver'], ['Art', 'Venere', '8 W Cerritos Ave #54', 'Bridgeport', 'Gloucester', 'NJ', '8014', '856-636-8749', 'art@venere.org', 'bronze']] The part where I'm having difficulty understanding what is happening is when trying to replace the data of the txt file with the customer's data. My current code is able to replace the data in the file, but it only does it with the first set of data, and never seems to counts up in the array and work with the next customer's data: file_obj = open(PATH_SAVE_DIR + EMAIL_TEMPLATE, 'r') file_input = file_obj.read() count = 0 for customer in range(len(customerdata)): customernumber = str(customer + 1) while count…
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/88443173
has text: yes removed it but the error remains, trying now with firefox
comment on: http://stackoverflow.com/a/50715975
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90604010
type: Comment
comment on: http://stackoverflow.com/a/50744752
has text: please see: http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/algo-params/categorical_encoding.html?highlight=categorical_encoding
type: AnswerComment
score: 0

http://stackoverflow.com/a/50784333
accepted answer of: http://stackoverflow.com/q/50784137
upvote count: 16
answers question: http://stackoverflow.com/q/50784137
downvote count: 0
score: 16
has comment: http://stackoverflow.com/comment/98360931
type: AcceptedAnswer
type: Answer
has body: It seems like some other application is using port 5000. You can use netstat to see which processes are using ports with the command below: netstat -tulpn You can also check common apps using port 5000 by visiting this page

http://stackoverflow.com/comment/88620983
type: Comment
score: 0
has text: @GrahamDumpleton the `django` package directory is inherited from `/home/ec2-user/.local/lib/python3.6/site-packages/django` and Apache does run as `ec2-user`, so it should have permission and access to it, correct?
type: QuestionComment
comment on: http://stackoverflow.com/q/50791205

http://stackoverflow.com/q/50809114
has title: Equivalent of cdr/rest for iterators
tagged with: python
accepted answer: http://stackoverflow.com/a/50809172
type: AnsweredQuestion
score: 0
type: Question
has body: Given an iterator (like an infinite sequence with iter = itertools.count()) I can get the first one with next(iter). What is the inverse of this where you get all but the first? I realize I can do def rest(iter): next(iter) return (x for x in iter) But is there nothing built in?
answer count: 1
has answer: http://stackoverflow.com/a/50809172

http://stackoverflow.com/q/50776079
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88559110
tagged with: python-3.x
type: UnansweredQuestion
has title: Python re.search finds result but group doesnt work
tagged with: python
has comment: http://stackoverflow.com/comment/88559212
tagged with: regex
has answer: http://stackoverflow.com/a/50777885
has comment: http://stackoverflow.com/comment/88559148
type: Question
has answer: http://stackoverflow.com/a/50776175
has body: I want to find number matching my pattern inside every line in the .txt file. text fragment sometext - 0.007442749125388171 sometext - 0.004296183916209439 sometext - 0.0037923667088698393 sometext - 0.003137404884873018 code file = codecs.open(FILEPATH, encoding='utf-8') for cnt, line in enumerate(file): result_text = re.match(r'[a-zżźćńółęąś]*', line).group() result_value = re.search(r'[0-9].[0-9]*', line).group() print("Line {}: {}".format(cnt, line)) It's strange because re.search finds results: &lt;_sre.SRE_Match object; span=(8, 28), match='0.001879612135574806'&gt; but if I want to assign result to variable I get this: error File "read.py", line 18, in &lt;module&gt; result_value = re.search(r'[0-9].[0-9]*', line).group() AttributeError: 'NoneType' object has no attribute 'group'
has comment: http://stackoverflow.com/comment/88559220

http://stackoverflow.com/comment/88645259
comment on: http://stackoverflow.com/a/50799463
score: 0
has text: Ah, I never noticed this before: the type conversion happens *before* the choice validation. I'll update the answer.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50703682
answers question: http://stackoverflow.com/q/50703000
has body: The usage of GLM is correct. However, I guess your Poisson is the discrete_model.Poisson which is a separate model. GLM needs the family Poisson. The correct usage using the api should be sm.GLM(y, X, family=sm.families.Poisson()).fit().summary() or with direct imports, from an example that I was working on from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.genmod import families mod = GLM(y, x, family=families.Poisson()) res = mod.fit() print(res.summary())
accepted answer of: http://stackoverflow.com/q/50703000
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/88571786
comment on: http://stackoverflow.com/a/50782438
has text: Having it around can be good for readability, but it's worth noting that iterating over a dictionary is the same as iterating over its keys, so `.keys()` could be removed here.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89084286
comment on: http://stackoverflow.com/a/50823891
type: AnswerComment
type: Comment
score: 0
has text: When I apply this to my data frame in it works great for the entries which are letters, but then returns NaN for the numbers. Is there a way to fix this?

http://stackoverflow.com/comment/88610821
score: 0
type: Comment
type: QuestionComment
has text: Better test / validate this with **`x.flags`** and if **`OWNDATA: False `**, such an object still **remains** ( since it's original mode of instantiation ) **a view** onto some zone of the underlying numpy array.
comment on: http://stackoverflow.com/q/50802238

http://stackoverflow.com/q/50793243
tagged with: django-queryset
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50793281
favorite count: 0
tagged with: python
tagged with: django-orm
has body: I have a model as such class Post(models.Model): submission_time = models.DateTimeField() user = models.ForeignKey(User) and I would like to have a queryset where it returns the number of Posts a user has made per month. I have tried using ExtractMonth as so : user.post_set.annotate(month_sub=ExtractMonth('submission_time')).values('month_sub').annotate(count=Count('month_sub')) But its giving me a QuerySet like this : &lt;QuerySet [{'month_sub': 5, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}]&gt; Instead of one like this(Which i'd like to have) : &lt;QuerySet [{'month_sub': 5, 'count': 1}, {'month_sub': 6, 'count': 7}]&gt; Any Ideas on how to receive a queryset like so ?
upvote count: 1
tagged with: django
type: AnsweredQuestion
score: 1
has title: How to QuerySet for Post per month
type: Question
has answer: http://stackoverflow.com/a/50793281

http://stackoverflow.com/comment/88573933
comment on: http://stackoverflow.com/q/50779667
has text: how many times does it run before crashing? you work with grids so it means 2d-arrays at least. isn't happiness_list 2d too?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88702084
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50849478
type: QuestionComment
has text: By the way, you should edit the docs link into your question, instead of only having it as a comment.

http://stackoverflow.com/comment/88575630
type: Comment
comment on: http://stackoverflow.com/a/50783966
has text: So are mine... Notice that each element in my series is a list of dictionaries represented as a string. There are no "cells" in Pandas. Only series and dataframes.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50751322
upvote count: 5
score: 3
type: Answer
downvote count: 2
has body: This might not be the fastest solution and you need additional lists. d = {'animals': ['dog','cat','fish'], 'colors': ['red','black','blue','dog']} keys = [k for k in d.keys() for v in d[k]] values = [v for k in d.keys() for v in d[k]] pd.DataFrame.from_dict({'index': keys, 'values': values})
answers question: http://stackoverflow.com/q/50751184

http://stackoverflow.com/q/50741455
has comment: http://stackoverflow.com/comment/88491129
has comment: http://stackoverflow.com/comment/88491137
has comment: http://stackoverflow.com/comment/88490457
has body: I ran the code below; from win10toast import ToastNotifier toaster = ToastNotifier() toaster.show_toast("Hello World!!!", "Python is 10 seconds awsm!", icon_path="custom.ico", duration=10) I am getting below error : File "C:\Users\jnp\AppData\Local\Continuum\anaconda3\lib\site-packages\win10toast\__init__.py", line 83, in _show_toast self.hwnd = CreateWindow(self.classAtom, "Taskbar", style, AttributeError: 'ToastNotifier' object has no attribute 'classAtom'
favorite count: 0
possible better answer: http://stackoverflow.com/a/64324906
tagged with: python
has title: 'ToastNotifier' object has no attribute 'classAtom'
has comment: http://stackoverflow.com/comment/88490551
answer count: 4
score: 2
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/51878830
downvote count: 1
has answer: http://stackoverflow.com/a/55933972
type: Question
has comment: http://stackoverflow.com/comment/88490439
has answer: http://stackoverflow.com/a/50741613
accepted answer: http://stackoverflow.com/a/50741613
has answer: http://stackoverflow.com/a/64324906

http://stackoverflow.com/q/50728604
has body: I am new to python and I'm trying to create a program that will list out all the files in a folder and be able to parse through all the files. I am getting this error TypeError: Document() takes from 0 to 1 positional arguments but 2 were given and I am not sure how to fix it because I need those 2 arguments in Document(). Any help anyone can give is greatly appreciated! import docx, os from docx import Document from os listdir #1. List all documents in folder paths = listdir(folderpath) #2. Iterate through folder to continuously update the file path in the doc variable i = 0 for i in range(0,len(paths)): filename = paths[i] print(filename) doc = Document(folderpath, filename) #folderpath + filename = filepath i = i+1
type: UnansweredQuestion
has title: Change number of positional arguments in a function
upvote count: 1
has answer: http://stackoverflow.com/a/50728696
downvote count: 1
has comment: http://stackoverflow.com/comment/88465275
has comment: http://stackoverflow.com/comment/88466211
type: Question
has comment: http://stackoverflow.com/comment/88465858
answer count: 1
score: 0
tagged with: arguments
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/88450026
comment on: http://stackoverflow.com/a/50712915
score: 0
type: AnswerComment
has text: This looks like it is comparing accuracy results to print the best one, the sample output just happened to have that pattern. Rather I am looking to incorporate scaling data in the loop.
type: Comment

http://stackoverflow.com/q/50842921
type: Question
tagged with: time-series
answer count: 2
downvote count: 0
favorite count: 0
has body: I am getting incorrect data using the resample function to convert minute data into daily data. After a careful examination of the output, I have discovered that the process is outputting the open of the 16:00 bar for the DAILY OPEN. Furthermore, it is outputting the close of the 9:31 bar as the DAILY CLOSE. Here's my code: import numpy as np import pandas as pd from pylab import mpl, plt plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' %matplotlib inline import cufflinks as cf df = pd.read_csv('ES#CMin_Pit.csv', index_col='Date', parse_dates=['Date']) df.tail() Time Inc Vol Volume Open High Low Close Date 2005-09-07 09:34:00 2309.0 39145.0 1150.75 1151.00 1150.50 1150.75 2005-09-07 09:33:00 1803.0 36836.0 1150.75 1150.75 1150.25 1150.50 2005-09-07 09:32:00 972.0 35033.0 1150.75 1150.75 1150.50 1150.75 2005-09-07 09:31:00 1440.0 34061.0 1150.75 1151.00 1150.50 1150.50 NaT NaN NaN NaN NaN NaN NaN NaN conversion = {'Open' : 'first', 'High' : 'max', 'Low' : 'min', 'Close' : 'last', 'Volume' : 'sum'} data_day = df.resample('D').apply(conversion) data_day.tail(5) Open High Low Close Volume Date 2018-05-20 NaN NaN NaN NaN 0.0 2018-05-21 2732.50 2739.25 2725.25 2730.50 210297692.0 2018-05-22 2726.00 2741.75 2721.50 2738.25 179224835.0 2018-05-23 2731.75 2732.75 2708.50 2710.50 292305588.0 2018-05-24 2726.00 2730.50 2705.75 2725.00 312575571.0 I suspect that the problem is establishing the "conversion" dictionary, however, I have seen this method uses more than once in my research. Any suggestions to specify the appropriate bar to pull the daily open and close values from? Namely, to use the "first," of 9:31 minute bar instead of the 16:00 bar for the DAILY OPEN price. Additionally to use the "last" of the 16:00 bar instead of the 9:31 bar for the DAILY CLOSE price? Thanks LL
has answer: http://stackoverflow.com/a/50843477
tagged with: python
type: UnansweredQuestion
upvote count: 1
has title: Incorrect output from resample function converting OHLC minute data to daily OHLC data
score: 1
has answer: http://stackoverflow.com/a/50843028

http://stackoverflow.com/a/50717778
downvote count: 0
score: 1
has body: I doubt that you can gain much performance from vectorization because your array ultimately stores list references. But here is one approach that avoids writing loops and works for arbitrary shapes. @np.vectorize def append_vec(mat, elt): mat.append(elt) append_vec(matrix_of_lists, 1) # works inplace # array([[list([2, 3, 1, 1]), list([1, 1])], # [list([2, 5, 4, 1]), list([2, 5, 1])]], dtype=object) A better way without creating an array of NaNs. def append_vec(mat, elt): mat.append(elt) return None append_vec = np.frompyfunc(append_vec, 2, 0)
answers question: http://stackoverflow.com/q/50717368
upvote count: 1
type: Answer

http://stackoverflow.com/comment/88453356
comment on: http://stackoverflow.com/a/50720736
type: AnswerComment
has text: @TomdeGeus, That seems to work too. I updated with an example.
score: 0
type: Comment

http://stackoverflow.com/q/50799964
has answer: http://stackoverflow.com/a/50800027
has answer: http://stackoverflow.com/a/50800174
has title: Extract specific pattern from text python 3
favorite count: 0
answer count: 3
linked to: http://stackoverflow.com/q/4894069
tagged with: python
score: -2
tagged with: regex
has answer: http://stackoverflow.com/a/50800234
type: AnsweredQuestion
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/4894069
has body: I have a string which looks like this avg(foo) from where i want to extract only foo. For this I am using import re re.sub(")( avg","","avg(foo)") But this is not working. Where am I going wrong?
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/88606505
type: Question
possible better answer: http://stackoverflow.com/a/50800027
accepted answer: http://stackoverflow.com/a/50800234

http://stackoverflow.com/a/50828593
accepted answer of: http://stackoverflow.com/q/50724356
answers question: http://stackoverflow.com/q/50724356
upvote count: 10
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/88687012
has comment: http://stackoverflow.com/comment/88686859
has comment: http://stackoverflow.com/comment/88696381
has comment: http://stackoverflow.com/comment/88695688
score: 10
has comment: http://stackoverflow.com/comment/88696181
type: AcceptedAnswer
has body: Use Styler.apply. (To output to xlsx format, use to_excel function.) Suppose one's dataset is other price outlier 0 X 1.99 F,C 1 X 1.49 L,C 2 X 1.99 F 3 X 1.39 N def hightlight_price(row): ret = ["" for _ in row.index] if len(row.outlier.split(",")) >= 2: ret[row.index.get_loc("price")] = "background-color: yellow" return ret df.style.\ apply(hightlight_price, axis=1).\ to_excel('styled.xlsx', engine='openpyxl') From the documentation, "DataFrame.style attribute is a property that returns a Styler object." We pass our styling function, hightlight_price, into Styler.apply and demand a row-wise nature of the function with axis=1. (Recall that we want to color the price cell in each row based on the outlier information in the same row.) Our function hightlight_price will generate the visual styling for each row. For each row row, we first generate styling for other, price, and outlier column to be ["", "", ""]. We can obtain the right index to modify only the price part in the list with row.index.get_loc("price") as in ret[row.index.get_loc("price")] = "background-color: yellow" # ret becomes ["", "background-color: yellow", ""] Results

http://stackoverflow.com/q/50772780
tagged with: python
linked to: http://stackoverflow.com/q/171480
has body: I have this string : u'''[ "A", """B""",'C' , " D"]''' I would like to get a list like : ["A","""B""",'C'," D"] *edited as ""B"" was not valid indeed Some use "" "" or ' ' to escape ' or " or both inside. I tried various solutions from : Convert string representation of list to list s= u'''[ "A", """B""",'C' , " D"]''' 1) import numpy as np List = np.array(s).tolist() print(List) print(type(List)) Result : [ "A", """B""",'C' , " D"] &lt;class 'str'&gt; So not a list, then : 2) import ast List = ast.literal_eval(s) print(List) print(type(List)) Result SyntaxError: cannot mix bytes and nonbytes literals Any other idea how to do it ? (I m using Python 3.6) I thought of regex or simple string replacements but when I think of all the cases where we escape replacing characters like ", ' in the list elements it gets complicated real fast
has answer: http://stackoverflow.com/a/50788817
tagged with: list
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88553110
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2148587
tagged with: numpy
downvote count: 0
score: 1
tagged with: string
has comment: http://stackoverflow.com/comment/88553187
favorite count: 0
has title: Python : transform complex list-like string into list (without SyntaxError for mixing bytes and nonbytes literal)
has comment: http://stackoverflow.com/comment/88553295
type: Question
linked to: http://stackoverflow.com/q/1894269

http://stackoverflow.com/a/66069071
type: Answer
downvote count: 0
score: 1
has body: I have implemented a method similar to your method 1) using sqlAlchemy with the pyodbc dialect. It can easily be adapted to the pyodbc library directly. The trick was to had a SELECT NULL; before the Insert query. This way the first OUTPUT of the insert query will be in the returned sets. Using this method if you inserted n rows you will need to fetch 2n-1 sets using the cursor's nextset(). This is a patch because either MSSQL or pyodbc discards the first set. I wonder if there is an option is MSSQL server or pyodbc where you could specify to return the first set. from sqlalchemy.orm import Session from sqlalchemy.sql.expression import TableClause def bulk_insert_return_defaults_pyodbc( session: Session, statement: TableClause, parameters: List[dict], mapping: dict ): """ Parameters ---------- session: SqlAlchemy Session object statement: SqlAlchemy table clause object (ie. Insert) parameters: List of parameters ex: [{"co1": "value1", "col2": "value2"}, {"co1": "value3", "col2": "value4"}] mapping Mapping between SqlAlchemy declarative base attribute and name of column in database Returns ------- """ if len(parameters) > 0: connexion = session.connection() context = session.bind.dialect.execution_ctx_cls._init_statement( session.bind.dialect, connexion, connexion._Connection__connection.connection, statement, parameters, ) statement = context.statement.compile( session.bind, column_keys=list(context.parameters[0].keys()) ) session.bind.dialect.do_executemany( context.cursor, "SELECT NULL; " + str(statement), [ tuple(p[p_i] for p_i in statement.params.keys()) for p in context.parameters ], context, ) results = [] while context.cursor.nextset(): try: result = context.cursor.fetchone() if result[0] is not None: results.append(result) except Exception: continue return [ {mapping[r.cursor_description[i][0]]: c for i, c in enumerate(r)} for r in results ] else: return [] multi_params = bulk_insert_return_defaults_pyodbc( session, table_cls.__table__.insert(returning=[tabl…
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50812766
answers question: http://stackoverflow.com/q/50812766

http://stackoverflow.com/q/50822614
has title: How to remove every possible accents from a column in python
tagged with: python-module-unicodedata
type: UnansweredQuestion
has body: I am new in python. I have a data frame with a column, named 'Name'. The column contains different type of accents. I am trying to remove those accents. For example, rubén =&gt; ruben, zuñiga=zuniga, etc. I wrote following code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import re import unicodedata data=pd.read_csv('transactions.csv') data.head() nm=data['Name'] normal = unicodedata.normalize('NFKD', nm).encode('ASCII', 'ignore') I am getting error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-41-1410866bc2c5&gt; in &lt;module&gt;() 1 nm=data['Name'] ----&gt; 2 normal = unicodedata.normalize('NFKD', nm).encode('ASCII', 'ignore') TypeError: normalize() argument 2 must be unicode, not Series
tagged with: python
has answer: http://stackoverflow.com/a/50822789
has comment: http://stackoverflow.com/comment/88650509
has comment: http://stackoverflow.com/comment/88650263
type: Question
has comment: http://stackoverflow.com/comment/88650403
has answer: http://stackoverflow.com/a/50822908
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/72432868

http://stackoverflow.com/comment/88476542
score: 0
comment on: http://stackoverflow.com/q/50729310
type: QuestionComment
type: Comment
has text: Check out the edit sir. I've included source code.

http://stackoverflow.com/comment/88508614
score: 0
has text: https://github.com/mkleehammer/pyodbc/wiki/Calling-Stored-Procedures
comment on: http://stackoverflow.com/q/50750101
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88457716
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50720694
has text: @BearBrown that seems to fit what am I asking. Is there any way of enabling or disabling those logging options in the code so I can narrow it down to the parts I want to debug? Also, I tried setting up a formatter to color it differently but it is always red, no matter if I target the DEBUG level, INFO, WARNING, ERROR or CRITICAL.

bash
tags question: http://stackoverflow.com/q/50821693
tags question: http://stackoverflow.com/q/50769974
tags question: http://stackoverflow.com/q/50781828
tags question: http://stackoverflow.com/q/50846131
tags question: http://stackoverflow.com/q/50749745
tags question: http://stackoverflow.com/q/50724560
tags question: http://stackoverflow.com/q/50774143
tags question: http://stackoverflow.com/q/50745485
tags question: http://stackoverflow.com/q/50842628
type: Tag
tags question: http://stackoverflow.com/q/50849032
tags question: http://stackoverflow.com/q/50739241
tags question: http://stackoverflow.com/q/50740414
tags question: http://stackoverflow.com/q/50749840
tags question: http://stackoverflow.com/q/50845531
tags question: http://stackoverflow.com/q/50735140
tag name: bash
tags question: http://stackoverflow.com/q/50785972
tags question: http://stackoverflow.com/q/50769372

http://stackoverflow.com/q/50784021
type: Question
has title: How to Convert Keras Datasets to Embedding Matrices?
score: 0
answer count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/50785810
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has body: I want to use Keras's IMDB dataset. This is how it looks like: An Input Vector Sample = [23022, 309, 6, 3, 1069, 209, 9, 2175, 30, 1, 169, 55, 14, 46, 82, 5869, 41, 393, 110, 138, 14, 5359, 58, 4477, 150, 8, 1, 5032, 5948, 482, 69, 5, 261, 12, 23022, 73935, 2003, 6, 73, 2436, 5, 632, 71, 6, 5359, 1, 25279, 5, 2004, 10471, 1, 5941, 1534, 34, 67, 64, 205, 140, 65, 1232, 63526, 21145, 1, 49265, 4, 1, 223, 901, 29, 3024, 69, 4, 1, 5863, 10, 694, 2, 65, 1534, 51, 10, 216, 1, 387, 8, 60, 3, 1472, 3724, 802, 5, 3521, 177, 1, 393, 10, 1238, 14030, 30, 309, 3, 353, 344, 2989, 143, 130, 5, 7804, 28, 4, 126, 5359, 1472, 2375, 5, 23022, 309, 10, 532, 12, 108, 1470, 4, 58, 556, 101, 12, 23022, 309, 6, 227, 4187, 48, 3, 2237, 12, 9, 215] A Label Sample = 1 This is how I get it: top_words = 5000 test_split = 0.30 from keras.datasets import imdb (X, y), (X_test, y_test) = imdb.load_data() # num_words=top_words The problem is in this way, I dont knwo what an input sentence is like? How can I then put sum of pre-trained word vectors as the feature for that sentence? Any way to do that beyond Keras too? Scikit learn also does not have the imdb dataset. Thanks a lot for your help. Any help is greatly appreciated.
tagged with: tensorflow

http://stackoverflow.com/a/50771875
score: 10
answers question: http://stackoverflow.com/q/50769972
has body: You need to add full path. Instead of &lt;link href="{% static 'css/print.css' %}" rel="stylesheet"&gt; you'd use &lt;link href="http://localhost/static/css/print.css" rel="stylesheet"&gt; The second approach you have found works too, but again you need to use full path for files, something like: import os from django.conf import settings css = os.path.join(settings.STATIC_ROOT, 'css', 'print.css') pdfkit.from_file('file.html', css=css) In the latter case you need to provide full path to file.html as well. In Django, however, you'd probably rather first render file.html to string and then use rendered html to create PDF. Something like: import os from django.conf import settings from django.template.loader import render_to_string t = render_to_string('file.html', {}) css = os.path.join(settings.STATIC_ROOT, 'css', 'print.css') pdf = pdfkit.from_string(t, 'file.pdf', css=css) ... or if you'd like to return PDF as response from django.http import HttpResponse pdf = pdfkit.from_string(t, False, css=css) response = HttpResponse(pdf) response['Content-Type'] = 'application/pdf' response['Content-Disposition'] = 'attachment; filename = file.pdf' return response
has comment: http://stackoverflow.com/comment/88555014
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88554671
accepted answer of: http://stackoverflow.com/q/50769972
type: Answer
has comment: http://stackoverflow.com/comment/88554853
has comment: http://stackoverflow.com/comment/88555393
upvote count: 10

http://stackoverflow.com/comment/88653121
comment on: http://stackoverflow.com/q/50823934
score: 0
type: Comment
type: QuestionComment
has text: In my opinion, you shouldn't use `choices` option. There's a function to check if a path is valid or not ([see here](https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta)). To me, you should just check the value of the flag you're receiving. As you should *always* do anyways.

http://stackoverflow.com/comment/88574393
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50783925
has text: That's what I would expect when the number of processes is four times the number of CPU cores.

http://stackoverflow.com/a/50772850
has body: The shortest way would be a list comprehension cities = [city for city in cityes if len(city) &lt; 6] This is eqivalent to cities_filterd = [] for city in cities: if len(city) &lt; 6: cities_filterd.append(city) cities_filterd will then contain the citiey with a lenth smaller than 6.
answers question: http://stackoverflow.com/q/50772799
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88553146
has comment: http://stackoverflow.com/comment/88553074
type: Answer

http://stackoverflow.com/q/50802957
possible better answer: http://stackoverflow.com/a/50803104
favorite count: 0
has comment: http://stackoverflow.com/comment/88663951
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/88613143
tagged with: loops
has answer: http://stackoverflow.com/a/50803104
has comment: http://stackoverflow.com/comment/88612159
accepted answer: http://stackoverflow.com/a/50804729
type: Question
has comment: http://stackoverflow.com/comment/88612123
has comment: http://stackoverflow.com/comment/88613226
has body: My repl (Various JSON files for various language use cases.) import json # v = "64457.json" #jp # v = "35777.json" #en, jp, ro v = "66622.json" #ge, jp, ro # v = "50900k.json" #ko # v = "25364c.json" #ch, en with open(v) as f: data = json.load(f) track_list = data['discs'][0]['tracks'] langs = ('German', 'French' , 'Korean', 'Chinese') for x, track in enumerate(track_list): for i in track['names']: print i, len(track["names"].keys()) if i not in langs: print "NOT I" if len(track["names"].keys()) == 3 and i in ('Romaji', 'Japanese', 'English'): d = track["names"]["Romaji"] s = track["names"]["Japanese"] y = track["names"]["English"] print '-', x+1, y, d, s break elif len(track["names"].keys()) == 3 and i in langs and i in ('Romaji', 'Japanese'): d = track["names"]["Romaji"] s = track["names"]["Japanese"] y = track["names"][i] print '@', x+1, y, d, s break elif len(track["names"].keys()) == 2 and i in langs: y = track["names"][i] e = track["names"]["English"] print '+', x+1, y, e break else: print '~', x+1, track["names"].values()[0] Error Printed German 3 Japanese 3 NOT I Traceback (most recent call last): File "main.py", line 25, in &lt;module&gt; y = track["names"]["English"] KeyError: 'English' What I'm trying to do I'm trying to loop through each of the keys in track['names']. Once it hits a key that is also in the langs tuple, I want it to stop and go to the corresponding section in the if section. If it's not in the langs tuple, it should output what info it does have, especially if the keys are Eng, Rom, and Jpn. I think all the looping is confusing me.
score: -1
has title: Looping through track keys and jumping to the appropriate part of the loop structure
has comment: http://stackoverflow.com/comment/88615436
has answer: http://stackoverflow.com/a/50804729
tagged with: python-2.7
answer count: 2
tagged with: for-loop
downvote count: 1
has comment: http://stackoverflow.com/comment/88613526

http://stackoverflow.com/a/50723391
has comment: http://stackoverflow.com/comment/88483072
has comment: http://stackoverflow.com/comment/88471845
score: 8
type: Answer
has body: Are you sure you have the correct path? train_df = pd.read_csv("./input/train.csv") (if the csv file is in the input folder which is in the same folder as your jupyter notebook) Easiest would be you have a folder which contains the juptyer notebook and the csv file. Then you would just need to do: train_df = pd.read_csv("./train.csv") or train_df = pd.read_csv("train.csv") Try using train_df = pd.read_csv("train.csv",encoding='utf-8' ) to get rid of the 'b in front of b'../input/train.csv'
accepted answer of: http://stackoverflow.com/q/50722067
upvote count: 8
answers question: http://stackoverflow.com/q/50722067
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50787828
type: Question
has comment: http://stackoverflow.com/comment/88582009
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88583667
linked to: http://stackoverflow.com/q/50128668
has title: Matplotlib: How to reduce the number of axis labels to make it more legible?
duplicate of: http://stackoverflow.com/q/47155569
tagged with: matplotlib
has body: I wrote the following code to create a graph in matplotlib: plt.plot(batches, meanCell) plt.show() The problem I am having is that there are hundreds of pieces of data and it looks like it is trying to put every single piece of data in the axis of the graph: How would I go about formatting the axis to put less labels so the numbers are legible?

http://stackoverflow.com/a/50820682
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50820545
has body: You should call fill before painting using QPainter, look at reference here about QPixmap constructor This will create a PySide.QtGui.QPixmap with uninitialized data. Call PySide.QtGui.QPixmap.fill() to fill the pixmap with an appropriate color before drawing onto it with PySide.QtGui.QPainter .
answers question: http://stackoverflow.com/q/50820545
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/88678261
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50836060
type: QuestionComment
has text: I just created a subdirectory, and tried the same command within the new, empty directory, and got the same result.

http://stackoverflow.com/a/50758977
has body: The problem is that the website is blocking downloads based on the browser signature. Rename your img.jpg file to page.html and open in a browser, then you will see something like this: Error 1010 Ray ID: xxxxxxxxx • 2018-06-08 10:39:01 UTC Access denied What happened? The owner of this website (asset.keepeek-cache.com) has banned your access based on your browser's signature (xxxxxxxxxx). Cloudflare Ray ID: xxxxxxxxxx • Your IP: xx.xx.xx.xx • Performance &amp; security by Cloudflare Once you have considered if you want to perhaps contravene the web site owner's wishes, you can change your user agent by doing (for instance) import urllib # Change user agent to look like Firefox urllib.URLopener.version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' # Download file with new user agent urllib.urlretrieve(url, "img.jpg") which fixed the problem for me.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50758637
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50758637

http://stackoverflow.com/comment/88650229
has text: I got an answer. It's not supposed to be in-place but the function needs to act like a void function, so the list that is called with the function gets sorted at the end. Apparently the goal is that if you call a sorting algorithm, you want to call it without knowing whether it's in-place or not.
comment on: http://stackoverflow.com/a/50803435
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/54917277
type: Answer
has body: Suppose A_ub is a sparse matrix, a_rows = A_ub.row.tolist() a_cols = A_ub.col.tolist() a_vals = A_ub.data list_rhs = list(b_ub) problem.linear_constraints.add(rhs=list_rhs, senses=['L'] * n_less_cons) problem.linear_constraints.set_coefficients(zip(a_rows, a_cols, a_vals)) You may try it. It works better in my case.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50714397
downvote count: 0

http://stackoverflow.com/comment/88499576
score: 0
type: Comment
has text: Hi thank you so much for helping me out! I've tried this and it works when I have just one column or just one row but when I use the image I attached above, some of the values cannot be seen. There are 12000 squares so should technically have 12000 values in the array. I'll greatly appreciate it if you could help me out. I don't understand where its going wrong...
type: AnswerComment
comment on: http://stackoverflow.com/a/50744582

http://stackoverflow.com/q/50787840
tagged with: coordinates
type: Question
has body: I have three points: A, B and C (lat,long coords in WGS84) I'd like to calculate the distance between C and the smallest path between A, B. (This have to work with any lat,long so I can't make projections) Can pyproj or geographiclib.geodesic can do that for me ? EDIT: Not duplicate because I'd like to work in WGS84 not on a sphere. As I said this have to work with any lat,long. I know that there is no simple solution to this problem, that's why I'm asking if there is a simple way to do that with libs like pyproj or geographiclib.geodesic.
has title: Distance between great circle and point
linked to: http://stackoverflow.com/q/43440813
has comment: http://stackoverflow.com/comment/88582032
upvote count: 1
answer count: 1
tagged with: pyproj
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: gps
downvote count: 0
has answer: http://stackoverflow.com/a/51895595
score: 1
has comment: http://stackoverflow.com/comment/88582084
has comment: http://stackoverflow.com/comment/88582199

http://stackoverflow.com/comment/88644581
comment on: http://stackoverflow.com/q/50819491
type: Comment
type: QuestionComment
has text: It is also a good idea to have a clause like `The response has a key {key} with value {value}.` which can be reused.
score: 0

http://stackoverflow.com/comment/88499257
comment on: http://stackoverflow.com/a/50745359
has text: Anything I can modify about this code? `dfA` has 2 columns, the first of which is `col_abc`, used to create the index of the dictionary, and the second of which is `value`, used for the values. Right now this code adds the column name to each value, creating what you described as a dictionary within a dictionary.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50811791
answers question: http://stackoverflow.com/q/50810846
has comment: http://stackoverflow.com/comment/88631786
has comment: http://stackoverflow.com/comment/88629559
score: 0
has body: This is one more regex /((?:\+39)|(?:0039))+[0-9. ]+/gm. which will help to locate your telephone numbers Demo
type: Answer

http://stackoverflow.com/q/50752277
favorite count: 0
has answer: http://stackoverflow.com/a/50752316
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: Upload {% for i in range(amount_of_images) %} {{description[i]}} Update Description Above is my HTML/Jinja Code @app.route("/gallery-manager", methods = ["GET", "POST"]) def gallery_manager(): if request.method == "POST": if(request.form["image-url"] and request.form["description"]) is not None: model.add_new_image(request.form["image-url"], request.form["description"]) id, image, description, amount_of_images = model.get_gallery() return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id) if request.form['update-description'] is not None: print("hello") id, image, description, amount_of_images = model.get_gallery() return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id) Above is my Python/Flask Code... The issue, when I click on the update-description submit button, aka the second POST being handled in the html code, I get a 400 error Bad Request The browser (or proxy) sent a request that this server could not understand. I realized that this error occurs when one of the POST fields are empty and can not be found. I understand that this happens because when I click the second POST submit button, it runs through the first POST check (request.form["image-url"] etc and finds that it is satisfied therefore wanting to run that code, but cant because update-description is still empty. How do I avoid this. In other words how do I handle multiple POST methods. Thank you,
type: UnansweredQuestion
downvote count: 2
tagged with: jinja2
duplicate of: http://stackoverflow.com/q/11041405
score: -2
linked to: http://stackoverflow.com/q/11041405
type: Question
upvote count: 0
has title: Flask Bad Request Error; ocurring because of multiple POST requests
answer count: 1
tagged with: flask

http://stackoverflow.com/q/50811341
has body: When i am executing Selenium tests, there are hundreds of import lines in main.py. What is the best way to hide them? Edit： This problem arises because I did not use an IDE with auto-hide functionality. It now appears that there is only one way to slove it. Move all imports to another file, like the following answers.
tagged with: python
type: AnsweredQuestion
has title: How to hide import lines in python?
downvote count: 1
has answer: http://stackoverflow.com/a/50811485
type: Question
has comment: http://stackoverflow.com/comment/88628171
accepted answer: http://stackoverflow.com/a/50811485
score: -1
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88628040

http://stackoverflow.com/a/61821127
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50849789
downvote count: 0
score: 1
has body: numpy.linalg.norm function is used to get the sum from a row or column of a matrix.Suppose , &gt;&gt;&gt; c = np.array([[ 1, 2, 3], ... [-1, 1, 4]]) &gt;&gt;&gt; LA.norm(c, axis=0) array([ 1.41421356, 2.23606798, 5. ]) &gt;&gt;&gt; LA.norm(c, axis=1) array([ 3.74165739, 4.24264069]) &gt;&gt;&gt; LA.norm(c, ord=1, axis=1) array([6, 6])

http://stackoverflow.com/q/50844954
has comment: http://stackoverflow.com/comment/88694526
tagged with: google-chrome
tagged with: selenium-webdriver
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/88695438
has answer: http://stackoverflow.com/a/54369187
has body: I've been trying to get the webdriver to work with Python in Chrome at work, but can't for the life of me figure out what's wrong, despite troubleshooting for most of the day. I've unzipped chromedriver to the folder I'm working in. I've tried using the executable_path argument with chromedriver. I've tried updating the options within chromedriver to direct to the Chrome.exe file. Code is below. Pretty straightforward. 'url' has an address from earlier in the code that I'm not including here - the script doesn't even make it that far anyways. from selenium import webdriver driver = webdriver.Chrome(executable_path = 'U:/Scraping/chromedriver.exe') driver.get(url) And the error: Traceback (most recent call last): File "&lt;ipython-input-67-db2ce2aa7cdf&gt;", line 1, in &lt;module&gt; runfile('U:/Scraping/Project.py', wdir='U:/Scraping') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "U:/Scraping/Project.py", line 14, in &lt;module&gt; driver = webdriver.Chrome(executable_path = 'U:/Scraping/chromedriver.exe') File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__ self.service.start() File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 98, in start self.assert_process_still_running() File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 111, in assert_process_still_running % (self.path, return_code) WebDriverException: Service U:/Scraping/chromedriver.exe unexpectedly exited. Status code was: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88693558
upvote count: 6
has answer: http://stackoverflow.com/a/50846857
has comment: http://stackoverflow.com/comment/88698319
has answer: http://stackoverflow.com/a/61195125
answer count: 3
has comment: http://stackoverflow.com/comment/88699311
favorite count: 0
tagged with: selenium-chromedriver
has title: WebDriverException: Service U:/Scraping/chromedriver.exe unexpectedly exited. Status code was: 1 while working with Chrome and Python
type: UnansweredQuestion
score: 6
tagged with: python

http://stackoverflow.com/comment/88443447
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50716519
has text: it works perfectly for the example by importing combinations from itertools - but by adding more columns or rows, its unfortunately not working anymore

http://stackoverflow.com/comment/88549081
comment on: http://stackoverflow.com/q/50770438
score: 0
type: Comment
type: QuestionComment
has text: This would be a lot easier to debug if you were working with the same html text every time, so you would know exactly what to expect. Save one request to a file and then work with that file until the bugs are gone, then go back to parsing the live page.

http://stackoverflow.com/comment/88646012
comment on: http://stackoverflow.com/a/50820085
type: AnswerComment
type: Comment
score: 0
has text: OP is not using `os.path.join` but simply concatenating two strings, thus missing a back slash

http://stackoverflow.com/comment/88521435
type: QuestionComment
score: 1
has text: You are missing .driver in all find element statement. as Goran answer. it shoudd be self.driver.fine_element not self.find_element.
comment on: http://stackoverflow.com/q/50755766
type: Comment

http://stackoverflow.com/q/50827416
has comment: http://stackoverflow.com/comment/88660883
score: 0
tagged with: levenshtein-distance
has body: Ive got a large list of names (strings) that I have to check against each other to see if there are any typos. To do this I've been using the pypi python-Levenshtein extension against the iterated list, with a typo being considered as a comparison with a Levenshtein distance of 1. I am running into a problem with names such as 'cat 1' and 'cat 2' which are clearly ~different cats~ (not a typo), but are being flagged because their Levenshtein distance is 1. I've tried putting a stop in before hand to check the string for any numbers , but as the list is quite long it doesn't do much for efficency. Ideally, Im looking for a way to specify that if the only character changing is an int (ie. 'cat 1' vs 'cat 2'), then it is not considered a typo Any suggestions for a different extension/method is welcomed, my greatest concern is efficiency, as mentioned - I have a big list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88660286
has title: Is there a way to filter what the python-levenshtein extension changes?
tagged with: python
answer count: 0
type: Question

http://stackoverflow.com/comment/88579999
type: Comment
type: QuestionComment
has text: You must specify `action="{% url 'url_name'%}"` and `method="get"` attribute to your form tag in html
comment on: http://stackoverflow.com/q/50786529
score: 0

http://stackoverflow.com/a/50705528
type: Answer
has comment: http://stackoverflow.com/comment/88475493
has comment: http://stackoverflow.com/comment/88435229
score: 1
has comment: http://stackoverflow.com/comment/88476521
has body: @Gayathri, the first thing is that global keyword is used to refer the global variables declared in the program or to declare any variable as global which is going to appear inside function block (as in your case). Let you please understand the difference between following 2 code samples. &raquo; Using global keyword: i = 10; def func(): global i; i = 20; # Modifying global i print(i); # 20 print(i); # 10 func(); print(i); # 20 &raquo; Without using global keyword: i = 10; def func(): i = 20; # It won't modify global i, here i is local to func() print(i); # 20 print(i); # 10 func(); print(i); # 10 Now, let's focus on the main problem. ✓ In first case, the value of local person in def display(person): is "Dave" and it is printing here is Dave &amp; after that it is creating global i and setting its value to 'Jack'. In second call i.e. display(i) is passing the set value Jack of i which is assigned to local person variable available in def display(person): and therefore it is printing here is Jack and no error. ✓ In second case, no explicit assignment or function call for setting value of i before function call display(i) therefore there's an error.
accepted answer of: http://stackoverflow.com/q/50704705
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50704705
has comment: http://stackoverflow.com/comment/88437162

http://stackoverflow.com/q/50704363
tagged with: python
has title: Making a dictionary where key is a list
duplicate of: http://stackoverflow.com/q/5558418
has comment: http://stackoverflow.com/comment/88418004
downvote count: 2
has body: so given a list of dictionaries: my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'}, {'a': '1', 'b': '8', 'c': '1', 'd': '2'}, {'a': '7', 'b': '4', 'c': '1', 'd': '5'}] and a list of keys in the dictionary for example [ 'a', 'b'] I am trying to make a list of dictionaries for both 'a' and 'b' for their respective values i.e the final product will resemble new_dict = ['a':['4', '1', '7'], 'b':['5', '8', '4']] any help will be appreciated
type: Question
score: -2
has answer: http://stackoverflow.com/a/50704441
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88418330
linked to: http://stackoverflow.com/q/5558418

http://stackoverflow.com/comment/88542049
has text: @RickyZhou is the dtypes actually string or object for that column? `'21543'` will not match `'21543.0'` but if they are numeric they will match. Unless of course `21543` is really being stored as `21543.000000000000000000001`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50762410
type: AnswerComment

http://stackoverflow.com/q/50833570
has title: Python setup failed error 0x80070005 access denied
has answer: http://stackoverflow.com/a/59182212
type: UnansweredQuestion
tagged with: python
upvote count: 5
has body: When installing python on my system I am getting this error shown in below picture. Please help how can I fix this issue? My account has admin rights on windows 10 pro 64 bit operating system. I have downloaded python setup from below link: https://www.python.org/downloads/windows/
has comment: http://stackoverflow.com/comment/88671280
has comment: http://stackoverflow.com/comment/88671097
has answer: http://stackoverflow.com/a/50833608
type: Question
score: 5
has answer: http://stackoverflow.com/a/54966746
has answer: http://stackoverflow.com/a/69707006
downvote count: 0
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/50833764
has answer: http://stackoverflow.com/a/57783217
has answer: http://stackoverflow.com/a/66338908

http://stackoverflow.com/q/50753232
has comment: http://stackoverflow.com/comment/88514412
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: I'm working on an assignment which needs a python backend and react.js frontend. While both of those parts are working fine individually, I am having some problems dealing with the interaction between the two. I am using a flask based python REST API for the backend. When the API is hosted on pythonanywhere it works with the frontend perfectly. The problem is that the implementation should be able to be run locally and offline. I tried running the API on localhost:5000 and the front end is running via npm localhost:3000. When I try to access the API this way I get the error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/list/all. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘True’). I had a similar problem for the hosted version, but using Simple Requests fixed that. The same approach is not working here. I would appreciate any advice you have. Thanks in advance. Edit: Found a solution. I used flasks jsonify method. It turns out the problem was that the data was text and this caused the CORS problem
type: Question
tagged with: reactjs
tagged with: javascript
has comment: http://stackoverflow.com/comment/88514430
has title: Python REST API localhost CORS issues
score: 0
tagged with: api
linked to: http://stackoverflow.com/q/28461001

http://stackoverflow.com/a/50725047
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50724655
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50724655
type: Answer
has body: You need to tell your view to use your form class: class AccountCreateView(CreateView): fields = ('foo', 'bar') model = models.Account form_class = AccountForm

http://stackoverflow.com/a/50860684
has body: Below is my code and it worked perfectly fine. if __name__ == '__main__': n = int(input()) if n in range(2,11): student_marks = {} for _ in range(n): line = raw_input().split() name = line[0] scores = line[1:] scores = list(map(float, scores)) truth,x,y = 0,0,0 y = len(scores) for x in scores: if 0&lt;=x&lt;=100: truth = truth+1 if(truth == y): student_marks[name] = scores else: print("Marks out of range") query_name = raw_input() add = 0 m=0 """for s in student_marks[query_name]: m = m+1""" #if x in student_marks: for x in student_marks: if x == query_name: y = len(student_marks[query_name]) for g in (student_marks[query_name]): add = add + g average = float(add/y) print("%.2f" % average)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50834506

http://stackoverflow.com/q/50836729
type: Question
has comment: http://stackoverflow.com/comment/88678057
has answer: http://stackoverflow.com/a/50837267
score: 1
linked to: http://stackoverflow.com/q/437589
accepted answer: http://stackoverflow.com/a/50837267
has comment: http://stackoverflow.com/comment/88677359
answer count: 1
downvote count: 0
favorite count: 0
has body: While working on a module I use the repl (python console) to test the functionality. The problem I'm trying to solve is easily reloading the module and reimporting the module objects after a modification. An example shows the problem. In a console I start testing a function in package a.b.c &gt;&gt;&gt; from a.b.c import * &gt;&gt;&gt; myFunction(1) wrong answer I go back to the text editor and fix myFunction Now I want to re test it (I don't want to kill the repl and restart it, since I might have some test variables that I want to reuse) So I have to do something like this: &gt;&gt;&gt; import a.b.c &gt;&gt;&gt; from importlib import reload &gt;&gt;&gt; reload(a.b.c) &gt;&gt;&gt; from a.b.c import * &gt;&gt;&gt; myFunction(1) hopefully the right answer I would like to write a function that would do the reload and reimport * in one go. Ideally I would like to replace the previous session with something like &gt;&gt;&gt; myTestReload(a.b.c) &gt;&gt;&gt; myFunction(1) hopefully the right answer In the myTestReload() function I can use reload(a.b.c) to reload the modified module but I didn't find a way to do the equivalent of from a.b.c import *
linked to: http://stackoverflow.com/q/5364050
tagged with: python
has title: How to easily reload/reimport a module while working in a console
has comment: http://stackoverflow.com/comment/88677561
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88677201
upvote count: 1
tagged with: read-eval-print-loop

http://stackoverflow.com/q/50833399
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/88670651
type: Question
has comment: http://stackoverflow.com/comment/88670680
tagged with: javascript
has comment: http://stackoverflow.com/comment/88670706
has comment: http://stackoverflow.com/comment/88670915
linked to: http://stackoverflow.com/q/15151133
has title: Can I use JavaScript to pass an email to a python file I have in my website?
has comment: http://stackoverflow.com/comment/88670855
duplicate of: http://stackoverflow.com/q/15151133
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has body: I am using Django for my website and so am more familiar with Python. Because of this I want to send an email to an email address I receive from my HTML and JS form using Python not JavaScript, as I know little JS. Any ideas/suggestions? What is the JS code to use for sending data from a JS program to a Python script? WITHOUT using Ajax or extra content. Is there a way to just do it using plain JS???

http://stackoverflow.com/a/50827601
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50827568
type: Answer
upvote count: 2
has body: I'm assuming you're wondering why you get an IndexError from the above code (since there are no explicit tuples or indexing going on in it). '{}|{}|{}'.format() implicitly means '{0}|{1}|{2}'.format(), where the 0, 1 and 2 indicate indices into the positional arguments passed to format. Problem is, you didn't pass any arguments, so when it indexes the tuple of arguments with 0, it immediately fails, raising IndexError. You need to pass as many arguments as you provided placeholders for in the format string.

http://stackoverflow.com/q/50816320
has title: Jupyter install returns “python setup.py egg_info” failed with error code 1
has body: I'm new to Python and have been trying to install Jupyter packages with pip. My command line throws me this Exception Command "python setup.py egg_info" failed with error code 1 in C:\Users\TOSHIB~1\AppData\Local\Temp\pip-install-spdc68do\tornado\ Happens when I do pip install jupyter. How can I solve this? I already did python -m pip install --upgrade pip and pip install --upgrade setuptools.
type: Question
has answer: http://stackoverflow.com/a/50816764
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88637640
tagged with: exception
linked to: http://stackoverflow.com/q/37017155
tagged with: jupyter
has comment: http://stackoverflow.com/comment/88637672
tagged with: jupyter-notebook
favorite count: 0
type: UnansweredQuestion
tagged with: pip
upvote count: 1
tagged with: python
score: 1

http://stackoverflow.com/comment/88557179
comment on: http://stackoverflow.com/a/50773924
has text: Thank you for your appreciation, I'll give you the permanent solution to this. Where you dont need to use splash or anything else and you can get your data 98% for the sites.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/102686929
score: 1
has text: Sounds like a lot of manual boilerplate work for a language for automation
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50826519

http://stackoverflow.com/q/50736287
tagged with: django
has comment: http://stackoverflow.com/comment/88480209
type: Question
score: 3
has title: How to get a full url using reverse in Django
has answer: http://stackoverflow.com/a/50736425
has body: I want to save in a variable the url to access a service, so I am using reverse and the name for the entry in urlpatterns, and I get something like /es/general/provider_types/, but I want to get a full url, like https://127.0.0.1:8000/es/general/provider_types/ This is how I am using reverse: {'name': models.ProviderType._meta.verbose_name_plural.title(), 'url': reverse('rest_provider_types_list')} Is there any way I can do this?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88480271
favorite count: 0
upvote count: 3
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50736425

http://stackoverflow.com/comment/88534953
comment on: http://stackoverflow.com/q/50763584
has text: I also suggest using the the pathlib library rather than os. In my opinion it is a lot nicer to work with.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88409683
type: Comment
has text: It seems I get an attribute error when I try to execute this, the error message I get is __exit__
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50699828

file
type: Tag
tags question: http://stackoverflow.com/q/50709515
tags question: http://stackoverflow.com/q/50698800
tags question: http://stackoverflow.com/q/50717130
tags question: http://stackoverflow.com/q/50707139
tags question: http://stackoverflow.com/q/50834798
tags question: http://stackoverflow.com/q/50833634
tags question: http://stackoverflow.com/q/50772448
tag name: file
tags question: http://stackoverflow.com/q/50797043
tags question: http://stackoverflow.com/q/50822053
tags question: http://stackoverflow.com/q/50752791
tags question: http://stackoverflow.com/q/50797289
tags question: http://stackoverflow.com/q/50803037
tags question: http://stackoverflow.com/q/50849639
tags question: http://stackoverflow.com/q/50815580
tags question: http://stackoverflow.com/q/50839985
tags question: http://stackoverflow.com/q/50768656
tags question: http://stackoverflow.com/q/50714467
tags question: http://stackoverflow.com/q/50827312
tags question: http://stackoverflow.com/q/50822085
tags question: http://stackoverflow.com/q/50795204
tags question: http://stackoverflow.com/q/50766483
tags question: http://stackoverflow.com/q/50750555
tags question: http://stackoverflow.com/q/50767236
tags question: http://stackoverflow.com/q/50723137
tags question: http://stackoverflow.com/q/50819717

http://stackoverflow.com/q/50842360
has body: I'm trying to use GeoText to genrate country mentions, but cities like Rio de Janeiro, Rio das Ostras are not recognized. I verified the dictionary and those cities are OK in there. Input: text = "Rio de Janeiro, Las Vegas, New York" geo = GeoText(text) print(geo.cities) Output: ['Las Vegas', 'New York'] Expected Output: ['Rio de Janeiro','Las Vegas','New York'] Using python 3.x and geotext 0.3.0
has answer: http://stackoverflow.com/a/50843368
accepted answer: http://stackoverflow.com/a/50843368
tagged with: data-mining
answer count: 1
favorite count: 0
tagged with: python
tagged with: module
tagged with: python-3.x
downvote count: 0
has title: Python - Geotext - Cities like "Rio de Janeiro" are not recognized
score: 2
type: AnsweredQuestion
tagged with: geotext
has comment: http://stackoverflow.com/comment/88688858
type: Question
upvote count: 2

http://stackoverflow.com/comment/88656429
comment on: http://stackoverflow.com/q/50825520
has text: That's not a simple thing. You are trying to construct an unusual array.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88424450
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50706802
has text: Please do not post code and output/errors from the terminal in images. Please see here for why: https://unix.meta.stackexchange.com/q/4086/40481

http://stackoverflow.com/comment/88540817
score: 0
has text: I don't think this question is answerable until the OP answers the comment, so I don't know whether this question is useful or useless yet. But I'm guessing the downvoter did so because you didn't explain what these functions are meant to do, or even provide a link to where to find that info. If so, it's somewhat better now, but downvoters usually don't come back, so…
type: Comment
comment on: http://stackoverflow.com/a/50766583
type: AnswerComment

http://stackoverflow.com/comment/88628505
comment on: http://stackoverflow.com/q/50809491
type: Comment
type: QuestionComment
score: 0
has text: check this https://stackoverflow.com/a/5172952/9752602

http://stackoverflow.com/q/50830001
answer count: 4
has comment: http://stackoverflow.com/comment/88664260
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/155609
score: 1
upvote count: 3
has body: learning python and working with some basic string methods. I have this program which finds the index of the first lowercase char in a string: def find_lower(word): i = 0 while not isupper(word[i]): i = i+1 return i however, when I run this code, I get the error builtins.NameError: name 'isupper' is not defined Do I need to import a module or something for isupper() to work?
downvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/50830206
has title: Why am I getting "isupper is not defined" error?
has answer: http://stackoverflow.com/a/50830044
tagged with: string
has answer: http://stackoverflow.com/a/50830028
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88664342
has answer: http://stackoverflow.com/a/50830042
possible better answer: http://stackoverflow.com/a/50830028
tagged with: python
has answer: http://stackoverflow.com/a/50830206

http://stackoverflow.com/comment/88688542
comment on: http://stackoverflow.com/q/50840891
score: 0
type: QuestionComment
type: Comment
has text: what type of access token did you use?

http://stackoverflow.com/comment/88430975
type: QuestionComment
has text: Not sure what does the transformation do exactly?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50710987

http://stackoverflow.com/q/50786590
type: Question
has comment: http://stackoverflow.com/comment/88601580
answer count: 1
downvote count: 0
has title: Tkinter / Pygments: Strange results in highlighting
has comment: http://stackoverflow.com/comment/88600956
has comment: http://stackoverflow.com/comment/88601875
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88598080
tagged with: tkinter
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50820118
has body: I try to highlight texts according to tokens. Tokens can be highlighted by the below codes but there are some unwanted results. Some examples: Suppose to, i typed: a = "a" Both a's are highlighted with the same color despite the first 'a' is Token.Name, the second 'a' is Token.Literal.String.Double Another unwanted case is, when i typed "if", the word is highlighted and if i continue to add some letters to the word "if", the color of the word is changed as expected. However when i delete some letters of this word until the word becomes "if" again, this word is not highlighted as before. Can you help me to understand this problem here? Codes: #!/usr/bin/env python3 # -*- coding: utf-8 -*- from pygments import lex from pygments.token import Token from pygments.lexers import Python3Lexer try: import Tkinter as tk except ImportError: import tkinter as tk ROOT = tk.Tk() TEXT = tk.Text(master=ROOT, fg="white", bg="black", font="TkDefaultFont 10") TEXT.pack(fill="both", expand=True) def tag(event): def colorize(word, color): index = [] index1 = TEXT.search(word, "1.0", "end") while index1: index2 = ".".join([index1.split(".")[0], str(int(index1.split(".")[1]) + len(word))]) index.append((index1, index2)) index1 = TEXT.search(word, index2, "end") for i, j in index: TEXT.tag_add(word, i, j) TEXT.tag_configure(word, foreground=color) for token, content in lex(TEXT.get("1.0", "end"), Python3Lexer()): if token == Token.Literal.Number.Integer: colorize(content, color="purple") elif token == Token.Keyword: colorize(content, color="orange") elif token == Token.Operator.Word: colorize(content, color="red") elif token == Token.Name.Builtin: colorize(content, color="blue") elif token == Token.Comment.Hashbang or token == Token.Comment.Single: colorize(content, color="grey") elif token == Token.Keyword.Namespace: colorize(content, color="yellow") elif token == Token.Namespace: colorize(content, color="green") elif token == Token.Punctuation: colorize(content, color="brown") elif token…
score: 1
has comment: http://stackoverflow.com/comment/88583828
tagged with: pygments

http://stackoverflow.com/a/50841635
score: 2
answers question: http://stackoverflow.com/q/50841165
downvote count: 0
has comment: http://stackoverflow.com/comment/88687385
upvote count: 2
has body: You can achieve this by overwriting using __getitem__ within __getattr__. class AttrDict(dict): def __getattr__(self, item): return super().__getitem__(item) def __setattr__(self, item, value): return super().__setitem__(item, value) x = AttrDict({'some': 'value'}) x['blah'] = 'hello world' print(x.blah) # hello world print(x.some) # value # you can also assign value this way x.foo = 'bar' print(x['foo']) # bar
type: Answer

http://stackoverflow.com/q/50817415
answer count: 2
has comment: http://stackoverflow.com/comment/88640259
has comment: http://stackoverflow.com/comment/88639894
has comment: http://stackoverflow.com/comment/88639987
downvote count: 0
linked to: http://stackoverflow.com/q/10005533
possible better answer: http://stackoverflow.com/a/50817508
favorite count: 0
tagged with: winforms
tagged with: pycharm
upvote count: 2
tagged with: pyinstaller
tagged with: python
score: 2
type: AnsweredQuestion
has title: error in creating executable file from python
has answer: http://stackoverflow.com/a/50817703
accepted answer: http://stackoverflow.com/a/50817703
has body: i coded a python script in pycharm as "probe.py" and later built the executable(.exe) file out of it using the mentioned code in setup.py file but the exe file thus created shows error on opening as import error mising required dependency['numpy'] even when it is present in my project. error image import sys from cx_Freeze import setup,Executable include_files = ['autorun.inf'] base = None if sys.platform == "win32": base = "Win32GUI" setup(name="Probe",version="0.1",description="fun", options={'build_exe':{'include_files': include_files}}, executables=[Executable("probe.py",base=base)]) `
has comment: http://stackoverflow.com/comment/88640176
has comment: http://stackoverflow.com/comment/88640142
has answer: http://stackoverflow.com/a/50817508
type: Question
tagged with: numpy

http://stackoverflow.com/comment/88651182
type: AnswerComment
comment on: http://stackoverflow.com/a/50822862
score: 0
type: Comment
has text: That seems unlikely, since that's not how any browser encodes form parameters. I don't think he's showing the raw POST data, he's showing FF's formatted version.

http://stackoverflow.com/a/50822945
score: 0
has body: You need to give it as a single ndarray which you can extract using the .values property of the data frame. The expected shape for the input is (1000, 128, 647).
type: Answer
answers question: http://stackoverflow.com/q/50822774

http://stackoverflow.com/q/50783617
has comment: http://stackoverflow.com/comment/88620759
has comment: http://stackoverflow.com/comment/88621109
upvote count: 7
has body: since i used cv2.namedWindow('Frame', cv2.WINDOW_NORMAL) I was able to resize my window while running but I also want to print the new window size. Anyone who could help? Update: This is not the full code but it's something like this cap = cv2.VideoCapture(0) cv2.namedWindow('Frame', cv2.WINDOW_NORMAL) while(True): # Capture frame-by-frame ret, frame = cap.read() cv2.imshow('Frame',frame) print(frame.shape) #prints image dimension if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() It kept printing (480, 640, 3) even after I resized the window
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/51017413
has comment: http://stackoverflow.com/comment/88573845
score: 7
has title: PYTHON - how to return the window size of a cv2.imshow window?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51017413
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88622681
type: AnsweredQuestion

http://stackoverflow.com/a/50713977
downvote count: 0
has body: You missed some point in your view when you get the User instance, actually, you need to delete the Following instance in case it exists, try this: def follow_unfollow(follower, id): target = get_object_or_404(User, id=id) if follower.is_authenticated(): following = target.followers.filter(follower=follower) if following.exists(): following.delete() else: # target.followers.create(follower=follower,target=target) Following.objects.create(follower=follower,target=target)
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50713488
score: 2

http://stackoverflow.com/comment/88687984
type: AnswerComment
has text: 'list' object has no attribute 'get' comes back in the response. From a quick search this is because it sees it as a list? r = requests.get("http://192.168.1.48:8080/api") json_data = r.json() print json_data if json_data.get("status") == 'idle':
type: Comment
comment on: http://stackoverflow.com/a/50841419
score: 0

http://stackoverflow.com/q/50839521
downvote count: 0
favorite count: 0
type: Question
has title: Scipy detrend not equivalent to MATLAB
tagged with: python
tagged with: matlab
has answer: http://stackoverflow.com/a/50840016
upvote count: 2
answer count: 1
tagged with: scipy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88682887
score: 2
has body: I have two files with the same purpose, one in Python and one in MATLAB. After reading in a data file, I want them to calculate and error, use detrend to remove a constant offset, then interpolate a surface to fit the errors using griddata. In detrending the data in my Python file, I attempted to use scipy.signal.detrend with both linear and constant argument types since constant initially didn't work. (See for documentation of scipy.signal.detrend) However, neither of these methods get the same array err as the MATLAB file, and I ensured that everything else up to that point had matched. Can you tell me a different way to detrend as MATLAB does? Python code (minus the header/imports): timestamp = datetime.datetime.today().strftime('%Y%m%d%H%M') print timestamp plt.rc('xtick', labelsize=5) plt.rc('ytick', labelsize=5) plt.rc('grid', ls='dotted') plt.rcParams['lines.dotted_pattern'] = [0.1,0.5] np.set_printoptions(suppress=True) def main(argv): testdir = argv[0] # if list indexing error --&gt; you must input a file name after &lt;python es15302_squareness.py&gt; in the command line fname = os.path.join(testdir,'OUTDATA.DAT') s = np.loadtxt(fname) #If in current directory s2 = np.transpose([s[:,0],s[:,2]]) # these are s3 = np.transpose([-s[:,1],s[:,3]]) # all going posEncUm = np.divide(s2,25000) # to be posLasUm = np.divide(s3,25000) # 169x2 err = posEncUm - posLasUm; # -------------------------Everything good up to here---------------------- err[:,0] = scipy.signal.detrend(err[:,0], type=='constant') err[:,1] = scipy.signal.detrend(err[:,1], type=='constant') print err Matlab code: function ES15302_squareness(myDir) close all; cd(myDir); s = load('outdata.dat'); posEncUm = [s(:,1) s(:,3)]/25000; posLasUm = [-s(:,2) s(:,4)]/25000; err = posEncUm - posLasUm; err(:,1) = detrend(err(:,1),'constant'); err(:,2) = detrend(err(:,2),'constant'); (I don't have any errors, it's just that err in MATLAB doesn't match err in Python after the detrends)

http://stackoverflow.com/comment/88454324
type: QuestionComment
has text: I understand plt.plot(time,f1(time),color = 'green') and plt.plot(a,b,color = 'green') produces the same outcome. I used interpolation so that I can connect the dots on the missing data. So that for a given date, I would have an approximate idea where y values would be. Are you suggesting resampling is a better way to go?
comment on: http://stackoverflow.com/q/50711904
score: 0
type: Comment

http://stackoverflow.com/comment/88788261
comment on: http://stackoverflow.com/q/50807507
type: Comment
type: QuestionComment
score: 1
has text: You could install Anaconda, which includes Numpy

http://stackoverflow.com/q/50830687
favorite count: 0
has body: I am working on iMX6-quard armv7-a architecture. I need numpy, to run my python code on it. The best option to install numpy is pip install numpy, but I don't have pip too. I tried to install pip like curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py but it's not working. I tried by downloading wheel from https://gergely.imreh.net/wheels/numpy/, but again I didn't get success to install numpy. If anyone has done it successfully, please help me to do the same. Any help would be appreciated.
tagged with: python
has title: How to bring numpy on iMX6?
has comment: http://stackoverflow.com/comment/88667208
answer count: 0
has comment: http://stackoverflow.com/comment/88666615
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88667137
score: 1
has comment: http://stackoverflow.com/comment/88666462
type: Question
tagged with: numpy
tagged with: arm
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/121486923
has comment: http://stackoverflow.com/comment/88666379
tagged with: armv7
downvote count: 0

http://stackoverflow.com/q/50772990
type: Question
score: 0
has answer: http://stackoverflow.com/a/50773008
answer count: 1
has body: I have the following code in views: def submit_affective(request): if request.method == 'POST': choice=request.POST['aff_choices'] urlid=request.POST['url_list'] url = Url.objects.get(id=urlid) aff_result=Affective.objects.create( affective=choice, url=url ) return redirect('detail_affective',id=url.id) def detail_affective(request,id): boring_count=Affective.objects.filter(affective='Boring',url.id=id).count() confusing_count=Affective.objects.filter(affective='Confusing',url.id=id).count() engaging_count=Affective.objects.filter(affective='Engaging',url.id=id).count() context = { 'boring_count':boring_count, 'confusing_count':confusing_count, 'engaging_count':engaging_count, } return render(request,'feedback/detail_affective.html',context) I want to show the number of "boring","confusing","engaging" in detail_affective only for that URL for which choice has been submitted in submit_affective. Please tell me the problem in my code. Am I passing the url id to detail_affective correctly? And is my way of filtering correct?
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/50773008
tagged with: http-redirect
tagged with: django
has title: Parameters in Django Page Redirection
type: AnsweredQuestion

http://stackoverflow.com/a/50709034
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50708912
has body: You can only string-concatenate strings, not integers. Crude but should work: args = ( 'virt-install' + ' --name=' + name + ' --vcpus=' + str(vcpus) + # fix ' --memory=' + str(memory) + # fix ' --cdrom=' + iso + ' --disk size=' + str(discsize) + # fix ' --os-type=' + os_type + ' --os-varient=' + os_variant + ' --network bridge=' + network_bridge + " --extra-args 'console=ttyS0,115200n8 serial'" ) If you are on python 3.6 you might want to switch to Literal String Interpolation PEP-498: someValue = 22 c = f"This text contains {someValue}" or you can use .format() someValue = 22 c = "This text contains {}".format(someValue) # positional replacement of {} by var
has comment: http://stackoverflow.com/comment/88458637
downvote count: 0

http://stackoverflow.com/comment/88568784
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50780974
has text: Your code doesn't do what you say it does: it checks for duplicates through the whole file, not just whether adjacent lines are equal. Which one do you want?

http://stackoverflow.com/q/50743896
has answer: http://stackoverflow.com/a/69555308
has answer: http://stackoverflow.com/a/55855390
answer count: 2
tagged with: python-requests
linked to: http://stackoverflow.com/q/42981429
upvote count: 5
tagged with: ssl
type: UnansweredQuestion
tagged with: ssl-certificate
has body: I am using requests to connect to a REST API and I have a certificate bundle as well as a .pem key that I am using to authenticate who I am with the API. The certificates and code I have work on my Ubuntu machine, so I know the certificates are good. I encountered this similar problem a while back when I was setting this up on Linux and the exception was being thrown when I put those certificates in etc/pki/tls/certs. When I moved those certificates to etc/ssl/certs, everything worked perfectly. To be clear, I have hashed the directory with those certificates although I honestly am not sure what the importance of hashing is. So, my question is: Where should I put those certificates on Windows? Here is a snippet of code: import requests private_key = '\path\to\private\key.pem' cert_bundle = '\path\to\bundle' url = 'https://www.securedsite.com/api-entry' session = requests.Session() session.cert = private_key session.verify = cert_bundle try: resp = session.post(url) except: # Exception Where I currently have my certs, on Windows: 'C:\stuff\admin\private\core_admin.pem' 'C:\stuff\admin\certs\' Software versions: Windows 10 Python 3.6.3 requests 2.18.4 openssl 1.0.2l For reference, the linux machine is: Ubuntu 16.04.1 4.13.0-39-generic Python 3.6.3 requests 2.18.4 openssl 1.0.2l Within the code, I am using pathlibs Path to build the path so that I can switch back and forth between linux and windows and everything works on linux. I think I just need guidance on where to place my certs.
downvote count: 0
favorite count: 0
type: Question
score: 5
tagged with: windows
tagged with: python
has title: Python requests certificate verify failed on Windows

http://stackoverflow.com/comment/88660836
type: AnswerComment
has text: Also, I don't a difference b/w your original solution and the update. Am I missing something here?
comment on: http://stackoverflow.com/a/50827993
type: Comment
score: 0

http://stackoverflow.com/q/50785308
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/93074177
upvote count: 2
has comment: http://stackoverflow.com/comment/88577394
type: Question
has answer: http://stackoverflow.com/a/55436557
has body: When I am trying to load the Cloud9 IDE for my AWS Lightsail instance it gives me this error: Installation Started Package Cloud9 IDE 1 -------------------- Python version 2.7 is required to install pty.js. Please install Python 2.7 and try again. You can find more information on how to install Python in the docs: http://docs.aws.amazon.com/console/cloud9/python-ssh exiting with 1 Failed Bash. Exit code 1 My Lightsail instance does have python 2.7.15 installed (when I do python --version). Does anyone know a solution to this issue?
tagged with: amazon-web-services
has title: AWS Lightsail Cloud9 Install Fails
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50743323
has comment: http://stackoverflow.com/comment/88500234
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88499303
type: Answer
accepted answer of: http://stackoverflow.com/q/50742245
has comment: http://stackoverflow.com/comment/88512364
answers question: http://stackoverflow.com/q/50742245
has comment: http://stackoverflow.com/comment/88512594
has body: Yes, you should convert the matrix in a tensor, this can be simply: user_matrix = K.variable(user_matrix) Also, you're going to need K.gather or tf.gather. The tensorflow version is better because you can choose the axis: user_latent_vector = Lambda(lambda x: K.gather(user_matrix,x))(user_input) item_latent_vector = Lambda(lambda x: tf.gather(user_matrix,x,axis=1))(item_input) Maybe you will need Input(batch_shape=(None,),....) to achieve this properly.
has comment: http://stackoverflow.com/comment/88515893
has comment: http://stackoverflow.com/comment/88497024
has comment: http://stackoverflow.com/comment/88500535
score: 0
has comment: http://stackoverflow.com/comment/88500522

async-await
tags question: http://stackoverflow.com/q/50757497
tags question: http://stackoverflow.com/q/50789031
type: Tag
tags question: http://stackoverflow.com/q/50833802
tag name: async-await

http://stackoverflow.com/a/50765222
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88538794
has comment: http://stackoverflow.com/comment/88538211
answers question: http://stackoverflow.com/q/50764746
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50764746
has comment: http://stackoverflow.com/comment/88544060
type: Answer
has body: You have to configure MEDIA_URL in your django settings https://docs.djangoproject.com/en/2.0/ref/settings/#media-url Django builds your url the following way: settings.MEDIA_URL + "origin_files/Presentation.pptx" the MEDIA_URL default is an empty string, therefore you get the url "origin_files/Presentation.pptx" and your browser concatenates it to the current page, because the url doesn't start with a slash. so you have to set the MEDIA_URL for example to '/media/' then everything will work in your development environment. On remote server this also requires configuring the web server appropriatelly for it to serve your MEDIA_ROOT to MEDIA_URL (out of the scope of this question obviously).
has comment: http://stackoverflow.com/comment/88546459

http://stackoverflow.com/comment/88814561
has text: @rofelia09 and the header that you are using isn't the same as the one that I put in the answer (It tried using your header and I get the same error as you)
comment on: http://stackoverflow.com/a/50905625
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50720688
has comment: http://stackoverflow.com/comment/88451222
type: Question
tagged with: nginx
has title: Maintaining log.django file
has comment: http://stackoverflow.com/comment/88468074
tagged with: digital-ocean
score: 0
has body: I have the standard django logging config in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.django', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } so it logs to log.django. However log.django is getting too big (>500k lines) so I'm wondering if it is ok to delete this file. Will the file create itself once it's deleted? I'm running django with nginx/gunicorn via digitalocean and I thought there was already a measure in place to maintain this file - but it doesn't seem to be working.
has comment: http://stackoverflow.com/comment/88468189
has comment: http://stackoverflow.com/comment/88469306
tagged with: gunicorn
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88472662
has comment: http://stackoverflow.com/comment/88451812

http://stackoverflow.com/comment/88467156
type: Comment
score: 4
type: QuestionComment
has text: Those apostrophes are there because its a string datatype.
comment on: http://stackoverflow.com/q/50729672

http://stackoverflow.com/comment/88530487
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50761454
type: Comment
has text: https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python

http://stackoverflow.com/q/50805607
upvote count: 1
tagged with: python
has title: python 3: Name error from input within a function
has answer: http://stackoverflow.com/a/50805904
type: Question
has comment: http://stackoverflow.com/comment/88642508
has body: I need to define a function that multiplies two integers gathered from user input. Instructions say to gather user input "within the function", but doing so results in error: NameError: name 'num_1' is not defined. Here was my attempt: def multiply(num_1, num_2): num_1 = input("enter a whole number:") num_2 = input("enter another whole number:") result = int(num_1)*int(num_2) return(num_1 + " * " + num_2 + " = " + str(result)) multiply(num_1, num_2) Changing the code so that input is gathered when calling the function makes it pass: def multiply(num_1, num_2): result = int(num_1)*int(num_2) return(num_1 + " * " + num_2 + " = " + str(result)) print(multiply(input("enter a whole number: "), input("enter another whole number: "))) But I want to know if it's POSSIBLE to gather input within the function as the directions stated.
score: -1
tagged with: nameerror
answer count: 3
has comment: http://stackoverflow.com/comment/88617251
has comment: http://stackoverflow.com/comment/88617264
has comment: http://stackoverflow.com/comment/88617427
favorite count: 0
has answer: http://stackoverflow.com/a/50805670
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50805691
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/88626230
comment on: http://stackoverflow.com/q/50806354
has text: First replace all the values you want to impute to Nan, as given in the answer below.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50797940
tagged with: python
has comment: http://stackoverflow.com/comment/88601763
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88601710
score: 0
linked to: http://stackoverflow.com/q/2612802
has body: Can someone explain whether its python features or what? new = [] a = [1,2,3] for i in range(len(a)): a.remove(a[0]) new.append(a) print(a) new &gt;&gt; [2,3] &gt;&gt; [3] &gt;&gt; [] &gt;&gt; [[], [], []] Why list 'new' consists of empty elements?
has title: Can someone explatin why this happening with python list
duplicate of: http://stackoverflow.com/q/2612802
type: UnansweredQuestion

http://stackoverflow.com/comment/88509317
score: 0
comment on: http://stackoverflow.com/a/50750674
type: AnswerComment
has text: Thanks for the link!!! I try to find documentation but it's hard sometimes when you're new to a framework and don't know how it's organized.
type: Comment

http://stackoverflow.com/q/50706661
score: 1
possible better answer: http://stackoverflow.com/a/50706754
upvote count: 1
accepted answer: http://stackoverflow.com/a/50706948
has answer: http://stackoverflow.com/a/50706754
has comment: http://stackoverflow.com/comment/88422656
type: Question
answer count: 2
has title: How do I choose both instances within the random choice function?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50706948
has comment: http://stackoverflow.com/comment/88423172
tagged with: python
has comment: http://stackoverflow.com/comment/88422551
type: AnsweredQuestion
has body: I may seem unclear but here is what I want, I would like to use both instances within a random.choice function. So here is the code: B = True C = True x = random.choice([B, C]) d = ? I want (d) to hold the left over choice once (x) has been chosen, so let's say if (x) was (B) I would like (d) to hold (C).

http://stackoverflow.com/q/50768698
answer count: 0
type: UnansweredQuestion
has body: I want to parse 'https://meshb.nlm.nih.gov/treeView' with BeautifulSoup, but running the below code only gives me empty list [] import json,requests from bs4 import BeautifulSoup url=('https://meshb.nlm.nih.gov/treeView') page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') print(soup.find_all("ul", { "class" : "treeItem ng-scope" },recursive=False)) Can someone please help me what is wrong with my code?
has comment: http://stackoverflow.com/comment/88544919
has comment: http://stackoverflow.com/comment/88545317
duplicate of: http://stackoverflow.com/q/42475964
has comment: http://stackoverflow.com/comment/88545077
has comment: http://stackoverflow.com/comment/88544887
linked to: http://stackoverflow.com/q/42475964
has comment: http://stackoverflow.com/comment/88545695
type: Question
score: 0
has title: BeautifulSoup cannot parse the website
tagged with: beautifulsoup
tagged with: python
has comment: http://stackoverflow.com/comment/88545009

command-prompt
tags question: http://stackoverflow.com/q/50838326
tag name: command-prompt
type: Tag

http://stackoverflow.com/comment/88677359
score: 0
comment on: http://stackoverflow.com/q/50836729
has text: Possible duplicate of [How do I unload (reload) a Python module?](https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88680277
comment on: http://stackoverflow.com/q/50837829
has text: @jezrael The first result to fall within a 0.05 tolerance
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88528571
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50729516
has text: @FedericoPanunzio Ofc.. I added a section to the question you can have a look
score: 0

http://stackoverflow.com/q/50733466
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88474841
has comment: http://stackoverflow.com/comment/88474747
tagged with: python
tagged with: large-data
has body: So, I have a large amount of data that I wish to upload on a table in MySQL. I can use MySQL's inbuilt data import wizard to upload each .csv file(around 90 files, ~150 mb each) into the table but each file takes too long and it will take months to upload all this data. So instead, I want to use the 'LOAD DATA INFILE' command(which apparently is faster according to the internet) in MySQL but this is generally done for individual files, so I was wondering if I can maybe 'loop' this SQL command using Python(Python has a module that connects to MySQL named 'MySQLclient') and run it through the directory where each of my data file is in so that all the data gets uploaded on to my table one by one automatically. But unfortunately I am not able to come up with a syntactically accurate method to do so in Python 3.6. Maybe you can help? Other methods/commands to perform this task are also welcome. Versions: Python 3.6; MySQL 5.7; Win 8.1;
has comment: http://stackoverflow.com/comment/88475543
has title: How to import and read multiple large .csv files into a table in an SQL database using Python?
has comment: http://stackoverflow.com/comment/88474739
tagged with: mysql
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88475395
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88484737
answer count: 0

beautifulsoup
tags question: http://stackoverflow.com/q/50760322
tags question: http://stackoverflow.com/q/50810419
tags question: http://stackoverflow.com/q/50806104
tags question: http://stackoverflow.com/q/50746724
tags question: http://stackoverflow.com/q/50769439
tags question: http://stackoverflow.com/q/50741849
tags question: http://stackoverflow.com/q/50769003
tags question: http://stackoverflow.com/q/50782308
tags question: http://stackoverflow.com/q/50728690
tags question: http://stackoverflow.com/q/50767758
tags question: http://stackoverflow.com/q/50702820
tags question: http://stackoverflow.com/q/50790248
tags question: http://stackoverflow.com/q/50714453
tags question: http://stackoverflow.com/q/50782666
tags question: http://stackoverflow.com/q/50761140
tags question: http://stackoverflow.com/q/50741221
tags question: http://stackoverflow.com/q/50768698
tags question: http://stackoverflow.com/q/50706832
tags question: http://stackoverflow.com/q/50783451
tags question: http://stackoverflow.com/q/50812715
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/50769809
tags question: http://stackoverflow.com/q/50769931
tags question: http://stackoverflow.com/q/50824140
tags question: http://stackoverflow.com/q/50779879
tags question: http://stackoverflow.com/q/50728615
tags question: http://stackoverflow.com/q/50775100
tags question: http://stackoverflow.com/q/50777076
tags question: http://stackoverflow.com/q/50776702
tags question: http://stackoverflow.com/q/50813926
tags question: http://stackoverflow.com/q/50709402
tags question: http://stackoverflow.com/q/50705372
tags question: http://stackoverflow.com/q/50827458
tags question: http://stackoverflow.com/q/50704445
tags question: http://stackoverflow.com/q/50789729
tags question: http://stackoverflow.com/q/50755186
tags question: http://stackoverflow.com/q/50705909
tags question: http://stackoverflow.com/q/50792640
tags question: http://stackoverflow.com/q/50851632
tags question: http://stackoverflow.com/q/50760596
tags question: http://stackoverflow.com/q/50796893
tags question: http://stackoverflow.com/q/50720246
tags question: http://stackoverflow.com/q/50850774
tags question: http://stackoverflow.com/q/50703916
tags question: http://stackoverflow.com/q/50837086
tags question: http://stackoverflow.com/q/50775455
tags question: http://stackoverflow.com/q/50811616
tags question: http://stackoverflow.com/q/50799552
tags question: http://stackoverflow.com/q/50808295
tags question: http://stackoverflow.com/q/50703496
tags question: http://stackoverflow.com/q/50759011
tags question: http://stackoverflow.com/q/50784900
tags question: http://stackoverflow.com/q/50770699
tags question: http://stackoverflow.com/q/50716232
tags question: http://stackoverflow.com/q/50803602
tags question: http://stackoverflow.com/q/50780510
type: Tag
tags question: http://stackoverflow.com/q/50714663
tags question: http://stackoverflow.com/q/50835485
tags question: http://stackoverflow.com/q/50753495
tags question: http://stackoverflow.com/q/50841439
tags question: http://stackoverflow.com/q/50817991
tags question: http://stackoverflow.com/q/50761376
tags question: http://stackoverflow.com/q/50757488
tags question: http://stackoverflow.com/q/50778481
tags question: http://stackoverflow.com/q/50750609
tags question: http://stackoverflow.com/q/50767112
tags question: http://stackoverflow.com/q/50746909
tags question: http://stackoverflow.com/q/50747043
tags question: http://stackoverflow.com/q/50777758
tags question: http://stackoverflow.com/q/50710290
tags question: http://stackoverflow.com/q/50751828
tags question: http://stackoverflow.com/q/50829622
tags question: http://stackoverflow.com/q/50725454
tags question: http://stackoverflow.com/q/50806462
tags question: http://stackoverflow.com/q/50713919
tags question: http://stackoverflow.com/q/50770438
tags question: http://stackoverflow.com/q/50794929
tags question: http://stackoverflow.com/q/50849057
tags question: http://stackoverflow.com/q/50782503

http://stackoverflow.com/comment/88446053
comment on: http://stackoverflow.com/q/50718623
has text: Post it where? HTTP post? Csv is a string already so just send it? .post(df.to_csv(index=False))
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88632560
type: AnswerComment
score: 0
type: Comment
has text: Thanks, one of my problem solved. And how can I input 5 row as input,and predict 6th?
comment on: http://stackoverflow.com/a/50813545

http://stackoverflow.com/q/50837627
has answer: http://stackoverflow.com/a/50837823
tagged with: pandas
tagged with: sql
downvote count: 0
duplicate of: http://stackoverflow.com/q/48629413
answer count: 4
favorite count: 0
has title: Use variable in pd.read.sql
has comment: http://stackoverflow.com/comment/88679965
has answer: http://stackoverflow.com/a/50838097
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50838739
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50837780
has comment: http://stackoverflow.com/comment/88678983
type: Question
has comment: http://stackoverflow.com/comment/88680338
possible better answer: http://stackoverflow.com/a/50837780
has comment: http://stackoverflow.com/comment/88680223
has body: I have data in SQL and I want to read some data out from it with variable instead of using number like "953381". Having no idea why I just can't use var = 9553381, directly. df = pd.read_sql('select name, data, from sheet where name = "953381" ', conn, index_col=['date'], parse_dates=['date'])
accepted answer: http://stackoverflow.com/a/50838739

http://stackoverflow.com/q/50773587
has comment: http://stackoverflow.com/comment/88573377
has comment: http://stackoverflow.com/comment/88573664
has comment: http://stackoverflow.com/comment/88573336
has comment: http://stackoverflow.com/comment/88573939
has comment: http://stackoverflow.com/comment/88574342
favorite count: 0
has answer: http://stackoverflow.com/a/54494033
upvote count: 2
has comment: http://stackoverflow.com/comment/88557500
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88557204
has comment: http://stackoverflow.com/comment/88573332
tagged with: python
has comment: http://stackoverflow.com/comment/88554495
has body: While I am trying to install scrapy on my Mac Os : pip install Scrapy I get an error Uninstalling zope.interface-4.1.1: Could not install packages due to an EnvironmentError: [('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/zope/init.py', '/private/var/folders/h6/sh206j3129l3bvkbccnqp3xm0000gn/T/pip-uninstall-I2xi1I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/zope/init.py', "[Errno 1] Operation not permitted: '/private/var/folders/h6/sh206j3129l3bvkbccnqp3xm0000gn/T/pip-uninstall-I2xi1I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/zope/init.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/zope/init.pyc', '/private/var/folders/h6/sh206j3129l3bvkbccnqp3xm0000gn/T/pip-uninstall-......]
has comment: http://stackoverflow.com/comment/88573743
has comment: http://stackoverflow.com/comment/88557291
has comment: http://stackoverflow.com/comment/88573794
score: 2
has comment: http://stackoverflow.com/comment/88557620
has comment: http://stackoverflow.com/comment/88573473
tagged with: scrapy
has title: Error during installing scrapy in mac
type: Question
has comment: http://stackoverflow.com/comment/88557425
has comment: http://stackoverflow.com/comment/88557586
has comment: http://stackoverflow.com/comment/88557035
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88557145

http://stackoverflow.com/comment/88473169
score: 0
type: Comment
has text: What modules are you using? I suggest using pandas for csv. It offers a lot more versatility than just reading the file normally.
type: QuestionComment
comment on: http://stackoverflow.com/q/50732536

http://stackoverflow.com/q/50848661
has comment: http://stackoverflow.com/comment/88724027
has answer: http://stackoverflow.com/a/50848758
type: Question
score: 5
tagged with: autocomplete
has comment: http://stackoverflow.com/comment/88700620
answer count: 2
has answer: http://stackoverflow.com/a/50864701
favorite count: 0
has title: Autocomplete does not always work on Pycharm
linked to: http://stackoverflow.com/q/28677670
upvote count: 5
type: UnansweredQuestion
has body: I'm starting to use Pycharm, creating a test with Pygame. I notice that some Pygame methods do not appear in Pycharm AutoComplete. For example, if I want to put a pygame.mask.from_surface (), typing pygame.mas will not do anything. But if I manually complete mask and press., then the auto-complete from_surface () appears correctly. Ex: import pygame car = pygame.image.load("car.png").convert_alpha() car_mask = pygame.mas #### .... here, Pycharm should already show autocomplete This also appears for other situations, for example, if I want to use car.get_rect(), it does not appear there anymore after typing car. Here are my project settings: How to fix this?
tagged with: python
tagged with: pygame
tagged with: pycharm
downvote count: 0

http://stackoverflow.com/comment/88601883
type: Comment
comment on: http://stackoverflow.com/a/50797818
score: 0
type: AnswerComment
has text: How working first solution? `df2 = df.loc[df.index.repeat(b.clip_upper(1))]` ?

http://stackoverflow.com/a/52533264
has body: Other option (I used this appoach in my project): Lets assume that projects are ran from project1.py and project2.py files accordingly. At the top of these files you can add following imports and actions: import sys import os sys.path.append(os.path.join(os.getcwd(), os.pardir)) import your_other_modules your_other_modules.py will contains following for impotring utils from utils import storage from utils import geometry # or from project2 import project2, etc.. May be it's not a best way, but just like one more option. I hope it will be helpful for someone.
score: -1
answers question: http://stackoverflow.com/q/50810656
type: Answer
downvote count: 1
upvote count: 0

http://stackoverflow.com/comment/88676257
type: QuestionComment
has text: Also, your date string contains no timezone information, so converting to UTC makes little sense.
comment on: http://stackoverflow.com/q/50836003
score: 0
type: Comment

boto
tags question: http://stackoverflow.com/q/50730042
tags question: http://stackoverflow.com/q/50750304
type: Tag
tags question: http://stackoverflow.com/q/50763147
tag name: boto
tags question: http://stackoverflow.com/q/50776214

http://stackoverflow.com/comment/88554066
score: 1
comment on: http://stackoverflow.com/q/50773406
type: Comment
type: QuestionComment
has text: What's `SetNames`???

http://stackoverflow.com/comment/88470482
score: 0
type: Comment
type: QuestionComment
has text: Absolutely. Next time I will do that.
comment on: http://stackoverflow.com/q/50731253

http://stackoverflow.com/comment/88658148
has text: @solarc @abarnert you're right that it's not actually a json string. I'm trying to test a function that handles json from a request but the (already existing) function that gives me a python dictionary to match the json comes back with the `u` and I'm trying to convert that into a string that the parser can then handle
score: 0
comment on: http://stackoverflow.com/q/50826609
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50820125
answers question: http://stackoverflow.com/q/50819839
has comment: http://stackoverflow.com/comment/88911093
type: Answer
has body: Loading Excel data into Pandas is notoriously slow. Your first option is to use pd.concat once on a list of dataframes as described by jezrael. Otherwise, you have a couple of options: Convert your Excel files to CSV efficiently outside of Python. For example, see this answer. Pandas performs better reading CSV files. You may see an extra improvement if you convert to csv.gz (gzipped). Consider categorical data to improve memory management; chunking; or lazy operations via a library. See this answer for more details. If your workflow involves "read many times" I strongly advise you convert from Excel to a format more Pandas-friendly, such as CSV, HDF5, or Pickle.
score: 0

http://stackoverflow.com/comment/88494825
has text: OK Thanks! I want to use the Adam algorithm for optimization. How would I achieve that the parameters of B and C won't change?
comment on: http://stackoverflow.com/q/50743411
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88502796
has text: The issue of /9 was that these seems to be unsigned 8 bit int. So it was overflowing when you did the summing. That is why the result was looking weird since it was wrapping around.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50747144

http://stackoverflow.com/a/53270513
has body: You have to specify a distribution strategy in the RunConfig of your estimator as described in this documentation: https://github.com/tensorflow/tensorflow/tree/r1.8/tensorflow/contrib/distribute. However I'm afraid that you're looking for a Parameter Server Strategy(as you have a 'ps' task) which is not available in TF 1.8. Please take a note that in the recent versions of TF this API has been changed and documentation is much more complete: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/distribute/README.md#example
answers question: http://stackoverflow.com/q/50828432
score: 0
type: Answer

http://stackoverflow.com/comment/88617673
has text: Possible duplicate of [int object is not iterable?](https://stackoverflow.com/questions/1938227/int-object-is-not-iterable)
comment on: http://stackoverflow.com/q/50805242
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88580272
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50786783
has text: I don't know that rewriting enumerate is a great idea given that's a builtin, but it is nice to show how it might work.
type: AnswerComment

http://stackoverflow.com/a/50707047
accepted answer of: http://stackoverflow.com/q/50706901
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50706901
has body: When you use scatter plot, you set a color for both face and edge. In the official documentation you can find an additional parameter, edgecolors, which allows setting the edge color. edgecolors : color or sequence of color, optional, default: None If None, defaults to ‘face’ If ‘face’, the edge color will always be the same as the face color. If it is ‘none’, the patch boundary will not be drawn. For non-filled markers, the edgecolors kwarg is ignored and forced to ‘face’ internally. So, after all, you need only plt.scatter(x, y, c=colors[i],edgecolors='black')
type: Answer
has comment: http://stackoverflow.com/comment/108092534
upvote count: 69
downvote count: 0
score: 69

http://stackoverflow.com/comment/88449098
score: 0
type: AnswerComment
type: Comment
has text: Yes. It is dd/mm/yyyy time
comment on: http://stackoverflow.com/a/50718085

http://stackoverflow.com/q/50788082
has body: Instead of this (from json.dumps): [ { "created": 581937573, "text": "asdf" }, { "created": 581937699, "text": "asdf" } ] I would like to get this [non-JSON] output: [ { created: 581937573, text: "asdf" }, { created: 581937699, text: "asdf" } ] If json.dumps had an option to change the quote character for keys, I could just set it to a placeholder and strip them out later. Unfortunately it doesn't appear to have this option... any other clever ideas? (load from this format is not necessary, but would be interesting if a solution for it exists as well)
downvote count: 0
has answer: http://stackoverflow.com/a/68230880
has title: How to dump json-like string without quoting keys?
favorite count: 0
possible better answer: http://stackoverflow.com/a/68230880
tagged with: python
upvote count: 6
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88582651
score: 6
type: Question
has answer: http://stackoverflow.com/a/50788116
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50788116
answer count: 2

http://stackoverflow.com/comment/88507367
has text: @juvian sorry, but it doesn't work that way. While it is a decent rule-of-thumb that the number of loops corresponds to the degree of the polynomial, you can write any single-loops as a nested loop (and so on and so forth), and the complexity won't change. Now, I haven't analysed the above code in detail to say either way, but just because you change the number of loops in your code it won't change the complexity/runtime necessarily.
comment on: http://stackoverflow.com/q/50749481
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50823484
has body: file_4 = open('numbers.txt','r') number_lines = 0 lines = file_4.readlines()[1:] for file_4 in lines: number_lines += 1 print(lines) print(number_lines) output: ['2\n', '3\n', '4\n', '5'] 4 My text file has 5 lines 1 2 3 4 5 I want the output to skip the first line, and display the rest. How can I get rid of the /n and also how can I print each of these numbers on a different row instead of on one?
has comment: http://stackoverflow.com/comment/88652196
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/50823642
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50823618
has comment: http://stackoverflow.com/comment/88652045
has answer: http://stackoverflow.com/a/50823674
has title: How to remove unwanted '\n' from output
favorite count: 0
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50823886
has answer: http://stackoverflow.com/a/50823640
tagged with: python

http://stackoverflow.com/a/79318799
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50825528
has body: You can compare the real size of a response when it comes (before requests or others decompress gzip automatically) with the Content-Length: class SizeTrackingAdapter(HTTPAdapter): def init(self, *args, **kwargs): super().init(*args, **kwargs) self.compressed_size = None def build_response(self, req, resp): raw_content = resp.read(decode_content=False) compressed_size = len(raw_content) resp._fp = BytesIO(raw_content) response = super().build_response(req, resp) response.compressed_size = compressed_size return response adapter = SizeTrackingAdapter(max_retries=Retry(3)) session = requests.session() session.mount('http://', adapter) session.mount('https://', adapter) response = session.get(YOUR_URL)

http://stackoverflow.com/q/50829800
answer count: 3
has answer: http://stackoverflow.com/a/50829948
possible better answer: http://stackoverflow.com/a/50829932
tagged with: python
has answer: http://stackoverflow.com/a/50829932
has body: To merge the elements of two lists like the following, it is very easy: one = [['hi', 'hello'], ['namaste']] two = [['hi', 'bye'], ['namaste']] [m+n for m,n in zip(one,two)] However, if I had a list greater than length 2, how can this be done? For example, concatenating each element in the list of list of lists that follows: three = [['hi', 'why'], ['bye']] list_ = [one, two, three] I want an output like: [['hi', 'hello', 'hi', 'bye', 'hi', 'why'], ['namaste', 'namaste', 'bye']] How can this be done in a scalable way, which works with even a list_ of length 10?
has answer: http://stackoverflow.com/a/50829938
favorite count: 0
score: 2
downvote count: 0
type: Question
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/50829948
has title: Element wise merging of lists python

http://stackoverflow.com/comment/88559212
comment on: http://stackoverflow.com/q/50776079
type: Comment
type: QuestionComment
has text: Your code is a bit brittle right now and depends on there being a match. Are you checking that each line actually has a match group before trying to call `.group()` on it?
score: 0

http://stackoverflow.com/comment/88673880
score: 0
type: QuestionComment
type: Comment
has text: Is the URL correct? Tried with 127.0.0.1:4840? Can you start server without nodes?
comment on: http://stackoverflow.com/q/50823022

http://stackoverflow.com/a/50838337
type: AcceptedAnswer
type: Answer
score: 2
has body: The following line doesn't make any sense poslearn1 = mr.fileids(categories="pos"[:667]) Its simply equivalent to writing poslearn1 = mr.fileids(categories="pos") You can try following categories="pos"[:667] print(categories) # prints pos And this line categories="pos"[667:] will find nothing other than empty string. It is trying to produce a substring of "pos" starting at index 667 which doesn't exist.
downvote count: 0
answers question: http://stackoverflow.com/q/50838132
accepted answer of: http://stackoverflow.com/q/50838132
upvote count: 2

http://stackoverflow.com/q/50832864
has title: How to create regular Expression in Python for a specific type of Alpha numeric word
accepted answer: http://stackoverflow.com/a/50857604
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/50834425
upvote count: 0
possible better answer: http://stackoverflow.com/a/50832944
has answer: http://stackoverflow.com/a/50832944
answer count: 3
has answer: http://stackoverflow.com/a/50857604
has body: I am looking for suggestions to create a regular expression based search in Python. I have got following type of string values in a server log file, 2017-03-18 13:24:05,791 INFO [STDOUT] SUB Request Status :Resubmitted INBIOS_ABZ824 2017-03-12 13:24:05,796 INFO [STDOUT] SUB Submit Status :Resubmitted INDROS_MSR656 2017-04-12 13:24:05,991 INFO [STDOUT] SUB Request Status :Resubmitted INHP_GSN848 and I need to search the log and extract the values like following, 2017-03-18 13:24:05,791 INBIOS_ABZ824 2017-03-12 13:24:05,796 INDROS_MSR656 2017-04-12 13:24:05,991 INHP_GSN848 I am using the following code, but its extracting the complete line where the strings like these are present (INBIOS_ABZ824). How can I extract only the specified values from the log as above, Please share your thoughts. import os import re # Regex used to match relevant loglines (in this case) line_regex = re.compile(r"[A-Z]+IOS_[A-Z]+[0-9]+", re.IGNORECASE) # Output file, where the matched loglines will be copied to output_filename = os.path.normpath("output.log") # Overwrites the file, ensure we're starting out with a blank file with open(output_filename, "w") as out_file: out_file.write("") # Open output file in 'append' mode with open(output_filename, "a") as out_file: # Open input file in 'read' mode with open("ServerError.txt", "r") as in_file: # Loop over each log line for line in in_file: # If log line matches our regex, print to console, and output file if (line_regex.search(line)): print(line) out_file.write(line)
favorite count: 0
score: -3
tagged with: python
tagged with: regex
type: AnsweredQuestion

http://stackoverflow.com/comment/88562840
type: QuestionComment
comment on: http://stackoverflow.com/q/50777923
score: 1
type: Comment
has text: `itertools.count()` iterates over integers indefinitely, so it better not pre-allocate a `list`.

http://stackoverflow.com/q/50832497
upvote count: 0
has title: To get notification is that must to keep pycharm open in my pc?
answer count: 3
has answer: http://stackoverflow.com/a/50832929
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88669906
tagged with: pycharm
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50845113
accepted answer: http://stackoverflow.com/a/50832929
has answer: http://stackoverflow.com/a/50853373
has answer: http://stackoverflow.com/a/50845113
score: -1
has body: To get notifications is that must to keep the pycharm online? Everything work fine and pushing notifications but when i close the pycharm then the notification stops and not working!
type: Question

http://stackoverflow.com/a/50737322
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88483454
has body: You seem to be struggling with two issues: accessing the file paths resize For you to win, better separate these two tasks, sample code below IMG_PX_SIZE = 64 def resize(image): # your resize code here similar to: # return v2.resize(np.array(image.pixel_array(IMG_PX_SIZE,IMG_PX_SIZE)) pass def read(path): # your file read operation here pass big_list = [['~/images/0001.dcm','~/images/0135.dcm'], ['~/images/0002.dcm','~/images/0136.dcm']] resized_images = [[resize(read(path)) for path in paths] for paths in big_list]
type: Answer
has comment: http://stackoverflow.com/comment/88488684
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88489149
answers question: http://stackoverflow.com/q/50736643
has comment: http://stackoverflow.com/comment/88489612
accepted answer of: http://stackoverflow.com/q/50736643
has comment: http://stackoverflow.com/comment/88483722
has comment: http://stackoverflow.com/comment/88487076
upvote count: 1

wikipedia-api
tag name: wikipedia-api
tags question: http://stackoverflow.com/q/50830961
type: Tag
tags question: http://stackoverflow.com/q/50837619

http://stackoverflow.com/q/50808986
type: Question
has body: I have the foll. pandas dataframe: 2018-05-25 0.000381 0.264318 land 2018-05-25 2018-05-26 0.000000 0.264447 land 2018-05-26 2018-05-27 0.000000 0.264791 NaN NaT 2018-05-28 0.000000 0.265253 NaN NaT 2018-05-29 0.000000 0.265720 NaN NaT 2018-05-30 0.000000 0.266066 land 2018-05-30 2018-05-31 0.000000 0.266150 NaN NaT 2018-06-01 0.000000 0.265816 NaN NaT 2018-06-02 0.000000 0.264892 land 2018-06-02 2018-06-03 0.000000 0.263191 NaN NaT 2018-06-04 0.000000 0.260508 land 2018-06-04 2018-06-05 0.000000 0.256619 NaN NaT 2018-06-06 0.000000 0.251286 NaN NaT 2018-06-07 0.000000 0.244250 NaN NaT 2018-06-08 0.000000 0.235231 NaN NaT 2018-06-09 0.000000 0.223932 land 2018-06-09 I want to replace values in the 3rd column with NaN when there are 3 or more consecutive NaN values in the 4th column. The output should look like this: 2018-05-25 0.000381 0.264318 land 2018-05-25 2018-05-26 0.000000 0.264447 land 2018-05-26 2018-05-27 0.000000 0.264791 NaN NaT 2018-05-28 0.000000 0.265253 NaN NaT 2018-05-29 0.000000 NaN NaN NaT 2018-05-30 0.000000 0.266066 land 2018-05-30 2018-05-31 0.000000 0.266150 NaN NaT 2018-06-01 0.000000 0.265816 NaN NaT 2018-06-02 0.000000 0.264892 land 2018-06-02 2018-06-03 0.000000 0.263191 NaN NaT 2018-06-04 0.000000 0.260508 land 2018-06-04 2018-06-05 0.000000 0.256619 NaN NaT 2018-06-06 0.000000 0.251286 NaN NaT 2018-06-07 0.000000 NaN NaN NaT 2018-06-08 0.000000 NaN NaN NaT 2018-06-09 0.000000 0.223932 land 2018-06-09 I am also ok if instead of replacing by NaNs, the row is completely removed
has title: replace values in pandas column when N number of NaNs exist in another column
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50809282
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50809282
possible better answer: http://stackoverflow.com/a/50809392
has answer: http://stackoverflow.com/a/50809392

http://stackoverflow.com/a/50824242
has body: I've found out what the issue was! I wasn't passing through self. Such a small issue/error can cause so much frustration! For those that look at this post in the future, make sure you carefully read what the error says, and make sure that when using classes, self is passed through. Thank you to Andrew and PydPiper for your efforts, I probably could've addressed the question better, but I appreciate you guys having a go!
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50788007
answers question: http://stackoverflow.com/q/50788007

http://stackoverflow.com/comment/88465071
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50728328
has text: Comment here if you get stuck, ideally showing some progress of what you have tried in the question, serving a file from Flask has several solutions and is prerequisite that your html can show/reach that file. Your html is not necessarily wrong completely, you cannot just pass a Python object to the view, so what you pass as {{ name }} should be a URL. And you want that to be in "" too. Hope you succeed.
score: 2

http://stackoverflow.com/q/50824608
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/88684146
has answer: http://stackoverflow.com/a/50879934
score: 0
tagged with: python
tagged with: ssm
has body: ssm = boto3.client('ssm' ) instance = 'i-123123' response = ssm.send_command( InstanceIds=[ instance ], DocumentName='AWS-RunShellScript', Comment='slack testing', Parameters={ "commands":[ "hostname" ] } ) command_id = response['Command']['CommandId'] command_id.encode("utf-8") output = ssm.get_command_invocation( CommandId=command_id, InstanceId=instance ) Above is the code . the issue is in get_command_invocation its is not passing as varibale but passing as string and throing below error An error occurred (InvocationDoesNotExist) when calling the GetCommandInvocation operation: : InvocationDoesNotExist Traceback (most recent call last): File "/var/task/lambda_function.py", line 137, in lambda_handler InstanceId=instance File "/var/runtime/botocore/client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "/var/runtime/botocore/client.py", line 612, in _make_api_call raise error_class(parsed_response, operation_name) InvocationDoesNotExist: An error occurred (InvocationDoesNotExist) when calling the GetCommandInvocation operation: but if i separately print command_id and instance they are actually printing the actual id. What will the solution for this?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88656719
tagged with: boto3
type: Question
has title: aws boto pass variable
answer count: 1

http://stackoverflow.com/a/50783018
has comment: http://stackoverflow.com/comment/88574174
has comment: http://stackoverflow.com/comment/88575213
has body: assuming you have your original DF, before grouping: In [70]: df Out[70]: ID A B C D 0 1.0 x x x 10.0.0.50/TCP/50 1 1.0 x x x 192.168.1.90/TCP/51 2 1.0 x x x server1/TCP/80 3 1.0 x x x 10.0.0.9/TCP/78 4 2.0 y y y 192.168.3.90/UDP/53 5 2.0 y y y 10.0.4.10/TCP/65 6 2.0 y y y 10.0.3.4/TCP/34 7 2.0 y y y host1/UDP/80 8 3.0 z z z 10.0.0.40/TCP/80 9 3.0 z z z 10.0.0.41/TCP/443 10 3.0 z z z 192.168.2.70/UDP/98 11 3.0 z z z 10.0.0.9/TCP/12 Option 1: multi-index DF: In [69]: (df.assign(x=df.D.replace(['/.*',r'\b(\d{1})\b',r'\b(\d{2})\b'], ...: ['',r'00\1',r'0\1'], ...: regex=True)) ...: .sort_values('x') ...: .groupby(['ID','A','B','C'], sort=False, as_index=False)['D'] ...: .apply('\n'.join) ...: .to_frame('D')) ...: ...: Out[69]: D ID A B C 1.0 x x x 10.0.0.9/TCP/78\n10.0.0.50/TCP/50\n192.168.1.9... 3.0 z z z 10.0.0.9/TCP/12\n10.0.0.40/TCP/80\n10.0.0.41/T... 2.0 y y y 10.0.3.4/TCP/34\n10.0.4.10/TCP/65\n192.168.3.9... Option 2: regular DF: In [75]: (df.assign(x=df.D.replace(['/.*',r'\b(\d{1})\b',r'\b(\d{2})\b'], ...: ['',r'00\1',r'0\1'], ...: regex=True)) ...: .sort_values('x') ...: .groupby(['ID','A','B','C'], sort=False, as_index=False)['D'] ...: .apply('\n'.join) ...: .reset_index(name='D')) ...: ...: Out[75]: ID A B C D 0 1.0 x x x 10.0.0.9/TCP/78\n10.0.0.50/TCP/50\n192.168.1.9... 1 3.0 z z z 10.0.0.9/TCP/12\n10.0.0.40/TCP/80\n10.0.0.41/T... 2 2.0 y y y 10.0.3.4/TCP/34\n10.0.4.10/TCP/65\n192.168.3.9... the following might help to understand how does it work: add a virtual column x with zero padded IP octets: In [71]: df.assign(x=df.D.replace(['/.*',r'\b(\d{1})\b',r'\b(\d{2})\b'], ...: ['',r'00\1',r'0\1'], ...: regex=True)) ...: ...: Out[71]: ID A B C D x 0 1.0 x x x 10.0.0.50/TCP/50 010.000.000.050 1 1.0 x x x 192.168.1.90/TCP/51 192.168.001.090 2 1.0 x x x server1/TCP/80 server1 3 1.0 x x x 10.0.0.9/TCP/78 010.000.000.009 4 2.0 y y y 192.168.3.90/UDP/53 192.168.003.090 5 2.0 y y y 10.0.4.10/TCP/65 010.000.004.010 6 2.0 y y y 10.0.3.4/TCP/34 010.000.003.004 7 2.0 y y y …
has comment: http://stackoverflow.com/comment/88575158
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50782385
has comment: http://stackoverflow.com/comment/88575765
score: 1
upvote count: 1

http://stackoverflow.com/comment/88498706
comment on: http://stackoverflow.com/q/50745460
type: Comment
has text: The output makes sense to me. You're checking `keyboard.is_pressed` in a loop, and you might reasonably expect the loop to iterate a thousand times a second. So if you hold down ctrl+c for one second, then the conditional will execute a thousand times. You should look at the keyboard documentation to see if there's a way to perform some action exactly once in response to a keyboard event.
score: 0
type: QuestionComment

http://stackoverflow.com/q/50777658
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
has body: Trying to set up a neural network using Keras in python. I get this error when trying to predict with my neural network: ValueError: Error when checking : expected input_1 to have shape (12,) but got array with shape (1,) However if i print(x.shape) it returns as (12,) This is the code block: def predict(str): y = convert(str) x = data = np.array(y, dtype='int64') with graph.as_default(): print(x.shape); #perform the prediction out = model.predict(x) print(out) print(np.argmax(out,axis=1)) print ("debug3") #convert the response to a string response = np.array_str(np.argmax(out,axis=1)) return response
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50782484
tagged with: machine-learning
upvote count: 1
type: Question
score: 1
has title: Keras, wrong input shape, but x.shape is right
accepted answer: http://stackoverflow.com/a/50782484

http://stackoverflow.com/comment/88679862
comment on: http://stackoverflow.com/a/50836700
type: AnswerComment
has text: awesome! great! please, could you explain me the first syntax a bit? thanks!
score: 1
type: Comment

swagger-codegen
tag name: swagger-codegen
type: Tag
tags question: http://stackoverflow.com/q/50809860

http://stackoverflow.com/a/50745244
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50745224
has body: You don't need a double assignment. Try this: data.loc[data['Value2'] &lt; 10, 'Value1'] = np.nan Remember pd.DataFrame.loc can be used both as a "getter" and as a "setter". So it is perfectly natural to assign a value to data.loc[slice1, slice2].
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50745224

http://stackoverflow.com/comment/88708465
type: Comment
has text: @MelvinAbraham That will just convert byte question marks into Unicode question marks. (Tested on ActivePython 2.7.14.2717).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50837681

http://stackoverflow.com/comment/88705471
type: QuestionComment
comment on: http://stackoverflow.com/q/50834357
score: 0
has text: @MartinEvans Yes, done.
type: Comment

http://stackoverflow.com/q/50808979
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50811816
type: Question
has body: I have a python (pandas) script that reads csv files into a dataframe, edits them, and makes them into a new csv (output): import pandas as pd df = pd.read_csv(r'\filename.csv', sep=',') # I skipped over the dataframe edits try: df.to_csv(r'outputfilename', sep='\t', encoding='utf-8') except IOError as e: print('Could not make Excel file' % e)` I would like to use it on multiple csv files at once and get multiple outputs (csv's): I have tried: from tkinter.filedialog import askopenfilename filename = askopenfilename() df = pd.read_csv(filename, sep=',') ... and it works (gives me an selection window), but I am only able to choose one file
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50812455
score: 0
has title: Using python pandas script on multiple files
possible better answer: http://stackoverflow.com/a/50812455
has answer: http://stackoverflow.com/a/50811816

http://stackoverflow.com/a/50752492
has comment: http://stackoverflow.com/comment/88513401
has comment: http://stackoverflow.com/comment/88514705
has comment: http://stackoverflow.com/comment/88513507
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88566232
has body: A good deterministic way to find relatively small prime numbers is to use a sieve. The mathematical principle behind this technique is the following: to check if a number is prime, it is sufficient to check that it is not divisible by other primes. import math def is_prime(n): # Prepare our Sieve, for readability we make index match the number by adding 0 and 1 primes = [False] * 2 + [True] * (n - 1) # Remove non-primes for x in range(2, int(math.sqrt(n) + 1)): if primes[x]: primes[2*x::x] = [False] * (n // x - 1) return primes[n] # Or use the following to return all primes: # return {x for x, is_prime in enumerate(primes) if is_prime} print(is_prime(13)) # True For reusability your could adapt the above code to return the set of all prime numbers up to n.
accepted answer of: http://stackoverflow.com/q/50752438
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88514692
answers question: http://stackoverflow.com/q/50752438
has comment: http://stackoverflow.com/comment/88514720

http://stackoverflow.com/a/50843573
type: Answer
answers question: http://stackoverflow.com/q/50843263
has comment: http://stackoverflow.com/comment/88691032
has body: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html As mentioned in the comment just do x.replace(None, 'N/A', True)
has comment: http://stackoverflow.com/comment/88690747
score: 0

http://stackoverflow.com/comment/88957851
comment on: http://stackoverflow.com/a/50944989
score: 0
type: Comment
has text: I am not sure if one can combine the both with a temporary hack, if you can do something or have any updates, please post here :)
type: AnswerComment

http://stackoverflow.com/q/50813738
has comment: http://stackoverflow.com/comment/88632684
tagged with: python
has comment: http://stackoverflow.com/comment/88636729
tagged with: django
has answer: http://stackoverflow.com/a/53723503
accepted answer: http://stackoverflow.com/a/53723503
has title: Python virtualenv no module named django
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88633251
has comment: http://stackoverflow.com/comment/88634139
has comment: http://stackoverflow.com/comment/90375753
type: Question
has comment: http://stackoverflow.com/comment/88665004
has comment: http://stackoverflow.com/comment/88666328
has comment: http://stackoverflow.com/comment/88633272
answer count: 1
has body: In my ec2 machine i need to run a django project, I do the below thinks: Install python 3.4: sudo yum install python34 ok, now i create a virtual enviroment for python 3: virtualenv -p python3 .venv3 at this point activate my venv: source .venv3/bin/activate all done! Now i have to install django: pip install django the installation was ok but when i try to check my django version: python -c "import django; print(django.get_version())" system return the error "No module name django found" How is possible? In my machine there is also python 2.7 installed. I try outside the virtualenv to remove django with: sudo python -m pip uninstall django all done, but in my .venv3 enviroment the issue is still present. How can i fix the problem? i also tried to reinstall django like this: pip install --upgrade --force-reinstall django response: Collecting django Using cached https://files.pythonhosted.org/packages/56/0e/afdacb47503b805f3ed213fe732bff05254c8befaa034bbada580be8a0ac/Django-2.0.6-py3-none-any.whl Collecting pytz (from django) Using cached https://files.pythonhosted.org/packages/dc/83/15f7833b70d3e067ca91467ca245bae0f6fe56ddc7451aa0dc5606b120f2/pytz-2018.4-py2.py3-none-any.whl Installing collected packages: pytz, django Found existing installation: pytz 2018.4 Uninstalling pytz-2018.4: Successfully uninstalled pytz-2018.4 Successfully installed django-2.0.6 pytz-2018.4 but when i try: pip freeze response is: gunicorn==19.8.1 pytz==2018.4 virtualenv==16.0.0 Why django isn't installed? thanks in advance
tagged with: amazon-ec2
tagged with: virtualenv
tagged with: centos
score: 0
has comment: http://stackoverflow.com/comment/88633679

http://stackoverflow.com/a/50764143
score: 2
downvote count: 0
has body: As you are on Debian Server and working with Headless Chrome you need to configure the WebDriver instance as follows: from selenium import webdriver options = webdriver.ChromeOptions() options.binary_location='/usr/bin/google-chrome-stable' options.add_argument('--headless') options.add_argument('--start-maximized') options.add_argument('disable-infobars') options.add_argument('--disable-extensions') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument('window-size={}x{}'.format(*self.window_size)) self.driver = webdriver.Chrome(chrome_options=options, executable_path='/path/to/chromedriver') Reference How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? trouble running chrome headless browser
answers question: http://stackoverflow.com/q/50761757
has comment: http://stackoverflow.com/comment/88604496
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88701270
comment on: http://stackoverflow.com/q/50849090
score: 0
has text: @DyZ added it..Somehow it got removed while copy paste
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50821114
has comment: http://stackoverflow.com/comment/88647572
tagged with: python
has comment: http://stackoverflow.com/comment/88647616
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50821423
has body: I've got a class that has replaced __iter__ to hide extra unneeded data. I've made the rest of my code backwards compatible by setting iteritems to either dict.iteritems or dict.items depending on the python version, and I can then call iteritems(class_object), but it doesn't seem to work well with my class. It'll be easier to explain with an example: class Test(dict): def __init__(self, some_dict): self.some_dict = some_dict super(self.__class__, self).__init__(self.some_dict) def __iter__(self): for k, v in self.some_dict.iteritems(): yield k, v['value'] test_dict = { 'a': {'value': 'what', 'hidden': 123}, 'b': {'value': 'test'} } If I do Test(test_dict).__iter__(), then it correctly returns {'a': 'what', 'b': 'test'} If I add iteritems = __iter__ to the class, then it also works when doing Test(test_dict).iteritems() However, no matter what I try, doing dict.iteritems(Test(test_dict)) defaults to the standard dict iterating, and returns {'a': {'hidden': 123, 'value': 'what'}, 'b': {'value': 'test'}} I've tried a couple of trace functions but they don't go deep enough to figure out what's going on.
has title: Unable to find override for dict.iteritems(class)
type: Question
has comment: http://stackoverflow.com/comment/88648088
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88647993
has answer: http://stackoverflow.com/a/50821423
has comment: http://stackoverflow.com/comment/88648305

http://stackoverflow.com/q/50768601
has comment: http://stackoverflow.com/comment/88544622
has answer: http://stackoverflow.com/a/51328856
type: UnansweredQuestion
tagged with: python
score: -5
has comment: http://stackoverflow.com/comment/88544624
has comment: http://stackoverflow.com/comment/88544645
type: Question
upvote count: 0
has body: I am trying to make a program where it converts imperial to metric. The part I am having trouble with is that with any input that is an invalid number (any negative) I am supposed to terminate the program without using exit, break, or system exit. print('Hello, Please input the Imperial values!') #Miles Miles = float(input('Miles to Kilometers: ')) totalKilometers = (1.6 * Miles) if Miles &lt; 0: print('Please no negative numbers') else: if Miles &gt; 0: print("The metric conversion is ", totalKilometers) #Fahrenheit Fahrenheit = float(input('Fahrenheit to Celsius: ')) totalCelcius = ((Fahrenheit - 32) * 5/9 ) if Fahrenheit &lt; 0 or Fahrenheit &gt; 1000: print('Please check your Fahrenheit number, It must be greater than 0 and less than 1000') else: if Fahrenheit &gt; 0 or Fahrenheit &lt; 1000: print("The metric conversion is ", totalCelcius) #Gallons Gallons = float(input('Gallons to Liters: ')) totalLiters = (3.9 * Gallons) if Gallons &lt; 0: print('Please no negative numbers') else: if Gallons &gt; 0: print("The metric conversion is ", totalLiters) #Pounds Pounds = float(input('Pounds to Kilograms: ')) totalKilograms = (.45 * Pounds) if Pounds &lt; 0: print('Please no negative numbers') else: if Pounds &gt; 0: print("The metric conversion is ", totalKilograms) #Inches Inches = float(input('Inches to Cenitmeters: ')) totalCentimeters = (2.54 * Inches) if Inches &lt; 0: print('Please no negative numbers') else: if Inches &gt; 0: print("The metric conversion is ", totalCentimeters)
downvote count: 5
has title: How to make a program exit upon receiving invalid input?
has comment: http://stackoverflow.com/comment/88544642
answer count: 1
has comment: http://stackoverflow.com/comment/88544690
favorite count: 0

http://stackoverflow.com/a/50723371
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50715886
has body: Or you could achieve the same without using hardcoded index: import requests from bs4 import BeautifulSoup url = "https://www.bloomberg.com/research/stocks/private/person.asp?personId=45794107&amp;privcapId=8032555&amp;previousCapId=12437591&amp;previousTitle=Pawan%20Hans%20Limited" response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') for items in soup.find_all(class_="sectionTitle"): if "Board Members" in items.text: item = items.find_next_sibling() presence = items.find_next_sibling().text position = item.find_next("div") company = item.find_next("a") print("{}\n{}\n{}".format(presence,position.text,company.text)) Output: 2017-Present Independent Director Air India Limited

http://stackoverflow.com/comment/88692714
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50844458
has text: @Joe Good point! Looks like my answer is identical to some others then. Deleting.

http://stackoverflow.com/a/50731750
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50731702
has body: Using pd.Series.str.split. Specific to your particular format. df['str'] = df['str'].str.split('_').str[-1].str[0] print(df) id str 0 1 d 1 2 d 2 3 e 3 4 b
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88540810
type: QuestionComment
comment on: http://stackoverflow.com/q/50721746
score: 3
has text: Even if you could trace your calls to `str`, it wouldn’t cover things like `"%s"%x`, `"".join(…)`, _etc_.
type: Comment

http://stackoverflow.com/q/50808519
has answer: http://stackoverflow.com/a/50822870
tagged with: python
has title: Remove double quotes from front and end while splitting CSV files
has comment: http://stackoverflow.com/comment/88622685
type: UnansweredQuestion
score: 0
type: Question
has body: I work with large CSV files. I was able to put up a code which splits the files into small chunks: import csv divisor = 500000 outfileno = 1 outfile = None with open('testM.txt', 'r') as infile: infile_iter = csv.reader(infile) header = next(infile_iter) for index, row in enumerate(infile_iter): if index % divisor == 0: if outfile is not None: outfile.close() outfilename = 'big-{}.csv'.format(outfileno) outfile = open(outfilename, 'w') outfileno += 1 writer = csv.writer(outfile) writer.writerow(header) writer.writerow(row) if outfile is not None: outfile.close() The problem I'm facing is that the first csv which is getting generated after the split has double quotes in the beginning and end for all its lines. Rest of the CSV files are not having this double quote issue. Also, the original file does not have any double quotes. Example, the first csv file looks something like below: "abc,ghhh,123,fgfg" "hjfhj,12312,adfa,6765" This causes an issue as I have to run few more tests over them and the first file is causing the issue while rest are just fine. It would be helpful if someone can help me modify this code to resolve my issue.
answer count: 2
has comment: http://stackoverflow.com/comment/88624324
has answer: http://stackoverflow.com/a/50808568
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/50824852
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88690133
type: UnansweredQuestion
tagged with: python
has title: Adding stylesheet to Bokeh App
has answer: http://stackoverflow.com/a/50825272
tagged with: bokeh
type: Question
has body: I have made a big complicated Bokeh dashboard. I have not defined any html templates for the dashboard. I have simply served it using the code below. My problem is, the dashboard looked very nice when using the bokeh.plotting.output_notebook function to embed it into a Jupyter notebook. Now, when trying to create and serve the dashboard outside of Jupyter, it looks much uglier because some stylesheets that render pretty tables aren't there. My question is, how do I get external stylesheets into my bokeh webapp. Dashboard Code: def emb_bokehdash(self, doc, dash_width=1500, dash_height=800): # Get base data: df_orig = self._get_base_data_for_vis(unlabeled_name) unique_labels = list(df_orig.label.unique()) ... # Sentence Selection Controls: index_text = AutocompleteInput( title="select sentence index", value=str(candidate_state), completions=list(df_orig.index.map(lambda idx: str(idx))), width=control_width ) index_next = Button(label="next", button_type="primary", width=button_width) index_back = Button(label="back", button_type="primary", width=button_width) selection_checkboxes = CheckboxGroup(labels=['unseen', 'random'], active=[]) index_input = row( widgetbox(index_text, width=control_width+200), widgetbox(index_next, index_back, width=button_width+40), selection_checkboxes, width=info_width ) ... More code defining DOM and wrangling data layout_ = row(inputs_and_info, plot, height=dash_height) # initial load of the data update_selectioninfo_and_plot() update_selected_info() # Register title and dashboard with the document: doc.title = "Smart Feedback Labeler" doc.add_root(layout_) Dashboard Server Code: from bokeh.server.server import Server from os import getpid def emb_bokehdash_serve(self, **server_kwargs): # Route App: apps = {'/': Application(FunctionHandler(self.bokeh_dashboard))} # Extract Port (default = 5000): if "port" not in server_kwargs: server_kwargs["port"] = 5000 # Find a suitable port to use: while True: try: server = Server(apps, **server_kwargs…

http://stackoverflow.com/comment/88563454
comment on: http://stackoverflow.com/a/50778168
has text: @malan you are welcomed. And sure you will; arguably, if you process literature without an NLP toolkit you are doing it wrong.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50721307
type: Question
tagged with: subplot
has answer: http://stackoverflow.com/a/50721507
score: 0
answer count: 2
has body: I am trying to plot 5 subplots in Python with differing sizes and orientation. I have seen usage of gridspec to alter column width, plt.figure(figsize=[]), etc. but each seems to be slightly off from what I want (e.g. no uniform column width, all one plot, so can't use plt.figure()). What I currently have is a subplot(3,2,2) with the first 5 plots filled such that it looks like a 3x2 grid without the bottom right filled in. What I would like is a 2x2 grid with a single plot below it. The plot below should also be larger (maybe twice as wide) as the four above it. This is what I have versus what I would like. Here is my code (sorry for the line numbers): plot3 = plt.figure(1) plt.subplot(321) #gs = gridspec.GridSpec(1,2,3,4,5,6,width_ratios=[1,1,1,1,2,0]) plt.scatter(0.001*posEncUm[:,0],err[:,0], s=1, linewidths=1) p = np.polyfit(0.001*posEncUm[:,0],err[:,0],1) plt.title('Slope = {0:4.1f} um/100mm'.format(p[0]*100), fontsize=10) plt.xlabel('Encoder Position (X), mm', fontsize=7) plt.ylabel('Laser Error (X), um', fontsize=7) plt.subplots_adjust(hspace = 1.0, wspace = 0.5) plt.grid() plt.subplot(322) plt.scatter(0.001*posEncUm[:,1],err[:,0], s=1, linewidths=1) p = np.polyfit(0.001*posEncUm[:,1],err[:,0],1) plt.title('Slope = {0:4.1f} um/100mm'.format(p[0]*100), fontsize=10) plt.xlabel('Encoder Position (Y), mm', fontsize=7) plt.ylabel('Laser Error (X), um', fontsize=7) plt.grid() plt.subplot(323) plt.scatter(0.001*posEncUm[:,0],err[:,1], s=1, linewidths=1) p = np.polyfit(0.001*posEncUm[:,0],err[:,1],1) plt.title('Slope = {0:4.1f} um/100mm'.format(p[0]*100), fontsize=10) plt.xlabel('Encoder Position (X), mm', fontsize=7) plt.ylabel('Laser Error (Y), um', fontsize=7) plt.grid() plt.subplot(324) plt.scatter(0.001*posEncUm[:,1],err[:,1], s=1, linewidths=1) p = np.polyfit(0.001*posEncUm[:,1],err[:,1],1) plt.title('Slope = {0:4.1f} um/100mm'.format(p[0]*100), fontsize=10) plt.xlabel('Encoder Position (Y), mm', fontsize=7) plt.ylabel('Laser Error (Y), um', fontsize=7) plt.gri…
accepted answer: http://stackoverflow.com/a/50721507
has answer: http://stackoverflow.com/a/50722000
tagged with: python
possible better answer: http://stackoverflow.com/a/50722000
has title: Customizing Subplot Orientation and Size with Maplotlib
type: AnsweredQuestion

http://stackoverflow.com/q/50708706
tagged with: python
score: 0
type: UnansweredQuestion
tagged with: django
type: Question
has title: Use components in Django Framework
answer count: 1
has body: I'm struggling with using components in Django. My project: I'm working on a weblog that presents the current blog post. In the sidebar I want to include a component that lists ten latest posts and ten related posts. Each of these components are not only templates, but also include logic (which I rather would not include in the template using template tags). What would be the best way to go to include such components?
has answer: http://stackoverflow.com/a/50708826

http://stackoverflow.com/a/50706242
score: 2
has body: Loopy numpy method This is not the most beautiful way, and there is likely a vectorized approach that is much more elegant and efficient, but you can do the following with a list comprehension. See the bottom for benchmark. Given a 2-d array x: &gt;&gt;&gt; x array([[ 1, 3, 7, 34], [ 1, 4, 3, 6], [ 1, 8, 2, 10], [ 2, 9, 35, 11], [ 2, 10, 12, 24]]) np.vstack([np.insert(x[x[:,0] == i][:,1:].sum(axis=0),0,i) for i in np.unique(x[:,0])]) Returns: array([[ 1, 15, 12, 50], [ 2, 19, 47, 35]]) pandas suggestion For this sort of tabular data, though, you might want to consider pandas. For example: import pandas as pd df = pd.DataFrame(x) &gt;&gt;&gt; df 0 1 2 3 0 1 3 7 34 1 1 4 3 6 2 1 8 2 10 3 2 9 35 11 4 2 10 12 24 &gt;&gt;&gt; df.groupby(0).sum() 1 2 3 0 1 15 12 50 2 19 47 35 You would also easily be able to get it back to a numpy array: &gt;&gt;&gt; df.groupby(0).sum().reset_index().values array([[ 1, 15, 12, 50], [ 2, 19, 47, 35]]) Benchmarks To my surprise, both methods are comparable as far as speed, with my loopy numpy method narrowly beating the pandas method: on a large array of shape (100000, 100), the loopy numpy method took about 0.1 seconds on average, and the pandas method took about 0.13 seconds on average import timeit x = np.random.randint(0,10,(100000, 100)) def np_method(arr = x): return np.vstack([np.insert(arr[arr[:,0] == i][:,1:].sum(axis=0),0,i) for i in np.unique(arr[:,0])]) def pd_method(df = pd.DataFrame(x)): return df.groupby(0).sum().reset_index().values &gt;&gt;&gt; timeit.timeit(pd_method, number = 100) / 100 0.12673938989639283 &gt;&gt;&gt; timeit.timeit(np_method, number = 100) / 100 0.09724574089050293
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50705996
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/88440808
accepted answer of: http://stackoverflow.com/q/50705996

http://stackoverflow.com/q/50732289
accepted answer: http://stackoverflow.com/a/50990229
favorite count: 0
tagged with: servo
has comment: http://stackoverflow.com/comment/88472475
upvote count: 1
has title: Servo Issues while using PWM with Raspberry Pi
type: AnsweredQuestion
score: 1
has body: My setup is simply the servo JX-PDI-6221MG being directly activated with raspberry pi's PWM through GPIO library. The servo is brand new, I followed this tutorial and set duty cycle values between 0 and 100. The angles it makes have no pattern, it seems to go one way from 20 to 50 and them from 60 to 90 the other. I decide to loop through all possible duty cycles (code is below) and I confirm that the variations aren't smooth and it doesn't look precise. After trying to set fix values again it suddenly starts to spin in multiple directions, even without I changing anything. Not even GPIO.cleanup() or killing python related processes made it stop. Is my Raspberry Pi getting jitter and being very imprecise or was I a victim of falsification? Code: import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(11,GPIO.OUT) pwm=GPIO.PWM(11,330) #which is the same as shown in datasheet pwm.start(0) for i in range(0,100): pwm.ChangeDutyCycle(i) time.sleep(0.02) for i in range(0,100): i = 100 - i pwm.ChangeDutyCycle(i) time.sleep(0.02)`
has answer: http://stackoverflow.com/a/50990229
type: Question
has answer: http://stackoverflow.com/a/75634487
tagged with: raspberry-pi
downvote count: 0
possible better answer: http://stackoverflow.com/a/61971166
has answer: http://stackoverflow.com/a/61971166
answer count: 3
tagged with: python

http://stackoverflow.com/comment/88622703
comment on: http://stackoverflow.com/q/50780561
has text: Mr. Patel, thank you for your quick response. "aidentensor" is a folder, so in the folder I added a file called "trained_model.py" and then in my code, appended my path to /aidentensor/trained_model.py" and it still couldn't find it. What am I doing wrong?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88571429
type: QuestionComment
has text: Ah that would be due to your IP being flagged by their services.
comment on: http://stackoverflow.com/q/50782308
score: 0
type: Comment

http://stackoverflow.com/comment/88637350
type: AnswerComment
score: 0
has text: @SeyyidSaid Your update doesn't make the question any more clearer. Is your objective to select an image from a gallery and then exclude it from that gallery? or is it to select an image from a gallery, and exclude it from a list of all images? Either way, you need to identify the image first through its own id, not through the gallery's slug.
type: Comment
comment on: http://stackoverflow.com/a/50798597

http://stackoverflow.com/q/50796302
tagged with: scapy
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50796723
has body: I am trying to send TCP traffic to a device using a python script. My script reads a particular pcap for processing packets. In my packet capture file there is Dot1Q VLAN tagging and I would like to remove it using scapy in my script. Output contains the following : Ether / Dot1Q / IP / TCP >: port > : port Please tell how I can remove the vlan tagging in my script using scapy.
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: Scapy - Removing Dot1q (801.2 Q) from a pcap
tagged with: python
score: 1

http://stackoverflow.com/q/50712919
has comment: http://stackoverflow.com/comment/88435560
has comment: http://stackoverflow.com/comment/88441974
has comment: http://stackoverflow.com/comment/88435296
has body: EDIT: Problem solved, keeping this open for posterity. numpy.genfrontext has trouble delimiting strings that have commas. In order to solve this, simply use pandas.read_csv and employ the quotechar = '"' to allow the importer to properly handle the strings that contain your commas. Strange problem here. I'm importing lists of protein data from .csv files that, for 99.9% of IDs, works flawlessly. However, 1 ID out of ~5000 thousand IDs is consistently importing the wrong data. Here's the code I use to pull in my data. It's using glob to pull in csv files with similar names. Headers are stored as a list and then used as columns just in case the csv files have their headers mixed around (damn you, Proteome Discoverer): indexes = ["Accession", "# Peptides", "MW [kDa]", "Score"] headers = pd.read_csv(str(WorkingDirectory) + "/" + str(name) + "-R1.csv", nrows=1).columns.tolist() total = [np.genfromtxt(x, delimiter = ',', skip_header = 1, usecols = [int(headers.index(indexes[0])),int(headers.index(indexes[1])),int(headers.index(indexes[2])),int(headers.index(indexes[3]))], filling_values = 0.01, dtype = ('|U16','float64','float64','float64')).tolist() for x in glob.glob(str(WorkingDirectory) + "/" + str(name) + "*.csv")] IDs are then stored in a list, where each list entry matches the original file. [File 1, File 2, File 3] Here's where it gets weird. Of the 5.5K entries in each .csv file, there is one ID that consistently (with code restarts) reports the wrong numbers. Please find attached the output of my program, alongside the excel sheets that the data are sourced from. Columns A, C, E and H are my imports (Accession, Score, # Peptides and MW [kDa] respectively, in orange) It looks like the ID's name and score are importing the correct value, but the next two columns are, respectively, off by 1 (it's importing F, not E) and then trying to pick up a value from an unspecified column that doesn't exist (hence the 0.01 due to filling values) Things I have checked: 1) Yes, …
linked to: http://stackoverflow.com/q/17933282
type: Question
tagged with: numpy
has title: np.genfromtext importing wrong values from .csv file - 2nd column is full of commas inside quote marks
has comment: http://stackoverflow.com/comment/88434792
score: 0
has comment: http://stackoverflow.com/comment/88435261
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88435260
has comment: http://stackoverflow.com/comment/88434771
has comment: http://stackoverflow.com/comment/88435664
has comment: http://stackoverflow.com/comment/88434759
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88435307

http://stackoverflow.com/comment/88639926
comment on: http://stackoverflow.com/a/50771431
type: Comment
score: 0
has text: Ok so it is better to just break things down into basic data types before dumping/loading? Thanks for the thorough answer.
type: AnswerComment

http://stackoverflow.com/comment/88617351
type: Comment
has text: With this config, will I see all the logs (like in dev terminal) in a file?
comment on: http://stackoverflow.com/a/50784827
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88602379
type: AnswerComment
comment on: http://stackoverflow.com/a/50798233
has text: yeah. You are right. Why I didn't see that. Just curious ,is the order matter
type: Comment
score: 0

http://stackoverflow.com/q/50731785
tagged with: python
linked to: http://stackoverflow.com/q/45600246
has title: Create random shape/contour using matplotlib
score: 25
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50732357
linked to: http://stackoverflow.com/q/63107373
possible better answer: http://stackoverflow.com/a/50751932
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50751932
tagged with: bezier
linked to: http://stackoverflow.com/q/49570341
type: Question
tagged with: contour
downvote count: 0
has body: I am trying to generate an image of a random contour using python but I couldn't find an easy way to do it. Here is an example sort of what I want: Initially I tought of doing it using matplotlib and gaussian functions, but I could not even get close to the image I showed. Is there a simple way to do it? I appreciate any help
answer count: 3
has answer: http://stackoverflow.com/a/50732357
has answer: http://stackoverflow.com/a/50732182
favorite count: 0
upvote count: 25
tagged with: shapes

http://stackoverflow.com/q/50806165
favorite count: 0
accepted answer: http://stackoverflow.com/a/50806435
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50806375
upvote count: 1
tagged with: python
has body: I am new to Python especially when it comes to using it with Excel. I need to write code to search for the string “Mac”, “Asus”, “AlienWare”, “Sony”, or “Gigabit” within a longer string for each cell in column A. Depending on which of these strings it finds within the entire entry in column A’s cell, it should write one of these 5 strings to the corresponding row in column C’s cell. Else if it doesn’t find any of the five, it would write “Other” to the corresponding row in column C. For example, if Column A2’s cell contained the string “ProLiant Asus DL980 G7, the correct code would write “Asus” to column C2’s cell. It should do this for every single cell in column A, writing the appropriate string to the corresponding cell in column C. Every cell in column A will have one of the five strings Mac, Asus, AlienWare, Sony, or Gigabit within it. If it doesn’t contain one of those strings, I want the corresponding cell in column 3 to have the string “Other” written to it. So far, this is the code that I have (not much at all): import openpyxl wb = openpyxl.load_workbook(path) sheet = wb.active for i in range (sheet.max_row): cell1 = sheet.cell (row = i, column = 1) cell2 = sheet.cell (row = I, column = 3) # missing code here wb.save(path)
possible better answer: http://stackoverflow.com/a/50806375
type: AnsweredQuestion
score: 1
tagged with: excel-2010
has title: manipulating excel spreadsheets with python
has comment: http://stackoverflow.com/comment/88618869
has comment: http://stackoverflow.com/comment/88646706
type: Question
has comment: http://stackoverflow.com/comment/88643596
answer count: 2
tagged with: automation
has answer: http://stackoverflow.com/a/50806435
downvote count: 0
tagged with: string-search

http://stackoverflow.com/comment/88509970
has text: Ah -- I see -- `helpers` appears to be a separate module, independent of any class. Dead end -- I would think that the next line of attack would be to dig into and past the `encoder` to see how the data flows there.
comment on: http://stackoverflow.com/q/50750387
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50826625
tagged with: nlp
upvote count: 3
type: UnansweredQuestion
tagged with: machine-learning
type: Question
score: 3
tagged with: lstm
has body: I am working on an image captioning system in python using Keras and when using argmax search I get reasonable results (~0.58 Bleu_1 score and the sentences are quite diverse). When I try beam search, however, I get almost the same sentence for every image. I have the following code for generating the captions: # create an array of captions for a chunk of images; first token # of each caption is the start token test_x = np.zeros((chunk_size, self.max_len - 1), dtype=np.int) test_x[:, 0] = self.start_idx + 1 # probability of each caption is 1 captions_probs = np.ones(chunk_size) # for every image, maintain a heap with the best captions self.best_captions = [FixedCapacityMaxHeap(20) for i in range(chunk_size)] # call beam search using the current cnn features self.beam_search(cnn_feats, test_x, captions_probs, 0, beam_size) The beam search method is the following: def beam_search(self, cnn_feats, generated_captions, captions_probs, t, beam_size): # base case: the generated captions have max_len length, so # we can remove the (zero) pad at the end and for each image # we can insert the generated caption and its probablity into # the heap with the best captions if t == self.max_len - 1: for i in range(len(generated_captions)): caption = self.remove_zero_pad(list(generated_captions[i])) self.best_captions[i].push(list(caption), captions_probs[i]) else: # otherwise, make a prediction (we only keep the element at time # step t + 1, as the LSTM has a many-to-many architecture, but we # are only interested in the next token (for each image). pred = self.model.predict(x=[cnn_feats, generated_captions], batch_size=128, verbose=1)[:, t + 1, :] # efficiently get the indices of the tokens with the greatest probability # for each image (they are not necessarily sorted) top_idx = np.argpartition(-pred, range(beam_size), axis=1)[:, :beam_size] # store the probability of those tokens top_probs = pred[np.arange(top_idx.shape[0])[:, None], top_idx] # for every 'neighbour' (set of newly…
answer count: 1
downvote count: 0
tagged with: keras
has title: Python beam search for Keras LSTM model generating the same sequence
favorite count: 0
has answer: http://stackoverflow.com/a/50859176
tagged with: python

windows
tags question: http://stackoverflow.com/q/50848226
tags question: http://stackoverflow.com/q/50779165
tags question: http://stackoverflow.com/q/50761252
tags question: http://stackoverflow.com/q/50804416
tags question: http://stackoverflow.com/q/50702056
tags question: http://stackoverflow.com/q/50743723
tags question: http://stackoverflow.com/q/50743896
tags question: http://stackoverflow.com/q/50783177
tags question: http://stackoverflow.com/q/50746046
tags question: http://stackoverflow.com/q/50719840
tags question: http://stackoverflow.com/q/50811506
tags question: http://stackoverflow.com/q/50721107
tags question: http://stackoverflow.com/q/50718126
tags question: http://stackoverflow.com/q/50784571
tags question: http://stackoverflow.com/q/50715822
tags question: http://stackoverflow.com/q/50766483
tags question: http://stackoverflow.com/q/50833971
tags question: http://stackoverflow.com/q/50742361
tags question: http://stackoverflow.com/q/50760914
tags question: http://stackoverflow.com/q/50761021
tags question: http://stackoverflow.com/q/50776173
tags question: http://stackoverflow.com/q/50711760
tags question: http://stackoverflow.com/q/50768565
tags question: http://stackoverflow.com/q/50797819
type: Tag
tags question: http://stackoverflow.com/q/50840640
tags question: http://stackoverflow.com/q/50798150
tags question: http://stackoverflow.com/q/50803692
tags question: http://stackoverflow.com/q/50772694
tags question: http://stackoverflow.com/q/50702903
tags question: http://stackoverflow.com/q/50743706
tags question: http://stackoverflow.com/q/50835541
tags question: http://stackoverflow.com/q/50702896
tags question: http://stackoverflow.com/q/50788641
tag name: windows
tags question: http://stackoverflow.com/q/50711722
tags question: http://stackoverflow.com/q/50768623
tags question: http://stackoverflow.com/q/50730539

http://stackoverflow.com/q/50728574
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88501374
has body: I am exporting some data in a Django view to csv, simplified code example below. I want to get all the games from the Game model and for each game, get the scores (one to many relationship). I am getting the error tuple object has no attribute score_set so the below code which I have tried doesn't appear to be the correct way to do this. I have no problem with getting the Game objects exported alone. Can anyone point me in the right direction please? response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="stuff.csv"' writer = csv.writer(response) writer.writerow(['Name', 'Details', 'More details']) games = Game.objects.filter(user=request.user).values_list('name', 'details', 'more_details') for game in games: scores = game.score_set.all().values_list('score', 'date_played') writer.writerow(game) for score in scores: writer.writerow(score) return response
accepted answer: http://stackoverflow.com/a/50729077
score: 1
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50729077
tagged with: python
has comment: http://stackoverflow.com/comment/88466474
has title: Django - getting entries from a foreign key relationship for csv output
tagged with: django
upvote count: 1

http://stackoverflow.com/q/50759500
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88526429
has comment: http://stackoverflow.com/comment/88526396
tagged with: floating-point
type: Question
accepted answer: http://stackoverflow.com/a/50759572
has body: I want to define the precision of a float while taking it as an input NGAS=float(input("enter a number with 3 decimal places")) instead of mentioning the 3 decimal places I want to do the equivalent of print('%.3f%' % ESTART) while taking the input. Since, it affects my calculations.
has answer: http://stackoverflow.com/a/50759572
has comment: http://stackoverflow.com/comment/88526346
upvote count: 1
answer count: 1
tagged with: precision
favorite count: 0
tagged with: python-3.x
has title: Define float precision while taking input in python3
tagged with: python

http://stackoverflow.com/q/50807336
has comment: http://stackoverflow.com/comment/88620477
answer count: 1
favorite count: 0
has title: Why doesn't this break?
downvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88620488
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/50807437
has comment: http://stackoverflow.com/comment/88620457
upvote count: 0
has body: I wrote some code I have to submit to an online programming class. The code is intended to: Import and open a file Append data to said file Read from said file to display each city name and month average high temperature in Celsius. The output is supposed to look like this: City of Beijing month ave: highest high is 30.9 Celsius City of Cairo month ave: highest high is 34.7 Celsius City of London month ave: highest high is 23.5 Celsius City of Nairobi month ave: highest high is 26.3 Celsius City of New York City month ave: highest high is 28.9 Celsius City of Sydney month ave: highest high is 26.5 Celsius City of Tokyo month ave: highest high is 30.8 Celsius City of Rio De Janeiro month ave: highest high is 30.0 Celsius When the code is run it goes into an infinity loop and I don't understand why. I thought that when the file pointer got to the end of the file, the code would break because the read would equal ""(empty string) and that is Falsey so it would stop. I know that it would be better to write the code without keyword "while" but in my class that keyword is required to be in the code. I got the code to work perfectly with a for/in keyword. Any help is greatly appreciated. The code: !curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt mean_temp_file = open("mean_temp.txt","a+") mean_temp_file.write("Rio de Janeiro,Brazil,30.0,18.0\n") mean_temp_file.seek(0) headings = mean_temp_file.readline() headings_list = headings.split(",") city_temp = mean_temp_file.readlines() while city_temp: for each_line in city_temp: each_line_list = each_line.split(",") print(headings_list[0].title(),"of",each_line_list[0].title(),headings_list[2],"is",each_line_list[2],"Celsius.") mean_temp_file.close() In case it helps, I wrote the code in Microsoft Azure Notebooks.
has comment: http://stackoverflow.com/comment/88620441
type: Question

http://stackoverflow.com/q/50829278
tagged with: python
has title: Python Syntax error: non-ASCII
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10589620
has body: I keep getting an error and I'm not sure on how to fix it. The Code line: if not len(lines) or lines[-1] == '' or lines[-1] == '▁': lines = list(filter(lambda line: False if line == '' or line == '▁' else True, list(lines))) Output: SyntaxError: Non-ASCII character '\xe2' in file prepare_data.py on line 512, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
linked to: http://stackoverflow.com/q/6289474
has comment: http://stackoverflow.com/comment/88663406
has comment: http://stackoverflow.com/comment/88662815
has answer: http://stackoverflow.com/a/50829958
type: Question
duplicate of: http://stackoverflow.com/q/10589620
answer count: 2
tagged with: syntax-error
has answer: http://stackoverflow.com/a/50829362
score: 0
linked to: http://stackoverflow.com/q/728891
has comment: http://stackoverflow.com/comment/88664563
has comment: http://stackoverflow.com/comment/88664442

http://stackoverflow.com/a/50822096
answers question: http://stackoverflow.com/q/50822068
accepted answer of: http://stackoverflow.com/q/50822068
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: In a nutshell : In python True is 1 and False is 0. This should correct this weird behavior : bw_np = numpy.asarray(bwImage, dtype=int) Long answer : Maybe imageOpen.convert("1", dither=Image.NONE) prefer bool instead of int32 for a better memory management : import sys import numpy print("Size of numpy.bool_() :", sys.getsizeof(numpy.bool_())) print("Size of numpy.int32() :", sys.getsizeof(numpy.int32())) Result : Size of numpy.bool_() : 13 Size of numpy.int32() : 16

http://stackoverflow.com/q/50840847
type: Question
tagged with: bokeh
has title: Color based on year in bokeh
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/50840898
tagged with: pandas
tagged with: python
type: UnansweredQuestion
has body: So I've basically got this snippet of code: import pandas as pd from bokeh.plotting import figure, ColumnDataSource from bokeh.io import show, output_file import bokeh.models as bmo data = { 'ranking': df['ranking'], 'pct_intl_student' : df['pct_intl_student'], 'years': year_list, 'color': colors, 'university':df['university_name'] } source = ColumnDataSource(data) hover = bmo.HoverTool( tooltips=[('year', '@years'), ('ranking', '@ranking'), ('% Int. Stu.', '@pct_intl_student'), ('University', '@university')]) p = figure(tools=[hover], title="Scatterplot: International Students") p.xaxis.axis_label = 'International Ranking' p.yaxis.axis_label = 'Pct. International Students' p.scatter('ranking', 'pct_intl_student', source=source) show(p) Where color is basically a list that has a color that corresponds to every datapoint in ranking and pct_intl_student. Basically, they're the same length. Would it be possible to make sure that every datapoint that I plot in the scatterplot has the color as specified in the colors list? I figured it would just be some attribute of the figure, but can't find it easiliy in the documentation. All data is retrieved from a dataframe and I created the color mapping as such: colormap = {2016: 'red', 2017: 'green', 2018: 'blue'} colors = [colormap[x] for x in df['year']]

http://stackoverflow.com/q/50721890
has comment: http://stackoverflow.com/comment/88461147
score: 4
favorite count: 0
has title: Google App Engine dev_appserver.py: watcher_ignore_re flag "is not JSON serializable"
tagged with: development-environment
has comment: http://stackoverflow.com/comment/88527275
tagged with: python
has answer: http://stackoverflow.com/a/54155850
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/88913376
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/54155850
possible better answer: http://stackoverflow.com/a/52238832
has comment: http://stackoverflow.com/comment/88655726
has answer: http://stackoverflow.com/a/52238832
type: Question
upvote count: 4
has body: Why I run the dev_appserver.py with the option watcher_ignore_re, I get an error message that the regex is not JSON serializable. Is this a bug with the development server? Am I using this command improperly? The command and callstack is printed below. C:\Users\mes65\Documents\MyProject&gt;"C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\dev_appserver.py" ^ --watcher_ignore_re="(.*\.git|.*\.idea|tmp\.py)" ^ "C:\Users\mes65\Documents\MyProject" WARNING 2018-06-06 09:28:59,161 appinfo.py:1622] lxml version "2.3" is deprecated, use one of: "3.7.3" INFO 2018-06-06 09:28:59,187 devappserver2.py:120] Skipping SDK update check. Traceback (most recent call last): File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\dev_appserver.py", line 96, in &lt;module&gt; _run_file(__file__, globals()) File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\dev_appserver.py", line 90, in _run_file execfile(_PATHS.script_file(script_name), globals_) File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 454, in &lt;module&gt; main() File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 442, in main dev_server.start(options) File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 163, in start bool(ssl_certificate_paths), options) File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\metrics.py", line 166, in Start self._cmd_args = json.dumps(vars(cmd_args)) if cmd_args else None File "C:\Python27\lib\json\__init__.py", line 244, in dumps return _default_encoder.encode(obj) File "C:\Python27\lib\json\encoder.py", line 207, in encode chunks = self.iterencode…
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/88521939
has text: Is the indentation you see on the site (especially lines 5-8) the same as you have in the editor?
type: Comment
comment on: http://stackoverflow.com/q/50757156
type: QuestionComment
score: 2

http://stackoverflow.com/comment/88413372
has text: I'm unsure if you can do Shell("C:\Python27\python.exe C:\Users\myName\Desktop\test.py" && Pause, 1)
comment on: http://stackoverflow.com/q/50701563
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50707680
score: 0
has body: You can use a dictionary comprehension: x = {'1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4}} full_sub_keys = {i for b in map(dict.keys, x.values()) for i in b} x['total'] = {i:sum(b.get(i, 0) for b in x.values()) for i in full_sub_keys} Output: {'1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4}, 'total': {'b': 7, 'a': 3}}
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50707632
has comment: http://stackoverflow.com/comment/88424508

http://stackoverflow.com/q/50812838
type: Question
accepted answer: http://stackoverflow.com/a/50812871
has answer: http://stackoverflow.com/a/79461662
has title: Error in pip install torchvision on Windows 10
downvote count: 0
possible better answer: http://stackoverflow.com/a/53544723
favorite count: 0
has answer: http://stackoverflow.com/a/53544723
upvote count: 8
has body: on pytorch, installing on Windows 10, conda and Cuda 9.0. cmd did not complain when i ran conda install pytorch cuda90 -c pytorch, then when I ran pip3 install torchvision I get this error message. Requirement already satisfied: torchvision in PATHTOFILE\python35\lib\site-packages (0.2.1) Requirement already satisfied: numpy in PATHTOFILE\python35\lib\site-packages (from torchvision) (1.12.0+mkl) Requirement already satisfied: six in PATHTOFILE\python35\lib\site-packages (from torchvision) (1.10.0) Collecting pillow&gt;=4.1.1 (from torchvision) Using cached https://files.pythonhosted.org/packages/ab/d2/d27a21bd3e64db1ca1dc7dc16026a16d77f5c3ffca9ec619eddeea7c47ce/Pillow-5.1.0-cp35-cp35m-win_amd64.whl Collecting torch (from torchvision) Using cached https://files.pythonhosted.org/packages/5f/e9/bac4204fe9cb1a002ec6140b47f51affda1655379fe302a1caef421f9846/torch-0.1.2.post1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\USERNAME~1\AppData\Local\Temp\pip-install-a70g611u\torch\setup.py", line 11, in &lt;module&gt; raise RuntimeError(README) RuntimeError: PyTorch does not currently provide packages for PyPI (see status at https://github.com/pytorch/pytorch/issues/566). Please follow the instructions at http://pytorch.org/ to install with miniconda instead. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\USERNAME~1\AppData\Local\Temp\pip-install-a70g611u\torch\ Anyone got this error?
has answer: http://stackoverflow.com/a/63555791
tagged with: python
has answer: http://stackoverflow.com/a/61668842
score: 8
has answer: http://stackoverflow.com/a/50812871
type: AnsweredQuestion
tagged with: python-3.x
tagged with: pytorch
answer count: 5

variables
tag name: variables
tags question: http://stackoverflow.com/q/50826831
tags question: http://stackoverflow.com/q/50752394
tags question: http://stackoverflow.com/q/50788102
tags question: http://stackoverflow.com/q/50813024
tags question: http://stackoverflow.com/q/50777830
tags question: http://stackoverflow.com/q/50784959
tags question: http://stackoverflow.com/q/50793734
type: Tag
tags question: http://stackoverflow.com/q/50756058
tags question: http://stackoverflow.com/q/50798909
tags question: http://stackoverflow.com/q/50770043
tags question: http://stackoverflow.com/q/50716690
tags question: http://stackoverflow.com/q/50725882
tags question: http://stackoverflow.com/q/50814814
tags question: http://stackoverflow.com/q/50768522
tags question: http://stackoverflow.com/q/50765634

http://stackoverflow.com/comment/118626021
type: Comment
has text: +1 I was having problems with a Pub/Sub app and adding google.cloud.storage to requirements.txt solved my problem.
comment on: http://stackoverflow.com/a/58063253
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88467614
comment on: http://stackoverflow.com/q/50729885
score: 0
type: Comment
type: QuestionComment
has text: Yes. I want a matrix dataframe.

http://stackoverflow.com/q/50828170
has comment: http://stackoverflow.com/comment/88661012
has comment: http://stackoverflow.com/comment/88660974
has comment: http://stackoverflow.com/comment/88661484
type: Question
score: 0
has title: Convert values of a dictionary to lowercase
answer count: 1
has answer: http://stackoverflow.com/a/50843450
has comment: http://stackoverflow.com/comment/88660998
tagged with: python
has comment: http://stackoverflow.com/comment/88660987
has comment: http://stackoverflow.com/comment/88660885
type: UnansweredQuestion
has body: I have a dictionary in python that has a dictionary within it and some values are placed in an array or list. I want to print the dictionary to be all lowercase without changing anything else but the only code I have only iterates through values of a plain dict, it doesn't deal with arrays or lists. Any suggestions for how to fix this? Here's the code I have so far: new_data = {} for i in range (0, len(json_file)): try: data = json_file[i]['payload'] for key, value in data.iteritems(): new_data[value.lower()] = value print (new_data) except: continue And this is the nested dictionary: { "payload": { "existence_full": 1, "geo_virtual": "[\"56.9459720|-2.1971226|20|within_50m|4\"]", "latitude": "56.945972", "locality": "Stonehaven", "_records_touched": "{\"crawl\":8,\"lssi\":0,\"polygon_centroid\":0,\"geocoder\":0,\"user_submission\":0,\"tdc\":0,\"gov\":0}", "address": "The Lodge, Dunottar", "email": "dunnottarcastle@btconnect.com", "existence_ml": 0.56942382176587, "domain_aggregate": "", "name": "Dunnottar Castle", "search_tags": [ "Dunnottar Castle Aberdeenshire", "Dunotter Castle" ], "admin_region": "Scotland", "existence": 1, "category_labels": [ [ "Landmarks", "Buildings and Structures" ] ], "post_town": "Stonehaven", "region": "Kincardineshire", "review_count": "719", "geocode_level": "within_50m", "tel": "01569 762173", "placerank": 65, "longitude": "-2.197123", "placerank_ml": 37.279160734645, "fax": "01330 860325", "category_ids_text_search": "", "website": "http:\/\/www.dunnottarcastle.co.uk", "status": "1", "geocode_confidence": "20", "postcode": "AB39 2TL", "category_ids": [ 108 ], "country": "gb", "_geocode_quality": "4" }, "uuid": "3867aaf3-12ab-434f-b12b-5d627b3359c3" }

http://stackoverflow.com/comment/88680760
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50838384
has text: Please post the whole error (which also contains the text that couldn't be converted, e.g.: `ValueError: could not convert string to float: '1,3'`).

http://stackoverflow.com/q/50746046
upvote count: 1
has answer: http://stackoverflow.com/a/50758128
has comment: http://stackoverflow.com/comment/88505876
has answer: http://stackoverflow.com/a/50766687
favorite count: 0
has comment: http://stackoverflow.com/comment/88500706
tagged with: windows
tagged with: python
tagged with: pyodbc
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88500264
linked to: http://stackoverflow.com/q/6044326
has comment: http://stackoverflow.com/comment/88499999
has comment: http://stackoverflow.com/comment/88499985
downvote count: 0
score: 1
has title: pyodbc fails to connect to database, but IBM data studio connects with same credentials
type: Question
possible better answer: http://stackoverflow.com/a/50748566
has answer: http://stackoverflow.com/a/50748566
has comment: http://stackoverflow.com/comment/88505813
has body: I'm trying to connect to a database on an IBM machine, and I can connect just fine via the IBM desktop client "IBM Data Studio." However, when I try to connect with pyodbc it fails to connect. I've received a series of errors but it seems the main response is along the lines of the following pyodbc.OperationalError: ('08001', u'[08001] [Microsoft][ODBC SQL Server Driver] [TCP/IP Sockets]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]ConnectionOpen ( Connect()). (10061); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)') My code follows: import pyodbc # Specifying the ODBC driver, server name, database, etc. directly cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=*****; PORT=50000;DATABASE=****;UID=***;PWD=***') # Create a cursor from the connection cursor = cnxn.cursor() cnxn.close() I am working on a Windows machine.
has comment: http://stackoverflow.com/comment/88503657
tagged with: db2
tagged with: odbc
accepted answer: http://stackoverflow.com/a/50766687
has comment: http://stackoverflow.com/comment/88501965
answer count: 3
has comment: http://stackoverflow.com/comment/88500583

http://stackoverflow.com/a/50699471
has comment: http://stackoverflow.com/comment/88408277
type: AcceptedAnswer
downvote count: 0
score: 8
upvote count: 8
type: Answer
has body: From the source: /* Comparison is pretty much a nightmare. When comparing float to float, * we do it as straightforwardly (and long-windedly) as conceivable, so * that, e.g., Python x == y delivers the same result as the platform * C x == y when x and/or y is a NaN. * When mixing float with an integer type, there's no good *uniform* approach. * Converting the double to an integer obviously doesn't work, since we * may lose info from fractional bits. Converting the integer to a double * also has two failure modes: (1) a long int may trigger overflow (too * large to fit in the dynamic range of a C double); (2) even a C long may have * more bits than fit in a C double (e.g., on a 64-bit box long may have * 63 bits of precision, but a C double probably has only 53), and then * we can falsely claim equality when low-order integer bits are lost by * coercion to double. So this part is painful too. */ As such, the potential pitfalls of conversion are taken into account.
has comment: http://stackoverflow.com/comment/88409471
has comment: http://stackoverflow.com/comment/88408388
answers question: http://stackoverflow.com/q/50699194
has comment: http://stackoverflow.com/comment/88452477
has comment: http://stackoverflow.com/comment/88410561
accepted answer of: http://stackoverflow.com/q/50699194

http://stackoverflow.com/a/50824375
accepted answer of: http://stackoverflow.com/q/50804025
answers question: http://stackoverflow.com/q/50804025
type: AcceptedAnswer
downvote count: 0
has body: Since you converted your DataFrame object to a numpy array, you have to choose one data type for the whole array. If you want each column to have a different data type, you need to keep it as a DataFrame. import pandas as pd from sklearn.preprocessing import LabelEncoder,MinMaxScaler import numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(100, 5)), columns=list('ABCDE')) BinEncoder = LabelEncoder() scalar = MinMaxScaler() X = df.loc[:500,'A':'D'] X['D'] = BinEncoder.fit_transform(X['D']) X.loc[:,'A':'C'] = scalar.fit_transform(X.loc[:,'A':'C']) print(X.dtypes) Hope that helps.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/50724763
tagged with: python
tagged with: dictionary
answer count: 4
linked to: http://stackoverflow.com/q/50722056
has answer: http://stackoverflow.com/a/50725032
has answer: http://stackoverflow.com/a/50725197
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50725532
accepted answer: http://stackoverflow.com/a/50725532
type: Question
has answer: http://stackoverflow.com/a/50724899
score: 3
linked to: http://stackoverflow.com/q/46933995
linked to: http://stackoverflow.com/q/17805304
has body: I want to obtain distribution of tags from this dataframe: df=pd.DataFrame([ [43,{"tags":["webcom","start","temp","webcomfoto","dance"],"image":["https://image.com/Kqk.jpg"]}], [83,{"tags":["yourself","start",""],"image":["https://images.com/test.jpg"]}], [76,{"tags":["en","webcom"],"links":["http://webcom.webcomdb.com","http://webcom.webcomstats.com"],"users":["otole"]}], [77,{"tags":["webcomznakomstvo","webcomzhiznx","webcomistoriya","webcomosebe","webcomfotografiya"],"image":["https://images.com/nt4wzguoh/y_a3d735b4.jpg","https://images.com/sucb0u24x/b1sd_Naju.jpg"]}], [81,{"tags":["webcomfotografiya"],"users":["myself","boattva"],"links":["https://webcom.com/nk"]}], ],columns=["_id","tags"]) I need to get a table with number of 'id's with specific number of tags. eg. Number of posts | Number of tags 31 9 44 8 ... 129 1 I used this approach for the case when 'tags' is the only field. In this dataframe I also have 'image', 'users' and other text fields with values. How should I handle data in this case? Thank you
linked to: http://stackoverflow.com/q/38609971
tagged with: dataframe
tagged with: counting
has title: How to extract data from text field in pandas dataframe?
upvote count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50724899

http://stackoverflow.com/a/50812735
upvote count: 2
has comment: http://stackoverflow.com/comment/88631395
has comment: http://stackoverflow.com/comment/88632520
answers question: http://stackoverflow.com/q/50812361
has comment: http://stackoverflow.com/comment/88631497
score: 2
has comment: http://stackoverflow.com/comment/88631207
downvote count: 0
has comment: http://stackoverflow.com/comment/88631242
type: Answer
has body: cut + get_dummies Here's one way: import numpy as np import pandas as pd a = np.array([0., 14., 29., 43., 58., 72., 86., 101., 115., 130., 144.]) b = np.array([10, 26, 36, 48, 64, 71, 91, 105, 123, 133, 141]) df = pd.DataFrame({'Values': b}) df['Range'] = pd.cut(df['Values'], a) dummies = pd.get_dummies(df['Range']) res = pd.concat([df, dummies], axis=1) print(res) Explanation pandas.cut uses default labels relating to ranges, if none are supplied. pandas.get_dummies expands a series into "one-hot encoding" format. pandas.concat allows you to join the original dataframe to the output from get_dummies. Optionally, you can set your Values as index via res = res.set_index('Values'). Result print(res) Values Range (0, 14] (14, 29] (29, 43] (43, 58] (58, 72] \ 0 10 (0, 14] 1 0 0 0 0 1 26 (14, 29] 0 1 0 0 0 2 36 (29, 43] 0 0 1 0 0 3 48 (43, 58] 0 0 0 1 0 4 64 (58, 72] 0 0 0 0 1 5 71 (58, 72] 0 0 0 0 1 6 91 (86, 101] 0 0 0 0 0 7 105 (101, 115] 0 0 0 0 0 8 123 (115, 130] 0 0 0 0 0 9 133 (130, 144] 0 0 0 0 0 10 141 (130, 144] 0 0 0 0 0 (72, 86] (86, 101] (101, 115] (115, 130] (130, 144] 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 4 0 0 0 0 0 5 0 0 0 0 0 6 0 1 0 0 0 7 0 0 1 0 0 8 0 0 0 1 0 9 0 0 0 0 1 10 0 0 0 0 1

http://stackoverflow.com/q/50755291
has body: In PostgreSQL database timestamp datatype column has value as: 2018-06-08 12:35:09 But when retrieving data using django, data is returned as (datetime is combining microseconds): "2018-06-08T12:35:09.225" How can I convert this datetime object to "DD-MM-YYYY HH:MM:SS" format in django? Note - I am using CookieCutter Code I am using to retrieve data from Model Bid is as below (views.py): request_data = json.loads(request.body) bidId = request_data['id'] bidData = Bid.objects.get(bid_id=bidId) data = serializers.serialize('json', [bidData, ]) serialized = json.loads(data) bid_obj = json.loads(serialized[0]['fields']['bid_obj']) serialized[0]['fields']['bid_obj'] = bid_obj outputArray = { "bid": serialized[0]['fields'] } return JsonResponse(outputArray, safe=False)
answer count: 1
has comment: http://stackoverflow.com/comment/88518620
has comment: http://stackoverflow.com/comment/88518582
has comment: http://stackoverflow.com/comment/88518504
tagged with: postgresql
score: 0
has comment: http://stackoverflow.com/comment/88519531
tagged with: python
tagged with: cookiecutter-django
has comment: http://stackoverflow.com/comment/88518667
favorite count: 0
has comment: http://stackoverflow.com/comment/88519146
tagged with: django
downvote count: 1
has title: Python : How to remove microseconds from django timestamp?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88518404
has comment: http://stackoverflow.com/comment/88518744
type: Question
has comment: http://stackoverflow.com/comment/88518467
has answer: http://stackoverflow.com/a/50756402
accepted answer: http://stackoverflow.com/a/50756402
upvote count: 1

http://stackoverflow.com/q/50776139
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/88559231
has body: I am using Flask and Flask SQLAlchemy and Flask Test. I define an example model with a string column with max length of 100. I thought I should get an exception if I try to insert a string with a length bigger than 100. SQLAlchemy even allows me to insert other data types like an int. Even if I have defined this column to be of type string. Or if I try to insert an empty string I also do not raise an Exception. Although I have set the column not to be nullable. Why does SQLAlchemy just accepts everything. Shouldn't there be at least one exception raised? from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_testing import TestCase db = SQLAlchemy() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" db.init_app(app) return app class Example(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) class MyTest(TestCase): def create_app(self): return create_app(self) def setUp(self): db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_example_that_should_work(self): example = Example(name="ABC") db.session.add(example) db.session.commit() self.assertEqual(Example.query.count(), 1) def test_example__do_not_insert_strings_of_bigger_size(self): example = Example(name="ABC"*100) db.session.add(example) db.session.commit() self.assertEqual(Example.query.count(), 0) # AssertionError: 1 != 0 def test_example_do_not_insert_different_data_type(self): example = Example(name=42) db.session.add(example) db.session.commit() self.assertEqual(Example.query.count(), 0) # AssertionError: 1 != 0 def test_example_do_not_insert_nullable(self): example = Example(name="") db.session.add(example) db.session.commit() self.assertEqual(Example.query.count(), 0) # AssertionError: 1 != 0
score: 0
tagged with: python
has title: SQLAlchemy accepts everything like different data types, empty strings, strings with bigger length
has comment: http://stackoverflow.com/comment/88559338
has comment: http://stackoverflow.com/comment/88559261
tagged with: flask-testing
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88559627
type: Question
has comment: http://stackoverflow.com/comment/88559565
linked to: http://stackoverflow.com/q/8980735
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/130264822

http://stackoverflow.com/a/57574587
has comment: http://stackoverflow.com/comment/101609331
has body: Interesting, "bug" I think you found here in pandas.SeriesGroupBy object with sorted dataframes. I think instead we a can use pandas.DataFrameGroupBy object (however, I do believe you have a bug there). import pandas as pd df = pd.DataFrame({'a': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar', 'qux', 'qux', 'qux'], 'b': ['baz', 'baz', 'baz', 'bat', 'baz', 'baz', 'bat', 'bat', 'bat', 'baz', 'bat', 'bat'], 'c': [1, 3, 2, 5, 6, 4, 9, 12, 7, 10, 8, 11]}) df2 = df.sort_values('c', ascending=True) df_sorted = df2.groupby(['a','b']).apply(lambda x: x.nsmallest(n=3, columns='c')).reset_index(drop=True) df_unsorted = df.groupby(['a','b']).apply(lambda x: x.nsmallest(n=3, columns='c')).reset_index(drop=True) all(df_sorted.eqw(df_unsorted) Output: True Print df_sorted and df_unsorted: print(df_sorted) a b c 0 bar bat 7 1 bar bat 9 2 bar bat 12 3 bar baz 4 4 bar baz 6 5 foo bat 5 6 foo baz 1 7 foo baz 2 8 foo baz 3 9 qux bat 8 10 qux bat 11 11 qux baz 10 print(df_unsorted) a b c 0 bar bat 7 1 bar bat 9 2 bar bat 12 3 bar baz 4 4 bar baz 6 5 foo bat 5 6 foo baz 1 7 foo baz 2 8 foo baz 3 9 qux bat 8 10 qux bat 11 11 qux baz 10
downvote count: 0
answers question: http://stackoverflow.com/q/50770370
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/50895188
answers question: http://stackoverflow.com/q/50786002
has body: The scripts must be adapted to work with AWS Step functions, as describe in FAQ: Q: How does AWS Step Functions work with Amazon EC2 and other compute resources? All work in your state machine is done by tasks. A task may be an Activity, which can consist of any code in any language. Activities can be hosted on Amazon EC2, Amazon ECS, mobile devices—basically any computer that can communicate with the AWS Step Functions API. Activities long-poll Step Functions using API calls to request work, receive input data, do the work, and return a result. An example in Ruby is on this page: Example Activity Worker in Ruby: For Python you can try to use boto3
type: Answer
has comment: http://stackoverflow.com/comment/109216862
has comment: http://stackoverflow.com/comment/88882232
has comment: http://stackoverflow.com/comment/88880488
has comment: http://stackoverflow.com/comment/88923591
score: 0

http://stackoverflow.com/a/50851979
downvote count: 0
has comment: http://stackoverflow.com/comment/88707841
accepted answer of: http://stackoverflow.com/q/50851516
has comment: http://stackoverflow.com/comment/88707644
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50851516
has comment: http://stackoverflow.com/comment/88708848
has body: I've had a lot of problems enabling pylint, and after spending 2 days changing all possible settings I switched linter to flake8. Everything just works from the first try, and it's great. Try enabling flake8 first, then if it doesn't work, you'll have to change your settings and if it does just use it. If your code can't find your module try this: Create a file named .env in your project root directory Add the following contents to the .env file: PYTHONPATH=path to your module folder
type: AcceptedAnswer

http://stackoverflow.com/comment/88432745
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50711890
score: 0
has text: browser object which is WebDriver has `find_element` method and also By.xpath should be written as `browser.find_element(By.XPATH, '//a[text() = "Log in"]')` Read about the selenium api's

http://stackoverflow.com/a/50774173
answers question: http://stackoverflow.com/q/50774143
has comment: http://stackoverflow.com/comment/88555735
score: 0
has comment: http://stackoverflow.com/comment/88555479
has comment: http://stackoverflow.com/comment/88555763
has body: Try this job.sh #!/bin/bash python file.py $* file.py import sys import os from myClass import myClass label, list = sys.argv[1], sys.argv[2:] myObject = myClass(label, list)
has comment: http://stackoverflow.com/comment/88555778
has comment: http://stackoverflow.com/comment/88555447
has comment: http://stackoverflow.com/comment/88555408
type: Answer

http://stackoverflow.com/comment/88559260
has text: One option: start with an empty Numpy array of the designated size, and assign the values to indexed slices of it. For larger arrays this will be much much faster. Besides that this looks good :)
comment on: http://stackoverflow.com/a/50775271
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50805778
has comment: http://stackoverflow.com/comment/88618032
possible better answer: http://stackoverflow.com/a/50876063
tagged with: iteration
has answer: http://stackoverflow.com/a/50876063
score: 0
has answer: http://stackoverflow.com/a/50818103
tagged with: sqlite
has comment: http://stackoverflow.com/comment/88618028
has body: I have two tables in sqlite3 database with coordinates for different objects. Structured like id-longtitude-latitude. Let's name them object1_coor and object2_coor. I just need to find distance between every object in object1_coor table and object2_coor table. How can I do this in Python 3? As of now I've read a lot, but didn't find a solution for such iteration. I'll use for distance algorithm below: obj1_lat = radians(float(obj1_lat))) obj1_lon = radians(float(obj1_lon))) obj2_lat = radians(float(obj2_lat))) obj2_lon = radians(float(obj2_lon))) dist = 6371.01 * acos(sin(obj1_lat)*sin(obj2_lat) + cos(obj1_lat)*cos(obj2_lat)*cos(obj1_lon - obj2_lon)) print("The distance is " % dist)
tagged with: python
tagged with: python-3.x
has title: Iterate variables from two tables sqlite python
has comment: http://stackoverflow.com/comment/88617770
accepted answer: http://stackoverflow.com/a/50818103
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88617828
has comment: http://stackoverflow.com/comment/88617681
has comment: http://stackoverflow.com/comment/88618009
type: Question
has comment: http://stackoverflow.com/comment/88617805
answer count: 2

http://stackoverflow.com/q/50814296
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50814867
tagged with: python
has answer: http://stackoverflow.com/a/50814867
tagged with: nlp
tagged with: performance
upvote count: 3
has body: I have the following two sentences: I want to go home. I would like to leave. My goal is to quantify similarity between the two sentences using a kernel suggested in this paper. I extract all the dependency triplets for each sentence. These are 3 item tuples containing all the relations between words in the sentence and look like (tail, relationship, head). To calculate similarity, I need to loop through every possible combination of triplet across sentences and add a particular number to the similarity score based on how many nodes match and whether the relationship matches. I attempted using list comprehensions inside a for loop since I figured it would be more efficient than another nested for loop but am getting a syntax error. Here's my code: sim = 0 theta = 2.5 for d1 in deps1: [sim += theta for d2 in deps2 if ((d1[0]==d2[0] or d1[2]==d2[2]) and d1[1]==d2[1])] [sim += 1 for d2 in deps2 if ((d1[0]==d2[0] or d1[2]==d2[2]) and d1[1]!=d2[1])] For reference, here's what deps1 and deps2 look like when printed: [('I', 'nsubj', 'want'), ('want', 'ROOT', 'want'), ('to', 'aux', 'go'), ('go', 'xcomp', 'want'), ('home', 'advmod', 'go')] [('I', 'nsubj', 'like'), ('would', 'aux', 'like'), ('like', 'ROOT', 'like'), ('to', 'aux', 'leave'), ('leave', 'xcomp', 'like')] Questions: What's the correct syntax to do this with a list comprehension? Is there a more efficient way, maybe using numpy(?), to do this computation?
downvote count: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/50816168
has title: Syntax error when using list comprehensions in Python 3.6 to loop over and compare dependency triplets for two sentences
tagged with: list-comprehension
linked to: http://stackoverflow.com/q/4728073
accepted answer: http://stackoverflow.com/a/50816168
score: 2
linked to: http://stackoverflow.com/q/47789
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/a/50772731
type: Answer
accepted answer of: http://stackoverflow.com/q/50700763
answers question: http://stackoverflow.com/q/50700763
downvote count: 0
score: 1
has body: For the data that you have here, hexbin makes more sense that heatmap. This solution uses ImageGrid to handle most of the requirements quite naturally. Note that I'm passing specific values for max and min so that the colorbar works correctly. from mpl_toolkits.axes_grid1 import ImageGrid fig = plt.figure() grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.3, cbar_mode='single') for ax, col in zip(grid, ['z1', 'z2', 'z3', 'z4']): hb = ax.hexbin(df.x, df.y, C=df[col], cmap='RdBu_r', vmin=0, vmax=1) ax.set_title(col) ax.set_xlabel('x') ax.set_ylabel('y') grid.cbar_axes[0].colorbar(hb)
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/88509785
comment on: http://stackoverflow.com/q/50749555
type: QuestionComment
has text: Rewritten to be Minimal, Complete, and Verifiable. The problem is on the @messaging decorator line. I can't get it to work when the decorator is within the class.
type: Comment
score: 0

http://stackoverflow.com/q/50795367
tagged with: jinja2
has body: I am rather new to jinja, so please excuse this potentially dumb question ... I have a jinja macro sitting in a file named lib.jinja which looks as as follows {% macro some_macro(some_content) %} {{ some_content }} {%- endmacro %} I import it from another file named content.htm, which looks roughly as follows: {% from "lib.jinja" import some_macro %} {% block content %} Some content {% endblock %} {{ some_macro(self.some_macro(self.content())) }} The rendered output looks as follows: Some content Some content Notice that the content appears twice, once rendered through/by the macro, another time - directly above - rendered like it was defined in the block named content in content.htm. I would love to avoid that the block is rendered twice - it is supposed to be fed into the macro and rendered through it only. I appears that I can "work around" it by turning content.htm into a child template (by adding an extends tag at its top) of an empty base template. Maybe I have a lack of understanding for the concepts here: A block is not a variable - I get that. If there is no extends tag, the template is treated as a base template, I assume. If there are no child templates or other directives, I guess the block is just rendered as-is and then, for a second time so to speak, picked up by the macro - correct? How can I solve this in a sane manner, i.e. how could I handle this other than by extending an empty base template? Is there another type of block or variable that would fit my needs?
type: Question
has title: How to avoid rendering a block in a base template - or: how to define a multiline block-like variable?
score: 0
accepted answer: http://stackoverflow.com/a/50795522
answer count: 1
tagged with: templating-engine
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50795522

http://stackoverflow.com/comment/88727221
score: 0
type: Comment
has text: You're right, it did work, thank you and sorry that I can't translate better, I have lots of stuff to do in college with little time. By the way I'm gonna let the algorithm there in that link if you want to play around, I'm gonna translate it soon.
type: AnswerComment
comment on: http://stackoverflow.com/a/50849739

http://stackoverflow.com/comment/88542173
has text: Hi Novel, code is updated. Thank you for your persistent help.
type: Comment
comment on: http://stackoverflow.com/a/50765334
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88607545
comment on: http://stackoverflow.com/q/50800056
type: Comment
has text: I don't know about pytorch, but numpy arrays are contiguous in memory. That sounds incompatible with "in-place concatenation". Ref: https://docs.scipy.org/doc/numpy/reference/internals.html
score: 0
type: QuestionComment

http://stackoverflow.com/q/50761807
answer count: 1
accepted answer: http://stackoverflow.com/a/50762598
type: Question
tagged with: python
tagged with: geometry
has title: Plotting points on a circle, where each point is further from the origin based on how often it is present. Weird behavior
score: 0
has body: I have a large amount of hue values expressed in degrees (0 to 360) that I wish to plot on a circle. Here is some 'test' data. My real data is similar to this. # create values with a normal distributions. mu = 0.5 sigma = 0.02 values = np.random.normal(mu,sigma,10000) values = values*360 Now I create a simple circle. # create a circle circle = np.linspace(0,2*np.pi,1000) x = np.sin(circle) y = np.cos(circle) plt.plot(x,y,color='black') plt.axis('equal') plt.show() Next, I wish to plot my data onto this circle. # plot values on circle x = [] y = [] for i in values: x.append(round(math.cos(math.radians(i)),2)) y.append(round(math.sin(math.radians(i)),2)) plt.scatter(x,y,color='red') plt.show() Hmmm. Okay, so the values are plotted onto the circle. But now it looks as if the points are more-or-less equally likely within the spread. I would like to show the data in such a way, that you can see the distribution of the data too. Something like a normal bell curve. That is, I would like something like this (don't mind the bad paint skills) In this image, the further away from the black circle, the more often we find these data points. Basically, a circular normal bell curve. I tried to multiply each data-point by a value that increases as the likelihood for that value increases. I.e, the more likely the data-point, the further away it is from the black circle. (Just as a bell curve, but than on a circle) but it is giving me these weird results. uniqueX = set(x) uniqueY = set(y) countx = max([x.count(i) for i in set(x)]) county = min([y.count(i) for i in set(y)]) ofset = [((1/countx*x.count(i))+1) for i in x] x = [x*ofset[ii] for ii,x in enumerate(x)] y = [x*ofset[ii] for ii,x in enumerate(y)] plt.scatter(x,y,color='red') plt.show() This output is not what I had inentend. I'm not sure where I am going wrong (my geometry and math has never been my strong suit). How can I make my desired plot? My data looks like this:
tagged with: normal-distribution
has answer: http://stackoverflow.com/a/50762598
tagged with: matplotlib
type: AnsweredQuestion

http://stackoverflow.com/q/50770092
tagged with: python
answer count: 0
has title: How to call a function from inside a class?
tagged with: methods
type: Question
tagged with: class
score: 0
tagged with: function
has comment: http://stackoverflow.com/comment/88547856
has body: I am new to Python but I have figured out a few cool things already. I have recently written a couple of classes to draw buttons / text boxes for an application to print labels at work. I need to cycle through some records on my sql server - the connectivity works OK so I won't post all of that code. I have a function getNextPart()that calls the next item from a table on my sql server- the intention is when I click my "+" spinner button, it runs getnextpart() and assigns that to a global parameter. The same would happen for getprevpart() when I click the "-" button. When I click the "+" button the handler event does everything as expected, but doesn't run the getnextpart() function at all. It doesn't run the print statement or anything, so I am suspecting that it isn't the database connector that is broken. There are also no errors being reported. I tried including getnextpart as a method and referring to it as self.getnextpart() but that didn't work for me either. I have searched for a couple of days but can't find anything, so I'm asking for some guidance here please. How (or even can I) call a function from within the handle_event() method of the SpinnerButton class? This is my program, excluding the mysql connector and other parameters initialised at the start. # Initialise global variables for display on the screen partnumber = '' def getnextpart(): global partnumber print(str('Get Next Part should run here !!')) dbcurs=cnx.cursor() cnx.commit() query = 'spGetNextItem' args=[partnumber] result_args = dbcurs.callproc(query ,args) for result in dbcurs.stored_results(): itemresult = result.fetchone() itemcode = str(itemresult[0]) partnumber = itemcode print(partnumber) def getprevpart(): global partnumber dbcurs=cnx.cursor() cnx.commit() query = 'spGetPrevItem' args=[partnumber] result_args = dbcurs.callproc(query ,args) for result in dbcurs.stored_results(): itemresult = result.fetchone() itemcode = str(itemresult[0]) partnumber = itemcode print(partnumber) class…
has comment: http://stackoverflow.com/comment/88547939
has comment: http://stackoverflow.com/comment/88547878
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88547949

http://stackoverflow.com/q/50814621
has title: Python GraphQL variable not defined
has answer: http://stackoverflow.com/a/50829621
downvote count: 0
has answer: http://stackoverflow.com/a/76841228
favorite count: 0
type: UnansweredQuestion
tagged with: graphql
tagged with: python
upvote count: 3
linked to: http://stackoverflow.com/q/72999653
has body: I'm trying to do a GraphQL request that contains some variables using the apollo-boost client on a Flask + Flask-GraphQL + Graphene server. let data = await client.query({ query: gql`{ addItemToReceipt(receiptId: $receiptId, categoryId: $categoryId, value: $value, count: $count) { item { id category { id } value count } } }`, variables: { receiptId: this.id, categoryId: categoryId, value: value, count: mult } }) But I get "Variable X is not defined" errors. [GraphQL error]: Message: Variable "$receiptId" is not defined., Location: [object Object],[object Object], Path: undefined [GraphQL error]: Message: Variable "$categoryId" is not defined., Location: [object Object],[object Object], Path: undefined [GraphQL error]: Message: Variable "$value" is not defined., Location: [object Object],[object Object], Path: undefined [GraphQL error]: Message: Variable "$count" is not defined., Location: [object Object],[object Object], Path: undefined [Network error]: Error: Response not successful: Received status code 400 I've added some debug prints to the graphql_server/__init__.py # graphql_server/__init__.py:62 all_params = [get_graphql_params(entry, extra_data) for entry in data] print(len(all_params)) print(all_params[0]) # ... But from the output I get, everything seems to be OK. The graphql_server.run_http_query() does receive all the variables. GraphQLParams(query='{\n addItemToReceipt(receiptId: $receiptId, categoryId: $categoryId, value: $value, count: $count) {\n item {\n id\n category {\n id\n __typename\n }\n value\n count\n __typename\n }\n __typename\n }\n}\n', variables={'receiptId': '13', 'categoryId': 'gt', 'value': 0, 'count': 0}, operation_name=None) What am I doing wrong?
tagged with: graphene-python
type: Question
score: 3
tagged with: apollo-client
answer count: 2

http://stackoverflow.com/comment/89214693
comment on: http://stackoverflow.com/a/50824248
has text: Logan, do you know if it's possible to set up the key/token using a service account and avoid expiring tokens?
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/51005951
has body: You can use python code to locate various things in core files. The structer package includes an elf module whose Elf class provides methods for that. The following output from a gdb session has examples of how to use that code. The first excerpt of that session shows gdb opening a core file which was generated by gcore, and providing some data for the subsequent searches. 18:33:00 $ gdb -q /home/efuller/gnu/bin/gdb core.17856 Reading symbols from /home/efuller/gnu/bin/gdb...done. [New LWP 17856] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Core was generated by `/home/efuller/gnu/bin/gdb /home/efuller/gnu/bin/gdb'. Program terminated with signal SIGINT, Interrupt. #0 0x00007ffff62c5660 in __poll_nocancel () at ../sysdeps/unix/syscall-template.S:84 84 ../sysdeps/unix/syscall-template.S: No such file or directory. (gdb) backtrace #0 0x00007ffff62c5660 in __poll_nocancel () at ../sysdeps/unix/syscall-template.S:84 #1 0x00005555557f7ea6 in gdb_wait_for_event (block=1) at event-loop.c:772 #2 0x00005555557f7185 in gdb_do_one_event () at event-loop.c:347 #3 0x00005555557f71bd in start_event_loop () at event-loop.c:371 #4 0x00005555557f003a in captured_command_loop (data=0x0) at main.c:324 #5 0x00005555557eb2e9 in catch_errors (func=0x5555557efff8 &lt;captured_command_loop(void*)&gt;, func_args=0x0, errstring=0x555555b4f733 "", mask=RETURN_MASK_ALL) at exceptions.c:236 #6 0x00005555557f16e2 in captured_main (data=0x7fffffffea10) at main.c:1149 #7 0x00005555557f170b in gdb_main (args=0x7fffffffea10) at main.c:1159 #8 0x00005555555f2daa in main (argc=2, argv=0x7fffffffeb18) at gdb.c:32 (gdb) frame 6 #6 0x00005555557f16e2 in captured_main (data=0x7fffffffea10) at main.c:1149 1149 catch_errors (captured_command_loop, 0, "", RETURN_MASK_ALL); (gdb) info locals context = 0x7fffffffea10 argc = 2 argv = 0x7fffffffeb18 quiet = 0 set_args = 0 inhibit_home_gdbinit = 0 symarg = 0x7fffffffed8e "/home/efuller/gn…
accepted answer of: http://stackoverflow.com/q/50845037
downvote count: 0
answers question: http://stackoverflow.com/q/50845037
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/50846145
answers question: http://stackoverflow.com/q/50844589
type: Answer
has body: Try use only appointments = Appointment.objects.filter(start_date__day=tomorrow.day) If that does not work, perhaps you problem in different time zone: tomorrow val +00:00 and in model -04:00.
score: 0

http://stackoverflow.com/comment/88548327
score: 0
comment on: http://stackoverflow.com/q/50770218
type: QuestionComment
has text: I want in an "input" folder with lots of txt files and replace "%" with "" and that replacement file creates a new txt file in the "output" folder. @RishikeshAgrawani
type: Comment

http://stackoverflow.com/comment/88705726
score: 0
has text: clever. thanks for the solution. I am looking for a generic solution because we do this type of data processing all the time. sometimes it may not be mathematically aligned as 1, 2, 3, 4.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50851336

http://stackoverflow.com/a/51140223
has body: 1st solution: Override the template (Django Documentation can help you with that) Onchange of the field, you need to make an ajax call to an API which takes in session_id and returns you all the categories. Fill the returned result into categories through JS. Also, you can give a try to django-ajax-selects 2nd solution: (without JS/AJAX) To register an article, You can first go to session admin and then have a link there to add an article. a. If you want to do it changeform_view then, You can use inline admin and override its form init() to prepopulate the categories. b. If you want the link in changelist_view, http://localhost:8000/admin/&lt;app&gt;/article/add/?session_id=&lt;&gt; You can override the Article Admin form init() and read the session_id passed and use it accordingly.
type: Answer
answers question: http://stackoverflow.com/q/50799470
score: 0

http://stackoverflow.com/a/50823517
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50823473
has body: they are completely different concepts. context managers are objects to be used with the python with keyword. It runs code when entering the block and exiting the block. decorators are modifications to a function or class definition. It runs code that replaces the function as it is being defined. @D def Y(...): ... is just another way of writing def Y(...): .... Y = D(Y)

http://stackoverflow.com/q/50715822
has comment: http://stackoverflow.com/comment/88484115
type: Question
has comment: http://stackoverflow.com/comment/88442484
has title: I am getting the following errors while trying to install PyQt and Scrapy in MS Windows through CMD
score: 0
has body: PyQt installation error Could not find a version that satisfies the requirement PyQt (from versions: ) No matching distribution found for PyQt Scrapy installation error Command "c:\users\tanuj.chhabra\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;file='C:\Users\TANUJ~1.CHH\AppData\Local\Temp\pip-install-di2wv0lk\Twisted\setup.py';f=getattr(tokenize, 'open', open(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\TANUJ~1.CHH\AppData\Local\Te mp\pip-record-vkbbg2ax\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\TANUJ~1.CHH\AppData\Local\Temp\pip -install-di2wv0lk\Twisted\
tagged with: pyqt
tagged with: windows
has comment: http://stackoverflow.com/comment/88483711
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88524856
tagged with: scrapy

http://stackoverflow.com/a/50822311
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50822099
downvote count: 0
type: Answer
has body: You could try using os.listdir(path) to get all the files and dirs from the given path. Once you have all the files and directories you could use filter and a lambda function to create a new list of only the files with the desired timestamp. You could then iterate through that list to do what work you need to on the correct files.

multi-index
tags question: http://stackoverflow.com/q/50765997
tags question: http://stackoverflow.com/q/50785715
tags question: http://stackoverflow.com/q/50709365
type: Tag
tags question: http://stackoverflow.com/q/50833119
tag name: multi-index
tags question: http://stackoverflow.com/q/50819579
tags question: http://stackoverflow.com/q/50829995
tags question: http://stackoverflow.com/q/50798855

http://stackoverflow.com/a/50728686
has body: eval already does what you want: &gt;&gt;&gt; eval("3*x**2 + 4*y", None, dict(x=0, y=-10000000)) -40000000 If your project does truly demand wrapping eval in a lambda: &gt;&gt;&gt; fn = lambda expr, **kwargs : eval(expr, None, kwargs) &gt;&gt;&gt; fn("3*x+4*y",x=1,y=2) 11 If you are using sympy, lambdify is a more robust alternative that comes with multiple backends: &gt;&gt;&gt; import sympy as sp &gt;&gt;&gt; x, y = sp.symbols('x y') &gt;&gt;&gt; f = sp.lambdify((x, y), 3*x+4*y, modules='numpy') &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; f(np.random.randn(10), np.random.randn(10)) array([ 3.86723102, 0.85028042, -1.74461009, -4.02824375, -0.59191871, -0.52022366, 5.43335779, -2.09120517, -7.16387162, -0.22421031])
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50708170
answers question: http://stackoverflow.com/q/50708170

http://stackoverflow.com/comment/88740534
has text: Anyway, what should I do then?
score: 0
comment on: http://stackoverflow.com/a/50845016
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50795928
tagged with: pandas
type: AnsweredQuestion
has title: Convert json to dataframe in python
tagged with: python
has answer: http://stackoverflow.com/a/50796272
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 3
upvote count: 1
has body: I have a json file (sample below). I am trying to create a Dataframe from this using python: JSON: {"data": { "A": [{ "CREATION_DATE": "1482105600", "SOURCE_COUNT": "0" }, { "CREATION_DATE": "1482105600", "SOURCE_COUNT": "0" } ], "B": [{ "CREATION_DATE": "1487808000", "SOURCE_COUNT": "1048" }, { "CREATION_DATE": "1487894400", "SOURCE_COUNT": "1103" } ] } } When I am trying to convert it into a dataframe: My Code: import json file = 'mysample.json' with open(file) as train_file: dict_train = json.load(train_file) # converting json dataset from dictionary to dataframe train = pd.DataFrame.from_dict(dict_train, orient='index') train.reset_index(level=0, inplace=True) Output: index A B 0 data [{'CREATION_DATE': '1482105600', 'SOURCE_COUNT... [{'CREATION_DATE': '1487808000', 'SOURCE_COUNT... Instead I am looking to convert this into a dataframe which looks like below: system CREATION_DATE SOURCE_COUNT A 1482105600 0 A 1482105600 0 B 1487808000 1048 B 1487894400 1103 How to modify my code to get to the expected output?
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
has answer: http://stackoverflow.com/a/50796142
downvote count: 0
has answer: http://stackoverflow.com/a/50796129
score: 1
possible better answer: http://stackoverflow.com/a/50796142
accepted answer: http://stackoverflow.com/a/50796129

http://stackoverflow.com/comment/88496915
has text: I mean it should always be first_organizer after the second loop, no matter if 3, 5 or 9 iterations.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50744488
score: 0

http://stackoverflow.com/comment/88670874
type: Comment
type: QuestionComment
score: 1
has text: it means *return `False` if `i` is bigger than `100` or else return `255`*
comment on: http://stackoverflow.com/q/50833486

http://stackoverflow.com/comment/88458289
comment on: http://stackoverflow.com/a/50722847
has text: Hey csevier i just posted my code, can you please check it once.
score: 0
type: AnswerComment
type: Comment

decorator
tags question: http://stackoverflow.com/q/50791020
tags question: http://stackoverflow.com/q/50791782
tags question: http://stackoverflow.com/q/50765072
tag name: decorator
tags question: http://stackoverflow.com/q/50711796
tags question: http://stackoverflow.com/q/50813567
tags question: http://stackoverflow.com/q/50815820
type: Tag

http://stackoverflow.com/comment/88644372
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50816718
score: 0
has text: @eryksun, changed it to pass byref(LARGE_INTEGER(-50 * 10 * 1000)), get the same error. But I hope it's another small step to fixing it.)

http://stackoverflow.com/comment/88574790
type: QuestionComment
has text: yeah, I know this way to add sleep, but what will happen if app will be launching for 12 seconds ? I am looking for universal solution.
score: 0
comment on: http://stackoverflow.com/q/50784147
type: Comment

http://stackoverflow.com/a/58411594
has body: I had this issue because I was adding 2 tensors as x1+x2 somewhere in my model instead of using Add()([x1,x2]). That solved the problem.
score: 5
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/50715928
has comment: http://stackoverflow.com/comment/103499586
type: Answer

http://stackoverflow.com/a/50818941
type: Answer
accepted answer of: http://stackoverflow.com/q/50817371
score: 2
answers question: http://stackoverflow.com/q/50817371
has comment: http://stackoverflow.com/comment/88706568
has body: If I understand well, you wanna be able to give Models keys as well as their index in the dicts modelX_indices ? This is how I would approach the problem: If the key parameter was a tuple or list, we treat each entry inside as a separate key to convert it to int. If the key is a slice, we don't touch it*. If the key is a Model, we convert it to an int, and don't touch it if it's already an int. The following function does this work: def key_to_int(self, key): if isinstance(key, (tuple, list)): return tuple(key_to_int(k) for k in key) if isinstance(key, Model1): return self.models1_indices[key] if isinstance(key, Model2): return self.models2_indices[key] return key *: Except if you have a sense for slicing with Models ?
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88676675
upvote count: 2

http://stackoverflow.com/q/50782566
has body: I am really up sad. Some of my CSV-Files of Stackoverflow dont get inserted into my local database. Because I get an KeyError. The problem it dont work for the Id of posts.csv instead it work for the id of tags.csv. Here is 5 rows of posts.csv 4,1,7,2008-07-31,21:42:52,543,34799,"b"" I want to use a track-bar to change a form's opacity. \n\n This is my code: \n\n decimal trans = trackBar1.Value / 5000 6,1,31,2008-07-31,22:08:08,241,15696,"b' I have an absolutely positioned div containing several children, one of which is a relatively positioned div. When I use a percentage-based width on the child div, it collapses to \'0\' width on Internet&nbsp 7,2,None,2008-07-31,22:17:57,391,None,"b"" An explicit cast to double like this isn't necessary: \n\n double trans = (double) trackBar1.Value / 5000.0 9,1,1404,2008-07-31,23:40:59,1716,439828,"b"" Given a DateTime representing a person's birthday, how do I calculate their age in years? \n""",1,How do I calculate someone's age in C#?,"c#,.net,datetime,",64,376 11,1,1248,2008-07-31,23:55:37,1286,130055,"b' Given a specific DateTime value, how do I display relative time, like: \n\n \n 2 hours ago \n 3 days ago \n a month ago \n \n'",1,Calculate relative time in C#,"c#,datetime,time,datediff,relative-time-span,",34,528 My Code: def writePostsToSql(): con = sqlite3.connect("database.db") cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS posts (Id, PostTypeId, AcceptedAnswerId, Date, Time, Score, ViewCount, Body, OwnerUserId, Title, Tags, AnswerCount, FavoriteCount, PRIMARY KEY (Id), FOREIGN KEY (AcceptedAnswerId), FOREIGN KEY (OwnerUserId));") # use your column names here with open('Posts.csv', 'r') as fin: dr = csv.DictReader(fin) # comma is default delimiter to_db = [(i['Id'], i['PostTypeId'], i['AcceptedAnswerId'], i['Date'], i['Time'], i['Score'], i['ViewCount'], i['Body'], i['OwnerUserId'], i['Title'], i['Tags'], i['AnswerCount'], i['FavoriteCount']) for i in dr] cur.executemany("INSERT INTO posts (Id, PostTypeId, …
has answer: http://stackoverflow.com/a/50783142
type: Question
answer count: 1
score: 0
has title: KeyError by inserting csv to Database?
tagged with: http://stackoverflow.com/tag/csv
tagged with: sql
tagged with: sqlite
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion

awk
tag name: awk
tags question: http://stackoverflow.com/q/50740414
type: Tag
tags question: http://stackoverflow.com/q/50785972
tags question: http://stackoverflow.com/q/50758785
tags question: http://stackoverflow.com/q/50777423
tags question: http://stackoverflow.com/q/50765499

http://stackoverflow.com/a/50705719
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50705612
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/88424414
upvote count: 4
has body: Using groupby + pd.Series.diff: g = df_so_ex2.groupby('ID') df_so_ex2['Chg_avg_value'] = g['Avg. Value'].apply(pd.Series.diff) df_so_ex2['Days_since'] = g['DateOf'].apply(pd.Series.diff).dt.days print(df_so_ex2) Avg. Value Count DateOf ID Chg_avg_value Days_since Index 0 4.4 4 2017-08-01 553 NaN NaN 1 3.0 1 2017-08-03 553 -1.4 2.0 2 5.3 3 2017-08-04 553 2.3 1.0 3 6.4 4 2017-08-07 559 NaN NaN 4 5.0 9 2017-08-09 559 -1.4 2.0 5 4.2 11 2017-08-11 559 -0.8 2.0 6 3.5 4 2017-08-12 559 -0.7 1.0 7 2.0 2 2017-08-02 914 NaN NaN 8 3.3 10 2017-08-04 914 1.3 2.0 9 2.2 5 2017-08-07 914 -1.1 3.0
answers question: http://stackoverflow.com/q/50705612

http://stackoverflow.com/q/50719610
score: -1
answer count: 2
has title: RobotFramework - Unable to import RemoteSwingLibrary
downvote count: 1
has answer: http://stackoverflow.com/a/63744057
favorite count: 0
type: UnansweredQuestion
has body: Screenshot of error in RobotFramework Hello, I am trying to use the RemoteSwingLibrary in RobotFramework for testing. Other libraries I have been able to pip install just fine. However, RemoteSwing is not available with pip. I have a jar file of the library in the python27 folder with other libraries and have it explicitly listed in the path variable. Still receiving the error message that it does not see the module. Please advise. Thank you!
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/50719885
tagged with: swing
has comment: http://stackoverflow.com/comment/88447645
linked to: http://stackoverflow.com/q/34954387
type: Question
tagged with: testing
tagged with: robotframework

http://stackoverflow.com/comment/88603966
type: AnswerComment
has text: Why not a list of list? Do you really that starting at 1 instead of 0 is worth the overhead of a dict against a list?
comment on: http://stackoverflow.com/a/50799012
type: Comment
score: 0

http://stackoverflow.com/q/50814590
has title: Prefix-tree for pairs of elements
type: Question
type: AnsweredQuestion
tagged with: algorithm
tagged with: trie
answer count: 1
has body: I have a nested list: lists = [['a', 'b', 'c', 'd'], ['a', 'b', 'd', 'e'], ['a', 'b', 'd', 'f'], ['a', 'b', 'd', 'f', 'h', 'i']] I know how to build a simple prefix-tree: tree = {} end = "END" for lst in lists: d = tree for x in lst: d = d.setdefault(x, {}) d[end] = {} Result: &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(tree) {'a': {'b': {'c': {'d': {'END': {}}}, 'd': {'e': {'END': {}}, 'f': {'END': {}, 'h': {'i': {'END': {}}}}}}}} Now I can recursively traverse that tree, and whenever a node has only a single child (a sub-dict with just a single element), join those nodes. def join(d, pref=[]): if end in d: yield [' '.join(pref)] if pref else [] for k, v in d.items(): if len(v) == 1: for x in join(v, pref + [k]): # add node to prefix yield x # yield next segment else: for x in join(v, []): # reset prefix yield [' '.join(pref + [k])] + x # yield node + prefix and next Result: &gt;&gt;&gt; for x in join(tree): ... print(x) ... ['a b', 'c d'] ['a b', 'd', 'e'] ['a b', 'd', 'f'] ['a b', 'd', 'f', 'h i'] What I need is an algorithm where only common pairs of elements become single node of the tree. Ideally, the minimum length of a node = n1, the maximum length of a node = n2. Desired output: [['a b', 'c d'], ['a b', 'd e'], ['a b', 'd f'], ['a b', 'd f', 'h i']]
has answer: http://stackoverflow.com/a/50815234
accepted answer: http://stackoverflow.com/a/50815234
score: 0
tagged with: python
tagged with: python-3.x

mysql-python
tags question: http://stackoverflow.com/q/50805061
tags question: http://stackoverflow.com/q/50823950
tags question: http://stackoverflow.com/q/50846478
tags question: http://stackoverflow.com/q/50789829
tags question: http://stackoverflow.com/q/50754100
type: Tag
tags question: http://stackoverflow.com/q/50850840
tags question: http://stackoverflow.com/q/50850868
tag name: mysql-python

http://stackoverflow.com/comment/88618913
comment on: http://stackoverflow.com/q/50806427
has text: Possible duplicate of [Python bytecode and .pyc file format specification](https://stackoverflow.com/questions/35229387/python-bytecode-and-pyc-file-format-specification)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88595236
score: 0
type: Comment
has text: The upper part should also work. What error exactly are you getting when running test file?
type: QuestionComment
comment on: http://stackoverflow.com/q/50794468

http://stackoverflow.com/a/50739130
downvote count: 0
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/50723384
type: Answer
upvote count: 1
has body: The method index() returns the index in list that obj appears. This method returns index of the found object otherwise raise an exception indicating that value does not find. Example: alist = [123, 'xyz', 'muhammad', 'abc']; print ("Index for xyz : ", alist.index( 'xyz' )) print ("Index for Muhammad : ", alist.index( 'muhammad' ) ) Index for xyz : 1 Index for Muhammad : 2 The problem discussed above in the question can be print("Index of ModelsOne :",modelsOne.index(('+', '+', '+', '+', '+', '+', '+', '+', 'a', 'a', 'a', 'd', 'd', 'e', 'e'))) OutPut: Index of ModelsOne :6144
answers question: http://stackoverflow.com/q/50723384

http://stackoverflow.com/a/65571687
upvote count: 10
score: 10
downvote count: 0
has comment: http://stackoverflow.com/comment/123070499
answers question: http://stackoverflow.com/q/50781562
has body: Here is a Python function that splits a Pandas dataframe into train, validation, and test dataframes with stratified sampling. It performs this split by calling scikit-learn's function train_test_split() twice. import pandas as pd from sklearn.model_selection import train_test_split def split_stratified_into_train_val_test(df_input, stratify_colname='y', frac_train=0.6, frac_val=0.15, frac_test=0.25, random_state=None): ''' Splits a Pandas dataframe into three subsets (train, val, and test) following fractional ratios provided by the user, where each subset is stratified by the values in a specific column (that is, each subset has the same relative frequency of the values in the column). It performs this splitting by running train_test_split() twice. Parameters ---------- df_input : Pandas dataframe Input dataframe to be split. stratify_colname : str The name of the column that will be used for stratification. Usually this column would be for the label. frac_train : float frac_val : float frac_test : float The ratios with which the dataframe will be split into train, val, and test data. The values should be expressed as float fractions and should sum to 1.0. random_state : int, None, or RandomStateInstance Value to be passed to train_test_split(). Returns ------- df_train, df_val, df_test : Dataframes containing the three splits. ''' if frac_train + frac_val + frac_test != 1.0: raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \ (frac_train, frac_val, frac_test)) if stratify_colname not in df_input.columns: raise ValueError('%s is not a column in the dataframe' % (stratify_colname)) X = df_input # Contains all columns. y = df_inputstratify_colname # Dataframe of just the column on which to stratify. # Split original dataframe into train and temp dataframes. df_train, df_temp, y_train, y_temp = train_test_split(X, y, stratify=y, test_size=(1.0 - frac_train), random_state=random_state) # Split the temp dataframe into val and test dataframes. relative_…
type: Answer

http://stackoverflow.com/comment/88598186
type: QuestionComment
comment on: http://stackoverflow.com/q/50745153
type: Comment
has text: If it is important then you must show it in your question, have you read the meaning of a [mcve]?
score: 0

http://stackoverflow.com/a/71949137
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/137212949
has body: This question is bit dated, but since I faced a similar issue, what worked for me might help someone! I did pip install requests from within my conda environment, but failed to import requests even after trying out everything. What worked for me: run python -m pip install requests or python3 -m pip install requests within you environment. This installed requests successfully for me.
downvote count: 0
answers question: http://stackoverflow.com/q/50762627

http://stackoverflow.com/comment/88455416
comment on: http://stackoverflow.com/q/50723524
type: Comment
score: 1
type: QuestionComment
has text: Can you post your expected output?

http://stackoverflow.com/a/72800376
score: 0
type: Answer
has body: The values in subsets(rows) will be a position of 1(True) and 0(False) in the rest of columns: import numpy as np list_ = [[5, 3, 5, 2], [6, 3, 2, 1, 3], [5, 3, 2, 5, 2]] ################################## # convert to binary matrix ################################## #find number of columns(dimenseion of matrix) nbr_of_columns = max(map(max, list_))+1 #maximun value in lists_ Mat = np.zeros((len(list_), nbr_of_columns), dtype=bool) for i in range(0, len(list_)): for j in range(0, len(list_[i])): Mat[i, list_[i][j]] = True print(Mat) enter image description here
answers question: http://stackoverflow.com/q/50702988

http://stackoverflow.com/q/50745754
tagged with: python
has comment: http://stackoverflow.com/comment/88499187
score: 2
type: AnsweredQuestion
has title: How to read large pandas dataframe efficiently?
type: Question
has body: I have a 4300*4300 diagonally symmetric pandas dataframe with 1 as diagonal value. It is a correlation matrix. I want to read half of this matrix and also the corresponding 2 column names associated with that value. I have written 2 nested for loops to read values and columns names into 3 lists, but it takes long time. Is there any efficient way for this. Expected output dataframe: column1, column2, corr_val
downvote count: 0
has answer: http://stackoverflow.com/a/50745874
tagged with: pandas
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50745874
upvote count: 2

http://stackoverflow.com/comment/88661233
type: Comment
type: QuestionComment
has text: This is bad function design. Not all control paths return a value. Either way this is just a typo.
comment on: http://stackoverflow.com/q/50828363
score: 0

http://stackoverflow.com/q/50703203
has body: I am trying to make a webscraping bot that logs into https://adelbert.magister.net/ so that I can scrap data in the website after logging in. My code: import mechanicalsoup browser = mechanicalsoup.StatefulBrowser( soup_config={'features': 'lxml'}, raise_on_404=True, user_agent='bot', ) browser.open("https://adelbert.magister.net/") print(browser.get_url()) If you visit the page in your normal browser it redirects to a URL that looks like this: <a href="https://accounts.magister.net/account/login?sessionId=6aa0c7f9387a4b4b8acea413446d918c&amp;returnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3DM6-adelbert.magister.net%26redirect_uri%3Dhttps%253A%252F%252Fadelbert.magister.net%252Foidc%252Fredirect_callback.html%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520magister.ecs.legacy%2520magister.mdv.broker.read%2520magister.dnn.roles.read%26state%3D505f79f6dc244b8ba45daaa215709ac0%26nonce%3D49d332e1fb2e499fb2a17bcd37d756a4%26acr_values%3Dtenant%253Aadelbert.magister.net#!/gebruikersnaam" rel="nofollow noreferrer">https://accounts.magister.net/account/login?sessionId=6aa0c7f9387a4b4b8acea413446d918c&amp;returnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3DM6-adelbert.magister.net%26redirect_uri%3Dhttps%253A%252F%252Fadelbert.magister.net%252Foidc%252Fredirect_callback.html%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520magister.ecs.legacy%2520magister.mdv.broker.read%2520magister.dnn.roles.read%26state%3D505f79f6dc244b8ba45daaa215709ac0%26nonce%3D49d332e1fb2e499fb2a17bcd37d756a4%26acr_values%3Dtenant%253Aadelbert.magister.net#!/gebruikersnaam How can I get it on the good page so that I can make the program login with mechanicalsoup? This is the same question as posted Here but no one has answered that post. Please help me.
answer count: 1
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50704100
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: mechanicalsoup
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46893406
tagged with: web-scraping
upvote count: 1
type: Question
has title: mechanicalsoup is not redirecting to where it should redirect to
has answer: http://stackoverflow.com/a/50704100

http://stackoverflow.com/q/50806837
has body: I'm trying to debug an issue in a separate question, Django "MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in)": when I try to python manage.py migrate, I get an error no schema has been selected to create in. In my version of Django (1.11.9), the ensure_schema method of the MigrationRecorder is def ensure_schema(self): """ Ensures the table exists and has the correct schema. """ # If the table's there, that's fine - we've never changed its schema # in the codebase. import ipdb; ipdb.set_trace() if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): return # Make the table try: with self.connection.schema_editor() as editor: editor.create_model(self.Migration) except DatabaseError as exc: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) (It would appear that in https://github.com/django/django/blob/master/django/db/migrations/recorder.py this is slightly refactored, but essentially the same). Note that I've set a trace at the beginning of the method using import ipdb; ipdb.set_trace(). Now, when I drop into the debugger, I see that introspection.table_names() on the self.connection.cursor() returns an empty list: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate > /Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py(53)ensure_schema() 52 import ipdb; ipdb.set_trace() ---> 53 if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): 54 return ipdb> self.Migration._meta.db_table 'django_migrations' ipdb> self.connection.introspection.table_names(self.connection.cursor()) [] So it seems like the database does not contain any tables, and in particular, doesn't contain the django_migrations table. How can this be? If I look at our DATABASES setting, it seems to be configured correctly: (venv) Kurts-…
type: Question
score: 0
has title: Django connection cursor not showing any tables?
has answer: http://stackoverflow.com/a/50866869
linked to: http://stackoverflow.com/q/50805996
answer count: 1
tagged with: postgresql
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/88483578
score: 0
comment on: http://stackoverflow.com/q/50737695
type: QuestionComment
type: Comment
has text: No, I'm talking about `Ionic.Zlib.ZlibStream` in the same library.

http://stackoverflow.com/q/50799552
has comment: http://stackoverflow.com/comment/88606448
has comment: http://stackoverflow.com/comment/88606980
has comment: http://stackoverflow.com/comment/88605887
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88609450
tagged with: beautifulsoup
has title: finding content of with Beautifulsoup in Python
has body: I'm trying to find how many times a newspaper article has been shared on Facebook with Beautifulsoup. Here's the page: https://www.lemonde.fr/international/article/2018/06/10/isole-trump-est-parvenu-a-imposer-son-agenda-au-cours-d-un-g7-tendu_5312382_3210.html and here's what the html looks like: Isolé, Trump est parvenu à imposer son agenda au cours d’un G7 explosif Partager (142) Tweeter Here's how I'm retrieving the page source as a string: try: req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) response = urlopen(req,timeout=20) except: timeOut = True print(url,'timed out') if timeOut: return "timeOut",[] if 'text/html' in response.getheader('Content-Type') and not timeOut: htmlBytes = response.read() htmlString = htmlBytes.decode("utf-8") self.feed(htmlString) return htmlString, self.links else: return "",[] I'm looking for the " (142)" part (this may have changed on the live webpage when you'll look at it), under: (142) Here's how I'm attempting to do it: shares = BeautifulSoup(data, "lxml").find("span", {"class": "fixed-header-facebook-likes-counter"}).text But it return an empty string (and, interestingly, not "None" as when Beautifulsoup doesn't find anything). What am I missing here?
tagged with: python
has comment: http://stackoverflow.com/comment/88605661
has comment: http://stackoverflow.com/comment/88606856
answer count: 0
has comment: http://stackoverflow.com/comment/88605773
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88605871
has comment: http://stackoverflow.com/comment/88607417

http://stackoverflow.com/a/50740857
has comment: http://stackoverflow.com/comment/88489844
has body: Here: #function call converty = getRows() getDetails(converty) def getRows(): convert = str(rows) return convert def getDetails(convert): data = aliexpress.get_product_details(['productUrl', 'discount', 'evaluateScore', 'volume', 'packageType', 'lotNum', 'validTime', 'storeName', 'storeUrl','allImageUrls'], convert) productId = convert
has comment: http://stackoverflow.com/comment/88490059
answers question: http://stackoverflow.com/q/50740392
score: 0
has comment: http://stackoverflow.com/comment/88490244
type: Answer
has comment: http://stackoverflow.com/comment/88490544
has comment: http://stackoverflow.com/comment/88489747

http://stackoverflow.com/a/50748400
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50747704
answers question: http://stackoverflow.com/q/50747704
has body: Automatically grab all functions from a module is generally not a good idea. It is dangerous, because modules usually have protected functions and functions that you have imported from other modules. However, you can do what you want if you have some way to select only the desired functions from the module, either using some rule about their names or by checking their properties. Here is an example using the name of the functions as a way to filter them. import verification from inspect import signature # Obtain a list of all functions in `verify` which have `verify_` in their name # `my_function` is a list of tuples (function_name, function) my_functions = [(func_name, getattr(verification, func_name)) for func_name in dir(verification) if "verify_" in func_name] menu_options = {func_name: (func, list(signature(func).parameters)) for func_name, func in my_functions} The list(signature(func).parameters)) obtains a list of the arguments' names of the func function.
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50705859
has answer: http://stackoverflow.com/a/50706126
has body: So I've got some code tensors = [] //its filled with 3D float tensors total = sum(tensors) if I change that last line to total = tf.add_n(tensors) then the code produces the same output but runs much more slowly and soon causes an out-of-memory exception. Whats going on here? Can someone explain how pythons built in sum function and tf.add_n interact with an array of tensors respectively and why pythons sum would seemingly just be a better version?
tagged with: tensorflow
type: Question
score: 3
upvote count: 3
answer count: 2
has title: python sum on array of tensors vs tf.add_n
has answer: http://stackoverflow.com/a/50706991
type: UnansweredQuestion
tagged with: python
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50738120
has body: I am trying to import PIL on AWS. I installed PIL using the below command. pip3 install Pillow -t Desktop/myfolder then zipped inside library and a lambda_function.py It looks on aws console like this EDIT : New snapshot But I'm getting the below error. ule 'lambda_function': cannot import name '_imaging'
upvote count: 1
answer count: 1
has title: Import Error: 'lambda_function': cannot import name '_imaging'
linked to: http://stackoverflow.com/q/50734416
has comment: http://stackoverflow.com/comment/88485756
has comment: http://stackoverflow.com/comment/88484078
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50738378
downvote count: 0
score: 1
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88483769

http://stackoverflow.com/q/50753487
score: -1
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88514879
favorite count: 0
has answer: http://stackoverflow.com/a/50753662
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88515078
has body: First of all, I'm a newbie to Python. I'm just practicing. I have made users to input a certain data into the memory by using append. store = [] def inputData(): name = input("Name: ") amount = input("Amount: ") date = input("Data: ") store.append({'name':name, 'amount':amount, 'date':date}) I want to let users be able to search the data stored in the memory. Any hints would be really appreciated. ====================================== Here is my output code def outputData(): print("="*30) print("Name / Amount / Date") print("="*30) for d in store: print("%(name)s %(amount)s %(date)s"%d)
has comment: http://stackoverflow.com/comment/88514969
downvote count: 1
has title: How to search & output a data in python?
type: Question

oracle-database
tags question: http://stackoverflow.com/q/50839398
tag name: oracle-database
type: Tag
tags question: http://stackoverflow.com/q/50812891
tags question: http://stackoverflow.com/q/50839266
tags question: http://stackoverflow.com/q/50843369
tags question: http://stackoverflow.com/q/50774190
tags question: http://stackoverflow.com/q/50755400
tags question: http://stackoverflow.com/q/50844790
tags question: http://stackoverflow.com/q/50786175

gem-fury
tag name: gem-fury
tags question: http://stackoverflow.com/q/50800665
type: Tag

http://stackoverflow.com/comment/88443376
comment on: http://stackoverflow.com/q/50717438
has text: `grid = list(map(lambda s: s.strip('\n'),grid))`
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50705725
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50705935
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: rasa-core
score: 1
has title: How to listen to the data in a specific port?
type: Question
tagged with: server
has body: I wiuld like to create a chatbot from this tutorial, but it seems that the Rasa version is too old and suddenly the commands do not work. I know how to recover and respond to messages through Slack, but I do not know how to do it from a web application that I develop with a chat interface. With Slack, I launched the following script: from rasa_core.channels import HttpInputChannel from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter #from rasa_slack_connector import SlackInput nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/moodnlu') agent = Agent.load('./models/dialogue',interpreter = nlu_interpreter) # With Slack # https://api.slack.com/apps/AASPDV196/oauth? #input_channel = SlackInput('OAuth Access Token','Bot User OAuth Access Token', 'Verification Token',True) #agent.handle_channel(HttpInputChannel(5004,'/',input_channel)) # With inner app input_channel = SlackInput('OAuth Access Token','Bot User OAuth Access Token', 'Verification Token',True) agent.handle_channel(HttpInputChannel(5000,'/',input_channel)) I know I have to modify input_channel so that he hears in the right port, but I really do not know how. Here is where HttpInputChannel comes from
accepted answer: http://stackoverflow.com/a/50705935
upvote count: 1

http://stackoverflow.com/comment/88475442
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50733827
has text: `print ("Cost: %.2f per %s" % (mrate[choice], munit[choice]))`

http://stackoverflow.com/comment/88491391
comment on: http://stackoverflow.com/q/50741849
score: 0
type: QuestionComment
type: Comment
has text: save all the table data inside pandas dataframe and it will be easier for getting the data compared to approach you are following

http://stackoverflow.com/comment/88646562
has text: According to my IDE (I'm using Visual Studio Code), it's saying if just_sent = channelD["just_sent"]: is invalid syntax.
type: Comment
comment on: http://stackoverflow.com/a/50820478
score: 0
type: AnswerComment

http://stackoverflow.com/q/50746971
type: UnansweredQuestion
tagged with: python
has body: Sorry if this is a duplicate question but I could not find clear answer. I am trying to call a python script (dnstwist.py) from within .NET using IronPython. public static void runDNSTwistPython(string url) { var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("dnstwist-master\\dnstwist.py"); test.main(); } I need a way to call this and put the output in a .csv file. I can easily do this from command line but can't figure out how to do it in my C# method. python dnstwist.py --csv google.com &gt; output.csv Thanks
type: Question
tagged with: c#
tagged with: .net
has answer: http://stackoverflow.com/a/50747140
score: 0
answer count: 1
has title: Call a python script with parser arguments in .NET

http://stackoverflow.com/a/50751726
has comment: http://stackoverflow.com/comment/88511368
score: 2
has body: This is because you are not zeroing the gradients. What loss.backward() does is accumulate gradients - it adds gradients to existing ones. If you don't zero the gradient, then running loss.backward() over and over just keep adding the gradients to each other. What you want to do is zero the gradients after each step and you will see that the gradients are calculated correctly. If you have built a network net( which should be a nn.Module class object), you can zero the gradients simply by calling net.zero_grad(). If you haven't built a net (or an torch.optim object) you will have to zero the gradients yourself manually. Use weight.grad.data.zero_() method there.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50751689
has comment: http://stackoverflow.com/comment/134340400
upvote count: 2
answers question: http://stackoverflow.com/q/50751689
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88646385
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50820405
has text: So what is the expected ouput ? [mcve] please

http://stackoverflow.com/comment/88442484
type: QuestionComment
has text: Hmm ... looks like your best bet is downloading the source and building it yourself. But i wonder why it looks like you tried to pip install twisted rather than pyqt oO
type: Comment
comment on: http://stackoverflow.com/q/50715822
score: 0

http://stackoverflow.com/comment/88503148
comment on: http://stackoverflow.com/q/50746992
score: 0
type: Comment
type: QuestionComment
has text: If `aa` is integer and from a not too large interval you can use `np.bincount(aa, bb, aa.max()+1)` I didn't benchmark it but would expect it too typically to scale better than pandas.

http://stackoverflow.com/q/50746942
tagged with: software-design
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Login and authentication functionality in Django REST API and React Native
tagged with: react-native
type: Question
has body: One of my projects I have developed backend API using Django REST Framework and mobile app using React Native. I have done the following things: When the users log in I store their username in local (mobile) database. When users post data I send the username to server reading from local database along with the POST data. I check whether the user is logged in or not using the username and then process the request. My question is: am I doing it in the right way? If no then what are the right procedures to do this kind of authentication checking?
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/50747853
accepted answer: http://stackoverflow.com/a/50747853

http://stackoverflow.com/q/50705083
favorite count: 0
type: UnansweredQuestion
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/50705193
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88419484
has comment: http://stackoverflow.com/comment/88419478
type: Question
has body: I want the user to input lyrics to the program (this will later be extended to searching a website, but i dont currently want help with that) and the program will tell me if the inputted info contains a word from a list. banned_words = ["a","e","i","o","u"] #This will be filled with swear words profanity = False lyrics = input ("Paste in the lyrics: ") for word in lyrics: if word in banned_words: print("This song says the word "+word) profanity = True if profanity == False: print("This song is profanity free") This code just outputs 'This song is profanity free.'
has title: How to check if a string contains a word from a list
upvote count: 2
tagged with: filter
answer count: 1
tagged with: profanity

http://stackoverflow.com/comment/88622811
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50808322
type: QuestionComment
has text: Do you have Microsoft Visual C++ 14.0 ?

http://stackoverflow.com/comment/88648048
has text: Hi, thanks for the comment. I added `mask_zero=True` and played around with a larger embedding size (up to 20), but neither had a noticeable effect (accuracy still gets stuck at 0.3166). I also changed the padding to `post`, but it actually worsened the accuracy (I'm not sure why). The hyperparameters I have messed with so far is the learning_rate, number of hidden layers and also the batch size, but I haven't been able to get better results with any of these yet. Do you have any other suggestions for hyperparameters to change? Thanks
score: 0
comment on: http://stackoverflow.com/q/50820527
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50820361
has comment: http://stackoverflow.com/comment/88646600
has body: I have 2 models in Django that are connected by a one to one relationship. For example: class User(AbstractBaseUser): username = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=100, unique=True) date_joined = models.DateTimeField(auto_now_add=True, null=True) bio = models.CharField(max_length=200, null=True) avatar = models.CharField(max_length=200, null=True) profile = models.OneToOneField(Settings, null=True) class Profile(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) bio = models.CharField(max_length=200, null=True) avatar = models.CharField(max_length=200, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) dob = models.DateField(max_length=8, null=True) Every user may have Profile details, but some users may not have entered any information so they might not have any details provided yet (0 rows). What I'd like to do is create a settings page that either creates or updates the user profile details upon submission. Basically this is what I have so far: class ProfileSettings(UpdateView): template_name = 'oauth/profile-settings.html' form_class = ProfileForm model = Profile def get_object(self, queryset=None): return get_object_or_404(Profile, user=self.request.user) With this type of view, the update works when a user has profile details, but when the user doesn't have profile details a 404 error is displayed instead. Is it possible to display the view to the user even though he doesn't have profile details and if so, could they create profile details for themselves and then can go back and update them?
tagged with: python
has comment: http://stackoverflow.com/comment/88695334
answer count: 0
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/88646627
tagged with: django-views
has title: CreateView and UpdateView based on type of submission?
score: 0

http://stackoverflow.com/comment/88569199
type: QuestionComment
comment on: http://stackoverflow.com/q/50781199
has text: why arent you printing out `os.path.join(mypath, f)` and see if the file is there when to error message clearly tells you that the file location you provided is not there?
score: 0
type: Comment

http://stackoverflow.com/a/50838439
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50838184
has body: web.py passes the values as strings, not as integers. You can see this by running your script in the interpreter with strings vs ints. &gt;&gt;&gt; print myfunc('1980', '3', '4') ('1980 is Ge Sh', 'and its l is somehow', 'the n is CND, the o is CHN', 'The p is Wrong input! and the q is Wrong input!.') &gt;&gt;&gt; print myfunc(1980, 3, 4) ('1980 is Ge Sh', 'and its l is somehow', 'the n is CND, the o is CHN', 'The p is CHN and the q is GBP.') As a sidenote, your code could be improved by using more descriptive variable names, using datetime to parse the input and refactored to remove your if statements (maybe use a dictionary to map input -> output instead).

http://stackoverflow.com/comment/101143339
has text: I does not make sense to look only at the average loading coefficient across all PCs. In my second part, if you have no labels you can define some e.g. `['0','1','2','4','5']` and then you will eventually can map this label to the initial unlabeled features. For example '0' should be the first column/feature in your dataset
type: Comment
comment on: http://stackoverflow.com/a/50845697
score: 0
type: AnswerComment

http://stackoverflow.com/a/50727578
answers question: http://stackoverflow.com/q/50708914
has body: If you attach the actual code that you are trying to except it would be helpful. In your attached stack trace its : " File "/home/ec2-user/dradis/dradisetl-daily.py", line 106" Similar except code works fine for me. mind you, e.pgerror will be empty if the error occurred on the client side, such as the error in my example. the e.diag object will also be useless in this case. try: conn = psycopg2.connect('') except psycopg2.Error as e: print('Unable to connect!\n{0}'.format(e)) else: print('Connected!')
has comment: http://stackoverflow.com/comment/88465322
has comment: http://stackoverflow.com/comment/88527680
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/108836566
upvote count: 2
downvote count: 2

http://stackoverflow.com/comment/88494305
comment on: http://stackoverflow.com/q/50743216
has text: What is the Python version?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88638191
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50815005
has text: "does not work" is no useful error description. What is the expected behavior? What happens instead? Please include any error messages you get in detail in your question (not as comment).
type: Comment

http://stackoverflow.com/comment/88599772
type: Comment
comment on: http://stackoverflow.com/a/50796779
score: 0
has text: ``pytest`` does not require you to turn non-packages into packages. You *already have* a package there, though.
type: AnswerComment

http://stackoverflow.com/comment/88582065
comment on: http://stackoverflow.com/q/50787783
score: 0
type: Comment
has text: Possible duplicate of [Understanding nested list comprehension](https://stackoverflow.com/questions/8049798/understanding-nested-list-comprehension)
type: QuestionComment

http://stackoverflow.com/comment/88509595
score: 2
has text: I guess the `data` is a dictionary which makes `prod` to be a string.
comment on: http://stackoverflow.com/q/50750861
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88635854
type: QuestionComment
has text: `a.plot()` seems to return the `figure` instance, so to get the `Axes` you would need to do `b.axes[0]` or something similar
score: 0
comment on: http://stackoverflow.com/q/50814953
type: Comment

http://stackoverflow.com/a/50800503
has body: Here's an approach which takes the first value in each index/season pair and then sums them up: res = df2.groupby([df2.index, 'season'])['avail'].first().sum(level=0) df2.join(res.rename('sum_avail')) season value avail test2 sum_avail 2020 1 -2 3 4 11 2020 1 3 3 5 11 2020 1 1 3 7 11 2020 2 5 8 8 11 2020 2 8 8 9 11 2021 2 6 4 10 29 2021 3 7 25 11 29 2021 3 5 25 12 29
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88607196
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50800409

hocr
type: Tag
tags question: http://stackoverflow.com/q/50702264
tag name: hocr

http://stackoverflow.com/q/50728738
has comment: http://stackoverflow.com/comment/88469349
has title: How to delete a node in Binary Search Tree using Python
tagged with: oop
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88467579
has answer: http://stackoverflow.com/a/50733579
has comment: http://stackoverflow.com/comment/88471531
linked to: http://stackoverflow.com/q/23331419
type: Question
has comment: http://stackoverflow.com/comment/88470235
tagged with: data-structures
has comment: http://stackoverflow.com/comment/88467774
upvote count: 1
answer count: 1
favorite count: 0
has body: def delete_a_node(self,data): if self.root==None: print("Empty BST") else: parent=None node=self.root replace_node=None while(node!=None and node.data!=data): parent=node if data&gt;=node.data: node=node.rightchild flag=1 else: node=node.leftchild flag=0 if node is None: print("node not in BST.") else: if (node.leftchild==None) and (node.rightchild==None): if (flag): parent.rightchild=None else: parent.leftchild=None del node elif (node.leftchild==None) or (node.rightchild==None): if node.leftchild==None: if(flag): parent.rightchild=node.rightchild else: parent.leftchild=node.rightchild else : if(flag): parent.rightchild==node.leftchild else: parent.leftchild=node.leftchild del node else: replace_node,parent=self.minimum_element(node.rightchild) node=replace_node if parent==None: node.rightchild=None else: parent.leftchild=None del replace_node def minimum_element(self,node): if self.root==None: print("Empty BST") else: parent=None while(node.leftchild!=None): parent=node node=node.leftchild return (node,parent) Hello guys, I was trying to delete a node from binary search tree. I tried to learn it from https://www.geeksforgeeks.org/binary-search-tree-set-2-delete/. Since, they are using recursion in their code. I was unable to grasp it well. So, I tried to make this code. Here I initialize root in init method and rest two methods are in front of you. def __init__(self): self.root=None FLAG Variable: I used it to just find the relationship between the parent node and data node(we want to delete). As we know, There are three cases When the node we want to delete has no child (it's working fine) When the node we want to delete has one child (it's working fine) When the node we want to delete has both the children(HERE IS THE PROBLEM) Please, Can anyone help me with this code? Would you mind showing me, correct method to delete the node from BST should I use del node in python or not, because of I just read that there is no need to free up space in Python. Is my complex…
tagged with: binary-search-tree
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88469385

http://stackoverflow.com/a/50743299
has comment: http://stackoverflow.com/comment/138311440
score: 4
has comment: http://stackoverflow.com/comment/88495359
type: Answer
accepted answer of: http://stackoverflow.com/q/50741377
answers question: http://stackoverflow.com/q/50741377
has body: You need to create a new shading_elm_green element for each cell. Each time you assign it in your current code, you're just moving it from one cell to the next. That's why it ends up at the end. The lxml API is a little counterintuitive that way (until you think about how you would do it yourself :). When you assign an existing element as a child of another element, for example, using .append(), lxml moves the element to be a child of that other element. If you append it to a different element, it moves it there. The assigned element isn't automatically "cloned" or anything like that. It can only live one place, and that place is where you last "placed" it. You don't show your element creation code, but whatever it is, insert it at the next to last row and things should work the way you expect.
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88460312
type: AnswerComment
has text: I have no your data, so not possible check another solution - change `ix` to `loc`. But I hope EDIT answer working nice.
type: Comment
comment on: http://stackoverflow.com/a/50725839
score: 0

http://stackoverflow.com/q/50746323
has answer: http://stackoverflow.com/a/50746388
tagged with: pandas
tagged with: map-function
has title: Usage of .map with defaultdict
has comment: http://stackoverflow.com/comment/88500257
tagged with: python
tagged with: dictionary
downvote count: 1
accepted answer: http://stackoverflow.com/a/50746388
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88544438
upvote count: 5
type: Question
has comment: http://stackoverflow.com/comment/88544360
answer count: 1
has body: I have a pandas dataframe and I have to fill a new column based on the values of an existing column, associating the values of a dictionary. mydict={'key1':'val1', 'key2':'val2'} df['new_col']=df['keys'].map(mydict) Now I have a similar problem, but the dictionary is now a defaultdict(list) my_defdict=defaultdict(list) my_defdict={'key1':['val1','item1'], 'key2':['val2','item2']} and I need a new column with the second element of the list, something like df['new_col2']=df['keys'].map(my_defdict()[1]) which is of course wrong. How can I perform this operation without creating another normal dictionary?
score: 4
favorite count: 0
tagged with: defaultdict

http://stackoverflow.com/comment/98324999
comment on: http://stackoverflow.com/a/51997797
type: Comment
score: 3
type: AnswerComment
has text: @Kota Mori, I am not quite sure that this class you have introduced works correctly for Cross validation with early stopping. Suppose you want to do 5 Fold CV. In the first round we take the first 4 folds as training and we fit the model on them and evaluate/validate the model with the last fold to get the score. With your class, you do another train-test split (test_size=0.1 in the fit function in your class) and basically you evaluate the model within the 10% of the first 4 folds instead of validating the model using the last fold. right? Please correct me if I misunderstood sth here.

http://stackoverflow.com/a/50764115
type: Answer
has comment: http://stackoverflow.com/comment/88536150
answers question: http://stackoverflow.com/q/50763695
accepted answer of: http://stackoverflow.com/q/50763695
has comment: http://stackoverflow.com/comment/88539071
score: 0
type: AcceptedAnswer
has body: objects is a list. So if you write it, you are going to get the reproduction of a list. But you actually want each line separately. You will want to change your output code to something like this: with open(save_path, 'w') as temp_xml: temp_xml.write('\n'.join([str(x).strip() for x in objects])) Update: As mentioned, some of this shouldn't be needed, if this line removes the spaces: values=(' {} {} {} {} {} '.format(name,midx,midy,wid,hgt)) should be values=('{} {} {} {} {}'.format(name,midx,midy,wid,hgt)) Then it could be simplified to with open(save_path, 'w') as temp_xml: temp_xml.write('\n'.join(objects))

http://stackoverflow.com/q/50729464
has answer: http://stackoverflow.com/a/50761972
type: Question
tagged with: numpy
score: 0
answer count: 2
has body: I am trying to create a Matlab file (*.mat) from Python that contains a Matlab data structure that would look like: s.key1 where key1 is an array of values s.key2 where key2 is an array of 1D arrays s.key3 where key3 is an array of 2D arrays If I use savemat and a dictionary, the Matlab output is a cell array rather than a Matlab data structure. I have tried using np.core.records.fromarrays(data_list, names=q_keys) but this doesn't seem to work for keys with 2D arrays. I have both 2D and 3D arrays that need to be in a Matlab structure for compatibility with an existing file format. Is there a way to do this in Python? Thanks
has title: How can I create a Matlab file from Python with multi-dimensional arrays in a Matlab data structure?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50730601
tagged with: matlab

http://stackoverflow.com/a/50731599
accepted answer of: http://stackoverflow.com/q/50731499
has comment: http://stackoverflow.com/comment/88471020
has comment: http://stackoverflow.com/comment/88471153
type: Answer
has body: Here's one way: def is_palindrome(x): return x == x[::-1] with open('so_palindromes.txt', 'r') as f: for line in map(lambda x: x.rstrip(), f): if is_palindrome(line): print(line) Test file: lol not really a palindrome yay hah Output: lol a yay hah
answers question: http://stackoverflow.com/q/50731499
has comment: http://stackoverflow.com/comment/88471063
has comment: http://stackoverflow.com/comment/88471165
has comment: http://stackoverflow.com/comment/88471133
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/88471093
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50786484
has comment: http://stackoverflow.com/comment/88581325
favorite count: 0
accepted answer: http://stackoverflow.com/a/50787480
linked to: http://stackoverflow.com/q/50775083
tagged with: pandas
tagged with: python
has body: I have the following pandas Dataframe: Date Variable 2018-04-10 21:05:00 a 2018-04-10 21:05:00 a 2018-04-10 21:10:00 b 2018-04-10 21:15:00 a 2018-04-10 21:35:00 b 2018-04-10 21:45:00 a 2018-04-10 21:45:00 a My goal is to compute the number of rows containing, say, 'a' that are 30 minutes before and 30 minutes after each time (including rows with the same time both before and after, but not including each row that is being analysed). Then do the same for each Variable. So for the Variable a I'd end up with something like the following: Date nr_30_min_bef_a nr_30_min_after_a 2018-04-10 21:05:00 1 2 2018-04-10 21:05:00 1 2 2018-04-10 21:10:00 2 1 2018-04-10 21:15:00 2 2 2018-04-10 21:35:00 3 2 2018-04-10 21:45:00 2 1 2018-04-10 21:45:00 2 1 I have tried to perform a for loop to iterate over all rows, the problem is that the whole series has more than million rows, therefore I was looking for a more efficient solution. import pandas as pd df = pd.DataFrame({'Date': ['2018-04-10 21:05:00', '2018-04-10 21:05:00', '2018-04-10 21:10:00', '2018-04-10 21:15:00', '2018-04-10 21:35:00', '2018-04-10 21:45:00', '2018-04-10 21:45:00'], 'Variable': ['a', 'a', 'b', 'a', 'b', 'a', 'a']}) Thanks in advance.
has title: Python - Vectorized conditional variable sum based on difference of dates on 1 million row table
has answer: http://stackoverflow.com/a/50787480
downvote count: 0
type: AnsweredQuestion
score: 1
type: Question
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/88458531
type: Comment
comment on: http://stackoverflow.com/a/50724536
has text: add a set to record the processed ones.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88531588
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50761987
has text: almost same question https://stackoverflow.com/questions/50645297/how-to-use-isin-while-ignoring-index/50645672#50645672

http://stackoverflow.com/q/50793088
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I have a sample data Index, Column1,Value1 1, 1,6 1, 2,7 1, 3,8 Index, Column1,Value1 2, 11,16 2, 12,17 2, 13,18 2, 14,19 2, 15,20 Index, Column1,Value1 3, 21,24 3, 22,25 i want to reshape in this way Index Column1, Value1, Column2, Value2, Column3, Value3, Column4, Value4 1 1, 6, 2, 7, 3, 8 2 11, 16, 12, 17, 13, 18, 14, 19 3 21, 24, 22, 25 I am using this print(df.groupby('Index')'Column1', 'Value1'.apply(','.join).reset_index()) but i got weird output. What I am doing wrong here ? Any suggestions ? Index 0 1 Column1,Value1 2 Column1,Value1 3 Column1,Value1 Index Column1,Value1
downvote count: 0
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/50793152
accepted answer: http://stackoverflow.com/a/50793152
type: Question
has title: Pandas, Converting multiple rows into multiple columns
tagged with: pandas
upvote count: 1

http://stackoverflow.com/comment/88507821
type: AnswerComment
comment on: http://stackoverflow.com/a/50750005
score: 0
type: Comment
has text: This doesn't work since `matches` is not present on the `Game` model.

http://stackoverflow.com/q/50759255
linked to: http://stackoverflow.com/q/37302931
has answer: http://stackoverflow.com/a/50759719
upvote count: 3
duplicate of: http://stackoverflow.com/q/2170252
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/45293436
has title: Upgrade python from 2.7 to 3.4 in virtual environment
score: 2
has answer: http://stackoverflow.com/a/50759736
tagged with: virtualenv
tagged with: python-2.7
tagged with: python
has body: I have a virtual machine on rhel 7 that comes along with a built in package of python 2.7 , now i have a created a virtual environment for Django where few libraries are expecting the Python version to be 3.4 or version's more than that. I am not able to Upgrade python inside my Django virtual environemnt , i tried out many update commands to have it from 2.7 to 3.5 but it isn't working out. For Example: pip install Python --upgrade Requirement already up-to-date: Python in /usr/lib64/python2.7/lib-dynload (2.7.5) Please let me know how do i upgrade my Python to a higher version in Django virtual env.
favorite count: 0
has comment: http://stackoverflow.com/comment/88525898
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 1

http://stackoverflow.com/a/50728504
answers question: http://stackoverflow.com/q/50728444
has body: Don't use regex. Split the string, cast the 0 index as a float, and compare it to 120.
downvote count: 0
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/a/50803074
score: 1
answers question: http://stackoverflow.com/q/50802824
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88612340
has comment: http://stackoverflow.com/comment/88612186
accepted answer of: http://stackoverflow.com/q/50802824
type: Answer
upvote count: 1
has body: This would be the equivalent of your loop using list comprehension: [print e for e in list_1 for k in list_2 if k in e]

http://stackoverflow.com/a/50705474
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50704849
answers question: http://stackoverflow.com/q/50704849
has body: You are executing three JavaScript snippets one after another, and in your second snippet you expect variable x to be defined, which it isn't, hence you get the ReferenceError: selenium.common.exceptions.JavascriptException: Message: ReferenceError: x is not defined I'd suggest trying it like this: driver.execute_script(";".join([js_one, js_two, js_three])) This will join your individual snippets to a single one using ; and has the selenium driver execute it.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88424194
type: Answer

http://stackoverflow.com/a/50816883
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50816767
has comment: http://stackoverflow.com/comment/123209255
answers question: http://stackoverflow.com/q/50816767
has body: You need treeString (which for some reason, I couldn't find in the python API) #v will be a string v = df._jdf.schema().treeString() You can convert it to a RDD and use saveAsTextFile sc.parallelize([v]).saveAsTextFile(...) Or use Python specific API to write a String to a file.
upvote count: 14
score: 12
downvote count: 2

http://stackoverflow.com/a/50769590
score: 3
has comment: http://stackoverflow.com/comment/88549688
upvote count: 3
has comment: http://stackoverflow.com/comment/107517658
has body: To remove duplicates whilst preserving order, you can key off a dict: &gt;&gt;&gt; data = [1, 2], [2, 1], [3, 5], [6, 3], [3, 6] &gt;&gt;&gt; list({frozenset(edge): edge for edge in data}.values()) [[2, 1], [3, 5], [3, 6]] Order is preserved overall, and also the order within each pair. In case of dupes, the last pair seen will be the one kept in result. You could keep the first pair by reversed iteration: &gt;&gt;&gt; list({frozenset(edge): edge for edge in reversed(data)}.values())[::-1] [[1, 2], [3, 5], [6, 3]] If you have an older version of Python (&lt;3.6) where the standard dict is not order-preserving, then do the same using an OrderedDict: &gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; list(OrderedDict((frozenset(edge), edge) for edge in data).values()) [[2, 1], [3, 5], [3, 6]]
has comment: http://stackoverflow.com/comment/88548109
has comment: http://stackoverflow.com/comment/88560804
answers question: http://stackoverflow.com/q/50769558
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88591429

http://stackoverflow.com/q/50785356
answer count: 2
downvote count: 0
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/88577390
tagged with: python
has answer: http://stackoverflow.com/a/50785460
has body: I have the following code that is self explanatory in the docstring. How do I get it to not flag single letters with a 1, thereby turning a single digit into 2 in the final compressed string? For example in the docstring it turns AAABBBBCDDDD -> A3B4C1D4 but I want it to turn into A3B4CD4. I'm new at this so it's any comments are greatly appreciated. class StringCompression(object): ''' Run Length Compression Algorithm: Given a string of letters, such as nucleotide sequences, compress it using numbers to flag contiguous repeats. Ex: AAABBBBCDDDD -&gt; A3B4C1D4 &gt;&gt;&gt;x = StringCompression('AAAAbC') &gt;&gt;&gt;x.compress() 'A4bC' ''' def __init__(self, string): self.string = string def compress(self): '''Executes compression on the object.''' run = '' length = len(self.string) if length == 0: return '' if length == 1: return self.string #+ '1' last = self.string[0] count = 1 i = 1 while i &lt; length: if self.string[i] == self.string[i - 1]: count += 1 else: run = run + self.string[i - 1] + str(count) count = 1 i += 1 run = (run + self.string[i - 1] + str(count)) return run
has comment: http://stackoverflow.com/comment/88577327
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50785482
has title: Python compression string not quite right
score: 3
type: Question

http://stackoverflow.com/comment/88584418
score: 0
type: QuestionComment
has text: I tried several things, for example, I used geslacht = vragenlijst_data['geslacht'] plt.hist(geslacht), and it gives an error TypeError: cannot perform reduce with flexible type
type: Comment
comment on: http://stackoverflow.com/q/50788977

http://stackoverflow.com/a/50779308
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/50779252
accepted answer of: http://stackoverflow.com/q/50779252
has body: You may be looking for numpy.random.normal. For example: import numpy as np arr = np.random.normal(loc=1, scale=0.50, size=(500, 500)) print(arr.mean()) # 0.9995707343806642 print(arr.std()) # 0.5010967322495354 Here loc represents the mean and scale the standard deviation, i.e. the square root of variance. Of course, you are drawing samples from a distribution, so you will not have a mean of 1.0 or a standard deviation of 0.50, unless you have a very large array.

http://stackoverflow.com/q/50783006
has title: How get data array from JSON object in python?
tagged with: python
has answer: http://stackoverflow.com/a/50783403
favorite count: 0
accepted answer: http://stackoverflow.com/a/50783396
answer count: 3
upvote count: 1
tagged with: django
has body: I have a jquery POST function like this : $.post(data_send_url, { all_letters:["A","B","C"] }, function(data, status){ alert(data); }); In the server side when I access it using request.data in a Django view function I get &lt;QueryDict: {'all_letters[]': ['e', 'r', 'p']}&gt;. How can I get a Python list like all_letters = ['e','r','p'] ?
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88572668
has answer: http://stackoverflow.com/a/50783396
downvote count: 0
has answer: http://stackoverflow.com/a/50784173
score: 1
tagged with: jquery
has comment: http://stackoverflow.com/comment/88572619
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50784173

http://stackoverflow.com/q/50807990
has body: import patsy from patsy import dmatrices, dmatrix, demo_data dt=pd.DataFrame({'F1':['a','b','c','d','e','a'],'F2':['X','X','Y','Y','Z','Z']}) I know I can do this dmatrix("1+I(F1=='a')",dt) but can I create a arbitrary function patsy? I'm trying to mimicing same level flexibility in formula language in R, but it seems not straight forward to achieve in python def abd(x): 1 if x in ['a','b','d'] else 0 dmatrix("1+abd(F1)",dt)
has title: Create a custom function in Patsy
has answer: http://stackoverflow.com/a/50808119
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50808119
tagged with: lazy-evaluation
has answer: http://stackoverflow.com/a/50849022
type: Question
tagged with: formula
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50849022
tagged with: pandas
tagged with: patsy
tagged with: python

http://stackoverflow.com/a/50732262
has comment: http://stackoverflow.com/comment/88472523
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50732178
answers question: http://stackoverflow.com/q/50732178
has body: If you need to save to CSV, here's a hack you can use to fix the display before saving. m = m.sort_index().reset_index() m['id'] = m['id'].mask(m['id'].ne(m['id'].shift()).cumsum().duplicated(), '') print(m) id name1 Value1 0 1 A 4 1 B 4 2 C 7 3 D 6 4 2 A 9 5 B 6 6 C 5 7 D 0 m.to_csv('file.csv') Disclaimer; if you're doing anything besides saving, do not run this beforehand.
has comment: http://stackoverflow.com/comment/88472467
has comment: http://stackoverflow.com/comment/88472450
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88472727
has comment: http://stackoverflow.com/comment/88473584
type: Answer
has comment: http://stackoverflow.com/comment/88472640
has comment: http://stackoverflow.com/comment/88472721

http://stackoverflow.com/comment/88632972
has text: @smoggers I am sorry I did not mean like that. It's not a stupid answer, in fact as I state it's a correct answer. It would be stupid only in case there was more stuff going on in the for loop which I did not mention before so your answer was absolutely correct and it was my mistake to not stating that there is more process going on in the for loop.
comment on: http://stackoverflow.com/q/50784007
score: 0
type: Comment
type: QuestionComment

qcombobox
tags question: http://stackoverflow.com/q/50711763
tags question: http://stackoverflow.com/q/50735744
tag name: qcombobox
type: Tag
tags question: http://stackoverflow.com/q/50783666
tags question: http://stackoverflow.com/q/50763897
tags question: http://stackoverflow.com/q/50789605

http://stackoverflow.com/q/50758361
downvote count: 2
tagged with: theano
has comment: http://stackoverflow.com/comment/88527437
type: UnansweredQuestion
has body: i get a stuck at this point , i've readed "pong from pixel" of kapathy blog, and i wanna improve this by integrate CNN model then i've got this tutor from GG. **link here: https://github.com/yshvrdhn/Pong-Agent-Using-Policy-Gradients/blob/master/pong_keras.py But i cannot run and dont know the usage of this line: model= learning_model() ,plz someone can help me ??? ***error that i got after compile these code : Traceback (most recent call last): File "C:\Users\thinh dang\Desktop\pong\kerasDemo.py", line 3, in &lt;module&gt; from keras.models import Sequential File "C:\Python27\lib\site-packages\keras\__init__.py", line 3, in &lt;module&gt; from . import utils File "C:\Python27\lib\site-packages\keras\utils\__init__.py", line 6, in &lt;module&gt; from . import conv_utils File "C:\Python27\lib\site-packages\keras\utils\conv_utils.py", line 9, in &lt;module&gt; from .. import backend as K File "C:\Python27\lib\site-packages\keras\backend\__init__.py", line 84, in &lt;module&gt; from .theano_backend import * File "C:\Python27\lib\site-packages\keras\backend\theano_backend.py", line 7, in &lt;module&gt; import theano File "C:\Python27\lib\site-packages\theano\__init__.py", line 110, in &lt;module&gt; from theano.compile import ( File "C:\Python27\lib\site-packages\theano\compile\__init__.py", line 12, in &lt;module&gt; from theano.compile.mode import * File "C:\Python27\lib\site-packages\theano\compile\mode.py", line 11, in &lt;module&gt; import theano.gof.vm File "C:\Python27\lib\site-packages\theano\gof\vm.py", line 674, in &lt;module&gt; from . import lazylinker_c File "C:\Python27\lib\site-packages\theano\gof\lazylinker_c.py", line 140, in &lt;module&gt; preargs=args) File "C:\Python27\lib\site-packages\theano\gof\cmodule.py", line 2388, in compile_str (status, compile_stderr.replace('\n', '. '))) Exception: Compilation failed (return status=1): The system cannot find the path specified.
upvote count: 0
tagged with: keras
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50765732
has answer: http://stackoverflow.com/a/50758485
answer count: 2
has title: pong from pixle with CNN and policy gradient
tagged with: python
score: -2

http://stackoverflow.com/q/50833184
score: 0
has title: How do I use python script to get apache's home body data?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50833461
tagged with: http://stackoverflow.com/tag/json
has body: The content of index.html in apache is: Title { "Java": "ad5aedf87c4f591aa51e02daaea31717ee0798cf-40", "Python": "b6525442fc002ca1ea255e90286ab57afd1c952a-12", "Shell": "12d6180f298ab6419c34d6543aca593d81ec446e-10", "JavaScript": "b6525442fc002ca1ea255e90286ab57afd1c952a-13", "C": "6ad83ed9f599a8c9c967ef2f7168127f8dee28f6-229" } Now the data of index.html is json format. My python script is this : #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import os req = urllib2.Request('http://127.0.0.1') response = urllib2.urlopen(req) the_page = response.read() print (the_page) dictionfo = json.loads(the_page) print (the_page) prints everything from index.html Currently I just want to get the content of body in index.html, how python script should write ？
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50833317

http://stackoverflow.com/comment/88669751
score: 0
comment on: http://stackoverflow.com/q/50772361
has text: Did one of the below solutions help? If so, feel free to accept, or ask for clarification.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88513760
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50752906
type: AnswerComment
has text: not quite: as it gives the incorrect answers as the resulting quantiles do not use the NAN or first 1 in their quantile calculations

http://stackoverflow.com/comment/88660213
score: 0
type: Comment
type: QuestionComment
has text: Where does that `Resource` type come from? Is this `Flask-RESTful`? If so, when you `return val, status` from a `get` method, by default it assumes you're returning JSON, and it won't handle anything else without custom code. See [here](http://flask-restful.readthedocs.io/en/latest/extending.html#content-negotiation) for details.
comment on: http://stackoverflow.com/q/50827706

http://stackoverflow.com/comment/88578804
type: Comment
type: QuestionComment
has text: Yes its located in the 2 second line but than I look at this line I see that everything is seperated by a comma and couldnt awk not just count the fields up until it reaches the geo part ?
comment on: http://stackoverflow.com/q/50785972
score: 0

http://stackoverflow.com/comment/88617093
score: 0
type: Comment
has text: Thanks a lot for the code revision. I am studying it now and I can get it to work. Is it possible to have the table shown in the actual GUI and not in a separate pop-up window?
comment on: http://stackoverflow.com/a/50803367
type: AnswerComment

http://stackoverflow.com/a/50753121
accepted answer of: http://stackoverflow.com/q/50751990
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
has body: One easy way is to create a max-heap of size b. Then run this code: for arr in arrays // process each of the k arrays in turn for i = 0 to length(k)-1 if heap.count &lt; b heap.push(arr[i]) else if (arr[i] &lt; heap.peek()) heap.pop() heap.push(arr[i]) The idea here is that you fill a max-heap with the first b items. Then, for every other item, if it's smaller than the largest item on the heap, you remove the largest item on the heap with the new item. When you've processed all km items, the smallest b items are on the heap, and since it's a max-heap, the first b-a items you pop will be the ath through bth items in all k arrays. // all items have been processed, take the first *b - a* items from the max heap for i = 0 to (b-a-1) result[i] = heap.pop() Worst case is O(km log b) for the first loop, and O(b log b) for the second loop, using O(b) additional memory. If you're allowed to destroy the source arrays, you could write a custom quickselect that indexes the k arrays as a single array. That would be O(km), using O(k) extra memory for an indirect index. The downside being that the indexing code would somewhat slower. And, of course, that items would move among arrays. And you'd probably want O(b) additional memory for the return value. Asymptotically it's more efficient than my original selection. Whether it would run faster is another question entirely. One other possibility. Run the build-heap method on each of the k arrays. That'd be O(km). Then do a merge to select the first b items. The merge would require: O(log m) to remove each item from the source arrays O(log b) to add each item to the merge heap O(log b) to remove each item from the merge heap The second step would be O(b * (log m + log b + log b)). That gives a total of O(km + b * (log m + log b + log b)), and you'd use O(b) extra memory. Whether that would be faster than the original suggestion is questionable. It depends on the relationship between b and m. The larger the value of b, the less likely …
answers question: http://stackoverflow.com/q/50751990

http://stackoverflow.com/a/50957764
type: Answer
has comment: http://stackoverflow.com/comment/89107484
accepted answer of: http://stackoverflow.com/q/50736310
has body: You have to deploy your code using a Pcollection representation for your pipeline. Pubsub messaging (as you did using PubsubIO). is one of the ways to communicate with the GAE. Please follow here to get more details. A simple code could be as follows: // streamData is Unbounded. PCollection&lt;String&gt; streamData = ...; streamData.apply(PubsubIO.Write.named("WriteToPubsub") .topic("/topics/my-topic")); The python code also can be written as follows (pcol has to be placed after all the stes including ptransform and Pardo, etc): from apache_beam.io.gcp.pubsub import WriteStringsToPubSub pcoll = (p | ReadStringsFromPubSub('projects/fakeprj/topics/baz') | beam.Map(lambda x: x)) | WriteStringsToPubSub('projects/fakeprj/topics/a_topic') For more details please review here. Please note that the pipeline also can be run from your GAE python application. Thus, you need to just add a notifier command after the following lines (To make sure that the job is finished and wait_until_finish() function can be used. ): results = p.run() result.wait_until_finish() You can also use the grpc. For more details, please read here. AMQP protocols such as RabbitMQ and ZeroMQ python client codes also can be used.
answers question: http://stackoverflow.com/q/50736310
score: 0
has comment: http://stackoverflow.com/comment/94211953
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89114658

http://stackoverflow.com/q/50764860
has body: I am trying to build a python script where the script will sum a column of a large csv file and give me the output. I was able to sum the columns with the script below: port csv with open("o77069894.out","r+",encoding='utf8') as fin: headerline = fin.readline() amount = 0 debit = 0 value = 0 for row in csv.reader(fin,delimiter=","): value = float(row[17]) if value else 0.0 debit+=value print (debit) But i ran in to an error when i was testing it with csv column with numbers like '12.4 blank space' (the field has blank spaces). So i tried to use: value =row[17].strip() inside the for loop but a error was thrown: Traceback (most recent call last): File "sum_csv1_v3_modified.py", line 8, in for row in csv.reader(fin,delimiter="|"): File "C:\ProgramData\Anaconda3\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 3213: inval id start byte I wont be able show the real data as it is confidential but i think as the code was working for other csv files the issue may be due to the blanks. Even if it is a file issue i would like to know how to deal with such fields. Also i would like to know how can i edit my code to replace ',' or '$' in the numbers. Thanks.
has answer: http://stackoverflow.com/a/50765013
has comment: http://stackoverflow.com/comment/88537601
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50765149
type: Question
has title: How to replace blank space when summing a CSV column
answer count: 2

python-asyncio
tags question: http://stackoverflow.com/q/50805374
tags question: http://stackoverflow.com/q/50750938
tags question: http://stackoverflow.com/q/50757497
tags question: http://stackoverflow.com/q/50853551
tags question: http://stackoverflow.com/q/50789505
tags question: http://stackoverflow.com/q/50816560
tags question: http://stackoverflow.com/q/50705914
tags question: http://stackoverflow.com/q/50789031
tags question: http://stackoverflow.com/q/50804706
tags question: http://stackoverflow.com/q/50746986
tags question: http://stackoverflow.com/q/50779419
tag name: python-asyncio
type: Tag
tags question: http://stackoverflow.com/q/50801910
tags question: http://stackoverflow.com/q/50833802

xpath
tags question: http://stackoverflow.com/q/50708574
tags question: http://stackoverflow.com/q/50845799
tag name: xpath
tags question: http://stackoverflow.com/q/50729897
tags question: http://stackoverflow.com/q/50763386
tags question: http://stackoverflow.com/q/50811070
tags question: http://stackoverflow.com/q/50841915
tags question: http://stackoverflow.com/q/50764879
tags question: http://stackoverflow.com/q/50812299
tags question: http://stackoverflow.com/q/50705252
tags question: http://stackoverflow.com/q/50737246
tags question: http://stackoverflow.com/q/50845165
tags question: http://stackoverflow.com/q/50705928
tags question: http://stackoverflow.com/q/50752182
tags question: http://stackoverflow.com/q/50711963
type: Tag
tags question: http://stackoverflow.com/q/50767714
tags question: http://stackoverflow.com/q/50808295

http://stackoverflow.com/comment/131730475
score: 0
type: Comment
has text: I see how to change shortcuts there, but is it possible to add new shortcuts?
comment on: http://stackoverflow.com/a/50788727
type: AnswerComment

http://stackoverflow.com/comment/88627870
has text: Since when is constructor a keyword?: OCaml version 4.02.3 # let constructor = 1;; val constructor : int = 1
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50795957
type: Comment

http://stackoverflow.com/comment/88559602
type: Comment
comment on: http://stackoverflow.com/a/50775978
type: AnswerComment
has text: @FlorianBernard - Your code working with `index` values also, check it by `print(i)`, similar behaviour is if reset_index() in my answer :)
score: 0

http://stackoverflow.com/q/50825126
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: pyqt5
upvote count: 1
has title: How to increase QFrame.HLine line separator width and distance with the other buttons?
type: Question
tagged with: qt
score: 1
has body: I got this very tiny QFrame.HLine I leaned to do on the thread Separator in box layout: But I cannot figure out how to increase its size, i.e, makes bigger the spacing between them. This is a Photoshop image of what I am trying to do: I tried setting the properties setLineWidth and setMidLineWidth, but does not matter how big I set their values, the line does not gets bigger. This is the example code: #! /usr/bin/env python # -*- coding: utf-8 -*- import sys import PyQt5 from PyQt5 import QtWidgets from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QFrame from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QGridLayout def main(): app = QtWidgets.QApplication( sys.argv ) programWindow = ProgramWindow() programWindow.show() sys.exit( app.exec_() ) class ProgramWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__( self ) self.setup_main_window() self.create_input_text() self.set_window_layout() def setup_main_window(self): self.resize( 400, 300 ) self.centralwidget = QWidget() self.setCentralWidget( self.centralwidget ) def create_input_text(self): self.separatorLine = QFrame() self.separatorLine.setFrameShape( QFrame.HLine ) self.separatorLine.setFrameShadow( QFrame.Raised ) # self.separatorLine.setLineWidth( 150 ) # self.separatorLine.setMidLineWidth( 150 ) rect = self.separatorLine.frameRect() print( "frameShape: %s" % rect ) print( "width: %s" % self.separatorLine.width() ) print( "height: %s" % self.separatorLine.height() ) self.redoButton = QPushButton( "Redo Operations" ) self.calculate = QPushButton( "Compute and Follow" ) self.open = QPushButton( "Open File" ) self.save = QPushButton( "Save File" ) self.verticalGridLayout = QGridLayout() self.verticalGridLayout.addWidget( self.redoButton , 1 , 0) self.verticalGridLayout.addWidget( self.calculate , 2 , 0) self.verticalGridLayout.addWidget( self.sep…
tagged with: layout
downvote count: 0
answer count: 1
tagged with: button
has answer: http://stackoverflow.com/a/50826265
accepted answer: http://stackoverflow.com/a/50826265

http://stackoverflow.com/q/50707653
type: UnansweredQuestion
tagged with: python
has title: Apply tensorflow operations to list of tensors
answer count: 0
score: 1
has body: I'm trying to learn word embeddings using cosine similarity between differing translations. x1 is the embeddings for words in an English sentence. x2 is the embeddings for words in the correct Inuktitut translation. x3 is the embeddings for words in the wrong Inuktitut translation. I'm trying to maximize the cosine similarity between x1 and x2 and minimize it between x1 and x3. There are many triplets of sentences for which I have to do this. My current training function is the following: def train(self): for epoch in range(self.epochs): total_loss = 0 for x1, x2, x3 in zip(self.x1_list, self.x2_list, self.x3_list): norm1 = tf.norm(x1, axis=1) norm2 = tf.norm(x2, axis=1) norm3 = tf.norm(x3, axis=1) cos1 = tf.matmul(x1, x2, transpose_b=True) / norm2 cos1 = tf.transpose(tf.transpose(cos1) / norm1) cos2 = tf.matmul(x1, x3, transpose_b=True) / norm3 cos2 = tf.transpose(tf.transpose(cos2) / norm1) loss = tf.reduce_mean(cos2) - tf.reduce_mean(cos1) optimizer = tf.train.AdamOptimizer(learning_rate=self.eta).minimize(loss) self.session.run(tf.global_variables_initializer()) _, loss = self.session.run([optimizer, loss]) total_loss += loss if epoch % 5 == 0 or epoch == self.epochs-1: print("Epoch {}: loss = {}".format(epoch, total_loss)) I don't want to recreate all of the tensorflow operations in each loop iteration, but since x1, x2, and x3 are Variables, I can't use placeholders for them. Is there a way to apply these operations to a list of Variable tensors?
upvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88429415
linked to: http://stackoverflow.com/q/41175401
has comment: http://stackoverflow.com/comment/88428435
has comment: http://stackoverflow.com/comment/88428190
has comment: http://stackoverflow.com/comment/88429464
has comment: http://stackoverflow.com/comment/88428320
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50736759
score: 1
upvote count: 1
has body: The general way to convert a list of tuples to a tree structure is by iterating over it and creating parent/children relationships: data = [(newid, parentid, name), ...] # getting the data into this format left as an excercise for the reader # convert data into tree-structure tree = { newid: { "parentid": parentid, "name": name, "parent": None, "children": [] } for newid, parentid, name in data } for newid, item in data.items(): node = tree[newid] if node['parentid'] is not None: parent = node['parent'] = tree[node['parentid'] parent.children.append(node) then you can find the root nodes by: roots = [node for node in tree.values() if node.parent is None] You can create a template tag to help display these, or you can do it in javascript, e.g. if you pass roots to your template as json.dumps(roots): there are much better ways to do this in js, but this should get you started.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50735993
type: Answer
accepted answer of: http://stackoverflow.com/q/50735993

http://stackoverflow.com/a/50822672
downvote count: 0
has comment: http://stackoverflow.com/comment/88664912
has comment: http://stackoverflow.com/comment/88664851
accepted answer of: http://stackoverflow.com/q/50822230
has comment: http://stackoverflow.com/comment/88651561
has comment: http://stackoverflow.com/comment/88650500
has body: If you refer to 9gag FAQ (https://about.9gag.com/faq/#six-two) you can see the following: Comment Failings: I can't see my comments anymore. Why? This could be for one of two reasons: The auto spam filter identified your comments as spams OR The community/other users downvoted and/or reported your comments Multiple failings: I can't upload/I can't comment anymore. Why? It’s very likely your account is suspended or banned because you have violated our 9GAG rules. As for the 9gag rules (https://about.9gag.com/rules): No spamming, manipulation and multiple account abuse Everyone hates spam. Don’t post large amounts of untargeted, unwanted or repetitive content and comments in order to increase views. Creating multiple accounts with overlapping uses or in order to evade the temporary or permanent ban of a separate account is not allowed. ... so, I would say you got detected either by the short period of time between your comments, or the content of them. To try out this possibilities, I would make a script which sleeps a random amount of time between comments, and generates random comments of random lenghts: import random import time import string while True: random_comment = ' '.join([random.choice(string.printable) for i in range(random.randint(10,100))]) random_time = random.randint(1, 10) time.sleep(random_time) upload_comment(random_comment)
answers question: http://stackoverflow.com/q/50822230
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88764844
has comment: http://stackoverflow.com/comment/88650603
score: 2
has comment: http://stackoverflow.com/comment/88652093

http://stackoverflow.com/q/50705909
has body: I'm interested in gathering production budgets, national gross, worldwide gross and titles. By exploiting the following code, I've got the whole HTML, while I'd just need the text: import re import requests from bs4 import BeautifulSoup URL = 'https://www.the-numbers.com/movie/budgets/all' def scarica_pagina(link): page = requests.get(link) soup = BeautifulSoup(page.text, 'lxml') cnt=0 for film in soup.find("table").find_all("tr"): cnt=cnt+1 title = film.find_all('b') budget = film.find_all('td') print(cnt, title, budget) if __name__ == '__main__': scarica_pagina(URL) I've tried to code: title = film.find_all('b').text budget = film.find_all('td').text However, the following error occurs: "ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()? ". Indeed, I removed .text, getting the whole HTML. Please help me out.
downvote count: 1
has answer: http://stackoverflow.com/a/50706062
score: 0
possible better answer: http://stackoverflow.com/a/50705988
accepted answer: http://stackoverflow.com/a/50707925
answer count: 4
linked to: http://stackoverflow.com/q/24108507
type: Question
has title: Web Scraping gives the whole html
has answer: http://stackoverflow.com/a/50706029
type: AnsweredQuestion
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/107580935
has answer: http://stackoverflow.com/a/50707925
tagged with: web-scraping
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50705988

http://stackoverflow.com/a/50814886
has comment: http://stackoverflow.com/comment/88638808
has body: You don't need to define the method. def atclub(self): return self.atclub Because atclub is already an attribute, doing student.atclub will work.
type: Answer
has comment: http://stackoverflow.com/comment/88637970
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50814776
has comment: http://stackoverflow.com/comment/88637470

http://stackoverflow.com/comment/88510897
has text: Thanks dude, It was really painful, but at least cx_freeze gives better warnings or error messages! I got it, but it was really painful!! haha thanks!!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50728551
type: Comment

http://stackoverflow.com/q/50723319
upvote count: 6
has title: How do I determine a correlation coefficient in Python?
has comment: http://stackoverflow.com/comment/88455055
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88455291
linked to: http://stackoverflow.com/q/3949226
has body: The equation that I'm working with is as follows- The description says that x-bar and y-bar are the average of array 1 and array 2. The minimum coefficient is 0.3. The reason I'm asking is because I am not too familiar with reading statistical equations, let alone implementing them in Python...
downvote count: 1
type: Question
score: 5
has answer: http://stackoverflow.com/a/50723494
tagged with: statistics
answer count: 2
possible better answer: http://stackoverflow.com/a/50723494
has answer: http://stackoverflow.com/a/50723531
favorite count: 0
has comment: http://stackoverflow.com/comment/88455075
accepted answer: http://stackoverflow.com/a/50723531
tagged with: python

http://stackoverflow.com/a/50742771
score: 0
type: Answer
has body: Why are you doing the .T on the X? This changes the shape of X from (18,2) to (2,18) and hence the error. The following is working for me (Just removed the .T from end of X): X = np.matrix([[1.,2], [3.,4], [5.,1], [6.,5], [4, 7.], [9,8.], [1.,2], [3.,4], [5.,1], [6.,5], [4,7.], [ 9,8.], [1.,2], [3.,4], [5.,1], [6.,5], [4,7.], [9,8.]]) y = [84, 42, 47, 55, 25, 78, 52, 25, 75, 22, 45, 45, 88, 56, 77, 58, 48, 79] gp.fit(X, y)
answers question: http://stackoverflow.com/q/50742651
has comment: http://stackoverflow.com/comment/95874620

http://stackoverflow.com/comment/88711935
has text: Yes your assumptions are correct. I am not in spyder's directory when launching and not launching with ./spyder
comment on: http://stackoverflow.com/a/50854214
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88564837
has text: Looking at the first rows, the users upped the temperature almost 20% within 5 minutes. You need to study your problem. Do many users have access to the thermostat? If so, remember that everybody's comfortable temperature is different. That would completely mess with what the thermostat "should" be set at. I suggest looking at Andrew Ng's or Google (Tensorflow)'s Machine Learning courses for more info on the topic.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50778877

http://stackoverflow.com/a/50844958
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/88693735
downvote count: 0
has body: This is part of a project I did and it worked for the style app.layout = html.Div( style={'backgroundColor': 'black'}, children=[ html.H1('html code')])
type: Answer
answers question: http://stackoverflow.com/q/50844844

http://stackoverflow.com/comment/88667055
type: Comment
has text: I get the same result
comment on: http://stackoverflow.com/a/50831404
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88928319
type: Comment
comment on: http://stackoverflow.com/a/50961753
has text: Sorry Tarun Lalwani , I can't award this bounty until 13 hours from now. The system doesn't allow me to do so and yes this is the answer what does worth it.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50709803
tagged with: postgresql
accepted answer: http://stackoverflow.com/a/50709888
type: Question
upvote count: 2
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50709888
has title: update pandas to postgres
tagged with: pandas
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I'm trying to upload a pandas dataframe to a PostgreSQL database but I'm encountering an error. import pandas as pd import psycopg2 import pandas.io.sql as sql conn_string = "host='localhost' dbname='**' user='postgres' password='**' port=5432" conn = psycopg2.connect(conn_string) cursor = conn.cursor() hh = pd.read_csv("C:/opus/data/mrcog/inputs/synthpop/synth_hhlds.csv") hh.to_sql('buildings_updated', conn) but when i try to upload the table, I'm getting an error that i dont understand what is telling. DatabaseError Traceback (most recent call last) &lt;ipython-input-12-b1b2758437b2&gt; in &lt;module&gt;() 16 17 hh = pd.read_csv("C:/opus/data/mrcog/inputs/synthpop/synth_hhlds.csv") ---&gt; 18 hh.to_sql('buildings_updated', conn) C:\Anaconda2\lib\site-packages\pandas\core\generic.pyc in to_sql(self, name, con, flavor, schema, if_exists, index, index_label, chunksize, dtype) 1343 sql.to_sql(self, name, con, flavor=flavor, schema=schema, 1344 if_exists=if_exists, index=index, index_label=index_label, -&gt; 1345 chunksize=chunksize, dtype=dtype) 1346 1347 def to_pickle(self, path, compression='infer'): C:\Anaconda2\lib\site-packages\pandas\io\sql.pyc in to_sql(frame, name, con, flavor, schema, if_exists, index, index_label, chunksize, dtype) 469 pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index, 470 index_label=index_label, schema=schema, --&gt; 471 chunksize=chunksize, dtype=dtype) 472 473 C:\Anaconda2\lib\site-packages\pandas\io\sql.pyc in to_sql(self, frame, name, if_exists, index, index_label, schema, chunksize, dtype) 1503 if_exists=if_exists, index_label=index_label, 1504 dtype=dtype) -&gt; 1505 table.create() 1506 table.insert(chunksize) 1507 C:\Anaconda2\lib\site-packages\pandas\io\sql.pyc in create(self) 584 585 def create(self): --&gt; 586 if self.exists(): 587 if self.if_exists == 'fail': 588 raise ValueError("Table '%s' already exists." % self.name) C:\Anaconda2\lib\site-packages\pandas\io\sql.pyc in exists(self) 572 573 def exists(self): --&…
favorite count: 0

http://stackoverflow.com/a/50778227
has body: There is no figure canvas from which to get a timer for the animation. Usually you would use pyplot (import matplotlib.pyplot as plt) and let it create a figure with canvas for you via plt.figure() or plt.subplots(). In case you don't do that you need to manually attach your figure to a canvas and in addition you would of course need to create the GUI via one of the supported Frameworks like Tk, PyQt, Wx etc. Which route of those you want to take is not clear from the question and would depend on the final purpose of the application you create.
answers question: http://stackoverflow.com/q/50777961
score: 0
type: Answer

http://stackoverflow.com/a/50805676
score: 3
downvote count: 0
type: AcceptedAnswer
upvote count: 3
has body: From looking at the actual package code, and the examples there, it looks like the correct import is actually: from holoext.xbokeh import Mod See, e.g. this notebook example
accepted answer of: http://stackoverflow.com/q/50804495
answers question: http://stackoverflow.com/q/50804495
type: Answer

http://stackoverflow.com/comment/88689985
has text: @juanpa.arrivillaga Thank you, I have edited my answer, does it look better now?
type: Comment
comment on: http://stackoverflow.com/a/50842919
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88622147
score: 0
comment on: http://stackoverflow.com/a/50784620
type: Comment
has text: While using `xvfb`, you still need manually set `DISPLAY` environment variable when launching your script. Maybe because of this?
type: AnswerComment

http://stackoverflow.com/comment/88669899
has text: @brunodesthuilliers is this what you've meant (answer is edited)?
comment on: http://stackoverflow.com/a/50832376
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88554458
has text: http://idownvotedbecau.se/noattempt/ - SO is about fixing _your_ Code - not implementing your ideas. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [minimal verifyable complete example](https://stackoverflow.com/help/mcve).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50773602
score: 4

http://stackoverflow.com/comment/88580911
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50786975
has text: @aweeeezy - Interesting, after investigating problem was found, better is use `np.number` :)

http://stackoverflow.com/comment/88434209
score: 0
type: Comment
has text: I did, I've written about what happened when I did that in the question, for some reason it's still not working. It displays the same page, but with no user profile details
comment on: http://stackoverflow.com/a/50712678
type: AnswerComment

http://stackoverflow.com/comment/88588426
type: QuestionComment
comment on: http://stackoverflow.com/q/50791247
has text: It is trivial to send an audio file, and you don't seem to need dynamic speech generation; just prerecord the message and dump it into Discord as needed? If you do need text-to-speech, there's `google-tts-api`.
score: 0
type: Comment

http://stackoverflow.com/q/50800409
has answer: http://stackoverflow.com/a/50800503
type: AnsweredQuestion
score: 2
has body: I have the following dataframe: df2 = pd.DataFrame({'season':[1,1,1,2,2,2,3,3],'value' : [-2, 3,1,5,8,6,7,5], 'avail':[3,3,3,8,8,4,25,25],'test2':[4,5,7,8,9,10,11,12]},index=['2020', '2020', '2020','2020', '2020', '2021', '2021', '2021']) df2.index= pd.to_datetime(df2.index) df2.index = df2.index.year print(df2) avail season test2 value 2020 3 1 4 -2 2020 3 1 5 3 2020 3 1 7 1 2020 8 2 8 5 2020 8 2 9 8 2021 4 2 10 6 2021 25 3 11 7 2021 25 3 12 5 I would like to compute efficiently for each year the sum of the 'avail' column. The difficulty here beeing to sum only one 'avail' value for each season. For instance for the year 2020 I want to sum 3+8 =11. Expected result (column 'sum_avail'): avail season test2 value sum_avail 2020 3 1 4 -2 11 2020 3 1 5 3 11 2020 3 1 7 1 11 2020 8 2 8 5 11 2020 8 2 9 8 11 2021 4 2 10 6 29 2021 25 3 11 7 29 2021 25 3 12 5 29
has answer: http://stackoverflow.com/a/50800488
type: Question
has title: Pandas dataframe summing with multiple groupby
tagged with: group-by
has answer: http://stackoverflow.com/a/50800490
accepted answer: http://stackoverflow.com/a/50800490
upvote count: 2
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50800488

http://stackoverflow.com/q/50828895
has answer: http://stackoverflow.com/a/50829502
favorite count: 0
has comment: http://stackoverflow.com/comment/88662633
answer count: 3
has title: list indices must be integers or slices, not numpy.float64
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88662505
score: -2
has answer: http://stackoverflow.com/a/50829291
has comment: http://stackoverflow.com/comment/88662481
has answer: http://stackoverflow.com/a/50828912
type: Question
tagged with: numpy
upvote count: 0
has body: I have matrix like this: print(sent_vectors[1]) [-1.17820399 0.46562683 -0.57934981 -0.78578004 -0.56564459 0.33715023 -0.56717469 0.82579453 0.52400108 -0.59714594 0.14502474 0.44333297 -0.71063957 -0.18717706 -0.47924724 -0.61488901 -0.19839954 -0.5482594 0.35703259 0.15601261 -0.15312789 0.08714889 0.83434086 -0.59783169 0.61747206 -0.16931582 0.13103572 0.1438039 -0.15157178 -1.2203296 0.31373093 0.89667472 -0.17520199 0.48635741 -0.11917028 -0.19563493 -0.59079649 1.08398885 0.23845113 0.75308501 -0.52543743 0.63864713 -1.28121311 -0.27246536 -0.40900175 -0.82675008 -0.60381615 0.88978195 NaN -0.56387159] My question is how to find whether the matrix contains NaN values or not? If it contains NaN values print that matrix? please help me out. I tried thus by using: i=1; for i in sent_vectors[i]: a=sent_vectors[i] np.where(np.isnan(a)) print(i) i += 1 ERROR : list indices must be integers or slices, not numpy.float64

http://stackoverflow.com/comment/88693292
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50781907
has text: @ kimplausibl0 - if I doing so, I got some empty lines without 'hello fellow, can you solve this math problem?\n\n2 x 7?\n' ... what I miss?

http://stackoverflow.com/q/50778694
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/15705630
favorite count: 0
linked to: http://stackoverflow.com/q/50778770
tagged with: python
score: 2
upvote count: 2
tagged with: aggregate
has answer: http://stackoverflow.com/a/50778725
has body: I have a Pandas dataframe that looks as follows: ID Cat 1 SF 1 W 1 F 2 R64 2 SF 2 F The first column is an identifier and the second column contains categorical data where the order is as follows: R64 &lt; SF &lt; F &lt; W I want a new dataframe that contains for each ID the maximum categorical value. The resulting dataframe should look as follows: ID Cat 1 W 2 F I tried the solution from this thread, but it does not seem to work for categorical data: df.groupby("ID", as_index=False).Cat.max() The result with this approach looks like this: ID number 1 SF 2 SF I declare the categorical column like this: df['Cat'] = pd.Categorical(df['Cat'], categories = ["R64", "SF", "F", "W"], ordered = True)
type: Question
type: AnsweredQuestion
has title: Python Pandas groupby and maximum value of categorical column
tagged with: categorical-data
tagged with: pandas-groupby
accepted answer: http://stackoverflow.com/a/50778725
tagged with: pandas

http://stackoverflow.com/comment/88581839
type: Comment
type: QuestionComment
has text: @StephenRauch Curious how this is not a "minimal, complete, and verifiable" example? Please explain your critique and proposed improvement so that we all may benefit from "better answers". Thanks.
comment on: http://stackoverflow.com/q/50786866
score: 0

http://stackoverflow.com/a/50716714
has comment: http://stackoverflow.com/comment/88444419
has comment: http://stackoverflow.com/comment/88446090
type: Answer
has comment: http://stackoverflow.com/comment/88443399
has comment: http://stackoverflow.com/comment/88444739
has comment: http://stackoverflow.com/comment/88445262
answers question: http://stackoverflow.com/q/50716403
has body: There are a few problems with your snippet. Identation: if __name__ == '__main__': is part of the square function The functionsquare should take the argument numbers not x The arguments passed to the process should be args=(numbers,) Once you fix all this, you get: from multiprocessing import Process def square(numbers): for x in numbers: print('%s squared is %s' % (x, x**2)) if __name__ == '__main__': numbers = [43, 50, 5, 98, 34, 35] p = Process(target=square, args=(numbers,)) p.start() p.join() print ("Done") which runs correctly. If you use IDLE on Windows, to see the output, you need to start IDLE from the command line: C:\Users\MyName&gt;python -m idlelib as explained in this question
has comment: http://stackoverflow.com/comment/88444615
has comment: http://stackoverflow.com/comment/88443531
has comment: http://stackoverflow.com/comment/88443878
has comment: http://stackoverflow.com/comment/88445081
has comment: http://stackoverflow.com/comment/88442087
has comment: http://stackoverflow.com/comment/88445161
score: 2
has comment: http://stackoverflow.com/comment/88445083
has comment: http://stackoverflow.com/comment/88445905
downvote count: 0
has comment: http://stackoverflow.com/comment/88445354
has comment: http://stackoverflow.com/comment/88444237
has comment: http://stackoverflow.com/comment/88444474
has comment: http://stackoverflow.com/comment/88444695
upvote count: 2

http://stackoverflow.com/comment/88611738
type: QuestionComment
has text: Not relavant to your question, but I notice you use \ characters in the string for a directory separator - this is dangerous if the character following happens to be a special character, like b, n, r. Use a raw string, two backslashes, or a forward slash /.
comment on: http://stackoverflow.com/q/50802824
score: 0
type: Comment

http://stackoverflow.com/comment/88420070
has text: Many thanks, @EdChum. your solution works
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50702709

http://stackoverflow.com/q/50802556
has answer: http://stackoverflow.com/a/50803450
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/50803450
favorite count: 0
upvote count: 7
has body: Is there a straight forward way to plot an area plot using pandas, but orient the plot vertically? for example to plot an area plot horizontally I can do this: import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) df.plot(kind='area'); I can plot a bar plot vertically with 'barh' df.plot(kind='barh'); But I can't figure out a straightforward way to get a area plot vertical
has comment: http://stackoverflow.com/comment/88611826
possible better answer: http://stackoverflow.com/a/50803052
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50803052
score: 7
tagged with: matplotlib
has title: How to plot a vertical area plot with pandas
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/a/50704404
accepted answer of: http://stackoverflow.com/q/50703912
score: 0
type: AcceptedAnswer
has body: Googling the error ( ;) ) led me to https://github.com/deschler/django-modeltranslation/issues/436 – if I'm assuming correctly, you're using Django 2.0, and no released version of django-modeltranslation supports it yet.
answers question: http://stackoverflow.com/q/50703912
type: Answer
has comment: http://stackoverflow.com/comment/88418793

http://stackoverflow.com/comment/88652861
type: Comment
score: 0
has text: Thanks for the tip, I will try headless Chrome. I have tried regular Chrome before and Phantom was actually faster, that's why I used it.
type: AnswerComment
comment on: http://stackoverflow.com/a/50820700

http://stackoverflow.com/comment/88409007
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50699802
has text: have you tried in the same way ? `ssh = subprocess.Popen(["ssh","-t", "-q","%s" % HOST, COMMAND] ...`
type: Comment

http://stackoverflow.com/q/50718626
score: 2
tagged with: http://stackoverflow.com/tag/zip
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88455370
has comment: http://stackoverflow.com/comment/88446376
has comment: http://stackoverflow.com/comment/88463681
type: Question
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88455390
has body: I have a large zip file that contains many jar files. I want to read the content of the jar files. What I tried is to read the inner jar file into memory, which seem to work (see below). However, I am not sure how large the jar files can be, and am concerned that they won't fit into memory. Is there streaming solution for this problem? hello.zip +- hello.jar +- Hello.class #!/usr/local/bin/python3 import os import io import zipfile zip = zipfile.ZipFile('hello.zip', 'r') for zipname in zip.namelist(): if zipname.endswith('.jar'): print(zipname) jarname = zip.read(zipname) memfile = io.BytesIO(jarname) jar = zipfile.ZipFile(memfile) for f in jar.namelist(): print(f) hello.jar META-INF/ META-INF/MANIFEST.MF Hello.class
type: UnansweredQuestion
tagged with: python
has title: How to read a jar file inside a zip file using Python
has comment: http://stackoverflow.com/comment/88446207
has comment: http://stackoverflow.com/comment/88446190

http://stackoverflow.com/comment/88646360
comment on: http://stackoverflow.com/a/50816852
score: 0
type: AnswerComment
type: Comment
has text: Great thanks. I'll look into it and try to implement it, if it's not possible it's not a big deal.

http://stackoverflow.com/a/50703086
answers question: http://stackoverflow.com/q/50702709
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88415767
has comment: http://stackoverflow.com/comment/88415775
has body: Now that I've understood what you want, let's try something like transform + any: df[df.assign(key=df.day &gt; 4) .groupby(['cc', 'odd', 'tree1', 'tree2']).key.transform('any') ] Or, df[df.day.gt(4).groupby([df.cc, df.odd, df.tree1, df.tree2]).transform('any')] cc odd tree1 tree2 day 4 BB 3435 SAP ATK 3 5 BB 3435 SAP ATK 4 6 BB 3435 SAP ATK 5 7 BB 3435 SAP ATK 6 8 DD 3434 ASP ATK 2 9 DD 3434 ASP ATK 3 10 DD 3434 ASP ATK 4 11 DD 3434 ASP ATK 5 12 DD 3435 SAP ATK 1 13 DD 3435 SAP ATK 3 14 DD 3435 SAP ATK 5 15 DD 3435 SAP ATK 7 16 ZZ 3434 ASP ATK 1 17 ZZ 3434 ASP ATK 2 18 ZZ 3434 ASP ATK 6 19 ZZ 3434 ASP ATK 8 20 ZZ 3435 SAP ATK 2 21 ZZ 3435 SAP ATK 4 22 ZZ 3435 SAP ATK 6 23 ZZ 3435 SAP ATK 8
score: 4
has comment: http://stackoverflow.com/comment/88420269
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50702709

http://stackoverflow.com/comment/88608666
type: AnswerComment
score: 0
type: Comment
has text: Thanks. This did the trick. However, I referred to [this](https://stackoverflow.com/a/31709208/9847180) answer and still can't understand why that works and mine doesn't.I also tried a code to print characters in a string like mantra = "Always look on the bright side" and python still asks for a string prompt when I run the end = ' ' in print function.
comment on: http://stackoverflow.com/a/50801291

http://stackoverflow.com/q/50757929
type: Question
has comment: http://stackoverflow.com/comment/88551557
answer count: 2
score: 5
has title: How to sum rows with the same keys?
possible better answer: http://stackoverflow.com/a/50758270
tagged with: python
has comment: http://stackoverflow.com/comment/88551546
accepted answer: http://stackoverflow.com/a/50758466
has comment: http://stackoverflow.com/comment/88524930
has comment: http://stackoverflow.com/comment/88551906
upvote count: 5
tagged with: dataframe
tagged with: sorting
has body: In my code, df is defined like this df = pd.read_excel(io=file_name, sheet_name=sheet, sep='\s*,\s*') I have a [86 rows x 1 columns] dataframe df which looks like this on print(df) 0 Male 511 Female 461 Male 273 Female 217 Male 394 Female 337 Female 337 Male 337 ... I wish to write a code that would merge the Male and Female entries like this 0 1 2 3 ... Male 511 273 394 337 ... Female 461 217 337 337 ... The final task I need to do is to .sum() the male row and then the female row to get the total of each sex. I am new to python and pandas and I haven't been able to make much progress so far. Any help, tutorial, documentation would be great! Thank you! Edit: By keys I mean the indexes. I hope these labels of Male and Females can be used to 'club' these rows together, but I don't know how to. Edit: I have accomplished my last task directly via print(df.ix['Female'].sum()) print(df.ix['Male'].sum()) But I am yet to achieve my forst task. Any ideas?
has answer: http://stackoverflow.com/a/50758466
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88551597
has answer: http://stackoverflow.com/a/50758270
favorite count: 0
has comment: http://stackoverflow.com/comment/88551947

http://stackoverflow.com/comment/88458875
score: 0
comment on: http://stackoverflow.com/a/50716174
type: AnswerComment
has text: Thanks a lot! I found the id in the calendar settings and exchanged primary with the id. I´ll use your function to get the id later on so it will run automatically.
type: Comment

http://stackoverflow.com/comment/88824773
comment on: http://stackoverflow.com/q/50800867
type: Comment
type: QuestionComment
has text: @MooingRawr , Sorry, I wish I could provide you with that example, but the script I wrote is now not being used anymore. It was used in order to read and convert certain files into XML. ET is the ElementTree package and an FMUV is just FMUVariable, an object which main purpose is to just hold some variables needed for the specific (branch?) of the tree. Next time posting, I will think about the Minimal, Complete and Verifiable example! Sorry for the headache.
score: 0

http://stackoverflow.com/comment/88602422
has text: You are right. I have used the `TimeSeriesGenerator` together with a simpler network and predictions started to look better. Thank you. Anyway I still have a doubt about the `steps_per_epoch` parameter of a ` fit_generator` . I have used an equation: `stepspe = len(train_X) / batchsize` (where batchsize = 32). Is this a correct approach?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50743564
type: Comment

jmx
tags question: http://stackoverflow.com/q/50813976
tag name: jmx
type: Tag

http://stackoverflow.com/a/50819620
has comment: http://stackoverflow.com/comment/88664803
type: Answer
score: 2
has body: Use unstack with select column SlabLT: print (df['SlabLT'].unstack()) But if possible duplicates in MultiIndex is necessary aggregate column, a.g. by mean: print (df.groupby(level=[0,1])['SlabLT'].mean().unstack()) Sample: df = pd.DataFrame({'date':['2017-10-01','2017-10-08','2017-10-08','2017-10-15', '2017-10-15'], 'SlabType':['UOM2','AMOUNT','UOM2','AMOUNT','AMOUNT'], 'SlabLT':[1,6000,1,6000,5000]}).set_index(['date','SlabType']) print (df) SlabLT date SlabType 2017-10-01 UOM2 1 2017-10-08 AMOUNT 6000 UOM2 1 2017-10-15 AMOUNT 6000 &lt;-duplicated MultiIndex '2017-10-15', 'AMOUNT' AMOUNT 5000 &lt;-duplicated MultiIndex '2017-10-15', 'AMOUNT' print (df['SlabLT'].unstack()) ValueError: Index contains duplicate entries, cannot reshape print (df.groupby(level=[0,1])['SlabLT'].mean()) date SlabType 2017-10-01 UOM2 1 2017-10-08 AMOUNT 6000 UOM2 1 2017-10-15 AMOUNT 5500 Name: SlabLT, dtype: int64 print (df.groupby(level=[0,1])['SlabLT'].mean().unstack()) SlabType AMOUNT UOM2 date 2017-10-01 NaN 1.0 2017-10-08 6000.0 1.0 2017-10-15 5500.0 NaN
upvote count: 2
has comment: http://stackoverflow.com/comment/88664585
accepted answer of: http://stackoverflow.com/q/50819579
has comment: http://stackoverflow.com/comment/88664958
answers question: http://stackoverflow.com/q/50819579
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88664560

http://stackoverflow.com/comment/88565033
comment on: http://stackoverflow.com/q/50779042
score: 0
has text: I'm not that knowledgeable about Python ctypes, but it seems to me that you tell Python that `print_query` returns a `char`, but the C function is declared to not return anything.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88546168
type: AnswerComment
score: 0
has text: @Ignus Your right i will edit my answer
type: Comment
comment on: http://stackoverflow.com/a/50761328

http://stackoverflow.com/comment/88719590
type: Comment
comment on: http://stackoverflow.com/q/50785764
type: QuestionComment
has text: I was starting to think the same. I was hoping this would be taken off hold fairly quick but doesn't seem so :/
score: 1

http://stackoverflow.com/comment/88695790
type: Comment
type: QuestionComment
has text: https://django-allauth.readthedocs.io/en/latest/forms.html
score: 0
comment on: http://stackoverflow.com/q/50845990

http://stackoverflow.com/comment/88593198
type: Comment
type: AnswerComment
has text: Thanks exactly what i needed
comment on: http://stackoverflow.com/a/50787581
score: 0

http://stackoverflow.com/comment/88453809
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50722468
has text: @AntoineLB I'm trying your code I think this is exactly what I want

http://stackoverflow.com/comment/88413772
type: Comment
score: 1
has text: You want `df[~df['col2'].isin(['A','B'])]`
comment on: http://stackoverflow.com/q/50702224
type: QuestionComment

http://stackoverflow.com/comment/88481181
comment on: http://stackoverflow.com/q/50720945
type: Comment
type: QuestionComment
has text: It´s already solved! You were right. With the task inside the thread it works fine :) Thanks!
score: 0

http://stackoverflow.com/comment/88666738
comment on: http://stackoverflow.com/q/50831165
score: 1
has text: Are you sure the API provider (OMDB) does not have any limitations in order to avoid high traffic etc?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88726654
has text: Good solution. BTW, is it possible to increase the number of ShapeFilter categories?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50845842
type: Comment

http://stackoverflow.com/a/50704719
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50704445
upvote count: 1
score: 1
has body: I suggest you should process it at data extraction end before constructing data frame you can construct your list as below: from bs4 import BeautifulSoup import requests url = 'https://www.zoopla.co.uk/for-sale/property/london/paddington/?q=Paddington%2C%20London&amp;results_sort=newest_listings&amp;search_source=home' r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') res_lis = [int(price.text.strip().split('\n')[0].replace('£', '').replace(',', '')) for price in soup.find_all('a', {"class":"listing-results-price text-price"}) if price] print(res_lis) result: [2000000, 549950, 1050000, 500000, 675000, 980000, 475000, 849950, 1050000, 1050000, 650000, 1100000, 1300000, 895000, 1000000, 26800000, 1600000, 695000, 2100000, 510000, 3000000, 1200000, 599000, 26800000, 1550000, 750000, 1600000, 1025000] It's always better if you construct/manipulate all data according to requirement as much as possible before storing it which will be your data extraction phase and then

http://stackoverflow.com/comment/88635448
type: Comment
has text: Thanks! Having that pattern implemented in a widely-used library is as close as we can get, I guess. Do we observe the same pattern in other libraries, too? (e.g. Batteries, database libraries, etc.)
comment on: http://stackoverflow.com/a/50810526
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88505871
type: QuestionComment
comment on: http://stackoverflow.com/q/50749047
has text: Possible duplicate of [python merge 3 lists into 1 list](https://stackoverflow.com/questions/34761978/python-merge-3-lists-into-1-list)
score: 0
type: Comment

http://stackoverflow.com/q/50739607
has comment: http://stackoverflow.com/comment/88486875
tagged with: python
has title: Partition by Rows equivalent in pandas (python
type: UnansweredQuestion
tagged with: azure-machine-learning-service
has answer: http://stackoverflow.com/a/50739700
type: Question
score: 0
tagged with: pandas
tagged with: sql
tagged with: sqlite
answer count: 1
has body: I am using Azure Machine Learning Studio and what to add a running total on my dataset. This includes a date column, and I want to sum all the rows (for a group) on or before the row date. In SQL Server, I would use: SELECT [t1].*, SUM([t1].[Amount (Settlement CCY)) OVER ( PARTITION BY [t1].[Contract Ref], [t1].[LOBCode], [t1].[Superline], [t1].[Occupation], [t1].[TransType], [t1].[SettCCY] ORDER BY [t1].[Transaction Date] ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) FROM [t1] GROUP BY [t1].[contract ref], [t1].[Transaction date], [t1].[LOBCode], [t1].[Superline], [t1].[Occupation], [t1].[TransType], [t1].[SettCCY] but Azure Machine learning uses SQLite where the Over / Partition clauses aren't implemented. I've tried an alternative in python/pandas: dataframe1 = dataframe1.assign(cumAMTscTD=dataframe1.groupby(['ContractRef', 'Basis', 'LOBCode', 'Superline', 'Occupation', 'TransType', 'SettCCY'])['AmtSettCCY'].transform('sum')).sort_values(['ContractRef','TransDate']) but this sums up everything for the group, not just the those for the dates up toe current row. I assume therefore it doesn't cover the: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW How would I acheive this?
has comment: http://stackoverflow.com/comment/88486805

http://stackoverflow.com/q/50732327
tagged with: python
has comment: http://stackoverflow.com/comment/88472560
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88472539
has title: csv python: generate list of tuples from rows in csv
type: Question
has body: I have thousands of csv files with the same internal format. Rows typically have eight columns with the format: row1 = ['string in column 0', 'string in column 1', 'string in column 2'...] row2 = ['string in column 0', 'string in column 1', 'string in column 2'...] row3 = ['string in column 0', 'string in column 1', 'string in column 2'...] For each file, I would like to read in certain rows and output a list of tuples separated by row. For example, the files have strings in the first eight columns and I would like the final output to read: list_of_tuples = [('row1_col0','row1_col2','row1_col5','row1_col6'),('row2_col0','row2_col2','row2_col5','row2_col6'),...] Not all of the rows have all four values so I'm afraid to generate four lists and then build a tuple after they get read in. The function that I have built so far reads import csv def list_of_tuples_from_csv(filepath_to_csv): total_text = [] with open(file path_to_csv, 'r') as f: reader = csv.reader(f) for row in reader: total_text.append(tuple(row[0],row[2],row[5],row[6])) total_posts = list(set(total_text)) return total_posts But I get an error reading Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 6, in list_of_tuples_from_csv TypeError: tuple() takes at most 1 argument (4 given)
score: -2
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/88472779
answer count: 1
has answer: http://stackoverflow.com/a/50732519
favorite count: 0
accepted answer: http://stackoverflow.com/a/50732519
tagged with: python-3.x
tagged with: tuples
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/88696490
score: 0
type: Comment
has text: Would it be possible to weight the different categories. For example color having a score of 1, and size having a score of 10, and shape having a score of 15?
comment on: http://stackoverflow.com/a/50845339
type: AnswerComment

http://stackoverflow.com/q/50803382
tagged with: server
accepted answer: http://stackoverflow.com/a/50933085
has body: I made a Docker Image of a Web Application which is built on Python and my Web application needs CouchDB server to start before running the programme. Can anyone please tell me how can I install and run CouchDB server in the Dockerfile of this Web Application. My Dockerfile is given below: FROM python:2.7.15-alpine3.7 RUN mkdir /home/WebDocker ADD ./Webpage1 /home/WebDocker/Webpage1 ADD ./requirements.txt /home/WebDocker/requirements.txt WORKDIR /home/WebDocker RUN pip install -r /home/WebDocker/requirements.txt RUN apk update &amp;&amp; \ apk upgrade &amp;&amp; \^M apk add bash vim sudo EXPOSE 8080 ENTRYPOINT ["/bin/bash"]
tagged with: docker
answer count: 1
downvote count: 0
tagged with: couchdb
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50933085
has title: How to install and start CouchDB server in a Docker image of a Web Application?
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/50725414
score: 0
has answer: http://stackoverflow.com/a/50725467
answer count: 1
has body: I'm trying to write a script that will ask a user for input and then insert their response into a dict. So far I have been able to get 1 key/value but am confused on how I am able to continually ask for input over and over again... number = int(input('How many student\'s do you have in your class? ')) name = raw_input('Please input your student\'s name. ') grade = raw_input('What is the student\'s final grade? ') for n in range(number): usr_input[name] = [grade] for k,v in usr_input.iteritems(): print k,v I am aiming to understand how I can have the script continuously ask for input based off what the user answers to 'number'. For instance, if the user answers '5' as the number of students. How can I get the script to ask the user for 5 student's names and their respective grade?
accepted answer: http://stackoverflow.com/a/50725467
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88459098
type: Question
has title: Looping through user input and inserting into dict

http://stackoverflow.com/q/50710124
linked to: http://stackoverflow.com/q/14326665
type: UnansweredQuestion
score: 6
has answer: http://stackoverflow.com/a/51416470
type: Question
has comment: http://stackoverflow.com/comment/88434432
has body: I'm trying to connect to host and run command with module Fabric 2 and have this error: Traceback (most recent call last): File "Utilities/fabfile.py", line 4, in &lt;module&gt; res.run('uname -s') File "&lt;decorator-gen-3&gt;", line 2, in run File "/usr/local/lib/python2.7/dist-packages/fabric/connection.py", line 29, in opens self.open() File "/usr/local/lib/python2.7/dist-packages/fabric/connection.py", line 501, in open self.client.connect(**kwargs) File "/home/trishnevskaya/.local/lib/python2.7/site-packages/paramiko/client.py", line 424, in connect passphrase, File "/home/username/.local/lib/python2.7/site-packages/paramiko/client.py", line 715, in _auth raise SSHException('No authentication methods available') paramiko.ssh_exception.SSHException: No authentication methods available Simple code from docs (http://docs.fabfile.org/en/latest/getting-started.html): from fabric import Connection res = Connection('&lt;host-ip&gt;') res.run('uname -s') Accoding to docs, I don't need in special configs, but it's doesn't work... fabric 2.1.3 python 2.7.14
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88434204
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/5327465
favorite count: 0
has title: How use Connection in Fabric 2?
tagged with: fabric
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/53915848

http://stackoverflow.com/comment/88420743
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50705748
type: QuestionComment
has text: Did anyone mention yet that the \ needs to be escaped?

http://stackoverflow.com/q/50813779
tagged with: dataset
has title: Delete rows containing Numeric characters
score: 0
has body: I have been working on a dataset which contains unigrams related to products. Within the dataframe we have unigrams like cadbury9gm or 100gmdoritos, SO I would like to delete the entire row containing names like these i.e containing numerical values to make dataframe more clean so that I can proceed further because I have to classify products in categories and sub-categories. Is there a way to do delete rows containing numerical characters ? Thanks
has comment: http://stackoverflow.com/comment/88634220
tagged with: spyder
has answer: http://stackoverflow.com/a/50814798
type: UnansweredQuestion
tagged with: data-cleaning
tagged with: python
has answer: http://stackoverflow.com/a/50814738
tagged with: dataframe
type: Question
answer count: 2

http://stackoverflow.com/a/50818238
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/88646264
has body: As Paulo Scardine mentioned in the comment, don't reinvent the wheel, use itertools.combinations. You are looking for the ids argument in parametrize hook. It's either list of names for each argument, or a function that accepts the argument and returns a string - repr is a simple solution for builtin types. Combined example: import itertools import pytest opts = ['a', 'b', 'c'] @pytest.mark.parametrize('param', itertools.combinations(opts, 2), ids=repr) def test_fn(param): first = param[0] second = param[1] assert first != second
has comment: http://stackoverflow.com/comment/88647076
score: 5
has comment: http://stackoverflow.com/comment/88645184
has comment: http://stackoverflow.com/comment/88645628
upvote count: 5
answers question: http://stackoverflow.com/q/50817905

http://stackoverflow.com/a/50714096
has comment: http://stackoverflow.com/comment/88473545
has comment: http://stackoverflow.com/comment/88442476
has comment: http://stackoverflow.com/comment/88529165
score: 0
has body: Download these jar https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml/3.15 and https://mvnrepository.com/artifact/org.apache.poi/poi/3.15 and add them to your build path import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelReader { public static void main(String[] args) throws IOException { //specify your file path FileInputStream file = new FileInputStream("D:\\test.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(file); //to fetch sheet XSSFSheet sheet = workbook.getSheetAt(0); // for iterating through rows for(int c=0;c&lt;=sheet.getLastRowNum();c++) { // for iterating through columns Row rows = sheet.getRow(c); for(int b=0;b&lt;=rows.getLastCellNum();b++) { Cell cells=rows.getCell(b); //to read cell value as string String comp=cells.getStringCellValue(); } } } }
type: Answer
answers question: http://stackoverflow.com/q/50713455

http://stackoverflow.com/q/50778593
has body: I used tf.layers.dense to build a fully connected autoencoder. and I want to save it and restore only the encoder to get the embedding output. How to use tf.train.saver to restore only the encoder? Because I want to set different batch size of the restored model, to input only one data into it. I saw many tutorials but there is no tutorials about this. Is there any standard solution about this Thank you very much
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50781250
type: UnansweredQuestion
has title: tensorflow save and restore autoencoder
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/50850325
tagged with: heatmap
type: AnsweredQuestion
tagged with: matplotlib
downvote count: 2
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50850493
linked to: http://stackoverflow.com/q/33158075
score: -1
has answer: http://stackoverflow.com/a/50850493
has answer: http://stackoverflow.com/a/50850532
answer count: 2
tagged with: pandas
favorite count: 0
tagged with: seaborn
has title: Heatmap drawing using matplotlib or seaborn?
tagged with: python
has body: I am new to Python. I need to draw a heat map with annotation in every grid using a data frame like this: t=pd.DataFrame({'ReturnType':['ReturnWithoutReceipt','Return With Receipt', 'ReturnWithoutReceipt','Return With Proof Of Purchase','Return With Proof Of Purchase', 'Return With Receipt'], 'Payment':['Card','Cash','Cash','Cash','Card','Card'], 'Hour':[11,12,12,14,16,16], 'value':[1,26,3,67,17,37], 'Label':['1.0--11','26.0--12','3.0--12','67.0--14','17.0--16','37.0--16']}) In my heat map, the row is ReturnType, the column is Payment. The color is decided by value. Label need to be shown in every grid. So, the figure will look like this: So how to do it using matplotlib or seaborn?
accepted answer: http://stackoverflow.com/a/50850532

http://stackoverflow.com/a/50779731
answers question: http://stackoverflow.com/q/50779567
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88566297
downvote count: 0
has body: As bla said without &amp;_callback=jQuery1124033955090772971586_1528569153921 the data is vaild json, callback is not required also is not static, for example http://web.ifzq.gtimg.cn/appstock/hk/HkInfo/getFinReport?type=3&amp;reporttime_type=1&amp;code=00001&amp;startyear=1990&amp;endyear=2016&amp;_callback=test is gives the same results

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/50725166
tag name: qpushbutton
tags question: http://stackoverflow.com/q/50763897

http://stackoverflow.com/comment/88603474
score: 0
comment on: http://stackoverflow.com/q/50798353
has text: @vivek_23 thanks for your suggestion.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50824660
downvote count: 0
answers question: http://stackoverflow.com/q/50824613
accepted answer of: http://stackoverflow.com/q/50824613
type: AcceptedAnswer
upvote count: 11
has body: You can create a dictionary from l2: l1 = [2,4,6,7,8] l2 =[(4,6),(6,8),(8,10)] new_l2 = dict(l2) l3 = [new_l2.get(i, 0) for i in l1] Output: l3 = [0,6,8,0,10]
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/88654313

http://stackoverflow.com/comment/88560418
has text: You've set the numbering type, but you need an actual page number field in your header or footer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50776715

http://stackoverflow.com/q/50721515
has comment: http://stackoverflow.com/comment/88451369
favorite count: 0
has comment: http://stackoverflow.com/comment/88451362
has comment: http://stackoverflow.com/comment/88451339
tagged with: python
has title: Pygame: Player has no attribute 'rect'
has answer: http://stackoverflow.com/a/50721811
accepted answer: http://stackoverflow.com/a/50721811
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/88451617
type: Question
score: -2
downvote count: 2
has body: I'm making a 2d shooter game but when I run it, I get an error and python tells me "Player has no attribute 'rect'". Here is the coding for my 'Player' class Player(pygame.sprite.Sprite): def _init_(self): super(). __init__() pygame.sprite.Sprite.__init__(self) self.image=pygame.Surface([20,20]) self.image.fill(COLOUR2) self.rect=self.image.get_rect() player.rect.x=20 Here is the coding for my whole game: import pygame import sys import math from pygame.locals import * pygame.init() WINDOW = pygame.display.set_mode((900, 700)) COLOUR2 = (32,59,202) COLOUR = (0,180,0) COLOUR3 =(1,234,254) WINDOW.fill(COLOUR) keys=pygame.key.get_pressed() y=100 z=100 x=100 FPS=70 fpsClock=pygame.time.Clock() #Defines what a pygame bullet is. class Bullet(pygame.sprite.Sprite): def __init__(self): super(). __init__() self.image=pygame.Surface self.image.fill(COLOUR2) self.rect=self.image.get_rect() def update(self): self.rect.y-=3 class Player(pygame.sprite.Sprite): def __init__(self): super(). __init__() pygame.sprite.Sprite.__init__(self) self.image=pygame.Surface([20,20]) self.image.fill(COLOUR2) self.rect=self.image.get_rect() player.rect.x=20 all_sprites_list=pygame.sprite.Group()#List of all the sprites bullets_lis=pygame.sprite.Group()#List of all the bullets player=Player()#Creates a player sprite and adds it to the small sprite list all_sprites_list.add(player)#Adds the players to the list while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() keys=pygame.key.get_pressed() #Makes Player character move right by pressing "d" if keys[pygame.K_d]: x=x+3 if x&gt; 900: x=900 #Makes player character move left by pressing "a" if keys[pygame.K_a]: x=x-3 if x&lt;0: x=0 #Makes bullets shoot out of player character by pressing *space* if keys[pygame.K_SPACE]: bullet=Bullet() bullet.rect.x=player.rect.x bullet.rect.y=player.rect.y all_sprites_list.add(bullet) bullet_list.add(bullet) pygame.display.update() #Updates all sprites (makes them move) all_spr…
answer count: 1

http://stackoverflow.com/comment/88662205
has text: `return EMA_window()`, you are trying to call a pandas `Series` object, it doesn't support that. Should it just be `return EMA_window`?
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50828946

http://stackoverflow.com/comment/88634864
score: 0
type: AnswerComment
has text: if a letter is repeating it should be given twice with the number of times it is repeating.....for example aaa should be aa3 while a should just be a but aa should be aa2
type: Comment
comment on: http://stackoverflow.com/a/50808401

http://stackoverflow.com/q/50755209
has body: there is example code: # b.py c = False def d(i=c): print(i, c) I want to write a.py to let the output of b.d to be True, True: # a.py import b b.c = True b.d() but the output is False, True. so, why and how to get it? write after answer to why: # `inspect` may be useful import inspect v = True def f(i=v): print(i, v) s = inspect.signature(f) s.parameters Out[6]: mappingproxy({'i': &lt;Parameter "i=True"&gt;})
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88518540
has answer: http://stackoverflow.com/a/50755417
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50755417
has comment: http://stackoverflow.com/comment/88518475
has answer: http://stackoverflow.com/a/50755384
downvote count: 0
has comment: http://stackoverflow.com/comment/88518308
score: 1
has comment: http://stackoverflow.com/comment/88518764
favorite count: 0
has title: reassignment python modules's variable, but function use that var as default don't change
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/50755384

parameters
tags question: http://stackoverflow.com/q/50836071
type: Tag
tags question: http://stackoverflow.com/q/50752478
tags question: http://stackoverflow.com/q/50745439
tags question: http://stackoverflow.com/q/50782726
tag name: parameters
tags question: http://stackoverflow.com/q/50795993
tags question: http://stackoverflow.com/q/50805556
tags question: http://stackoverflow.com/q/50841770

http://stackoverflow.com/q/50765085
score: 0
has answer: http://stackoverflow.com/a/50765743
has title: How do i format an HTTP request
answer count: 1
tagged with: sockets
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50765743
tagged with: http
type: Question
has body: This works just fine. sock.send("GET / HTTP/1.0%s" % (CRLF)) When I use this one google replies by telling me the client sent a malformed request. sock.send("GET {0} HTTP/ {1}".format(path, CRLF))

http://stackoverflow.com/comment/88435989
has text: Thanks for an update. I have solved the problem in the same way.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50708137

http://stackoverflow.com/q/50788167
score: 5
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50788195
has title: Appending Column With value_counts() in pandas
tagged with: python
tagged with: append
accepted answer: http://stackoverflow.com/a/50788195
has body: I have a dataframe named output that looks like as below : created_at 0 1/8/2017 0:00 1 1/8/2017 0:00 2 1/8/2017 0:00 3 1/8/2017 0:00 4 1/8/2017 0:00 5 1/8/2017 1:00 6 1/8/2017 2:00 7 1/8/2017 3:00 I wanted to count the number of times a particular time appears in the dataframe named df3. The result is as as below : 1/8/2017 0:00 5 1/8/2017 1:00 1 1/8/2017 3:00 1 1/8/2017 2:00 1 What I want is to have two headings added to the df3 called created_at and count. What I first did was to remove the duplicates from the output dataframe and sorted the values, getting a result as below : created_at 0 1/8/2017 0:00 5 1/8/2017 1:00 6 1/8/2017 2:00 7 1/8/2017 3:00 Now I added the column count in the output dataframe but I get the result as below : created_at count 0 1/8/2017 0:00 NaN 5 1/8/2017 1:00 NaN 6 1/8/2017 2:00 NaN 7 1/8/2017 3:00 NaN What i want to achieve is a dataframe called result which should look like this : created_at count 0 1/8/2017 0:00 5 5 1/8/2017 1:00 1 6 1/8/2017 2:00 1 7 1/8/2017 3:00 1 How do I do this? My code is as below : import pandas as pd df1 = pd.read_csv(path1) df2 = pd.read_csv(path2) output = pd.merge(df1, df2, how="inner", on="created_at") df3 = output.created_at.value_counts() output = output.drop_duplicates() output = output.sort_values(by=['created_at']) output['count'] = df3 print(output,'\n\n') Any and all help would be appreciated Thanks
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88583668
upvote count: 5
tagged with: dataframe
type: Question

http://stackoverflow.com/q/50703339
upvote count: 2
has answer: http://stackoverflow.com/a/50703415
type: Question
possible better answer: http://stackoverflow.com/a/50703415
has comment: http://stackoverflow.com/comment/88416317
has title: How to group elements in a list?
score: -2
has body: I have a python list: ['AM43', 'AM22', 'AM51', 'AM43', 'AM22', 'AM51', 'AM43', 'AM22', 'AM51'] I want the output to be a list: ['AM43', 'AM43', 'AM43', 'AM22', 'AM22', 'AM22', 'AM51', 'AM51', 'AM51'] I tried sort() but that also rearranges the order. I don't want that. I want the output to be in the same order as the input list.
has answer: http://stackoverflow.com/a/50703977
tagged with: sorting
has comment: http://stackoverflow.com/comment/88416335
downvote count: 4
has answer: http://stackoverflow.com/a/50703412
favorite count: 0
has comment: http://stackoverflow.com/comment/88416267
has answer: http://stackoverflow.com/a/50703770
answer count: 5
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50703412
has answer: http://stackoverflow.com/a/78902866
tagged with: list

http://stackoverflow.com/comment/88439076
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50715134
has text: But I am making the text list, then I am remove the chars and finally I am join it to string....Because the string is immutable

http://stackoverflow.com/q/50814088
upvote count: 3
tagged with: itk
has answer: http://stackoverflow.com/a/50814510
tagged with: dicom
has answer: http://stackoverflow.com/a/50824115
answer count: 4
favorite count: 0
downvote count: 0
type: UnansweredQuestion
has title: DICOM Images read with GDCMSeriesFileNames or list of paths
tagged with: python
score: 3
tagged with: simpleitk
has answer: http://stackoverflow.com/a/50931080
type: Question
has body: I am using SimpleITK to analyse Dynamic PET Data. I have a folder with 148 * N images (with N the number of frames of my Dynamic PET) and I want to separate the images of each frames. Firstly, I created one subfolder for each frame with the corresponding images. &gt;folder #Folder of dynamic data &gt;subfolder1 #Subfolder with images of Frame 1 &gt;image1, image2, ..., image148 &gt;subfolder2 #Subfolder with images of Frame 2 &gt;image149 image 150, ..., image296 I was reading my images as following: series_reader = sitk.ImageSeriesReader() image = sitk.ReadImage(series_reader.GDCMSeriesFileNames(path_subfolder1)) Creating all these subfolders is not very user-friendly so I try to store all the paths of the images in lists : frame1 = [image1, ..., image148] frame2 = [image149, ..., image296] ... frame_list = [frame1, frame2, ..., frameN] And reading images like this: image = sitk.ReadImage(frame_list[0]) The problem is that when I am looking at the value of a voxel located in the same coordinates (x, y, z), I don't get the same value with the 2 methods. It seems that with series_reader.GDCMSeriesFileNames() SimpleITK retrieve some information about the DICOM image like the Origin. Which information are retrieved by SimpleITK to create his images with series_reader.GDCMSeriesFileNames() that I need to have the exactly same image? Or is there another way to have the same image using list of paths? P.S. : In this post, all the variables named with 'image' are the paths to the images not a SimpleITK Image object. Edit : In my case, all of my frames have got the same series number so I can't use series_reader.GDCMSeriesFileNames(path_folder, series_ID)
has answer: http://stackoverflow.com/a/65165429

http://stackoverflow.com/a/50815983
accepted answer of: http://stackoverflow.com/q/50815820
answers question: http://stackoverflow.com/q/50815820
has body: You can simply copy the __qualname__ attribute across to your wrapped_f wrapper function; it is this function that is returned when the decorator is applied, after all. You could use the @functools.wraps() decorator to do this for you, together with other attributes of note: from functools import wraps class decorator_with_arguments(object): def __init__(self, arg1=0, arg2=0, arg3=0): self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 def __call__(self, f): print("Inside __call__()") @wraps(f) def wrapped_f(*args): print(f.__qualname__) f(*args) return wrapped_f The @wraps(f) decorator there copies the relevant attributes from f onto wrapped_f, including __qualname__: &gt;&gt;&gt; Lol.sayHello.__qualname__ 'Lol.sayHello'
type: AcceptedAnswer
type: Answer
score: 8
downvote count: 0
upvote count: 8

http://stackoverflow.com/comment/88581463
type: QuestionComment
has text: why is it a problem?
comment on: http://stackoverflow.com/q/50785226
score: 0
type: Comment

http://stackoverflow.com/comment/88725969
type: AnswerComment
comment on: http://stackoverflow.com/a/50856674
type: Comment
has text: How would I get the cookie? Thanks.
score: 0

http://stackoverflow.com/a/50703587
has comment: http://stackoverflow.com/comment/88418252
has body: If your distinguishing feature is mainly the colour, you can pre-process to help the neural network. In this case, you can convert RGB into Hue Saturation Value (HSV) and just use for example the Hue channel which will contain information about the colour of pixels and ignore shading etc. Here is a post on that and you can use it as preprocessing_function for ImageDataGenerator.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88417953
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50703359

http://stackoverflow.com/comment/88522028
has text: Problem appears to be that docker-compose requires colorama v 0.3.9 while awsebcli requires 0.3.7
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50757023
type: QuestionComment

http://stackoverflow.com/comment/88583851
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50785955
has text: @SuhaibRoomy No. it is in models.py(which declares Model)
score: 0

http://stackoverflow.com/q/50751639
has comment: http://stackoverflow.com/comment/88512041
has title: How to standardize address type properly
has body: I'm trying to standardize street address by converting the abbreviations to the full word (e.g. RD - Road). I created many lines to account for different spellings and ran into an issue where one replace code overrode another one import pandas as pd mydata = {'Street_type': ['PL', 'pl', 'Pl', 'PLACE', 'place']} mydata = pd.DataFrame(mydata) mydata['Street_type'] = mydata['Street_type'].replace('PL','Place',regex=True) mydata['Street_type'] = mydata['Street_type'].replace('pl','Place',regex=True) mydata['Street_type'] = mydata['Street_type'].replace('Pl','Place',regex=True) mydata['Street_type'] = mydata['Street_type'].replace('PLACE','Place',regex=True) mydata['Street_type'] = mydata['Street_type'].replace('place','Place',regex=True) Instead of Place, I got Placeace. What is the best way to avoid this error? Do I write a if-else statement or any function? Thanks in advance!
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/60227700
has comment: http://stackoverflow.com/comment/88511771
has answer: http://stackoverflow.com/a/50751904
type: Question
has comment: http://stackoverflow.com/comment/88511343
has answer: http://stackoverflow.com/a/50752034
tagged with: replace
upvote count: 2
score: 0
has comment: http://stackoverflow.com/comment/88511655
downvote count: 2
answer count: 3
favorite count: 0

http://stackoverflow.com/comment/88486155
comment on: http://stackoverflow.com/q/50737813
score: 0
type: Comment
type: QuestionComment
has text: If you want to display them in forms you can set initial values there. Something like here e.g.: https://avilpage.com/2015/03/django-form-gotchas-dynamic-initial.html In other cases it can be easy substituted in views or templates. As far as I get this question

http://stackoverflow.com/a/50705877
has comment: http://stackoverflow.com/comment/88499253
answers question: http://stackoverflow.com/q/50704350
has body: It may have to do with the encoding of your file. Try this: import re path = "g:\python_code\A.txt" f_general=open(path, "r", encoding="UTF-16") data = f_general.read() special=re.findall(chr(8482), data) print(special) print(chr(8482)) Note I'm using the decimal value for Trade mark. This is the site I use: https://www.ascii.cl/htmlcodes.htm So, open the file you have in notepad. Do a save as and choose encoding unicode and this should all work. Working with extended ascii can be a hassle. I am using Python 3.6 but I think this should still work in 2.x Note when it prints out the chr(8482) in your command line it will probably just be a T, at least that is what I get in windows. update Try this for Python 2 and this should capture the word before trademark: import re with open("g:\python_code\A.txt", "rb") as f: data = f.read().decode("UTF-16") regex = re.compile("\S+" + chr(8482)) match = re.search(regex, data) if match: print (match.group(0))
has comment: http://stackoverflow.com/comment/88453011
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88507411
has comment: http://stackoverflow.com/comment/88453486

http://stackoverflow.com/comment/88467707
score: 0
type: AnswerComment
has text: Thanks this is great. I was getting `TypeError: tuple indices must be integers, not str` until I changed `v['event_type__name']` to `v[1]` and `itemgetter('date')` to `itemgetter(0).` Do you know if this is an issue with my version of Python? I am using Python2.7 with Django 1.8.X
type: Comment
comment on: http://stackoverflow.com/a/50729263

http://stackoverflow.com/comment/88680990
type: AnswerComment
comment on: http://stackoverflow.com/a/50787172
type: Comment
has text: How should I go about sending log info to Node? Now that I'm combining the buffers, I can't use print() to send any log messages as those will now be concatenated along with any JSON data I send. Is there a way to trigger stdout.on('end') manually to clear the buffer?
score: 0

http://stackoverflow.com/comment/112039131
has text: Good to know thanks @MartijnPieters It is a little frustrating though
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50819719

http://stackoverflow.com/a/50724577
answers question: http://stackoverflow.com/q/50724356
type: Answer
has comment: http://stackoverflow.com/comment/88647008
downvote count: 0
has body: Key points You need to access values in the multiple columns for your lambda function, so apply to the whole dataframe instead of the price column only. The above also solves the issue that apply for a series has no axis argument. Add else x to fix the syntax error in the conditional logic for your lambda When you index x in the lambda it is a value, no longer a series, so kill the str attribute calls and just call len on it. So try: data.apply(lambda x: highlight_otls(x) if len(x['outlier'].split(',')) &gt;= 2 else x, axis=1) Output 0 [background-color: yellow] 1 [background-color: yellow] 2 [None, None] 3 [None, None] dtype: object One way to deal with null outlier values as per your comment is to refactor the highlighting conditional logic into the highlight_otls function: def highlight_otls(x): if len(x['outlier'].split(',')) &gt;= 2: return ['background-color: yellow'] else: return x data.apply(lambda x: highlight_otls(x) if pd.notnull(x['outlier']) else x, axis=1) By the way, you may want to return something like ['background-color: white'] instead of x when you don't want to apply highlighting.
has comment: http://stackoverflow.com/comment/88457765
score: 2
upvote count: 2

http://stackoverflow.com/q/50842802
has comment: http://stackoverflow.com/comment/88689493
has comment: http://stackoverflow.com/comment/88697134
upvote count: 1
has comment: http://stackoverflow.com/comment/88709426
linked to: http://stackoverflow.com/q/31252791
answer count: 0
has title: ImportError: No module named 'flask'
type: UnansweredQuestion
tagged with: flask
tagged with: importerror
has comment: http://stackoverflow.com/comment/88692293
downvote count: 0
score: 1
favorite count: 0
type: Question
has body: I am trying to build a new API in my already well running system. and suddenly my page stopped responding with Internal server Error. When i checked the Apache logs i had the following error [client 166.137.143.124:40797] mod_wsgi (pid=4153): Target WSGI script '/var/www/barnyard/flaskapp.wsgi' cannot be loaded as Python module., referer: http://162.243.13.216/display [client 166.137.143.124:40797] mod_wsgi (pid=4153): Exception occurred processing WSGI script '/var/www/barnyard/flaskapp.wsgi'., referer: http://162.243.13.216/display [client 166.137.143.124:40797] Traceback (most recent call last):, referer: http://162.243.13.216/display [client 166.137.143.124:40797] File "/var/www/barnyard/flaskapp.wsgi", line 7, in &lt;module&gt;, referer: http://162.243.13.216/display [client 166.137.143.124:40797] from FlaskApp import app as application, referer: http://162.243.13.216/display [client 166.137.143.124:40797] File "/var/www/barnyard/FlaskApp/__init__.py", line 1, in &lt;module&gt;, referer: http://162.243.13.216/display [client 166.137.143.124:40797] from flask import Flask, render_template, flash, request, url_for, redirect,session,jsonify, g, referer: http://162.243.13.216/display [client 166.137.143.124:40797] ImportError: No module named 'flask', referer: http://162.243.13.216/display This is what happens when i try to install Flask again just in case it wasn't installed correctly. root@PHost1:/var/www/barnyard/FlaskApp# sudo pip install flask Requirement already satisfied: flask in /usr/local/lib/python2.7/dist-packages (0.12) Requirement already satisfied: Jinja2&gt;=2.4 in /usr/local/lib/python2.7/dist-packages (from flask) (2.9.5) Requirement already satisfied: Werkzeug&gt;=0.7 in /usr/local/lib/python2.7/dist-packages (from flask) (0.11.15) Requirement already satisfied: click&gt;=2.0 in /usr/local/lib/python2.7/dist-packages (from flask) (6.7) Requirement already satisfied: itsdangerous&gt;=0.21 in /usr/local/lib/python2.7/dist-packages (from flask) (0.2…
tagged with: python

http://stackoverflow.com/a/50778403
has body: A regular expression would do the job by looking for either the beginning of the string or the underscore character before your pattern: &gt;&gt;&gt; import re &gt;&gt;&gt; key = 'a-1_tea-1' &gt;&gt;&gt; re.sub(r'(?:^|(?&lt;=_))a-1', 'a-2', key) 'a-2_tea-1' &gt;&gt;&gt; key = 'tea-1_a-1' &gt;&gt;&gt; re.sub(r'(?:^|(?&lt;=_))a-1', 'a-2', key) 'tea-1_a-2' See Python Regular expression syntax documentation for more information.
has comment: http://stackoverflow.com/comment/92492365
accepted answer of: http://stackoverflow.com/q/50778188
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88563688
answers question: http://stackoverflow.com/q/50778188

http://stackoverflow.com/comment/127397178
type: AnswerComment
comment on: http://stackoverflow.com/a/71666401
type: Comment
has text: Why do you need `t`? Does not make sense, `t2` does a diff of start and end of the script.
score: 1

http://stackoverflow.com/q/50799238
answer count: 3
has answer: http://stackoverflow.com/a/50802036
tagged with: airflow
has answer: http://stackoverflow.com/a/53407580
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50802036
type: Question
possible better answer: http://stackoverflow.com/a/50800615
tagged with: python
has answer: http://stackoverflow.com/a/50800615
has body: I'm reviewing the example code here There are two "operation" function: def my_sleeping_function(random_base): """This is a function that will run within the DAG execution""" time.sleep(random_base) and: def print_context(ds, **kwargs): pprint(kwargs) print(ds) return 'Whatever you return gets printed in the logs' For each run of my_sleeping_function we run print_context? What I don't understand is the order. This is the graph and the Tree.. the execution order isn't the same: What happens first? What happens after? Why? I assume that according to this: for i in range(5): task = PythonOperator( task_id='sleep_for_' + str(i), python_callable=my_sleeping_function, op_kwargs={'random_base': float(i) / 10}, dag=dag) task.set_upstream(run_this) run_this executes and then task executes but the loop confuses me.
has title: Order of execution in Airflow
upvote count: 3

http://stackoverflow.com/comment/88642181
type: AnswerComment
has text: @JoshPilson - Values are sorted, because also `groupby` sort by keys first.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50818244

http://stackoverflow.com/comment/88464043
type: AnswerComment
score: 1
type: Comment
has text: Glad, it helped. Happy coding. Consider [accepting](https://stackoverflow.com/help/someone-answers) the answer. @Muss
comment on: http://stackoverflow.com/a/50727859

http://stackoverflow.com/comment/88711749
score: 0
type: AnswerComment
type: Comment
has text: Ok so you don't use the good algorithms. Look for a classifier because you want to perform supervised learning
comment on: http://stackoverflow.com/a/50853408

http://stackoverflow.com/a/50769081
answers question: http://stackoverflow.com/q/50769024
type: Answer
has body: Try this link http://pyqt.sourceforge.net/Docs/PyQt4/qtwebkit.html The error message is typical if the module has not been imported in the script, or if an error in finding the module has occurred.
downvote count: 1
score: -1
upvote count: 0

http://stackoverflow.com/q/50786498
favorite count: 0
tagged with: optimization
upvote count: 9
tagged with: python
has comment: http://stackoverflow.com/comment/128518788
has answer: http://stackoverflow.com/a/74340667
has title: What is faster, scipy fsolve vs root?
downvote count: 0
type: UnansweredQuestion
has body: I am trying to find the root of a function. I have used fsolve in the past but as my data sets get larger, it seems to get more inconsistent (--&gt; n = 187). Now I am looking for alternatives and have found scipy.root. I don't understand what the difference is between the two, and which one is better in my scenario. I am trying to solve the following 3N coupled equations and trying to find vector x y and z: My code is the following, where inrec, outrec and rec are predetermined lists of values: import scipy as sp import numpy as np from scipy.optimize import fsolve import math def f(w, n, onrec, inrec, rec): F = [0]*3*n for i in range(n): F[i] = -onrec[i] #k_i&gt; F[n+i] = -inrec[i] #k_i&lt; F[(2*n)+i] = -rec[i] #k_i &lt;&gt; for j in range(n): if i == j: None else: #below the three functions are stated. w[i] = x_i, w[n+i] = y_i, w[2*n + i] = z_i F[i] += (w[i]*w[n+j])/(1+w[i]*w[n+j]+w[j]*w[n+i]+w[2*n+i]*w[2*n+j]) F[n+i] += (w[j]*w[n+i])/(1+w[i]*w[n+j]+w[j]*w[n+i]+w[2*n+i]*w[2*n+j]) F[2*n+i] += (w[(2*n)+i]*w[(2*n)+j])/(1+w[i]*w[n+j]+w[j]*w[n+i]+w[2*n+i]*w[2*n+j]) return(F) u = [1]*3*n s = fsolve(f, u, args=(n, onrec, inrec, rec))
type: Question
tagged with: performance
tagged with: scipy
score: 9
answer count: 1

http://stackoverflow.com/q/50816800
score: 1
has comment: http://stackoverflow.com/comment/88674522
upvote count: 1
type: Question
has body: I have original data (X_train, y_train), and I am modifying this data into something else. Original data are just images with labels. Modified data should be pairs of images for Siamese network which are high in number and it would be around 30 GB in memory. So can't run this function to create pairs on whole original data. So, I used keras fit_generator thinking it would load only that particular batch. I ran both model.fit and also model.fit_generator on sample pairs but i observed both are using the same amount memory. So, I guess think some problem with my code in using fit_generator. Below is the relevant code. Can you guys please help me with this? Code Below: def create_pairs(X_train, y_train): tr_pairs = [] tr_y = [] y_train = np.array(y_train) digit_indices = [np.where(y_train == i)[0] for i in list(set(y_train))] for i in range(len(digit_indices)): n = len(digit_indices[i]) for j in range(n): random_index = digit_indices[i][j] anchor_image = X_train[random_index] anchor_label = y_train[random_index] anchor_indices = [i for i, x in enumerate(y_train) if x == anchor_label] negate_indices = list(set(list(range(0,len(X_train)))) - set(anchor_indices)) for k in range(j+1,n): support_index = digit_indices[i][k] support_image = X_train[support_index] tr_pairs += anchor_image,support_image negate_index = random.choice(negate_indices) negate_image = X_train[negate_index] tr_pairs += anchor_image,negate_image tr_y += [1,0] return np.array(tr_pairs),np.array(tr_y) def myGenerator(): tr_pairs, tr_y = create_pairs(X_train, y_train) while 1: for i in range(110): # 1875 * 32 = 60000 -&gt; # of training samples if i%125==0: print("i = " + str(i)) yield [tr_pairs[i*32:(i+1)*32][:, 0], tr_pairs[i*32:(i+1)*32][:, 1]], tr_y[i*32:(i+1)*32] model.fit_generator(myGenerator(), steps_per_epoch=110, epochs=2, verbose=1, callbacks=None, validation_data=([te_pairs[:, 0], te_pairs[:, 1]], te_y), validation_steps=None, class_weight=None, max_queue_size=10, workers=1, use_multip…
has title: fit_generator in keras, loading everything into memory
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88664985
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88639303
tagged with: python
tagged with: generator
has answer: http://stackoverflow.com/a/50817195

http://stackoverflow.com/a/50785460
has comment: http://stackoverflow.com/comment/88577640
type: Answer
score: 2
has body: Here's an alternative solution using itertools.groupby and a generator: from itertools import chain, groupby x = 'AAABBBBCDDDD' def compressor(s): for i, j in groupby(s): size = len(list(j)) yield (i, '' if size==1 else str(size)) res = ''.join(chain.from_iterable(compressor(x))) print(res) A3B4CD4
upvote count: 2
has comment: http://stackoverflow.com/comment/88577622
answers question: http://stackoverflow.com/q/50785356
downvote count: 0

http://stackoverflow.com/q/50805099
type: Question
has body: I am trying to make a communication between NodeJS and Python by making a post request from file .ejs rendered by NodeJS. But I don't know how to listen to that post request with python. I tried flask as this link How to send and receive HTTP POST requests in Python but flask and node cannot run on the same port. In index.ejs: Calibration PH (for example: 4) : In app.js: app.set('view engine', 'ejs'); app.get('/',(req,res)=>{ console.log("OK") res.render('index'); }); app.post('/new',(req,res)=>{ var number = req.body.PH; res.redirect('/'); console.log(number); }) app.listen(process.env.PORT || 3000, process.env.IP, function(){ console.log("SERVER IS RUNNING!"); })
has comment: http://stackoverflow.com/comment/88616222
downvote count: 0
has comment: http://stackoverflow.com/comment/88618129
favorite count: 0
has comment: http://stackoverflow.com/comment/88617597
has comment: http://stackoverflow.com/comment/88617748
linked to: http://stackoverflow.com/q/38070373
tagged with: python
has comment: http://stackoverflow.com/comment/88616220
has comment: http://stackoverflow.com/comment/88618176
has comment: http://stackoverflow.com/comment/88616316
has comment: http://stackoverflow.com/comment/88616400
tagged with: node.js
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41940663
has comment: http://stackoverflow.com/comment/88618382
upvote count: 1
has title: How to receive post request with python?
has comment: http://stackoverflow.com/comment/88622165
has comment: http://stackoverflow.com/comment/88622267
score: 1
has comment: http://stackoverflow.com/comment/88616540
tagged with: post

http://stackoverflow.com/q/50729090
has comment: http://stackoverflow.com/comment/88466056
tagged with: mcafee
type: Question
tagged with: python-2.7
answer count: 1
has answer: http://stackoverflow.com/a/50729237
favorite count: 0
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88466083
type: UnansweredQuestion
upvote count: 1
has body: I have a dict object in which I'm trying to parse out and capture only a part of the string. I'm using McAfee EPO Python API's and can grab results of a query, but I don't think that is relevant to this question. Here is the strings in the objects (multiple lines of similar content). What I'm after is extracting the 'WORKSTATION001' text from this string. {u'EPOLeafNode.NodeName': u'WORKSTATION001'} Here's the code I'm using: for system in epoSystems: computerName = system.rstrip().split('u') print computerName This results in: computerName = system.rstrip().split('u') AttributeError: 'dict' object has no attribute 'rstrip' Any ideas on how to grab just that string?
has title: AttributeError when splitting a string
downvote count: 1
has comment: http://stackoverflow.com/comment/88466266

http://stackoverflow.com/comment/88583513
has text: @jonrsharpe I edited my answer now it considers missing signals as zero
comment on: http://stackoverflow.com/a/50782370
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88643314
has text: I have tried the solution but it didn't work for me. It does not give me error but do not highlight any column. I also can't add comment on that thread due to reputation issue. What should i do now ? thank you
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50804925
score: 0

http://stackoverflow.com/a/65275558
score: 3
downvote count: 0
has body: I suggest using 3d adaptive remeshing with smoothing. The Geogram programming library (http://alice.loria.fr/software/geogram/doc/html/index.html) provides a nice implementation. Please see: https://twitter.com/brunolevy01/status/1132343120690122752?lang=en
answers question: http://stackoverflow.com/q/50822911
has comment: http://stackoverflow.com/comment/115402731
upvote count: 3
type: Answer

http://stackoverflow.com/q/50802744
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
type: Question
has title: How to get string from an emoji from a reaction
tagged with: discord.py
score: 0
has answer: http://stackoverflow.com/a/50802873
has body: I'm using discord.py and I would like to know how to get the string value of an emoji that a user has reacted with. Such as if a user reacted with a GB flag I would be able to get the string :flag_gb: so that I can access if they reacted with a flag and if so what flag it was. @client.event async def on_reaction_add(reaction, user): channel = reaction.message.channel
answer count: 1
linked to: http://stackoverflow.com/q/48831593
tagged with: discord

http://stackoverflow.com/comment/88642555
has text: @Mauro Check now
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50808053

http://stackoverflow.com/comment/88679374
type: Comment
comment on: http://stackoverflow.com/a/50807810
has text: Thanks! Yes, it would be great having it back.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50759237
upvote count: 1
has comment: http://stackoverflow.com/comment/88525927
has comment: http://stackoverflow.com/comment/88527141
tagged with: parallel-processing
score: 1
has comment: http://stackoverflow.com/comment/88528313
type: Question
has comment: http://stackoverflow.com/comment/88528437
tagged with: ipython-parallel
downvote count: 0
has body: I have been trying to read a large file and writing to another file at the same time after processing the data from the input file, the file is pretty huge around 4-8 GB, is there a way to parallelise the process to save the time The original program is: with open(infile,"r") as filein: with open(writefile,"w") as filewrite: with open(errorfile,"w") as fileerror: line=filein.readline() count=0 filewrite.write("Time,Request,IP,MAC\n") while line: count+=1 line=filein.readline() #print "{}: {}".format(count,line.strip()) testing content if requestp.search(line): filewrite.write(line.strip()[:15]+",") filewrite.write(requestp.search(line).group()+",") if IP.search(line): filewrite.write(IP.search(line).group()) filewrite.write(",") if MACp.search(line): filewrite.write(MACp.search(line).group()) filewrite.write("\n") else: fileerror.write(line) But this takes too much time to process such a file and I have 100's of such files, I've tried using Ipyparellel to parallilise the code but have not met with success yet, is there a way to do this.
has title: Parallel file reading in python
has comment: http://stackoverflow.com/comment/88528589
tagged with: python
has comment: http://stackoverflow.com/comment/88559010
favorite count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50786922
downvote count: 0
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50786866
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88581728
answers question: http://stackoverflow.com/q/50786866
has body: You have to format each field individually: class foo: def __init__(self): self.datalist = [] def push_data(self, s1, int2, flt3): self.datalist.append({ "s1": '%s' % s1, "int2": '%i' % int2, "dec3": '%0.2f' % flt3 }) def print_data(self): return self.datalist f = foo() f.push_data("HelloWorld", 1, 3.1415) f.print_data() # [{'dec3': '3.14', 'int2': '1', 's1': 'HelloWorld'}]
type: Answer

http://stackoverflow.com/q/50711313
type: Question
has body: I'm running my python-project which is about training a neural network with tensorflow at PyCharm, and find that my network has been already well-trained since the second restart of running my project. I have no command to restore any trained model in my project (I do have commands for saving models). Anyone knows anything about my problem? Is it possible that tensorflow or pycharm have default settings to save and restore? Great thanks!
score: 0
favorite count: 0
has title: Why tensorflow would automatically continue training the model?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88434452
tagged with: python
has comment: http://stackoverflow.com/comment/88480143
answer count: 0
upvote count: 1
downvote count: 1
tagged with: tensorflow

http://stackoverflow.com/a/50745359
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50745285
has comment: http://stackoverflow.com/comment/88498944
type: Answer
has body: What's happening is your dictionary values are themselves dictionaries. So pd.Series.map will only map to dictionary values. It can't do anything else. There are some workarounds. Use itemgetter to extract values This will extract the value for the "value" key in each dictionary. from operator import itemgetter df['new_col'] = df['col1'].map(d).apply(itemgetter('value')) Restructure your dictionary before mapping Construct a new dictionary with the key-mapping your desire before mapping your series. d = {k: v['value'] for k, v in d.items()} df['new_col'] = df['col1'].map(d)
has comment: http://stackoverflow.com/comment/88499301
has comment: http://stackoverflow.com/comment/88499257
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88499144
answers question: http://stackoverflow.com/q/50745285

http://stackoverflow.com/q/50724176
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88477915
tagged with: inheritance
has title: Getting an attribute of grandparent class using getattr
has comment: http://stackoverflow.com/comment/88457054
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50724294
has answer: http://stackoverflow.com/a/50724341
has body: I'm trying to access an instance attribute (inst_baseA / inst_baseB) of Base class from an instance of ClassB, depending on an attribute of the instance (self.x of object ClassB). Here is my code: class Base(object): def __init__(self): self.inst_baseA = 'base_B' self.inst_baseB = 'base_A' class ClassA(object): def __init__(self): self.node = Base() class ClassB(ClassA): def __init__(self): super(ClassB, self).__init__() self.x = 'base_A' This is what I tried first: &gt;&gt;&gt; b = ClassB() &gt;&gt;&gt; getattr(b, 'node.inst_{}'.format(b.x)) Traceback (most recent call last): File "&lt;pyshell#26&gt;", line 1, in &lt;module&gt; getattr(b, 'node.inst_{}'.format(b.x)) AttributeError: 'ClassB' object has no attribute 'node.inst_base_A' I overcome this if I chain calls to getattr: &gt;&gt;&gt; getattr(getattr(b, 'node'), b.x) 'base_A' Out of curiosity: Is there a way to get an attribute of the Base class from grandchildren class besides doing two calls to getattr? Update: the reason I need it is I'm trying to: - Get an attribute fron grandparent class (either inst_baseA or inst_baseB) - Depending on an attribute on my instance (the value of x) So my code is actually something like: getattr(self, 'node.{}'.format(self.x)). I didn't explain it correctly at the first time, hope it makes more sense now.
has answer: http://stackoverflow.com/a/50724294
has comment: http://stackoverflow.com/comment/88477656
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50724341
has comment: http://stackoverflow.com/comment/88477600
type: AnsweredQuestion

http://stackoverflow.com/comment/88641125
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50817862
has text: @Skiffel as per your question, 'from the duplicates' means that tupple with 22 as FID is not even considered, as there is only 1 tupple with FID 22 for comparison so which would mean that it would not be dropped

http://stackoverflow.com/q/50760064
tagged with: arrays
accepted answer: http://stackoverflow.com/a/50760126
has body: I'm trying to divide one array by another, say a = np.array([[2., 2., 2., 2., 2.], [2., 2., 2., 2., 2.]]) b = np.array([[20., 16., 0., 10., nan], [5., 4., nan, 2., 0.]]) np.divide(a,b) will result in array([[ 0.1 , 0.125, inf, 0.2 , nan], [ 0.4 , 0.5 , nan, 1. , inf]]) and gives me the error RuntimeWarning: divide by zero encountered in true_divide, which doesn't come as a big surprise. I tried try: np.divide(a,b) except ZeroDivisionError: value = float('nan') which didn't work. Also an if-loop wasn't the solution: if b != 0: value = a / b else: value = float('nan') gives me the error 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'. But using if np.any(b != 0): as a first line instead, yields array([[ 10. , 8. , 0. , 5. , nan], [ 2.5, 2. , nan, 1. , 0. ]]) Same goes for if np.all(b != 0): I do understand that this must be due to the fact that np.any just returns a boolean True or False. Is there no other option as to replace inf-values that come up with np.divide(a,b) and accept the RuntimeWarning?
upvote count: 1
tagged with: divide-by-zero
answer count: 1
has answer: http://stackoverflow.com/a/50760126
tagged with: nan
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: Interpret division by zero as nan
score: 1
type: Question
tagged with: numpy

http://stackoverflow.com/a/50741988
upvote count: 2
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50741881
answers question: http://stackoverflow.com/q/50741881
type: Answer
has body: if guess == 'q' or 'quit': This statement will not work because you are trying to use a string as a boolean. The OR doesn't assume you want the exact same thing to happen like before it, you have to fill the condition again. if guess == 'q' or guess == 'quit': This will work because you are now getting a boolean out of the right side instead of just trying to use a string.
score: 1

http://stackoverflow.com/q/50826411
tagged with: macos
favorite count: 0
tagged with: terminal
has comment: http://stackoverflow.com/comment/88689563
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88657566
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I am trying to install the cassandra driver on my mac but every time I try: $sudo pip install cassandra-driver it throws an error of The directory '/Users/jigarmehta/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. even though i am using the admin account on my personal mac. I would be very thankful if anyone could help me tackle this please!
tagged with: cassandra
type: Question
has title: Unable to install Cassandra Driver on mac
score: 1

http://stackoverflow.com/a/50854403
has body: There is no looping needed at all. Also no zipping. Just do the following: a = np.array([1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1]) idx = np.where(a &lt; 0)[0][:3] np.where returns a tuple with the indices of the chosen condition. [0] indexes this tuple's first dimension (for a 1D-input array this is the only dimension) and [:3] slices these indices to only use the first three indices. If the occurrence of the first three consecutive negative numbers is needed, you can do the following: idx = np.where(np.diff(np.where(a &lt; 0), n=2) == 0)[1][0] + 2 This will give you the index of the first negative number of three consecutive negative numbers. If you want the indices of all three first negative consecutive numbers, do this: idx_start = np.where(np.diff(np.where(a &lt; 0), n=2) == 0)[1][0] + 2 idx = np.arange(idx_start, idx_start + 3) This will work as long as the first two numbers in the array are not part of three consecutive negative numbers.
score: 0
answers question: http://stackoverflow.com/q/50853691
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/56491267
has body: Systemd EnvironmentFile won't expand the variable inside it so your PATH will only look at /anaconda/bin if you just want to extend your PATH it's better to use ExecStart=/bin/bash -c 'PATH=/path/to/venv/bin/:$PATH exec /path/to/airflow scheduler this solved my issue with No such file or directory, because airflow couldn't find the binary that I was calling inside my bash operator.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50790965

http://stackoverflow.com/q/50801553
tagged with: python
has comment: http://stackoverflow.com/comment/88615832
upvote count: 4
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python-docx
has comment: http://stackoverflow.com/comment/88615860
has title: How to extract the body of a Section in a word document? Python
type: Question
has comment: http://stackoverflow.com/comment/88609412
tagged with: nlp
has body: I have a document with the following structure. INPUT: OUTPUT: Text Text Text I want to extract this body In the above image, I want to extract the text of Article I and II in Python. These Articles are actually sections, as you can see it on the left Navigation. Those are not raw text, I cannot select the Article, it is just like bullets. I tried the following code, which I found on StackOverflow. import docx document = docx.Document("rwi.docx") for paragraph in document.paragraphs: if paragraph.style.name == 'Heading 1': print(paragraph.text) But this just prints the Heading Title but not the body (text) of the title. How can I extract the body of the titles?
favorite count: 0
tagged with: python-3.x
score: 4
has comment: http://stackoverflow.com/comment/88615403

http://stackoverflow.com/q/50776545
tagged with: qt5
score: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88561254
type: UnansweredQuestion
has title: Upgrading Qt5 to version 5.6.2 throws error
tagged with: python
has comment: http://stackoverflow.com/comment/88561605
tagged with: qt
has comment: http://stackoverflow.com/comment/88561150
answer count: 0
tagged with: qt5.6
has comment: http://stackoverflow.com/comment/88561414
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/88560847
has comment: http://stackoverflow.com/comment/88560875
downvote count: 1
has body: I recently updated my ubuntu system and Qt5 library was updated to version 5.6.2 I had an existing ui file which was being used in my python file as : class Window(QtWidgets.QMainWindow): def __init__(self): super(Window,self).__init__() print("into init") uic.loadUi('main.ui',self) print("loaded main.ui") self.pushButton_2.clicked.connect(lambda: self.reset()) self.pushButton.clicked.connect(lambda: self.submit()) self.pushButton_3.clicked.connect(self.close) But now uic.loadUi('main.ui',self) gives a segmentation fault. I tried opening the ui file in designer and it opened with the following error Error while reparenting! Designer: A class name mismatch occurred when creating a widget using the custom widget factory registered for widgets of class KDialog. It returned a widget of class QDialog. QMetaProperty::read: Unable to handle unregistered datatype 'SelectionBehavior' for property 'QTabBar::selectionBehaviorOnRemove' appmenu-qt: registerWindow 206 "&amp;File" appmenu-qt: registerWindow 206 "&amp;Edit" appmenu-qt: registerWindow 206 "F&amp;orm" appmenu-qt: registerWindow 206 "&amp;View" appmenu-qt: registerWindow 206 "&amp;Settings" appmenu-qt: registerWindow 206 "&amp;Window" appmenu-qt: registerWindow 206 "&amp;Help" NOTE : the ui file does open as it is supposed to but I am not able to load it from my python function and get a Segmentation Fault
type: Question
has comment: http://stackoverflow.com/comment/88561121
has comment: http://stackoverflow.com/comment/88561429
has comment: http://stackoverflow.com/comment/88561128
has comment: http://stackoverflow.com/comment/88560773
has comment: http://stackoverflow.com/comment/88560628

http://stackoverflow.com/comment/88472127
has text: Yeah, it is possible and there is an easier way. But let's help out the community by asking this as a separate question and marking my answer as the correct answer if you found it to be helpful. Thanks
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50714764

http://stackoverflow.com/comment/100151431
type: AnswerComment
score: 0
type: Comment
has text: I have found that calling define_new_dimension before copying fields works.
comment on: http://stackoverflow.com/a/50948457

http://stackoverflow.com/comment/88673317
score: 0
type: AnswerComment
type: Comment
has text: Edited! Here is how this works: https://docs.python.org/3/reference/expressions.html#grammar-token-comp_operator
comment on: http://stackoverflow.com/a/50834640

http://stackoverflow.com/comment/88414716
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50702625
has text: This can be done so much more easily with a loop and (open) parenthesis counter
type: Comment

http://stackoverflow.com/q/50727595
tagged with: webdriver
type: Question
answer count: 2
has title: selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver.exe while opening chrome browser
has answer: http://stackoverflow.com/a/50740753
has comment: http://stackoverflow.com/comment/88474792
downvote count: 1
score: 8
favorite count: 0
upvote count: 9
possible better answer: http://stackoverflow.com/a/50740753
accepted answer: http://stackoverflow.com/a/50742641
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
has body: I have following environment at my local Chrome 67 Python 3.5.0 Selenium 3.12.0 I have downloaded chromedriver with version 2.39 I have .py file as follows from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome(executable_path="hromedriver.exe") driver.get('http://www.google.com') time.sleep(5) search_box = driver.find_element_by_name('q') search_box.send_keys('Python') search_box.submit() time.sleep(5) driver.quit() I am getting following error. C:\Python354\python.exe D:/formf.py Traceback (most recent call last): File "D:/PCPNDT/form.py", line 4, in &lt;module&gt; driver = webdriver.Chrome(executable_path="chromedriver.exe") # Optional argument, if not specified will search path. File "C:\Python354\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__ self.service.start() File "C:\Python354\lib\site-packages\selenium\webdriver\common\service.py", line 104, in start raise WebDriverException("Can not connect to the Service %s" % self.path) selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver.exe I also tried with other webdriver like geckodriver.exe still same error. Please help me out to resolve this error. Thanks!
has answer: http://stackoverflow.com/a/50742641
tagged with: selenium

http://stackoverflow.com/comment/88522797
type: AnswerComment
comment on: http://stackoverflow.com/a/50757085
type: Comment
has text: Dear Mathieu, and Vincent [[weights_dict.get(x, 0) for x in sublist.flatten()] for sublist in y_labeled] did the job. You are the best. P.s. Mathieu, your answer from above works as well like a charm
score: 0

http://stackoverflow.com/q/50714181
has comment: http://stackoverflow.com/comment/88439114
has comment: http://stackoverflow.com/comment/88439716
answer count: 0
has comment: http://stackoverflow.com/comment/88439750
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88439696
has comment: http://stackoverflow.com/comment/88439621
has comment: http://stackoverflow.com/comment/88438974
has title: Writing into consecutive rows in csv file through pandas python
type: Question
has comment: http://stackoverflow.com/comment/88439031
has comment: http://stackoverflow.com/comment/88437599
has comment: http://stackoverflow.com/comment/88439778
has comment: http://stackoverflow.com/comment/88439058
score: 0
has comment: http://stackoverflow.com/comment/88438940
has body: How do keep writing into consecutive rows using pandas.Dataframe? I have the following function that is called consecutively and writes the given values into a .csv file but the values are overwritten in the same row. Is there a way i can specify it to write into consecutive rows? def csv_writer(filename, OutputFolder): f = open(OutputFolder + '\Output_' + filename +'_LOG.txt') s = f.read() m = re.search("GHz\s+\=(.*)dB",s) if m: Lossval = float(m.group(1)) print("Loss Value for filename " + filename + "is :", Lossval) params['Lossval'] = Lossval n = re.search("Impedance\s+\=(.*)ohms",s) if n: Zc = float(n.group(1)) print("Impedance Value for filename " + filename + "is :", Zc) params['Zc'] = Zc print("The Target Impedance is", TargetImpedance) params['Target Impedance'] = TargetImpedance value.append(params.copy()) df = pd.DataFrame(value) df.to_csv('Values.csv') Val = 1/(abs(Zc - TargetImpedance) + 100*Lossval) return Val
tagged with: pandas

http://stackoverflow.com/a/50851671
has comment: http://stackoverflow.com/comment/125214765
answers question: http://stackoverflow.com/q/50846431
has comment: http://stackoverflow.com/comment/125200546
type: Answer
has comment: http://stackoverflow.com/comment/125204881
has comment: http://stackoverflow.com/comment/118318612
score: 18
upvote count: 19
has body: There is no such thing as a Python JSON object. JSON is a language independent file format that finds its roots in JavaScript, and is supported by many languages. If your YAML document adheres to the old 1.1 standard, i.e. pre-2009, you can use PyYAML as suggested by some of the other answers. If it uses the newer YAML 1.2 specification, which made YAML into a superset of JSON, you should use ruamel.yaml (disclaimer: I am the author of that package, which is a fork of PyYAML). import ruamel.yaml import json in_file = 'input.yaml' out_file = 'output.json' yaml = ruamel.yaml.YAML(typ='safe') with open(in_file) as fpi: data = yaml.load(fpi) with open(out_file, 'w') as fpo: json.dump(data, fpo, indent=2) which generates output.json: { "Section": { "heading": "Heading 1", "font": { "name": "Times New Roman", "size": 22, "color_theme": "ACCENT_2" } }, "SubSection": { "heading": "Heading 3", "font": { "name": "Times New Roman", "size": 15, "color_theme": "ACCENT_2" } }, "Paragraph": { "font": { "name": "Times New Roman", "size": 11, "color_theme": "ACCENT_2" } }, "Table": { "style": "MediumGrid3-Accent2" } } ruamel.yaml, apart from supporting YAML 1.2, has many PyYAML bugs fixed. You should also note that PyYAML's load() is also documented to be unsafe, if you don't have full control over the input at all times. PyYAML also loads scalar numbers 021 as integer 17 instead of 21 and converts scalar strings like on, yes, off to boolean values (resp. True, True and False).
has comment: http://stackoverflow.com/comment/118313897
downvote count: 1

http://stackoverflow.com/comment/88435295
has text: Thanks for your reasoning but still I wonder how value of variable ' i ' can be set as value of variable ' person '
type: Comment
comment on: http://stackoverflow.com/a/50704827
score: 0
type: AnswerComment

web-services
type: Tag
tags question: http://stackoverflow.com/q/50816080
tags question: http://stackoverflow.com/q/50808834
tags question: http://stackoverflow.com/q/50825093
tags question: http://stackoverflow.com/q/50789094
tag name: web-services

http://stackoverflow.com/comment/88468716
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50730489
score: 3
has text: As a side note, wouldn't it be a simpler API to just `@add_properties('a', 'b')` instead of requiring `_arg_names`? (Unless you need that class attribute for something else?)

http://stackoverflow.com/q/50787082
has answer: http://stackoverflow.com/a/50787172
has title: Sending JSON from Python to Node via child_process gets truncated if too long, how to fix?
has body: My Node &amp; Python backend is running just fine, but I now encountered an issue where if a JSON I'm sending from Python back no Node is too long, it gets split into two and my JSON.parse at the Node side fails. How should I fix this? For example, the first batch clips at ... [1137.6962355826706, -100.78015825640887], [773.3834338399517, -198 and the second one has the remaining few entries .201506231888], [-87276.575065248, -60597.8827676457], [793.1850250453127, -192.1674702207991], [1139.4465453979683, -100.56741252031816], [780.498416769341, -196.04064849430705]]} Do I have to create some logic on the Node side for long JSONs or is this some sort of a buffering issue I'm having on my Python side that I can overcome with proper settings? Here's all I'm doing on the python side: outPoints, _ = cv2.projectPoints(inPoints, np.asarray(rvec), np.asarray(tvec), np.asarray(camera_matrix), np.asarray(dist_coeffs)) # flatten the output to get rid of double brackets per result before JSONifying flattened = [val for sublist in outPoints for val in sublist] print(json.dumps({'testdata':np.asarray(flattened).tolist()})) sys.stdout.flush() And on the Node side: // Handle python data from print() function pythonProcess.stdout.on('data', function (data){ try { // If JSON handle the data console.log(JSON.parse(data.toString())); } catch (e) { // Otherwise treat as a log entry console.log(data.toString()); } });
upvote count: 3
accepted answer: http://stackoverflow.com/a/50787172
type: Question
tagged with: stdout
answer count: 1
downvote count: 0
tagged with: child-process
favorite count: 0
tagged with: python
tagged with: node.js
type: AnsweredQuestion
score: 3

string
tags question: http://stackoverflow.com/q/50811228
tags question: http://stackoverflow.com/q/50832667
tags question: http://stackoverflow.com/q/50777661
tags question: http://stackoverflow.com/q/50752067
tags question: http://stackoverflow.com/q/50758779
tags question: http://stackoverflow.com/q/50803581
tags question: http://stackoverflow.com/q/50750368
tags question: http://stackoverflow.com/q/50778302
tags question: http://stackoverflow.com/q/50727759
tags question: http://stackoverflow.com/q/50843370
tags question: http://stackoverflow.com/q/50848877
tags question: http://stackoverflow.com/q/50742864
tags question: http://stackoverflow.com/q/50801041
tags question: http://stackoverflow.com/q/50742132
tags question: http://stackoverflow.com/q/50760319
tags question: http://stackoverflow.com/q/50829364
tags question: http://stackoverflow.com/q/50843251
tags question: http://stackoverflow.com/q/50753043
tags question: http://stackoverflow.com/q/50723416
tags question: http://stackoverflow.com/q/50846719
tags question: http://stackoverflow.com/q/50779612
tags question: http://stackoverflow.com/q/50783087
tag name: string
tags question: http://stackoverflow.com/q/50841713
tags question: http://stackoverflow.com/q/50729581
tags question: http://stackoverflow.com/q/50819002
tags question: http://stackoverflow.com/q/50748906
tags question: http://stackoverflow.com/q/50829381
tags question: http://stackoverflow.com/q/50783262
tags question: http://stackoverflow.com/q/50785356
tags question: http://stackoverflow.com/q/50810019
tags question: http://stackoverflow.com/q/50757890
tags question: http://stackoverflow.com/q/50804061
tags question: http://stackoverflow.com/q/50744369
tags question: http://stackoverflow.com/q/50751339
type: Tag
tags question: http://stackoverflow.com/q/50845987
tags question: http://stackoverflow.com/q/50840822
tags question: http://stackoverflow.com/q/50830001
tags question: http://stackoverflow.com/q/50782317
tags question: http://stackoverflow.com/q/50761157
tags question: http://stackoverflow.com/q/50731702
tags question: http://stackoverflow.com/q/50848178
tags question: http://stackoverflow.com/q/50777479
tags question: http://stackoverflow.com/q/50775529
tags question: http://stackoverflow.com/q/50820844
tags question: http://stackoverflow.com/q/50840416
tags question: http://stackoverflow.com/q/50772448
tags question: http://stackoverflow.com/q/50787091
tags question: http://stackoverflow.com/q/50721847
tags question: http://stackoverflow.com/q/50806693
tags question: http://stackoverflow.com/q/50716144
tags question: http://stackoverflow.com/q/50702058
tags question: http://stackoverflow.com/q/50850120
tags question: http://stackoverflow.com/q/50772780
tags question: http://stackoverflow.com/q/50762163
tags question: http://stackoverflow.com/q/50730813
tags question: http://stackoverflow.com/q/50841823
tags question: http://stackoverflow.com/q/50824555
tags question: http://stackoverflow.com/q/50700617
tags question: http://stackoverflow.com/q/50702625
tags question: http://stackoverflow.com/q/50756522
tags question: http://stackoverflow.com/q/50820753
tags question: http://stackoverflow.com/q/50839856
tags question: http://stackoverflow.com/q/50762877
tags question: http://stackoverflow.com/q/50797289
tags question: http://stackoverflow.com/q/50746538
tags question: http://stackoverflow.com/q/50752936
tags question: http://stackoverflow.com/q/50783745

http://stackoverflow.com/comment/88694775
score: 0
type: AnswerComment
has text: @AlexT The vector I gave works correctly: https://ideone.com/RuLPLB . Response `hello`
type: Comment
comment on: http://stackoverflow.com/a/50844957

http://stackoverflow.com/comment/123576950
has text: @WillemVanOnsem I will check it and update.
comment on: http://stackoverflow.com/a/61891151
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/53324605
has body: this snippet will add directory containing the tac file to python path import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__))) from foo.bar import Bar
answers question: http://stackoverflow.com/q/50803916
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/68594285
has body: Cufflinks import problem solved Install the module: pip install cufflinks First import sys module: import sys and then import cufflinks: import cufflinks I hope it works for you too..
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50713726
downvote count: 0

http://stackoverflow.com/q/50844431
has comment: http://stackoverflow.com/comment/88693909
answer count: 1
tagged with: counter
has body: i'm using a regex to find the strings corresponding to the keys of a counter and i'm trying to access this counter with a variable that contains one of those strings. It is identical to the key but when i use the variable instead of a key directly, the count returns an integer equal to zero. For example, the variable ngram_b contains the string ('long,') which is a key in my counter. With the code below, proba_b will be equal to zero and I get a division by zero error, but proba_b = probas.ngrams[order][('long,')] returns the correct answer 0.006. for ngram, count in joint_probas.items(): ngram_b = re.search(r'(?&lt;=\), ).*\)(?=\))',str(ngram),re.DOTALL) ngram_b= ngram_b.group(0) order = int(ngram_b.count('\'')/2) proba_b = probas.ngrams[order][ngram_b] if proba_b == 0 : print(ngram_b, order) proba_joint = joint_probas[ngram] condi_prob[ngram] = proba_joint / proba_b This is really weird to me and there must be something that I don't understand about how dictionaries work, hopefully someone will see what i'm missing. EDIT : Joint_probas is a counter containing joint probabilities of two ngrams, format of the key (for a one-gram with a bi-gram) : (('word1',), ('word2', 'word3')). Probas is a counter containing the probability of all ngrams, format is ('word2', 'word3') for a bigram. I'm trying to look up the single probability of the second term in each entry in joint_probas to compute conditional probabilities. Thank you
has title: Python : Unable to return correct count when searching counter with variable as key
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88693043
tagged with: dictionary
has answer: http://stackoverflow.com/a/50847391
accepted answer: http://stackoverflow.com/a/50847391
has comment: http://stackoverflow.com/comment/88694824
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88692824

http://stackoverflow.com/comment/88450020
comment on: http://stackoverflow.com/a/50720736
type: AnswerComment
has text: Thanks! Can you comment about the complexity of this operation? I.e. how fast is it? (I ask because I did something similar before, and the time increased with size of the file, i.e. the number of entries in each datasets, rather than with the number of datasets.)
score: 0
type: Comment

http://stackoverflow.com/comment/88591036
has text: maybe if `=` in line print `line.split('=')[1]`?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50792565
score: 1

http://stackoverflow.com/a/50746370
has comment: http://stackoverflow.com/comment/88500474
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50746266
has comment: http://stackoverflow.com/comment/88500389
answers question: http://stackoverflow.com/q/50746266
type: Answer
upvote count: 2
has body: just put property decorator behind the func some useful docs @property def distance(self): ... @property def slope(self): ...

http://stackoverflow.com/comment/88624163
has text: related: [Ляп в Питоне: x + 1.0 < x](https://ru.stackoverflow.com/q/748183/23044) (see links there)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50699194

http://stackoverflow.com/q/50716347
favorite count: 0
tagged with: datetime
tagged with: python
type: AnsweredQuestion
upvote count: 2
score: 1
has body: When I tried to utilize datetime module In [31]: datetime.now() Out[31]: datetime.datetime(2018, 6, 6, 8, 59, 35, 49991) In [32]: str(datetime.now()) Out[32]: '2018-06-06 08:59:45.633486' I intend to change to my local time but were lost in dozens of timezone modules and third-party package as pytz. How could I change betweens timezones in a straight forward way?
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50717039
has title: Change between timezones
has comment: http://stackoverflow.com/comment/88442742
answer count: 1
accepted answer: http://stackoverflow.com/a/50717039

http://stackoverflow.com/comment/88508955
score: 0
type: AnswerComment
type: Comment
has text: oh wow so you can actually embed functional logic within dictionaries?! would this work with python 2.7 too?
comment on: http://stackoverflow.com/a/50750479

http://stackoverflow.com/a/50800931
upvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88607988
has comment: http://stackoverflow.com/comment/88612168
has comment: http://stackoverflow.com/comment/88608289
accepted answer of: http://stackoverflow.com/q/50800769
has comment: http://stackoverflow.com/comment/88608322
has comment: http://stackoverflow.com/comment/88609001
has comment: http://stackoverflow.com/comment/88610057
type: Answer
has comment: http://stackoverflow.com/comment/88609560
has comment: http://stackoverflow.com/comment/88608656
has comment: http://stackoverflow.com/comment/88608866
has comment: http://stackoverflow.com/comment/88609437
has body: The list is here: Just peek what you need. Firstly you have to type name (better full name) in input field, then wait a bit(2-3 seconds) before the list will appear, then you can locate your element from dropdown lost and click on it. For example: ville = browser.find_element_by_id('city') ville.send_keys("Paris (75001)") driver.implicitly_wait(2) # waits 2 sec element = driver.find_element_by_xpath("//*[contains(text(), 'Paris (75001)')]") # locate the dropdown elem element.click() # click on it
downvote count: 1
has comment: http://stackoverflow.com/comment/88608811
has comment: http://stackoverflow.com/comment/88608733
has comment: http://stackoverflow.com/comment/88609632
score: -1
has comment: http://stackoverflow.com/comment/88608533
has comment: http://stackoverflow.com/comment/88612129
answers question: http://stackoverflow.com/q/50800769
has comment: http://stackoverflow.com/comment/88609148

http://stackoverflow.com/q/50699713
has title: Python: Select Rows by value in large dataframe
tagged with: pandas
score: 2
answer count: 1
has answer: http://stackoverflow.com/a/50700348
downvote count: 0
favorite count: 0
has body: Given a data frame df: Column A: [0, 1, 3, 4, 6] Column B: [0, 0, 0, 0, 0] The goal is to conditionally replace values in column B. If column A's values exist in a set assginedToA, we replace the corresponding values in column B with a constant b. For example: if b=1 and assignedToA={1,4}, the result would be Column A: [0, 1, 3, 4, 6] Column B: [0, 1, 0, 1, 0] My code for finding the A values and write B values into it looks like this: df.loc[df['A'].isin(assignedToA),'B']=b This code works, but it is really slow for a huge dataframe. Do you have any advice, how to speed this process up? The dataframe df has around 5 Million rows and assignedToA has a maximum of 7 values.
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50700348
upvote count: 2
type: Question
tagged with: performance
tagged with: dataframe

http://stackoverflow.com/q/50787563
has answer: http://stackoverflow.com/a/50787581
accepted answer: http://stackoverflow.com/a/50787581
tagged with: django-forms
type: Question
has body: I'm trying to get the name of each option associated with a particular checkbox element. For example when I allow django to render the checkbox it produces Care Parking Now I'm trying to render the forms manually and I want to find a way of displaying 'Care Parking'. This is what I have done but it doesn't display anything {% for box in form.amenities %} {{ box.html_name }} {% endfor %}
has title: Get checkbox option names when redndering manually
score: 0
has comment: http://stackoverflow.com/comment/88581446
answer count: 1
has comment: http://stackoverflow.com/comment/88593106
tagged with: django
tagged with: python
type: AnsweredQuestion

out-of-memory
tags question: http://stackoverflow.com/q/50842783
tags question: http://stackoverflow.com/q/50709371
tags question: http://stackoverflow.com/q/50780454
type: Tag
tag name: out-of-memory

http://stackoverflow.com/comment/88619248
score: 0
type: AnswerComment
has text: yes the first answers works perfectly thanks!!! Is there a way to label the x-axis correctly? Like 'Monday 1 Am' or did i lose this information on the way
type: Comment
comment on: http://stackoverflow.com/a/50806255

http://stackoverflow.com/q/50730946
downvote count: 0
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/88469588
favorite count: 0
has comment: http://stackoverflow.com/comment/88470255
has comment: http://stackoverflow.com/comment/88469633
tagged with: python
has answer: http://stackoverflow.com/a/50731133
score: 2
has title: pip uninstall fails with "owned by OS" - even under sudo
possible better answer: http://stackoverflow.com/a/50731001
upvote count: 2
has answer: http://stackoverflow.com/a/50731001
tagged with: pip
has body: I'm working on a DevOps project for a client who's using Python. Though I never used it professionally, I know a few things, such as using virtualenv and pip - though not in great detail. When I looked at the staging box, which I am trying to prepare for running a functional test suite, I saw chaos. Tons of packages installed globally, and those installed inside a virtualenv not matching the requirements.txt of the project. OK, thought I, there's a lot of cleaning up. Starting with global packages. However, I ran into a problem at once: ➜ ~ pip uninstall PyYAML Not uninstalling PyYAML at /usr/lib/python2.7/dist-packages, owned by OS OK, someone must've done a 'sudo pip install PyYAML'. I think I know how to fix it: ➜ ~ sudo pip uninstall PyYAML Not uninstalling PyYAML at /usr/lib/python2.7/dist-packages, owned by OS Uh, apparently I don't. A search revealed some similar conflicts caused by users installing packages bypassing pip, but I'm not convinced - why would pip even know about them, if that was the case? Unless the "other" way is placing them in the same location pip would use - but if that's the case, why would it fail to uninstall under sudo?
has comment: http://stackoverflow.com/comment/88469683
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88470102
accepted answer: http://stackoverflow.com/a/50731133
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/88470155

http://stackoverflow.com/comment/89637585
comment on: http://stackoverflow.com/a/50750079
has text: I am not using pandas. would be nice if you could provide a solution without using pandas here.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50803149
answers question: http://stackoverflow.com/q/50803148
has body: Explanation First of all, using conda to Install Bob is much easier and is the supported way to install Bob. Please consider again to use conda to install Bob before continuing. Bob is written in a mix of C++ and Python and links to a lot of different C/C++ libraries and Conda is a language-agnostic binary package manager which would handle all these. If you want to install Bob from source, you first need to install its dependencies manually. The dependencies for each package is listed inside the conda recipe of each Bob package. From its conda recipe, you have to install (if they exist) requirements:build, requirements:host, requirements:run, and test:requires. These packages are conda packages and not pip packages; some of them could be pip packages (the names could be different) and some of them could be just a C/C++ library that you should install with your system's package manager (or from source). For example, bob.extension's conda recipe is here: requirements: host: - python {{ python }} - setuptools {{ setuptools }} run: - python - setuptools - click - click-plugins test: requires: - bob-devel {{ bob_devel }}.* - nose - coverage - sphinx - sphinx_rtd_theme - boost - cmake - pkg-config - freetype - libblitz - numpy - {{ compiler('c') }} - {{ compiler('cxx') }} - bob.buildout Parsing this recipe would mean that you would need to install: boost, cmake, pkg-config, freetype, libblitz, C and C++ compilers, and probably numpy with your system's package manager first and then install click, click-plugins, nose, coverage, sphinx, sphinx_rtd_theme, and bob.buildout with pip. (You can also look into requirements.txt and test-requirements.txt of Bob packages for the pip package names of dependencies but that may not be updated to match its conda recipe). bob-devel is a conda meta-package which you do not need to install when not using conda. This will setup your environment to be ready to compile (if needed), install, and test bob.extension. After setting up the enviro…
type: Answer
upvote count: 5
score: 5
downvote count: 0

http://stackoverflow.com/q/50789537
has comment: http://stackoverflow.com/comment/88585284
has answer: http://stackoverflow.com/a/50792363
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50789569
has comment: http://stackoverflow.com/comment/88585425
tagged with: geckodriver
has comment: http://stackoverflow.com/comment/88586226
tagged with: python
has comment: http://stackoverflow.com/comment/88586210
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50789569
tagged with: selenium
has title: "WebDriverException: 'geckodriver' executable needs to be in PATH" error while 'driver = webdriver.Firefox()' through Selenium
type: Question
has body: To the experts out there, I ran the following code in Python using Spyder (on Mac): &gt;from selenium import webdriver &gt;from selenium.webdriver.common.keys import Keys &gt;driver = webdriver.Firefox() and I get the following errors: &gt;Traceback (most recent call last): &gt; &gt; File "&lt;ipython-input-4-fd567e24185f&gt;", line 1, in &lt;module&gt; &gt; driver = webdriver.Firefox() &gt; &gt; File "/Users/liminfang/anaconda3/lib/python3.6/site-&gt;packages/selenium/webdriver/firefox/webdriver.py", line 160, in __init__ &gt; self.service.start() &gt; &gt; File "/Users/liminfang/anaconda3/lib/python3.6/site-&gt;packages/selenium/webdriver/common/service.py", line 83, in start &gt; os.path.basename(self.path), self.start_error_message) &gt; &gt;WebDriverException: 'geckodriver' executable needs to be in PATH. Note that I have already added 'geckodriver' executable to the PATH by executing &gt;export PATH=$PATH:/Users/liminfang/anaconda3/geckodriver in Terminal. And I restarted my computer, but the error persists. Anyone know what's going on here? Please help. Thank you!
tagged with: firefox
possible better answer: http://stackoverflow.com/a/50792363

http://stackoverflow.com/q/50778410
linked to: http://stackoverflow.com/q/8575062
answer count: 4
has answer: http://stackoverflow.com/a/50778740
favorite count: 0
accepted answer: http://stackoverflow.com/a/50778740
upvote count: 1
tagged with: plot
possible better answer: http://stackoverflow.com/a/77987581
type: AnsweredQuestion
score: 1
has body: I am learning how to use matplotlib now. From what I read, it seems the plot() function should be creating the plot and show() should display it. However, when I run the following, the display occurs on the plt.plot() line, not plt.show(): In [1]: import matplotlib.pyplot as plt In [2]: %matplotlib inline In [3]: plt.plot() Out[3]: [] ￼In [4]: plt.show() The output above displays the empty plot after plot.plot(), but plt.show() does nothing. I am using Spyder with the iPython console. Running the code through the editor yields the same result. Am I misunderstanding what each function does individually or if I am not getting the correct results. Apologies if this is a stupid question. For a bit of clarity: My problem is not that the plot does not display. The plot displays perfectly! My issue is that so far, it seems the plt.show() function does not do anything. I can run my program, create a plot with plt.plot(x,y), change parameters such as the labels, and it displays as intended even if I completely omit plt.show(). plt.show() seems to have no functionality as it stands which is my issue.
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88563704
type: Question
has comment: http://stackoverflow.com/comment/88563786
downvote count: 0
has answer: http://stackoverflow.com/a/76326333
has comment: http://stackoverflow.com/comment/88563694
has title: Matplotlib displaying plots on plot() instead of show() in console
has answer: http://stackoverflow.com/a/77987581
has answer: http://stackoverflow.com/a/50778788
tagged with: display
tagged with: spyder
has comment: http://stackoverflow.com/comment/88563912
tagged with: python

header
type: Tag
tags question: http://stackoverflow.com/q/50732157
tag name: header
tags question: http://stackoverflow.com/q/50818250
tags question: http://stackoverflow.com/q/50767910

http://stackoverflow.com/q/50836535
tagged with: pip
has comment: http://stackoverflow.com/comment/88680012
type: AnsweredQuestion
has title: pip does not work, TTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded
tagged with: python-3.6
type: Question
linked to: http://stackoverflow.com/q/25981703
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51132608
has comment: http://stackoverflow.com/comment/88703428
accepted answer: http://stackoverflow.com/a/51132608
tagged with: python
has body: I try this: pip install numpy I get this: The directory '/home/teoman/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. The directory '/home/teoman/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting numpy Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/numpy/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/numpy/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/numpy/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/numpy/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/numpy/ Could not fetch URL https://pypi.python.org/simple/numpy/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/numpy/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping C…
has comment: http://stackoverflow.com/comment/88719305

http://stackoverflow.com/q/50705252
has comment: http://stackoverflow.com/comment/88424288
score: 1
has comment: http://stackoverflow.com/comment/88434025
has title: How to locate the certain value of an item using xpath?
type: Question
accepted answer: http://stackoverflow.com/a/50714099
answer count: 1
downvote count: 0
has body: I've written a script in python in combination with lxml library using xpath to parse the value of a certain apartment from a webpage. The name of that aparment visible in that site is Eden Tolly Cascades and the value of it is 15.92 to 36.28 Lac. How can i parse the value of it mentioning that apartment name within my xpath? I've tried like below and it is working without any issues. However, ain't there any cleaner approach to achieve the same? import requests from lxml.html import fromstring url = "https://www.99acres.com/ppc-2515-residential-apartment-mailer" res = requests.get(url) tree = fromstring(res.text) item = tree.xpath("//h1[contains(.,'Eden Tolly')]/../../../following::div//span/strong/text()")[0] print(item) This is one such container: &lt;div class="pro-text"&gt; &lt;div class="product-text-box"&gt; &lt;div class="product-heading"&gt; &lt;span&gt;&lt;img src="https://newprojects.99acres.com/projects/eden_group/eden_tolly_cascades/ln9rkpsb.jpg"&gt; &lt;h1 class="font-size15"&gt;Eden Tolly Cascades&lt;p&gt;Kabardanga&lt;/p&gt;&lt;/h1&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="product-text-box"&gt; &lt;ul class="product-lrg-box"&gt; &lt;li&gt; &lt;span&gt;&lt;strong&gt;&lt;span class="rupee-font"&gt;₹ &amp;nbsp;&lt;/span&gt;15.92 to 36.28 Lac&lt;/strong&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;strong&gt;549-1251 SQFT&lt;/strong&gt;&lt;/li&gt; &lt;li&gt;&lt;strong&gt;1-3 BHK&lt;/strong&gt;&lt;/li&gt; &lt;li style="width:20% !important;"&gt;&lt;strong&gt;New Launch&lt;/strong&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="tabs" class="tab-link tabs-menu tabs-menu-new"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#304355broch"&gt;e-Brochure&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#304355amn"&gt;Amenities&lt;/a&gt;&lt;/li&gt; &lt;!-- &lt;li style="width:20% !important;"&gt;&lt;a href="#304355floor"&gt;Floor Plan&lt;/a&gt;&lt;/li&gt;--&gt; &lt;li style="width:20% !important;"&gt;&lt;a href="#304355dir"&gt;Directions&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/…
has comment: http://stackoverflow.com/comment/88425119
tagged with: lxml
tagged with: python
favorite count: 0
tagged with: xpath
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50714099
upvote count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/88425405
has comment: http://stackoverflow.com/comment/88435850
type: AnsweredQuestion

http://stackoverflow.com/comment/88418466
has text: @cwallenpoole unfortunately values are still being returned as None
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50704445
type: Comment

http://stackoverflow.com/comment/88464449
type: Comment
comment on: http://stackoverflow.com/a/50728192
type: AnswerComment
has text: This moves a friday to the previous friday rather than leave it unchanged
score: 0

uwsgi
tags question: http://stackoverflow.com/q/50793624
tag name: uwsgi
type: Tag

http://stackoverflow.com/q/50807175
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50807495
accepted answer: http://stackoverflow.com/a/50807495
has comment: http://stackoverflow.com/comment/88620285
tagged with: python
has comment: http://stackoverflow.com/comment/88620442
has title: How to slice groups to nearest nth observation
type: AnsweredQuestion
has body: I have a time series dataset that looks something like this: Time ID X_Pos Y_Pos 1 1 150 300 2 1 160 310 3 1 156 500 4 2 300 439 5 2 200 500 6 3 500 320 7 3 400 230 8 3 500 540 9 3 450 600 10 3 400 600 I need to essentially round the number of observations within each ID to the nearest nth multiple, in this example, I will use the nearest 2. This should result in a dataset that looks like this: Time ID X_Pos Y_Pos 1 1 150 300 2 1 160 310 4 2 300 439 5 2 200 500 6 3 500 320 7 3 400 230 8 3 500 540 9 3 450 600 As you can see, the exact number of rows remaining in each group differs depending on the initial size of the group, but always remains a multiple of 2. I've gotten pretty close to getting what I need with the code below, but am missing the final step (noted by the question marks): grouped = data.groupby('ID') timesteps = 2 def round_down(num, divisor): return num - (num%divisor) endSlice = pd.DataFrame(round_down(grouped.size(), timesteps)).reset_index() slicedData = data.groupby('ID', as_index = False).apply(lambda x: x.iloc[0: ???????]) EDIT The question is, what do I need to put in the portion of the code where the question marks are in order to achieve the desired dataset (i.e., the second dataset), OR, is there a more efficient way to achieve this dataset? I think that the portion of the code where the question marks are just needs to refer to the endSlice value for each ID, but I'm pretty new to python and an lacking some knowledge on things like this. Thanks in advance for any help and apologies if this has been answered elsewhere.
type: Question
has comment: http://stackoverflow.com/comment/88620369
has comment: http://stackoverflow.com/comment/88620409
score: 0

http://stackoverflow.com/comment/93593879
has text: @2ps, please update with specifics of advantages of fabric over ansible. I would love to get back to playing with it in that case :-)
comment on: http://stackoverflow.com/a/51397324
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50845697
type: Answer
score: 140
has comment: http://stackoverflow.com/comment/101140508
has comment: http://stackoverflow.com/comment/101139705
has comment: http://stackoverflow.com/comment/101143339
has comment: http://stackoverflow.com/comment/109786325
has comment: http://stackoverflow.com/comment/101145983
has comment: http://stackoverflow.com/comment/101144752
has comment: http://stackoverflow.com/comment/88728862
has comment: http://stackoverflow.com/comment/109751502
has comment: http://stackoverflow.com/comment/88760668
has comment: http://stackoverflow.com/comment/88733763
accepted answer of: http://stackoverflow.com/q/50796024
has body: First of all, I assume that you call features the variables and not the samples/observations. In this case, you could do something like the following by creating a biplot function that shows everything in one plot. In this example, I am using the iris data. Before the example, please note that the basic idea when using PCA as a tool for feature selection is to select variables according to the magnitude (from largest to smallest in absolute values) of their coefficients (loadings). See my last paragraph after the plot for more details. Overview: PART1: I explain how to check the importance of the features and how to plot a biplot. PART2: I explain how to check the importance of the features and how to save them into a pandas dataframe using the feature names. PART 1: import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.decomposition import PCA import pandas as pd from sklearn.preprocessing import StandardScaler iris = datasets.load_iris() X = iris.data y = iris.target #In general a good idea is to scale the data scaler = StandardScaler() scaler.fit(X) X=scaler.transform(X) pca = PCA() x_new = pca.fit_transform(X) def myplot(score,coeff,labels=None): xs = score[:,0] ys = score[:,1] n = coeff.shape[0] scalex = 1.0/(xs.max() - xs.min()) scaley = 1.0/(ys.max() - ys.min()) plt.scatter(xs * scalex,ys * scaley, c = y) for i in range(n): plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5) if labels is None: plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center') else: plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center') plt.xlim(-1,1) plt.ylim(-1,1) plt.xlabel("PC{}".format(1)) plt.ylabel("PC{}".format(2)) plt.grid() #Call the function. Use only the 2 PCs. myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :])) plt.show() Visualize what's going on using the biplot Now, the importance of each feature is reflected by the magnit…
has comment: http://stackoverflow.com/comment/101141918
answers question: http://stackoverflow.com/q/50796024
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88733860
downvote count: 0
has comment: http://stackoverflow.com/comment/88728711
upvote count: 140
has comment: http://stackoverflow.com/comment/109760946

http://stackoverflow.com/q/50849592
tagged with: python
has body: I have a product names toy. there is a series of discounts for its sale. customer buy a toy a duration, when reach expire_time he will renew it. so the toy instance have pay_time and expire_time fields: class Toy(models.Model): pay_time = DateTimeField() expire_time = DateTimeField() when a customer have a toy instance, the pay_time is 2018.01.01, and expire_time is 2018.05.01. now when time reaches 2018.05.01, the customer will renew the product. the renew strategies discounts list are bellow: renew_discounts_list: [ { discount: 0.20, min_mon: 1, max_mon:3 }, { discount: 0.15, min_mon: 4, max_mon:6 }, .... ] if the customer want to renew 17 months, it is very complex for calculation. I want to a results of discounts, this is my required output: [ { 'months': 1, 'disconts': 0.15 #(4~6: 0.15) }, { 'months': 3, 'disconts': 0.10 #(7~9: 0.10) }, .... ] the results' total months is 17. I tried use judge for the solution, but its not a good solutions for it.
has comment: http://stackoverflow.com/comment/88706379
has answer: http://stackoverflow.com/a/50852624
type: Question
has title: Get the discounts list by given discount strategies and renew months
tagged with: math
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/88725815
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50722829
has text: Dammit, you're right. My apologies for abusing your time and expertise like this. There's data missing in that file which is potentially a significant problem for us - happy I caught it now rather than later!

http://stackoverflow.com/q/50809513
tagged with: machine-learning
tagged with: tensorflow
type: Question
score: 0
has answer: http://stackoverflow.com/a/50809957
answer count: 1
has title: how to pool different shaped convolutional layer outputs to a fixed shape to pass for Fully connected layer
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has body: I have different sized input images, and I am passing them through the Conv layers in a CNN after which I should connect the Conv outputs to a Fully Connected Layer for classification. Since the process has to be vectorised the outputs have to be of same shape so that a batch of images could be used for forward pass. And hence this problem of having same shape for all images at the input of Fully Connected layer. But since my input images are of different shape my final Conv layer gives different shaped outputs, how do I pool/reshape the different shaped outputs from Last Conv Layer to a fixed shape so that they can be connected to immediate FCN layer? Also, I have considered reshaping images to fixed size before processing but have performance[accuracy] issues as my input images vary in large[So, trying this].
tagged with: conv-neural-network

http://stackoverflow.com/comment/88448772
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50719857
has text: Sorry, I'm new in python. I did the "df.groupby('name')" and I get the output with grouping of name, but the actual I want to do is groupby with 3 column, which is 'name', 'city', 'county'. Then add internal_id for the same group like the **output file** that I mentioned. May you guide me with an example python code to let me try out? Thank!

http://stackoverflow.com/comment/88587333
type: QuestionComment
has text: Remember to `conn.commit()`, before you close it.
comment on: http://stackoverflow.com/q/50790682
score: 0
type: Comment

http://stackoverflow.com/q/50845199
tagged with: amazon-s3
score: 1
type: Question
downvote count: 0
has body: Need help on how to incorporate authentication header , when download from S3 object store using python. I found a few articles using both pycurl and response modules, but none worked for me. FYI not able to use `boto' module as the end container where the script will run has python that does not have the module. Here is a shell code which works seamless for upload, but i need to make the call from python as this will be part of a larger code which downloads from s3 object store and massage the data before use. ================ bucket=success file=sample.csv contentType="text" dateValue=`date -R` s3Key=key s3Secret=secret resource="/${bucket}/${file}" stringToSign="PUT\n\n${contentType}\n${dateValue}\n${resource}" signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${s3Secret} -binary | base64` curl -L -X PUT -T "${file}" \ -H "Host: testurl.com/${bucket}" \ -H "Date: ${dateValue}" \ -H "Content-Type: ${contentType}" \ -H "Authorization: AWS ${s3Key}:${signature}" \ http://testurl.com/${bucket}/${file} ================ Appreciate any insight using python only please. FYI version I am using is python 2.7. thank you RD
tagged with: python
favorite count: 0
has title: python download/upload api s3(with authorization)
tagged with: download
answer count: 0
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/88458165
has text: `args=(l)` does not do what you think it does : https://stackoverflow.com/q/12876177/5069029
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50724901

http://stackoverflow.com/comment/88695762
type: QuestionComment
has text: When it is hist(), it is working. Output: https://imgur.com/a/FHjnGrz
comment on: http://stackoverflow.com/q/50845998
score: 0
type: Comment

http://stackoverflow.com/q/50760319
tagged with: string-conversion
score: 0
answer count: 1
tagged with: string
has body: I'm wondering how I can translate a Caesar cipher code into a normal text. I have already done translating normal text into Cipher code, and this is how I did it: def conversion(chr,ord): for letter in stringinput: cipheresult = chr(ord(letter) + int(shiftnumber)) print(cipheresult) So I'm wondering how I could do the complete opposite of this and translate it back to what would have been the stringinput. The shiftnumber variable is determined by what the user is inputting into the program, by the way. Thanks
has comment: http://stackoverflow.com/comment/88528176
tagged with: python
has comment: http://stackoverflow.com/comment/88528042
type: AnsweredQuestion
tagged with: caesar-cipher
has title: How could I translate Caesar cipher code back to normal in Python?
type: Question
has answer: http://stackoverflow.com/a/50764896
has comment: http://stackoverflow.com/comment/88529608
accepted answer: http://stackoverflow.com/a/50764896
tagged with: function

http://stackoverflow.com/q/50825918
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50826081
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88657714
score: 0
has answer: http://stackoverflow.com/a/50826081
tagged with: pygame
has answer: http://stackoverflow.com/a/50826070
accepted answer: http://stackoverflow.com/a/50826070
linked to: http://stackoverflow.com/q/19158339
has title: gameExit not defined Error
tagged with: python
has body: I am trying to understand how to define exiting in pygame. I am making a car game where you have to avoid obstacles from coming into contact with the car. My error is line 71, in &lt;module&gt; while not gameExit: NameError: name 'gameExit' is not defined My code is import pygame import time import random pygame.init() display_width = 800 display_height = 600 black = (0,0,0) white = (255, 255, 255) red = (255,0,0) car_width = 73 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption("Hi There Fucker") clock = pygame.time.Clock() carImg = pygame.image.load("mycar.png") def things_dodged(count): font = pygame.font.SysFont(None, 25) text = font.render("Dodged: " + str(count), True, black) gameDisplay.blit(text, (0,0)) def things(thingx, thingy, thingw, thingh, color): pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh]) def car(x,y): gameDisplay.blit(carImg, (x,y)) def text_objects(text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def message_display(text): largeText = pygame.font.Font("freesansbold.ttf", 115) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = ((display_width/2), (display_height/2)) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(2) game_loop() def crash(): message_display("You crashed") def game_loop(): x = (display_width * 0.1) y = (display_height * 0.3) x_change = 0 thing_starx = random.randrange(0, display_width) thing_starty = -600 thing_speed = 7 thing_width = 100 thing_height = 100 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit()

http://stackoverflow.com/comment/88447414
score: 0
type: Comment
has text: This is normal: you read `fname` and `lname` after your loop into `values`. At this time, they contain the last content they got within the loop. You should write every `fname`/`lname` pair already in the loop into your database or collect them in an array and finally write this one.
type: QuestionComment
comment on: http://stackoverflow.com/q/50719532

http://stackoverflow.com/a/50748348
answers question: http://stackoverflow.com/q/50747681
score: 4
has comment: http://stackoverflow.com/comment/88509332
has body: Looking at your dataframe the counter columns seems unnecessary. Let us instead use the popularity column and make one mean and one count column: import pandas as pd import numpy as np np.random.seed(444) names = [ 'Robert Baratheon', 'Jon Snow', 'Daenerys Targaryen', 'Theon Greyjoy', 'Tyrion Lannister' ] df = pd.DataFrame({ 'actor': np.random.choice(names, size=10, p = [0.2,0.2,0.2,0.1,0.3]), 'director': np.random.choice(names, size=10, p = [0.4,0.1,0.1,0.1,0.3]), 'popularity': np.random.randint(0,100, size=10), 'counter': 0 }) df2 = df.groupby(['actor','director'])['popularity']\ .agg(['count', 'mean'])\ .reset_index()\ .sort_values(by='mean', ascending=False) print(df2) Returns: actor director count mean 0 Jon Snow Robert Baratheon 2 53.5 5 Tyrion Lannister Tyrion Lannister 2 49.0 2 Robert Baratheon Tyrion Lannister 2 48.5 1 Robert Baratheon Jon Snow 2 40.5 4 Theon Greyjoy Tyrion Lannister 1 13.0 3 Theon Greyjoy Robert Baratheon 1 7.0
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50747681
has comment: http://stackoverflow.com/comment/88504605
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88516907
type: Answer
has comment: http://stackoverflow.com/comment/88504467
has comment: http://stackoverflow.com/comment/88509436
has comment: http://stackoverflow.com/comment/88504547

http://stackoverflow.com/q/50761336
has comment: http://stackoverflow.com/comment/88530981
type: Question
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/88530777
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50761743
has body: I'm trying to write a function which takes a dataframe, duplicates it, changes the values in one of the columns and then concatenates them together. For example: df1 looks like column1 | column2 | column3 keyword1| 1 | 20 keyword2| 1 | 40 keyword3| 1 | 60 and I want a function which creates this: column1 | column2 | column3 keyword1| 1 | 20 keyword2| 1 | 40 keyword3| 1 | 60 keyword1| 2 | 20 keyword2| 2 | 40 keyword3| 2 | 60 I've tried this: def add_mobile(df): mobiledf = df.copy(deep=True) mobiledf['column2'].replace(1,2,inplace=True) df = pd.concat([df,mobiledf],axis=0) however when I put df1 though this function it returns df1 unedited. If I then look at df1.shape it has not changed.
has comment: http://stackoverflow.com/comment/88530996
possible better answer: http://stackoverflow.com/a/50761707
has comment: http://stackoverflow.com/comment/88530863
score: -3
downvote count: 3
has answer: http://stackoverflow.com/a/50761707
tagged with: python
linked to: http://stackoverflow.com/q/7869095
has comment: http://stackoverflow.com/comment/88530801
accepted answer: http://stackoverflow.com/a/50761743
type: AnsweredQuestion
has title: How to concatenate two pandas dataframes after replacing data within one function

http://stackoverflow.com/a/50748560
has comment: http://stackoverflow.com/comment/88504763
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88504787
accepted answer of: http://stackoverflow.com/q/50748494
upvote count: 2
answers question: http://stackoverflow.com/q/50748494
has body: It looks like you have bad timestamps, which will make it difficult to convert to datetime and search by month. My first recommendation would be to fix that data upstream, although if that is not an option, or if you are set on using regular expressions to match, you can simply use ^2018-06: df[df.Date.str.match(r'^2018-06')] Date Cost Source 0 2018-06-01 00:00:77 0.03 RFP 1 2018-06-01 00:05:77 0.01 RFP 2 2018-06-01 04:09:77 0.90 EFO The regex is quite straightforward: ^ # Asserts beginning of string 2018-06 # matches your date
type: AcceptedAnswer

http://stackoverflow.com/comment/88557500
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50773587
type: QuestionComment
has text: Ok, so `/Users/zahra/Library/Python/2.7/bin/scrapy ...` should work; to be able to call `scrapy` without the full path, open the file `.bash_profile` in your home directory and add two lines at the bottom: first is `PATH=${PATH}:${HOME}/Library/Python/2.7/bin` and the second is `export PATH`. Restart the terminal and you're good to go.

http://stackoverflow.com/comment/88614506
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50804203
has text: Looks good, but worth noting the implications, e.g. anything with `-` would be omitted; i.e. this mimics Python `str.isalpha`.
type: AnswerComment

http://stackoverflow.com/comment/88544010
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50767333
type: Comment
has text: try adding in your html form tag enctype="multipart/form-data"

http://stackoverflow.com/a/50729983
upvote count: 39
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/111008941
score: 39
accepted answer of: http://stackoverflow.com/q/50728351
has comment: http://stackoverflow.com/comment/127217013
answers question: http://stackoverflow.com/q/50728351
type: Answer
downvote count: 0
has body: Use --quiet to change the collection output. $ pytest --collect-only -q test_eggs.py::test_bacon[1] test_eggs.py::test_bacon[2] test_eggs.py::test_bacon[3] test_spam.py::test_foo test_spam.py::test_bar no tests ran in 0.03 seconds You can strip the status line with $ pytest --collect-only -q | head -n -2 When used twice (or more), --quiet will print the amount of tests per module: $ pytest --collect-only -qq test_eggs.py: 3 test_spam.py: 2

http://stackoverflow.com/a/50814660
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50814434
answers question: http://stackoverflow.com/q/50814434
has body: Using my as_strided recipe window_nd from here: input = np.random.rand(15, 5) current_output = input.reshape(-1, 5, 5) #I think? expected_output = window_nd(input, 5, steps = 1, axis = 0) steps and axis parameters aren't technically needed in this case but are included for clarity.

http://stackoverflow.com/q/50724433
tagged with: tuples
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50726314
has body: I have a problem with Code from the Mininet open source project. I abstracted it to the following scenario: def bar (*a, **b): b.update({'a':(a,)}) foo(**b) def foo (*a, **c): print(c) print(a) if __name__ == '__main__': bar(2,3,4, x=3, y=5) Method bar is only a helper to create a function call of foo. If I run it, print(a) has no output, because the values are still stored in the dictionary b. If I change *a to a, it works fine. And here my question: Is there a possibility which does not modify the Method foo which puts data into *a with data and the call of foo is like in line 3? This means only b in method bar is allowed to be modified.
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50724996
has title: Python: Cast Dictionary to Tuple implicit by calling a method
tagged with: optional-parameters
type: Question
has comment: http://stackoverflow.com/comment/88457688
score: 0
answer count: 2
tagged with: optional-arguments

http://stackoverflow.com/comment/88530343
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50756306
has text: When I tried: python transform_example.py images/example_01.png "[(73, 239), (356, 117), (475, 265), (187, 443)]" It gave me error "invalid syntax"

snappy
type: Tag
tags question: http://stackoverflow.com/q/50731058
tag name: snappy

http://stackoverflow.com/comment/88681452
comment on: http://stackoverflow.com/a/50838004
type: AnswerComment
score: 0
has text: Would I have to add a ForeignKey to the magazine class also ?
type: Comment

http://stackoverflow.com/q/50710219
type: UnansweredQuestion
tagged with: utf-8
tagged with: unicode
type: Question
has body: I have tried using the code made available by wassname at the following address https://gist.github.com/wassname/5b10774dfcd61cdd3f28 I have a question regarding the last part of the code (below). The resulting csv file contains unicode characters, but they are not the intended characters in German that I need to use. Python console does recognize the characters, but when I open up the csv files, I have to convert the file to 65001 unicode to observe the intended characters. Is there any way to adjust the code so as to skip the additional csv step? Thanks page=os.path.split(wiki)[1] fname='output_{}_t{}.csv'.format(page,tn) f = codecs.open(fname, 'w', encoding='utf-8') for i in range(nrows): rowStr=','.join(data[i]) rowStr=rowStr.replace('\n','') print(rowStr) rowStr=rowStr#.encode('unicode_escape') f.write(rowStr+ '\n') f.close()
tagged with: python
has title: Unicode String Encoding Python
has comment: http://stackoverflow.com/comment/88451690
score: 0
has comment: http://stackoverflow.com/comment/88454557
answer count: 0

http://stackoverflow.com/comment/88537710
comment on: http://stackoverflow.com/q/50764929
has text: @Prune is it possible to run `def name_i`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50747402
tagged with: python
downvote count: 0
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: pytest-qt
tagged with: qt
has title: Why can't pytest-qt find PyQt for Python 3.4?
score: 1
tagged with: pyqt
upvote count: 1
favorite count: 0
has body: I am using AppVeyor (Think Travis but for Windows) to run some tests again several different versions of Python. The tests depend on PyQt and pytest-qt. In some configurations, pytest-qt can't find PyQt, complaining: pytest-qt requires either PySide, PySide2, PyQt4 or PyQt5 to be installed The PyQt5 tests are working, but the tests also need to run older versions of Python, where PyQt4 is required. Python 2.7, 32-bit On Python 2.7 (32 bit), I install PyQt with conda: conda install -q pyqt=4 It successfully installs pyqt-4.11.4-py27_7 Then I install pytest-qt with pip: pip install pytest pytest-cov pytest-qt It successfully installs pytest-qt-2.4.0. Then I run the tests. It's fine. Python 2.7, 64-bit Exactly the same story. Works fine. Python 3.4, 64-bit This time it installs pyqt 4.11.4-py34_7, plus the same version of pytest-qt, but when the test runs, it crashes out: py.test tests -v INTERNALERROR&gt; Traceback (most recent call last): INTERNALERROR&gt; File "c:\miniconda34-x64\lib\site-packages\_pytest\main.py", line 174, in wrap_session INTERNALERROR&gt; config._do_configure() INTERNALERROR&gt; File "c:\miniconda34-x64\lib\site-packages\_pytest\config.py", line 957, in _do_configure INTERNALERROR&gt; self.hook.pytest_configure.call_historic(kwargs=dict(config=self)) INTERNALERROR&gt; File "c:\miniconda34-x64\lib\site-packages\pluggy\__init__.py", line 628, in call_historic INTERNALERROR&gt; res = self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) INTERNALERROR&gt; File "c:\miniconda34-x64\lib\site-packages\pluggy\__init__.py", line 222, in _hookexec INTERNALERROR&gt; return self._inner_hookexec(hook, methods, kwargs) INTERNALERROR&gt; File "c:\miniconda34-x64\lib\site-packages\pluggy\__init__.py", line 216, in &lt;lambda&gt; INTERNALERROR&gt; firstresult=hook.spec_opts.get('firstresult'), INTERNALERROR&gt; File "c:\miniconda34-x64\lib\site-packages\pluggy\callers.py", line 201, in _multicall INTERNALERROR&gt; return outcome.get_result() INTERNALERR…

http://stackoverflow.com/comment/88576491
has text: Possible duplicate of [Python - How to make a local variable (inside a function) global](https://stackoverflow.com/questions/14051916/python-how-to-make-a-local-variable-inside-a-function-global)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50784959
score: 1

http://stackoverflow.com/a/50811611
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50811387
has comment: http://stackoverflow.com/comment/88657271
has comment: http://stackoverflow.com/comment/88657063
answers question: http://stackoverflow.com/q/50811387
score: 4
has comment: http://stackoverflow.com/comment/88628871
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88628723
has body: I believe a dictionary is the most appropriate solution here. A dictionary allows you to keep track of which partition is associated to which key easily. If you just use a list with the values it can be more difficult to map a partition to a key. Here is a solution using a collections.defaultdict: dct = defaultdict(list) for i, e in enumerate(key): dct[e].extend(test[i]) # defaultdict(list, # {'one': [2, 4, 2, 4, 3, 5, 6, 6, 3, 2, 3, 3, 3, 7, 5, 3, 2, 4], # 'two': [4, 6, 3, 2, 4, 5, 3, 5, 4, 3, 5, 2, 6]}) # If you want the values print(list(dct.values())) Output: [[2, 4, 2, 4, 3, 5, 6, 6, 3, 2, 3, 3, 3, 7, 5, 3, 2, 4], [4, 6, 3, 2, 4, 5, 3, 5, 4, 3, 5, 2, 6]]
type: Answer

http://stackoverflow.com/comment/88476787
comment on: http://stackoverflow.com/q/50734464
type: Comment
type: QuestionComment
has text: response = requests.get('https://ec.europa.eu/esco/api/resource/concept?uri=http://data.europa.eu/esco/isco/C2&language=en') print(response.json())
score: 0

http://stackoverflow.com/comment/88488458
comment on: http://stackoverflow.com/q/50739918
has text: I have posted my proposition, That exactely what you need
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50847243
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50847060
has comment: http://stackoverflow.com/comment/88762555
has comment: http://stackoverflow.com/comment/88755305
has body: The only way to get back to the parent of a dict (or any recursive structure that doesn't have back-pointers) is to remember it as you traverse. But notice that you're already doing this: your path string is a path from the top to the current node. Let's write a function that uses the path: def follow(head, path): if not path: return head first, _, rest = path.partition('/') return follow(head[first], rest) Of course it would probably be nicer to build up path as a tuple of keys instead of a string, so we don't have to split them off (and so we don't have to worry about escaping or quoting if any of the keys might contain /, etc.); you can always join them at the end. And it might be even better to build up path as a tuple of nodes (or key-node pairs) instead of just the keys, so we can access the parent in constant time as just path[-1] instead of in logarithmic time as follow(head, path). But it really depends on what you're actually trying to do; your real code presumably doesn't just traverse the tree, building up paths to each node, and then doing nothing with them. However, a really nice way to solve this would be to turn the traversal inside-out: make traverse an iterator: def traverse(node, path =''): if isinstance(node, dict): for key in node: yield from traverse(node[key], path+'/'+key) elif isinstance(node, list): for elem in node: yield from traverse(elem,path+'/element') yield (node, path) Now we can just loop over traverse to do anything we want as a post-order depth-first traversal: for node, path in traverse(root): # do something And now you can change it easily to yield node, parent, path (whether parent is the parent node, or the parent key, or whatever you wanted).
upvote count: 1
type: Answer

http://stackoverflow.com/comment/88550315
score: 0
type: AnswerComment
type: Comment
has text: Thank you, but this doesn't helps. The fact that it can only detect that particular image only.
comment on: http://stackoverflow.com/a/50771223

http://stackoverflow.com/comment/88609106
type: AnswerComment
score: 0
type: Comment
has text: Yes, 'command' argument is used for that. You can call the function there, see the following: https://pastebin.com/mQrhpcEk If that solved your problem, you can accept it :)
comment on: http://stackoverflow.com/a/50787933

http://stackoverflow.com/q/50815095
has comment: http://stackoverflow.com/comment/88663230
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/88636650
has comment: http://stackoverflow.com/comment/88635014
has body: I tried to runserver with the manage.py but I get this error. I am a newbie in django framework. I am following tutsplus tutorial for news aggregator. bash -cl "/Users/Spandan/PycharmProjects/newsproject/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py runserver /usr/local/lib/python3.6/site-packages/django" Traceback (most recent call last): File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/__init__.py", line 16, in setup from django.urls import set_script_prefix File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/urls/__init__.py", line 1, in &lt;module&gt; from .base import ( File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/urls/base.py", line 8, in &lt;module&gt; from .exceptions import NoReverseMatch, Resolver404 File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/urls/exceptions.py", line 1, in &lt;module&gt; from django.http import Http404 File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/http/__init__.py", line 1, in &lt;module&gt; from django.http.cookie import SimpleCookie, parse_cookie File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/http/cookie.py", line 2, in &lt;module&gt; from http import cookies File "/usr/local/lib/python3.6/site-packages/django/http/__init__.py", line 1, in &lt;module&gt; from django.http.cookie import SimpleCookie, parse_cookie ImportError: cannot import name 'SimpleCookie'
type: Question
has comment: http://stackoverflow.com/comment/88663351
score: 0
has title: ImportError: cannot import name 'SimpleCookie' error
tagged with: python

http://stackoverflow.com/comment/88609604
has text: This did not work, I am getting an error TypeError: unsupported operand type(s) for +: 'NoneType' and 'BES'
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50801357

http://stackoverflow.com/comment/88567064
has text: Also, dictionary keys are required to implement `__hash__` and `__eq__` as you've noted, but for different reasons -- `__hash__` helps determine the "bucket", while `__eq__` determines whether the keys are the same (and thus the value should be overwritten) or they're not the same (and you have a hash collision and *both* should be stored. (`__eq__` has a default implementation btw (equivalent to `is`), while `__hash__` does not).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50780127

http://stackoverflow.com/comment/88518027
has text: I've checked my PATH variable and nodejs is in there. @jedwards
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50754836

http://stackoverflow.com/comment/88670837
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50833473
has text: Please correct your code indentation. In addition, show us an excerpt of `self.data`, since we need **[mcve]**.

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/50826644

http://stackoverflow.com/comment/88519519
comment on: http://stackoverflow.com/q/50705208
has text: I ask because if I add /VERBOSE to the command I cited above, it doesn't work
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88467953
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50729552
has text: If it is possible, but I could ignore it.

http://stackoverflow.com/comment/88462168
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50726818
has text: The data I get is partly read out from configuration files which can be wrongly specified by users. It is of course possible to clean all read out data and remove the first / but i am looking for a more elegant solution
score: 0

http://stackoverflow.com/q/50723423
answer count: 0
has comment: http://stackoverflow.com/comment/88534766
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88597732
type: Question
has comment: http://stackoverflow.com/comment/88493374
has comment: http://stackoverflow.com/comment/88504576
tagged with: python.net
has comment: http://stackoverflow.com/comment/88493494
tagged with: pythonnet
tagged with: .net
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88650448
has title: Visual Studio Python Environment - What are they hiding and where is it?
tagged with: python
has comment: http://stackoverflow.com/comment/88474606
has comment: http://stackoverflow.com/comment/88474636
has comment: http://stackoverflow.com/comment/88535583
has comment: http://stackoverflow.com/comment/88532056
has comment: http://stackoverflow.com/comment/88535124
tagged with: visual-studio
has body: I am using VS 2017 and I have installed pythonnet. I created a VS project "Python Application". I have other code (C# .NET) I would like to access from this new Python application. I should be able to: import clr However, in VS 2017 all works fine. I know for certain it works as not only is the CLR being imported, but I am running the .Net code (can see console outputs). The issue I am having is when I do not run in VS 2017. The purpose of this Python application is to provide demonstration to Python coding colleagues as to how to run the .Net DLLs. Said coders do NOT have Visual Studio, so the "VS Environment" magic that is happening must be done manually (when they install the .Net libs). If I run directly from cmd or use something else (like notepadd++) I get the ModuleNotFoundError: No module named 'clr' Where is VS hiding the clr.pyd and Python.Runtime.dll? As I understand it, these files need to be in the run directory but I am not seeing them there. As noted all works fine in VS though so it seems VS is loading those modules for me from somewhere.
linked to: http://stackoverflow.com/q/14633695
has comment: http://stackoverflow.com/comment/88538631
has comment: http://stackoverflow.com/comment/88493563

http://stackoverflow.com/a/50812820
downvote count: 0
has body: Your datetime.datetime.utcnow() is time zone unaware, and to make it aware use pytz: import datetime import dateutil.parser import pytz insertion_date = dateutil.parser.parse('2018-03-13T17:22:20.065Z') diffretiation = pytz.utc.localize(datetime.datetime.utcnow()) - insertion_date print diffretiation print insertion_date if diffretiation.days&gt;30: print "The insertion date is older than 30 days" else: print "The insertion date is not older than 30 days" #The insertion date is older than 30 days P.S. datetime.datetime.utcnow().isoformat() returns a string, and that was the error you encountered.
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50812578
answers question: http://stackoverflow.com/q/50812578
type: AcceptedAnswer

http://stackoverflow.com/q/50724560
score: -2
has comment: http://stackoverflow.com/comment/88459461
has comment: http://stackoverflow.com/comment/88457794
downvote count: 2
tagged with: bash
has answer: http://stackoverflow.com/a/50725492
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88458723
type: UnansweredQuestion
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/88457731
upvote count: 0
has comment: http://stackoverflow.com/comment/88458496
has body: I have parallel translated corpus in English-French (text.en,text.fr), each text includes around 500K of lines (sentences in source and target languge). what I want is to: 1- Remove the duplicated lines in both texts using python command; and avoid any alignment problem in both files. e.g: command deleted line 32 in text.en, then of course delete it in text.fr. 2- Then Split both files into Train/Dev/Test data, only 1K for dev, and 1K for test, and the rest for train. I need to split text.en and text.fr using the same command, so I could keep the alignment and corresponding sentences in both files. It would be better if I could extract test and dev data randomly, that will help getting better results. How can I do that? please write the commands. I appreciate any help, Thank you !
tagged with: corpus
tagged with: machine-translation
type: Question
has title: Removing duplicate lines and split parallel corpus
has comment: http://stackoverflow.com/comment/88457633

http://stackoverflow.com/q/50754756
score: 0
has comment: http://stackoverflow.com/comment/88522932
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/7585435
has body: Assuming I have the following variables: userVar = ABC passVar = XYZ I am familiar with this method of inserting the username and password directly but how can I use variable? userAndPass = b64encode(b"ABC:XYZ").decode("ascii") headerBasic = {'Authorization': 'Basic %s' % userAndPass} This gives me the headerBasic which then I call use as a header in my API Get. How can I not insert my username and password --> b64encode(b"ABC:XYZ") I have tried to create a string like this: str2 = userVar+":"+ passVar userAndPass = b64encode(b"str2").decode("ascii") it wont work.
tagged with: python
has comment: http://stackoverflow.com/comment/88517331
has title: Python creating Base64 key and calling an API
type: Question
linked to: http://stackoverflow.com/q/7585435
has comment: http://stackoverflow.com/comment/88517481

inheritance
tags question: http://stackoverflow.com/q/50840392
tags question: http://stackoverflow.com/q/50789288
tags question: http://stackoverflow.com/q/50724176
tag name: inheritance
tags question: http://stackoverflow.com/q/50736948
type: Tag
tags question: http://stackoverflow.com/q/50767971
tags question: http://stackoverflow.com/q/50724504
tags question: http://stackoverflow.com/q/50767808

http://stackoverflow.com/q/50711605
score: 0
tagged with: user-interface
has body: Here's the code I have written. It's supposed to ask the user for the user's home value and return an assessment value and taxes due. I'm not sure whether there's an issue with the IDLE on my computer or with my program. The program is supposed to: 1. ask the user to input their home value 2. give back the assessment value 3. include at least 2 buttons 4. Work (obviously) import tkinter class PropertyTaxApp: def __init__(self): # Creates main Window self.main_window tkinter.mainloop() #Creates the four frames self.homevalue_frame = tkinter.Frame(self.main_window) self.assessmentvalue_frame = tkinter.Frame(self.main_window) self.propertytaxes_frame = tkinter.Frame(self.main_window) self.button_frame = tkinter.Frame(self.main_window) #Create and pack the widgets for the home value self.homevalue_label = tkinter.Label(self.homevalue_frame, text = "Enter your home's value here: ") self.homevalue_entry = tkinter.Entry(self.homevalue_frame, width=10) self.homevalue_label.pack(side="left") self.homevalue_entry.pack(side="left") #Create and pack the widgets for the assessment value self.result_label = tkinter.label(self.assessmentvalue_frame, text="Assessment Value: ") self.assessmentvalue_label = tkinter.label(self.assessmentvalue_frame, textvariable=self.assessmentvalue) self.result_label.pack(side="left") self.assessmentvalue_label.pack(side="left") #Create and pack the widgets for the property taxes self.result_label = tkinter.label(self.propertytaxes_frame, text="Property Taxes: ") self.propertytaxes_label = tkinter.label(self.propertytaxes_frame, textvariable=self.propertytaxes) self.result_label.pack(side="left") self.assessmentvalue_label.pack(side="left") #Create and pack the button widgets self.calculate_button = tkinter.Button(self.button_frame, text="Calculate", command=self.calc_info) self.quit_button = tkinter.Button(self.button_frame, text="Quit Program", command=self.main_window.destroy) self.calculate_button.pack(side="left") self.quit_button.pack(side="lef…
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88432242
answer count: 0
has title: Python GUI "Property tax" program. When running the program, nothing seems to show up (i.e. no separate window pops up)
type: Question
has comment: http://stackoverflow.com/comment/88432229

http://stackoverflow.com/q/50772639
type: AnsweredQuestion
tagged with: file-manipulation
type: Question
has answer: http://stackoverflow.com/a/50773861
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88552722
score: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50773861
has body: def deleteEmployee(self,code,name): with open("employee.data","r+") as file: # data=file.readlines() for num, i in enumerate(file,1): print(i) a=i[:len(i)-1] if str(a)==str(code): print("found at",num) file.seek(num) file.write("\n") file.close() I just want to write a file handling code. Here I define delete function where I want to delete particular code if exists inside the file but it's not working.
has comment: http://stackoverflow.com/comment/88552947
has comment: http://stackoverflow.com/comment/88553032
has comment: http://stackoverflow.com/comment/88552690
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88552802
downvote count: 1
has title: How to delete a particular line from file in Python

http://stackoverflow.com/comment/88643962
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50817880
has text: But there's no way to tell how much time it will take the divs to load. Sometimes there might be 10 divs that take a minute to load. Other times there may be only one div that takes a second.
score: 0

http://stackoverflow.com/comment/88645762
type: Comment
type: QuestionComment
has text: yes, I think you are missing a "\" symbol in your folder path. Try use the inline code to outline problem and put more details in the question, so people will be able to help you.
score: 0
comment on: http://stackoverflow.com/q/50819717

http://stackoverflow.com/q/50708910
has body: I am working with an install of Anaconda on an offline server and want to install some third party packages. 1) Download the conda PACKAGE.tar.bz2 file to local desktop machine 2) SCP it into my home directory on the server 3) On the server, activate a Conda environment, using my Anaconda binary 4) On the server, run conda install PACKAGE.tar.bz2 Even though this runs without error, Anaconda cannot find PACKAGE when I try to import it. I think the problem is due to the channel being "unknown". For example, I tried to install Pyproj in my local environment. (testenv) [user@server ~]$ conda list # packages in environment at /home/user/anaconda2/envs/testenv: # # Name Version Build Channel anaconda 5.2.0 py27_3 pyproj 1.9.5.1 py27_0 &lt;unknown&gt; Anaconda sees that it has been installed in testenv but cannot import it. Is there some flags I need to use when installing the package? Is there a way to define the channel for Pyproj? Other solutions? Thanks. UPDATE: Install works if I am in the base environment. But it does not work if I try to install a package directly into one my user-defined environments.
answer count: 0
upvote count: 2
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88499655
tagged with: anaconda
has comment: http://stackoverflow.com/comment/88499533
has title: Anaconda offline - can't import installed package
has comment: http://stackoverflow.com/comment/88427889
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88470688
has comment: http://stackoverflow.com/comment/88469180
tagged with: python
score: 2

http://stackoverflow.com/comment/88423715
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50706702
has text: @IgnacioVazquez-Abrams Sure, but in this case that’s not going to end up any less verbose, and it means you have to pick a value that you know can never show up (or create one with `_sentinel=object()`).
type: AnswerComment

http://stackoverflow.com/a/50792284
type: Answer
has comment: http://stackoverflow.com/comment/88591802
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88591154
has body: You should be using itertools.product here. from itertools import product df_dict = { x[-1]: pd.DataFrame(list( product(x[0].split(', '), x[1].split(', '))) ) for x in df.values.tolist() } df = pd.concat(df_dict).reset_index(level=-1, drop=True).reset_index() df.columns = ['Weight', 'Destination', 'Origin'] df Weight Destination Origin 0 10000 AMS PVG 1 10000 FRA PVG 2 25000 LAX CAN 3 25000 LAX XMN 4 25000 ORD CAN 5 25000 ORD XMN
downvote count: 0
answers question: http://stackoverflow.com/q/50789834
has comment: http://stackoverflow.com/comment/88591782
has comment: http://stackoverflow.com/comment/88591069
has comment: http://stackoverflow.com/comment/88591217

generator
tags question: http://stackoverflow.com/q/50750052
tags question: http://stackoverflow.com/q/50755586
tags question: http://stackoverflow.com/q/50808335
tags question: http://stackoverflow.com/q/50774845
tags question: http://stackoverflow.com/q/50723378
tags question: http://stackoverflow.com/q/50759094
tags question: http://stackoverflow.com/q/50763783
type: Tag
tags question: http://stackoverflow.com/q/50746555
tags question: http://stackoverflow.com/q/50803690
tag name: generator
tags question: http://stackoverflow.com/q/50777923
tags question: http://stackoverflow.com/q/50816800
tags question: http://stackoverflow.com/q/50850477
tags question: http://stackoverflow.com/q/50801461
tags question: http://stackoverflow.com/q/50701644

http://stackoverflow.com/q/50722417
has comment: http://stackoverflow.com/comment/88453275
has comment: http://stackoverflow.com/comment/88454446
has title: why I have an empty list in the output
tagged with: python
has comment: http://stackoverflow.com/comment/88453837
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88453466
has comment: http://stackoverflow.com/comment/88453776
type: Question
has comment: http://stackoverflow.com/comment/88454189
has comment: http://stackoverflow.com/comment/88453215
has body: I have trayed to find the outliers that appear in more than on features but in the output I have an empty list even if there are an outlier in more on feature: outliersIndx = log_data[~((log_data[feature] &gt;= Q1 - step) &amp; (log_data[feature] &lt;= Q3 + step))].index.values.tolist() outliers=[] for i in outliersIndx: if outliersIndx.count(i) &gt; 1: outliers.append(i)

http://stackoverflow.com/q/50836917
answer count: 0
has body: This is my dataframe df: a b c 1.2 2 0.1 2.1 1.1 3.2 0.2 1.9 8.8 3.3 7.8 0.12 I'm trying to get the max value from each row of the dataframe, and record the column from which it came. I can do df['max_value'] = df.max(axis=1) to get the maximum value in a new column, but how can I record the column from which it came?
linked to: http://stackoverflow.com/q/39874501
type: Question
has comment: http://stackoverflow.com/comment/88683445
score: 0
tagged with: pandas
has title: pandas: Get the maximum value in a row, and record the column where it was found?
has comment: http://stackoverflow.com/comment/88683508
duplicate of: http://stackoverflow.com/q/39874501
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88677486
has comment: http://stackoverflow.com/comment/88683615

http://stackoverflow.com/comment/88491698
type: QuestionComment
has text: This is related to flask app.run()
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50739573

http://stackoverflow.com/comment/88552936
has text: I checked it. If I add a new element or just space to dict_2, it causes the problem. I still can add elements to dict_1 without any negative consequences.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50772694
type: Comment

http://stackoverflow.com/comment/88536769
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50764194
has text: @sulphur You don't understand me, I'm saying pd.read_cv(...) will already return a pandas `DataFrame`. You don't need to call `pd.DataFrame` as well

http://stackoverflow.com/comment/88612379
score: 2
has text: The answer you link to applies to Python 2-3 dict comprehensions and set comprehensions and generator expressions. It is only list-comprehensions that had a fundamentally different implementation that would let you get away with this in Python 2. I am probably going to close as a duplicate unless there are any objections...
comment on: http://stackoverflow.com/q/50803144
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50751204
type: Answer
has comment: http://stackoverflow.com/comment/88510598
accepted answer of: http://stackoverflow.com/q/50751120
downvote count: 0
answers question: http://stackoverflow.com/q/50751120
score: 1
has body: In your permission class you create a permissions attribute via backref to you role class, not your user class. costam2 = db.relationship('role', secondary=permission_role, backref=db.backref('permissions', lazy='dynamic')) should be costam2 = db.relationship('user', secondary=permission_role, backref=db.backref('permissions', lazy='dynamic')) This will at least fix that specific error Looking more closely at your diagram. Maybe you want to do something like: role1.permissions.append(admin) and then create a relationship between role and user
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/53326399
score: 0
answers question: http://stackoverflow.com/q/50734535
type: Answer
has body: Sorry for the late reply. I created a virtual assistant using the google speech API. It turns out the main problem is with the microphone threshold. Try playing with its threshold. Because when you record a stream in real-time try saving it and listening to it locally. There is a parameter in microphone function which is a threshold, try changing that because by default tunning its pretty bad if the microphone is builtin. The Google speech API might be block (but its working for me even though I am not using any token). Although the preferred option is to use Tokens in Google API (speech to text) While the text is returned in a perfect form. Check the documentation of speech recognition. There are tons of other APIs as well.

http://stackoverflow.com/comment/103399206
comment on: http://stackoverflow.com/a/58048911
type: Comment
type: AnswerComment
has text: You are right. I would not post it here if I found a simple way how to edit json file in my version of VS Code. If someone knows how to edit settings in old fashion, I would be happy to add this piece of information to my answer.
score: 0

http://stackoverflow.com/a/50827993
type: Answer
has comment: http://stackoverflow.com/comment/88660722
answers question: http://stackoverflow.com/q/50827506
has comment: http://stackoverflow.com/comment/88875003
has comment: http://stackoverflow.com/comment/88660858
has comment: http://stackoverflow.com/comment/88840417
score: 1
has comment: http://stackoverflow.com/comment/88841078
has comment: http://stackoverflow.com/comment/88876823
upvote count: 1
has comment: http://stackoverflow.com/comment/88660844
has body: IIUC get_dummies pd.get_dummies(df.set_index(['RecordID','Para']),prefix='',prefix_sep = '').sum(level=[0,1]).gt(0).astype(int) Out[272]: x y z a b c RecordID Para 1 A 1 0 1 1 1 1 2 B 0 1 0 1 1 0 Update pd.get_dummies(df.set_index(['RecordID','Para']),prefix='',prefix_sep = '').sum(level=[0,1]).gt(0).astype(int).replace(0,np.nan).groupby(level=0).ffill().fillna(0) Out[292]: x y z a b c RecordID Para 1 A 1.0 0.0 1.0 1 1.0 1.0 2 B 0.0 1.0 0.0 1 1.0 0.0 1 C 1.0 0.0 1.0 1 1.0 1.0
has comment: http://stackoverflow.com/comment/88660813
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88876380
has comment: http://stackoverflow.com/comment/88660698
accepted answer of: http://stackoverflow.com/q/50827506
has comment: http://stackoverflow.com/comment/88660836

http://stackoverflow.com/comment/88638714
type: Comment
type: QuestionComment
has text: `i` is not an index. It is one of the values from the `RunningMean [1:3]` slice (a list with two integers in it).
score: 0
comment on: http://stackoverflow.com/q/50816861

http://stackoverflow.com/a/50707922
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50707161
score: 4
answers question: http://stackoverflow.com/q/50707161
type: AcceptedAnswer
has body: You need to add leaflet.as_view() in urlpatterns urls.py from django.conf.urls import include, url from django.contrib import admin from main.views import leaflet urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^/', include('main.urls', namespace='Home')), url(r'^test/', leaflet.as_view()), ]
type: Answer

http://stackoverflow.com/a/50721035
has body: First of all, thank you @Van de Wack. This is the complete solution: Install the pysmb library (https://pypi.org/project/pysmb/): pip install pysmb Import the library to your code: from smb.SMBConnection import SMBConnection The follow code is a example to list all directories: server_ip = "10.110.10.10" # Take your server IP - I have put a fake IP :) server_name = 'myserver' # The servername for the IP above share_name = "GRUPOS" # This is the principal folder of your network that you want's to connect network_username = 'myuser' # This is your network username network_password = '***' # This is your network password machine_name = 'myuser@mac-mc70006405' # Your machine name conn = SMBConnection(network_username, network_password, machine_name, server_name, use_ntlm_v2 = True) assert conn.connect(server_ip, 139) files = conn.listPath(share_name, "/TECNOLOGIA_INFORMACAO/Dashboard Diretoria/") for item in files: print(item.filename)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50719840
score: 1
downvote count: 0

http://stackoverflow.com/q/50728615
has comment: http://stackoverflow.com/comment/88465984
tagged with: beautifulsoup
has body: I'm trying to save a product description into MySQL database. So far, I have tried changing datatype to BLOB, LONGBLOB, TEXT, LONGTEXT but it's not working. import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import mysql.connector cnx = mysql.connector.connect(user='root', password='Kradz579032!!', host='127.0.0.1', database='aliexpressapidb') cursor = cnx.cursor() add_data = ("INSERT INTO productdetails" "(description) " "VALUES (%s)") my_url = 'https://www.aliexpress.com/item/Cheap-Necklace-Jewelry-Alloy-Men-Vintage-Personality-Pendant-Creativity-Simple-Accessories-Symbol-Necklace-Wholesale-Fashion/32879629913.html?spm=a2g01.11147086.layer-iabdzn.4.4a716140Ix00VA&amp;scm=1007.16233.91830.0&amp;scm_id=1007.16233.91830.0&amp;scm-url=1007.16233.91830.0&amp;pvid=acdbf117-c0fb-458f-b8a9-ea73bc0d174b' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") description = page_soup.findAll("div", {"class": "ui-box-body"}) #print(description) data_insert = description cursor.execute(add_data, data_insert) cnx.commit() cursor.close() cnx.close() Keep getting error : File "/Users/reezalaq/.conda/envs/untitled3/lib/python3.6/site-packages/mysql/connector/conversion.py", line 160, in to_mysql return getattr(self, "_{0}_to_mysql".format(type_name))(value) AttributeError: 'MySQLConverter' object has no attribute '_tag_to_mysql' "MySQL type".format(type_name)) TypeError: Python 'tag' cannot be converted to a MySQL type
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50730109
has comment: http://stackoverflow.com/comment/88466021
tagged with: python
has title: Python-BeautifulSoup : How to save html into database?
has answer: http://stackoverflow.com/a/61501029
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88465373
has answer: http://stackoverflow.com/a/50728761
tagged with: mysql
type: Question

http://stackoverflow.com/a/50715155
downvote count: 0
has comment: http://stackoverflow.com/comment/88439736
has comment: http://stackoverflow.com/comment/88442626
type: Answer
has comment: http://stackoverflow.com/comment/88440884
has comment: http://stackoverflow.com/comment/88440568
score: 28
answers question: http://stackoverflow.com/q/50714316
upvote count: 28
has body: The naming of the loggers is what you are missing. In the example, a logger named spam_application is created in the main module. Then handlers and formatters are created and added to that logger. In auxiliary_module loggers are created with names that start with spam_application resp. spam_application.auxiliary. This effectively creates a hierarchy of loggers that propagate to their respective parents unless explicitly disabled. This hierarchy is spam_appliclation &lt;- spam_application.auxiliary &lt;- spam_application.auxiliary.Auxiliary or logger &lt;- module_logger &lt;- self.logger in the case of the cookbook example. If you replace the explicit logger names by __name__ you end up having a configured logger named __main__ in your main module, which is configured with handlers, but the naming of your auxiliary loggers is not in a way that it would create a hierarchy, hence your auxiliary_module loggers propagate to the implicit root logger which has no handlers configured. Try the following: Change your class' init method as follows: def __init__(self): self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary') print self.logger.parent self.logger.info('creating an instance of Auxiliary') Then run your main module once with self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary') and once with self.logger = logging.getLogger(__name__) The output should look like this: &lt;Logger spam_application.auxiliary (WARNING)&gt; # with explicit logger name &lt;RootLogger root (WARNING)&gt; # using __name__

http://stackoverflow.com/comment/88681432
comment on: http://stackoverflow.com/q/50838384
score: 1
has text: There has been an answer which seems to work (pending an edit), but i.split(' ',1) means your line is being split into two parts. Assuming you have more than two numbers per line, youre correctly converting the first number, and then attempting to float(remaining numbers on line). What happens if you remove the '1'?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88475551
comment on: http://stackoverflow.com/q/50729310
has text: This is not actually a solution, just a workaround.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50789448
favorite count: 0
has comment: http://stackoverflow.com/comment/88600648
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50790257
tagged with: python
has comment: http://stackoverflow.com/comment/88585148
score: 1
downvote count: 1
has body: What is the absolute fastest way of achieving this? I will be doing this over 1 million times per day so I want maximum efficiency. With numpy (avg after 20 runs 0.0001679009692429128) t0 = time.clock() print(np.random.randint(1,1000000)) t1 = time.clock() print (t1-t0) With random (avg: 0.0000920492372555262) t2 = time.clock() print(random.choice(range(1,1000000))) t3 = time.clock() print (t3-t2) To my surprise random was consistently faster than numpy. Is there a faster way?
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/7029993
has comment: http://stackoverflow.com/comment/88586032
has comment: http://stackoverflow.com/comment/88585138
has comment: http://stackoverflow.com/comment/88585147
has answer: http://stackoverflow.com/a/50790126
tagged with: random
has answer: http://stackoverflow.com/a/66411256
has answer: http://stackoverflow.com/a/50790263
linked to: http://stackoverflow.com/q/2866380
has title: Fastest way to get a random number between 1 and 1million in python
answer count: 4

http://stackoverflow.com/comment/88442586
comment on: http://stackoverflow.com/a/50716142
type: Comment
has text: Don't use `ALLCAPS` as variable names. Use `lowercase_with_underscores`
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88559538
type: QuestionComment
has text: Thank you so much. Do you mean like this? class Task(models.AbstractEntity): request = models.ForeignKey(Request, related_name='tasks', on_delete=models.CASCADE) assignee = models.ForeignKey(Group) updated_by =models. ForeignKey(User) activity_ref = CharField(max_length=100) status = CharField(verbose_name="Status", max_length=30, choices=TASK_STATUS)
score: 0
comment on: http://stackoverflow.com/q/50776076
type: Comment

mongodb
tags question: http://stackoverflow.com/q/50806601
tags question: http://stackoverflow.com/q/50764201
tags question: http://stackoverflow.com/q/50760889
tag name: mongodb
tags question: http://stackoverflow.com/q/50841709
type: Tag
tags question: http://stackoverflow.com/q/50726273
tags question: http://stackoverflow.com/q/50700643
tags question: http://stackoverflow.com/q/50826223
tags question: http://stackoverflow.com/q/50803754
tags question: http://stackoverflow.com/q/50733171
tags question: http://stackoverflow.com/q/50794434
tags question: http://stackoverflow.com/q/50706317
tags question: http://stackoverflow.com/q/50785389
tags question: http://stackoverflow.com/q/50802158
tags question: http://stackoverflow.com/q/50807778

http://stackoverflow.com/a/54926622
answers question: http://stackoverflow.com/q/50807507
has body: I am also a Windows user. And I have installed Python 3.7 and when I try to install any package it throws the same error that you are getting. Try this out. This worked for me. python -m pip install numpy And whenever you install new package just write python -m pip install &lt;package_name&gt; Hope this is helpful.
upvote count: 12
score: 12
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88500299
score: 1
type: AnswerComment
type: Comment
has text: If you're still stuck, please ask a new question. This is an unrelated problem so the comments aren't the best place to solve it.
comment on: http://stackoverflow.com/a/50744149

http://stackoverflow.com/a/50710630
has comment: http://stackoverflow.com/comment/88431520
has comment: http://stackoverflow.com/comment/88431287
score: 2
has comment: http://stackoverflow.com/comment/88431104
answers question: http://stackoverflow.com/q/50710057
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88431453
has body: This is a perfect case for the trash-can-appraoch: forget everything that is not in capture group 1. ".*?"|(\w+) Explanation: We select from two alternatives | ".?" matches a string from start to end using the quotes as an anchor and anything in-between using the .and the * quantifier that any number of repetitions. The ? changes the behavior of the star to match as few times as possible (lazy) to avoid to match too much with a default greedy match. (\w+) the parenthesis define a capture group that captures one or more + alphanumerics: \w itself is a shorthand character class that stands for [a-zA-Z0-9_] (this is called a character range). Sample code: import re regex = r'".*?"|(\w+)' test_str = "\"int open(const char *\" pathname \", int \" flags );" matches = re.finditer(regex, test_str, re.MULTILINE) for match in matches: if match.group(1): print ("Found at {start}-{end}: {group}".format(start = match.start(1), end = match.end(1), group = match.group(1))) Output: Found at 24-32: pathname Found at 42-47: flags
has comment: http://stackoverflow.com/comment/88431799
accepted answer of: http://stackoverflow.com/q/50710057
upvote count: 2
type: Answer

http://stackoverflow.com/q/50712998
type: UnansweredQuestion
type: Question
has title: How implement dynamic testimonials and carousel in django python
has answer: http://stackoverflow.com/a/50715095
score: 0
tagged with: django
tagged with: python
answer count: 1
has body: Im facing implementing the dynamic testimonials and carousel in django python, means i need to content in models that so present in front below i mention my code of implemetions template.html {% for p in tests %} {% if forloop.counter == 1 %} {% else %} {% endif %} {{ p.title }} `enter code here` {% endfor %} view.py def home(request): test=Testimonials.objects.all().order_by('id')[:13] template = loader.get_template('hme/home.html') context = { 'tests':test, } return HttpResponse(template.render(context, request))

http://stackoverflow.com/q/50804987
has body: I'm not sure why the following minimal code prints the mouse but not keyboard events. As far as I can tell, both methods have been overloaded correctly in my custom widget (housed inside a main window). Any ideas? from sys import argv, exit from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setCentralWidget(CustomWidget(self)) self.show() class CustomWidget(QWidget): def __init__(self, parent=None): super(CustomWidget, self).__init__(parent) pass def mousePressEvent(self, event): print(event) def keyPressEvent(self, event): print(event) if __name__ == '__main__': app = QApplication(argv) ex = MainWindow() exit(app.exec_())
type: Question
linked to: http://stackoverflow.com/q/22169216
has title: PyQt5 processes MousePressEvent but not KeyPressEvent
duplicate of: http://stackoverflow.com/q/22169216
has answer: http://stackoverflow.com/a/50805086
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50805086
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: pyqt5
upvote count: 1

http://stackoverflow.com/comment/88471200
type: QuestionComment
type: Comment
has text: Also, as written, your server can only handle one client at a time. Is that OK for your use case? If not, you need to add per-connection threads to the server (at which point there's even less reason not to have the client in a separate thread), or you need to rewrite the whole thing around asyncio or a manual selector or…
comment on: http://stackoverflow.com/q/50731435
score: 0

http://stackoverflow.com/q/50762077
has body: I am trying to send an e-mail using import smtplib. And I want it to render the html and send it in an e-mail. Unfortunately it currently just sends the html code in the e-mail. Any suggestion would be much appreciated. My Code is below: import smtplib import pandas as pd DEFAULT_EMAIL_SERVER = "x" TO = ["y@x.com"] FROM = "z@x.com" SUBJECT = "TEST" table = pd.read_excel('abc.xlsm') body = '&lt;html&gt;&lt;body&gt;' + table.to_html() + '&lt;/body&gt;&lt;/html&gt;' TEXT = body message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\ %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) server = smtplib.SMTP(x) server.sendmail(FROM, TO, message) server.quit()
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has answer: http://stackoverflow.com/a/74811948
favorite count: 0
possible better answer: http://stackoverflow.com/a/74811948
tagged with: python
has answer: http://stackoverflow.com/a/50762541
has title: Rendering HTML in Python when sending e-mails using import smtplib
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/50762541
type: Question
answer count: 2

http://stackoverflow.com/a/50787946
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50787915
upvote count: 1
has body: x = [] for word in list_a: x = [list_a.index(word) + ' - ' + word for word in list_a] return x
type: Answer

http://stackoverflow.com/a/51181213
answers question: http://stackoverflow.com/q/50834258
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6
has body: The solution is the cloudpickle module, regular pickle has problems pickling functions. An example: import cloudpickle with open('test.pkl', mode='wb') as file: cloudpickle.dump(instance, file) with open('test.pkl', mode='rb') as file: instance = cloudpickle.load(file)
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50834258

http://stackoverflow.com/comment/88507323
comment on: http://stackoverflow.com/q/50749481
score: 0
type: QuestionComment
has text: @juanpa.arrivillaga number of loops is what changes from O(n^5) to O(n^3) as operations inside loops are all O(1)...
type: Comment

http://stackoverflow.com/a/50824887
downvote count: 0
has body: I would always use Ajax1234's solution instead, but I wanted to illustrate how I would approach it using a for-loop, as you intended: l3 = [] for elem in l1: pairs = list(filter(lambda x: x[0] == elem, l2)) l3.append(pairs[0][1] if pairs else 0) An alternate approach would be using next() and a list comprehension instead of filter() and a for-loop. This one is far more efficient and readable: l3 = [next((u[1] for u in l2 if u[0] == elem), 0) for elem in l1]
answers question: http://stackoverflow.com/q/50824613
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88654840

http://stackoverflow.com/a/50812347
has comment: http://stackoverflow.com/comment/88630257
has comment: http://stackoverflow.com/comment/88630448
type: Answer
accepted answer of: http://stackoverflow.com/q/50812299
score: 1
upvote count: 1
has body: You can use for remove Unnamed columns startswith for boolean mask with loc: df = df.loc[:, ~df.columns.str.startswith('Unnamed')] And if necessary for remove NaNs in all column data use dropna: df.dropna(axis=0, how='all', inplace=True)
has comment: http://stackoverflow.com/comment/88630206
downvote count: 0
answers question: http://stackoverflow.com/q/50812299
type: AcceptedAnswer

http://stackoverflow.com/a/69140483
type: Answer
answers question: http://stackoverflow.com/q/50760596
score: 0
has body: As others mentioned, it's because there was no user-agent specified. The default requests user-agent is python-requests and urllib has something similar thus Google blocks a request because it knows that it's a bot and not a "real" user visit. User-agent fakes user visit by adding this information into HTTP request headers. It can be done by using requests library and adding custom headers. >>> params = {'key1': 'value1', 'key2': 'value2'} >>> r = requests.get('https://httpbin.org/get', params=params) >>> print(r.url) # https://httpbin.org/get?key2=value2&key1=value1 Alternatively, you can achieve the same thing by using the Google Organic Results API from SerpApi. It's a paid API with a free plan. The difference in your case is that you don't have to deal with such problems or maintain the parser over time since it's already done for the end-user, and the only thing that only needs to be done is to iterate over structured JSON and get the data you want fast. Code to integrate: import os from serpapi import GoogleSearch params = { "engine": "google", # search engine to search from "q": "what does katana mean", # query "hl": "en", # language "gl": "us", # country to search from "api_key": os.getenv("API_KEY"), # API key environment } search = GoogleSearch(params) results = search.get_dict() for result in results["organic_results"]: print(f"Title: {result['title']}\nSummary: {result['snippet']}\nLink: {result['link']}\n") --------- ''' Title: Katana - Wikipedia Summary: Pronounced [katana], the kun'yomi (Japanese reading) of the kanji 刀, originally meaning dao or knife/saber in Chinese, the word has been adopted as a loanword ... Link: https://en.wikipedia.org/wiki/Katana Title: Definition of "katana" - Merriam-Webster Summary: Katana definition is - a single-edged sword that is the longer of a pair worn by the Japanese samurai. Link: https://www.merriam-webster.com/dictionary/katana # other results ... ''' Disclaimer, I work for SerpApi.

http://stackoverflow.com/comment/88521024
score: 0
type: Comment
type: QuestionComment
has text: OP needs to preserve original order, which `np.unique()` will not do.
comment on: http://stackoverflow.com/q/50756639

http://stackoverflow.com/q/50824644
type: Question
has comment: http://stackoverflow.com/comment/88654255
has title: How to merge pandas DataFrame with same column name?
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50824715
favorite count: 0
has body: The index is a timestamp and column name, and also the ability to replace NaN to value. It does not seem to be working. sample: import pandas as pd times = pd.to_datetime(pd.Series(['2014-07-4', '2014-07-15','2014-08-24','2014-08-25','2014-09-10','2014-09-17'])) valuea = [0.01, 0.02, -0.03, 0.4 ,0.5,np.NaN] times2 = pd.to_datetime(pd.Series(['2014-07-6', '2014-07-16','2014-08-27','2014-09-5','2014-09-11','2014-09-17'])) valuea2 = [1, 2, 3, 4,5,-6] df1 = pd.DataFrame({'value A': valuea}, index=times) df2 = pd.DataFrame({'value A': valuea2}, index=times2) df3=pd.merge(df1,df2, left_index=True, right_index=True) df3.head()
has comment: http://stackoverflow.com/comment/88654679
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88654841
accepted answer: http://stackoverflow.com/a/50824715
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/88497935
type: AnswerComment
has text: I got the desired result, however I have to understand more about map function :-)
comment on: http://stackoverflow.com/a/50744798
type: Comment
score: 1

http://stackoverflow.com/comment/88593404
comment on: http://stackoverflow.com/a/50789385
score: 0
type: AnswerComment
type: Comment
has text: Unfortunately this doesn't work as Wikipedia redirects the request to `https`

http://stackoverflow.com/q/50786145
type: Question
score: 9
tagged with: curve-fitting
tagged with: python
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/50786333
tagged with: scipy
has answer: http://stackoverflow.com/a/50786249
upvote count: 10
has comment: http://stackoverflow.com/comment/88581090
has title: Scipy sigmoid curve fitting
type: AnsweredQuestion
has body: I have some data points and would like to find a fitting function, I guess a cumulative Gaussian sigmoid function would fit, but I don't really know how to realize that. This is what I have right now: import numpy as np import pylab from scipy.optimize import curve_fit def sigmoid(x, a, b): y = 1 / (1 + np.exp(-b*(x-a))) return y xdata = np.array([400, 600, 800, 1000, 1200, 1400, 1600]) ydata = np.array([0, 0, 0.13, 0.35, 0.75, 0.89, 0.91]) popt, pcov = curve_fit(sigmoid, xdata, ydata) print(popt) x = np.linspace(-1, 2000, 50) y = sigmoid(x, *popt) pylab.plot(xdata, ydata, 'o', label='data') pylab.plot(x,y, label='fit') pylab.ylim(0, 1.05) pylab.legend(loc='best') pylab.show() But I get the following warning: .../scipy/optimize/minpack.py:779: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) Can anyone help? I'm also open for any other possibilities to do it! I just need a curve fit in any way to this data.
possible better answer: http://stackoverflow.com/a/50786249
has comment: http://stackoverflow.com/comment/88607976
accepted answer: http://stackoverflow.com/a/50786333
favorite count: 0

http://stackoverflow.com/comment/88613014
type: Comment
has text: @IcyBloom My pleasure. Also consider https://stackoverflow.com/questions/50803272/getting-a-different-result-when-using-and-not-using-return-in-python-3/50803322#comment88612382_50803272 comment. _Usually_ when a function modifies input argument, it does not return it as well (unless you document this behavior). Also, that nested `if` can be combined into a single `if` using logical `and`. Finally, consider using list comprehension: https://stackoverflow.com/q/20639180/8033585
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50803322

http://stackoverflow.com/a/52138085
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50784756
has body: We can use the existing keras layers to convert the existing image shape to the expected shape for the pre-trained model rather than using the numpy for replicating channels. As replicating channels before training may consume 3x the memory, but integrating this processing at runtime will save up a lot of memory. You can proceed this way. Step 1: Create a Keras Model that converts your input images to the shape that can be fed as the input for the base_model as follows: from keras.models import Model from keras.layers import RepeatVector, Input, Reshape inputs = Input(shape=(128, 128, 1)) reshaped1 = Reshape(target_shape=((128 * 128 * 1,)))(inputs) repeated = RepeatVector(n=3)(reshaped1) reshaped2 = Reshape(target_shape=(3, 128, 128))(repeated) input_model = Model(inputs=inputs, outputs=reshaped2) Step 2: Define pre-trained model InceptionV3 as follows: base_model = InceptionV3(input_tensor=input_model.output, weights='imagenet', include_top=False) Step 3: Combine both the models as follows: combined_model = Model(inputs=input_model.input, outputs=base_model.output) The advantage of this method is that the keras model itself will take care of the image processing stuff like channel replication at runtime. Thus, we need not replicate the image channels by ourselves with numpy and the results will be memory efficient.
downvote count: 0
score: 1

http://stackoverflow.com/q/50821376
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88648500
has answer: http://stackoverflow.com/a/50823747
has title: Split nested numpy array
tagged with: arrays
score: 0
has comment: http://stackoverflow.com/comment/88648021
answer count: 1
has comment: http://stackoverflow.com/comment/88647972
has comment: http://stackoverflow.com/comment/88648239
tagged with: python
has comment: http://stackoverflow.com/comment/88649839
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50823747
has body: I have a numpy array of shape 28 x 1875. Each element is a 3-element list (only floats). I need to split each of these elements to individual ones, to obtain an array of shape 28x5625(1875*3). I've tried np.split, however it only separates each element, but no each sub-element. Is there a fast way to do this?

http://stackoverflow.com/a/50797050
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50796999
has body: Use datetime module. Ex: import datetime def substr(strtime): strtime = datetime.datetime.strptime(strtime, "%Y-%m-%d %H:%M:%S") return strtime.strftime("%H") print( substr( "2017-07-14 17:01:00") ) If you do not want to use datetime module you can do. def substr(strtime): return strtime[11:13] Output: 17
upvote count: 2
score: 2

http://stackoverflow.com/comment/88411999
type: Comment
score: 0
has text: @HadiFarah I can't get it to work properly. I updated my current code in the question above. Maybe you could check it. It doesn't execute the .cmd file.
type: AnswerComment
comment on: http://stackoverflow.com/a/50700072

http://stackoverflow.com/comment/88559487
comment on: http://stackoverflow.com/a/50776175
score: 0
type: AnswerComment
type: Comment
has text: The full code sample I posted above runs. Can you verify that the checks are present, as well as the parentheses in the regex?

http://stackoverflow.com/comment/88442237
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50710980
has text: static files are working fine the problem is in the media files

http://stackoverflow.com/q/50841800
type: AnsweredQuestion
has body: I want to randomly sample from a custom function using scipy in the range 0.15 to 10.1. However, my sample is highly skewed towards the left boundary of 0.15. In fact, all of the 50000 sampled points are less than 0.16. I'm not sure what the problem is with my code. import numpy as np from scipy import stats class your_distribution(stats.rv_continuous): def _pdf(self, x): p0 = 10.9949; p1 = 0.394447; p2 = 12818.4; p3 = 2.38898; return ((p1*p3)/(p3*p0+p2*p1))*(p0*np.exp(-1.0*p1*x))+(p2*np.exp(-1.0*p3*x)) distribution = your_distribution(a=0.15, b=10.1) sample = distribution.rvs(size=50000)
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/50842566
has answer: http://stackoverflow.com/a/50843591
accepted answer: http://stackoverflow.com/a/50843591
score: 0
tagged with: random
answer count: 3
has title: Scipy: sampled data points are of similar value
has comment: http://stackoverflow.com/comment/88689080
possible better answer: http://stackoverflow.com/a/50842566
has answer: http://stackoverflow.com/a/50843597
tagged with: python

http://stackoverflow.com/q/50784474
tagged with: optimization
has answer: http://stackoverflow.com/a/50800516
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88586633
accepted answer: http://stackoverflow.com/a/50800516
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88588908
has comment: http://stackoverflow.com/comment/88576052
has title: Optimize Sum of Squared Differences (SSD) in numpy
has body: I'm trying to optimise expected goal in football (soccer) matches by measuring the sum of squared difference against the individual match timeslots. Assuming each match is divided into k number of Timeslots with constant probabilities of a Goal scored by either team or No Goal. **Sample SSD for individual match_i with Final score [0-0]** xG is unique in each match. Team1 and Team2 has the following xG multiplied by arbitrary multiplier M. Team1 = xG_1*M Team2 = xG_2*M prob_1 = [1-(xG_1 + xG_2)/k, xG_1/k, xG_2/k]. where Prob_1 is a constant probability of a Draw, a Team1 Goal or a Team2 Goal for each Timeslot (k) per match_i where sum(prob_1) = 1. To measure SSD for match_i. x1 = [1,0,0] #; prob. of No goal scored per timeslot. x2 = [0,1,0] #; prob. of Home Team scoring per timeslot. x3 = [0,0,1] #; prob. of Away Team scoring per timeslot. y = np.array([1-(xG_1 + xG_2)/k, xG_1/k, xG_2/k]) # Using xG_Team1 and xG_Team2 from table below. total_timeslot = 180 Home_Goal = [] # No Goal scored Away_Goal = [] # Np Goal scored def sum_squared_diff(x1, x2, x3, y): ssd=[] for k in range(total_timeslot): if k in Home_Goal: ssd.append( sum((x2 - y)**2)) elif k in Away_Goal: ssd.append(sum((x3 - y)**2)) else: ssd.append(sum((x1 - y)**2)) return ssd SSD_Result = sum_squared_diff(x1, x2, x3, y) sum(SSD_Result) For example, using xGs of index 0 from the table below and M = 1 First, for k = 187 timeslot, xG per timeslot becomes 1.4405394105672238/187, 1.3800950382265837/187 and are constant throughout the match. y_0 = np.array([1-(0.007703419308 + 0.007380187370)/187, 0.007703419308/187, 0.007380187370/187]) Using y_0 in the function above, SSD_Result for xG at index 0 is 1.8252675137316426e-06. As SSD goes this looks promising but then again the match ended goalless and the two teams has almost identical xG figure.... Now I want to apply the same procedure to xG index 1, xG index 2....xG index 10000. Then take the total SSD and depending on the value, change the arbitrary multiplier…
type: Question
tagged with: numpy
tagged with: arrays
answer count: 1

http://stackoverflow.com/q/50713109
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50713146
type: Question
has comment: http://stackoverflow.com/comment/88435391
has body: Sorry about the vague heading, it's difficult to explain. I have two pandas df's which contain related information. One contains data that displays timestamps on when an event should occur and the other displays data on when that event actually occurs. I want to determine the difference between these timestamps. The issue is the values that represent each where these events are vary slightly. They are similar but aren't identical. So it's hard to merge or concatenate on a identical value. The first df is when the events should occur: Example df: Sched = pd.DataFrame({ 'E' : ['Home','Shops','Away','Shops','Home'], 'F' : ['10:00:00','11:00:00','12:00:00','13:00:00','14:00:00'], 'G' : ['No: 10', 'No: 2', 'No: 1','No: 3','No: 11'], }) So the place where events occur are labelled in Column E. e.g. Home, Shops, Away. This df displays when the event actually occurs: Meet = pd.DataFrame({ 'A' : ['10:00:05','11:00:05','12:00:05','13:00:05','14:00:05'], 'B' : ['HOME LOCK','AWAY HR','SHOPS JK','HOME LOCK','SHOPS JK'], 'C' : ['No:','No:','No:','No:','No:'], 'D' : ['10', '1', '2','11','3'], }) So the data in Column B is at the same meeting (Home, Away, Shops) but theres a few differences. It's all in capital letters, there's a few additional strings to some too. I have considered trying to map the appropriate codes in using: Code = pd.DataFrame({ 'H' : ['HOME LOCK','AWAY HR','SHOPS JK'], 'I' : ['Home','Away','Shops'], }) Meet['B'] = Meet['B'].map(Code.set_index('H')['I']) That way I could merge the output with the sched df. The problem is theres hundreds of codes and they continuously change each day. Is there a way to do a partial match of values? As in, can values which are largely the same be merged?
tagged with: concatenation
tagged with: pandas
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50713146
score: 1
has title: Combine two pandas df's based on a partial match
favorite count: 0
has comment: http://stackoverflow.com/comment/88435075
tagged with: python
tagged with: merge

http://stackoverflow.com/comment/88553888
score: 1
comment on: http://stackoverflow.com/q/50773216
type: Comment
type: QuestionComment
has text: Show us your code of `transform_country` method.

telegram
tags question: http://stackoverflow.com/q/50755566
tags question: http://stackoverflow.com/q/50755540
tags question: http://stackoverflow.com/q/50772320
tag name: telegram
type: Tag
tags question: http://stackoverflow.com/q/50771931
tags question: http://stackoverflow.com/q/50791248
tags question: http://stackoverflow.com/q/50717440

http://stackoverflow.com/comment/118294925
score: 0
type: AnswerComment
has text: The corresponding design pattern is named "Value Object" (different names may exist). https://martinfowler.com/bliki/ValueObject.html
type: Comment
comment on: http://stackoverflow.com/a/50817542

http://stackoverflow.com/comment/88606007
type: QuestionComment
has text: Some links that might be useful: [documentation on `urlopen`](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen) and [documentation on `HTTPResponse.read()`](https://docs.python.org/3/library/http.client.html#httpresponse-objects). I'm leaning towards `urlopen`, but their language is vague.
score: 1
comment on: http://stackoverflow.com/q/50799922
type: Comment

http://stackoverflow.com/comment/88457751
has text: This will allow a different card every time! try to test the code before commenting
comment on: http://stackoverflow.com/a/50724662
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88458732
has text: Unfortunately it does not solve my problem. Let me clarify: in +100 the "fraction: 0.2" means that the number has to end with 0.0, 0.2, 0.4, 0.6 or 0.8. So, 100.51 should convert to 100.6 (closest) or 100.4 (down)
type: Comment
comment on: http://stackoverflow.com/a/50723164
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88625597
has text: It also will not work if you are deploying with a multi process web server.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50810023

http://stackoverflow.com/a/50812388
upvote count: 1
has comment: http://stackoverflow.com/comment/88630438
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50811377
answers question: http://stackoverflow.com/q/50811377
has comment: http://stackoverflow.com/comment/88630171
has body: The error message your browser is showing indicates that your site is stuck in an infinite redirect loop. Looking at your condition, it is clear why: if not request.method != 'GET': is equivalent to if request.method == 'GET': A redirect always results in a GET request, so your view will redirect again and again... I assume what you actually want to achieve is to redirect only if there is no URL parameter. Those are stored in request.GET, so your condition would look like this: if not request.GET:
score: 1
has comment: http://stackoverflow.com/comment/88630581
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88630792
has comment: http://stackoverflow.com/comment/88630268

http://stackoverflow.com/q/50822463
tagged with: http://stackoverflow.com/tag/json
tagged with: pymongo
type: Question
upvote count: 1
answer count: 1
favorite count: 0
has body: I am trying to take user input, create a URI, and add it with a collection in Pymongo, but whenever I try to do this, the format gets messed up and I cant figure out how to fix it. When running the line: print(db.command("create", "storage", someStorage={ "URI": {FS_URI}})) where "Storage" is the collection, I want the object to be {"fs" : "something://a:b"} or {'fs' : 'something://a:b'} FS_URI = ('\"fs\" : \"'+URI+'\"') gives the error: Cannot encode object: {'"fs" : "something://a:b"'} FS_URI = ("fs\" : \"%s" % URI) gives the error" Cannot encode object: {'fs" : "something://a:b'} FS_URI = ("fs\' : \'%s" % URI) gives the error" Cannot encode object: {"fs' : 'something://a:b"} The quotes are always unmatching, or have extra quotes around them. I have tried the command with the actual URI in the quote format I want, and it runs perfectly.
tagged with: python
has answer: http://stackoverflow.com/a/50827370
has title: Opposite single/double quotes using pymongo command
accepted answer: http://stackoverflow.com/a/50827370
tagged with: quotes
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/50779467
favorite count: 0
has comment: http://stackoverflow.com/comment/88565832
answer count: 0
type: UnansweredQuestion
upvote count: 1
has title: why cannot I keep all varibles in the list when while loop is running
tagged with: list
has comment: http://stackoverflow.com/comment/88565817
tagged with: loops
has comment: http://stackoverflow.com/comment/88594180
type: Question
downvote count: 0
score: 1
tagged with: while-loop
has body: while not endgame: cardsOnTable = OnTable() faceUp1 = player1.dequeue() cardsOnTable.place('player1',faceUp1,False) faceUp2 = player2.dequeue() cardsOnTable.place('player2',faceUp2,False) print(str(cardsOnTable)) size1 = player1.size() size2 = player2.size() print('Player1 : '+str(size1),'Player2 : '+str(size2)) result = compareCard(faceUp1,faceUp2) elif result == 0: print('WAR STARTS!!!') i = 0 player1war = [] #a list for placing player1's card in war(cards on table) player2war = [] #a list for placing player2's card in war(cards on table) while i &lt; nbWarCards: faceDown1 = player1.dequeue() player1war.append(faceDown1) faceDown2 = player2.dequeue() player2war.append(faceDown2) i += 1 for card in player1war: cardsOnTable.place('player1',card,True) player1war.clear() for card in player2war: cardsOnTable.place('player2',card,True) player2war.clear() if player1.size() == 0 or player2.size() == 0: endgame = True my problem happens when I tried to print(str(cardOnTable)) when the first time this while loop runs, it will give me [AS | AH], that's what I want. However, when this while loop runs second time, it is supposed to print [A3 XX XX XX AS | AH XX XX XX A5],it only prints [A3 | A5]. this is my class OnTable(): class OnTable: def __init__(self): self.__cards = [] self.__faceUp = [] def place(self,player,card,hidden): if player == 'player2': self.__cards.append(card) if hidden == False: self.__faceUp.append(False) elif hidden == True: self.__faceUp.append(True) elif player == 'player1': self.__cards.insert(0,card) if hidden == False: self.__faceUp.insert(0,False) elif hidden == True: self.__faceUp.insert(0,True) #return self.__cards def cleanTable(self): self.__cards.clear() self.__faceUp.clear() def __str__(self): for i in range(len(self.__faceUp)): if self.__faceUp[i] == True: self.__cards[i] = 'XX' list1 = '[' for item in self.__cards: list1 += (str(item)+' ') list1 = re.sub(' ', ' ', list1.strip()) half = int(len(list1)//2) list1 = list1[:half] + ' |' + list1[h…
tagged with: python

http://stackoverflow.com/comment/88566280
type: QuestionComment
has text: It is still showing me as none
type: Comment
comment on: http://stackoverflow.com/q/50779576
score: 0

http://stackoverflow.com/a/50744691
answers question: http://stackoverflow.com/q/50744471
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: You correctly provided the argument end=" " to print inside your loop, but forgot about it for the print before your loop. n = int(input('How many terms you want to Generate: ')) i = 1 j = 1 k = 0 print(i, j, end=" ") while k &lt; n: j += i print(j, end=" ") i = j-i k += 1 Output: How many terms you want to Generate: 5 1 1 2 3 5 8 13 Although, note that your solution still does not print the correct number of elements. Improvements More elegants solutions exist using generators, which are well-suited to represent infinite sequences. import itertools def fib(): a, b = 1, 1 while True: yield a a, b = b, a + b n = int(input('How many terms you want to Generate: ')) print(*itertools.islice(fib(), n)) Output: How many terms you want to Generate: 5 1 1 2 3 5

http://stackoverflow.com/comment/88519953
score: 2
comment on: http://stackoverflow.com/q/50755932
type: Comment
type: QuestionComment
has text: your text isn't unicode because it doesn't have the `u` prefix (python 2 needs it)

http://stackoverflow.com/q/50843636
upvote count: 4
tagged with: logging
downvote count: 0
has body: I'm using Robot Framework to run python scripts that I've made and I'm running into an issue when I try to do logging through a custom root logger that I've been using to output my python logging in a desired format. If I don't use a root logger RF will output my logs just fine, but if I use my root logger then RF doesn't output and of the logging done by my python scripts. Here's my code: logger.py: import logging.config import os _WORKSPACE = os.getenv( 'WORKSPACE', default=R'C:\opt\ci\jenkins\workspace\Killer_Automation_Robot' ) def _get_named_logging_config(test_name): named_logging_config = dict( version = 1, disable_existing_loggers = False, formatters = { 'file': { 'format': '[%(asctime)-s] {%(filename)-30s:%(lineno)-3d} %(levelname)-8s - %(message)-s' }, 'console': { 'format': '[%(asctime)-s] {%(filename)-30s:%(lineno)-3d} %(levelname)-8s - %(message)-s' } }, handlers = { 'default': { 'level': 'INFO', #'level': 'DEBUG', 'formatter': 'console', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'formatter': 'file', 'class': 'logging.FileHandler', 'filename': ''.join([ _WORKSPACE, R'\{!s}.log'.format( test_name ), ]), 'mode': 'w', 'encoding': 'utf-8' }, }, loggers = { '': { 'handlers': ['default','file'], 'level': 'DEBUG', 'propagate': True }, 'hammer': { 'handlers': ['default'], 'level': 'WARN', 'propagate': False }, }, root = { 'handlers': ['default','file'], 'level': 'DEBUG', }, ) return named_logging_config def instantiate_logger(name): named_logging_config = _get_named_logging_config( ''.join([ 'robot_', name, ]) ) return named_logging_config def make_logging(): named_logging_config = instantiate_logger('do_math') logging.config.dictConfig(named_logging_config) log = logging.getLogger('') do_something.robot *** Settings *** Library do_math *** Test Cases *** Logging test do logging do_something.py: import logger import logging logger.make_logging() log = logging.getLogger(__name__) log.info('Starting {!s}'.format('Install Software Test')) cl…
has answer: http://stackoverflow.com/a/56627468
type: Question
tagged with: robotframework
tagged with: automation
score: 4
answer count: 2
has title: Using a python root logger with robot framework
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50862517
tagged with: python

http://stackoverflow.com/comment/88422546
type: Comment
comment on: http://stackoverflow.com/q/50706682
type: QuestionComment
score: 2
has text: You are probably facing the output buffering. Check this out: https://stackoverflow.com/questions/107705/disable-output-buffering

http://stackoverflow.com/q/50796257
tagged with: python-import
has comment: http://stackoverflow.com/comment/88601053
score: 0
has body: I'm trying to import a Python script as a module into one of my Notebooks, but the import or import importlib commands do not work in Jupyter Notebook like they do in a standard Python file and terminal. I've come across the %load command but as far as I understand and have seen in my own Notebook, is that it only loads the contents of the script I'm trying to import into the current cell and is invisible to the other cells, and it also outputs the code in the script being imported for everyone to see. I want to be able to load the script and make it available to all cells, as well as hiding the code for the purpose of encapsulation and also keeping the Notebook neat and tidy - only focusing on the code relevant to the topic of the Notebook. Is this possible?
has title: How to load Python script into Jupyter Notebook without revealing code and making it available to all cells
tagged with: jupyter-notebook
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88598709
type: Question

http://stackoverflow.com/comment/88636705
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50814714
has text: I already used `Counter`, I'm quite familiar with it. It's the idea of subclassing that sound funny. I need to look more into it, anyway, thanks a lot!
score: 0

http://stackoverflow.com/q/50729188
type: Question
upvote count: 4
has body: Right now I am coloring a cell in openpyxl in Python by importing this: from openpyxl.styles import Color, PatternFill, Font, Border and then doing this: myFill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type = 'solid') ws.cell(row=row,column=column).fill = myFill Where "ws" is a worksheet, row and column are a particular row and column, etc. This works great, but adjacent cells are totally filled and it's hard to distinguish one cell from another without grid lines. Is there any simple way to adjust this code so that the grid lines remain but the color is still there?
score: 4
has answer: http://stackoverflow.com/a/50742171
has title: How do I color a cell with openpyxl while retaining the grid lines?
tagged with: colors
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/24917201
has comment: http://stackoverflow.com/comment/88482108
accepted answer: http://stackoverflow.com/a/50742171
tagged with: python
tagged with: excel
type: AnsweredQuestion
tagged with: fill
tagged with: openpyxl

http://stackoverflow.com/comment/88518638
comment on: http://stackoverflow.com/q/50755186
has text: try `import logging` and then in `except` `logging.exception(str(e))`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88475020
type: AnswerComment
comment on: http://stackoverflow.com/a/50733196
type: Comment
has text: Assuming you already have the tail pointer set to the last guy, this should work... It is just swapping the two guys and then adjusting their corresponding next guys
score: 0

http://stackoverflow.com/a/50767863
has body: You need: df['Position'] = np.where((df['Volume'] &gt; df['Volume'].shift(-1)) &amp; ((df['Close'] &gt;= df['Close'].shift(-1)) &amp; (df['Open'] &lt;= df['Open'])),"UP","DOWN") Output: Open High Low Close Volume Position 0 1.20821 1.20821 1.20793 1.20794 138.96 UP 1 1.20794 1.20795 1.20787 1.20788 119.61 DOWN 2 1.20788 1.20793 1.20770 1.20779 210.42 DOWN 3 1.20779 1.20791 1.20779 1.20789 77.51 DOWN 4 1.20789 1.20795 1.20789 1.20792 56.97 DOWN
has comment: http://stackoverflow.com/comment/88543594
score: 8
has comment: http://stackoverflow.com/comment/88543722
answers question: http://stackoverflow.com/q/50767799
type: Answer
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/88543559

http://stackoverflow.com/q/50732157
tagged with: python
upvote count: 0
has title: How do I rename the 1 values in a categorical variable as the header of the column?
has comment: http://stackoverflow.com/comment/88472567
type: Question
has body: I have a Pandas DataFrame with several categorical variables (1 or 0) and I would like to rename the 1 value as per its own variable name, how to do it? Name Achiever Arranger Belief Consistency Deliberative 0 Alex 1.0 0.0 0.0 0.0 0.0 13 Luke 0.0 0.0 0.0 1.0 0.0 I would like to return Name Achiever Arranger Belief Consistency Deliberative 0 Alex Achiever 0.0 0.0 0.0 0.0 13 Luke 0.0 0.0 0.0 Conistency 0.0
score: -2
tagged with: rename
has comment: http://stackoverflow.com/comment/88472208
downvote count: 2
tagged with: pandas
answer count: 1
tagged with: header
has answer: http://stackoverflow.com/a/50734031
favorite count: 0
linked to: http://stackoverflow.com/q/11346283
type: UnansweredQuestion

http://stackoverflow.com/a/50849130
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88702655
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50848795
upvote count: 2
answers question: http://stackoverflow.com/q/50848795
has body: Your sons attribute is a dict, mapping single-character strings to nodes. So, when you do this: for son in currentNode.sons: … each son is a single-character str object, not a Node object. That's why the first recursive call prints out q, and why it raises an exception about that 'q' string not having a sons attribute. If you want to iterate over the values in a dict, rather than the keys, you need to say so: for son in currentNode.sons.values(): You have multiple other errors in your code, from invalid indentation to typos like ccurrentChar, and it's incomplete (there's no writeCSVFile function anywhere), so I can't test whether this actually fixes your function—but it does fix this particular bug.

http://stackoverflow.com/a/50742155
score: 1
upvote count: 1
has body: If you don't care about the distribution, you can simply use uniform distribution from random. Assuming the original DataFrame is named df and you want a random_df of the same length: from random import random import pandas as pd A_max = df['A'].max() B_max = df['B'].max() random_df = pd.DataFrame(columns=df.columns) i = 0 while i &lt; range(len(df)): A_random = int(random() * A_max) B_random = int(random() * B_max) # Checking that the combination does not exist in the original DataFrame if len(df[(df['A'] == A_random) &amp; (df['B'] == B_random)] == 0: i += 1 random_df.append({'A': A_random, 'B': B_random}, ignore_index=True)
answers question: http://stackoverflow.com/q/50741349
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50741349

http://stackoverflow.com/a/50791380
answers question: http://stackoverflow.com/q/50791347
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50791347
score: 2
has comment: http://stackoverflow.com/comment/88588783
has comment: http://stackoverflow.com/comment/88588897
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88588817
downvote count: 0
has body: I believe need parameter skipinitialspace=True in read_csv: main_df = pd.read_csv(filename, skipinitialspace=True) And then stripping columns is not necessary. But if need use your function: return dataframe
type: Answer

http://stackoverflow.com/a/50727781
accepted answer of: http://stackoverflow.com/q/50727428
answers question: http://stackoverflow.com/q/50727428
type: AcceptedAnswer
score: 0
has body: You have circular dependent imports. you try to execute import lib.core.common as abc in two files, in driver.py and in util.py The easiest way to fix this is to move the path import to the end of the node module, some docs, or def dostuff(): from foo import bar ... or this also will work, from lib.core import common as abc When Python imports a module, it checks the module registry to see if the module was already imported. If the module was already registered, Python uses that existing object from cache. The module registry is a table of modules that have been initialized and indexed by module name. This table can be accessed through sys.modules. If it was not registered, Python finds the module, initializes it if necessary, and executes it in the new module's namespace.
type: Answer
has comment: http://stackoverflow.com/comment/88463990
has comment: http://stackoverflow.com/comment/98803914
has comment: http://stackoverflow.com/comment/88464155

http://stackoverflow.com/a/50737336
answers question: http://stackoverflow.com/q/50737026
score: 0
has body: If you are looking for a scripting solution you can do TCP/IP part using ssh. Client can use ssh to log into the RPi and run the commands. It can use scp for pushing updated code/script. For automating you can look into Pexpect that lets you script your steps.
type: Answer

http://stackoverflow.com/comment/88605445
type: Comment
comment on: http://stackoverflow.com/q/50799656
score: 0
type: QuestionComment
has text: Could you please add a stack trace of your exceptions?

http://stackoverflow.com/comment/88457721
comment on: http://stackoverflow.com/q/50724655
type: Comment
type: QuestionComment
has text: Please show the view.
score: 0

http://stackoverflow.com/comment/88481238
score: 0
comment on: http://stackoverflow.com/a/50717494
has text: The report title (the report name + the line "Report generated on ...") are not affected by this and will be still present.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88600015
type: AnswerComment
has text: @Austin, Bear Brown, Rory Daulton - Thanks for your valuable comments.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50796646

http://stackoverflow.com/q/50780220
has comment: http://stackoverflow.com/comment/88567288
has comment: http://stackoverflow.com/comment/88567706
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88567367
has title: Python Serial and CSV for Arduino
possible better answer: http://stackoverflow.com/a/50923950
has body: I'm trying to write a code to read value from Arduino Uno every 2ms. At the Arduino end here is the code and what it will send every 2ms. Serial.print(AngleV); Serial.print(","); Serial.print(AngleH); Serial.print(","); Serial.println(distance); whereas the AngleV value is from 0-180,AngleH value is from 0-3600,distance value is from 0-4000. At the pc end, I want to read all 3 value in, then do some calculation and write it to the csv file: x = distance * sin(AngleV)*cos(AngleH) y = distance * cos(AngleV)*sin(AngleH) z = distance * cos(AngleV) So in the .csv file it will be something like x,y,z.... So far this is what I have done.Can any one point me to what to do next? Thank you for your time. import serial import csv # open com port ser = serial.Serial('COM4', 115200) print (ser.name) # create csv file with open('C:/Users/sylan/Desktop/Python/datafile.csv', 'w') as new_file: csv_writer = csv.writer(new_file) while True: line = ser.readline() print(line) if line[0] == "B": line = line[1:len(line)] if line[len(line)-2] == "E": line = line[:(len(line)-2)] csv_writer.writerow([line]) print('\n\nThis is the end of the file\n') ser.close() break else: line = line[:(len(line)-1)] csv_writer.writerow([line])
tagged with: python
tagged with: arduino
has comment: http://stackoverflow.com/comment/88567528
has comment: http://stackoverflow.com/comment/88567450
type: AnsweredQuestion
tagged with: math
has comment: http://stackoverflow.com/comment/88567219
has answer: http://stackoverflow.com/a/50923950
has comment: http://stackoverflow.com/comment/88567432
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50780507
accepted answer: http://stackoverflow.com/a/50780507

list-comprehension
tags question: http://stackoverflow.com/q/50780322
tags question: http://stackoverflow.com/q/50769728
tags question: http://stackoverflow.com/q/50816604
tags question: http://stackoverflow.com/q/50819224
tags question: http://stackoverflow.com/q/50814296
tags question: http://stackoverflow.com/q/50757595
tags question: http://stackoverflow.com/q/50727460
tags question: http://stackoverflow.com/q/50774884
tag name: list-comprehension
tags question: http://stackoverflow.com/q/50768493
tags question: http://stackoverflow.com/q/50715058
type: Tag
tags question: http://stackoverflow.com/q/50756085
tags question: http://stackoverflow.com/q/50843126
tags question: http://stackoverflow.com/q/50776263
tags question: http://stackoverflow.com/q/50756288

http://stackoverflow.com/comment/88484437
comment on: http://stackoverflow.com/q/50737444
type: Comment
has text: firstly, to achieve your goal here, i recommend the use of `numpy.take()`; to answer your question why your slicing assignments fails: `cop` still referes to the lists in `target`, which is modified during the loop; as said,complex types should always be explicitly copied
type: QuestionComment
score: 1

http://stackoverflow.com/q/50794467
has answer: http://stackoverflow.com/a/50795782
accepted answer: http://stackoverflow.com/a/50795782
has comment: http://stackoverflow.com/comment/88596484
tagged with: python
has comment: http://stackoverflow.com/comment/88595473
downvote count: 0
tagged with: equation
tagged with: plot
type: AnsweredQuestion
score: 1
has body: I've done a regression so I obtained: slope_b = -0.7583790156301706 intercept_b = 7.22190409922338 r_value_b = -0.887981466827434 I want to add the regression equation into the plot like: y = -0.76x + 7.22 r = -0.88 As I couldn't find the way to do it I did like a text: axarr[0].text(8,6,'y=-0.76x+7.22') axarr[0].text(9,5, 'r²=-0.88') However, I add variables all the time to the regression so the slope, intercept and r_value are changing so I have to change the expression every time. I did some research and I found this: axarr[0].text(8,6,'y=', slope_b, '*x+', intercept_b) But I didn't get the wanted result. Also, is there a way to have these values with just two decimals? I prefer a shorter number in the equation rather than this: -0.7583790156301706.
type: Question
has title: Writing regression equation in plot python
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/50807014
has body: There's a typo in your payload key, can you try it again with "message" instead of "massage"?
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/88622382
downvote count: 0
type: AcceptedAnswer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50789210
answers question: http://stackoverflow.com/q/50789210

code-generation
tag name: code-generation
tags question: http://stackoverflow.com/q/50822656
type: Tag

http://stackoverflow.com/a/51008969
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50843354
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50843354
type: Answer
score: 3
upvote count: 3
has body: I had to dig through pip source code to make an educated guess here. The "simple" console script is generated when whatever you install is installed through a wheel. So you could make sure it's generated this way by making a wheel out of your package and installing the wheel.

http://stackoverflow.com/a/50754224
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50754075
has body: You can try this : while Name == "" or Name.isnumeric() == True: Name = input("What is your name? ") print("") Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.

http://stackoverflow.com/q/50722883
type: Question
has comment: http://stackoverflow.com/comment/88459861
has answer: http://stackoverflow.com/a/50724001
has body: I've found many posts regarding rounding in python, but from my understanding none so far solves my problem. Two solutions I'm looking for: Round closest: float/string numbers which need to be rounded differently depending on their size. Round down: float/string numbers which need to be rounded down differently depending on their size. Round up: float/string numbers which need to be rounded up differently depending on their size. Example: +500: 0 decimals (whole numbers) (e.g., Closest: 500.5 -> 501; Down: 500.99 -> 500; Up: 500.01 -> 501) +100: 1 decimals (fraction: 0.2) (e.g., Closest: 100.29 -> 100.2; Down: 100.39 -> 100.2; Up: 100.21 -> 100.4). So, the value must end with .0, .2, .4, .6 or .8 +5: 2 decimals (fraction: 0.01) (e.g., Closest: 5.019 -> 5.02; Down: 5.019 -> 5.01; Up: 5.011 -> 5.02). So, the value must end with .x0, .x1, .x2, .x3, .x4, .x5, .x6, .x7, .x8 or .x9 The resulting variable should be a string. The neat thing I'm, looking for is a function in which i can pass number of decimals and fraction
tagged with: rounding
tagged with: decimal
possible better answer: http://stackoverflow.com/a/50723164
answer count: 2
has comment: http://stackoverflow.com/comment/88454353
has answer: http://stackoverflow.com/a/50723164
downvote count: 0
tagged with: floor
accepted answer: http://stackoverflow.com/a/50724001
favorite count: 0
tagged with: python
has title: python: round/format float/string to specific decimal/fraction
type: AnsweredQuestion
tagged with: fractions
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88454194

http://stackoverflow.com/q/50804025
tagged with: numpy
score: 0
has answer: http://stackoverflow.com/a/50824375
has comment: http://stackoverflow.com/comment/88617707
tagged with: pandas
answer count: 1
tagged with: dataset
has comment: http://stackoverflow.com/comment/88628284
tagged with: python
has comment: http://stackoverflow.com/comment/88653784
has comment: http://stackoverflow.com/comment/88614293
has body: I want to encode a column of dataset in LabelEncoder and the others one in MinMaxScaler. But it remains a float64 BinEncoder = LabelEncoder() scalar = MinMaxScaler() dat = df.values X = dat[0:500,0:5] X[:,-1] = BinEncoder.fit_transform(X[:,-1]) X[:,0:4] = scalar.fit_transform(X[:,0:4]) print(X) print(X) , returns : [[0.35435163 1. 0.96428571 0.05465126 0. ] [0.07876241 0.85714286 0.85714286 0.04695418 0. ] [0.11814948 0.64285714 0.5 0.08307676 3. ] ... [0.25025542 0.79166667 0.54285714 0.10023708 1. ] [0.25029285 1. 1. 0.0569226 1. ] [0.25025127 1. 0.82608696 0.06935726 0. ]] Full code: import pandas as pd from sklearn.preprocessing import LabelEncoder,MinMaxScaler import numpy as np df = pd.read_csv('./EURUSD_DATAFRAME.csv') BinEncoder = LabelEncoder() scalar = MinMaxScaler() dat = df.values #print(df.head()) X = dat[0:500,0:5] Y = dat[:,5] X[:,4] = BinEncoder.fit_transform(X[:,4]) print(X[:,-1]) X[:,0:4] = scalar.fit_transform(X[:,0:4]) print(X[:,-1]) print(X) Y=BinEncoder.fit_transform(Y) X = X.reshape(100,5,5) #print(X[0])
type: AnsweredQuestion
has title: Encode partialy of a dataset
accepted answer: http://stackoverflow.com/a/50824375
has comment: http://stackoverflow.com/comment/88617424
has comment: http://stackoverflow.com/comment/88615607
has comment: http://stackoverflow.com/comment/88614248
tagged with: dataframe
type: Question

http://stackoverflow.com/comment/88678387
type: QuestionComment
has text: @VincentvanderWeele Thanks for your reply! All first common elements should form a string. Sublists with no matching first elements just should become a big single string.
comment on: http://stackoverflow.com/q/50837066
score: 0
type: Comment

http://stackoverflow.com/comment/88639009
comment on: http://stackoverflow.com/q/50784147
score: 0
has text: @MartinHennings hey, I need to do this without changing application code.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50851661
type: Question
has body: I seem to have a very common problem although nothing I try works for me: I have installed Python 3.6.5 for Windows 64 bit and am using Vs Code for editing. I used Ubuntu to install pip3 and then installed gspread as follows: pip3 install gspread Although import gspread gives an error: Traceback (most recent call last): File "c:\Users\User\Documents\Vs Code\test.py", line 2, in &lt;module&gt; import gspread ModuleNotFoundError: No module named 'gspread' How do I fix this problem to import gspread?
tagged with: visual-studio-code
tagged with: ubuntu
score: 0
has comment: http://stackoverflow.com/comment/88773153
has comment: http://stackoverflow.com/comment/88706598
has comment: http://stackoverflow.com/comment/88706659
answer count: 1
has comment: http://stackoverflow.com/comment/88731632
has comment: http://stackoverflow.com/comment/88706342
type: UnansweredQuestion
has title: No module named 'gspread', ModuleNotFoundError. Problem with import in Python
tagged with: python
tagged with: gspread
has comment: http://stackoverflow.com/comment/88706767
has answer: http://stackoverflow.com/a/64245030

http://stackoverflow.com/a/50729461
upvote count: 1
has body: You just need groupby + mean + stack df.groupby('place').mean().stack().rename_axis(['name', 'color']).to_frame('avg').reset_index() Outputs place color avg 0 MO red 0.6 1 MO green 2.2 2 MO yellow 3.0 3 NJ red 1.4 4 NJ green 3.2 5 NJ yellow 3.8 6 VA red 4.4 7 VA green 2.6 8 VA yellow 6.6
answers question: http://stackoverflow.com/q/50729226
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/50839348
answers question: http://stackoverflow.com/q/50838388
score: 9
accepted answer of: http://stackoverflow.com/q/50838388
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88684793
upvote count: 9
type: Answer
has body: Something like this? @client.event async def on_member_update(before, after): if str(before.status) == "online": if str(after.status) == "offline": print("{} has gone {}.".format(after.name,after.status)) That is if you want it to only trigger when the user has been online and goes "offline" You can do something like @client.event async def on_member_update(before, after): if str(after.status) == "offline": print("{} has gone {}.".format(after.name,after.status)) if you want it to trigger when the user was "Idle" or "dnd" and went "offline".
has comment: http://stackoverflow.com/comment/88690376
downvote count: 0
has comment: http://stackoverflow.com/comment/88685320
has comment: http://stackoverflow.com/comment/88689203
has comment: http://stackoverflow.com/comment/88694627

http://stackoverflow.com/comment/105477964
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59364846
score: 0
has text: @Learning stats by example In *Python 3*, the maximum length of an integer number is not `63`. It's kind of unlimited as the integer is represented as an array of 64-bit integers. Hence, `O(log(n))` is valid.

http://stackoverflow.com/a/50769607
accepted answer of: http://stackoverflow.com/q/50769456
has body: GridSpec has an argument height_ratios. You can set it to a list of the vertical shape of the heatmaps. import numpy as np import matplotlib.pyplot as plt data = [np.random.rand(n,8) for n in [3,7,10,4]] fig, axes = plt.subplots(nrows=len(data), gridspec_kw=dict(height_ratios=[d.shape[0] for d in data])) for ax, d in zip(axes, data): ax.imshow(d) ax.tick_params(labelbottom=False) plt.show()
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50769456

http://stackoverflow.com/q/50777830
score: 0
has answer: http://stackoverflow.com/a/50778043
accepted answer: http://stackoverflow.com/a/50778043
upvote count: 1
tagged with: sqlite
answer count: 1
downvote count: 1
tagged with: variables
has comment: http://stackoverflow.com/comment/88562752
has title: how to insert variable in sqlite3 request python
favorite count: 0
has comment: http://stackoverflow.com/comment/88562895
tagged with: python
type: AnsweredQuestion
type: Question
has body: Dears, how can I check if pos_cli from database is equal to variable pos_id? for now with code below I get the following error cur.execute("CREATE TABLE IF NOT EXISTS Magnit_Coor (pos_cli INTEGER PRIMARY KEY, lat INTEGER, long INTEGER);") cur.execute('SELECT * FROM Magnit_pos') data = cur.fetchall() while True: for coo in data: full_add = coo[6:11] pos_id = coo[0] print (pos_id) yand_add = ", ".join(full_add) g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_Coor WHERE pos_cli = (?))',pos_id) g = cur.fetchone()[0] error below 10001 Traceback (most recent call last): File "geoco.py", line 17, in &lt;module&gt; g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_pos WHERE pos_cli = (?))',pos_id) ValueError: parameters are of unsupported type The initial code to create Magnit_pos table and pos_cli especially below cur.execute("DROP TABLE IF EXISTS Magnit_Pos;") cur.execute( "CREATE TABLE Magnit_Pos (pos_cli INTEGER PRIMARY KEY, magnit_name TEXT, codesfa TEXT, codewsot TEXT, pos_sap TEXT, source_dc TEXT, zip TEXT, region TEXT, area TEXT, city TEXT, street TEXT, house TEXT, build TEXT);") with open('magnit.csv') as csvfile: magnit = csv.reader(csvfile, delimiter=';') print(magnit) for row in magnit: print(row[0]) # to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8")] cur.execute("INSERT INTO Magnit_Pos (pos_cli, magnit_name, codesfa, codewsot, pos_sap, source_dc, zip, region, area, city, street, house, build) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", row)

http://stackoverflow.com/q/50793994
has body: I have written a class in views.py file for adding a group in auth_group table. But i am getting an error message saying: - duplicate key value violates unique constraint "auth_group_name_key" DETAIL: Key (name)=() already exists. Following is my views.py file code. class AddGroup(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def post(self, request): log.debug("Getting into the function !!") try: log.debug(request.data) group11 = Group.objects.create() log.debug(group11) group11.save(2, str(request.data['customer'])) # group11.save(str(request.data['customer'])) log.debug(group11) return Response(request.data['customer']+' created successfully !!', status= status.HTTP_201_CREATED) Following is my models.py code class MyGroup(GroupManager): use_in_migrations = True def create(self, group_name): # GroupManager.create(group_name) group = self.model( group_name=group_name, ) group.save(using=self._db) return group
tagged with: django-models
score: 0
answer count: 1
tagged with: django-rest-framework
has title: How to make use of auth_group table in Django
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50794992
type: AnsweredQuestion
tagged with: django-views
type: Question
has answer: http://stackoverflow.com/a/50794992

sympy
tags question: http://stackoverflow.com/q/50854803
tags question: http://stackoverflow.com/q/50802583
tag name: sympy
tags question: http://stackoverflow.com/q/50798642
tags question: http://stackoverflow.com/q/50706092
tags question: http://stackoverflow.com/q/50710258
tags question: http://stackoverflow.com/q/50750966
tags question: http://stackoverflow.com/q/50754020
tags question: http://stackoverflow.com/q/50816096
type: Tag
tags question: http://stackoverflow.com/q/50782952
tags question: http://stackoverflow.com/q/50708170

http://stackoverflow.com/a/50720612
type: Answer
upvote count: 1
has body: The problem was that when I was saving the file, the PIL library automatically switched the color space of the image(ROMM-RGB) to other color space(RGB or sRGB) and basically every color changed. All you have to do is preserve the color space of the image and you're fine. If you want to convert to another color space you should look up OpenCV library. I can't explain too much in detail because I am just breaking the ice on this. Here is the code that solved this issue: resized_image.save('resized.jpg', #file name format = 'JPEG', #format of the file quality = 100, #compression quality icc_profile = resized_image.info.get('icc_profile','')) #preserve the icc profile of the photo(this was the one that caused problems) Here is a link to a more in-depth answer: LINK
score: 1
accepted answer of: http://stackoverflow.com/q/50714025
downvote count: 0
answers question: http://stackoverflow.com/q/50714025
type: AcceptedAnswer

http://stackoverflow.com/comment/88670403
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50832937
has text: @IljaEverilä yeah, i get it right now and i dont understand what i need to put here, im new at work with databaases
score: 0

http://stackoverflow.com/comment/88469824
comment on: http://stackoverflow.com/a/50731043
score: 1
has text: Looks like no need to convert `Series` to `dataframe` for plotting.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88622551
has text: would that work?? :o
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50808335

http://stackoverflow.com/q/50819225
favorite count: 0
has title: How to give column list for select statement in sqlalchemy?
tagged with: python
type: AnsweredQuestion
has body: below code is for select "country", "gender" from "Message" where ~ users = session.query( Message.country, Message.gender, ).filter( Message.date_joined.between(begin_date, end_date), ).all() when I try sql with this columns = ( Message.country, Message.gender, ) users = session.query( columns ).filter( Message.date_joined.between(begin_date, end_date), ).all() I got error sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '(&lt;sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x117f215c8&gt;, &lt;sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x117f21518&gt;)' I thought if i gave parameter as tuple, would be possible however there was exception. How can I give columns as variable for query?
score: 1
accepted answer: http://stackoverflow.com/a/50820376
upvote count: 1
tagged with: sqlalchemy
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50820376

http://stackoverflow.com/comment/88424789
has text: I need to be able to print these count values to a single .CSV file. Each file that's opened will consume only one line in the output. Hope this makes sense. :)
comment on: http://stackoverflow.com/q/50707821
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88422148
has text: That fixed it! Would you answer that so I can mark it as the correct answer?
comment on: http://stackoverflow.com/q/50706311
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50845837
accepted answer of: http://stackoverflow.com/q/50843032
has body: For a list of objects, Python knows how to iterate over it directly so you can eliminate the index shown in most of the other answers, res = [func1(c, value) for c in centroids] That's all there is to it.
score: 5
answers question: http://stackoverflow.com/q/50843032
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 5

http://stackoverflow.com/a/50854667
type: Answer
answers question: http://stackoverflow.com/q/50854417
has body: I also had the same error and my work around the issue was putting using this code after your model fit. parallel_model.fit(x_train,y_train,epochs = 1, batch_size =2000) from keras.models import model_from_json # serialize model to JSON model_json = parallel_model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model.h5") print("Saved model to disk")
score: 2
has comment: http://stackoverflow.com/comment/88716273
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50854417
upvote count: 2

http://stackoverflow.com/q/50769024
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88545988
has body: I'm new to python and have been playing around with it and have ran into a problem using PyQt5. Could someone please explain to me what this means: ModuleNotFoundError: No module named 'PyQt5.QtWebKit'. Actually, I think I understand WHAT it means, but how do i fix it? I found a solution in another forum but all it said was QtWebKit needed to be compiled in PyQt5. I don't understand what that means or how to do it. I should clarify by saying I have installed PyQt5 and I have ran some example scripts with just simple windows with a few widgets. I started getting this error trying to use code from a tutorial on creating a web browser with PyQt5. I really like the python language and I am wanting to convert a project from Access to python. In the Access project, I have a few WebBrowser controls and I was looking for a GUI toolkit that would allow me to do the same thing using python. I thought PyQt5 would work, but I keep getting the ModuleNotFoundError. I am using Windows 8.1 if that makes a difference.
downvote count: 0
has comment: http://stackoverflow.com/comment/88545780
score: 1
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/88545762
linked to: http://stackoverflow.com/q/37876987
type: Question
has comment: http://stackoverflow.com/comment/88546350
tagged with: pyqt
has comment: http://stackoverflow.com/comment/88546359
tagged with: qtwebkit
upvote count: 1
favorite count: 0
has title: ModuleNotFoundError: No module named 'PyQt5.QtWebKit'
has comment: http://stackoverflow.com/comment/88547014
has comment: http://stackoverflow.com/comment/88546336
answer count: 1
has answer: http://stackoverflow.com/a/50769081

http://stackoverflow.com/a/50749609
type: Answer
upvote count: 1
score: 1
has body: You don't return anything when the first iteration did not give 1 as sum. Change the last line into return self.isHappy(x) (Then you'll find your solution enters an infinite loop when presented with an unhappy number.)
answers question: http://stackoverflow.com/q/50749527
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50749527

http://stackoverflow.com/a/50724662
downvote count: 3
has comment: http://stackoverflow.com/comment/88457739
has comment: http://stackoverflow.com/comment/88457928
upvote count: 0
has comment: http://stackoverflow.com/comment/88457677
answers question: http://stackoverflow.com/q/50724576
has comment: http://stackoverflow.com/comment/88457796
type: Answer
has comment: http://stackoverflow.com/comment/88457897
score: -3
has body: This guarantees a different card every time: from random import randint cards = [2,3,4,5,6,7,8,9,10,'King','Queen','Jack'] first_card = cards[randint(0, len(cards)-1)] second_card = cards[randint(0, len(cards)-1)] while second_card == first_card: second_card = cards[randint(0, len(cards)-1)] print first_card print second_card
has comment: http://stackoverflow.com/comment/88457751

http://stackoverflow.com/comment/88622547
score: 0
has text: @coldspeed not, it should be random filled with one of the top 2 values into its Category. For example, some Technologies NaN values should be filled with "Google" and some others with "Apple".
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50808374

http://stackoverflow.com/a/50837403
answers question: http://stackoverflow.com/q/50837262
type: Answer
has body: In python, you can iterate through a list, basically coding "For each variable in this list, do something". You do it using the for / in for item in list: # do something To solve your example, you have to add 'item' to a variable's value. list = [1, 2, 3, 4, 5] sum = 0 for x in list: sum = sum + x # Or, you just do sum += x print (sum) # To show your result.
score: 0

http://stackoverflow.com/comment/88671273
type: AnswerComment
score: 0
type: Comment
has text: @RagsGupta Is there any incentive to loop over the dictionary?
comment on: http://stackoverflow.com/a/50833328

http://stackoverflow.com/q/50751484
has title: Restore TensorFlow model on different machine
possible better answer: http://stackoverflow.com/a/50997384
has comment: http://stackoverflow.com/comment/88512210
type: AnsweredQuestion
has body: I trained on TensorFlow model on a GPU cluster, saved the model using saver = tf.train.Saver() saver.save(sess, config.model_file, global_step=global_step) and now I am trying to restore the model with saver = tf.train.import_meta_graph('model-1000.meta') saver.restore(sess,tf.train.latest_checkpoint(save_path)) for evaluation, on a different system. The issue is that saver.restore yields the following error: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1664, in &lt;module&gt; main() File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/Users/jonpdeaton/Developer/BraTS18-Project/segmentation/evaluate.py", line 205, in &lt;module&gt; main() File "/Users/jonpdeaton/Developer/BraTS18-Project/segmentation/evaluate.py", line 162, in main restore_and_evaluate(save_path, model_file, output_dir) File "/Users/jonpdeaton/Developer/BraTS18-Project/segmentation/evaluate.py", line 127, in restore_and_evaluate saver.restore(sess, tf.train.latest_checkpoint(save_path)) File "/Users/jonpdeaton/anaconda3/envs/BraTS/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1857, in latest_checkpoint if file_io.get_matching_files(v2_path) or file_io.get_matching_files( File "/Users/jonpdeaton/anaconda3/envs/BraTS/lib/python3.6/site-packages/tensorflow/python/lib/io/file_io.py", line 337, in get_matching_files for single_filename in filename File "/Users/jonpdeaton/anaconda3/envs/BraTS/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 519, in __exit__ c_api.TF_GetCode(self.stat…
tagged with: tensorflow
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88512143
has answer: http://stackoverflow.com/a/50997384
accepted answer: http://stackoverflow.com/a/50997552
score: 0
has comment: http://stackoverflow.com/comment/88512122
has answer: http://stackoverflow.com/a/50997552
tagged with: python

swift
tags question: http://stackoverflow.com/q/50841201
tags question: http://stackoverflow.com/q/50743766
type: Tag
tag name: swift

http://stackoverflow.com/comment/88675175
comment on: http://stackoverflow.com/q/50830227
has text: @desertnaut - No issues. Thanks.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50808091
answers question: http://stackoverflow.com/q/50808055
type: Answer
has body: You're calling randint: Return a random integer N such that a &lt;= N &lt;= b. Alias for randrange(a, b+1). If it's not obvious why this is a problem, let's use a much smaller example: &gt;&gt;&gt; a = ['x', 'y'] &gt;&gt;&gt; len(a) 2 &gt;&gt;&gt; a[0] 'x' &gt;&gt;&gt; a[1] 'y' &gt;&gt;&gt; a[2] IndexError: list index out of range &gt;&gt;&gt; randint(0, 2) 1 &gt;&gt;&gt; randint(0, 2) 2 # oops This is why Python usually uses half-open ranges, where a &lt;= N &lt; b, instead of a &lt;= N &lt;= b. And why you normally want to use randrange instead of randint. Or, even more often, when you find yourself reaching for randint or randrange, there's a good chance you wanted shuffle (which will randomly reorder the whole list in one go), or choice (which will pick a value out of a list, without needing to first pick an index), etc., so skim through the docs to see if what you want is already written.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88622338
upvote count: 1

http://stackoverflow.com/comment/88651113
score: 0
comment on: http://stackoverflow.com/q/50822925
type: QuestionComment
type: Comment
has text: Are you sure `t` is an array as well? It's not `dt` as a float it needs to be an array of all values of `t`.

http://stackoverflow.com/comment/88617927
type: Comment
comment on: http://stackoverflow.com/a/50805736
score: 0
type: AnswerComment
has text: Thanks for your answer. Could you kindly put it in the context of the code that I provided? Specifically, how does my_worker() spawn a new my_worker (to get the next page)? How does my_worker() get access to the loop to call loop.run_in_executor()? Thanks.

http://stackoverflow.com/comment/88588415
score: 0
type: Comment
type: QuestionComment
has text: @ThierryLathuille for using readlines ?
comment on: http://stackoverflow.com/q/50790824

http://stackoverflow.com/q/50710422
tagged with: dictionary
upvote count: 4
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50710459
has answer: http://stackoverflow.com/a/50710603
tagged with: list
downvote count: 0
type: Question
score: 4
has answer: http://stackoverflow.com/a/50710571
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50710603
possible better answer: http://stackoverflow.com/a/50710459
has answer: http://stackoverflow.com/a/50710549
has title: Remove dictionary from list if two dictionaries have duplicate keys
has body: I am still not too familiar with list composition and stuff so I appreciate the help. I have a list of dictionaries which contain a url and a number in each dictionary like so: data = [{'url': 'www.url1.com', 'max': '14.6'}, {'url': 'www.url2.com', 'max': '17.8'}, {'url': 'www.url2.com', 'max': '18.4'}, {'url': 'www.url3.com', 'max': '15.5'}] I would like to filter out any dictionaries with a duplicate url key even if the max key is different from the other duplicate entry. My expected result would be: data = [{'url': 'www.url1.com', 'max': '14.6'}, {'url': 'www.url2.com', 'max': '17.8'}, {'url': 'www.url3.com', 'max': '15.5'}] I have tried quite a few things but none of it is close enough to post here in order to fix. I appreciate your help, thank you!
tagged with: python

http://stackoverflow.com/q/50794251
has comment: http://stackoverflow.com/comment/88594839
score: 1
has comment: http://stackoverflow.com/comment/88595152
favorite count: 0
has answer: http://stackoverflow.com/a/50794767
has body: I am trying to count total times of inversion using def count_inversion def count_inversion(alist): count = 0 if len(alist)&gt;1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] a=count_inversion(lefthalf) b=count_inversion(righthalf) i=0 j=0 k=0 track = 0 while i &lt; len(lefthalf) and j &lt; len(righthalf): if lefthalf[i] &lt; righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 count+=len(righthalf[i:]) k=k+1 while i &lt; len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j &lt; len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 return count def main(): alist = [10,9,8,7,6,5,4,3,2,1] inversion = count_inversion(alist) print(alist) print(inversion) main() I did get a sortred list[1,2,3,4,5,6,7,8,9,10], but for inversion count, it shows it is 25 instead of 45.I think I probably make some error in my code, but I have no idea how to fix it...It would be grateful if someone could help me...
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50796660
tagged with: python
tagged with: merge
has title: how to count inversion by using merge sort?
upvote count: 1
tagged with: inversion
type: Question
downvote count: 0
tagged with: sorting
has answer: http://stackoverflow.com/a/50794407
answer count: 3
has comment: http://stackoverflow.com/comment/88595466

http://stackoverflow.com/a/66514156
type: Answer
answers question: http://stackoverflow.com/q/50725706
has body: When using the same group in both of the group-paramaters of groupcollide it will always consider the sprite it is checking in group_a as colliding with that same sprite in group_b. This results in groupcollide always returning a collision. To get around this I created a new function in pygame's sprite.py that ignores single collisions and only returns collisions >= 2. My only change was to add: if len(collision) >=2: And then the required tab for the following line(s). The code I added to sprite.py is pasted below but the tab for the def intra_groupcollide is one too far: def intra_groupcollide(groupa, groupb, dokilla, dokillb, collided=None): """detect collision between a group and itself. This is modified from groupcollide but excludes collisions <=1 pygame.sprite.groupcollide(groupa, groupb, dokilla, dokillb): return dict """ crashed = {} # pull the collision function in as a local variable outside # the loop as this makes the loop run faster sprite_collide_func = spritecollide if dokilla: for group_a_sprite in groupa.sprites(): collision = sprite_collide_func(group_a_sprite, groupb, dokillb, collided) if collision: if len(collision) >=2: crashed[group_a_sprite] = collision group_a_sprite.kill() else: for group_a_sprite in groupa: collision = sprite_collide_func(group_a_sprite, groupb, dokillb, collided) if collision: if len(collision) >=2: crashed[group_a_sprite] = collision #print(crashed) return crashed Then in my own python program, I simply replaced groupcollide with intra_groupcollide. I set both kill paramaters as 'false' because in my usage I'm bouncing them off each other. I have not tested this code with them set to 'true'. I found sprite.py in my file system by following this answer: Where are the python modules stored?
score: 0

http://stackoverflow.com/q/50776086
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Filter dataframe rows containing a set of string in python
tagged with: python
has answer: http://stackoverflow.com/a/50776095
upvote count: 3
type: AnsweredQuestion
has body: I have a dataframe df like - A B 12 A cat 24 The dog 54 An elephant I have to filter rows based on values on column B containing a list of string. I can do that for a string "cat" as follows: df[df["B"].str.contains("cat", case=False, na=False)] This will return me A B 12 A cat But now I want to filter it for a list of string i.e. ['cat', 'dog',.....]. A B 12 A cat 24 The dog I can do that using a for loop but am searching for a pandas way of doing this. I am using python3 and pandas and have searched a lot of solutions on stack overflow since past 2 days
score: 3
type: Question
accepted answer: http://stackoverflow.com/a/50776095

http://stackoverflow.com/a/50821239
type: Answer
has body: It may be easier to generate the output file without the writer: SEP = ',' # Use any other separator here, if you want with open('outputdata.csv', 'w') as outfile: for line in list_a: outfile.write(SEP.join(['({}; {})'.format(*pair) for pair in line])) outfile.write("\n")
score: 0
has comment: http://stackoverflow.com/comment/88647920
has comment: http://stackoverflow.com/comment/88647825
has comment: http://stackoverflow.com/comment/88648279
has comment: http://stackoverflow.com/comment/88648216
answers question: http://stackoverflow.com/q/50821092

http://stackoverflow.com/comment/88680609
score: 0
has text: I see that I didn't explain myself clearly, sorry for that. I am not surprised by the behaviour of the class, what I would like if possible, is that dd["one"] returned an object that I could manipulate using a set of custom methods and return it to the class dictionary without having to wrap it explicitly as suggested by @Blckknght.
comment on: http://stackoverflow.com/q/50837113
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50848201
type: AnsweredQuestion
tagged with: list
downvote count: 3
possible better answer: http://stackoverflow.com/a/50848391
type: Question
has title: Python: combine columns then rows by group
has body: I have this dataframe: In [182]: data_set Out[182]: name parent distance rank 0 x aaa 10 1 1 x bbb 5 1 2 x fff 3 2 3 y aaa 2 2 4 y bbb 10 1 5 z ccc 8 2 I want to reshape it to: name Combined x ('aaa',10,1),('bbb',5,1),('fff',3,2) y ('aaa',2,2),('bbb',10,1) z ('ccc',8,2) Then I wanted to convert it into dataframe 3x2 with two columns name and combined. I was thinking to use zip or group but those return different outputs.
upvote count: 0
accepted answer: http://stackoverflow.com/a/50848221
tagged with: tuples
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/50848221
has answer: http://stackoverflow.com/a/50848391
favorite count: 0
score: -3
tagged with: python

http://stackoverflow.com/comment/88706114
comment on: http://stackoverflow.com/a/50846530
type: Comment
has text: 1) Where is the JSON the OP requested? JSON [strings](https://www.json.org/) have double quotes. 2) PyYAML's `load()` is documented to be unsafe, and there is no excuse for using it instead of `safe_load()` here (or almost anywhere else). 3) You fail to mention that PyYAML only supports the old, pre-2009, YAML 1.1 specification.
score: 4
type: AnswerComment

http://stackoverflow.com/a/50725615
answers question: http://stackoverflow.com/q/50725079
downvote count: 1
score: -1
upvote count: 0
has body: I don't think its good idea, in python modules used to connect your code and allow you link and reuse code easily. First of all, I think this method of "looping" is not efficient since loading python module is heavier operation than simply jumping to a new line in the code. Some more practical downsides I can think about is when you will insert another code into your module (as you said your code is much more complicated). In general, my ideology is that not everything you can do you should do. Like you can use while loop iterating on a list, or iterate using indexes instead of iterators: for i in range(len(arr)): print(arr[i]) but of course, it is not "pythonic" (and also it is not efficient).
type: Answer

http://stackoverflow.com/q/50732688
has answer: http://stackoverflow.com/a/50732741
has body: I have a csv file containing peoples' details, such as: 1010,Bill,145.98 1147,Gina,10288.97 2917, Willie, 4.97 and I want to create a dictionary called entries so that entries["Gina"] would return the sublist [1147,'Gina',10288.97]. My attempt so far with open('namesFile.txt', 'r') as f: entries = {} people = f.readlines() people = [person.strip().split(',') for person in people] print(people) for person in range(len(people)): entries[person] = person[1] gives me a TypeError: 'int' object is not subscriptable error. It produces a nice nested list of people: [['1010', 'Bill', '145.98'], ['1147', 'Gina', '10288.97'], ['2917', ' Willie', ' 4.97']] and I'm not sure how to organise the dictionary based on the person's name (person[1] in the code), which is the intended purpose of the last two lines of code. How can I put the entries into a dictionary in this fashion?
type: Question
has answer: http://stackoverflow.com/a/50732872
score: -2
accepted answer: http://stackoverflow.com/a/50732979
upvote count: 0
has title: Make a list into a dictionary, indexed by a label in the list
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50736282
answer count: 4
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/50732741
has answer: http://stackoverflow.com/a/50732979
downvote count: 2

http://stackoverflow.com/comment/88623470
type: Comment
comment on: http://stackoverflow.com/a/50808844
score: 1
type: AnswerComment
has text: @Jonas My answer is much clearer though, this code runs right off the page.

http://stackoverflow.com/q/50721944
answer count: 0
has comment: http://stackoverflow.com/comment/88452393
has comment: http://stackoverflow.com/comment/88452244
has comment: http://stackoverflow.com/comment/88452593
type: Question
has comment: http://stackoverflow.com/comment/88452618
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/88452765
score: 0
has comment: http://stackoverflow.com/comment/88452286
has comment: http://stackoverflow.com/comment/88452280
has comment: http://stackoverflow.com/comment/88452719
has body: I'm getting dependency error while installing dependency for django project Here is my part of requirement file social-auth-app-django==1.2.0 social-auth-core==1.7.0 ... stream-django==1.4.0 .. PyJWT==1.3.0 .. without pyJWT == 1.3.0 line, stream-python 2.8.1 has requirement pyjwt==1.3.0, but you'll have pyjwt 1.6.4 which is incompatible. with pyJWT == 1.3.0 social-auth-core 1.7.0 has requirement PyJWT>=1.4.0, but you'll have pyjwt 1.3.0 which is incompatible. djangorestframework-jwt 1.11.0 has requirement PyJWT&lt;2.0.0,>=1.5.2, but you'll have pyjwt 1.3.0 which is incompatible. requirements.txt. &lt;- I deleted many lines from here. It works on my ubuntu machine but somehow most of packages are deprecated since last year. apturl==0.5.2 beautifulsoup4==4.4.1 bleach==1.5.0 blinker==1.3 boto==2.48.0 Brlapi==0.6.4 certifi==2017.7.27.1 chardet==3.0.4 checkbox-support==0.22 command-not-found==0.3 cryptography==1.2.3 decorator==4.0.10 defer==1.0.6 defusedxml==0.5.0 Django==1.10.5 django-allauth==0.32.0 django-braces==1.11.0 django-cors-headers==2.1.0 django-cors-middleware==1.3.1 django-crispy-forms==1.6.0 django-filter==1.1.0 django-markdown-deux==1.0.5 django-multiselectfield==0.1.8 django-oauth-toolkit==1.0.0 django-pagedown==0.1.1 django-rest-auth==0.9.1 django-rest-framework-social-oauth2==1.0.8 django-storages==1.6.5 django-storages-redux==1.3.3 djangorestframework==3.6.3 djangorestframework-jwt==1.11.0 entrypoints==0.2.2 feedparser==5.1.3 guacamole==0.9.2 hmmlearn==0.2.0 html5lib==0.999 httplib2==0.9.1 httpsig==1.1.2 idna==2.6 ipykernel==4.5.2 ipython==5.1.0 ipython-genutils==0.1.0 ipywidgets==5.2.2 Jinja2==2.8 jsonschema==2.5.1 jupyter==1.0.0 jupyter-client==4.4.0 jupyter-console==5.0.0 jupyter-core==4.2.1 language-selector==0.1 louis==2.6.4 lxml==3.5.0 Mako==1.0.3 Markdown==2.6.9 markdown2==2.3.1 MarkupSafe==0.23 mistune==0.7.3 nbconvert==5.0.0 nbformat==4.2.0 notebook==4.3.0 numpy==1.12.1 oauthlib==2.0.3 onboard==1.2.0 padme==1.1.1 pandocfilters==1.4.1 pexpect==…
has comment: http://stackoverflow.com/comment/88469692
has title: Can't `pip3 install -r requirement.txt`
has comment: http://stackoverflow.com/comment/88452827
linked to: http://stackoverflow.com/q/6445167
has comment: http://stackoverflow.com/comment/88452353
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/88452569
has comment: http://stackoverflow.com/comment/88455336

http://stackoverflow.com/comment/88581340
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50777215
has text: i got it solved and at the same momemt, i'm very confused. Openerp is passing lists to the parameters product_id and uom_id to the method onchange_product_id, containing the db id and the result of name_get of the corresponding field. e.g. it is passing [13484, 'Allzweckreiniger'] to the product id, causing the problem. i workarounded it now, checking for a list in the parameter, filter out all not integer values and overwriting product id with the first integer value found. But it feels very wrong doing this. In my opinion, this has to happen with every onchange method if it fails here.
score: 0

http://stackoverflow.com/q/50807129
tagged with: api
answer count: 1
has comment: http://stackoverflow.com/comment/88626119
score: 0
has title: How to read data from a csv file using API in Python
has comment: http://stackoverflow.com/comment/88620055
has answer: http://stackoverflow.com/a/50807244
tagged with: python
has body: I am trying to download data from the following link: NHTSA Website If I create the link as below, it downloads the CSV file on my machine http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/2019/make/ACURA/model/RDX?format=csv How can I read this file for different vehicles, using API in Python? Here is my code so far: db = sql.connect("localhost","root","password","TEST") cursor = db.cursor() sql = "SELECT * FROM TEST.car_model" cursor.execute(sql) data = cursor.fetchall() for row in data: apiUrl = "http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/" apiParams = str(row[1])+"/make/"+row[2].replace(" ","%20")+"/model/"+row[3].rstrip().replace(" ","%20") apiFormat = "?format=csv" link = apiUrl + apiParams + apiFormat response = urlopen(apiUrl + apiParams + apiFormat) f = open(link, 'rb') reader = csv.reader(f) for row in reader: print(row) db.close() Will response automatically download the file into my Downloads folder?
tagged with: python-3.x
type: UnansweredQuestion
tagged with: mysql
type: Question

http://stackoverflow.com/comment/88484942
has text: What's the desired output???
score: 0
comment on: http://stackoverflow.com/q/50738713
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88549435
comment on: http://stackoverflow.com/q/50770218
type: QuestionComment
type: Comment
has text: No problem **@Monso**. Enjoy Python. Good luck.
score: 0

http://stackoverflow.com/q/50806677
tagged with: h2o
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: logging
has body: Here is my code: from pysparkling import H2OConf #commenting this line makes it work import logging logging.basicConfig(filename='my_log.log',level=logging.INFO) logging.info('test') I cannot get the log file to get created, unless I comment the first line of the code. If I do that, then everything works as normal. I'm assuming it's an import inside H2OConf that messes up the handlers. Anybody experience anything similar? I run the script with spark-submit --master yarn script.py Thanks
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: sparkling-water
tagged with: pyspark
has title: pysparkling H2OConf interfering with my application log

http://stackoverflow.com/comment/88582367
type: Comment
comment on: http://stackoverflow.com/a/50788006
has text: @Anush it's likely doing either lexicographical or month-first comparisons and failing.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88596563
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50793976
has text: @Daiwen Thanks for pointing out that other question. However, my question asks for an idiom that is one level of abstraction above try-finally.
score: 0

http://stackoverflow.com/comment/88548641
has text: When you say "sidebar", which part of the page are you referring to? Can you provide an example of a few elements that you would expect to be properly scraped?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50770438

http://stackoverflow.com/comment/88577827
type: QuestionComment
comment on: http://stackoverflow.com/q/50785134
score: 0
type: Comment
has text: what exactly do you want help with? please specify.

http://stackoverflow.com/a/53290048
answers question: http://stackoverflow.com/q/50728223
has body: I ran into a similar issue. Make sure you're pip installing the right version (3.x or 2.x). If you're using Python 3, pip3 install xlrd will make sure it is installed and accessible when running Python3 code.
type: Answer
score: 0

http://stackoverflow.com/q/50736281
tagged with: regex
favorite count: 0
tagged with: python-3.x
has body: I have a string that looks like this a = 'readyM01JUN_01_18_0144.xlsx' and I would like to tease out the JUN. I thought first trying to split a with respect to digits, but a.split('[0-9]+') doesn't work. Any ideas ?
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50737281
has answer: http://stackoverflow.com/a/50736433
has comment: http://stackoverflow.com/comment/88480551
has comment: http://stackoverflow.com/comment/88480469
type: Question
accepted answer: http://stackoverflow.com/a/50736433
downvote count: 0
has answer: http://stackoverflow.com/a/50736438
has title: How to get substring between two numbers (of unknown digit length) in python
score: 1
has comment: http://stackoverflow.com/comment/88480407
answer count: 3
possible better answer: http://stackoverflow.com/a/50736438
has comment: http://stackoverflow.com/comment/88480137
tagged with: python

http://stackoverflow.com/q/50778147
type: AnsweredQuestion
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/88567517
type: Question
has comment: http://stackoverflow.com/comment/88563176
accepted answer: http://stackoverflow.com/a/50778163
has title: How to return True if even one word matches?
has comment: http://stackoverflow.com/comment/88563248
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/50778163
has body: I have to write a function which return True even if one word between the two strings matches. willis towers watson and willis singapore -> True as willis matches willis towers watson and willis s pte ltd -> True as willis matches willis towers watson and will tow wat -> False as no Word matches I unsuccessfully tried a regex: bool(re.search('willis towers watson', 'willis singapore')) One liner is preferable instead of a for loop.
tagged with: python

http://stackoverflow.com/comment/88514476
comment on: http://stackoverflow.com/a/50753225
type: AnswerComment
has text: @njzk2 I have edited my answer to include alternatives.
score: 0
type: Comment

http://stackoverflow.com/comment/90606660
has text: this does not answer my question. I asked: Due to `categorical_encoding='enum'` i do not know the number of features used for training. Therefore I can not set `mtries` - Parameter as you suggested. How to set `mtries` in this case?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50744752
score: 1

http://stackoverflow.com/comment/88717874
score: 0
comment on: http://stackoverflow.com/q/50846666
type: Comment
has text: That's true, which is the part that is was confusing to me. The answer by SpghttCd gets me much closer.
type: QuestionComment

http://stackoverflow.com/comment/88657585
type: Comment
score: 0
type: AnswerComment
has text: @RJL If you are happy you can accept the answer. If not you can maybe point out what is missing :)
comment on: http://stackoverflow.com/a/50769332

http://stackoverflow.com/q/50714736
tagged with: python-requests
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88438523
score: 1
has answer: http://stackoverflow.com/a/50715631
has title: Python Requests POST - error 400
has comment: http://stackoverflow.com/comment/88438229
answer count: 2
has comment: http://stackoverflow.com/comment/88438741
has body: I have this code: import requests import json data={"client_id" : "a", "client_secret" : "thisissecret", "grant_type" : "clientcredentials", "scope" : "PublicApi"} url = 'http://MYURL/connect/token' response = requests.post(url, json=data, verify=False) print(response) print response.reason print(response.json()) I'm trying to test connection to a new auth service in test environment (which is why verify is FALSE) This should give me the access token and the token type and with them I can POST to the API. But I always get: &lt;Response [400]&gt; Bad Request {u'error': u'invalid_request'} I'm not sure what is the problem? Why is it a bad request?
possible better answer: http://stackoverflow.com/a/50714932
has answer: http://stackoverflow.com/a/50714932
favorite count: 0
accepted answer: http://stackoverflow.com/a/50715631
linked to: http://stackoverflow.com/q/45058583
has comment: http://stackoverflow.com/comment/88438309
has comment: http://stackoverflow.com/comment/88438542
tagged with: python
has comment: http://stackoverflow.com/comment/88440010
has comment: http://stackoverflow.com/comment/88438792
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/q/50803037
has body: can we extract text from pdf file object collected from request for example f = request.FILES.get('file', None) So from f can we extract text of the document as we get text content from text file object.
type: Question
has answer: http://stackoverflow.com/a/50803111
score: 0
answer count: 1
has title: extract text from pdf file object in python
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
tagged with: file

http://stackoverflow.com/a/50838027
has comment: http://stackoverflow.com/comment/88702154
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88705042
has comment: http://stackoverflow.com/comment/88705177
answers question: http://stackoverflow.com/q/50836956
has body: First, you can try: conda update --all If it doesn't help, this solution works for many people: conda uninstall pillow pip install pillow Source: https://github.com/python-pillow/Pillow/issues/2945
has comment: http://stackoverflow.com/comment/88701763
upvote count: 1
has comment: http://stackoverflow.com/comment/88702205

http://stackoverflow.com/q/50713614
tagged with: python
upvote count: 4
type: UnansweredQuestion
has title: Tensorflow prints the same info twice while training
tagged with: tensorflow
type: Question
has body: I'm training a model for object detection using tensorflow.. and while training, in the terminal, tensorflow prints the same info twice as follows : INFO:tensorflow:global step 3292: loss = 3.2832 (2.960 sec/step) INFO:tensorflow:global step 3292: loss = 3.2832 (2.960 sec/step) INFO:tensorflow:global step 3293: loss = 3.5285 (3.675 sec/step) INFO:tensorflow:global step 3293: loss = 3.5285 (3.675 sec/step) INFO:tensorflow:global step 3294: loss = 2.3972 (3.564 sec/step) INFO:tensorflow:global step 3294: loss = 2.3972 (3.564 sec/step) INFO:tensorflow:Recording summary at step 3294. INFO:tensorflow:Recording summary at step 3294. INFO:tensorflow:global_step/sec: 0.294019 INFO:tensorflow:global_step/sec: 0.294019 I noticed this "issue" only while training using tensorflow installed from source, I trained two models using tensorflow installed using pip and the logging was normal. I don't see any side effect of this behavior but I'm curious about what's causing it. Any idea?
has comment: http://stackoverflow.com/comment/88436981
has comment: http://stackoverflow.com/comment/88436290
has comment: http://stackoverflow.com/comment/88436492
has comment: http://stackoverflow.com/comment/90141652
score: 4
has comment: http://stackoverflow.com/comment/88436004
has answer: http://stackoverflow.com/a/52196072
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50799849
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88608014
tagged with: python
has comment: http://stackoverflow.com/comment/88608379
score: 1
has comment: http://stackoverflow.com/comment/88608132
upvote count: 1
tagged with: python-requests
has title: beautifulsoup Extract text which doesn't have tag
type: Question
has body: I have HTML parsed text as below and trying to extract the texts in the same order. Data Data Summary Data Description Data paragraph which contains huge string Data 2 Data 2 Summary Data 2 Description Data 2 paragraph which contains huge string Am able to extract the between the tags i and b using soup.findAll(['b', 'i']) but am struggling to get the text without tags comes after every b tag. I have tried with next_sibling which doesn't even work with this. Any help would be appreciated. The expected result is: Data Summary : Data Description : Data paragraph which contains huge string newline Data 2 : Data 2 Summary : Data 2 Description : Data 2 paragraph which contains huge string
has comment: http://stackoverflow.com/comment/88756917
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88608205
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50877465

http://stackoverflow.com/q/50774939
answer count: 3
accepted answer: http://stackoverflow.com/a/50775271
has comment: http://stackoverflow.com/comment/88556775
favorite count: 0
has answer: http://stackoverflow.com/a/50775020
has body: What is the best way to place numbers (1,2,3) randomly in a matrix [10, 10] in python? I want to have an appearance of 1 = 20 times 2 = 30 times 3 = 50 times
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50775257
downvote count: 3
possible better answer: http://stackoverflow.com/a/50775257
type: Question
has comment: http://stackoverflow.com/comment/88556927
linked to: http://stackoverflow.com/q/312443
upvote count: 0
has title: How to place numbers randomly in matrix?
has answer: http://stackoverflow.com/a/50775271
score: -3

http://stackoverflow.com/comment/88517356
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50754269
has text: @AntonvBR its a normal dataframe... should have put a datframe sample though..but this question just blocked me for two days..:( don't downvote..several people facing the same issue will benefit..whats wrong..alternative approaches solved the problem?

http://stackoverflow.com/comment/88456162
type: QuestionComment
type: Comment
score: 2
has text: That's too much code for Stack Overflow. Please [reduce it](https://stackoverflow.com/help/mcve).
comment on: http://stackoverflow.com/q/50723067

flask
tags question: http://stackoverflow.com/q/50788813
tags question: http://stackoverflow.com/q/50839614
tags question: http://stackoverflow.com/q/50749683
tags question: http://stackoverflow.com/q/50794964
tags question: http://stackoverflow.com/q/50848260
tags question: http://stackoverflow.com/q/50778963
tags question: http://stackoverflow.com/q/50851054
tags question: http://stackoverflow.com/q/50779889
tags question: http://stackoverflow.com/q/50708061
tags question: http://stackoverflow.com/q/50735626
tags question: http://stackoverflow.com/q/50822822
tags question: http://stackoverflow.com/q/50812305
tags question: http://stackoverflow.com/q/50725284
tags question: http://stackoverflow.com/q/50751685
tags question: http://stackoverflow.com/q/50766062
tags question: http://stackoverflow.com/q/50831596
tags question: http://stackoverflow.com/q/50762446
tags question: http://stackoverflow.com/q/50728328
tags question: http://stackoverflow.com/q/50752137
tags question: http://stackoverflow.com/q/50751972
tags question: http://stackoverflow.com/q/50813272
tags question: http://stackoverflow.com/q/50763052
tags question: http://stackoverflow.com/q/50767192
tags question: http://stackoverflow.com/q/50844180
tags question: http://stackoverflow.com/q/50825155
tags question: http://stackoverflow.com/q/50834023
tags question: http://stackoverflow.com/q/50766521
tags question: http://stackoverflow.com/q/50791076
tags question: http://stackoverflow.com/q/50839890
tags question: http://stackoverflow.com/q/50804420
tags question: http://stackoverflow.com/q/50838394
tags question: http://stackoverflow.com/q/50831205
tags question: http://stackoverflow.com/q/50748753
tags question: http://stackoverflow.com/q/50822882
tags question: http://stackoverflow.com/q/50700671
tags question: http://stackoverflow.com/q/50828707
tags question: http://stackoverflow.com/q/50701892
tags question: http://stackoverflow.com/q/50833687
tags question: http://stackoverflow.com/q/50705860
tags question: http://stackoverflow.com/q/50827099
tags question: http://stackoverflow.com/q/50725737
tags question: http://stackoverflow.com/q/50836331
tags question: http://stackoverflow.com/q/50817817
tags question: http://stackoverflow.com/q/50785712
tags question: http://stackoverflow.com/q/50752277
tags question: http://stackoverflow.com/q/50825819
type: Tag
tags question: http://stackoverflow.com/q/50825826
tags question: http://stackoverflow.com/q/50823832
tags question: http://stackoverflow.com/q/50812817
tags question: http://stackoverflow.com/q/50787904
tags question: http://stackoverflow.com/q/50816080
tags question: http://stackoverflow.com/q/50729353
tags question: http://stackoverflow.com/q/50828939
tags question: http://stackoverflow.com/q/50750359
tags question: http://stackoverflow.com/q/50721200
tags question: http://stackoverflow.com/q/50842802
tags question: http://stackoverflow.com/q/50813120
tags question: http://stackoverflow.com/q/50708821
tags question: http://stackoverflow.com/q/50801247
tags question: http://stackoverflow.com/q/50850904
tags question: http://stackoverflow.com/q/50812537
tags question: http://stackoverflow.com/q/50784137
tags question: http://stackoverflow.com/q/50783655
tags question: http://stackoverflow.com/q/50739573
tags question: http://stackoverflow.com/q/50728304
tags question: http://stackoverflow.com/q/50842554
tags question: http://stackoverflow.com/q/50793624
tags question: http://stackoverflow.com/q/50723498
tags question: http://stackoverflow.com/q/50832220
tags question: http://stackoverflow.com/q/50822254
tags question: http://stackoverflow.com/q/50822987
tags question: http://stackoverflow.com/q/50752972
tags question: http://stackoverflow.com/q/50743230
tags question: http://stackoverflow.com/q/50711572
tags question: http://stackoverflow.com/q/50804774
tags question: http://stackoverflow.com/q/50753741
tags question: http://stackoverflow.com/q/50827406
tags question: http://stackoverflow.com/q/50818147
tags question: http://stackoverflow.com/q/50793098

http://stackoverflow.com/q/50763441
score: 1
has comment: http://stackoverflow.com/comment/88534620
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88535198
has comment: http://stackoverflow.com/comment/88534533
downvote count: 0
has comment: http://stackoverflow.com/comment/88536170
tagged with: amazon-web-services
has body: I have aws recognition code written in Python, and it run's by Node API, which works fine on Windows system but when I'm deploying it on Linux I'm facing this issue:- botocore.errorfactory.InvalidS3ObjectException: An error occurred (InvalidS3ObjectException) when calling the DetectText operation: Unable to get object metadata from S3. Check object key, region and/or access permissions. I have given both AmazonRekognitionFullAccess and AmazonS3ReadOnlyAccess access role to I'm user. Still I don't know how to get things going. Python code:- bucket = 'image-test' def image_to_dict(fileName, bucket): client = boto3.client('rekognition', 'us-east-2') response = client.detect_text(Image = { 'S3Object': { 'Bucket': bucket, 'Name': fileName } }) return response Node Code used to run Python script:- var options = { mode: 'text', pythonPath:"/usr/bin/python2.7" pythonOptions: ['-u'], scriptPath: "/home/ubuntu/test", args: [imageURl] }; PythonShell.run('script.py', options, function (err, results) { if (err) throw err; console.log("Data is: "+results) I have Python version 2.7 installed on my Ubuntu, pip version 10.0.1.
answer count: 1
accepted answer: http://stackoverflow.com/a/50796824
favorite count: 0
has answer: http://stackoverflow.com/a/50796824
tagged with: python
tagged with: node.js
type: AnsweredQuestion
tagged with: amazon-s3

http://stackoverflow.com/comment/88520989
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50756522
has text: @jewards Should've asked it better at the end I just want a solution that's under PEP8's limit per line. Thanks for your answer.

http://stackoverflow.com/comment/88706461
type: QuestionComment
comment on: http://stackoverflow.com/q/50851878
has text: and if request in wordlist - get its index(docs for list item index)
score: 0
type: Comment

http://stackoverflow.com/comment/88614456
type: QuestionComment
has text: Hi @NimishBansal, but the thing is any thread could be optional based on the user's choice, how do I successfully join them without exhaustively using a whole bunch of "if ... else"s? Thanks.
comment on: http://stackoverflow.com/q/50749343
score: 0
type: Comment

http://stackoverflow.com/a/50727148
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50726973
has comment: http://stackoverflow.com/comment/88462800
upvote count: 2
has comment: http://stackoverflow.com/comment/88462982
has body: Here's one way using collections.defaultdict for an O(n) solution. Since we use str.split, it's necessary to keep track of counts so that we join multiple values which appear after a key. There is an edge case, where your string does not begin with a key, unaccounted for. I leave that as an exercise. from collections import defaultdict s = 'AAAA xsdfe123 BBBB 1jhfhfs CCCC 13 AAAA hjhj 300 DDDD hfh3 BBBB 14 x' d = defaultdict(list) valid_keys = {'AAAA', 'BBBB', 'CCCC', 'DDDD'} for item in s.split(): if item in valid_keys: count = 0 key = item else: count += 1 if count == 1: d[key].append(item) else: d[key][-1] = '{0} {1}'.format(d[key][-1], item) defaultdict(list, {'AAAA': ['xsdfe123', 'hjhj 300'], 'BBBB': ['1jhfhfs', '14 x'], 'CCCC': ['13'], 'DDDD': ['hfh3']})
type: Answer

http://stackoverflow.com/q/50819073
has answer: http://stackoverflow.com/a/50819887
score: 2
type: AnsweredQuestion
has body: There are 2 array Plot1 is of form plot1 = [1.0, 2.0, 3.0] (1X4)and we have tp find minimum distance of plot1 with plot2,(plot2 which have multiple array stored in it).We want O/P as i)min distance among all points from plot2 (Smin) ii)Index where point is stored iii)Index of array where point is stored My code works when plot2 is have one array in it.But fails when it have multiple array as plot2 = np.array([[(1.0, 4.0, 5.0),(4.0, 7.0, 90.0),(1.0, 4.0, 5.0)], [(2.9,3.2,3.3),(2.3,2.6,5.5),(2.4,3.5,4.4)], [(2.9,3.2,3.3),(2.3,2.6,5.5),(2.4,3.5,4.4)]]) So my working code is import numpy as np plot1 = [1.0, 2.0, 3.0] plot2 = [(1.0, 4.0, 5.0), (4.0, 7.0, 90.0), (1.0, 4.0, 5.0), (-1.0, -4.0, -5.0)] indexes = [] for i in range(len(plot2)): # To get one element at a time from plot2 plotk = plot2[i] S = np.linalg.norm(np.array(plot1) - np.array(plotk)) print("Distance between plot1 and plotk is %f" %(S)) # euclidian distance is calculated if (i == 0): Smin = S Sminant = S indexes.append(i) else: if (S &lt; Sminant): Smin = S Sminant=Smin indexes = [] indexes.append(i) elif (S == Sminant): indexes=[] indexes.append(i) print('indexes:') print(indexes) for i in range(len(indexes)): print("VAlues of Slist with min \n",indexes[i], plot2[indexes[i]],Smin)
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/50821121
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/50819887
tagged with: python
has title: To find minimum distance between two array PLOT1 and PLOT2 and also store the index where that point is
favorite count: 0
possible better answer: http://stackoverflow.com/a/50821121
upvote count: 2

http://stackoverflow.com/comment/134981940
comment on: http://stackoverflow.com/a/76541574
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50764750
type: Answer
answers question: http://stackoverflow.com/q/50763704
has body: You can override the built in serializer create method but it may make more sense to deal with the object itself in a pre_save signal, that way you can access the ManyToMany objects fields.
has comment: http://stackoverflow.com/comment/88552450
score: 0
has comment: http://stackoverflow.com/comment/88732283

http://stackoverflow.com/comment/88616932
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50805147
has text: @FamousJameous I find a class called CudnnLSTM where it defines __call__() which takes the same arguments as the examples gives. [tensorflow/blob/r1.8/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py](https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py) It is in a 'ops' subfolder
score: 0

http://stackoverflow.com/comment/88684965
comment on: http://stackoverflow.com/a/50825309
type: AnswerComment
score: 0
type: Comment
has text: @ℕʘʘḆḽḘ I partially solved the problem with dask https://github.com/dask/dask/issues/3598#issuecomment-396970081 To save a df with about 10M rows take less than 20 seconds on my machine. Now it will be interesting to see if we can set `flavor='spark'` and name the files accordingly.

http://stackoverflow.com/a/50766623
answers question: http://stackoverflow.com/q/50766513
type: Answer
downvote count: 0
has body: First, you're calling fl() which is trying to call the list as a function. that doesn't work. In Python, putting () after a function evaluates the function and provides the return value. This means fl = [func1(1),func1(2),func1(3)] means "Create a list, and put the result of calling func1(1), func1(2), and func1(3)" If you want to call the function later, then you can put the parameter into the list and walk through the list, or you can bind. f = func1 # storing the function as a variable fl = [1,2,3] for v in fl: f(v) then you can do something like use lambda to bind: f = func1 # storing the function as a variable fl = [lambda :f(1), lambda :f(2), lambda :f(3)] for v in fl: v() # v is bound to the parameters, so you don't need to use a param
score: 1
upvote count: 1

http://stackoverflow.com/q/50826359
has answer: http://stackoverflow.com/a/50826885
type: Question
has body: I save a model of sklearn.linear_model.LinearRegression using pickle, and then load it the reverse way using: i = 1 Xtr_num, Xte_num, Xtr_cat, Xte_cat, Ytr, Yte, Xvl_num, Xvl_cat, Yvl = data.get_splitted_data(i) lm = linear_model.LinearRegression() pickle.dump(lm, open('pre_model/y'+str(i)+'-skl.pickle.sav', 'wb')) X = np.concatenate((Xtr_num, Xtr_cat), axis=1) model = lm.fit(X,Ytr) loaded_model = pickle.load(open('pre_model/y'+str(1)+'-skl.pickle.sav', 'rb')) print loaded_model.predict(X) It gives me the error below. Can you please advise. --------------------------------------------------------------------------- NotFittedError Traceback (most recent call last) &lt;ipython-input-14-8d246f04f2b7&gt; in &lt;module&gt;() 1 loaded_model = pickle.load(open('pre_model/y'+str(1)+'-skl.pickle.sav', 'rb')) ----&gt; 2 print loaded_model.predict(X) /usr/lib64/python2.7/site-packages/sklearn/linear_model/base.pyc in predict(self, X) 254 Returns predicted values. 255 """ --&gt; 256 return self._decision_function(X) 257 258 _preprocess_data = staticmethod(_preprocess_data) /usr/lib64/python2.7/site-packages/sklearn/linear_model/base.pyc in _decision_function(self, X) 235 236 def _decision_function(self, X): --&gt; 237 check_is_fitted(self, "coef_") 238 239 X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) /usr/lib64/python2.7/site-packages/sklearn/utils/validation.pyc in check_is_fitted(estimator, attributes, msg, all_or_any) 766 767 if not all_or_any([hasattr(estimator, attr) for attr in attributes]): --&gt; 768 raise NotFittedError(msg % {'name': type(estimator).__name__}) 769 770 NotFittedError: This LinearRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50826885
has comment: http://stackoverflow.com/comment/88679137
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88683451
has comment: http://stackoverflow.com/comment/88683200
has comment: http://stackoverflow.com/comment/88683339
tagged with: python
has title: Does sklearn.linear_model.LinearRegression can saved?
has comment: http://stackoverflow.com/comment/88682568
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88683040
has comment: http://stackoverflow.com/comment/88658389
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/88683706

http://stackoverflow.com/comment/88685306
type: QuestionComment
score: 1
has text: You are looking for `last_date` DatetimeIndex which is not in the dataframe.
comment on: http://stackoverflow.com/q/50840769
type: Comment

http://stackoverflow.com/q/50770356
has answer: http://stackoverflow.com/a/50780610
favorite count: 0
has comment: http://stackoverflow.com/comment/88567820
has comment: http://stackoverflow.com/comment/88548670
has body: The following is a small python3 script from a web tutorial that demonstrates how to make pulldown menubars using Tkinter. It is copied directly from https://www.tutorialspoint.com/python3/tk_menu.htm with no changes! It works fine when I run it on a raspberry pi (using 3 different IDEs) BUT when I run it on my Mac (in 2 different IDEs) it just creates the white window and places no menu elements into it. NOTE that this Mac is able to run other simple Tkinter scripts that I have been making as I try to learn Tkinter... making buttons, popups, no problem. New Edit: When I go to the macs that this is failing on, and I do: &gt;&gt;&gt; import tkinter &gt;&gt;&gt; tkinter._test() ...the test works fine with its little buttons etc, and I get the little window telling me it's v8.5. What is it about this script that is making the mac choke (and the other computer is not)? Huge thanks! Here is the tkinter script that fails on the macs: # !/usr/bin/python3 from tkinter import * def donothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() root = Tk() menubar = Menu(root) filemenu = Menu(menubar, tearoff = 0) filemenu.add_command(label="New", command = donothing) filemenu.add_command(label = "Open", command = donothing) filemenu.add_command(label = "Save", command = donothing) filemenu.add_command(label = "Save as...", command = donothing) filemenu.add_command(label = "Close", command = donothing) filemenu.add_separator() filemenu.add_command(label = "Exit", command = root.quit) menubar.add_cascade(label = "File", menu = filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label = "Undo", command = donothing) editmenu.add_separator() editmenu.add_command(label = "Cut", command = donothing) editmenu.add_command(label = "Copy", command = donothing) editmenu.add_command(label = "Paste", command = donothing) editmenu.add_command(label = "Delete", command = donothing) editmenu.add_command(label = "Select All", command = do…
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/88550468
type: AnsweredQuestion
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88548554
has comment: http://stackoverflow.com/comment/88548385
score: 1
accepted answer: http://stackoverflow.com/a/50780610
has comment: http://stackoverflow.com/comment/88548555
has comment: http://stackoverflow.com/comment/88548681
upvote count: 1
has comment: http://stackoverflow.com/comment/88548269
type: Question
has comment: http://stackoverflow.com/comment/88550470
has comment: http://stackoverflow.com/comment/88548623
has title: Why does this simple Tkinter tutorial script run fine on Raspberry Pi, but not on MacOS?
has comment: http://stackoverflow.com/comment/88548575
has comment: http://stackoverflow.com/comment/88548701
has comment: http://stackoverflow.com/comment/88548541
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88669083
comment on: http://stackoverflow.com/a/50831226
has text: @WoodsChen - hmmm, and if use `return np.arange(df['start'], df['end'], 1)` it working?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88455055
type: QuestionComment
comment on: http://stackoverflow.com/q/50723319
score: 0
has text: Take a look here: https://stackoverflow.com/questions/3949226/calculating-pearson-correlation-and-significance-in-python
type: Comment

http://stackoverflow.com/comment/88584182
score: 1
has text: chop this code down into the essence of the problem to make it easier for us to help you. Chances are in doing so you might even answer your own question. From looking at the error message you are getting you have a float wrapped in a list/set, and you're trying to use it in the place of a normal float. For example trying to do [4.] / 2 instead of 4. / 2.
comment on: http://stackoverflow.com/q/50788874
type: Comment
type: QuestionComment

fractions
type: Tag
tags question: http://stackoverflow.com/q/50722883
tag name: fractions

http://stackoverflow.com/q/50779419
has comment: http://stackoverflow.com/comment/88566496
answer count: 1
has title: Python concurrent logging to avoid disk bottleneck in code
score: 0
tagged with: python-asyncio
tagged with: python
has comment: http://stackoverflow.com/comment/88640363
type: UnansweredQuestion
tagged with: multithreading
tagged with: logging
type: Question
has answer: http://stackoverflow.com/a/50781441
has body: I'm not super familiar with asyncio, but I was hoping there would be some easy way to use asyncio.Queue to push log messages to a Queue instead of writing them to the disk, and then have a worker on a thread wait for these Queue events and write them to disk when resources are available. This seems pretty widely necessary, as logging is a huge bottleneck in a lot of code but isn't always needed in real time. Are there any pre-existing packages for this or can anyone with more experience write a short example script to get me started? NOTE: This needs to interface with existing code, so making it all packaged in a class would probably be preferred.

http://stackoverflow.com/a/50737688
has body: Depending on your specific use case (frequency of the export, size of the exports, etc.), the solutions proposed in the answer by @GrahamPolley may work for you, although they would take more development and attention. The current possibility for writing query results is either to write the results to a table or to download it locally, and even downloading directly to CSV has some limitations. Therefore, there is not the possibility to write query results to GCS in CSV format directly. However, there is a 2-steps solutions consisting in: Write query results to a BQ table Export data from a BQ table to a CSV file in GCS. Note that this feature has some limitations too, but they are not as narrow. The following Python code can give you an idea of how to perform that task: from google.cloud import bigquery client = bigquery.Client() # Write query results to a new table job_config = bigquery.QueryJobConfig() table_ref = client.dataset("DATASET").table("TABLE") job_config.destination = table_ref job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE query_job = client.query( 'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` LIMIT 10', location='US', # Location must match dataset job_config=job_config) rows = list(query_job) # Waits for the query to finish # Export table to GCS destination_uri = "gs://BUCKET/FILE.CSV" dataset_ref = client.dataset("DATASET", project="PROJECT_ID") table_ref = dataset_ref.table("TABLE") extract_job = client.extract_table( table_ref, destination_uri, location='US') extract_job.result() # Waits for job to complete Note that, after that, you would have to delete the table (you can also do that programatically). This may not be the best solution if you have to automatize the process (if that is your use case, maybe you should better explore @Graham's solutions), but it will do the trick for a simple scenario.
has comment: http://stackoverflow.com/comment/88484577
has comment: http://stackoverflow.com/comment/88483328
has comment: http://stackoverflow.com/comment/88482855
answers question: http://stackoverflow.com/q/50735075
score: 15
upvote count: 15
has comment: http://stackoverflow.com/comment/88487927
downvote count: 0
has comment: http://stackoverflow.com/comment/88483890
has comment: http://stackoverflow.com/comment/88484926
has comment: http://stackoverflow.com/comment/88485063
type: Answer

http://stackoverflow.com/comment/88463596
has text: Possible duplicate of [passing one list of values instead of mutiple arguments to a function?](https://stackoverflow.com/questions/11064406/passing-one-list-of-values-instead-of-mutiple-arguments-to-a-function)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50727542
score: 0

http://stackoverflow.com/a/50796354
has comment: http://stackoverflow.com/comment/88599835
accepted answer of: http://stackoverflow.com/q/50796325
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88605191
answers question: http://stackoverflow.com/q/50796325
has body: Use repeat with loc if detault RangeIndex: print (df.index.repeat(df['Col 2'])) Int64Index([0, 0, 0, 1, 1], dtype='int64') df = df.loc[df.index.repeat(df['Col 2'])].reset_index(drop=True) print (df) Col 1 Col 2 0 Adam 3 1 Adam 3 2 Adam 3 3 Sarah 2 4 Sarah 2 And then: df.to_csv(file, index=False) General solution for duplicated Index or DatetimeIndex is repeat numpy array created by numpy.arange and selecting by positions by iloc: df = df.iloc[np.arange(len(df)).repeat(df['Col 2'])].reset_index(drop=True) EDIT: Solution without np.repeat: df =df.loc[[c for a, b in zip(df.index, df['Col 2']) for c in [a] * b]].reset_index(drop=True) print (df) Col 1 Col 2 0 Adam 3 1 Adam 3 2 Adam 3 3 Sarah 2 4 Sarah 2
has comment: http://stackoverflow.com/comment/88644324
has comment: http://stackoverflow.com/comment/88601463
has comment: http://stackoverflow.com/comment/88602726
upvote count: 7
downvote count: 0
has comment: http://stackoverflow.com/comment/88603740
type: Answer
has comment: http://stackoverflow.com/comment/88601505
has comment: http://stackoverflow.com/comment/88602692
score: 7
has comment: http://stackoverflow.com/comment/88604398
has comment: http://stackoverflow.com/comment/88599878

http://stackoverflow.com/comment/88544218
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50767865
has text: I'm not sure if I can read line by line because I'm applying a function on the whole file to search for non matching parentheses. Let me think. Thanks for a while.
type: Comment

http://stackoverflow.com/a/50762931
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50760914
type: AcceptedAnswer
type: Answer
has body: You're likely not activating the python interpreter from the virtual environment. What you have to do is path\to\virtual\environment\python.exe path\to\script\main.py The two paths may be the same, but calling the right python.exe is crucial.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50760914

http://stackoverflow.com/q/50747928
favorite count: 0
has body: I have 2 lists: 1. ['a', 'b', 'c'] 2. ['a', 'd', 'a', 'b'] And I want dictionary output like this: {'a': 2, 'b': 1, 'c': 0} I already made it: #b = list #1 #words = list #2 c = {} for i in b: c.update({i:words.count(i)}) But it is very slow, I need to process like 10MB txt file. EDIT: Entire code, currently testing so unused imports.. import string import os import operator import time from collections import Counter def getbookwords(): a = open("wu.txt", encoding="utf-8") b = a.read().replace("\n", "").lower() a.close() b.translate(string.punctuation) b = b.split(" ") return b def wordlist(words): a = open("wordlist.txt") b = a.read().lower() b = b.split("\n") a.close() t = time.time() #c = dict((i, words.count(i)) for i in b ) c = Counter(words) result = {k: v for k, v in c.items() if k in set(b)} print(time.time() - t) sorted_d = sorted(c.items(), key=operator.itemgetter(1)) return(sorted_d) print(wordlist(getbookwords()))
possible better answer: http://stackoverflow.com/a/50748106
type: Question
has answer: http://stackoverflow.com/a/50748313
has answer: http://stackoverflow.com/a/50748106
score: 3
has answer: http://stackoverflow.com/a/50748197
tagged with: python
accepted answer: http://stackoverflow.com/a/50748313
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88503470
has answer: http://stackoverflow.com/a/50748226
upvote count: 3
has title: Count how many times are items from list 1 in list 2
has comment: http://stackoverflow.com/comment/88503563
has comment: http://stackoverflow.com/comment/88503520
answer count: 5
has answer: http://stackoverflow.com/a/50748065
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/88411375
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50698982
score: 0
has text: @bobrobbob not sure to understand you reply !!!

http://stackoverflow.com/comment/88548149
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50770294
has text: you can use if test.count("a") == 2: # do something
type: Comment

http://stackoverflow.com/comment/122062478
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51756462
has text: @PiyushShandilya If the text is more compact the variables in comments (`morph_size`, `min_text_height_limit`, `max_text_height_limit`, `cell_threshold`, `min_columns`) could be tweaked to improve accuracy. They can be even dynamically adjusted somehow. The code I provided is just snippet illustrating one of possible approaches, you can use it any way you want and improve it.

for-loop
tags question: http://stackoverflow.com/q/50710859
tags question: http://stackoverflow.com/q/50762922
tags question: http://stackoverflow.com/q/50756288
tags question: http://stackoverflow.com/q/50781119
tags question: http://stackoverflow.com/q/50750021
tags question: http://stackoverflow.com/q/50711647
tags question: http://stackoverflow.com/q/50802957
tags question: http://stackoverflow.com/q/50707253
tags question: http://stackoverflow.com/q/50854360
tags question: http://stackoverflow.com/q/50770294
tags question: http://stackoverflow.com/q/50708813
tags question: http://stackoverflow.com/q/50734412
tags question: http://stackoverflow.com/q/50774884
tags question: http://stackoverflow.com/q/50766521
tags question: http://stackoverflow.com/q/50826328
tag name: for-loop
tags question: http://stackoverflow.com/q/50706020
tags question: http://stackoverflow.com/q/50798493
tags question: http://stackoverflow.com/q/50788191
tags question: http://stackoverflow.com/q/50730905
tags question: http://stackoverflow.com/q/50775354
tags question: http://stackoverflow.com/q/50774697
tags question: http://stackoverflow.com/q/50820577
tags question: http://stackoverflow.com/q/50814689
tags question: http://stackoverflow.com/q/50778096
tags question: http://stackoverflow.com/q/50807582
tags question: http://stackoverflow.com/q/50703526
tags question: http://stackoverflow.com/q/50721834
tags question: http://stackoverflow.com/q/50752304
tags question: http://stackoverflow.com/q/50784007
tags question: http://stackoverflow.com/q/50827588
tags question: http://stackoverflow.com/q/50786744
tags question: http://stackoverflow.com/q/50798861
type: Tag
tags question: http://stackoverflow.com/q/50821934
tags question: http://stackoverflow.com/q/50785759
tags question: http://stackoverflow.com/q/50718293
tags question: http://stackoverflow.com/q/50808650
tags question: http://stackoverflow.com/q/50716690
tags question: http://stackoverflow.com/q/50809220
tags question: http://stackoverflow.com/q/50748727
tags question: http://stackoverflow.com/q/50776263
tags question: http://stackoverflow.com/q/50749481

http://stackoverflow.com/comment/88700649
comment on: http://stackoverflow.com/a/50848757
score: 0
type: Comment
has text: Thanks for your reply. I apply minmaxscaler() only on input feature set. I do only label encoding on target column. I am wondering whether this points to any issue with the model? How do i know if it is highly biased or highly varianced model etc.
type: AnswerComment

http://stackoverflow.com/q/50707913
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
type: Question
has title: Trying to load a json file into a flattened pandas DataFrame
has body: I'm trying to load a json file from nist.gov into a pandas DataFrame without nested dicts so that I end up with flattened records in a pandas DataFrame. I can live with nested lists as I will stack and merge later. The intent is to end up with a flat file of vulnerabilities by affected products. import pandas as pd pd.set_option('display.max_colwidth', 80) # set pandas column width to facilitate viewing df = pd.read_json('https://nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-recent.json.zip', compression='zip') # load json file from nist The values in df include a nested dict. df.head(2) CVE_data_type CVE_data_format CVE_data_version CVE_data_numberOfCVEs CVE_data_timestamp CVE_Items 0 CVE MITRE 4 640 2018-06-05T18:00Z {'cve': {'data_type': 'CVE', 'data_format': 'MITRE', 'data_version': '4.0', ... 1 CVE MITRE 4 640 2018-06-05T18:00Z {'cve': {'data_type': 'CVE', 'data_format': 'MITRE', 'data_version': '4.0', ... When I expand df.CVE_Items into a CVE_Items DataFrame, I get more nested dicts. CVE_items = df.CVE_Items.apply(pd.Series) CVE_items.head(2) cve configurations impact publishedDate lastModifiedDate 0 {'data_type': 'CVE', 'data_format': 'MITRE', 'data_version': '4.0', 'CVE_dat... {'CVE_data_version': '4.0', 'nodes': [{'operator': 'OR', 'cpe': [{'vulnerabl... {'baseMetricV2': {'cvssV2': {'version': '2.0', 'vectorString': '(AV:N/AC:M/A... 2011-12-27T11:55Z 2018-06-04T13:46Z 1 {'data_type': 'CVE', 'data_format': 'MITRE', 'data_version': '4.0', 'CVE_dat... {'CVE_data_version': '4.0', 'nodes': [{'operator': 'OR', 'cpe': [{'vulnerabl... {'baseMetricV3': {'cvssV3': {'version': '3.0', 'vectorString': 'CVSS:3.0/AV:... 2018-04-24T20:29Z 2018-06-04T16:11Z If I continue to expand the newly formed DataFrames, the plot thickens as I get more nested dicts and/or lists with nested dicts. cve = CVE_items.cve.apply(pd.Series) configurations = CVE_items.configurations.apply(pd.Series) impact = CVE_items.impact.apply(pd.Series) cve.head(2) data_type data_format data_version CVE_data_…
has answer: http://stackoverflow.com/a/55816791
accepted answer: http://stackoverflow.com/a/55816791
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
tagged with: dictionary

windows-10
tags question: http://stackoverflow.com/q/50810082
tag name: windows-10
tags question: http://stackoverflow.com/q/50848226
type: Tag
tags question: http://stackoverflow.com/q/50776173

http://stackoverflow.com/comment/88574432
type: QuestionComment
comment on: http://stackoverflow.com/q/50782248
has text: After creating a polynomial model, you wish to reproduce the modeling result for the first row of data but the result is not the same. Is this correct?
score: 0
type: Comment

http://stackoverflow.com/comment/88421102
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50705552
has text: Can you try using 'latin-1' or 'ISO-8859-1'encoding instead of 'utf-8'

http://stackoverflow.com/a/50793281
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50793243
answers question: http://stackoverflow.com/q/50793243
has body: You are quite close, the only thing you are missing is an .order_by('month_sub') (yeah, I know that sounds a bit strange). So you should write: user.post_set.annotate( month_sub=ExtractMonth('submission_time') ).values('month_sub').annotate( count=Count('month_sub') ).order_by('month_sub') This will result in query that looks like: SELECT EXTRACT(MONTH FROM `post`.`submission_time`) AS `month_sub`, COUNT(EXTRACT(MONTH FROM `post`.`submission_time`)) AS `count` FROM `post` WHERE `post`.`user_id` = 123 GROUP BY EXTRACT(MONTH FROM `post`.`submission_time`) ORDER BY `month_sub` ASC (where 123 should be replaced with the id of the user). You can perhaps boost performance a tiny bit, by using Count('id'), although it is possible this has no (noticeable) impact: user.post_set.annotate( month_sub=ExtractMonth('submission_time') ).values('month_sub').annotate( count=Count('id') ).order_by('month_sub') If I run this on a sample database, I get: &lt;QuerySet [{'count': 273, 'month_sub': 1}, {'count': 172, 'month_sub': 2}, {'count': 565, 'month_sub': 3}, {'count': 59, 'month_sub': 4}, {'count': 452, 'month_sub': 5}, {'count': 550, 'month_sub': 6}, {'count': 622 'month_sub': 7}, {'count': 43, 'month_sub': 8}, {'count': 357, 'month_sub': 9}, {'count': 378, 'month_sub': 10}, {'count': 868, 'month_sub': 11}, {'count': 293, 'month_sub': 12}]&gt; (did some formatting to make it easier to inspect the result)
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/88562649
comment on: http://stackoverflow.com/q/50777577
has text: @TrojanHorse, In that case, you need be very explicit in your question that's the problem. Give a concrete reproducible example. Show us that it doesn't work. Then we can suggest other approaches. Until then, this is a duplicate.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50822985
linked to: http://stackoverflow.com/q/42659418
has body: Python noob here. I recently came across a blog site that taught a lesson on how to automate EBS snapshots using lambda &amp; python. The script runs perfect and technically does everything I want except I can't figure out how to add AWS tags in boto3 lib. import boto3 import datetime import pytz import os ec2 = boto3.resource('ec2') def lambda_handler(event, context): print("\n\nAWS snapshot backups starting at %s" % datetime.datetime.now()) instances = ec2.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) for instance in instances: instance_name = filter(lambda tag: tag['Key'] == 'Name', instance.tags)[0]['Value'] for volume in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [instance.id]}]): description = 'scheduled-%s-%s' % (instance_name, datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")) if volume.create_snapshot(VolumeId=volume.volume_id, Description=description): print("Snapshot created with description [%s]" % description) for snapshot in volume.snapshots.all(): retention_days = int(os.environ['retention_days']) if snapshot.description.startswith('scheduled-') and ( datetime.datetime.now().replace(tzinfo=None) - snapshot.start_time.replace(tzinfo=None) ) &gt; datetime.timedelta(days=retention_days): print("\t\tDeleting snapshot [%s - %s]" % ( snapshot.snapshot_id, snapshot.description )) snapshot.delete() print("\n\nAWS snapshot backups completed at %s" % datetime.datetime.now()) return True Please can someone explain how I can add tags to the ebs snapshots being created by this script. my educational guess is that it should be in this portion of the script. because thats where the description is being created. so could i in theory just add a variable named tag = ec2.Tag('resource_id','key','value') ? for volume in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [instance.id]}]): description = 'scheduled-%s-%s' % (instance_name, datetime.datetime.now().strftime("%Y-%m-%d-%H…
type: Question
has answer: http://stackoverflow.com/a/50823377
tagged with: boto3
score: 4
tagged with: amazon-web-services
has title: Adding AWS Tag in Boto3 python script
upvote count: 4
answer count: 1
downvote count: 0
favorite count: 0
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/88651224
accepted answer: http://stackoverflow.com/a/50823377
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88457533
score: 0
type: Comment
has text: I tried to include `axis=1` but is giving `SyntaxError`. Can you write an example how to do this, please.
type: QuestionComment
comment on: http://stackoverflow.com/q/50723524

http://stackoverflow.com/comment/88667907
score: 0
comment on: http://stackoverflow.com/q/50829647
type: Comment
has text: Have you got a begin of code? We are here to help find a solution, not to code ii for you.
type: QuestionComment

http://stackoverflow.com/comment/88490244
score: 0
type: Comment
has text: @ReezalAQ you should really read a tutorial on how to use python functions. This is fundamental to virtually every bit of code you're going to write. It's also not exclusive to MySQL at all.
comment on: http://stackoverflow.com/a/50740857
type: AnswerComment

http://stackoverflow.com/q/50822404
accepted answer: http://stackoverflow.com/a/50837385
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
tagged with: matplotlib
has title: Zoom stops working after pressing '1' button, but only in subplot
has answer: http://stackoverflow.com/a/50837385
answer count: 1
downvote count: 0
has body: I am developing a simple GUI to analyze some data using Matplotlib's own event handling. This works great in general, but I have been scratching my head for the last hours over some weird bug. Code below is a heavily chopped down version of my real application. The way it works is that you can click on the image to add and remove points by clicking with left and right mouse clicks. This 'editing mode' can be switched on and off by pressing the '0' and '1' keys. This works fine when the image is the only subplot. The bug is that if the image is one out of several subplots, Matplotlib's zoom button stops working as soon as you switch on the editing mode (by pressing the '1' button, which installs the on_click function as a handler for the button_press_event). After this, pressing 'o' or the zoom button changes the cursor, but the rectangle for the zoom area does no longer appear. I guess the handler somehow messes with Matplotlib's internals. Does anyone understand why the zoom keeps working in case of a single subplot, but stops working when installing an on_click handler in case of multiple subplots?. To change between working and buggy version comment/uncomment the indicated lines that generate the figure and the subplot(s). I am using python 2.7.14 and matplotlib 2.2.2, both from anaconda. import numpy as np import matplotlib.pyplot as plt class Points(object): def __init__(self, ax): self.ax = ax # make dummy plot, points will be added later self.dots, = ax.plot([], [], '.r') self.x = [] self.y = [] def onclick(self, event): print 'point.onclick' # only handle clicks in the relevant axis if event.inaxes is not self.ax: print 'outside axis' return # add point with left button if event.button == 1: self.x.append(event.xdata) self.y.append(event.ydata) # delete point with right button if event.button == 3 and len(self.x) &gt; 0: imn = np.argmin((event.xdata - self.x)**2 + (event.ydata - self.y)**2) del self.x[imn] del self.y[imn] self.dots.set_data(self.x, self.y) p…
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/88686122
comment on: http://stackoverflow.com/q/50841204
type: Comment
type: QuestionComment
has text: `import ast` and then `ast.literal_eval(x)` will give you a tuple of two lists.
score: 0

http://stackoverflow.com/comment/88450185
type: QuestionComment
comment on: http://stackoverflow.com/q/50720852
has text: Possible duplicate of [In Python, how do I convert all of the items in a list to floats?](https://stackoverflow.com/questions/1614236/in-python-how-do-i-convert-all-of-the-items-in-a-list-to-floats)
score: 0
type: Comment

http://stackoverflow.com/q/50753603
has answer: http://stackoverflow.com/a/50761427
tagged with: class
favorite count: 0
tagged with: python-3.x
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/50761427
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
has body: I've a class with a list of threads, and those need to access a variable in the superclass. I'm not sure how to access that variable in a safe way for threads to do their thing. An idea of what I'm trying to do. from threading import Thread class Parent(): def __init__(self, num): self.num = num self.arr = [] def run(self): self.arr.append(Child(25)) self.arr.append(Child(50)) for child in a.arr: child.start() for child in a.arr: child.join() print(self.num) class Child(Thread, Parent): def __init__(self, sum): Thread.__init__(self) self.sum = sum def run(self): # every thread should a.num + self.sum so I end up with a.num = 175 pass a = Parent(100) a.run()
answer count: 1
downvote count: 0
has title: Access a super class variable while working with threads

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/50789262
tags question: http://stackoverflow.com/q/50781970

http://stackoverflow.com/comment/88578667
type: Comment
type: QuestionComment
score: 1
has text: But your requirement is not clear? Which part of command's output you need in your output by using awk? Kindly elaborate more.
comment on: http://stackoverflow.com/q/50785972

http://stackoverflow.com/q/50707239
has answer: http://stackoverflow.com/a/50722335
has title: Python 3.5 JSON serialize a Decimal object
has comment: http://stackoverflow.com/comment/88424256
favorite count: 0
has comment: http://stackoverflow.com/comment/88424111
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50707902
tagged with: python
has body: I need to encode into json a decimal value: 999999.99990000005 while not losing precision and not changing representation to string. Expecting { "prc" : 999999.99990000005 } From [this post][1] i have this code. import json import decimal class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): return str(o) return super(DecimalEncoder, self).default(o) y = { 'prc' : decimal.Decimal('999999.99990000005')} but it produces a string json.dumps(y, cls=DecimalEncoder) '{"cPrc": "999999.99990000005"}' replacing str(o) with float(o) in isinstance truncates the number. Any way to get the non-string result? P.S. I cannot use any external modules like simplejson. EDIT: If I keep the value as a string, following produces a string too. &gt;&gt;&gt; x = json.loads("""{ "cPrc" : "999999.99990000005" }""", parse_float=decimal.Decimal) &gt;&gt;&gt; x {'cPrc': '999999.99990000005'}
upvote count: 6
has comment: http://stackoverflow.com/comment/88430282
has comment: http://stackoverflow.com/comment/88423887
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88423953
has comment: http://stackoverflow.com/comment/135751035
answer count: 2
score: 5

http://stackoverflow.com/q/50778583
has answer: http://stackoverflow.com/a/50810151
tagged with: python
type: AnsweredQuestion
tagged with: docker-compose
has body: trying to get remote debugging for my python flask API I have. I'm able to docker-compose up and have postman successfully call the running container, but when I try to attach the debugger, it never compiles. Below is my yml, dockerfile and vscode launch settings... the following error I get is: There was an error in starting the debug server. Error = {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":5050} version: '2' services: website: build: . command: &gt; python ./nomz/app.py environment: PYTHONUNBUFFERED: 'true' volumes: - '.:/nomz' ports: - '5000:5000' - '5050' DockerFile FROM python:3.6-slim ENV INSTALL_PATH /nomz RUN mkdir -p $INSTALL_PATH WORKDIR $INSTALL_PATH COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . EXPOSE 5000 5050 VSCode Launch Settings { "name": "Python: Attach", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}/nomz/app.py", "remoteRoot": "/nomz/", "port": 5050, "host": "localhost" }
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/88625591
accepted answer: http://stackoverflow.com/a/50810151
type: Question
tagged with: visual-studio-code
downvote count: 0
has title: Python Docker Remote Debugging VS Code
tagged with: docker
has comment: http://stackoverflow.com/comment/88615602
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50813567
has title: Decorator to override save to write in Multiple databases
tagged with: django
tagged with: python
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/88633913
has comment: http://stackoverflow.com/comment/88632933
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88632884
type: Question
has comment: http://stackoverflow.com/comment/88632540
tagged with: django-models
has comment: http://stackoverflow.com/comment/88633364
has comment: http://stackoverflow.com/comment/88632556
has comment: http://stackoverflow.com/comment/88632689
has answer: http://stackoverflow.com/a/50814919
score: 0
has comment: http://stackoverflow.com/comment/88632225
answer count: 1
has comment: http://stackoverflow.com/comment/88632298
has body: I am planning to have models in our application to write into two databases. I wanted to write a decorator to use it for all models. I am using the below code class save_multi_db(models.Model): def __call__(self, cls): class Wrapped(cls): def save(self, *args, **kwargs): redis_connection = redis.Redis(connection_pool=settings.MAPPING_REDIS_POOL) if int(redis_connection.get('write_to_db')): super(cls, self).save(using='prod') super(cls, self).save(using='default') else: return cls.save() return Wrapped I have classes like below @save_multi_db() class ModelA(models.Model): #model A class MobelB(ModelA): class Meta: db_table = 'name' This is perfectly working fine if I am using the decorator to a single model. But in the same models.py if I use the decorator on another model. I am getting the below error (fields.E300) Field defines a relation with model 'Wrapped', which is either not installed, or is abstract.
tagged with: decorator
has comment: http://stackoverflow.com/comment/88633030
has comment: http://stackoverflow.com/comment/88632973

http://stackoverflow.com/a/56951519
has body: Chrome doesn't support SOCKS5 proxy with authentication.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50728319

http://stackoverflow.com/comment/88650533
comment on: http://stackoverflow.com/q/50822571
score: 1
has text: What about `arr[:, :, x]`?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50786914
type: Answer
answers question: http://stackoverflow.com/q/50786798
has comment: http://stackoverflow.com/comment/88580754
has body: Since you have converted the year column to datetime, you can use: df['year'] = df['year'].dt.date # year # 1880-01-01 However, for datetime casting, note that pandas has an inbuilt datetime parser that is easy to use than dateutil IMO.
score: 0
has comment: http://stackoverflow.com/comment/88580738

http://stackoverflow.com/q/50709931
upvote count: 1
has comment: http://stackoverflow.com/comment/88450228
answer count: 1
has comment: http://stackoverflow.com/comment/88480608
has comment: http://stackoverflow.com/comment/88429915
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88453873
score: 0
has answer: http://stackoverflow.com/a/51228293
tagged with: python
has title: Scrollbar does not work in tkinter canvas widget after adding labels
has comment: http://stackoverflow.com/comment/88454741
tagged with: tkinter
type: UnansweredQuestion
has body: I have mad an app that ads label to the canvas. I have also set the vertical scrollbar. The problem is that I can not activate scrollbar, the scrollbar does not allow scrolling. I have used grid_propagate(0) but it still does not work. HOw to activate this feature? The program does not show me any error. from tkinter import * root=Tk() frame=Frame(root,width=300,height=300) frame.grid(row=0,column=0) frame.grid_propagate(0) canvas=Canvas(frame,width=300,height=300) vbar=Scrollbar(frame,orient=VERTICAL) vbar.grid(row=0, column=1,sticky="NS") vbar.config(command=canvas.yview) canvas.config(width=300,height=300) canvas.config(yscrollcommand=vbar.set) canvas.grid(row=0,column=0) n=0 m=10 def novi(): global n global m n +=1 m=m+2 e = Label(canvas, text=m ) e.grid(row=n,column=0, padx=10, pady=10) b = Button(root, text="add", command=novi) b.grid(row=0, column=2,sticky="N") root.mainloop()
has comment: http://stackoverflow.com/comment/88429975
has comment: http://stackoverflow.com/comment/88569854
type: Question
has comment: http://stackoverflow.com/comment/88493780
has comment: http://stackoverflow.com/comment/88437840
has comment: http://stackoverflow.com/comment/88566274

http://stackoverflow.com/comment/88625846
type: QuestionComment
has text: What you mean by *not working*? Any error?
score: 0
comment on: http://stackoverflow.com/q/50799885
type: Comment

http://stackoverflow.com/q/50711796
upvote count: 5
has comment: http://stackoverflow.com/comment/88437546
has title: how to validate arguments using decorators in python
score: 5
answer count: 3
downvote count: 0
tagged with: decorator
favorite count: 0
has body: I need to validate two given inputs before I call the add function: Ff any input is not an integer I should get invalid input or error message, if both are integers I should get the sum. import re def my_dec(arg1,arg2): x = re.compile(r"[^0-9]") if x.search(arg1) and x.search(arg2): return add(a,b) else: print("invalid input") @my_dec(arg1,arg2) def add(a,b): return a + b print(add(2,3)) I get function not defined errors in loops, but I don't know how to overcome it.
tagged with: python
has answer: http://stackoverflow.com/a/66206210
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/61982288
has answer: http://stackoverflow.com/a/50765673
type: Question

http://stackoverflow.com/comment/88648589
comment on: http://stackoverflow.com/q/50821728
type: QuestionComment
type: Comment
has text: you aren't calling the members of the class
score: 0

http://stackoverflow.com/comment/88695464
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50842919
has text: Thank you for the response. Good to know for future use though!

http://stackoverflow.com/q/50715574
tagged with: scikit-learn
type: AnsweredQuestion
has body: I am using the RandomForestRegressor class of the scikit-learn library (python 3.x) and I am aware that the function to measure the quality of a split in a decision tree is the variance reduction (mse). Given that the RandomForestRegressor class supports multiple output, my question is: how is the quality of a split computed in case of multiple outputs in this particular class? From reading the source code of the class defining the split criterion I would say that the impurity decrease of a split in a tree is computed as the average impurity decrease over all output variables. And hence, only one model is build given multiple outputs. Is that the default way in scikit-learn RandomForestRegressor class? I was hoping someone could have a look with me for I am not completely sure wether my statements are correct! Many thanks in advance! https://github.com/scikit-learn/scikit-learn/blob/a24c8b464d094d2c468a16ea9f8bf8d42d949f84/sklearn/tree/_criterion.pyx#L695
type: Question
has answer: http://stackoverflow.com/a/50716062
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/50716062
score: 0
answer count: 1
has title: How is the impurity decrease of a split computed in case we have multiple outputs using RandomForestRegressor of Scikit-Learn library
tagged with: random-forest

http://stackoverflow.com/q/50818608
has answer: http://stackoverflow.com/a/50818727
tagged with: post
type: AnsweredQuestion
tagged with: .net
has body: I need help converting the follow Python code to c# .net. This code is posting/uploading a text file to a webserver. The Python script has been tested and works. I have tried a few solutions with HTTPClient and WebRequest with no luck. Any guidance will be greatly appreciated. # request a session client = requests.session() # Establish the URL newurl = 'https://localhost/filedist/upload/' source_file = 'data/test.txt' headers = {'Authorization': 'Token MYTOKEN'} # Populate the values with our environment and target path values = dict(environment='dev', path='Business/Tools') files = dict(file=open(source_file, 'rb')) r = client.post(newurl, files=files, data=values, headers=headers) Here is my latest attempt, which currently is getting a 'Forbidden' error. public static async Task&lt;string&gt; UploadFile(string path, string fileName) { var client = new HttpClient(); string NewURL = "https://localhost/filedist/upload/"; string SourceFile = path; var content = new MultipartFormDataContent(); client.DefaultRequestHeaders.Add("Authorization", "Token MYTOKEN"); Stream fs = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None); content.Add(CreateFileContent(fs, fileName, "text/plain")); var parameters = new Dictionary&lt;string, string&gt; { { "environment", "dev" }, { "path", "Business/Tools" } }; content.Add(new FormUrlEncodedContent(parameters)); var response = await client.PostAsync(NewURL, content); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { string responseString = response.Content.ReadAsStringAsync().Result; return "true"; } else { return "false"; } } private static StreamContent CreateFileContent(Stream stream, string fileName, string contentType) { try { var fileContent = new StreamContent(stream); fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "UploadedFile", FileName = "\"" + fileName + "\"" }; fileContent.Headers.ContentType = new MediaTyp…
type: Question
accepted answer: http://stackoverflow.com/a/50818727
tagged with: python
has comment: http://stackoverflow.com/comment/88643209
score: 0
has title: Python code to c# .net for HTTP Post to API
answer count: 1
tagged with: c#

http://stackoverflow.com/a/50787075
upvote count: 1
has comment: http://stackoverflow.com/comment/108127883
downvote count: 1
has comment: http://stackoverflow.com/comment/88580512
has comment: http://stackoverflow.com/comment/88580545
answers question: http://stackoverflow.com/q/50786727
score: 0
type: Answer
has body: Try IronPython, it's a .Net - Python bridge. Or basicly you can access .net stuff from python or interpret python from c#.

http://stackoverflow.com/comment/88452701
has text: First off you iterate `k` through integers up to 15 and then compare it to strings, `'No_Goal'` and `'Home_Goal'`. Secondly, what is your question?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50722037

http://stackoverflow.com/a/70962962
downvote count: 0
type: Answer
has body: Credit to Ku Tang Pan's answer for this - I was able to customize their solution to something even more precise. I personally like to conditionally format my tables based on certain values. I find that generating your own HTML is the most precise way and gives you full control. ##note how any row that has the drop alert flag set to "Y" will be formatted yellow: dict_data = [df.to_dict(), df.to_dict('index')] htmldf = ' ' for key in dict_data[0].keys(): htmldf = htmldf + ' ' + key + ' ' htmldf = htmldf + ' ' for key in dict_data[1].keys(): htmldf = htmldf + ' ' if dict_data[1][key]['drop_alert'] == 'Y' else htmldf + '>' for subkey in dict_data[1][key]: htmldf = htmldf + ' ' + str(dict_data[1][key][subkey]) + ' ' htmldf = htmldf + ' ' htmldf = htmldf + ' ' # Write html object to a file (adjust file path; Windows path is used here) with open('C:\\Users\\Documents\\test.html','wb') as f: f.write(htmldf.encode("UTF-8")) Result: neatly conditionally formatted table
score: 4
answers question: http://stackoverflow.com/q/50807744
upvote count: 4

http://stackoverflow.com/comment/88535652
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50763348
has text: It's hard to reproduce the issue without the full working code.

http://stackoverflow.com/q/50820527
upvote count: 2
score: 1
tagged with: machine-learning
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50845559
has title: Why does my model accuracy get stuck at ~32%?
has answer: http://stackoverflow.com/a/50845559
has answer: http://stackoverflow.com/a/50830911
has comment: http://stackoverflow.com/comment/88646924
answer count: 2
tagged with: deep-learning
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/88648048
accepted answer: http://stackoverflow.com/a/50830911
tagged with: python
has body: Edit: I see someone downvoted this post, please let me know what I did so that I can avoid doing so in the future. Thanks I am very new to deep learning, and I am working on my first non-tutorial based RNN model however I am getting very poor results. I created a dataset of album reviews by Anthony Fantano with respective targets of scores between 1-9 (here). My objective was to use sentiment analysis to predict a score based on the input text. Firstly I am using the keras Tokenizer utility class to preprocess my raw text, then I pad/truncate the token-based text to a maximum size of np.mean(num_tokens) + 2 * np.std(num_tokens) and then I create an embedding vector (using the keras Embedding class) I am using one-hot encoding on my target data, with a vector of length 10. My network produces a length 10 vector with softmax activation, and I am using categorical_crossentropy as my loss function. I've chosen the unit sizes for my GRU cells (is this the correct terminology?) arbitrarily, but playing around with them has not produced better results for me. model = Sequential() model.add(embedding) model.add(GRU(units=32, return_sequences=True)) model.add(GRU(units=16)) model.add(Dense(10, activation='softmax')) optimizer = SGD(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) model.summary() model.fit(x_pad, y_encoded, validation_split=0.05, epochs=5, batch_size=64) Here is a summary of my network from keras _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= layer_embedding (Embedding) (None, 2290, 8) 8000 _________________________________________________________________ gru_1 (GRU) (None, 2290, 32) 3936 _________________________________________________________________ gru_2 (GRU) (None, 16) 2352 _________________________________________________________________ dense_1 (Dense) (None, 10) 170 =================…
has comment: http://stackoverflow.com/comment/88652119
type: AnsweredQuestion

http://stackoverflow.com/q/50732993
score: 3
tagged with: linked-list
downvote count: 0
has answer: http://stackoverflow.com/a/50733196
has answer: http://stackoverflow.com/a/50734534
type: Question
has comment: http://stackoverflow.com/comment/88473706
has body: I have been stuck on this for half of a day. Could I get some tips or pointers on how to swap just the head and tail of a linked list (not reverse the entire list) without copying their data? class myNode: def __init__(data, next): self.data = data self.next = next class MyLinkedList: def __init__(self): self.head = None self.tail = None If I could see the code and have an explanation to it, that would be awesome! edit: Basically, my initial way of solving this problem is. Literate through the list to find the tail ( by stopping the while loop when the node.next is None, meaning I have reached the end) and then linking the tail to the head.next Literate through the list to find the 2nd last node of the list and linking that to the head. Linking the original head to null as now the head should be swapped to the tail.
upvote count: 3
has title: Swapping head and tail of a single linked list
has answer: http://stackoverflow.com/a/50733489
has comment: http://stackoverflow.com/comment/88473983
has comment: http://stackoverflow.com/comment/88473760
favorite count: 0
has answer: http://stackoverflow.com/a/50745561
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21529359
tagged with: python
has comment: http://stackoverflow.com/comment/88474073
answer count: 4

http://stackoverflow.com/comment/88615132
has text: The fastest way is, to create a list with one element: `q = [item]`. So it depends, on what you really want to do, which solution is best.
type: Comment
comment on: http://stackoverflow.com/q/50804499
type: QuestionComment
score: 0

http://stackoverflow.com/q/50764002
tagged with: api
has answer: http://stackoverflow.com/a/50764125
accepted answer: http://stackoverflow.com/a/50764125
upvote count: 1
possible better answer: http://stackoverflow.com/a/50764166
has body: I am trying to call several api datasets within a for loop in order to change the call and then append those datasets together into a larger dataframe. I have written this code which works to call the first dataset but then returns this error for the next call. `url = base + "max=" + maxrec + "&amp;" "type=" + item + "&amp;" + "freq=" + freq + "&amp;" + "px=" +px + "&amp;" + "ps=" + str(ps) + "&amp;" + "r="+ r + "&amp;" + "p=" + p + "&amp;" + "rg=" +rg + "&amp;" + "cc=" + cc + "&amp;" + "fmt=" + fmt TypeError: must be str, not Response` Here is my current code import requests import pandas as pd base = "http://comtrade.un.org/api/get?" maxrec = "50000" item = "C" freq = "A" px="H0" ps="all" r="all" p="0" rg="2" cc="AG2" fmt="json" comtrade = pd.DataFrame(columns=[]) for year in range(1991,2018): ps="{}".format(year) url = base + "max=" + maxrec + "&amp;" "type=" + item + "&amp;" + "freq=" + freq + "&amp;" + "px=" +px + "&amp;" + "ps=" + str(ps) + "&amp;" + "r="+ r + "&amp;" + "p=" + p + "&amp;" + "rg=" +rg + "&amp;" + "cc=" + cc + "&amp;" + "fmt=" + fmt r = requests.get(url) x = r.json() new = pd.DataFrame(x["dataset"]) comtrade = comtrade.append(new)
favorite count: 0
has comment: http://stackoverflow.com/comment/88535863
has title: Change API call in for loop python
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50764166
tagged with: dataframe
tagged with: loops
type: Question
answer count: 2

http://stackoverflow.com/comment/88514546
has text: It is a good idea to display the bytecode. This answer has been really helpful, but would not have been quite sufficient if it was not for the key fact, given in @Amadan answer, that f-string code is generated at compile time, not at runtime and that it *does not* rely on calling an eval. If I could acceot both answers I would as it is combined that they give the best explanation.
type: Comment
comment on: http://stackoverflow.com/a/50753235
score: 0
type: AnswerComment

http://stackoverflow.com/a/50778614
type: Answer
has body: The best solution (in the sense that it preserves the desired goal and is "kept simple"), I came up with is: #!/usr/bin/env python3 from tkinter import * rcc = 1 def click(): global rcc rcc += 1 rc.set(rcc) print('rcc was increased to {}'.format(rcc)) if __name__ == '__main__': window = Tk() window.title("my click game boi") window.configure(background='black') rc = IntVar() photo1 = PhotoImage(file="kanekipic.gif") Label(window, image=photo1, bg='black').grid(row=0, column=0, sticky=E) Button(window, text="eat", width=3, command=click).grid(row=3, column=0, sticky=W) Label(window, textvariable=rc, bg="red", fg="white").grid(row=1, column=0, sticky=S) window.mainloop() Whenever you click on the eat button, the counter will be increased.
answers question: http://stackoverflow.com/q/50777728
has comment: http://stackoverflow.com/comment/88565510
score: 0

http://stackoverflow.com/a/50712162
has body: def is_prime(number): if number == 2: return True for x in range(2, int(math.sqrt(number)) + 1): if number%x == 0: return False return True If you ensure there's no number till square root of given number which can divide the given number, then you can mark it prime. No need to check till number - 1. Although a small improvement, could be significant in your case.
downvote count: 0
has comment: http://stackoverflow.com/comment/88433195
answers question: http://stackoverflow.com/q/50712114
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/50825954
score: 1
has body: First the signature of np.array: array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0) It's a function, and uses (). It takes one positional argument, which is usually a list. Additional arguments are interpreted as the keyword arguments, dtype, copy, etc. We can make a list of dictionaries: In [543]: alist = [{"russia" : 0}, {"saudi_arabia" : 0}, {"egypt" : 0}, {"urugua ...: y" : 0}] In [544]: alist Out[544]: [{'russia': 0}, {'saudi_arabia': 0}, {'egypt': 0}, {'uruguay': 0}] and we can make an array from that list. Note the dtype. The array is 1d. In [545]: arr = np.array(alist) In [546]: arr Out[546]: array([{'russia': 0}, {'saudi_arabia': 0}, {'egypt': 0}, {'uruguay': 0}], dtype=object) But why aren't you making one dictionary with multiple keys? A list or array of single element dictionaries doesn't look very useful. In [548]: adict = {"russia" : 0, "saudi_arabia" : 0, "egypt" : 0,"uruguay" : 0} In [549]: adict Out[549]: {'russia': 0, 'saudi_arabia': 0, 'egypt': 0, 'uruguay': 0} Compare ways of getting the dictionary keys: In [550]: alist[2].keys() Out[550]: dict_keys(['egypt']) In [551]: adict.keys() Out[551]: dict_keys(['russia', 'saudi_arabia', 'egypt', 'uruguay']) In [552]: [d.keys() for d in arr] Out[552]: [dict_keys(['russia']), dict_keys(['saudi_arabia']), dict_keys(['egypt']), dict_keys(['uruguay'])] In [554]: np.array([list(d.items()) for d in alist],object) Out[554]: array(['russia', 0, 'saudi_arabia', 0, 'egypt', 0, 'uruguay', 0], dtype=object) In [555]: _.shape Out[555]: (4, 1, 2) # multidimensional object array In [556]: __[:,0,0] Out[556]: array(['russia', 'saudi_arabia', 'egypt', 'uruguay'], dtype=object) we can also make a structured array from adict (but also indirectly from alist): In [559]: list(adict.items()) # produces a list of tuples Out[559]: [('russia', 0), ('saudi_arabia', 0), ('egypt', 0), ('uruguay', 0)] In [561]: sarr = np.array(list(adict.items()),dtype='U20,int') In [562]: sarr Out[562]: array([('rus…
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50825520
accepted answer of: http://stackoverflow.com/q/50825520
type: Answer
upvote count: 1

http://stackoverflow.com/q/50848769
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88700753
tagged with: pycharm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50848835
tagged with: python
score: 1
upvote count: 1
has title: package import error in command line but not in PyCharm
type: Question
has body: I have a project which i was compiling via PyCharm so far. It has a structure like so ParentFolder\ - Mains\ - __init__.py - main.py - package\ - __init__.py - util.py in main.py I had an import line like so: from package.util import ... Now when I run this in PyCharm, it works without any issues. However, when I try to run this via the command line, I am unable to import from util.py and I get the error No module named ... Looks like PyCharm is doing something extra, beyond a simply python main.py command. Any pointers on what could that be and how I should I replicate it via command line?

http://stackoverflow.com/comment/89943686
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50943700
type: AnswerComment
has text: Hey, thank you so much for this. I got sidelined at work by another project, but this is back on my plate. This works perfectly with one exception. Apparently, none of the keys correspond to the actual message. I can see the message in the .mbox file reading it manually, but I need it to be one of the .csv file's columns. Any idea on that?

http://stackoverflow.com/a/50729382
type: Answer
has body: Imports happens before class definition. In db/__init__.py you are importing pg.py, sqlite.py which are depends on classes defined here. To solve it move DbStorageAbstract to another file and if you are going to use it in the same file with pg.py, sqlite.py then make sure import is going to be like this: from . import dbstorage # this file is the new one contains DbStorageAbstract class from . import pg, sqlite Note that if two modules are depends on each other try to create a third module so solve this problem.
answers question: http://stackoverflow.com/q/50728439
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/88470574
score: 0
has text: Sorry I mean steps haha. Also the module venv is the same thing, it was just moved into python itself in python 3
type: AnswerComment
comment on: http://stackoverflow.com/a/50731135
type: Comment

pythonnet
type: Tag
tag name: pythonnet
tags question: http://stackoverflow.com/q/50732366
tags question: http://stackoverflow.com/q/50723423

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/50767761
tags question: http://stackoverflow.com/q/50791421
tags question: http://stackoverflow.com/q/50831596
tags question: http://stackoverflow.com/q/50746932
tags question: http://stackoverflow.com/q/50710001
tags question: http://stackoverflow.com/q/50708398
tags question: http://stackoverflow.com/q/50762077
tags question: http://stackoverflow.com/q/50769003
tags question: http://stackoverflow.com/q/50809314
tags question: http://stackoverflow.com/q/50714453
tags question: http://stackoverflow.com/q/50761140
tags question: http://stackoverflow.com/q/50791076
tags question: http://stackoverflow.com/q/50716344
tags question: http://stackoverflow.com/q/50841901
tags question: http://stackoverflow.com/q/50822882
tags question: http://stackoverflow.com/q/50716985
tags question: http://stackoverflow.com/q/50841883
tags question: http://stackoverflow.com/q/50752277
type: Tag
tags question: http://stackoverflow.com/q/50706292
tags question: http://stackoverflow.com/q/50784387
tags question: http://stackoverflow.com/q/50778767
tags question: http://stackoverflow.com/q/50703916
tags question: http://stackoverflow.com/q/50807493
tags question: http://stackoverflow.com/q/50833013
tags question: http://stackoverflow.com/q/50833399
tags question: http://stackoverflow.com/q/50743230
tags question: http://stackoverflow.com/q/50714663
tags question: http://stackoverflow.com/q/50761939
tags question: http://stackoverflow.com/q/50706782
tags question: http://stackoverflow.com/q/50798216
tags question: http://stackoverflow.com/q/50804774
tags question: http://stackoverflow.com/q/50712158
tags question: http://stackoverflow.com/q/50812937
tags question: http://stackoverflow.com/q/50725882
tags question: http://stackoverflow.com/q/50777852
tags question: http://stackoverflow.com/q/50729897
tags question: http://stackoverflow.com/q/50770703
tags question: http://stackoverflow.com/q/50808996
tags question: http://stackoverflow.com/q/50777758
tags question: http://stackoverflow.com/q/50751828
tag name: html
tags question: http://stackoverflow.com/q/50731359
tags question: http://stackoverflow.com/q/50784425
tags question: http://stackoverflow.com/q/50759182
tags question: http://stackoverflow.com/q/50843493
tags question: http://stackoverflow.com/q/50824810
tags question: http://stackoverflow.com/q/50777329
tags question: http://stackoverflow.com/q/50817880
tags question: http://stackoverflow.com/q/50776702
tags question: http://stackoverflow.com/q/50844331

http://stackoverflow.com/q/50842956
downvote count: 0
has answer: http://stackoverflow.com/a/71443750
accepted answer: http://stackoverflow.com/a/50843606
tagged with: monkeypatching
favorite count: 0
has comment: http://stackoverflow.com/comment/88689488
has title: How to monkey patch a function for multiple tests
has comment: http://stackoverflow.com/comment/88689555
tagged with: python
has answer: http://stackoverflow.com/a/69480086
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52710018
has comment: http://stackoverflow.com/comment/88689503
tagged with: pytest
has answer: http://stackoverflow.com/a/52710018
has body: Consider my module "mymodule.py" # contents of "mymodule.py" def func1(x): return x * 2 I want to mock this function and alter its return. Per the documentation I can do this: # contents of "test_mymodule.py" import mymodule import pytest @pytest.fixture def mock_func1(): def mock_ret(*args, **kwargs): return 2 def test_func1_a(monkeypatch, mock_func1): monkeypatch.setattr(mymodule, "func1", mock_func1) assert mymodule.func1(1) == 2 def test_func1_b(monkeypatch, mock_func1): monkeypatch.setattr(mymodule, "func1", mock_func1) assert mymodule.func1(1) != 37 However, I don't want to monkey patch the module for each test. What is the proper way to monkeypatch.setattr once for the scope of the whole test module test_mymodule.py? I'd expect something like this # contents of "test_mymodule.py" import mymodule import pytest @pytest.fixture def mock_func1(): def mock_ret(*args, **kwargs): return 2 monkeypatch.setattr(mymodule, "func1", mock_func1) def test_func1_a(): assert mymodule.func1(1) == 2 def test_func1_b(): assert mymodule.func1(1) != 37 But this gets me NameError: name 'monkeypatch' is not defined
type: Question
has answer: http://stackoverflow.com/a/50843606
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/88689604

http://stackoverflow.com/q/50782059
has body: I have dataframe whose some columns (C1 ,C2 ,C3) are categorical ( string) variable. Data and datatypes is as following: C1 C2 C3 C4 C5 \ 4 b'02e197c5' b'c2ced437' b'a2427619' b'3f85ecae' b'b8c51ab7' 9 b'62770d79' b'ad984203' b'ddd956c1' b'f7f54f97' b'bbaea1c0' 13 b'7ffd46c3' b'710103fd' b'a1407382' b'f2463ffb' b'664ff944' 14 b'9a8cb066' b'7a06385f' b'417e6103' b'6faef306' b'f8990a45' 45 b'6f877ce8' b'58cc2d25' b'9b48ba97' b'f2463ffb' b'd90dd51f' Datatype: C1 object C2 object C3 object Then , I have used DictVectorizer to apply one-hot-code for string labelTransformer = DictVectorizer(dtype='str') labelTransformer.fit_transform(clickDataFrame["C1"].astype("str")) But after that , I get error as following: File "click_main.py", line 60, in &lt;module&gt; df2 = labelTransformer.fit_transform(clickDataFrame["C1"].astype("str")) File "/usr/local/lib/python3.6/dist-packages/sklearn/feature_extraction/dict_vectorizer.py", line 230, in fit_transform return self._transform(X, fitting=True) File "/usr/local/lib/python3.6/dist-packages/sklearn/feature_extraction/dict_vectorizer.py", line 166, in _transform for f, v in six.iteritems(x): File "/usr/local/lib/python3.6/dist-packages/sklearn/externals/six.py", line 439, in iteritems return iter(getattr(d, _iteritems)(**kw)) AttributeError: 'str' object has no attribute 'items' I have tried alot of , but I can't find a solution ?
has answer: http://stackoverflow.com/a/50782225
tagged with: python
has title: How to use DictVectorizer to convert categorical column
tagged with: one-hot-encoding
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: dictvectorizer
has answer: http://stackoverflow.com/a/68941238
type: Question
tagged with: pandas

http://stackoverflow.com/comment/88842702
score: 0
type: AnswerComment
type: Comment
has text: So, you think it's a big and not something I did wrong? I would find this very weird, no?
comment on: http://stackoverflow.com/a/50845016

http://stackoverflow.com/q/50841383
has comment: http://stackoverflow.com/comment/88722125
answer count: 2
has answer: http://stackoverflow.com/a/50841436
favorite count: 0
has title: How to create an array that sums the value of a 2d array
has comment: http://stackoverflow.com/comment/88720129
score: 0
possible better answer: http://stackoverflow.com/a/50841488
has answer: http://stackoverflow.com/a/50841488
tagged with: python
has body: [[2, 3, 4, 6, 9], [4, 6, 8, 12, 18], [6, 9, 12, 18, 27], [8, 12, 16, 24, 36], [10, 15, 20, 30, 45], [12, 18, 24, 36, 54], [14, 21, 28, 42, 63], [16, 24, 32, 48, 72], [18, 27, 36, 54, 81], [20, 30, 40, 60, 90]] I wanted to sum to value into an array. Basically, I have this array data, how do I get this output. The output is something like this [2+3+4+6+9, 2+3+4+6+18, 2+3+4+6+27, 2+3+4+6+36, 2+3+4+6+45, 2+3+4+6+54, 2+3+4+6+63, 2+3+4+6+71, 2+3+4+6+81, 2+3+4+6+90, 4+3+4+6+9, ...] I tried something like this and it didn't work final = [] trans = [*zip(*data)] k = 0 l = 0 while(k != len(trans) * len(data)): val = 0 m = 0 for d1 in trans: val = val + d1[m * l] m = m + 1 l = l + 1 k = k + 1 final.append(val)
linked to: http://stackoverflow.com/q/44103323
has comment: http://stackoverflow.com/comment/88722038
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50841436
upvote count: 1
has comment: http://stackoverflow.com/comment/88686499
downvote count: 1
has comment: http://stackoverflow.com/comment/88686406
type: Question
has comment: http://stackoverflow.com/comment/88686471
has comment: http://stackoverflow.com/comment/88721989

http://stackoverflow.com/q/50798431
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88602818
duplicate of: http://stackoverflow.com/q/3995034
tagged with: python
tagged with: regex
answer count: 0
score: 1
upvote count: 1
type: Question
has body: &gt;&gt;&gt; a = """if HELLO ... do something""" &gt;&gt;&gt; b = b"""if HELLO ... do something""" &gt;&gt;&gt; if re.search(r"HELLO\b", a): ... print('yes') ... yes &gt;&gt;&gt; if re.search(b"HELLO\b", b): ... print('yes') ... &gt;&gt;&gt; Is there any way to use \b when searching through bytestrings? Or is there another option that does the same thing as \b?
downvote count: 0
has title: Is there a way to use \b in byte regex? (Python)
has comment: http://stackoverflow.com/comment/88603406
linked to: http://stackoverflow.com/q/3995034
favorite count: 0

http://stackoverflow.com/q/50845466
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88694497
has title: How to add 0's into two dimensional list using list comprehension in python?
upvote count: 1
has comment: http://stackoverflow.com/comment/88694590
has answer: http://stackoverflow.com/a/50845522
has comment: http://stackoverflow.com/comment/88694595
type: AnsweredQuestion
score: 1
type: Question
has body: I'm trying to convert this for loop into "list comprehension" format if possible: This loop adds 0 into two dimensional list test_list = [['string1'],['string2'],['string3']] for i in range(len(test_list)): test_list[i].insert(1, 0) output: test_list = [['string1',0],['string2',0],['string3',0]] I've tried this but for some reason it doesn't work. test_list = [test_list[i].insert(1, 0) for i in range(len(test_list))]
answer count: 2
possible better answer: http://stackoverflow.com/a/50845521
has answer: http://stackoverflow.com/a/50845521
downvote count: 0
accepted answer: http://stackoverflow.com/a/50845522

http://stackoverflow.com/comment/88595394
type: QuestionComment
has text: You can do whatever you want, but for production and/or team work, and readability, it’s a good idea to follow some sort of style guide. Pep8 is one of them.
score: 1
comment on: http://stackoverflow.com/q/50794689
type: Comment

http://stackoverflow.com/q/50818352
has comment: http://stackoverflow.com/comment/88641858
has body: I have dtaframe which looks like this: import pandas as pd import numpy as np df = pd.DataFrame({'ID': [332, 332, 332, 315, 315, 315, 315, 315, 310, 310], \ 'Name': ['Alex', 'Alex', 'Alex', 'Sara', 'Sara', 'Sara', 'Sara', 'Sara', 'Franck','Franck'], \ 'Shift': ['Day', 'Day', 'Night', 'Day', 'Night', 'Night', 'Day', 'Day', 'Night', 'Night']}) df Output ID Name Shift 0 332 Alex Day 1 332 Alex Day 2 332 Alex Night 3 315 Sara Day 4 315 Sara Night 5 315 Sara Night 6 315 Sara Day 7 315 Sara Day 8 310 Franck Night 9 310 Franck Night And I want to add a new column like this: ID Name Shift Two_Shift 0 332 Alex Day Yes 1 332 Alex Day Yes 2 332 Alex Night Yes 3 315 Sara Day Yes 4 315 Sara Night Yes 5 315 Sara Night Yes 6 315 Sara Day Yes 7 315 Sara Day Yes 8 310 Franck Night No 9 310 Franck Night No For this I have tried this code: df['Two_Shift'] = np.where((df['ID'] == df['ID']) &amp; (df['Shift'] != df['Shift']), 'Yes', 'No') but it does not work. Thanks!
type: Question
has answer: http://stackoverflow.com/a/50818468
has answer: http://stackoverflow.com/a/50818442
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50818442
has comment: http://stackoverflow.com/comment/88641801
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50818468
score: 2
type: AnsweredQuestion
upvote count: 2
has title: How to create a new column with distinct Id and different values of two other columns?

http://stackoverflow.com/comment/88592748
has text: If printing the whole array is crucial to you, then follow the numpy docs links I provided before.
type: AnswerComment
comment on: http://stackoverflow.com/a/50760279
score: 0
type: Comment

smtpexception
type: Tag
tag name: smtpexception
tags question: http://stackoverflow.com/q/50845224

http://stackoverflow.com/comment/88700194
has text: Thank you! It works only without lambda in tf.where.
comment on: http://stackoverflow.com/a/50832283
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50774747
downvote count: 0
score: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88561313
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50774921
has title: Randomly remove 30% of values in numpy array
has comment: http://stackoverflow.com/comment/88556773
has comment: http://stackoverflow.com/comment/88556728
type: Question
tagged with: numpy
tagged with: arrays
possible better answer: http://stackoverflow.com/a/50774993
has answer: http://stackoverflow.com/a/50774993
answer count: 2
accepted answer: http://stackoverflow.com/a/50774921
has body: I have a 2D numpy array which contains my values (some of them can be NaN). I want to remove the 30% of the non-NaN values and replace them with the mean of the array. How can I do so? What I tried so far: def spar_removal(array, mean_value, sparseness): array1 = deepcopy(array) array2 = array1 spar_size = int(round(array2.shape[0]*array2.shape[1]*sparseness)) for i in range (0, spar_size): index = np.random.choice(np.where(array2 != mean_value)[1]) array2[0, index] = mean_value return array2 But this is just picking the same row of my array. How can I remove from all over the array? It seems that choice works only for one dimension. I guess what I want is to calculate the (x, y) pairs that I will replace its value with mean_value.

http://stackoverflow.com/q/50781828
has answer: http://stackoverflow.com/a/50781907
type: UnansweredQuestion
tagged with: python
tagged with: command-line
type: Question
has title: how to run script on executable file?
has answer: http://stackoverflow.com/a/50781865
score: 0
tagged with: bash
answer count: 2
has body: maybe my question is stupid but I would be very happy if someone could help, I have some executable file that I got from my teacher, this executable file ask for the answer of some math problem and if you run it on CMD it's look like: C:\Users\guyzw&gt;solveme.exe Hello fellow, can you solve this math problem? 2 x 7? &gt; I'm run this exe file on my linux machine using wine, I want to write some of script in bash or python to insert the answer automatically, my question is how can I do so? this exe file doesn't get args so I don't now where to begin... Any help would be appreciated.
linked to: http://stackoverflow.com/q/46965024
tagged with: linux

http://stackoverflow.com/a/50789941
answers question: http://stackoverflow.com/q/50789880
has body: Using dot df.dot(df.columns+',').str[:-1] Out[168]: 0 id_0,id_2 1 id_0 2 id_1 3 id_0,id_1 4 id_2 5 dtype: object
type: AcceptedAnswer
downvote count: 0
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/88586886
accepted answer of: http://stackoverflow.com/q/50789880
upvote count: 7

http://stackoverflow.com/comment/88436678
type: Comment
has text: Thx for your answer, but where i can find this file? May be i install ckeditor not properly?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50711977

http://stackoverflow.com/q/50740414
has answer: http://stackoverflow.com/a/50740541
tagged with: awk
favorite count: 0
tagged with: linux
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50740558
has body: For eg I have a huge file with the pattern below. The search pattern is the date and i have to prefix the date for the next n number of rows. The date pattern is at the exact nth repetitive line and the next few lines are also a fixed number. date 1 line 1 line 2 line 3 date 2 line 4 line 5 line 6 date 3 line 7 line 8 line 9 The above pattern should be transformed to look like below date 1 line 1 date 1 line 2 date 1 line 3 date 2 line 4 date 2 line 5 date 2 line 6 date 3 line 7 date 3 line 8 date 3 line 9 Is there a simple command using sed/awk which would do this or should i go ahead and write a bash/python script ?
has comment: http://stackoverflow.com/comment/88718271
linked to: http://stackoverflow.com/q/50559897
upvote count: 1
downvote count: 1
has title: Search every nth line pattern in a large file and prefix them for then next x range of lines
type: Question
has answer: http://stackoverflow.com/a/50741069
tagged with: sed
has comment: http://stackoverflow.com/comment/88492330
linked to: http://stackoverflow.com/q/50635955
has answer: http://stackoverflow.com/a/50740631
score: 0
tagged with: bash

http://stackoverflow.com/q/50785198
has comment: http://stackoverflow.com/comment/88577837
answer count: 0
has comment: http://stackoverflow.com/comment/88619049
has comment: http://stackoverflow.com/comment/88577869
has body: I am trying to use LSTM in tensorflow to make an air quality prediction. The data is from https://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data. It is a 8-input and 8-output model. After I training my model and make prediction, the answer is always the same one. [ 1.07586029e+02 1.60341334e+00 1.03546591e+01 1.01711316e+03 1.08991003e+00 2.57353954e+01 -6.55468106e-02 1.81939721e-01] [ 1.07586029e+02 1.60341334e+00 1.03546591e+01 1.01711316e+03 1.08991003e+00 2.57353954e+01 -6.55468106e-02 1.81939721e-01] [ 1.07586029e+02 1.60341334e+00 1.03546591e+01 1.01711316e+03 1.08991003e+00 2.57353954e+01 -6.55468106e-02 1.81939721e-01] [ 1.07586029e+02 1.60341334e+00 1.03546591e+01 1.01711316e+03 1.08991003e+00 2.57353954e+01 -6.55468106e-02 1.81939721e-01] in each [] is air quality of every day, it should be different. It does not make different even if I change the input data. Retraining dose not work. I am so confused. Pls tell me why it happens and how to slove it. THANKS VERY MUCH! # -*- coding: utf-8 -*- """ Created on Wed Jun 6 10:56:52 2018 @author: Administrator """ import tensorflow as tf import pandas as pd import numpy as np import csv tf.reset_default_graph() rnn_unit = 50 #the amount of hidden lstm units batch_size = 72 #the amount of data trained every time input_size = 8 #size of input output_size = 8 #size of output lr = 0.006 #learn rate train_x, train_y = [], [] # f = open('C:\\Users\\Administrator\\Desktop\\BJair\\BjAirDat3.csv',encoding='UTF-8') df = pd.read_csv(f) #read the csv file #get data, use the data between 2010 ans 1013 for train，the data of 2014 as exam weatherdata = df.iloc[0:39312 ,5:13] #weather with 7 items, not including PM2.5, for train #pm25data = df.iloc[0+batch_size:39312+batch_size ,5:6] #pm2.5 data, for train weathertest = df.iloc[39312:, 5:13] #weatherdata with 7 items, not including PM2.5, for exam #pm25test = df.iloc[39312: 5:6] #pm2.5 data, for exam #train_x is a tensor which [?,batch_size,input_size] #train_y is a tensor wh…
type: UnansweredQuestion
tagged with: tensorflow
type: Question
tagged with: recurrent-neural-network
has title: Tensorflow LSTM model output same data
tagged with: lstm
score: 0
tagged with: python

opengl
tags question: http://stackoverflow.com/q/50805413
tags question: http://stackoverflow.com/q/50769689
tags question: http://stackoverflow.com/q/50764623
tags question: http://stackoverflow.com/q/50811394
tags question: http://stackoverflow.com/q/50700056
type: Tag
tags question: http://stackoverflow.com/q/50823531
tag name: opengl

http://stackoverflow.com/q/50753808
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88517688
answer count: 0
type: UnansweredQuestion
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88515627
has title: pyqt5 table+ video+ webview showing gmaps give seg fault on ubuntu
has comment: http://stackoverflow.com/comment/88525680
has body: I've a sample code which has a Table widget, A video widget and webview widget that shows google maps. his code works without any issue on Windows machine but when I try to run the same code on a Ubuntu 16.04 machine + PyQt5 5.10.1 I start getting segmentation fault when I run the script multiple times. The crash happens only when I load Google maps. If I simply load google.com then I don't see any crash. Am I missing something? import sys from PyQt5 import QtGui, QtCore from PyQt5.QtCore import QDir, Qt, QUrl from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import (QMainWindow, QApplication, QWidget, QTableWidget,QVBoxLayout, QTableWidgetItem, QHBoxLayout,QSplitter,QGroupBox) from PyQt5.QtWebKit import * from PyQt5.QtWebKitWidgets import * class Window(QWidget): def __init__(self,): super().__init__() self.v_layout = QVBoxLayout(self) self.splitter = QSplitter(QtCore.Qt.Horizontal) self.left = QGroupBox('Left') self.table1 = QTableWidget() self.table1.setRowCount(2) self.table1.setColumnCount(2) self.table1.setItem(0,0, QTableWidgetItem("Cell (1,1)")) self.table1.setItem(0,1, QTableWidgetItem("Cell (1,2)")) self.table1.setItem(1,0, QTableWidgetItem("Cell (2,1)")) self.table1.setItem(1,1, QTableWidgetItem("Cell (2,2)")) self.left_layout = QVBoxLayout(self.left) self.left_layout.addWidget(self.table1) self.right = QGroupBox('Right') self.VideoWidget = QVideoWidget() self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.player.setMedia(QMediaContent(QUrl.fromLocalFile("test.mp4"))) self.player.play() self.player.setVideoOutput(self.VideoWidget) self.webview = QWebView() url = "https://www.google.com/maps/search/?api=1&amp;query=" + str(50.0621004) + "," + str(8.5608973) self.webview.load(QUrl(url)) self.right_layout = QVBoxLayout(self.right) self.right_layout.addWidget(self.webview) self.right_layout.addWidget(self.VideoWidget) self.splitter.addWidget(self.left) self.splitter.…
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/91640934

http://stackoverflow.com/a/50832841
downvote count: 0
answers question: http://stackoverflow.com/q/50816080
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50816080
type: AcceptedAnswer
has body: Per my experience, your issue is resulted from the azure app python environment. Please refer to my work steps and see if the error still shows up. As you found in the Managing Python on Azure App Service , Azure App Service provide you with a site extension. You could install packages on KUDU console. Step 1 : Create azure web app and add Extensions(here is Python 3.6.1 x64) Step 2 : Publish your flask project and add the web.config. web.config: &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;appSettings&gt; &lt;add key="WSGI_HANDLER" value="&lt;Your Project Name&gt;.app"/&gt; &lt;add key="PYTHONPATH" value="D:\home\site\wwwroot"/&gt; &lt;add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/&gt; &lt;/appSettings&gt; &lt;system.webServer&gt; &lt;handlers&gt; &lt;add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\Python361x64\python.exe|D:\home\Python361x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; Step 3: Switch to the Kudu CMD and commands cd Python361x64 and touch get-pip.py and copy the content of the url https://bootstrap.pypa.io/get-pip.py into the get-pip.py via Edit button, then run python get-pip.py to install the pip tool. Step 4 : Install any packages you need via python -m pip install pyodbc Hope it helps you. Any concern ,please let me know.
type: Answer
score: 2

http://stackoverflow.com/comment/88620881
has text: @davedwards Only in Python 2. Since the OP is using 3.x-style `print`s, and it's 2018, he's more likely to be using 3.x.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50807548
score: 0

http://stackoverflow.com/comment/88542061
comment on: http://stackoverflow.com/q/50767161
score: 0
type: QuestionComment
type: Comment
has text: I've edited adding `train.prototxt`. How do i probe into HDF5 file if I can't read into it?

http://stackoverflow.com/a/50723980
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50723447
has body: You can use list(dict.keys()) to get the keys as a list. As N_tro_P pointed out, you can use sorted(dict.keys()) to get keys in sorted order and iterate with that.
answers question: http://stackoverflow.com/q/50723447
score: 4
upvote count: 4

http://stackoverflow.com/comment/88520277
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50751133
has text: `result = AsyncResult(task_id)` `state = result.state` you can return success state in views

http://stackoverflow.com/comment/88559610
type: Comment
comment on: http://stackoverflow.com/a/50775441
has text: @Guitarist I have updated the example for a maximization case. This should better clarify why your algorithm doesn't work.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88554562
has text: Smells alot like homework... Also, we have no idea what your data looks like, and you've made no attempt at beginning to solve this
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50773564

http://stackoverflow.com/comment/113745279
has text: This model is excellent. I had the oportunity to test the GPU implementation. Is there a way to implement it on CPU ?
type: Comment
comment on: http://stackoverflow.com/a/61716647
score: 0
type: AnswerComment

http://stackoverflow.com/q/50784136
has comment: http://stackoverflow.com/comment/88574755
has comment: http://stackoverflow.com/comment/88574921
has comment: http://stackoverflow.com/comment/88574685
has answer: http://stackoverflow.com/a/50784198
has title: How to define a member function outside class in python?
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/972
favorite count: 0
score: -3
duplicate of: http://stackoverflow.com/q/972
tagged with: python
downvote count: 4
has body: import numpy as np class MyClass: a = int() b = float() c = np.array([0 for i in range 10]) def Memberfunction(): print("Hii")
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50784198
type: Question
has comment: http://stackoverflow.com/comment/88574944
has comment: http://stackoverflow.com/comment/88574684

http://stackoverflow.com/comment/88514086
type: QuestionComment
score: 2
has text: If anyone posts an answer with eval they are getting downvoted.
comment on: http://stackoverflow.com/q/50753043
type: Comment

http://stackoverflow.com/q/50735112
tagged with: optimization
linked to: http://stackoverflow.com/q/48226089
answer count: 1
has comment: http://stackoverflow.com/comment/88479338
has answer: http://stackoverflow.com/a/50742437
downvote count: 0
has title: curve_fit a 2D function containing numpy arrays --> shapes (3,3,9) and (3,1) not aligned: 9 (dim 2) != 3 (dim 0)
has comment: http://stackoverflow.com/comment/88490251
favorite count: 0
has body: This is my first question here. I hope I provide sufficient information for you guys. I ran into problems when using curve_fit with a function that uses numpy arrays. Using the function with fixed parameters works fine. The task: I want to find two vectors. What I know is how the vectors are rotated around each other and the coordinate system and the resulting angle between one vector and the coordinate system y-axis. The problem: my_func is the function I want to use but it throws an error only when putting it into curve_fit. my_func2 should be a breakdown of the problem that works. As far as I can see the functions in principal are the same except for my_func2 having less and less complex formulas. This is the code I wrote: import numpy as np from scipy.optimize import curve_fit '''The function I want to optimize. 2D-xdata with 6 free parameters.''' def my_func(X, hx, hy, hz, lx, ly, lz): # These are the two independently measured angles (2D-xdata). phi, alpha = X # y-axis of the coordinate system. yaxis = np.array([[0], [1], [0]]) # First wanted vector h (first three parameters). h = np.array([[hx], [hy], [hz]]) # Second wanted vector l (last three parameters). l = np.array([[lx], [ly], [lz]]) # Projection matrix. Pxy = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]) # Needed to generate the rotation matrix around the unknown vector h. h_norm = h / np.linalg.norm(h) n1, n2, n3 = h_norm[0][0], h_norm[1][0], h_norm[2][0] # Rotation matrix for rotation around the vector h by angle alpha. R_h = np.array([[n1 ** 2 * (1 - np.cos(alpha)) + np.cos(alpha), n1 * n2 * (1 - np.cos(alpha)) - n3 * np.sin(alpha), n1 * n3 * (1 - np.cos(alpha)) + n2 * np.sin(alpha)], [n1 * n2 * (1 - np.cos(alpha)) + n3 * np.sin(alpha), n2 ** 2 * (1 - np.cos(alpha)) + np.cos(alpha), n2 * n3 * (1 - np.cos(alpha)) - n1 * np.sin(alpha)], [n1 * n3 * (1 - np.cos(alpha)) - n2 * np.sin(alpha), n2 * n3 * (1 - np.cos(alpha)) + n1 * np.sin(alpha), n3 ** 2 * (1 - np.cos(alpha)) + np.cos(alpha)]]) # Rotate the ve…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88482691
tagged with: python
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88482755
tagged with: scipy
type: Question
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/88483909

http://stackoverflow.com/comment/88534766
score: 0
comment on: http://stackoverflow.com/q/50723423
type: QuestionComment
type: Comment
has text: Without complete reproducible example we can't tell much

http://stackoverflow.com/q/50704932
linked to: http://stackoverflow.com/q/33072450
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50742637
favorite count: 0
tagged with: python
type: UnansweredQuestion
tagged with: spider-chart
upvote count: 1
has title: Adding tick marks on Thetagrid lines of a polar plot
score: 1
tagged with: matplotlib
has body: I've adapted this sample: Matplotlib: Polar plot axis tick label location. I want to add tick marks next to the tick labels (A, B, C, D and E) along the thetagrid from the center of the polar axis to the thetagrid labels. Also, I want a round circle ending each line, directly below the thetagrid titles (TG01, TG02, etc.). You will see these tick labels and thetagrid titles in my code sample. Visually, here's part of line TG01 to demonstrate what I'm looking for: Here's my current code: import numpy as np import matplotlib.pyplot as plt class Radar(object): def __init__(self, fig, titles, label, rect=None): if rect is None: rect = [0.05, 0.15, 0.95, 0.75] self.n = len(titles) self.angles = [a if a &lt;=360. else a - 360. for a in np.arange(90, 90+360, 360.0/self.n)] self.axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i) for i in range(self.n)] self.ax = self.axes[0] # Show the labels self.ax.set_thetagrids(self.angles, labels=titles, fontsize=14, weight="bold", color="black") for ax in self.axes[1:]: ax.patch.set_visible(False) ax.grid(False) ax.xaxis.set_visible(False) self.ax.yaxis.grid(False) for ax, angle in zip(self.axes, self.angles): ax.set_rgrids(range(1, 6), labels=label, angle=angle, fontsize=12) # hide outer spine (circle) ax.spines["polar"].set_visible(False) ax.set_ylim(0, 6) ax.xaxis.grid(True, color='black', linestyle='-') def plot(self, values, *args, **kw): angle = np.deg2rad(np.r_[self.angles, self.angles[0]]) values = np.r_[values, values[0]] self.ax.plot(angle, values, *args, **kw) fig = plt.figure(1) titles = ['TG01', 'TG02', 'TG03', 'TG04', 'TG05', 'TG06'] label = list("ABCDE") radar = Radar(fig, titles, label) radar.plot([3.75, 3.25, 3.0, 2.75, 4.25, 3.5], "-", linewidth=2, color="b", alpha=.7, label="Data01") radar.plot([3.25, 2.25, 2.25, 2.25, 1.5, 1.75],"-", linewidth=2, color="r", alpha=.7, label="Data02") radar.ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.10), fancybox=True, shadow=True, ncol=4) plt.show() And how…
type: Question

http://stackoverflow.com/comment/88429515
score: 0
type: Comment
has text: Gotcha, can you use that same program to open port 4000 on a second domain? Then use this address as the sockets.io connection address.
type: AnswerComment
comment on: http://stackoverflow.com/a/50710058

http://stackoverflow.com/q/50720588
type: Question
has answer: http://stackoverflow.com/a/50720739
has title: What do these warnings on Python pdfminer3k mean?
has body: What do these warnings on Python pdfminer3k mean? WARNING:pdfminer.layout:Too many boxes (104) to group, skipping. WARNING:pdfminer.layout:Too many boxes (122) to group, skipping.
answer count: 1
has comment: http://stackoverflow.com/comment/88449848
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88449684
tagged with: pdfminer
score: 0

http://stackoverflow.com/a/50735725
answers question: http://stackoverflow.com/q/50735703
has body: Replace things like r with 'r'. Python is reading the r you have written as a variable named r, and you are treating it as a string. Do the same with p, s, etc....
score: 2
downvote count: 0
upvote count: 2
type: Answer

apache
tag name: apache
tags question: http://stackoverflow.com/q/50818147
tags question: http://stackoverflow.com/q/50791205
tags question: http://stackoverflow.com/q/50699780
tags question: http://stackoverflow.com/q/50767192
tags question: http://stackoverflow.com/q/50839890
tags question: http://stackoverflow.com/q/50833833
type: Tag
tags question: http://stackoverflow.com/q/50766188

http://stackoverflow.com/a/50788880
has body: The reason your code isn't working is that you are converting a list to a string, and as such the square brackets and apostrophes are being rendered into the string also. So the timezone relating to iran is actually the string: "'iran',". That is the first letter of the string is an apostrophe, so when you call t.startswith(word), it doesn't match. I take it the goal of converting to string was so that you could turn all of the words to lowercase. A better way of achieving this would be: timezones = [tz.lower() for tz in pytz.all_timezones]
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50788809

http://stackoverflow.com/comment/93907640
type: Comment
comment on: http://stackoverflow.com/q/50750101
type: QuestionComment
has text: Can you share the complete SP codes and Python codes that you tried?
score: 0

http://stackoverflow.com/q/50772096
downvote count: 0
has comment: http://stackoverflow.com/comment/88562614
has comment: http://stackoverflow.com/comment/88551736
has comment: http://stackoverflow.com/comment/88565841
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88552080
type: Question
linked to: http://stackoverflow.com/q/33977273
has comment: http://stackoverflow.com/comment/88565756
has answer: http://stackoverflow.com/a/50779514
has comment: http://stackoverflow.com/comment/88565830
has comment: http://stackoverflow.com/comment/88565718
has body: I found a great Medium article on creating a new neural network architecture that I wanted to try out. Of course, I get to the training part, and things start to fail. I can't import TensorFlow. Whenever I do, I get the error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/myusername/.virtualenvs/worldmodels/lib/python3.5/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * # pylint: disable=redefined-builtin File "/home/myusername/.virtualenvs/worldmodels/lib/python3.5/site-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/home/myusername/.virtualenvs/worldmodels/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 25, in &lt;module&gt; from tensorflow.python.platform import self_check ImportError: No module named 'tensorflow.python.platform' Well, I looked at this which suggested importing in a different folder which did not work. I also tried exporting the PYTHONPATH variable, set to PYTHONPATH="/home/London/.virtualenvs/worldmodels/lib/python3.5/site-packages" and PYTHONPATH="${PYTHONPATH}:/usr/local/lib/python2.7/dist-packages/" and PYTHONPATH="/usr/local/lib/python2.7/dist-packages/", all to no avail. This one seemed to be a language issue, which shouldn't be my problem (and if it is, I don't know what they did to fix it.) This one gave the same folder changing advice. This one seemed to be an issue with someone's command, not just trying to import it. And this one again suggests the setting PYTHONPATH. (And yes, I did see this one, but both the question and answer quality are lacking.) Any ideas as to what I could do to get TensorFlow up and running? (Maybe using a different install process than just pip? I have already tried installing by running sudo pip install tensorflow. I would still like to be able to use it with the Medium tutorial though.)
has comment: http://stackoverflow.com/comment/88551832
has comment: http://stackoverflow.com/comment/88551809
has comment: http://stackoverflow.com/comment/88551872
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/50781121
has title: No module named tensorflow.python.platform on WSL
accepted answer: http://stackoverflow.com/a/50781121
has comment: http://stackoverflow.com/comment/88552108
favorite count: 0
has comment: http://stackoverflow.com/comment/88551863
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50779514
has comment: http://stackoverflow.com/comment/88552839
has comment: http://stackoverflow.com/comment/88559880
has comment: http://stackoverflow.com/comment/88551870
tagged with: python
tagged with: windows-subsystem-for-linux
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88559860

http://stackoverflow.com/q/50775975
accepted answer: http://stackoverflow.com/a/50776128
answer count: 1
tagged with: text-analysis
has title: To seperate words outside brackets as well as inside brackets and put into separate columns in Python?
tagged with: data-cleaning
tagged with: python
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88558878
type: Question
has body: I need solution to the following string in my data set. Need to be splitted into various words to get meaningful insights. a='(Barbecue)Cheese(earthyCamembert,Fontina,nuttyAsiago,Colby,Parmesan)General(Chocolate)Meat(Beef) Here the first words (Barbecue) - represent cusine second word - Cheese(earthyCamembert,Fontina,nuttyAsiago,Colby,Parmesan) third word - General(Chocolate) fourth word - Meat(Beef) Like this above example in need to split it into 4 categories. can anyone help me out to code it python. I am new to this. Thanks.
has answer: http://stackoverflow.com/a/50776128
score: 0

http://stackoverflow.com/a/50821719
type: Answer
answers question: http://stackoverflow.com/q/50821588
accepted answer of: http://stackoverflow.com/q/50821588
has body: I think you mean harva.search() instead of School.search(). You defined search as an instance method. You must call it on an instance of school, and not on School class itself.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/88610112
type: Comment
score: 1
has text: @vog I believe you miss the point of functional programming. You treat the features in Python like they are black-box magic, but you can see that it's easy to implement them using a technique, eg the `unwind` example in the linked duplicate. Once you encode the desired behavior in a function, you can reuse the function wherever that behavior is needed, with complexities of that function hidden away in implementation details that are invisible from the caller.
comment on: http://stackoverflow.com/q/50793976
type: QuestionComment

pyautogui
tags question: http://stackoverflow.com/q/50782056
type: Tag
tags question: http://stackoverflow.com/q/50712139
tags question: http://stackoverflow.com/q/50791644
tags question: http://stackoverflow.com/q/50730539
tag name: pyautogui

http://stackoverflow.com/q/50808188
has title: how to see the parsing speed of log file for every line and every 10sec
tagged with: python
answer count: 0
downvote count: 0
type: UnansweredQuestion
type: Question
has body: I have a log file and I want it to be parsed every line and in 10 seconds I need to know the speed of the parsing. But my code is parsing the data from the log file, so it only takes the data of the log, not speed of the log file . my python code: import re import schedule import threading import time log_file = '/Users/kiya/Desktop/mysql/ipscan/ip.txt' output_file ='/Users/kiya/Desktop/mysql/ipscan/puu.csv' name_to_check = 'MBX_AUTHENTICATION_FAILED' start = time.time() class Log_minning: def __init__(self): self.data_counter = 0 self.time_counter = 1 def get_userdata(self): user_att = [] list_usr = [] counterr = 0 with open(log_file) as infile: for line in infile: if name_to_check in line: date = re.search(r"([12]\d{3}(0[1-9]|1[0-2])+" "(0[1-9]|[12]\d|3[01]))", line) date = date.group() ) ip = ip.group() user_att.append(date) list_usr.append(user_att) counterr = counterr + 1 # print("get " + username + " " + date + " " + time + " " # + ip) self.data_counter = counterr return list_usr def procces(self): self.get_userdata() def check_length(self): speed = self.data_counter / (self.time_counter * 10) print("Speed =" + str(speed) + " data/sec") self.time_counter = self.time_counter + 1 def log_control(self): schedule.every(10).seconds.do(self.check_length) def schedule_triger(self): while True: schedule.run_pending() time.sleep(10) if __name__ == "__main__": lm = Log_minning() lm.log_control() t1 = threading.Thread(lm.procces()) t2 = threading.Thread(lm.schedule_triger()) t1.start() t2.start() t1.join() t2.join() my output is: Speed =11.7 data/sec Speed =5.85 data/sec Speed =3.9 data/sec This is the result I am expecting from my code: 92748.4 line/s 91840.8 line/s 91867.1 line/s 92661.2 line/s
score: 2
upvote count: 2
favorite count: 0

http://stackoverflow.com/a/50708003
upvote count: 1
has body: I hope I have understood your idea correctly. I suggest you could do the following. fh = open("my.csv", "w+") path = 'my path' for filename in os.listdir(path): with open(os.path.join(path,filename), "r") as infile: count1 = 0 count2 = 0 for line in infile: if re.search(r"\b10G\b", line, flags=re.IGNORECASE): count1 += 1 if re.search(r"\b10G\b", line, flags=re.IGNORECASE): count2 += 1 # write the count value to the csv after reading the file fh.write("Count1: {} Count2: {}\n".format(count1, count2)) # close the file reader - otherwise there won't be any content in the csv fh.close()
has comment: http://stackoverflow.com/comment/88425460
score: 1
has comment: http://stackoverflow.com/comment/88425986
has comment: http://stackoverflow.com/comment/88449515
has comment: http://stackoverflow.com/comment/88449491
accepted answer of: http://stackoverflow.com/q/50707821
has comment: http://stackoverflow.com/comment/88429382
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50707821
has comment: http://stackoverflow.com/comment/88449544
has comment: http://stackoverflow.com/comment/88438824
type: Answer
has comment: http://stackoverflow.com/comment/88448574

http://stackoverflow.com/a/50852027
has comment: http://stackoverflow.com/comment/88706708
upvote count: 1
answers question: http://stackoverflow.com/q/50851905
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88708600
accepted answer of: http://stackoverflow.com/q/50851905
has comment: http://stackoverflow.com/comment/88708033
has comment: http://stackoverflow.com/comment/88708507
type: Answer
downvote count: 0
score: 1
has body: The Word object model is not written in VBA (although the documentation is targeted at VBA developers). It is written as a language-agnostic binary object API which can be accessed from multiple languages. (See here for a comparison between using VBA and Python to access the object model.) In your case, this: word.Documents(1).Paragraphs.Item(3) returns an instance of a Paragraph object, which is not equivalent to a string. This makes sense because a Word paragraph is more than just a string -- it may include paragraph-level formatting, drop caps etc, character-level formatting etc. You need to start by getting the Range object corresponding to the paragraph, via the Paragraph's Range property. The Range object: corresponds to a contiguous area of the document Then you need the Text property of the Range object. Like so: word = win32.gencache.EnsureDispatch('Word.Application') word.Documents.Open('xxxxxxxxx.docx') string = word.Documents(1).Paragraphs(3).Range.Text print string if string == "My Hard Coded String": print "True" else: print "False" NB. I haven't tested, but I don't think you need to explicitly call Paragraphs.Item. The object model supports a concept called default properties, which means that (in Python, at least) you can pass arguments to an object with a default property and those arguments will be passed to the property. In other words, the following are equivalent: string = word.Documents(1).Paragraphs(3).Range.Text string = word.Documents.Item(1).Paragraphs.Item(3).Range.Text I think this is also why print string in your code prints out the string. Not because string is a different kind of string, but because the default property chain is as follows: Paragraph.Range.Text; and when a simple value (as opposed to an object) is expected, the chain is followed until the end, which is a string at the Text property. Reference: Paragraphs collection, Paragraphs.Item method Paragraph object, Paragraph.Range property Range object, Range.Text property Note…
has comment: http://stackoverflow.com/comment/88707488
has comment: http://stackoverflow.com/comment/88707963

http://stackoverflow.com/a/76717806
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50839667
has body: For protobuf&gt;=3.20.x Install Protocol Buffers library for Python pip install protobuf set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python Clean the caches and restart the kernel Alternatives Downgrade the protobuf package to 3.20.x or lower pip install protobuf=3.11.3 Search for any duplicate occurrences of the sentencepiece_model.proto file in your project. Make sure there is only one copy of the file present.

http://stackoverflow.com/a/50726414
has comment: http://stackoverflow.com/comment/88478184
answers question: http://stackoverflow.com/q/50723257
type: AcceptedAnswer
downvote count: 0
has body: You can display the result disparity using cv2.imshow() as well after you normalize it. norm_image = cv2.normalize(disparity, None, alpha = 0, beta = 1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) cv2.imshow('norm_image', norm_image) Notice the change of data type after normalizing the image. Prior to normalization disparity was of type int16. After normalization it is float32 (mentioned within the function cv2.normalize())
type: Answer
accepted answer of: http://stackoverflow.com/q/50723257
score: 3
upvote count: 3

http://stackoverflow.com/comment/88574045
comment on: http://stackoverflow.com/a/50783585
type: Comment
score: 0
type: AnswerComment
has text: I recommend you see the implementation here: https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/feature_selection/univariate_selection.py#L171

http://stackoverflow.com/comment/88645709
type: Comment
has text: You still have time to edit.
score: 2
comment on: http://stackoverflow.com/q/50820029
type: QuestionComment

http://stackoverflow.com/comment/88554703
score: 0
type: Comment
type: QuestionComment
has text: @Brenlla It worked!
comment on: http://stackoverflow.com/q/50772882

http://stackoverflow.com/comment/88542204
has text: Thank you for helping. I am new to Django. I am using Django version 1.11.13. I corrected the expression as suggested. still I am not able to add,deletecomplete,deleteall ( please give me correct regex expression for that)).
type: AnswerComment
comment on: http://stackoverflow.com/a/50767060
score: 0
type: Comment

http://stackoverflow.com/comment/88554404
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50752275
has text: Sorry, "double clicking" was a mistake, activatable cells are activated by just a click, see e.g. how toggle (checkbox) cells behave. Edit controls are indeed created after the cell is already selected -- but how else could it possibly work?
score: 0

http://stackoverflow.com/a/50822333
score: 5
has comment: http://stackoverflow.com/comment/88649676
has comment: http://stackoverflow.com/comment/88649766
type: Answer
has body: Ordering Users by the number of posts We can annotate a User with the number of Posts, and then use order_by on that annotation: from django.db.models import Count User.objects.annotate(nposts=Count('post')).order_by('-nposts') Here the dash (-) means that we sort in descending order (so from many posts to few posts). If you remove the dash, then it orders in ascending order. Assigning a numerical rank to the Users We can also assign a numerical rank to each user (so 1-10 map to 1, 11-20 map to 2, etc.) by adding some extra annotation: from django.db.models import Count, F from django.db.models.expressions import Func User.objects.annotate( nposts=Count('post'), nrank=Func(F('nposts') / 10, function='CEIL'), ).order_by('-nposts') Mapping the numeric rank to an textual rank We can map this rank to a textual rank, by defining for example a @property: from django.contrib.auth import User RANK_TEXTS = ['zero', 'first', 'second', 'third'] def rank_text(self): nrank = getattr(self, 'nrank', None) if nrank is None: nrank = (Post.objects(author=self).count() + 9) // 10 return RANK_TEXTS[nrank] User.rank_text = property(rank_text) So we monkey patch the User class such that it has a property rank_text. This will first look if we annotated the User with the nrank attribute. If that is not the case, we calculate the nrank manually. Finally we return the textual counterpart. So we can for example query with: u1 = User.objects.first() u1.rank_text # for example "second" Se here [so-post] how to monkey patch Django models.
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/88649700
has comment: http://stackoverflow.com/comment/88649807
has comment: http://stackoverflow.com/comment/88649742
has comment: http://stackoverflow.com/comment/88658080
answers question: http://stackoverflow.com/q/50822307

http://stackoverflow.com/comment/88656492
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50823537
has text: @DietrichEpp I found [my own answer on a feature request from over 3 years ago](https://meta.stackexchange.com/a/253759/230882), and two years later [that feature request was declined](https://meta.stackexchange.com/a/302182/230882), accepting that the `sub` workaround is, while ugly, good enough for SO.
type: AnswerComment

http://stackoverflow.com/q/50774378
has comment: http://stackoverflow.com/comment/88555899
has answer: http://stackoverflow.com/a/50777356
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88556059
has comment: http://stackoverflow.com/comment/88555933
has body: I am beginner in web developing. I am trying to make the ajax request with POST method (without jquery). Following is my JS code function loadDoc() { var Obj = {"user_Name":"testName"}; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200) { document.getElementById("x").innerHTML = this.responseText; } }; xhttp.open("POST", "/cgi-bin/Messapp/hostelapp.py", true); xhttp.setRequestHeader("Content-Type", "text/json"); xhttp.send(JSON.stringify(Obj)); } Then following is my python script #!D:/python/python.exe print("Content-Type: text/json\n\n") import cgi, cgitb , re cgitb.enable() form = cgi.FieldStorage() #I am facing problem in this line print(form["user_Name]) Please see the below error
tagged with: python
accepted answer: http://stackoverflow.com/a/50777356
has comment: http://stackoverflow.com/comment/88555967
has comment: http://stackoverflow.com/comment/88555790
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88555775
has title: JavaScript ajax post not getting data in python?
tagged with: javascript
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88556286

http://stackoverflow.com/a/50751176
has comment: http://stackoverflow.com/comment/88510323
has comment: http://stackoverflow.com/comment/88511828
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88513083
type: Answer
has comment: http://stackoverflow.com/comment/88510378
accepted answer of: http://stackoverflow.com/q/50750999
answers question: http://stackoverflow.com/q/50750999
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88658850
has body: It sounds like you're not correctly calling the .merge() method from your data frame. Try import pandas as pd # Your reproducible example d1 = {'Pressure': {0: 923.3383179, 1: 923.2299805, 2: 923.1216431, 3: 923.1466675}, 'merge_key': {0: '1/1/2012 0:00', 1: '1/1/2012 0:30', 2: '1/1/2012 1:00', 3: '1/1/2012 1:30'}} d2 = {'merge_key': {0: '1/1/2012 0:30', 1: '1/1/2012 0:30', 2: '1/1/2012 0:30', 3: '1/1/2012 0:30', 4: '1/1/2012 0:30', 5: '1/1/2012 0:30', 6: '1/1/2012 1:00', 7: '1/1/2012 1:00', 8: '1/1/2012 1:00', 9: '1/1/2012 1:00', 10: '1/1/2012 1:00', 11: '1/1/2012 1:00'}, 'value': {0: 16.9444, 1: 16.6837, 2: 16.6837, 3: 16.9444, 4: 16.1623, 5: 16.6837, 6: 16.1623, 7: 16.423, 8: 16.1623, 9: 17.2051, 10: 16.9444, 11: 16.423}} # Convert above dictionary to pandas data frame df1 = pd.DataFrame(d1) df2 = pd.DataFrame(d2) print(df1) # Pressure merge_key # 0 923.338318 1/1/2012 0:00 # 1 923.229981 1/1/2012 0:30 # 2 923.121643 1/1/2012 1:00 # 3 923.146668 1/1/2012 1:30 print(df2) # merge_key value # 0 1/1/2012 0:30 16.9444 # 1 1/1/2012 0:30 16.6837 # 2 1/1/2012 0:30 16.6837 # 3 1/1/2012 0:30 16.9444 # 4 1/1/2012 0:30 16.1623 # 5 1/1/2012 0:30 16.6837 # 6 1/1/2012 1:00 16.1623 # 7 1/1/2012 1:00 16.4230 # 8 1/1/2012 1:00 16.1623 # 9 1/1/2012 1:00 17.2051 # 10 1/1/2012 1:00 16.9444 # 11 1/1/2012 1:00 16.4230 print(df1.merge(df2)) # Pressure merge_key value # 0 923.229981 1/1/2012 0:30 16.9444 # 1 923.229981 1/1/2012 0:30 16.6837 # 2 923.229981 1/1/2012 0:30 16.6837 # 3 923.229981 1/1/2012 0:30 16.9444 # 4 923.229981 1/1/2012 0:30 16.1623 # 5 923.229981 1/1/2012 0:30 16.6837 # 6 923.121643 1/1/2012 1:00 16.1623 # 7 923.121643 1/1/2012 1:00 16.4230 # 8 923.121643 1/1/2012 1:00 16.1623 # 9 923.121643 1/1/2012 1:00 17.2051 # 10 923.121643 1/1/2012 1:00 16.9444 # 11 923.121643 1/1/2012 1:00 16.4230
has comment: http://stackoverflow.com/comment/88510358

http://stackoverflow.com/q/50794468
has title: pytest-mock - Mock a function from a module
accepted answer: http://stackoverflow.com/a/50795580
tagged with: python
has comment: http://stackoverflow.com/comment/88596515
has body: I have an util in my module engine.py, which is imported from another file: from main.utils.string import get_random_string def generate_random_string(): return get_random_string() In my test file: def test_generate_random_string(mocker): mocker.patch('main.utils.string.get_random_string', return_value='123456') However, it's still trying to use the real implementation of string.get_random_string instead of the mock that I've created, unless I change my engine.py to: from main.utils import string def generate_random_string(): return string.get_random_string() How can I achieve the mocking part without importing the whole string module to engine.py?
has comment: http://stackoverflow.com/comment/88595236
upvote count: 17
type: AnsweredQuestion
tagged with: pytest
has comment: http://stackoverflow.com/comment/88595315
has comment: http://stackoverflow.com/comment/88596082
possible better answer: http://stackoverflow.com/a/71665950
has answer: http://stackoverflow.com/a/71665950
score: 17
has answer: http://stackoverflow.com/a/50795580
type: Question
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88573963
comment on: http://stackoverflow.com/a/50783520
type: Comment
score: 0
type: AnswerComment
has text: @Zev O(n), but it really doesn't have much to do with his request, just wanted to make it easy for him to understand :)

http://stackoverflow.com/q/50845832
answer count: 1
has answer: http://stackoverflow.com/a/50866605
tagged with: cpython
tagged with: python
type: AnsweredQuestion
has title: where does python interpreter fit in Tensorflow runtime architecture?
has body: According to Tensorflow architecture page, the following figure illustrates the general architecture of Tensorflow runtime architecture. A C API separates user level code in different languages from the core runtime. How does python interpreter fit in the picture? In parallel to Tensorflow runtime?
accepted answer: http://stackoverflow.com/a/50866605
tagged with: tensorflow
type: Question
score: 0

http://stackoverflow.com/q/50717209
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50717302
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: django custom user model gives me lazy reference error
has body: My code is as shown below: models/user.py from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin,BaseUserManager ) class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email,and password. """ if not email: raise ValueError('The given email must be set') try: with transaction.atomic(): user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user except: raise def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password=password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. """ email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) return self models/init.py from user import User settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.Authenticatio…

http://stackoverflow.com/comment/88713556
type: QuestionComment
type: Comment
has text: I got stuck at on the line cur.execute("INSERT OR REPLACE INTO crawled VALUES. as i think this is adding more data not replacing it
comment on: http://stackoverflow.com/q/50757488
score: 0

http://stackoverflow.com/comment/88545094
comment on: http://stackoverflow.com/a/50767622
type: Comment
has text: Yeah I took the `seek`, it much better than closing and opening the file over and over.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88420042
has text: Works perfectly
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50705023

http://stackoverflow.com/q/50723020
has body: I'd like to ask if someone has ever dealt with the same type of error with different files. My friend and I did a code to convert PDF files to JPG images, but quite often it gives an error like: "wand.exceptions.CorruptImageError: unable to read image data C:/Users/ACERES~1/AppData/Local/Temp/magick-1364LojCg7PrnIwH1' @ error/pnm.c/ReadPNMImage/1344 Exception TypeError: TypeError("object of type 'NoneType' has no len()",) in <bound method Image.__del__ of <wand.image.Image: (empty)>> ignored" The files we are working with are not corrupted and they do open propely. Not only that, there quite a number of PDFs that work fine and this error doesn't show up. Any ideas on to solve that? Thanks for any tips and effort, in advance. We are using: Windows 10 64-bits JetBrains PyCharm Community Edition 2018.1 x64; ImageMagick-6.9.9-50-Q8-x64-dll (Win64 dynamic at 8 bits-per-pixel component); the following libraries: { from wand.image import Image from pyPdf import PdfFileReader, PdfFileWriter import io import glob import os.path }; The error occurs here: from wand.image import Image from pyPdf import PdfFileReader, PdfFileWriter import io import glob import os.path for page_num in range(reader.getNumPages()): writer = PdfFileWriter() writer.addPage(reader.getPage(page_num)) # outputStream = file(p, "w+") pdf_bytes = io.BytesIO() writer.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=100) # (*error in this line) img.convert("jpg") img.save(filename=dayName + "/" + str(page_num) + ".jpg")
has comment: http://stackoverflow.com/comment/88468889
score: 0
tagged with: imagemagick
has comment: http://stackoverflow.com/comment/88456541
has comment: http://stackoverflow.com/comment/90905556
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
has title: Constant error using ImageMagick with Python in Windows
tagged with: wand
answer count: 0
tagged with: pypdf
type: Question
has comment: http://stackoverflow.com/comment/88456326

http://stackoverflow.com/comment/88484347
score: 0
has text: the behavior of the `resample` function is really unexpected here ; I guess it could be worthy of an opened github issue
type: Comment
comment on: http://stackoverflow.com/q/50724231
type: QuestionComment

http://stackoverflow.com/comment/88494529
comment on: http://stackoverflow.com/a/50743104
type: Comment
has text: `for s in ls`: #O(n) `for ss in ls2`: #O(m) `if s in ss`: #O(p) `print (s,ss,ls.index(s))` #(q) because of `ls.index()` function. so overall O(m * n* p * q)
score: 0
type: AnswerComment

http://stackoverflow.com/a/50701871
has body: If you actually start with a list you can use slice and reversed to bounce it once like this: def bounce(a_list): yield from a_list yield from reversed(a_list[1:-1]) for x in bounce([1, 2, 3, 4]): print(x) Repeat the bouncyness for added fun. for x in itertools.cycle(bounce([0, 1, 2])): print(x)
upvote count: 3
has comment: http://stackoverflow.com/comment/88414040
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50701772
has comment: http://stackoverflow.com/comment/88413656
score: 3
answers question: http://stackoverflow.com/q/50701772
type: AcceptedAnswer

http://stackoverflow.com/q/50726370
has comment: http://stackoverflow.com/comment/88504669
has comment: http://stackoverflow.com/comment/88507387
type: Question
tagged with: python-2.7
upvote count: 1
tagged with: perl
linked to: http://stackoverflow.com/q/3207219
answer count: 1
has comment: http://stackoverflow.com/comment/88461124
tagged with: opendir
tagged with: python
has title: python equivalent of perl's "opendir"
favorite count: 0
tagged with: file-pointer
has answer: http://stackoverflow.com/a/62066364
has body: What I am essentially looking for is a way to return a handle to a directory in python, a bit like how perl can do something like this... opendir CWD . see: http://perldoc.perl.org/5.8.9/functions/opendir.html CWD can then be used as a handle for pointing to the directory like *CWD in file operations. The closest I've come across in python is open() but that doesn't return file descriptors/pointers and doesn't work with directories.
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88504964
score: 1

http://stackoverflow.com/q/50821649
has comment: http://stackoverflow.com/comment/88652136
answer count: 1
has body: I have two questions that bother me. I'm facing an implementation where some document are related to different level of geodata and would like a factory to generate them. Let's see an example how I thought it may work: from django.contrib.gis.db import models class Country(models.Model): name = models.CharField(max_length=60) class Region(models.Model): country = models.ForeignKey(Country, on_delete=models.PROTECT) name = models.CharField(max_length=60) class Law(models.Model): text = models.CharField(max_length=60) class Meta: abstract = True class CountryLaw(Law): country = models.ForeignKey(Country, on_delete=models.CASCADE) class RegionLaw(Law): region = models.ForeignKey(Region, on_delete=models.CASCADE) # Not sure this work but the idea is here class LawManager(models.Manager): def create_law(text,geodata): if isinstance(geodata, Country): return CountryLaw(text=text, country=geodata) elif isinstance(geodata, Region) return RegionLaw(text=text, region=geodata) else: raise TypeError("Inapropriate geodata type") I would like some factory method because I have some work to fill the fields of the "Law" that is common to all law, but this example doesn't show it. My question are the following : Is there a better way to design Law objects ? Would such a manager work ? How could I access it ? I search on google and stackoverflow for answer, but don't know what keyword to use and didnt found anything that could help me.. thanks for your help !
tagged with: django-models
has title: Django Generic Factory
accepted answer: http://stackoverflow.com/a/50826082
downvote count: 0
tagged with: factory-pattern
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88652032
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88648412
has answer: http://stackoverflow.com/a/50826082
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88562083
score: 0
type: AnswerComment
type: Comment
has text: It makes sense, if the ratio is 90% to 10% then this cross validator will guarantee that in your train and valid sets the distribution will be similar
comment on: http://stackoverflow.com/a/50776154

http://stackoverflow.com/comment/88690644
score: 0
type: Comment
has text: @user3088202 indeed I add a column, with urls. for `[:count+1] / [count+1:]` you are right about from the beginning to half and from half to the end. but it's not really accesing the index (as index does not have to be integer) but it is a slice of quantity, see this [link](https://pandas.pydata.org/pandas-docs/stable/indexing.html) for more details on slicing. So for the half, I used your `count` which give the half size of your data and I slice up to the half
comment on: http://stackoverflow.com/a/50842247
type: AnswerComment

http://stackoverflow.com/comment/88538118
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50764879
has text: Can you clarify why do you need to define dict inside class? Or why do you need that class at all?
score: 0

http://stackoverflow.com/comment/88522122
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50755159
has text: You may find the answers to https://stackoverflow.com/questions/1703640/how-to-implement-a-pythonic-equivalent-of-tail-f and https://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python helpful.
type: Comment

http://stackoverflow.com/a/78722092
score: -1
downvote count: 2
upvote count: 1
has body: here is an example from my repo https://github.com/kamangir/blue-options pip install blue_options then add this line to your ~/.bash_profile or ~/.bashrc, source $(python -m blue_options locate)/.bash/blue_options.sh and use it, function func() { local options=$1 local var=$(abcli_options "$options" var default) local key=$(abcli_options_int "$options" key 0) "$key" == 1 && echo "var=$var" }
answers question: http://stackoverflow.com/q/50794064
type: Answer

http://stackoverflow.com/comment/88679089
comment on: http://stackoverflow.com/a/50823537
score: 1
type: AnswerComment
type: Comment
has text: FWIW -2.0 in bit representation is actually 0xc000000000000000 (little-endian).

http://stackoverflow.com/comment/88699554
comment on: http://stackoverflow.com/q/50846548
score: 0
type: Comment
type: QuestionComment
has text: @AAA you have strange structure of project. Do you have customizations in `manage.py`? `'...'` in INSTALLED_APPS - is your real code or you just abbreviated before pasting here?

http://stackoverflow.com/a/50768735
has comment: http://stackoverflow.com/comment/88545074
accepted answer of: http://stackoverflow.com/q/50768503
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: I believe that this line: corrected_contents += corrected_line is the culprit. IIUC (and I'm sure people will correct me if I'm wrong) this allocates a bigger string, copies the old contents over and then appends the new stuff - for every line in the file. As it gets longer, more and more has to be copied over and you end up with the behavior you are observing. There is more information about string concatenation at How do I append one string to another in Python? where it is mentioned that apparently CPython optimizes this in certain cases and turns it from quadratic to linear (so I may be wrong above: yours may be such an optimized case). It also mentions that pypy does not. So it also depends on how you run your program. It might also be the case that the optimization does not apply because your string is too big (it's enough to fill a CD after all). The linked answer also has a wealth of information on methods to get around the problem (if it is indeed the problem). Well worth reading.
answers question: http://stackoverflow.com/q/50768503

http://stackoverflow.com/a/50758372
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88526219
has comment: http://stackoverflow.com/comment/88526075
answers question: http://stackoverflow.com/q/50758256
has body: You have a problem with your INSERT, the error reported is because the insert has failed and you have not rolled back the transaction before issuing another. The execute should use question marks as placeholders (?) not %s So for your statement you should use sql = "INSERT INTO udir_content (subject, level, school, place) VALUES (?, ?, ?, ?);"
has comment: http://stackoverflow.com/comment/88524823

http://stackoverflow.com/comment/88502569
score: 2
comment on: http://stackoverflow.com/q/50747481
type: QuestionComment
type: Comment
has text: The simplest way to write this is to write a simpler function that returns the score of a word, and then use it as a key function, so all you need is `def best(lista): return max(lista, key=score_of_word)`.

http://stackoverflow.com/q/50827917
accepted answer: http://stackoverflow.com/a/50828048
has comment: http://stackoverflow.com/comment/88660483
has body: Code: def match(i,arr=arr): tmp = filter(lambda x: len({*i} &amp; {*x})==4,arr) for i in tmp: print(i) t_arr = np.array([[10, 11 ,12 ,13 ,26 ,28],[10, 13 ,18 ,26 ,28, 30]]) match((10, 11, 12, 13),arr=t_arr) result: [10 11 12 13 26 28] [10 13 18 26 28 30] I want to select elements intersecting target one(10,11,12,13). The length of new intersected element should be 4. But my code fails to exclude [10, 13 ,18 ,26 ,28, 30] . And len({*(10,11,12,13)}&amp;{*[10, 13 ,18 ,26 ,28, 30]} get 2, which seems strange. Hope: Solve problem and explain why my code fails.
tagged with: python
has title: Filter fail to select data based on length in python?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88660711
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50828048
score: 0
answer count: 1

http://stackoverflow.com/q/50725424
type: Question
answer count: 1
has title: Python failure on mod.bind()
score: 0
accepted answer: http://stackoverflow.com/a/50769953
tagged with: python
has comment: http://stackoverflow.com/comment/88547323
type: AnsweredQuestion
has body: Description Index type must be set for one_hot operator, but I do not find where or how to set it. Environment info ----------Python Info---------- Version : 3.6.5 Compiler : GCC 7.2.0 Build : ('default', 'Apr 29 2018 16:14:56') Arch : ('64bit', '') ------------Pip Info----------- Version : 10.0.1 Directory : /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/pip ----------MXNet Info----------- Version : 1.3.0 Directory : /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet Commit Hash : 247d57944f7a989d8f445856769e704b83765828 ----------System Info---------- Platform : Linux-4.13.0-43-generic-x86_64-with-debian-stretch-sid system : Linux node : augustinasNT release : 4.13.0-43-generic version : #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 Error Message: RuntimeError: simple_bind error. Arguments: data: (1, 3, 112, 112) Error in operator one_hot0: [19:29:50] src/operator/tensor/./indexing_op.h:1002: Check failed: (*in_attrs)[0] != -1 (-1 vs. -1) Index type must be set for one_hot operator Stack trace returned 10 entries: [bt] (0) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet/libmxnet.so(+0x1d7c2a) [0x7fd3b2363c2a] [bt] (1) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet/libmxnet.so(+0x1d8261) [0x7fd3b2364261] [bt] (2) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet/libmxnet.so(+0x211641f) [0x7fd3b42a241f] [bt] (3) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet/libmxnet.so(+0x2672116) [0x7fd3b47fe116] [bt] (4) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet/libmxnet.so(+0x267b971) [0x7fd3b4807971] [bt] (5) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet/libmxnet.so(+0x267c3ca) [0x7fd3b48083ca] [bt] (6) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-packages/mxnet/libmxnet.so(+0x266ca22) [0x7fd3b47f8a22] [bt] (7) /home/augustinas/anaconda3/envs/mxnet/lib/python3.6/site-pack…
tagged with: mxnet
has answer: http://stackoverflow.com/a/50769953

http://stackoverflow.com/comment/118554241
type: Comment
has text: @Aenaon: according to the [docs](https://docs.python.org/3/library/logging.html#logging.getLogger) `getLogger()` (without an input argument) will return the `root` logger. So, indeed, you *will* see logging output from both `main_module` and `auxiliary_module`, *but* both messages will come from the `root` logger. The point of using `getLogger(__name__)` is that it lets us know from which module the log message originates.
score: 2
comment on: http://stackoverflow.com/a/50755200
type: AnswerComment

http://stackoverflow.com/comment/88450875
type: Comment
type: QuestionComment
has text: The working directory of a python program is the directory (folder) that the program is "in", in the same way that you're "in" a folder when you're navigating through Explorer on a Windows computer. This is the directory that you use by default, when reading, writing, and creating files. This is by default the directory from which you execute python, which is usually the one where your `.py` file is located. You can change this directory using `os.chdir`, or specify a path to a file in another directory, like `C:\test.txt` or `../../test.txt`.
score: 0
comment on: http://stackoverflow.com/q/50717130

http://stackoverflow.com/q/50721762
tagged with: python
linked to: http://stackoverflow.com/q/48449391
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88453166
upvote count: 1
has answer: http://stackoverflow.com/a/50721962
type: Question
tagged with: numpy
has body: I'm trying to run a loop that iterates through an image folder and returns two numpy arrays: x - stores the image as a numpy array y - stores the label. A folder can easily have over 40.000 rgb images, with dimensions (224,224). I have around 12Gb of memory but after some iterations, the used memory just spikes up and everything stops. What can I do to fix this issue? def create_set(path, quality): x_file = glob.glob(path + '*') x = [] for i, img in enumerate(x_file): image = cv2.imread(img, cv2.IMREAD_COLOR) x.append(np.asarray(image)) if i % 50 == 0: print('{} - {} images processed'.format(path, i)) x = np.asarray(x) x = x/255 y = np.zeros((x.shape[0], 2)) if quality == 0: y[:,0] = 1 else: y[:,1] = 1 return x, y
tagged with: imread
tagged with: image
has title: Out of memory converting image files to numpy array
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50721962
has comment: http://stackoverflow.com/comment/88453437
favorite count: 0
has comment: http://stackoverflow.com/comment/88452953

http://stackoverflow.com/comment/88507480
score: 0
type: Comment
type: QuestionComment
has text: @hoefling I tried your reinstall command and it appeared successful. But then when I tried using pip it still failed with the same message. I will add the error trace in my original post.
comment on: http://stackoverflow.com/q/50742538

http://stackoverflow.com/a/50806246
score: 1
has body: Your trouble here is that you're returning within a loop, which means that you never get the remainder of your data. You could fix that by simply swapping return for yield and changing your retrieval call to: data = list(getallDups()) This will allow your loop to complete fully.
has comment: http://stackoverflow.com/comment/88620823
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50806040
upvote count: 1

http://stackoverflow.com/comment/88459570
has text: To your other comment - the function is populating a data table. In this case, it is desirable to not have it raise an exception but to explain that I would have to walk you through a rather lengthy piece of code. There is a reason why this simple test allows the code to work right. I was looking to see if there was a way to get around my workaround for better readability.
score: 0
comment on: http://stackoverflow.com/q/50725331
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50825819
type: AnsweredQuestion
has title: Flask app on Cloud Foundry - Command "python setup.py egg_info" failed with error code 1
type: Question
linked to: http://stackoverflow.com/q/50812817
accepted answer: http://stackoverflow.com/a/50838187
has body: I am trying to push a Python (3.6.5) app via Flask to Cloud Foundry (cf version 6.36.1+e3799ad7e.2018-04-04). The application takes a POST request (text file), does some text transformation, saves the new file, and returns a confirmation message. It works locally (tested via Postman). However, when attempting to push it to CF, it gives the following error - Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ygzuah5g/logging/ Could you please let me know how I can go about solving this issue? Thanks in advance. The entire files together are ~ 350 MB. I am using a manifest.yml --- applications: - name: textsum memory: 512M command: python server.py buildpack: https://github.com/cloudfoundry/buildpack-python.git PS - Not sure if this is helpful, I do have import queue in one of my files. If I change it to import Queue (Py 2x compatible) and use Py 2.7.15 runtime, the cf push is successful, but it throws runtime errors ERROR in app: Exception on / [POST] File "/home/vcap/deps/0/python/lib/python2.7/subprocess.py", line 1047, in _execute_child ERR raise child_exception ERR OSError: [Errno 2] No such file or directory ERR 10.0.65.11 - - [12/Jun/2018 20:56:16] "POST / HTTP/1.1" 500 -
tagged with: flask
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50838187
tagged with: cloud-foundry
tagged with: python

http://stackoverflow.com/comment/88447863
type: AnswerComment
has text: hmmm, I am a bit confused, need add same value `59.959` ?
type: Comment
comment on: http://stackoverflow.com/a/50719653
score: 0

http://stackoverflow.com/comment/88544308
has text: You can just keep all the input file names in a list, iterate over all the names, and save the data in some other file. There is no need to open the notebook multiple times.
score: 2
comment on: http://stackoverflow.com/q/50768396
type: Comment
type: QuestionComment

function
tags question: http://stackoverflow.com/q/50839112
tags question: http://stackoverflow.com/q/50789348
tags question: http://stackoverflow.com/q/50768522
tags question: http://stackoverflow.com/q/50775733
tag name: function
tags question: http://stackoverflow.com/q/50756723
tags question: http://stackoverflow.com/q/50756793
tags question: http://stackoverflow.com/q/50854360
tags question: http://stackoverflow.com/q/50709759
tags question: http://stackoverflow.com/q/50752773
tags question: http://stackoverflow.com/q/50711005
tags question: http://stackoverflow.com/q/50854717
tags question: http://stackoverflow.com/q/50770092
tags question: http://stackoverflow.com/q/50839992
tags question: http://stackoverflow.com/q/50777577
tags question: http://stackoverflow.com/q/50766521
tags question: http://stackoverflow.com/q/50744405
tags question: http://stackoverflow.com/q/50831179
tags question: http://stackoverflow.com/q/50853849
tags question: http://stackoverflow.com/q/50743293
tags question: http://stackoverflow.com/q/50747181
tags question: http://stackoverflow.com/q/50760319
tags question: http://stackoverflow.com/q/50720241
tags question: http://stackoverflow.com/q/50703769
type: Tag
tags question: http://stackoverflow.com/q/50849458
tags question: http://stackoverflow.com/q/50761157
tags question: http://stackoverflow.com/q/50808799
tags question: http://stackoverflow.com/q/50744669
tags question: http://stackoverflow.com/q/50791347
tags question: http://stackoverflow.com/q/50748906
tags question: http://stackoverflow.com/q/50741765
tags question: http://stackoverflow.com/q/50738140
tags question: http://stackoverflow.com/q/50814814
tags question: http://stackoverflow.com/q/50820929
tags question: http://stackoverflow.com/q/50770833
tags question: http://stackoverflow.com/q/50780607
tags question: http://stackoverflow.com/q/50736210
tags question: http://stackoverflow.com/q/50777683

http://stackoverflow.com/comment/88507763
has text: you are correct, but strangely your solution is also retaining the `null`s for me
comment on: http://stackoverflow.com/a/50749778
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50768109
score: 0
has comment: http://stackoverflow.com/comment/88552890
type: Answer
accepted answer of: http://stackoverflow.com/q/50767064
answers question: http://stackoverflow.com/q/50767064
has body: try matching your port numbers for client and server. Also, instead of writing req_data= request.get(silent=True) write return jsonify(request.json) and change response = requests.post('http://192.168.37.129:5000/', data=open(msfFile).read()) to response = requests.post('http://192.168.37.129:5000/', json=data)
has comment: http://stackoverflow.com/comment/88556976
type: AcceptedAnswer

http://stackoverflow.com/q/50711082
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50711214
has comment: http://stackoverflow.com/comment/88431222
tagged with: raiserror
score: 0
possible better answer: http://stackoverflow.com/a/50711214
tagged with: exception
accepted answer: http://stackoverflow.com/a/50711147
tagged with: python
has body: So I'm experimenting making my own program. I have the user input a string and an integer (name, age). I want to raise a Value Error if the age is under 1 (if age > 1:) I did that. But I'm not sure what to do if the name is not a string. Is it a TypeError and can two types of errors be raised at the same time? If so how? Probably got some terminology wrong but having trouble thinking right now. Here's the code: # This program asks name how old you are and makes exceptions to check and see if there are errors def hogwarts_express (name, age): if age &lt; 1: raise ValueError ("Error: Apparently you don't exist. Please pick a number older than 0!") if int (age) &gt;= 10: print ("Hello {}! Welcome to the Hogwarts Express, your old enough to go now. Here 's your ticket!".format(name)) else: print ("Sorry {} you're not old enough to board the express.".format(name)) try: your_name = input("What's your name? ") age = int(input("How old might you be? ")) together = hogwarts_express (your_name, age) except ValueError as err: print ("That's not a valid value. Please input something else.") print ("{}".format(err)) else: print (together)
has title: Possible to raise two types of errors?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12826291
has comment: http://stackoverflow.com/comment/88431364
has answer: http://stackoverflow.com/a/50711147

http://stackoverflow.com/a/50804881
upvote count: 9
answers question: http://stackoverflow.com/q/50804826
has body: The constructor says, If there is no instance recorded, create an instance and record it return the recorded instance This is a standard singleton design pattern, for most languages, to ensure that only one instance of the class is ever created.
downvote count: 0
has comment: http://stackoverflow.com/comment/88615929
type: Answer
has comment: http://stackoverflow.com/comment/88615901
has comment: http://stackoverflow.com/comment/88615874
has comment: http://stackoverflow.com/comment/88615923
score: 9

http://stackoverflow.com/comment/88710661
score: 0
type: QuestionComment
type: Comment
has text: @czyzyk14 The machine you are on probably has just enough memory to hold 7.5 millions rows once, but when you make a copy of them in the line where it crashes it runs out. Regardless, your approach will eventually fail anyway if the number of rows increases. For large datasets you should always be chunking everywhere, so that you only keep at most 1000 (or however many) rows in memory at once.
comment on: http://stackoverflow.com/q/50850868

http://stackoverflow.com/q/50759213
has answer: http://stackoverflow.com/a/50759242
has title: Syntax error with '!<' filtering pandas
type: AnsweredQuestion
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/28272137
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50759381
has answer: http://stackoverflow.com/a/50759381
answer count: 2
tagged with: filter
tagged with: pandas
upvote count: 1
accepted answer: http://stackoverflow.com/a/50759242
tagged with: linux
has body: I have a variable called 'Biovolumes_vivo' type float64. I want to filter and remove the values higher than 8192. I've done some research and I found something similar here: Pandas How to filter a Series I modified the script according to my data: Biovolumes_vivo = Biovolumes_vivo[Biovolumes_vivo !&lt; 8192] However, it says 'invalid syntax'. I guees there is something wrong with '!&lt;'. Thanks in advance for the help
tagged with: python

http://stackoverflow.com/a/50821749
accepted answer of: http://stackoverflow.com/q/50742840
answers question: http://stackoverflow.com/q/50742840
type: Answer
upvote count: 1
score: 1
has body: Workaround: Just substitute "GMM" by "GaussianMixture" and "n_iter" by "max_itern": for x in models: bics=[] gmm = mixture.GaussianMixture(n_components=x, max_iter=100000, n_init=5, covariance_type='full') gmm.fit(np.array(s)) bic.append(gmm.bic(np.array(s))) return bic.index(min(bic))+2 Thank you @Vivek Kumar
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50816045
favorite count: 0
tagged with: count
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Count value Pandas and combining with other dataframe
type: Question
has answer: http://stackoverflow.com/a/50816131
accepted answer: http://stackoverflow.com/a/50816131
tagged with: pandas
has body: I have the following dataframes.: ServiceHierarchy id ClientConnectionID SH1 CN01 SH2 CN02 SH3 CN03 ServicePath id SH1 SH1 SH1 SH2 SH2 SH3 SH4 I want to calculate count_value() of each id of ServiceHierarchy in which can be found in ServicePath dataframe and return the list in ServiceHierarchy with the corresponds count of the value. The result would be the following: id ClientConnectionID count SH1 CN01 2 SH2 CN02 6 SH3 CN03 3 I started by data_ServicePath['Id'].value_counts() where it returns only the count values.
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50789464
favorite count: 0
type: UnansweredQuestion
has title: Unable to parse .msg files in for loop using python
tagged with: python
downvote count: 1
type: Question
tagged with: outlook
has body: I'm a newbie to Python programming. I need to automate copying about 450 "msg" files located within multiple sub-directories of a directory in Windows, to other directories based on the content within each "msg" file. I used following code: from shutil import copy2 import win32com.client # Function which returns dictionary with absolute filepaths, file names def list_files(dir): r = {} for root, dirs, files in os.walk(dir): for name in files: r[os.path.join(root, name)]=name return r allFiles = list_files(sourceDir) # Parsing all emails for filename in allFiles.items(): if filename[1].endswith(".msg"): outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") try: email = outlook.OpenSharedItem(filename[0]) emailContent = email.Subject + "\n" + email.Body print(emailContent) except FileNotFoundError as e: print("File Not Found Error: " + str(e)) finally: del email, outlook Further down, I'm going to copy the files based on the content. But many of the filepaths for these emails are longer than 260 characters. So, I'm getting following error: com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The URL was bad/not found:\r\n "C:\\Users\\HPHP\\Documents\\...\\Data\\...\\IHI ...\\......". Cannot find this file. Verify the path and file name are correct.', None, 0, -2147024894), None) If I rename the filename such that the absolute path length reduces below 260 characters, I'm not facing this error. However I need the filenames to be intact. I also tried bypassing the MAX_PATH limitation with following code, which isn't working in this case: email = outlook.OpenSharedItem("\\\\?\\"+filename[0]) I tried another way, to change the current working directory for every iteration. Following is the code: for filename in allFiles.items(): if filename[1].endswith(".msg"): os.chdir(filename[0].replace(filename[1],"")) outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") try: email = outlook.OpenSharedItem(file…
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50789483
answer count: 1

http://stackoverflow.com/comment/88470947
type: AnswerComment
has text: My suggestion is to reformat. Have one column for your string keys, another column for your numeric values. There are many questions on SO on this, but your'e welcome to ask a fresh question for this if you get stuck.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/50731385

http://stackoverflow.com/a/50783481
score: 0
has body: Repeated append() has disastrous performance in Pandas and NumPy. So instead of this: res = pd.DataFrame() while True: df_to_append.set_index('datetime', inplace=True) res = pd.concat([res, df_to_append]) Do this: res = [] while True: res.append(df_to_append) res = pd.concat(res) res.set_index('datetime', inplace=True) You can also simplify things by storing data as a tuple instead of a dict. The keys are the same every time, and if you just ignore them, you can populate res as a list of tuples in the loop, avoiding the construction of many temporary DataFrames and key lookups later on.
type: Answer
answers question: http://stackoverflow.com/q/50783355

http://stackoverflow.com/comment/88535701
type: Comment
type: QuestionComment
has text: You said *each products are uniquely related to Vendor*, then why don't you try a `OnetoOne` relation?
score: 0
comment on: http://stackoverflow.com/q/50763704

http://stackoverflow.com/q/50729248
downvote count: 0
answer count: 1
has title: How to run if-else statement on a loop within a dataframe
score: 1
has comment: http://stackoverflow.com/comment/88466442
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I have a dataframe with a column name1, I want to run an if-else statement to break out the lastname with special character '-' and output them like name2 and name3, how do I do that? import pandas as pd d = { 'name1': ['Braund', 'Cummings-Johnson', 'Heikkinen-Smith'], 'name2': ['Braund', 'Cummings', 'Heikkinen'], 'name3': ['Braund', 'Johnson', 'Smith'] } df = pd.DataFrame(d)
type: Question
has answer: http://stackoverflow.com/a/50752761
tagged with: pandas

http://stackoverflow.com/q/50787037
has answer: http://stackoverflow.com/a/50788948
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: python-dateutil
type: Question
tagged with: rrule
accepted answer: http://stackoverflow.com/a/50788948
downvote count: 0
answer count: 1
has title: Using rrule to assign days to relevant months
tagged with: datetime
favorite count: 0
tagged with: python-3.x
has body: I was able to list the days between two dates using rrule like so: from dateutil import rrule from datetime import datetime a = '20180306' b = '20180506' for dt in rrule.rrule(rrule.DAILY, dtstart = datetime.strptime(a, '%Y%m%d'), until = datetime.strptime(b, '%Y%m%d')): print (dt.strftime('%Y%m%d')) the output given is: 20180306 20180307 ... 20180408 20180409 ... 20180506 How can I go about assigning these days to their relevant months to give an output of: March-18: 26 days April-18: 30 days May-18: 6 days I am also curious about how to extend this to include hours in the calculation ie. March-18: 11.9 days Thanks black.mamba

http://stackoverflow.com/q/50709402
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50710279
has title: How do I work with Javascript Object Literals in Python
has comment: http://stackoverflow.com/comment/88427976
has body: Through Beautifulsoup module I have extracted an HTML page. From that page, I further extracted a Javascript script tag. Inside the script tag, there is an object literal that I would like to work with. You can see what I would like to achieve: &lt;script&gt; var main_obj = { "link":"", "stock":"", "price":[{"qty":1000,"value":"100$"}, {"qty":10000,"value":"1000$"}] } &lt;/script&gt; I would like to access the qty and value variables inside the object literals of price variable which is inside main_obj. Thankyou
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88428003
accepted answer: http://stackoverflow.com/a/50710279
type: Question
tagged with: javascript
answer count: 1
has comment: http://stackoverflow.com/comment/88428061

http://stackoverflow.com/comment/88709809
comment on: http://stackoverflow.com/a/50818607
type: Comment
has text: Would it be possible for you to post the code that you are trying to run? Maybe someone a bit more experienced than I could help then. :)
score: 0
type: AnswerComment

http://stackoverflow.com/q/50840025
tagged with: python
linked to: http://stackoverflow.com/q/42350118
tagged with: amazon-cognito
has title: Access authorizer from an AWS lambda function with proxy integration - Python
answer count: 0
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/88684087
linked to: http://stackoverflow.com/q/43990385
tagged with: aws-api-gateway
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88684172
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
has body: [Derived from AWS ApiGateway Lambda Proxy access Authorizer ] I´m using an Lambda Proxy and a Cognito User Pool Authorizer in my ApiGateway. With node.js Lambda functions, it's possible access to have access to the authorizer (basically, get the user id, email and stuff) in event.requestContext.authorizer.claims. But in Python, there's no such object. Exploring the event object and the context object shows there's nothing like requestContext or authorizer, just an identity object that contains Cognito Federated Identities information : for me, it's just null. I haven't seen any mention of the event.requestContext.authorizr.claims in Python AWS-Lambda functions, and it would be a pain to use federated identities instead in API Gateway, set Authorization to AWS_IAM and turn on Invoke with caller credential drop the proxy integration for a custom integration or write the lambdas with node.js instead of python Have you any idea if I'm missing something, if it's not implemented by AWS, if there's an easy workaround, or anything else ? Thanks a lot for your help ! Here's the context object in python aws-lambda function, in a dictionary-like form : "aws_request_id":"99XXXXf5-6XXe-1XX8-bXXf-5dXXXXXXXX50", "function_name":"test_DynamoDB", "function_version":"$LATEST", "invoked_function_arn":"arn:aws:lambda:eu-west-3:4XXXXXXXXXX0:function:test_DynamoDB", "log":"&lt;bound method LambdaContext.log of &lt;__main__.LambdaContext object at 0x7f07bcb21da0&gt;&gt;", "log_group_name":"/aws/lambda/test_DynamoDB", "log_stream_name":"2018/06/13/[$LATEST]76XXXXXXXXXXXXXXXXXXXXXXXXXXXXf0", "memory_limit_in_mb":"128", "identity":{ "cognito_identity_id":null, "cognito_identity_pool_id":null }, "client_context": None Update From https://stackoverflow.com/a/44039371/9936457 , it seems the same issue was in C# lambda functions and there's a workaround for it, using System.IO.Streams. Would this solution work in Python, with the right syntax ?
type: UnansweredQuestion

http://stackoverflow.com/q/50819576
has answer: http://stackoverflow.com/a/50832530
has comment: http://stackoverflow.com/comment/88645241
type: UnansweredQuestion
tagged with: python
tagged with: pass-by-reference
has comment: http://stackoverflow.com/comment/88645083
score: 3
has comment: http://stackoverflow.com/comment/88648266
upvote count: 3
linked to: http://stackoverflow.com/q/50003760
linked to: http://stackoverflow.com/q/50325050
has comment: http://stackoverflow.com/comment/88649721
type: Question
linked to: http://stackoverflow.com/q/49962265
tagged with: ctypes
tagged with: dll
downvote count: 0
has title: Python passing user-defined class by reference to DLLs
linked to: http://stackoverflow.com/q/50447199
has body: I am currently working on a project that requires to access functions in DLLs, and I found ctypes to handle the function call for me. However, I encounter some difficulties when some functions ask to pass parameters by reference. I've tried the ctypes.by_ref() but it doesn't work because the object is a user-defined class. And then I gave ctypes.pointer() a try and it spits out the error message: "type must have storage info". I guess that means it only takes ctypes data types? My code: from ctypes import * class myclass(): a= None # requiring c_int32 b= None # requiring c_int32 myci= myclass() myci.a= c_int32(255) myci.b= c_int32(0) mycip= pointer(myci) # let's say it's Line 8 here loadso= cdll.LoadLibrary(mydll) Result= loadso.thefunction (mycip) # int thefunction(ref myclass) And the terminal output: Line 8: TypeError: _type_ must have storage info I would like to know 1) what does that error message mean? and 2) the way to work around and pass a user-defined class by reference to an external DLL. Thank you in advance for your time.
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50731954
type: Question
has comment: http://stackoverflow.com/comment/88495048
has body: I wrote a small program to type in inputs on the social security quick calculator website using Selenium with chrome driver. At the beginning it always worked. However today when my Selenium program click this submit button: original web https://www.ssa.gov/oact/quickcalc/ I got this error page: While I am supposed to get: This can be given if I manually click on the submit button Could anyone tell me what is going on here?
has comment: http://stackoverflow.com/comment/88473374
linked to: http://stackoverflow.com/q/33225947
has comment: http://stackoverflow.com/comment/88472015
has title: Selenium seems to be blacklisted
tagged with: web
has comment: http://stackoverflow.com/comment/88480705
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/88495165
tagged with: python
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/88495143
answer count: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/50744170
has comment: http://stackoverflow.com/comment/88496098
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88496617
tagged with: django
upvote count: 1
tagged with: python
has title: Django : Object didn't load in HTML template
score: 1
type: Question
has body: I'm making my Django website and I'm getting an issue according to my first website template (my homepage). Environment : Django 2.0.1 Python 3.5 MariaDB 10.1 Issue : When I can access to my Django Homepage, it should display an image, according to my view but I get nothing. I get my picture only if I go somewhere else and I come back to the homepage. My code : My models.py class Photo(models.Model) : Nom = models.CharField(max_length=50, verbose_name="Nom de l'objet", blank=False) Date = models.DateField() ... Image_upload = models.ImageField(upload_to='Media/', width_field=None, height_field=None, verbose_name="Image") My views.py : from django.shortcuts import render from Photographies.models import Photo def Accueil(request): photo = Photo.objects.all().order_by('-Date')[0] return render(request, 'Accueil.html', {"photo": photo}) My HTML template : {% extends 'Base_Accueil.html' %} {% load staticfiles %} {% load static %} {% block content %} Petit mot de l'Astrophotographe & Développeur du site Je vous souhaite la bienvenue sur mon site dédié à l'Astrophotographie. A travers votre parcours sur celui-ci, vous allez découvrir ma passion pour la photographie des objets de l'Univers. Du Soleil, notre étoile, aux galaxies les plus lointaines en passant par les vastes amas de gaz qui composent l'infiniment grand, vous allez pouvoir contempler des objets atypiques de part leurs formes et leurs couleurs. C'est avec plaisir que je vous invite à vous ballader sur mon site, découvrir ma galerie d'images, mes bricolages, mes articles & publications, ... Vous trouverez également le matériel astronomique employé pour la réalisation des différents clichés disponibles sur ce site ainsi que diverses informations complémentaires. N'hésitez pas à partager vos avis et à venir le visiter régulièrement pour entrevoir les nouvelles images astrophotographiques. Je vous souhaite une bonne visite ! Dernière image publiée {{photo.Nom}} ({{photo.Designation}}) {% endblock content %} And fi…
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50744646
has comment: http://stackoverflow.com/comment/88496353

http://stackoverflow.com/comment/123745499
score: 0
type: Comment
has text: I do not understand why this question was closed and directed to a question that is not helpful, get_array is specific to the Flask-excel package and is only available if you have installed it
type: QuestionComment
comment on: http://stackoverflow.com/q/50701892

http://stackoverflow.com/q/50788102
has answer: http://stackoverflow.com/a/50788157
type: AnsweredQuestion
has title: python: assign value to a variable whose name is stored in a variable
downvote count: 3
has comment: http://stackoverflow.com/comment/88582546
upvote count: 1
type: Question
score: -2
tagged with: variables
accepted answer: http://stackoverflow.com/a/50788157
answer count: 1
favorite count: 0
tagged with: assign
has body: Maybe this question is very simple to answer, but after a long time of search in the internet I found badly no answer/workaround: In Python (v3) I would like to do the following: def func(): pass foo = "bar" # Now I would like to make an assignment to a variable named # based on the value of foo (i.e. effectively bar = func, but using foo) # so that: bar() == func() # is True bar is func # is also True How can I go about that? Thank you!
has comment: http://stackoverflow.com/comment/88583649
has comment: http://stackoverflow.com/comment/88582595
tagged with: python

http://stackoverflow.com/comment/88674356
has text: yep,it's worth giving a try.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50823832

http://stackoverflow.com/a/50767422
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: You have a couple of options. file.read() reads the entire file file.read(size) reads size amount of data (character for text mode, byte for binary mode) file.readlines() list(file) for line in file: all provide ways to read the whole file file.readline() returns a single line at a time (read until newline char (\n) or end of file (EOF)) check here for documentation.
answers question: http://stackoverflow.com/q/50767236

http://stackoverflow.com/comment/88681915
type: QuestionComment
has text: You could try pyspark.sql.functions.get_json_object which will parse the txt column and create one column per field with associated values
score: 0
comment on: http://stackoverflow.com/q/50838620
type: Comment

http://stackoverflow.com/comment/88529606
comment on: http://stackoverflow.com/a/50756728
score: 0
type: AnswerComment
has text: you also said "The 'Date' is dataframe's index.name" - how can you tell this?
type: Comment

http://stackoverflow.com/comment/88521345
comment on: http://stackoverflow.com/q/50756288
type: Comment
has text: Dear Mathieu, I thought so. Comming form years of Matlab, my brain is still wired the " wrong" way. The intention of the whole post is a bit to rewire my brain :-) Thanks
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88611699
type: Comment
comment on: http://stackoverflow.com/a/50796539
score: 0
type: AnswerComment
has text: I understood, but same error when i try the code given by you.

http://stackoverflow.com/a/50814863
has comment: http://stackoverflow.com/comment/88635954
has comment: http://stackoverflow.com/comment/88639391
has comment: http://stackoverflow.com/comment/88641982
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50814482
upvote count: 2
answers question: http://stackoverflow.com/q/50814482
has body: data = {'xG_Team1': {0: 1.440539, 1: 2.123673, 2: 1.819697, 3: 1.132676, 4: 1.244837}, 'xG_Team2': {0: 1.380095, 1: 0.946116, 2: 0.92166, 3: 1.375717, 4: 1.269933}} df = pd.DataFrame(data) x1 = [1,0,0] x2 = [0,1,0] x3 = [0,0,1] # Constants total_timeslot = 180 k = 180 # Measures Home_Goal = [] # No Goal Away_Goal = [] # No Goal def sum_squared_diff(x1, x2, x3, y): ssd = [] for k in range(total_timeslot): # k will take multiple values if k in Home_Goal: ssd.append(sum((x2 - y) ** 2)) elif k in Away_Goal: ssd.append(sum((x3 - y) ** 2)) else: ssd.append(sum((x1 - y) ** 2)) return ssd def my_function(row): xG_Team1 = row.xG_Team1 xG_Team2 = row.xG_Team2 return np.array([1-(xG_Team1 + xG_Team2)/k, xG_Team1/k, xG_Team2/k]) # You can use the apply function results = df.apply(lambda row: sum_squared_diff(x1, x2, x3, my_function(row)), axis=1) # Each item in results is a 180 item list results Out[]: 0 [0.0003683886105401867, 0.0003683886105401867,... 1 [0.0004576767592872215, 0.0004576767592872215,... 2 [0.00036036396694006056, 0.0003603639669400605... 3 [0.00029220949467635905, 0.0002922094946763590... 4 [0.00029279065228265494, 0.0002927906522826549... # For each list, calculate the sum results.map(lambda x: sum(x)) Out[]: 0 0.066310 1 0.082382 2 0.064866 3 0.052598 4 0.052702 # Get the sum of all these values results.map(lambda x: sum(x)).sum() Out[]: 0.3188573070707662
type: Answer
has comment: http://stackoverflow.com/comment/88638318
score: 2
has comment: http://stackoverflow.com/comment/88641917
has comment: http://stackoverflow.com/comment/88640195

http://stackoverflow.com/comment/88545307
score: 0
has text: You are correct, I am somehow leaving unnecessary \n's in the file, investigating. Thank you for the lead
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50768826

http://stackoverflow.com/q/50738536
has answer: http://stackoverflow.com/a/50746897
type: Question
tagged with: firebase
has title: how to update firestore from python appengine
has body: I want to update firestore from appengine python . Is there any library in python to this ? I am trying with firebase-admin but I am getting import errors . How can use firebase-admin in python appengine ?
answer count: 1
score: 0
tagged with: google-app-engine
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/88657131
type: QuestionComment
comment on: http://stackoverflow.com/q/50826140
type: Comment
score: 2
has text: Use `x==0` instead of `x is 0`

http://stackoverflow.com/comment/88634168
score: 1
has text: @Rovanion You can use `type()` if you want the other behaviour, e.g. `type(collections.OrderedDict()) in {list, dict, set}` >>> `False`
type: AnswerComment
comment on: http://stackoverflow.com/a/50812967
type: Comment

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/50768023
tags question: http://stackoverflow.com/q/50816996
type: Tag

sicp
tag name: sicp
type: Tag
tags question: http://stackoverflow.com/q/50769327

http://stackoverflow.com/comment/88683553
type: Comment
comment on: http://stackoverflow.com/q/50839884
type: QuestionComment
has text: are they strings? Is this what you want `df[df['id_original'].isin(['Classtype1'])]`?
score: 0

http://stackoverflow.com/comment/88455030
comment on: http://stackoverflow.com/a/50722808
type: Comment
has text: for 1. question i edit the answer, for 2. no magic: learn python in the online course, read django documentation, read the code of the projects in the github
score: 0
type: AnswerComment

http://stackoverflow.com/q/50845282
favorite count: 0
tagged with: parsing
accepted answer: http://stackoverflow.com/a/50845383
has comment: http://stackoverflow.com/comment/88695671
tagged with: python
has body: Here's what I would have, I would have a massive text file of a bunch of dna bases (A, T, C, G) and what I would like to do is take every 60 characters (arbitrary) and put it on a new line so that way the bases get separated out in chunks. But, I would also like for there to be overlap of each chunk by a certain number of bases. For example, if this 10 letter chunk ATGGCTGCTA was given, and the initial 4 block chunk was ATGG, if there overlap parameter was specified to be 2, then the next 4 block chunk would be GGCT, then CTGC and so on. I know I'll probably have to look into reading, opening, and writing text files with python. If any has resources they could point me torwards on achieving this and any tips and instructions that would be great. Example of the formatting of the text I would be working with: https://www.ncbi.nlm.nih.gov/nuccore/NC_000017.11?report=fasta&amp;from=7661779&amp;to=7687550
type: AnsweredQuestion
score: 0
upvote count: 1
tagged with: formatting
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88694249
has answer: http://stackoverflow.com/a/50845383
has title: How would I go about parsing a text file of thousands of DNA bases?
has comment: http://stackoverflow.com/comment/88694671
answer count: 1

http://stackoverflow.com/comment/88795562
type: Comment
comment on: http://stackoverflow.com/q/50826831
has text: Thank you for helping, I got it now!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88616334
type: Comment
type: QuestionComment
has text: @KlausD. So would you recommend having to separate python scripts running, in order to accomplish the task? One handling the web interface, and one handling all the logging and measuring tasks?
score: 0
comment on: http://stackoverflow.com/q/50804420

http://stackoverflow.com/comment/88700179
has text: The best way to receive messages as they arrive is via the webhook. Otherwise you can request them from the API as Timm has posted below.
comment on: http://stackoverflow.com/q/50779240
score: 0
type: Comment
type: QuestionComment

firebase
tags question: http://stackoverflow.com/q/50738536
tags question: http://stackoverflow.com/q/50759310
tags question: http://stackoverflow.com/q/50789210
type: Tag
tag name: firebase

http://stackoverflow.com/a/50820252
answers question: http://stackoverflow.com/q/50820074
score: 0
type: Answer
has body: You have to transform your code into something like this: def main(a,b): def ex(a,b): return a+b return ex(a,b) if __name__ == "__main__": main() to elaborate something like this would happen: import script script.main(1,2) The problem is that ex() is defined under the scope of the main function. You won't be able to access it from the outside directly.

http://stackoverflow.com/q/50713316
type: UnansweredQuestion
tagged with: pip
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question
has body: My pip package is broken inside a virtual environment. I tried to uninstall pip using pip uninstall pip. But it listed all my pip packages which are under the python folder whose path is set in the environment variables. So how do I uninstall pip package specific to a virtualenv? I am using Windows Machine.
has comment: http://stackoverflow.com/comment/88435554
has comment: http://stackoverflow.com/comment/88436472
has comment: http://stackoverflow.com/comment/88435460
has comment: http://stackoverflow.com/comment/88435574
tagged with: virtualenv
has title: Uninstall pip inside a virtual environment
tagged with: python-2.7
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50840450
answer count: 1
linked to: http://stackoverflow.com/q/50657788
has answer: http://stackoverflow.com/a/50854327
accepted answer: http://stackoverflow.com/a/50854327
tagged with: trading
tagged with: python
has body: I'm trying to use algo-trading as described in this tutorial: https://www.oreilly.com/learning/algorithmic-trading-in-less-than-100-lines-of-python-code class MomentumTrader(opy.Streamer): def __init__(self, momentum, *args, **kwargs): opy.Streamer.__init__(self, *args, **kwargs) self.ticks = 0 self.position = 0 self.df = pd.DataFrame() self.momentum = momentum self.units = 100000 def create_order(self, side, units): order = oanda.create_order(config["oanda"]["account_id"], instrument="EUR_USD", units=units, side=side, type="market") print("\n", order) def on_success(self, data): self.ticks += 1 # print(self.ticks, end=", ") # appends the new tick data to the DataFrame object self.df = self.df.append(pd.DataFrame(data["tick"], index=[data["tick"]["time"]])) # transforms the time information to a DatetimeIndex object self.df.index = pd.DatetimeIndex(self.df["time"]) # resamples the data set to a new, homogeneous interval dfr = self.df.resample("5s").last() # calculates the log returns dfr["returns"] = np.log(dfr["ask"] / dfr["ask"].shift(1)) # derives the positioning according to the momentum strategy dfr["position"] = np.sign(dfr["returns"].rolling( self.momentum).mean()) if dfr["position"].ix[-1] == 1: # go long if self.position == 0: self.create_order("buy", self.units) elif self.position == -1: self.create_order("buy", self.units * 2) self.position = 1 elif dfr["position"].ix[-1] == -1: # go short if self.position == 0: self.create_order("sell", self.units) elif self.position == 1: self.create_order("sell", self.units * 2) self.position = -1 if self.ticks == 250: # close out the position if self.position == 1: self.create_order("sell", self.units) elif self.position == -1: self.create_order("buy", self.units) self.disconnect() mt = MomentumTrader(momentum=12, environment="practice", access_token=config["oanda"]["access_token"]) mt.rates(account_id=config["oanda"]["account_id"], instruments=["DE30_EUR"], ignore_heartbeat=True) And I'm getting this error: JSONDecod…
type: AnsweredQuestion
type: Question
has title: Oandapy: Expecting property name enclosed in double quotes
tagged with: algorithmic-trading
score: 0

http://stackoverflow.com/q/50792759
type: Question
tagged with: django-admin
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88592807
accepted answer: http://stackoverflow.com/a/50792971
answer count: 1
linked to: http://stackoverflow.com/q/4014914
has comment: http://stackoverflow.com/comment/88595216
tagged with: django-templates
has answer: http://stackoverflow.com/a/50792971
upvote count: 2
has comment: http://stackoverflow.com/comment/88594642
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
has body: My env is: Django 2.0.6, Python 3.6.4 I have standard Django Admin (with inline edit): How to add background color for each row in list view, when object has field is_active_city=True? For example, background-color: green; for is_active_city=True, like this:
has title: Django Admin. How to add background color for each row in list view, when object has boolean field == True?

http://stackoverflow.com/q/50820043
type: AnsweredQuestion
downvote count: 0
tagged with: axis-labels
has comment: http://stackoverflow.com/comment/116783746
has answer: http://stackoverflow.com/a/50832331
favorite count: 0
accepted answer: http://stackoverflow.com/a/50820720
upvote count: 8
type: Question
tagged with: pandas
tagged with: python
tagged with: python-3.x
answer count: 3
linked to: http://stackoverflow.com/q/12608788
possible better answer: http://stackoverflow.com/a/50820497
has answer: http://stackoverflow.com/a/50820720
has answer: http://stackoverflow.com/a/50820497
tagged with: matplotlib
linked to: http://stackoverflow.com/q/43727278
has title: Hiding xticks labels every n-th label or on value on Pandas plot / make x-axis readable
has body: The question is pretty long because of the pictures, but there isn't much content in reality. Question at the bottom. Hi, I have a series of 30000 samples of ages ranging from 21 to 74. Series head: 0 24 1 26 2 34 3 37 4 57 Name: AGE, dtype: int64 I plot it using built-in Pandas feature .plot: age_series = original_df['AGE'] fig = plt.figure() fig.suptitle('Age distribution') age_series.value_counts().sort_index().plot(kind='bar') My problem is that it makes the x-axis not really user-friendly: I could increase the horizontal width between bars, but I don't want to do that. Instead, I'd like to make only a subset of the x-axis labels visible. I tried using MaxNLocator and MultipleLocator adding this line: plt.gca().xaxis.set_major_locator(plt.MaxNLocator(10)) However, it doesn't achieve my goals, as it now incorrectly labels bars and removes ticks (which I understand since using these functions change the xticks object): An ugly solution is to loop within the xticks object: xticks = plt.gca().xaxis.get_major_ticks() for i in range(len(xticks)): if i % 10 != 0: xticks[i].set_visible(False) Allowing this render, which is close to what I want: I'm not satisfied however, as the loop is too naive. I'd like to be able to access values from the xticks (the label) and make a decision upon it, to be able to show only multiple of 10 labels. This works (based upon this answer): for i, l in enumerate(labels): val = int(l.get_text()) if val % 10 != 0: labels[i] = '' plt.gca().set_xticklabels(labels) Question: Is there any different solution, which feels more Pythonic/efficient ? Or do you have suggestions on how to make this data readable ?
score: 8

http://stackoverflow.com/a/51756462
has comment: http://stackoverflow.com/comment/90477522
has comment: http://stackoverflow.com/comment/103404482
has comment: http://stackoverflow.com/comment/106556730
upvote count: 74
has comment: http://stackoverflow.com/comment/94061454
has body: Vaibhav is right. You can experiment with the different morphological transforms to extract or group pixels into different shapes, lines, etc. For example, the approach can be the following: Start from the Dilation to convert the text into the solid spots. Then apply the findContours function as a next step to find text bounding boxes. After having the text bounding boxes it is possible to apply some heuristics algorithm to cluster the text boxes into groups by their coordinates. This way you can find a groups of text areas aligned into rows and columns. Then you can apply sorting by x and y coordinates and/or some analysis to the groups to try to find if the grouped text boxes can form a table. I wrote a small sample illustrating the idea. I hope the code is self explanatory. I've put some comments there too. import os import cv2 import imutils # This only works if there's only one table on a page # Important parameters: # - morph_size # - min_text_height_limit # - max_text_height_limit # - cell_threshold # - min_columns def pre_process_image(img, save_in_file, morph_size=(8, 8)): # get rid of the color pre = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Otsu threshold pre = cv2.threshold(pre, 250, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # dilate the text to make it solid spot cpy = pre.copy() struct = cv2.getStructuringElement(cv2.MORPH_RECT, morph_size) cpy = cv2.dilate(~cpy, struct, anchor=(-1, -1), iterations=1) pre = ~cpy if save_in_file is not None: cv2.imwrite(save_in_file, pre) return pre def find_text_boxes(pre, min_text_height_limit=6, max_text_height_limit=40): # Looking for the text spots contours # OpenCV 3 # img, contours, hierarchy = cv2.findContours(pre, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # OpenCV 4 contours, hierarchy = cv2.findContours(pre, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Getting the texts bounding boxes based on the text size assumptions boxes = [] for contour in contours: box = cv2.boundingRect(contour) h = box[3] if min_text_heigh…
type: Answer
has comment: http://stackoverflow.com/comment/104547439
has comment: http://stackoverflow.com/comment/101580995
has comment: http://stackoverflow.com/comment/106571634
downvote count: 0
has comment: http://stackoverflow.com/comment/131725100
answers question: http://stackoverflow.com/q/50829874
has comment: http://stackoverflow.com/comment/107723132
has comment: http://stackoverflow.com/comment/120415835
has comment: http://stackoverflow.com/comment/100798744
has comment: http://stackoverflow.com/comment/103196795
accepted answer of: http://stackoverflow.com/q/50829874
has comment: http://stackoverflow.com/comment/93969726
has comment: http://stackoverflow.com/comment/100457767
score: 74
has comment: http://stackoverflow.com/comment/131537768
has comment: http://stackoverflow.com/comment/122062478
has comment: http://stackoverflow.com/comment/101616786
has comment: http://stackoverflow.com/comment/131726320
has comment: http://stackoverflow.com/comment/95587852
has comment: http://stackoverflow.com/comment/120311334
has comment: http://stackoverflow.com/comment/104315838
has comment: http://stackoverflow.com/comment/103241639
has comment: http://stackoverflow.com/comment/122029314
has comment: http://stackoverflow.com/comment/95106993
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/101601588

http://stackoverflow.com/comment/88689278
comment on: http://stackoverflow.com/q/50842831
score: 0
type: Comment
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. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.

http://stackoverflow.com/q/50814814
has answer: http://stackoverflow.com/a/50816447
has title: Calling a variable value from another script's class's functions
has comment: http://stackoverflow.com/comment/88634736
upvote count: 1
downvote count: 1
type: Question
tagged with: function
tagged with: variables
has answer: http://stackoverflow.com/a/50815390
accepted answer: http://stackoverflow.com/a/50816447
tagged with: class
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50815390
favorite count: 0
has comment: http://stackoverflow.com/comment/88635690
has body: I need help! I was trying to mod a game BombSquad and was trying to build a banning system for my server. okay so there is a funtion that denies people to enter def onPlayerRequest(self, player): """ Called when a new bs.Player wants to join; should return True or False to accept/reject. """ # limit player counts based on pro purchase/etc *unless* we're in a stress test if bsUtils._gStressTestResetTimer is None: if len(self.players) &gt;= self._maxPlayers: # print a rejection message *only* to the client trying to joinz # (prevents spamming everyone else in the game) bs.playSound(bs.getSound('error')) bs.screenMessage(bs.Lstr(resource='playerLimitReachedText', subs=[('${COUNT}', bsInternal._getAccountDisplayString())]), color=(0.8, 0.0, 0.0), clients=[player.getInputDevice().getClientID()], transient=True) return False bs.playSound(bs.getSound('dripity')) return True I need the player name from another file, and I will put it in the if statement to check if it matches the banlist and done! The files that brings out the player name is class DamnPartyWindow(PartyWindow): def _onPartyMemberPress(self, clientID, isHost, widget): # if we're the host, pop up 'kick' options for all non-host members if bsInternal._getForegroundHostSession() is not None: kickStr = bs.Lstr(resource='kickText') else: # kick-votes appeared in build 14248 if bsInternal._getConnectionToHostInfo().get('buildNumber', 0) &lt; 14248: return kickStr = bs.Lstr(resource='kickVoteText') for rst in self._roster: cid = rst['clientID'] if cid == clientID: bs.screenMessage(rst['displayString']) break p = PopupMenuWindow(position=widget.getScreenSpaceCenter(), scale=2.3 if gSmallUI else 1.65 if gMedUI else 1.23, choices=['kick'], choicesDisplay=[kickStr], currentChoice='kick', delegate=self).getRootWidget() self._popupPartyMemberClientID = clientID self._popupPartyMemberIsHost = isHost (This is a mod by another guy) I need the value of rst['displayString'] and check it in first sample... HELP! I tried putting…
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88713698
type: AnswerComment
type: Comment
has text: Noted, will consider posting a new question
score: 1
comment on: http://stackoverflow.com/a/50834879

http://stackoverflow.com/a/50756175
score: 0
type: Answer
has body: The issue may be that you have duplicate records in your file and when you load the data into a dict the keys are colliding causing a portion of them to be dropped. Instead of storing the data in a dict, store it in a list instead: import json with open('data.json') as json_file: lines = json_file.readlines() records = list(map(json.loads, lines)) You should then be able to iterate through records: print('There are %d records' % len(records)) for record in records: unique = record['payload']['locality'] print(unique)
answers question: http://stackoverflow.com/q/50755977

http://stackoverflow.com/a/50724715
score: 2
answers question: http://stackoverflow.com/q/50723922
accepted answer of: http://stackoverflow.com/q/50723922
downvote count: 0
has body: I could guess that you are using Windows cp1251 encoding. quote_plus uses by default utf_8, but also support any specific one: &gt;&gt;&gt; print(urllib.parse.quote_plus('Астрахань', encoding='cp1251')) %C0%F1%F2%F0%E0%F5%E0%ED%FC
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/a/50701996
type: AcceptedAnswer
has body: You need to use a placeholder try this: cursor.execute("""select name, test_time, id from test_table where test_time &gt; (CURDATE() - INTERVAL {0} day)""".format(date)) or SAFE: cursor.execute("""select name, test_time, id from test_table where test_time &gt; (CURDATE() - INTERVAL %s day)""", (date,))
has comment: http://stackoverflow.com/comment/88413575
has comment: http://stackoverflow.com/comment/88413801
type: Answer
has comment: http://stackoverflow.com/comment/88413401
upvote count: 1
answers question: http://stackoverflow.com/q/50701902
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50701902
score: 0

http://stackoverflow.com/comment/88420997
score: 0
type: Comment
type: QuestionComment
has text: Also, @Everyone, see [here](https://stats.stackexchange.com/questions/172945/rmse-root-mean-squared-error-for-logistic-models/172985#172985) that using accuracy is not necessarily a good way to measure performance.
comment on: http://stackoverflow.com/q/50705532

web-scraping
tags question: http://stackoverflow.com/q/50829622
tags question: http://stackoverflow.com/q/50782619
tags question: http://stackoverflow.com/q/50779567
tags question: http://stackoverflow.com/q/50713919
tags question: http://stackoverflow.com/q/50729310
tags question: http://stackoverflow.com/q/50803265
tags question: http://stackoverflow.com/q/50837504
tags question: http://stackoverflow.com/q/50784660
tags question: http://stackoverflow.com/q/50805949
tags question: http://stackoverflow.com/q/50807518
tags question: http://stackoverflow.com/q/50762583
tags question: http://stackoverflow.com/q/50703550
tags question: http://stackoverflow.com/q/50837030
tags question: http://stackoverflow.com/q/50729897
tags question: http://stackoverflow.com/q/50705252
tags question: http://stackoverflow.com/q/50852786
tags question: http://stackoverflow.com/q/50760322
tags question: http://stackoverflow.com/q/50806104
tags question: http://stackoverflow.com/q/50769439
tags question: http://stackoverflow.com/q/50788131
tags question: http://stackoverflow.com/q/50728690
tags question: http://stackoverflow.com/q/50797349
tags question: http://stackoverflow.com/q/50782666
tags question: http://stackoverflow.com/q/50757380
tags question: http://stackoverflow.com/q/50706832
tags question: http://stackoverflow.com/q/50714354
tags question: http://stackoverflow.com/q/50769809
tags question: http://stackoverflow.com/q/50769931
tags question: http://stackoverflow.com/q/50812070
tags question: http://stackoverflow.com/q/50779879
tags question: http://stackoverflow.com/q/50777076
tags question: http://stackoverflow.com/q/50846570
tags question: http://stackoverflow.com/q/50776702
tags question: http://stackoverflow.com/q/50703723
tags question: http://stackoverflow.com/q/50801360
tags question: http://stackoverflow.com/q/50789155
tags question: http://stackoverflow.com/q/50732935
tags question: http://stackoverflow.com/q/50827458
tags question: http://stackoverflow.com/q/50852617
tags question: http://stackoverflow.com/q/50776071
tags question: http://stackoverflow.com/q/50813906
tags question: http://stackoverflow.com/q/50805089
tags question: http://stackoverflow.com/q/50804359
tags question: http://stackoverflow.com/q/50732023
tags question: http://stackoverflow.com/q/50773194
tags question: http://stackoverflow.com/q/50777226
tags question: http://stackoverflow.com/q/50705909
tags question: http://stackoverflow.com/q/50703203
tags question: http://stackoverflow.com/q/50789473
tags question: http://stackoverflow.com/q/50805355
tag name: web-scraping
tags question: http://stackoverflow.com/q/50731954
tags question: http://stackoverflow.com/q/50700540
tags question: http://stackoverflow.com/q/50721473
tags question: http://stackoverflow.com/q/50759011
tags question: http://stackoverflow.com/q/50830491
tags question: http://stackoverflow.com/q/50716232
tags question: http://stackoverflow.com/q/50715886
type: Tag
tags question: http://stackoverflow.com/q/50707496
tags question: http://stackoverflow.com/q/50763971
tags question: http://stackoverflow.com/q/50753495
tags question: http://stackoverflow.com/q/50738670
tags question: http://stackoverflow.com/q/50831469
tags question: http://stackoverflow.com/q/50796893
tags question: http://stackoverflow.com/q/50841439
tags question: http://stackoverflow.com/q/50815686
tags question: http://stackoverflow.com/q/50733098
tags question: http://stackoverflow.com/q/50817991
tags question: http://stackoverflow.com/q/50850774
tags question: http://stackoverflow.com/q/50775373
tags question: http://stackoverflow.com/q/50845799
tags question: http://stackoverflow.com/q/50804501
tags question: http://stackoverflow.com/q/50808996
tags question: http://stackoverflow.com/q/50750609
tags question: http://stackoverflow.com/q/50777758
tags question: http://stackoverflow.com/q/50780501
tags question: http://stackoverflow.com/q/50751828
tags question: http://stackoverflow.com/q/50745843

http://stackoverflow.com/comment/88552796
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50772694
score: 1
has text: I don't think there is a fixed dictionary limitation size.

http://stackoverflow.com/comment/88620117
comment on: http://stackoverflow.com/q/50807018
type: QuestionComment
type: Comment
score: 1
has text: @jrjames83 i don't think that would work , it would give A as 3 an B as 2 i don't want a duplicate value

http://stackoverflow.com/q/50731649
has comment: http://stackoverflow.com/comment/88471220
has comment: http://stackoverflow.com/comment/88471476
favorite count: 0
has comment: http://stackoverflow.com/comment/88484429
has title: Adding labels to each individual bar
tagged with: seaborn
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43214978
downvote count: 1
type: Question
has body: ax0 = sns.barplot(x='techies', y=df.index, data=df, color = "b", label="techies") Produces this: I want now to place an annotation just to the inside of the end of each bar with a number corresponding to its value. I need therefore (I think) to iterate through each bar, and place an annotation with the correct coordinate offset to get it there. But I cannot figure out how to get there. Update Notice that I am asking about doing this with Seaborn. The linked possible duplicate is with matplotlib which is different. (Thanks @dux and @xg.plt.py)
tagged with: matplotlib
score: -1
tagged with: pandas
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50751274

http://stackoverflow.com/comment/88441162
type: QuestionComment
comment on: http://stackoverflow.com/q/50716232
has text: do you want `print("\t".join(data))`?
score: 0
type: Comment

http://stackoverflow.com/comment/88646113
type: Comment
has text: @jezrael Let me step back a little bit, so I want to make a column that says PSX1:VDD and another that says PSX2:VDD2. Underneath each of those columns I want to create 3 columns that have V, I, P. So is that possible to do or can you not create columns underneath a column?
comment on: http://stackoverflow.com/a/50816852
score: 0
type: AnswerComment

http://stackoverflow.com/a/50823747
has body: Making a 2d array of lists: In [522]: arr = np.empty(6,object) In [523]: arr[:] = [list(range(i,i+3)) for i in range(6)] In [524]: arr = arr.reshape(2,3) In [525]: arr Out[525]: array([[list([0, 1, 2]), list([1, 2, 3]), list([2, 3, 4])], [list([3, 4, 5]), list([4, 5, 6]), list([5, 6, 7])]], dtype=object) It's easier to fill such an array if it is 1d, which is why I start with (6,) and reshape after. Paul Panzer's suggestion: In [526]: np.array(arr.tolist()) Out[526]: array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[3, 4, 5], [4, 5, 6], [5, 6, 7]]]) In [527]: _.reshape(2,-1) Out[527]: array([[0, 1, 2, 1, 2, 3, 2, 3, 4], [3, 4, 5, 4, 5, 6, 5, 6, 7]]) You can also use np.stack (a version of np.concatenate) to create a nd array. It does though, require a 1d object array - hence the ravel: In [536]: np.stack(arr.ravel()) Out[536]: array([[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]) That can be reshaped as needed: In [537]: np.stack(arr.ravel()).reshape(2,-1) Out[537]: array([[0, 1, 2, 1, 2, 3, 2, 3, 4], [3, 4, 5, 4, 5, 6, 5, 6, 7]]) In some cases we need to transpose axes to get the desired order.
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50821376
answers question: http://stackoverflow.com/q/50821376

http://stackoverflow.com/q/50796254
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: ImportError: Numpy when importing pandas in virtual environment
tagged with: anaconda
has body: I am receiving a weird error, which I think is due to different python versions installed on my machine. I used Python 3.7 and Anaconda Python 3.6. In anaconda I set up a virtual environment which has pandas installed as a package. Nevertheless, I cannot load it as there is an error with numpy. I tried instaling/uninstalling the packages many times and also uninstalled and installed anaconda and python, but still the error occours. I am working on windows 10. This is the error Traceback (most recent call last): File "C:/Users/USER/Desktop/test.py", line 1, in &lt;module&gt; import pandas as pd File "C:\Users\USER\AppData\Local\conda\conda\envs\freelancetrade\lib\site-packages\pandas\__init__.py", line 19, in &lt;module&gt; "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] This is the very basic code i am executing: import pandas as pd print("done") As I mentioned I tried different solutions - but nothing helped so far. And also all packages are installed. Any good idea to solve this? Cheers Harry
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88603748
score: 0
tagged with: importerror
tagged with: pandas
has comment: http://stackoverflow.com/comment/88602055

http://stackoverflow.com/comment/88633592
type: QuestionComment
comment on: http://stackoverflow.com/q/50797311
has text: is there a `SetInputConnection` instead of the `SetInputData` in python ? In c++ this avoid some update related troubles.
score: 0
type: Comment

http://stackoverflow.com/comment/117660463
has text: @gdvd If your events happen at predictable times, you don't need the event functionality. Just do your integration up to the time of each event.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50703835

http://stackoverflow.com/a/50789970
has body: You can refer the blog and find how it is done during inference. https://machinelearningmastery.com/develop-encoder-decoder-model-sequence-sequence-prediction-keras/
answers question: http://stackoverflow.com/q/50784540
score: 0
type: Answer

http://stackoverflow.com/q/50792412
has body: so I am working with a friend in developing a robot (using a Raspberry Pi). This robot we are working on will be an autonomous boat. Now, for the Raspberry Pi, the Raspbian image we are using already has ROS (specifically, ROS Kinetic) nicely installed on it, and I have confirmed that ROS is working. For our robot boat, we have different features that we wish to include in it: Getting GPS location Getting audio via hydrophone and processing audio to detect a certain frequency range (ie. I want the boat to detect when a sound of 8500-9000 Hz is clearly heard via the hydrophone) Being able to communicate over XBee So I have used ROS in the past and I am familiar with the concept of publishing and subscribing to topics. However, my friend says that ROS will cause performance issues due to ROS having some "overhead", claiming that ROS will slow down our audio processing or something. Instead, he proposes the following alternative method: Have each of the 3 aspects of our robot (as mentioned above) in different Python files. When the Raspberry Pi starts up, have all of the Python files be run automatically. To pass information to each other (essentially "mimicking" the publishing/subscribing functionality of ROS), the Python files will write to different text files (to "publish" values) and read from those text files (to "subscribe"), and the values that these text files contain will be overwritten on each update of a new value. So... which method of passing information is the better method for our robot? Using ROS Using the aforementioned file writing/reading method proposed by my friend Something else Oh, and other things that I should mention: I know how to use ROS, my friend doesn't My friend has not actually finished writing all the code for doing his file writing/reading idea, whereas ROS is already all setup and good to go on the Raspberry Pi While I could find plenty of sites that list the various advantages of ROS, I could not find anything that compares ROS to …
type: UnansweredQuestion
has title: Using ROS vs other method (see post for more details on this "other method")
has comment: http://stackoverflow.com/comment/88637684
tagged with: python
tagged with: publish-subscribe
type: Question
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/50792760
score: 0
tagged with: robotics
tagged with: ros
answer count: 1

http://stackoverflow.com/comment/97284487
type: AnswerComment
type: Comment
score: 0
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/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#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)
comment on: http://stackoverflow.com/a/55276952

http://stackoverflow.com/q/50711760
score: 0
tagged with: windows
answer count: 1
tagged with: py2exe
type: UnansweredQuestion
tagged with: pyinstaller
has title: PyInstaller modules and DLL missing
tagged with: python
tagged with: exe
has body: My error message doesn't say much, File "C:...\site-packages\PyInstaller\loader\pyimod03_importers.py", line 714, in load_module module = loader.load_module(fullname) importError: dll load failed: the specified module could not be found. So i tried to find some solutions(stackoverflow, google...), and then I downloaded Dependency Walker, and I found many dlls with (red or orange?) boxes, then I supposed it was the missing DLLs, then I copied from system32 all of those red marked DLLs to /python35/Scripts/dist/ and nothing diffent happened. I also tried py2exe, but i just can't download pyobjc from pip or easy-install. Because I think it is not for windows, so I have no ideia... py2exe error message: 5 missing Modules ------------------ ? AppKit imported from keyboard._darwinkeyboard ? Quartz imported from keyboard._darwinkeyboard ? Queue imported from keyboard, keyboard._generic, keyboard._nixcommon ? readline imported from cmd, code, pdb ? tkinter imported from SCRIPT I am using Windows, python35.
type: Question
has answer: http://stackoverflow.com/a/50728551

http://stackoverflow.com/a/50750210
score: 5
type: AcceptedAnswer
has body: You're merely confusing the scope of your subscript variable. Try a more direct approach with the index method: a = [['df','37s',''],['4d','34','jd']] target = '' for lst in a: if target in lst: print(lst.index(target)) Output: 2
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50750120
downvote count: 0
answers question: http://stackoverflow.com/q/50750120

http://stackoverflow.com/comment/88706379
score: 0
type: Comment
type: QuestionComment
has text: It is not clear what your input and desired output are. Also, should the discounts somehow add up or is only the last discount valid?
comment on: http://stackoverflow.com/q/50849592

http://stackoverflow.com/comment/88426878
score: 0
type: Comment
has text: which part of the rules seems prohibitive? you question counts as geodesic, the only change can be is to omit the python and ask about algorithm
type: QuestionComment
comment on: http://stackoverflow.com/q/50705667

http://stackoverflow.com/comment/88456836
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50724049
has text: What is the output you need?
score: 0

http://stackoverflow.com/comment/88582199
type: QuestionComment
comment on: http://stackoverflow.com/q/50787840
score: 0
type: Comment
has text: Not duplicate, please read my edit.

http://stackoverflow.com/comment/88809741
has text: Unfortunately, this isn't working for me as all my images have got the same ID. You mean that it is possible to sort them out using another DICOM tag than Series ID? Will it work in `reader.GetGDCMSeriesFileNames(path, series_id)` if series_id is another DICOM tag ? An other way is maybe to modify the DICOM header to allocate new series ID to my images but I prefer not to if it's possible
comment on: http://stackoverflow.com/a/50824115
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50813430
has comment: http://stackoverflow.com/comment/88643514
tagged with: cgi
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/88639941
has body: I have a python CGI program (says: scrip1), that I am using to set values for some variable for another python CGI script (says: script 2) using web browser. I am using the script 2 to run a Lidar Sensor. The problem is I can set the variable in script 2 using script 1. But script 2 is not executing after receiving variable. Script 2 suppose to start my sensor. Any possible solutions. (I would like to stick on CGI scripts) #script 1 #!/usr/bin/python import os import cgi import cgitb print("Content-Type: text/html\r\n") print("") print''' Form to enter sleep time enter sleep time ''' #### second script is###### #!/usr/bin/python import os import cgi import cgitb import smbus import time print("Content-Type: text/html\r\n") form = cgi.FieldStorage() sleeptime = form.getfirst("sleeptime") #getting value from script 1 (form data) #script to run the Lidar is as follows# bus=smbus.SMBus(1) addr=0x62 while True: bus.write_byte_data(0x62,0x00, 0x04) val_high=bus.read_byte_data(0x62,0x0f) val_low=bus.read_byte_data(0x62,0x10) dist_cm=val_high*256+val_low print (dist_cm , " cm ") time.sleep(sleeptime)
has comment: http://stackoverflow.com/comment/88643608
score: 0
has answer: http://stackoverflow.com/a/50823226
answer count: 1
has comment: http://stackoverflow.com/comment/88642302
has comment: http://stackoverflow.com/comment/88632014
has title: Python CGI to invoke another CGI script that runs a sensor in Raspberry
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88506261
comment on: http://stackoverflow.com/a/50749266
type: AnswerComment
type: Comment
has text: I think it is. I usually stay away from questions like this where OP clearly has not made an effort to make it easy to understand or solve their problem. Either ignore, or in worse cases, vote to close. Saves everyone the headache.
score: 1

http://stackoverflow.com/comment/88630257
score: 0
type: AnswerComment
type: Comment
has text: Hmm, it seems you forget `df = pd.read_html(lines[0])[0]` last `[0]`, also `print type(df)` return `DataFrame` ?
comment on: http://stackoverflow.com/a/50812347

pivot
tags question: http://stackoverflow.com/q/50826832
tags question: http://stackoverflow.com/q/50752534
tag name: pivot
tags question: http://stackoverflow.com/q/50845807
tags question: http://stackoverflow.com/q/50789834
tags question: http://stackoverflow.com/q/50739402
type: Tag

http://stackoverflow.com/a/50838435
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88681115
has comment: http://stackoverflow.com/comment/88681067
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/50838369
answers question: http://stackoverflow.com/q/50838369
has body: Use boolean indexing, filter last 3 by tail and get mean: a = activity_df.loc[activity_df['activities']=='work', 'duration'].tail(3).mean() More general solution is create means by all last 3 rows of activities by GroupBy.tail: s = activity_df.set_index('activities').groupby('activities').tail(3).mean(level=0) print (s) EDIT: np.random.seed(1256) duration = np.random.randint(4, size = 30) activities = ['work', 'home', 'work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home', 'work', 'home'] For your new output need groupby with rolling and aggregate mean: activity_df = pd.DataFrame({'activities':activities, 'duration':duration}) activity_df['roll'] = (activity_df.groupby('activities')['duration'] .rolling(3) .mean() .reset_index(level=0, drop=True)) print (activity_df) activities duration roll 0 work 1 NaN 1 home 2 NaN 2 work 1 NaN 3 home 3 NaN 4 work 0 0.666667 5 home 1 2.000000 6 work 3 1.333333 7 home 0 1.333333 8 work 1 1.333333 9 home 3 1.333333 10 work 1 1.666667 11 home 1 1.333333 12 work 3 1.666667 13 home 2 2.000000 14 work 2 2.000000 15 home 3 2.000000 16 work 0 1.666667 17 home 2 2.333333 18 work 3 1.666667 19 home 0 1.666667 20 work 3 2.000000 21 home 0 0.666667 22 work 1 2.333333 23 home 3 1.000000 24 work 1 1.666667 25 home 2 1.666667 26 work 1 1.000000 27 home 2 2.333333 28 work 2 1.333333 29 home 1 1.666667
has comment: http://stackoverflow.com/comment/88681416

python-xarray
tags question: http://stackoverflow.com/q/50815219
type: Tag
tags question: http://stackoverflow.com/q/50781064
tag name: python-xarray

rss
tags question: http://stackoverflow.com/q/50747606
tag name: rss
type: Tag
tags question: http://stackoverflow.com/q/50844245

http://stackoverflow.com/comment/88618936
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50806403
type: Comment
has text: Use [negative lookarounds](https://www.regular-expressions.info/lookaround.html)

task
type: Tag
tag name: task
tags question: http://stackoverflow.com/q/50775398

http://stackoverflow.com/comment/88520666
score: 0
comment on: http://stackoverflow.com/q/50756446
type: Comment
type: QuestionComment
has text: Seems like an XY problem. Please explain the rationale with a minimal (but complete) example and we may be able to advise a better workflow.

http://stackoverflow.com/a/52194593
has body: Happenned to me today. I solved it by uninstalling python and installing Python x86 in C:\Python\Python37_32 FOR ALL USERS Then I've added C:\Python\Python37_32 and C:\Python\Python37_32\Scripts to the PATH env variable. Then using cmd I installed virtualenv with pip install virtualenv. After that virtualenv worked like a charm. Hope this helps
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50792179
score: 2
upvote count: 2

http://stackoverflow.com/comment/88440032
type: Comment
score: 0
has text: I think the `json.dumps(data)` part takes care of that.
comment on: http://stackoverflow.com/q/50715123
type: QuestionComment

http://stackoverflow.com/comment/88502621
type: AnswerComment
has text: I guess my question is more about passing the string address to any TestCase rather than parsing them. Sorry, if there was confusion
type: Comment
comment on: http://stackoverflow.com/a/50714693
score: 0

http://stackoverflow.com/q/50793976
type: Question
tagged with: raii
has answer: http://stackoverflow.com/a/50798240
score: 5
has comment: http://stackoverflow.com/comment/88610112
linked to: http://stackoverflow.com/q/2321511
has comment: http://stackoverflow.com/comment/88594124
has title: What is the OCaml counterpart to Python's "with"-statement (automatic release of resources)
downvote count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/88596563
has comment: http://stackoverflow.com/comment/88602889
has answer: http://stackoverflow.com/a/50810526
has comment: http://stackoverflow.com/comment/88602674
has comment: http://stackoverflow.com/comment/88602808
has answer: http://stackoverflow.com/a/67607879
favorite count: 0
has comment: http://stackoverflow.com/comment/88594058
tagged with: ocaml
has answer: http://stackoverflow.com/a/50813663
answer count: 5
has comment: http://stackoverflow.com/comment/88635236
has comment: http://stackoverflow.com/comment/88594543
tagged with: python
has comment: http://stackoverflow.com/comment/88602919
has comment: http://stackoverflow.com/comment/88602810
has comment: http://stackoverflow.com/comment/88638041
has body: What is the OCaml counterpart to Python's "with"-statement? with open('test.txt', 'r') as f: # Do stuff with f # At this point, f will always be closed, even in case of exceptions That is: What is the preferred way in OCaml to safely ensure that a certain resource (open file, database connection, HTTP connection, etc.) will always be freed at a certain point in time? Waiting for the garbage collector is no option here, and exceptions should never prevent resources from being freed. Of course, in OCaml you can always use try-finally and close the file "by hand", as you can do in Python. However, that kind of code is prone to errors. This is why Python introduced the "with"-statement. What's the OCaml idiom to make this kind of code easier to read and less prone to errors? Note that this question is very different from the question Emulating try-with-finally in OCaml, as this is one step further: I don't just want to emulate try-finally in OCaml! (where Lwt's [%finally ...] does a fine job, by the way.) I want to get one step further, eliminating the need to write those finally-clauses in the first place - as one can do in Python. Also note that this question is not about implementation details, but about idioms: Which of all possible designs and solutions gained some traction in the OCaml community and is generally accepted?
possible better answer: http://stackoverflow.com/a/50810526
tagged with: with-statement
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50795957
linked to: http://stackoverflow.com/q/11276985
accepted answer: http://stackoverflow.com/a/67607879

http://stackoverflow.com/q/50716935
tagged with: pandas
has answer: http://stackoverflow.com/a/50717219
tagged with: python
has answer: http://stackoverflow.com/a/50717686
favorite count: 0
type: UnansweredQuestion
has title: Finding value in a range in a pandas dataframe
upvote count: 1
has body: I have a dataframe and have a column named BOL. This value is between 2.0 and -2.0. I am trying to find, once BOL value reaches up to 0, if it reaches to 1.0 in 10 rows after current row. And would like to findout in how many rows BOL reaches to 1.0 after it's value 0. Here is the dataframe: import pandas as pd df = pd.DataFrame({'BOL': [-1.21, -1.35, -1.1, -0.84, -0.01, 0.09, -0.45, 0.78, 1.45, 1.78, 0.33, -0.96]})
score: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88443075
downvote count: 0
has comment: http://stackoverflow.com/comment/88442643

http://stackoverflow.com/comment/88642668
type: Comment
comment on: http://stackoverflow.com/q/50818735
score: 0
has text: wouldn't I then have to manually add all of the different variables to this list? - that's what I'm trying to avoid. I've only used three in the example, but there are a lot more in the original code!
type: QuestionComment

http://stackoverflow.com/q/50725284
tagged with: flask
has answer: http://stackoverflow.com/a/50727054
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has title: How to use Flask-Babel in enum?
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50727054
has body: In Jinja templates syntax _() and _l() works. But when I use an Enum the value is not translated. What I have to do? from enum import Enum from flask_babel import _ from flask_babel import lazy_gettext as _l class DFNError(Enum): def __new__(cls, *args, **kwds): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj._value_ = value return obj def __init__(self, code, message, developer_message): self.code = code self.message = message self.developer_message = developer_message UNKNOWN_ERROR_CODE = (name + str(0), _l('Internal Server Error'), _('d'))
tagged with: enums
tagged with: flask-babel
downvote count: 0

dicom
tag name: dicom
type: Tag
tags question: http://stackoverflow.com/q/50815936
tags question: http://stackoverflow.com/q/50814088

http://stackoverflow.com/comment/88573752
comment on: http://stackoverflow.com/a/50783625
type: Comment
has text: if the json is in another file or string format, you'd have to use `json.load(file)` or `json.loads(string)`: something like `import json; json.load("foods.json")`
score: 2
type: AnswerComment

http://stackoverflow.com/a/50786673
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50786362
accepted answer of: http://stackoverflow.com/q/50786362
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88579716
has body: This is a summary of the code from your link: # some import statements class Model(object): def __init__(self, input_dimensions, output_dimensions): # some init statements def train_on_data(self, training_data, training_labels): ''' Multiline comment ''' N = training_labels.size ... In the above code the last line is part of the class, not the train_on_data method. I think the last line (and the others elided) should be indented to be part of that method.

http://stackoverflow.com/comment/88549425
comment on: http://stackoverflow.com/q/50769943
type: Comment
score: 0
has text: check my answer bellow!
type: QuestionComment

http://stackoverflow.com/q/50786727
has comment: http://stackoverflow.com/comment/88580176
has comment: http://stackoverflow.com/comment/88581067
favorite count: 0
type: UnansweredQuestion
has title: Communicating between C# and Python
tagged with: python
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88580797
has answer: http://stackoverflow.com/a/50787075
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/88580308
answer count: 1
has body: I'm having a little bit of a problem with communication between C# and Python. I'm passing some arguments to Python from C# using the following hacky code: string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6); string pyUnintelligibilityPath = "\\unintelligibility.py"; string pyNeuralPredictorPath = "\\predict.py"; string clf = "\\clf.pkl"; public double unintelligibleProbability(string pyLocation, string msg) { FileStream tempMessage = new FileStream(path + "\\tempMessage.txt", FileMode.Create); StreamWriter writer = new StreamWriter(tempMessage); writer.WriteLine(msg); writer.Close(); string args = path + pyUnintelligibilityPath + " " + path + clf + " " + path + "\\tempMessage.txt" + " " + path + "\\tempCoefficient.txt"; ProcessStartInfo start = new ProcessStartInfo(); start.FileName = pyLocation; start.Arguments = args; start.UseShellExecute = false; start.RedirectStandardOutput = false; start.RedirectStandardError = false; Process process = Process.Start(start); Thread.Sleep(5000); double unintelligibility = Convert.ToDouble(File.ReadAllText(path + "\\tempCoefficient.txt").Replace('.', ',')); return unintelligibility; } Unfortunately, this solution is very inefficient in my situation (not even due to the fact that I don't have any code that checks if the file changes as that will be added later and it's not really the problem I'm having). The thing is, the Python code takes a very long time to load the .pkl file before it can actually do anything useful (don't mind the unnecessary imports, I just reused this thing from some other file): from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer, TfidfVectorizer from sklearn.linear_model import LogisticRegression, SGDClassifier from sklearn.svm import LinearSVC from sklearn.cross_validation import cross_val_score from sklearn.pipeline import Pipeline from sklearn.decomposition import NMF, TruncatedSVD from sklearn.ensemble import RandomForestClassifier, Grad…
upvote count: 3
has comment: http://stackoverflow.com/comment/88580060

http://stackoverflow.com/q/50792458
tagged with: airflow
linked to: http://stackoverflow.com/q/50784368
has title: Converting Python file to Airflow DAG
linked to: http://stackoverflow.com/q/41730297
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52537431
has comment: http://stackoverflow.com/comment/88601814
favorite count: 0
has comment: http://stackoverflow.com/comment/88601832
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88593361
has comment: http://stackoverflow.com/comment/88593508
downvote count: 0
has body: I have this Python file: class Get: def __init__(self, i): self.i = get_date(i) self.df = self.get_file() def get_file(self): try: ... return df except Exception as e: return ... def get_date(self,i): dt = datetime.now() - timedelta(days=i) return dt.strftime("%Y-%m-%d") def put(self,df): .... class Fix: def __init__(self,df): .... if __name__ == '__main__': for i in range(4, 0, -1): get = Get(i) fix = Fix(get.df) get.put(fix.df) Basically this code generates 4 last dates and run the functions over these dates (update statistics etc...) At first I wanted to convert each function into a PythonOperator and then schedule it but I don't think this will work. I don't know how to convert the Classes and the parameters that are transferred between them. This is what the code does if I run it on 2018-Jun-12 and below what it should be with Airflow: Is there a template that I can use or any suggestion how to do it?
score: 1
type: Question

http://stackoverflow.com/q/50847721
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88699097
has comment: http://stackoverflow.com/comment/88727525
answer count: 1
has answer: http://stackoverflow.com/a/50847936
type: Question
tagged with: pip
tagged with: python
has title: /anaconda3/bin/python: No module named pip
has body: I tried to run 'python -m pip install "package"' command but it gives me this error: /anaconda3/bin/python: No module named pip I have python2 and python3 installed. Looks like that's messing up everything. And why it is using python in anaconda rather than the default one in /usr/bin/python?
tagged with: anaconda

http://stackoverflow.com/a/50848026
type: Answer
has body: this should work df.loc[:, df.columns[1:]] / 10
answers question: http://stackoverflow.com/q/50847997
score: 0

http://stackoverflow.com/a/50827887
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88691205
has comment: http://stackoverflow.com/comment/119657856
has comment: http://stackoverflow.com/comment/88732475
has body: it will happen because, For security reasons, the value of the secret is changed each time a user logs in. In every Django form, you have a hidden input called "CSRF token" or {% csrf_token %}. This value is randomly and uniquely generated at the time the form rendered and will be compared after the request has been made. So the request can only be sent from the authorized user's browser. There is no way (which I know of) an attacker can get this token and perform the malicious request that can be accepted by Django backend. For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error. When validating the ‘csrfmiddlewaretoken’ field value, only the secret, not the full token, is compared with the secret in the cookie value. This allows the use of ever-changing tokens. While each request may use its own token, the secret remains common to all. This check is done by CsrfViewMiddleware. for more details click here
upvote count: 1
answers question: http://stackoverflow.com/q/50826216
has comment: http://stackoverflow.com/comment/88726106
type: Answer
has comment: http://stackoverflow.com/comment/88686927
has comment: http://stackoverflow.com/comment/88687951

http://stackoverflow.com/q/50789153
score: 0
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
has comment: http://stackoverflow.com/comment/88585522
has comment: http://stackoverflow.com/comment/88603579
linked to: http://stackoverflow.com/q/11779246
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: How can I make a pdf file already existed available to download by users in django?
has body: I'm using django for a small project and I would make users able to download a pdf that's already existed in media/doc/ path so I wrote this code with open('media/doc/document.pdf', 'r',encoding='latin1',errors='replace') as pdf: response = FileResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response but when the pdf file get downloaded it's shown pages empty btw I have already tried utf-8 encoding and doesn't work for me even this doesn't work for me So How can I make pages visible?
type: Question
has comment: http://stackoverflow.com/comment/88590361
has comment: http://stackoverflow.com/comment/88585591
has answer: http://stackoverflow.com/a/50790384
has comment: http://stackoverflow.com/comment/88585238

http://stackoverflow.com/q/50811228
downvote count: 0
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/50811342
type: UnansweredQuestion
tagged with: python
has title: pandas dataframe - two column string match and group
score: 1
upvote count: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/50811562
answer count: 2
tagged with: pandas
has body: I have a pandas dataframe which contains strings in two columns. I want to for each of the columns extract all strings which are similar except the numerical digits and add new columns where the similar text is exchanged against a idx value. From this: Id Name1 Name2 0 Alpha 1 Bravo 3 1 Alpha 2 Alpha 2 2 Bravo 3 Alpha 1 To This: Id Name1 Name2 NewCol1 NewCol2 0 Alpha 1 Bravo 3 1 2 1 Alpha 2 Zero 2 1 3 2 Bravo 3 Alpha 1 2 1 Is there a simple solution to this without a big iteration loop?

http://stackoverflow.com/comment/95628343
score: 0
has text: @blackarcanis this is the [issue tracker](https://issuetracker.google.com/issues/122506827) I post about this problem.
comment on: http://stackoverflow.com/q/50711867
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88618294
score: 1
has text: Which error do you get? Can you provide some HTML? It is too few information now. Can you provide a link?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50806124

http://stackoverflow.com/q/50759310
accepted answer: http://stackoverflow.com/a/50769277
answer count: 1
favorite count: 0
tagged with: python
score: -1
has title: How can use firebase url shortener in python Django?
tagged with: django
has answer: http://stackoverflow.com/a/50769277
tagged with: firebase-dynamic-links
downvote count: 1
tagged with: firebase
type: AnsweredQuestion
has body: Is there any way to use firebase URL shortener(dynamic links) programmatically in Python Django?
type: Question
upvote count: 0

http://stackoverflow.com/q/50750332
downvote count: 1
favorite count: 0
tagged with: yield
has answer: http://stackoverflow.com/a/50750479
tagged with: python
has comment: http://stackoverflow.com/comment/88508725
type: AnsweredQuestion
upvote count: 0
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/50750520
tagged with: if-statement
has title: Conditional Statement Syntax
score: -1
possible better answer: http://stackoverflow.com/a/50750520
accepted answer: http://stackoverflow.com/a/50750479
has body: I'm writing a web crawler at the moment and my Python is rusty as hell, so I'm simply wondering whether or not there is a shorter syntax to accomplish the following... def parse(self, response): prc_path = '//span[@class="result-meta"]/span[@class="result-price"]/text()' sqf_path = '//span[@class="result-meta"]/span[@class="housing"]/text()' loc_path = '//span[@class="result-meta"]/span[@class="result-hood"]/text()' prc_resp = response.xpath(prc_path).extract_first() sqf_resp = response.xpath(sqf_path).extract_first() loc_resp = response.xpath(loc_path).extract_first() if sqf_resp and loc_resp: yield { 'prc': response.xpath(prc_path).extract_first(), 'sqf': response.xpath(sqf_path).extract_first(), 'loc': response.xpath(loc_path).extract_first() } elif sqf_resp: yield { 'prc': response.xpath(prc_path).extract_first(), 'sqf': response.xpath(sqf_path).extract_first() } else: yield { 'prc': response.xpath(prc_path).extract_first(), 'loc': response.xpath(loc_path).extract_first() } As you can see, there is quite a bit of repetition and I'd like to remain as DRY as possible.
answer count: 2

http://stackoverflow.com/q/50851350
tagged with: python
has title: Get printable name of any QKeyEvent key value
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/88707961
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88706883
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/88708191
tagged with: qt
has comment: http://stackoverflow.com/comment/88707636
has answer: http://stackoverflow.com/a/50862318
type: Question
linked to: http://stackoverflow.com/q/21764138
score: 5
tagged with: pyqt
has comment: http://stackoverflow.com/comment/88706401
answer count: 1
has comment: http://stackoverflow.com/comment/88707519
favorite count: 0
has comment: http://stackoverflow.com/comment/88706995
has body: I'm using PyQt5. When I write a keyPressEvent handler, I would like to be able to print, for debugging purposes, a human-readable description of what keys were pressed. I want to be able to print such a thing no matter what, regardless of how many keys were pressed in the event, or whether they were modifiers or "regular" keys. I have seen this previous question in which the accepted answer (using C++) suggests creating a QKeySequence and using its .toString method. I can do this like this: def keyPressEvent(self, event): print("got a key event of ", QKeySequence(event.key()).toString()) However, this does not always work. For instance, if I press the Shift key, it will result in an encoding error when I try to output (or if I try to encode it to UTF-8). This seems to be because QKeySequence does not work on isolated modifier keys: &gt;&gt;&gt; QKeySequence(Qt.Key_Shift).toString().encode('unicode-escape') b'\\u17c0\\udc20' It gives gibberish instead of what I would expect, namely "Shift". It works if I use Qt.SHIFT (sort of, in that it gives "Shift+"), but that is of no use, because Qt.SHIFT is not what I get in event.key() if I press the Shift key. How can I get Qt to give me a printable representation of anything that might ever be the value of event.key(), where event is a QKeyEvent?
has comment: http://stackoverflow.com/comment/88706156
tagged with: keyboard-events
linked to: http://stackoverflow.com/q/8772595

http://stackoverflow.com/q/50719204
favorite count: 0
tagged with: boosting
has comment: http://stackoverflow.com/comment/88567691
tagged with: python
tagged with: multilabel-classification
has comment: http://stackoverflow.com/comment/88566447
accepted answer: http://stackoverflow.com/a/50868039
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50868039
type: Question
score: 10
answer count: 1
upvote count: 10
has body: I train a multi label classification model with XGBBoost and want to code this model in another system. Is it possible to see the text output of my XGBClassifier model as dump_model in XGB Booster. Edit: I found that model._Booster.dump_model(outputfile) returns a dump file as below. However, there is nothing that specifies the class. In my model, there are 10 classes, however in the dumpfile there is only a booster. So, I'm not sure if it's the model of all classes or just one of them. booster[0]: 0:[101&lt;0.142245024] yes=1,no=2,missing=1 1:[107&lt;0.102833837] yes=3,no=4,missing=3 3:[101&lt;0.039123565] yes=7,no=8,missing=7 7:leaf=-0.0142603116 8:leaf=0.023763923 4:[101&lt;0.0646461397] yes=9,no=10,missing=9 9:leaf=-0.0345750563 10:leaf=-0.0135767004 2:[107&lt;0.238691002] yes=5,no=6,missing=5 5:[103&lt;0.0775454491] yes=11,no=12,missing=11 11:leaf=0.188941464 12:leaf=0.0651629418 6:[101&lt;0.999929309] yes=13,no=14,missing=13 13:leaf=0.00403384864 14:leaf=0.236842111 booster[1]: 0:[102&lt;0.014829753] yes=1,no=2,missing=1 1:[102&lt;0.00999682024] yes=3,no=4,missing=3 3:[107&lt;0.0966737345] yes=7,no=8,missing=7 7:leaf=-0.0387153365 8:leaf=-0.0486520194 4:[107&lt;0.0922582299] yes=9,no=10,missing=9 9:leaf=0.0301927216 10:leaf=-0.0284226239 2:[102&lt;0.199759275] yes=5,no=6,missing=5 5:[107&lt;0.12201979] yes=11,no=12,missing=11 11:leaf=0.093562685 12:leaf=0.0127987256 6:[107&lt;0.298737913] yes=13,no=14,missing=13 13:leaf=0.227570012 14:leaf=0.113037519
tagged with: xgboost
has title: Dumping XGBClassifier model into text

http://stackoverflow.com/comment/88580147
type: Comment
type: QuestionComment
has text: A `siamese` newtork?
comment on: http://stackoverflow.com/q/50786427
score: 0

http://stackoverflow.com/a/50796779
type: Answer
accepted answer of: http://stackoverflow.com/q/50796370
has comment: http://stackoverflow.com/comment/88599772
score: 15
has comment: http://stackoverflow.com/comment/88600482
has body: Add __init__.py and use a relative or absolute import in conftest.py: # relative from .config import HOST_URL_DEFAULT, USER, PASSWORD # absolute from tests.config import HOST_URL_DEFAULT, USER, PASSWORD In a package (identified by __init__.py), you need unambiguous import paths. Using unqualified imports (from config import ...) depends on PYTHONPATH or sys.modules including your package root - this is generally not robust and should be avoided as it circumvents the package infrastructure. What you have here (config.py used by other modules) is a package. Treat it as one. pytest does not discourage the use of a test package with an __init__.py! There are veritable use cases for this - such as yours. What pytest does discourage is having a source package and test package in the same source root. However, that means you should move your source package, not your test package! mysource/ # root directory for both mypackage and mytests +- mypackage/ # should be src/mypackage instead! +- __init__.py +- abcd.py +- mytests +- __init__.py +- tests_abcd.py # ``from mypackage import abcd`` imports from source The problem is that running mytests means that mypackage is importable from source as well. That is, your tests are working on your source package, not your installed package. If there are any errors in your installation procedure, testing will not catch it. See the blog linked in the pytest docs for details.
downvote count: 1
upvote count: 16
has comment: http://stackoverflow.com/comment/138851167
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50796370
has comment: http://stackoverflow.com/comment/88599665

http://stackoverflow.com/a/51004661
answers question: http://stackoverflow.com/q/50752532
has body: Took a bit of digging, but I found the answer to this question. Full credit to Craig Glennie who posted the answer in a response to a question elsewhere on Stack Overflow: urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error I didn't realize that the out of the box Python 3.6 installed on OS-X does not have any certificates (as detailed in the ReadMe.rtf file with Python 3.6). Running /Applications/Python\ 3.6/Install\ Certificates.command got everything squared away.
score: 0
type: Answer

http://stackoverflow.com/comment/88556059
has text: Ok but now the backend isn't expecting JSON. Why are you using JSON at all?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50774378

http://stackoverflow.com/q/50832937
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/88669991
has comment: http://stackoverflow.com/comment/88670591
tagged with: python
has answer: http://stackoverflow.com/a/50833798
has body: So I get an a list of list which contain employees info and I want to write it to database. SQLAlchemy documentation says its correct by, now but DB is still empty. Database was created properly, how I can now insert data from employees_list to database ? My code from PyBambooHR import PyBambooHR import sqlalchemy from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base import pprint Base = declarative_base() class EmployeeData(Base): __tablename__ = 'employee_data' id = Column(Integer, primary_key=True) name = Column(String(120)) department = Column(String(120)) jobTitle = Column(String(120)) email = Column(String(120)) engine = sqlalchemy.create_engine('sqlite:///employee_db.db') connection = engine.connect() Base.metadata.create_all(engine) bamboo = PyBambooHR(subdomain='company', api_key='key') employees = bamboo.get_employee_directory() employees_list = [[item['displayName'], item['department'], item['jobTitle'], item['workEmail']] for item in employees] employees_list.sort() connection.execute(employees_list.insert()) connection.close() pprint.pprint(employees_list) causes Traceback (most recent call last): File &quot;...&quot;, line 37, in &lt;module&gt; connection.execute(employees_list.insert()) TypeError: insert() takes exactly 2 arguments (0 given)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88670403
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/88670502
type: Question
accepted answer: http://stackoverflow.com/a/50833798
has comment: http://stackoverflow.com/comment/88670589
has comment: http://stackoverflow.com/comment/88670436
has title: TypeError while INSERT'ing multiple instances into database using SQLAlchemy
has comment: http://stackoverflow.com/comment/88670207
score: 0

http://stackoverflow.com/comment/102271993
comment on: http://stackoverflow.com/q/50815151
has text: I'm confused by what you're actually asking here. Do you want to know how to identify a frame in a window? For what purpose? How are the frames created and why can't you store a reference to them in a variable/list?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50768852
downvote count: 3
score: -1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88545162
has title: python statement with `or` inside square brackets
favorite count: 0
has body: This is a code snippet I pasted from a setup.py python file. I am new to python and don't understand this build_args variable. Could someone give me some explanation for that? build_args = [NINJA or MAKE] # control the number of concurrent jobs if self.jobs is not None: build_args.extend(['-j', str(self.jobs)]) subprocess.check_call(build_args)
has answer: http://stackoverflow.com/a/50769053
has comment: http://stackoverflow.com/comment/88545182
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50768989
tagged with: python

http://stackoverflow.com/comment/88669729
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50812716
type: QuestionComment
has text: After receiving a feedback from the developer of the Plugin I've edited my code following his suggestion to edit the data structure (include a 'fields' key before 'allega_file') but unfortunately I'm having the same issue. https://wordpress.org/support/topic/python-script-fails-posting-some-data/

http://stackoverflow.com/q/50739024
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88519210
has comment: http://stackoverflow.com/comment/88492050
type: Question
tagged with: pdfminer
has title: How to solve this warning in python pdfminer3k?
score: 0
has comment: http://stackoverflow.com/comment/88521233
has comment: http://stackoverflow.com/comment/88488168
has body: When I running these code in python IDLE ,I got this warning ,how to solve this problem? WARNING:root:Cannot locate objid= nnn # -*- coding: utf-8 -*- from pdfminer.pdfinterp import PDFResourceManager, process_pdf from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from io import StringIO from io import open def readPDF(pdfFile): rsrcmgr = PDFResourceManager() retstr = StringIO() laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) process_pdf(rsrcmgr, device, pdfFile) device.close() content = retstr.getvalue() retstr.close() return content def saveTxt(txt): with open("xxx.txt", "w",encoding="utf-8") as f: f.write(txt) txt = readPDF(open('xxx.pdf', 'rb')) saveTxt(txt) When I add STRICT = True into psparser.py and run the program, it returns like that: Traceback (most recent call last): File "F:\Users\IceSun\Documents\py\pdfminer3kTest.py", line 30, in &lt;module&gt; txt = readPDF(pdfAhh) File "F:\Users\IceSun\Documents\py\pdfminer3kTest.py", line 17, in readPDF process_pdf(rsrcmgr, device, pdfFile) File "D:\Program_Files\Python\Python36\lib\site-packages\pdfminer\pdfinterp.py", line 695, in process_pdf doc.set_parser(parser) File "D:\Program_Files\Python\Python36\lib\site-packages\pdfminer\pdfparser.py", line 434, in set_parser self.info.append(dict_value(trailer['Info'])) File "D:\Program_Files\Python\Python36\lib\site-packages\pdfminer\pdftypes.py", line 92, in typecheck_value x = resolve1(x) File "D:\Program_Files\Python\Python36\lib\site-packages\pdfminer\pdftypes.py", line 58, in resolve1 x = x.resolve() File "D:\Program_Files\Python\Python36\lib\site-packages\pdfminer\pdftypes.py", line 47, in resolve return self.doc.getobj(self.objid) File "D:\Program_Files\Python\Python36\lib\site-packages\pdfminer\pdfparser.py", line 532, in getobj result = self._getobj(objid) File "D:\Program_Files\Python\Python36\lib\site-packages\pdfminer\pdfparser.py", line 345, in _getobj handle_error(PDFSyntaxError, 'Cannot loc…
tagged with: python

http://stackoverflow.com/a/50809526
answers question: http://stackoverflow.com/q/50808205
has body: Itertools loves you and wants you to be happy: from itertools import chain, groupby def run_length_encoder(src): return list( # chain.from_iterable flattens the series of tuples we make inside the # loop into a single list. chain.from_iterable( # groupby returns an iterable (item, group) where group is an # iterable that yields a copy of `item` as many times as that item # appears consecutively in the input. Therefore, if you take the # length of `group`, you get the run length of `item`. This # whole expression then returns a series of (letter, count) # tuples. (letter, len(list(group))) for letter, group in groupby(src) ) ) print(run_length_encoder("aajjjjiiiiohhkkkkkkkkhkkkk"))
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/50752200
tagged with: automated-tests
answer count: 1
has comment: http://stackoverflow.com/comment/88514415
type: UnansweredQuestion
tagged with: python
has title: Robot framework expected error failed: IndexError: list index out of range
type: Question
tagged with: robotframework
tagged with: automation
has answer: http://stackoverflow.com/a/50929427
has body: I have a problem with Robot Framework. Currently I do negative testing. I have a JSON response with length of an array 5 data (counting from 0). I want to check if the 6th exists or not. If the 6th data does not exist, the test is passed. Here's my code: ${msg} Run Keyword And Expect Error Resolving variable '${json_response['data'][5]}' failed: IndexError: list index out of range * Log To Console ${json_response['data'][5]} Should Contain ${msg} failed: IndexError: list index out of range The code gives failing results. How can I solve this problem?
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/88580326
has text: Whatever it is the OP is trying to do, multiple calls to awk with pipes, subshells, and unquoted variables is not the right way to do it. Also, @AneeshDurg, wrt your comment you never need grep when you're using awk since `cmd | grep foo | awk 'bar'` = `cmd | awk '/foo/{bar}'`
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50786177

http://stackoverflow.com/comment/113606505
has text: This does not provide an answer to the question. Please open a new post if you have a question.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/64245030
type: Comment

http://stackoverflow.com/comment/88421693
score: 0
has text: Welcome to StackOverflow. However, it is a requirement here that your question be clear and complete. When asked a question in a comment, you should answer it. You now have two questions that you need to answer. Frankly, I do not understand your question either.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50706120

http://stackoverflow.com/q/50704571
duplicate of: http://stackoverflow.com/q/19384532
has title: how to get unique values and its count in python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88419066
has comment: http://stackoverflow.com/comment/88418885
linked to: http://stackoverflow.com/q/19384532
type: Question
has comment: http://stackoverflow.com/comment/88420114
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88418527
tagged with: pandas
has body: I am new to python programming. I want to loop through each user and get unique countries and its counts. Here's the input data i have: df = pd.DataFrame({'User':['101','101','102','102','102'],'Country':['India,Brazil','India','India,Brazil,Japan','India,Brazil','India']}) wanted output here Thanks
tagged with: python

http://stackoverflow.com/q/50733604
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88597801
score: 1
tagged with: sift
has body: I have the following code: import numpy as np import cv2 import csv from matplotlib import pyplot as plt # load image img1 = cv2.imread('/Users/alisa/Desktop/sift.jpg',0) # queryImage img2 = cv2.imread('/Users/alisa/Desktop/siftt.jpg',0) # trainImage # Initiate SIFT detector sift = cv2.xfeatures2d.SIFT_create() # find the keypoints and descriptors with SIFT kp2, des2 = sift.detectAndCompute(img2,None) # read feature from file with open('/Users/alisa/Desktop/q.csv') as csvDataFile: csvReader = csv.reader(csvDataFile) for gr_img1 in csvReader: des1=gr_img1 # Read keypoints from file kp1 = [] lines = [line.strip() for line in open('/Users/alisa/Desktop/ali.txt')] for line in lines: list = line.split(',') kps = cv2.KeyPoint(x=float(list[0]), y=float(list[1]), _size=float(list[2]), _angle=float(list[3]), _response=float(list[4]), _octave=int(list[5]), _class_id=int(list[6])) kp1.append(kps) # create BFMatcher object bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) # Match descriptors. matches = bf.match(des1,des2) # Sort them in the order of their distance. matches = sorted(matches, key = lambda x:x.distance) # Draw first 10 matches. img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10],None, flags=2) plt.imshow(img3),plt.show() However, i get the following: TypeError: query Descriptors is not a numpy array, neither a scalar. Can someone help me with this error?
has comment: http://stackoverflow.com/comment/88597793
upvote count: 1
has comment: http://stackoverflow.com/comment/88484118
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/88477230
has comment: http://stackoverflow.com/comment/88481278
downvote count: 0
answer count: 1
has title: TypeError: query Descriptors is not a numpy array, neither a scalar
favorite count: 0
has answer: http://stackoverflow.com/a/50741787

http://stackoverflow.com/q/50785439
answer count: 1
downvote count: 1
favorite count: 0
tagged with: jupyter-notebook
has body: I'm using n1-highcpu-8 machine and running single notebook. the CPU utilization is always below ~20%. is it possible to use multi CPUs for utilization increasing?
has answer: http://stackoverflow.com/a/50803597
accepted answer: http://stackoverflow.com/a/50803597
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: google-cloud-datalab
has title: GCP Datalab - Increasing CPU utilization to ~100%
score: 0
upvote count: 1

http://stackoverflow.com/comment/88507619
score: 0
type: Comment
type: AnswerComment
has text: Copying all rows but one row.
comment on: http://stackoverflow.com/a/50749772

http://stackoverflow.com/a/50853061
type: Answer
accepted answer of: http://stackoverflow.com/q/50852725
answers question: http://stackoverflow.com/q/50852725
upvote count: 1
has body: You can use swapaxes like so: &gt;&gt;&gt; A = np.arange(24).reshape(2,3,4) &gt;&gt;&gt; out = np.empty_like(A) &gt;&gt;&gt; I = [2,0,1] &gt;&gt;&gt; axis = 1 &gt;&gt;&gt; out.swapaxes(0, axis)[I] = A.swapaxes(0, axis) &gt;&gt;&gt; out array([[[ 4, 5, 6, 7], [ 8, 9, 10, 11], [ 0, 1, 2, 3]], [[16, 17, 18, 19], [20, 21, 22, 23], [12, 13, 14, 15]]])
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/50714111
has comment: http://stackoverflow.com/comment/88436925
score: 0
answers question: http://stackoverflow.com/q/50713808
type: Answer
has body: you didn't tell what format you want to find you mean find whole string like format { str1 : str2 }? then it is '{.+:.+}'

http://stackoverflow.com/q/50762700
upvote count: 1
has body: Just a question : If the result of a dot product I want to produce is symetric A = numpy.random.random((3, 3)) # edited M = A.dot(A.T) M [[ 0. 0.11456226 0.1573452 ] [ 0.11456226 0. 0.00363075] [ 0.1573452 0.00363075 0. ]] for instance Is numpy going to copy Mij to Mji's by itself or is there a way to ask for it manualy ? maybe OpenBLAS ? thanks
duplicate of: http://stackoverflow.com/q/50733148
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/43453707
has title: python matrix.dot(matrix.T) symetric output calculation boost
tagged with: dot-product
tagged with: matrix
downvote count: 0
has comment: http://stackoverflow.com/comment/88533382
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: openblas
answer count: 0
has comment: http://stackoverflow.com/comment/88533477
score: 1

http://stackoverflow.com/comment/88421780
type: Comment
comment on: http://stackoverflow.com/a/50705635
has text: Hmm, then maybe the files were corrupted.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50711382
upvote count: 3
tagged with: plot
has body: When I mention the feature names while defining the data matrix in an internal data structure used by XGBoost, I get this error: d_train = xgboost.DMatrix(X_train, label=y_train, feature_names=list(X)) d_test = xgboost.DMatrix(X_test, label=y_test, feature_names=list(X)) ... ... ... shap_values = shap.TreeExplainer(model).shap_values(X_train) shap.summary_plot(shap_values, X_train) ValueError Traceback (most recent call last) &lt;ipython-input-59-4635c450279d&gt; in &lt;module&gt;() ----&gt; 1 shap_values = shap.TreeExplainer(model).shap_values(X_train) 2 shap.summary_plot(shap_values, X_train) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\shap\explainers\tree.py in shap_values(self, X, **kwargs) 104 if not str(type(X)).endswith("xgboost.core.DMatrix'&gt;"): 105 X = xgboost.DMatrix(X) --&gt; 106 phi = self.trees.predict(X, pred_contribs=True) 107 elif self.model_type == "lightgbm": 108 phi = self.trees.predict(X, pred_contrib=True) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\xgboost\core.py in predict(self, data, output_margin, ntree_limit, pred_leaf, pred_contribs, approx_contribs) 1042 option_mask |= 0x08 1043 -&gt; 1044 self._validate_features(data) 1045 1046 length = c_bst_ulong() ~\AppData\Local\Continuum\anaconda3\lib\site-packages\xgboost\core.py in _validate_features(self, data) 1286 1287 raise ValueError(msg.format(self.feature_names, -&gt; 1288 data.feature_names)) 1289 1290 def get_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): ValueError: feature_names mismatch: ['Serial No', 'gender', 'Date', 'Product_Type', 'Product_Type', ... ... , 'Last_feature'] ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24', 'f25', 'f26', 'f27', 'f28', 'f29', 'f30', 'f31', 'f32', 'f33', 'f34', 'f35', 'f36', 'f37', 'f38', 'f39'] &lt;names of some features at column number corresponding to feature number in the following li…
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/50721252
tagged with: matplotlib
type: Question
answer count: 1
downvote count: 0
tagged with: xgboost
favorite count: 0
tagged with: visualization
has title: Why am I getting a "ValueError: feature_names mismatch" when specifying the feature-name list in XGBoost for visualization?
tagged with: python
has answer: http://stackoverflow.com/a/50721252

http://stackoverflow.com/comment/88516418
type: QuestionComment
has text: How are you calculating the time differences? 08:30:00 - 17:30:00 = -9 hours, not 120 minutes.
score: 1
comment on: http://stackoverflow.com/q/50754122
type: Comment

http://stackoverflow.com/a/50759285
score: 1
answers question: http://stackoverflow.com/q/50754859
has body: what I want to achieve is to draw the background at the beginning and need not to reset the background That's not possible. When you draw something to the screen surface, it's just there. To get rid of it, you have to draw something new. The easiest way is to just fill the screen with a solid color or blit your background surface to the screen once every iteration of the main loop. There a more advanced techniques (like only redraw the areas of the screen with the background that where overwritten by another surface), and pygames offers some abstractions in the form of the different Group classes. E.g, there's a clear() function that will "clear" the screen from any sprites of the Group (and does so by redrawing those areas with the surface provided). At first I want to draw two layers, one for the static background and the other for the moving object. However, I do not find any attribute like layers You're looking for the LayeredUpdates class, which will draw its sprites in the order of their _layer-attribute. If you're new to pygame, you should look into how to use pygame's Sprite and Group classes, which will do what you need and are good enough in like 99% of all cases. tl;dr: Your options are: 1) fill the screen surface every iteration of the game loop 2) use sprites and a Group and its clear function every iteration of the game loop 3) use sprites and a LayeredUpdates-group and add background sprite
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50754859

http://stackoverflow.com/a/50805736
has comment: http://stackoverflow.com/comment/88617927
has comment: http://stackoverflow.com/comment/88635341
has comment: http://stackoverflow.com/comment/88641034
has comment: http://stackoverflow.com/comment/88617496
downvote count: 0
has body: First and foremost, how do I dynamically add more workers (to fetch subsequent pages) to the loop? You can enqueue new coroutines to the event loop with asyncio.ensure_future. How can I handle the persistence so that it doesn't block data fetching? If you're talking about writing to a database, there are libraries for that. If you're talking about writing to a file, then that's tricky-- local file IO is almost always blocking, so you'd have to delegate work to a separate thread. Luckily, asyncio provides a helper for that: loop.run_in_executor. Assuming multiple pages need to end up in the same file, how can I safely collect all of the data from these requests, merge it, and then persist without blocking other data fetching requests? This starts getting outside the bounds of what's a good question for SO. You should read up on different concurrency patterns for this.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50805374
score: 1
has comment: http://stackoverflow.com/comment/88625761

http://stackoverflow.com/a/50701220
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50701018
type: Answer
has comment: http://stackoverflow.com/comment/88412413
answers question: http://stackoverflow.com/q/50701018
score: 0
has body: This is due to the way the interpreter evaluates expressions with and/or: or expressions: If the first operand is True or equivalent to True, the second operand is not evaluated and the value of the first operand is returned. If the first operand is False or equivalent to False, the second operand is evaluated and returned Examples: True or np.nan: bool(True) is True, therefore return True np.nan or True: bool(np.nan) is True, therefore return np.nan False or np.nan: bool(False) is False, therefore return np.nan and expressions: If the first operand is False or equivalent to False, the second operand is not evaluated and the value of the first operand is returned If the first operand is True or equivalent to True, the second operand is evaluated and returned Examples: True and np.nan: bool(True) is True, therefore return np.nan np.nan and True: bool(np.nan) is True, therefore return True False and np.nan: bool(False) is False, therefore return False
has comment: http://stackoverflow.com/comment/88412122

http://stackoverflow.com/comment/88412426
score: 0
type: Comment
type: QuestionComment
has text: Can you [edit](https://stackoverflow.com/posts/50701531/edit) with some example data?
comment on: http://stackoverflow.com/q/50701531

http://stackoverflow.com/comment/88570804
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50781888
has text: When I run the code, nothing is printed. It seems to be due to the `reload(sys)` line, although I don't know why.

http://stackoverflow.com/q/50836594
has answer: http://stackoverflow.com/a/50839235
has comment: http://stackoverflow.com/comment/88681731
type: Question
has title: Pyserial Com3 Port no output? Windows 7
has body: Im trying to read data from a simple COM3 USB Serial Port with PySerial. My Code is as follows: import serial import time ser = serial.Serial("COM3", 230400, timeout=2) #Also tried timeout=None, loads to infinity then print (ser) while True: line = ser.readline() #also tried read() print(line) time.sleep(1) Console Outupt: print(ser) =>Serial&lt;id=0x2757c50, open=True&gt;(port='COM3', baudrate=230400, bytesize=8, parity='N', stopbits=1, timeout=2, xonxoff=False, rtscts=False, dsrdtr=False) I tried to mess around with the boolean-attributes of the Serial object ser(e.g. xonxoff) with no success print(line) => empty string or b'' I tried to test this in Python 2.7 and Python 3.6.5. Listing all COM Ports via serial.tools.list_ports.comports() returns this: COM3 - USB Serial Port (COM3) COM46 - com0com - serial port emulator CNCA0 (COM46) COM47 - com0com - serial port emulator CNCB0 (COM47) When I use the program HDTerm I get the following output: Screenshot_HDTerm_COM3_Port_Output So the Port actually returns something, but I can't read the data from python somehow. The parameters are the same in my Python Code as they are in HDTerm. Any idea why Python is printing nothing (or loading to infinity if timeout=None)? PS.: COM46 &amp; COM47 are working perfectly fine in Python and HDTerm. But they have other outputs (sending and receiving data from each other only).
score: 0
answer count: 2
tagged with: pyserial
accepted answer: http://stackoverflow.com/a/50839235
possible better answer: http://stackoverflow.com/a/50837260
has answer: http://stackoverflow.com/a/50837260
tagged with: serial-port
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88546926
comment on: http://stackoverflow.com/q/50769728
score: 0
type: QuestionComment
type: Comment
has text: But you never assigned it to anything.

http://stackoverflow.com/a/50846039
accepted answer of: http://stackoverflow.com/q/50845870
answers question: http://stackoverflow.com/q/50845870
has comment: http://stackoverflow.com/comment/88832621
upvote count: 1
has body: You can use itertools together with standard operators: &gt;&gt;&gt; import itertools, operator &gt;&gt;&gt; running_sum = itertools.accumulate(data) &gt;&gt;&gt; running_mean = map(operator.truediv, running_sum, itertools.count(1)) Example: &gt;&gt;&gt; data = (np.linspace(-i, i*i, 6) for i in range(10)) &gt;&gt;&gt; &gt;&gt;&gt; running_sum = itertools.accumulate(data) &gt;&gt;&gt; running_mean = map(operator.truediv, running_sum, itertools.count(1)) &gt;&gt;&gt; &gt;&gt;&gt; for i in running_mean: ... print(i) ... [0. 0. 0. 0. 0. 0.] [-0.5 -0.3 -0.1 0.1 0.3 0.5] [-1. -0.46666667 0.06666667 0.6 1.13333333 1.66666667] [-1.5 -0.5 0.5 1.5 2.5 3.5] [-2. -0.4 1.2 2.8 4.4 6. ] [-2.5 -0.16666667 2.16666667 4.5 6.83333333 9.16666667] [-3. 0.2 3.4 6.6 9.8 13. ] [-3.5 0.7 4.9 9.1 13.3 17.5] [-4. 1.33333333 6.66666667 12. 17.33333333 22.66666667] [-4.5 2.1 8.7 15.3 21.9 28.5]
has comment: http://stackoverflow.com/comment/88830829
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/50733805
has comment: http://stackoverflow.com/comment/88478146
has body: In my JSON file, I have strings with forward slashes that appear to be escaped. eg. This is path: \/home\/user\/test.txt. When I import this using Python's built-in json.loads() method, the escape slashes are removed. The comments here and here correctly state that in JSON \/ essentially means the same thing as /, so this is to be expected. The problem is that I want these forward slashes to remain escaped when I later go to export the JSON data again via json.dumps(). The JSON file I'm working with should remain as unchanged as possible. I currently have a hack in place when writing the JSON out after I perform the desired manipulation of the data: json_str.replace('/', '\/'). This feels ugly to me, or am I mistaken? Is there any better way? Here is a more complete example: $ python Python 2.7.13 (default, Nov 24 2017, 17:33:09) [GCC 6.3.0 20170516] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import json &gt;&gt;&gt; import collections &gt;&gt;&gt; a = r"""{ ... "version": 1, ... "query": "This is path: \/home\/user\/test.txt" ... }""" &gt;&gt;&gt; j = json.loads(a, object_pairs_hook=collections.OrderedDict) &gt;&gt;&gt; print j OrderedDict([(u'version', 1), (u'query', u'This is path: /home/user/test.txt')]) &gt;&gt;&gt; print json.dumps(j, indent=4, separators=(',', ': ')) { "version": 1, "query": "This is path: /home/user/test.txt" } &gt;&gt;&gt; print json.dumps(j, indent=4, separators=(',', ': ')).replace('/', '\/') { "version": 1, "query": "This is path: \/home\/user\/test.txt" } &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/88478972
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: escaping
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88478291
type: Question
score: 2
linked to: http://stackoverflow.com/q/1580647
linked to: http://stackoverflow.com/q/9364128
downvote count: 0
has title: How can I make python json.dumps() escape forward slashes?

http://stackoverflow.com/q/50834184
has body: My API(Python) is deployed on Amazon Lambda. The problem is when I request my API I get the internal server error. I can tail the Lambda logs but I don't see the actual error or stack trace where the code crashed. When I tail the logs I just get the following output. START RequestId: 62341bgd-6231-11e8-8c5b-25793532a32u Version: $LATEST END RequestId: 62341b0d-6231-1128-8r5b-2b793032a3ed REPORT RequestId: 6234te0b-6rte-aaa8-au5a-21t93132r3rt Duration: 0.46 ms How can I see the actual stack trace of my python api for debugging?
upvote count: 8
type: Question
accepted answer: http://stackoverflow.com/a/50872854
has answer: http://stackoverflow.com/a/68808042
tagged with: serverless
answer count: 6
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/88678790
tagged with: aws-lambda
has answer: http://stackoverflow.com/a/50872854
tagged with: python
has answer: http://stackoverflow.com/a/50837449
favorite count: 0
score: 8
has answer: http://stackoverflow.com/a/73120820
tagged with: aws-serverless
has title: Amazon lambda does not show python logs
downvote count: 0
has comment: http://stackoverflow.com/comment/88675146
has answer: http://stackoverflow.com/a/50862545
possible better answer: http://stackoverflow.com/a/50837449
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77307273

http://stackoverflow.com/q/50766148
tagged with: wshttpbinding
score: 0
answer count: 1
tagged with: wsse
tagged with: soap
tagged with: python
type: AnsweredQuestion
has body: I am writing a simple SOAP client application in Python. WSDL file can be found here: https://clients.nationalmailing.com.au/ServiceTest/OrderService.svc?wsdl Unfortunately the server declared usage of wsHttpBinding in its WSDL file and I had to learn how many troubles it brings to not-.NET developers. I have working C# code (and it is pretty simple there) and used Fiddler to capture the traffic and analyze messages. Now I know the structure to follow. Client sends 2 subsequental messages. I managed to create and send first request and receive a response from the server. BUT second request is a way more complex. I have found a library signxml which helped me to create &lt;Signature&gt; structure with all the fields that should present (as per captured traffic). But the server continues to answer with "Error 500: An error occurred when verifying security for the message." I realized that in the first message I put just random values for the following structure: &lt;s:Body&gt; &lt;trust:RequestSecurityToken xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt; &lt;trust:TokenType&gt;http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct&lt;/trust:TokenType&gt; &lt;trust:RequestType&gt;http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue&lt;/trust:RequestType&gt; &lt;trust:Entropy&gt; &lt;trust:BinarySecret u:Id="uuid-0649fd7a-9ae2-4f9f-964c-e3aa5d68e8cd-1" Type="http://docs.oasis-open.org/ws-sx/ws-trust/200512/Nonce"&gt;h/MaeQVSL5Br30Hnt/SAl274flYfZVZyx2Fri9zNuEY=&lt;/trust:BinarySecret&gt; &lt;/trust:Entropy&gt; &lt;trust:KeySize&gt;256&lt;/trust:KeySize&gt; &lt;/trust:RequestSecurityToken&gt; &lt;/s:Body&gt; The value of BinarySecret is just a random string encoded with Base64. I think this should be an issue on this stage. I also do not use the same parameters from server's response. Could anyone explain how should I use Entropy.BinarySecret - should it take part in the calculations of Signature and how it is used?
has answer: http://stackoverflow.com/a/50767560
accepted answer: http://stackoverflow.com/a/50767560
type: Question
has title: WSHttpBinding: Entropy.BinarySecret role in message encryption

http://stackoverflow.com/q/50787213
has title: Look up values when the columns names of two dataframes are a match
has comment: http://stackoverflow.com/comment/88581410
type: AnsweredQuestion
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/50787541
tagged with: match
downvote count: 1
type: Question
tagged with: insert-update
tagged with: dataframe
answer count: 2
possible better answer: http://stackoverflow.com/a/50787264
tagged with: pandas
has answer: http://stackoverflow.com/a/50787264
has answer: http://stackoverflow.com/a/50787541
favorite count: 0
has body: I would like to write a function that updates the values of df1 when the column names of df1 and df2 match each other. For example: df1: Name | Graduated | Employed | Married AAA 1 2 3 BBB 0 1 2 CCC 1 0 1 df2: Answer_Code | Graduated | Employed | Married 0 No No No 1 Yes Intern Engaged 2 N/A PT Yes 3 N/A FT Divorced Final Result: df3: Name | Graduated | Employed | Married AAA Yes PT Divorced BBB No Intern Yes CCC Yes No NO I would like to code something like this: IF d1.columns = d2.columns THEN df1.column.update(df1.column.map(df2.set_index('Answer_Code').column))
tagged with: python

http://stackoverflow.com/comment/88794987
comment on: http://stackoverflow.com/a/50841388
has text: For me I m seeing 'Make sure this file is located in /home/pi' and 'Do not rename this file' on the "how to". I m using this one https://developers.google.com/assistant/sdk/guides/library/python/embed/register-device
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88590510
type: QuestionComment
has text: Oh, I see. You want something of a cartesian product...
comment on: http://stackoverflow.com/q/50789834
score: 0
type: Comment

http://stackoverflow.com/comment/88606933
has text: But there is the problem arises, so new_user is instance of EmployeeModel not User model? Thats why my login fails.
comment on: http://stackoverflow.com/a/50800266
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50834244
has comment: http://stackoverflow.com/comment/88672263
accepted answer of: http://stackoverflow.com/q/50834143
has comment: http://stackoverflow.com/comment/88672861
has comment: http://stackoverflow.com/comment/88692438
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50834143
type: Answer
score: 2
upvote count: 2
has body: That's a bug in Python 3.5.2 and lower What is your python version? Source 0.23.1 saved the day @Anush Note: You should have first searched google for "TypeError: Type aliases cannot be used with isinstance()" and you would have arrived at the answer immediately

http://stackoverflow.com/q/50723316
score: 2
downvote count: 0
tagged with: scikit-image
tagged with: surface
type: Question
upvote count: 2
tagged with: numpy
tagged with: graph-theory
answer count: 1
has body: I'm using skimage.measure.marching_cubes to extract a surface, defined as faces and vertices. marching_cubes also outputs values for each face. How do I "smooth" these values (the actual smoothing could be a low-pass filter, median filter etc)? I thought that one way to achieve this would be to project, or to represent this surface in 2D, and then apply standard filters, but I can't think of how to do this from a list of faces and vertices. The reason for this "smoothing" is because the values are not informative at the scale of a single face of the surface, but over larger areas of the surface represented by many faces. Thanks in advance!
favorite count: 0
has title: Smooth values from skimage.measure.marching_cubes
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51188072

http://stackoverflow.com/comment/88425341
comment on: http://stackoverflow.com/q/50708118
has text: just use assignment
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50723776
score: 3
upvote count: 3
type: Question
downvote count: 0
has title: Splitting a dataframe in python
has answer: http://stackoverflow.com/a/50723889
answer count: 3
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/50723871
has body: I have a dataframe df= Type ID QTY_1 QTY_2 RES_1 RES_2 X 1 10 15 y N X 2 12 25 N N X 3 25 16 Y Y X 4 14 62 N Y X 5 21 75 Y Y Y 1 10 15 y N Y 2 12 25 N N Y 3 25 16 Y Y Y 4 14 62 N N Y 5 21 75 Y Y I want the result data set of two different data frames with QTY which has Y in their respective RES. Below is my expected result df1= Type ID QTY_1 X 1 10 X 3 25 X 5 21 Y 1 10 Y 3 25 Y 5 21 df2 = Type ID QTY_2 X 3 16 X 4 62 X 5 75 Y 3 16 Y 5 75
has answer: http://stackoverflow.com/a/50723924
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50803957
has comment: http://stackoverflow.com/comment/88615729
has body: I have some data, an array of 400k rows, with each row having 200 elements. I'm trying to use this data to do knn matching using FLANN. Using the pyflann library, which is just a set of bindings to the C++ code, I get outstanding performance. It takes very little time to build the index, and then once the index is built the speed and accuracy of the knn search is fantastic. This is the code used to build and query the index using python: import pyflann flann = pyflann.FLANN() # data is np.array(400000, 200), dtype = np.float32, rows are L2-normed flann.build_index(data, algorithm="kmeans", branching=32, iterations=7, checks=16) ind = 100 k = 5 vector = data[ind, :].reshape(1, 200) t0 = time.time() D, I = flann.nn_index(vector, k, algorithm="kmeans", branching=32, iterations=7, checks=16) t1 = time.time() t = t1 - t0 Typically the index is built in around 20 seconds, with the results D, I being calculated in less that 0.001 seconds on my machine. I'm trying to achieve the same performance using C++. In particular I am using the version of FLANN that is bundled with opencv. I have copied the default parameter values from pyflann into the index parameters, and attempt to setup kmeans, but I get terrible performance, I normally have to kill the indexing process after a few minutes. cvflann::IndexParams getParams(){ cvflann::IndexParams indexParams; indexParams["algorithm"] = cvflann::FLANN_INDEX_KMEANS; //branching=32, iterations=7, checks=16 indexParams["branching"] = 32; indexParams["iterations"] = 7; indexParams["checks"] = 16; indexParams["eps"] = 0.0; indexParams["cb_index"] = 0.5; indexParams["trees"] = 1; indexParams["leaf_max_size"] = 4; indexParams["centers_init"] = cvflann::FLANN_CENTERS_RANDOM; indexParams["target_precision"] = 0.9; indexParams["build_weight"] = 0.01; indexParams["memory_weight"] = 0.0; indexParams["sample_fraction"] = 0.1; indexParams["log_level"] = "warning"; indexParams["random_seed"] = -1; return indexParams; } cvflann::Matrix dataset(thi…
has comment: http://stackoverflow.com/comment/116250747
has comment: http://stackoverflow.com/comment/88630082
has title: pyflann code much faster than C++ FLANN
downvote count: 0
favorite count: 0
tagged with: flann
tagged with: python
tagged with: c++
answer count: 0
upvote count: 3
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88615457
tagged with: opencv
score: 3

http://stackoverflow.com/q/50794139
has comment: http://stackoverflow.com/comment/88601252
has comment: http://stackoverflow.com/comment/88599472
has comment: http://stackoverflow.com/comment/88600685
has title: Find Python compilation / runtime error before running
has comment: http://stackoverflow.com/comment/88601508
type: AnsweredQuestion
score: 3
upvote count: 3
has body: Consider the following: def func_a(param1,param2): print (param1 + param2) func_a("a") func_a expects two parameters, whereas it is called with only one. In other languages this kind of error is discovered while coding or compiling. Is it possible to find this Python coding error before runtime?
has comment: http://stackoverflow.com/comment/88610710
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88595272
has answer: http://stackoverflow.com/a/50813236
has comment: http://stackoverflow.com/comment/88594367
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/88601543
accepted answer: http://stackoverflow.com/a/50813236
answer count: 1
tagged with: python
favorite count: 0
tagged with: compiler-errors

http://stackoverflow.com/comment/88657484
type: Comment
has text: Update your fx version, check the link in my previous comment.
type: QuestionComment
comment on: http://stackoverflow.com/q/50826057
score: 1

http://stackoverflow.com/q/50785111
tagged with: python-multiprocessing
has title: Removing daemon from python multiprocessing process
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50785581
tagged with: python
favorite count: 0
has body: Using python 3.6, I have a problem like so: (1) there's a joblib.Parallel loop over embarrassingly parallel jobs (2) the jobs themselves are fairly time intensive c++ native objects that occasionally segfault and whose code I cannot modify. To guard against the segfaults, I attempted to wrap the jobs themselves inside a multiprocessing Process. Unfortunately, python itself throws an assertion error with daemonic processes are not allowed to have children with this solution. So I took the solution posted here and tried inheriting from Process: https://stackoverflow.com/a/8963618/614684 That didn't work either, and so I came up with the following solution which DOES work: class NoDaemonProcess(multiprocessing.Process): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None): super(NoDaemonProcess, self).__init__(group, target, name, args, kwargs, daemon=daemon) if 'daemon' in multiprocessing.process._current_process._config: del multiprocessing.process._current_process._config['daemon'] self._config = multiprocessing.process._current_process._config.copy() # make 'daemon' attribute always return False def _get_daemon(self): return False def _set_daemon(self, value): pass daemon = property(_get_daemon, _set_daemon) Basically, I modify the global state of the multiprocessing package to delete the fact that the current process is a daemon. Is there a better way to do this? I would appreciate any help in making this more robust and reliable.
linked to: http://stackoverflow.com/q/6974695
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88577012
type: Question
score: 2
has comment: http://stackoverflow.com/comment/88577634

http://stackoverflow.com/comment/88678865
comment on: http://stackoverflow.com/a/50837582
has text: `"errorMessage": "Parameter validation failed:\nInvalid type for parameter InstanceId, value: ['i-07d2c5b7056bc639d'], type: <type 'list'>, valid types: <type 'basestring'>"`
type: AnswerComment
score: 0
type: Comment

multithreading
tags question: http://stackoverflow.com/q/50786974
tags question: http://stackoverflow.com/q/50738072
type: Tag
tags question: http://stackoverflow.com/q/50737170
tags question: http://stackoverflow.com/q/50732206
tags question: http://stackoverflow.com/q/50788641
tags question: http://stackoverflow.com/q/50714551
tags question: http://stackoverflow.com/q/50751515
tags question: http://stackoverflow.com/q/50790774
tags question: http://stackoverflow.com/q/50748775
tags question: http://stackoverflow.com/q/50770253
tags question: http://stackoverflow.com/q/50799820
tags question: http://stackoverflow.com/q/50699300
tags question: http://stackoverflow.com/q/50758293
tags question: http://stackoverflow.com/q/50838371
tags question: http://stackoverflow.com/q/50765460
tags question: http://stackoverflow.com/q/50724389
tags question: http://stackoverflow.com/q/50753603
tags question: http://stackoverflow.com/q/50748748
tags question: http://stackoverflow.com/q/50773086
tags question: http://stackoverflow.com/q/50748265
tags question: http://stackoverflow.com/q/50700009
tags question: http://stackoverflow.com/q/50731203
tags question: http://stackoverflow.com/q/50779419
tags question: http://stackoverflow.com/q/50798820
tags question: http://stackoverflow.com/q/50793090
tags question: http://stackoverflow.com/q/50847096
tags question: http://stackoverflow.com/q/50720945
tags question: http://stackoverflow.com/q/50807554
tag name: multithreading
tags question: http://stackoverflow.com/q/50733047
tags question: http://stackoverflow.com/q/50712062

http://stackoverflow.com/comment/88585014
type: AnswerComment
type: Comment
has text: Wow! I was thinking about that but I didn't know how to do it! You're very clever - guess that's why you're at Harvard! Thank you for your help! :)
comment on: http://stackoverflow.com/a/50785761
score: 0

http://stackoverflow.com/a/50766666
answers question: http://stackoverflow.com/q/50763003
has comment: http://stackoverflow.com/comment/126583298
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50763003
has body: You could use py.io for this. something like: capture = py.io.StdCapture() pytest.main(['--collect-only', '-q']) std, err = capture.reset() print(std) Would get you the standard output you're looking for.

http://stackoverflow.com/comment/88665756
type: Comment
comment on: http://stackoverflow.com/a/50829815
score: 0
type: AnswerComment
has text: Ah sorry, I meant I want to filter those with value <= 300. It is working, thanks! But is there any way to delete the whole data, not only the authority section, if it is not within the requirement?

http://stackoverflow.com/q/50805638
has comment: http://stackoverflow.com/comment/88617768
has title: Python 3.x: Problems writing utf-8 strings to binary txt file
has comment: http://stackoverflow.com/comment/88625375
has comment: http://stackoverflow.com/comment/88617481
has comment: http://stackoverflow.com/comment/88617487
type: Question
has comment: http://stackoverflow.com/comment/88617343
has comment: http://stackoverflow.com/comment/88617622
score: 0
has body: I am currently working through "Learning Python the hardway" and try to alter one Excercise. Objective: Write the binary equivalents of the languages in a new .txt file import sys script, encoding, error = sys.argv def main(language_file, encoding, errors): line = language_file.readline() if line: print_line(line, encoding, errors) return main(language_file, encoding, errors) def print_line(line, encoding, errors): next_lang = line.strip() raw_bytes = next_lang.encode(encoding, errors=errors) cooked_string = raw_bytes.decode(encoding, errors=errors) bin_file.write(raw_bytes + "\n".encode("utf-8")) print(raw_bytes, "&lt;===&gt;", cooked_string) languages = open("languages.txt", encoding="utf-8") bin_file = open("bin_languages.txt", "wb") main(languages, encoding, error) The majority of this code is from the learning example, that is why there is for understanding purposes an encode/decode of raw_bytes to cooked_strings and back again. Unfortunately, the output file contains the same content as the original file. Is my approach not possible? Thanks!
has comment: http://stackoverflow.com/comment/88634285
has comment: http://stackoverflow.com/comment/88617544
has comment: http://stackoverflow.com/comment/88634055
tagged with: binary
has comment: http://stackoverflow.com/comment/88617396
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50804263
score: 1
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50804493
accepted answer: http://stackoverflow.com/a/50804493
answer count: 1
downvote count: 1
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has title: Pandas Dataframe: Replace values in a dataframe with values from corresponding column vector of a different dataframe
has body: I have two data frames DF_1: Item number Price Location 33 $4 Boston 29 $2 NYC DF_2: Item number 29 33 Property 1 2.4 4.2 Property 2 5.2 1.9 Property 3 8.9 3.8 I want to replace the Item number in DF_1 with the 3 corresponding properties for it from DF_2, so that the new DF looks like: New_DF: Property 1 Property 2 Property 3 Price Location 4.2 1.9 3.8 $4 Boston 2.4 5.2 8.9 $2 NYC I've gone through hours of trying to do it and also thoroughly looked through StackOverFlow but couldn't find anything similar. Please help.
type: AnsweredQuestion

http://stackoverflow.com/comment/88537386
comment on: http://stackoverflow.com/a/50764596
type: Comment
has text: This is great and very simple! I am obviously a newbie in python, and although I researched for hours before posting on here, I didn't find anything. Thanks!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88643165
type: QuestionComment
comment on: http://stackoverflow.com/q/50806403
has text: My apologies, I should've posted my attempt.
score: 0
type: Comment

http://stackoverflow.com/a/50788726
type: Answer
has comment: http://stackoverflow.com/comment/119987507
answers question: http://stackoverflow.com/q/50788508
has body: These will repeat the indices and preserve the columns as op demonstrated iloc version 1 df.iloc[np.arange(len(df)).repeat(3)] iloc version 2 df.iloc[np.arange(len(df) * 3) // 3]
downvote count: 1
upvote count: 19
score: 18

http://stackoverflow.com/comment/88701859
type: Comment
has text: appreciate your answer.But I can't use any inbuild function.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50849445

http://stackoverflow.com/a/53420574
score: 315
has comment: http://stackoverflow.com/comment/127395739
has comment: http://stackoverflow.com/comment/129329693
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50757497
has comment: http://stackoverflow.com/comment/132965005
has comment: http://stackoverflow.com/comment/136048531
upvote count: 316
has comment: http://stackoverflow.com/comment/124186856
type: Answer
has comment: http://stackoverflow.com/comment/133166322
has comment: http://stackoverflow.com/comment/136857171
downvote count: 1
has body: To answer your questions, I will provide three different solutions to the same problem. Case 1: just normal Python import time def sleep(): print(f'Time: {time.time() - start:.2f}') time.sleep(1) def sum_(name, numbers): total = 0 for number in numbers: print(f'Task {name}: Computing {total}+{number}') sleep() total += number print(f'Task {name}: Sum = {total}\n') start = time.time() tasks = [ sum_("A", [1, 2]), sum_("B", [1, 2, 3]), ] end = time.time() print(f'Time: {end-start:.2f} sec') Output: Task A: Computing 0+1 Time: 0.00 Task A: Computing 1+2 Time: 1.00 Task A: Sum = 3 Task B: Computing 0+1 Time: 2.00 Task B: Computing 1+2 Time: 3.00 Task B: Computing 3+3 Time: 4.00 Task B: Sum = 6 Time: 5.00 sec Case 2: async/await done wrong import asyncio import time async def sleep(): print(f'Time: {time.time() - start:.2f}') time.sleep(1) async def sum_(name, numbers): total = 0 for number in numbers: print(f'Task {name}: Computing {total}+{number}') await sleep() total += number print(f'Task {name}: Sum = {total}\n') start = time.time() loop = asyncio.new_event_loop() tasks = [ loop.create_task(sum_("A", [1, 2])), loop.create_task(sum_("B", [1, 2, 3])), ] loop.run_until_complete(asyncio.wait(tasks)) loop.close() end = time.time() print(f'Time: {end-start:.2f} sec') Output: Task A: Computing 0+1 Time: 0.00 Task A: Computing 1+2 Time: 1.00 Task A: Sum = 3 Task B: Computing 0+1 Time: 2.00 Task B: Computing 1+2 Time: 3.00 Task B: Computing 3+3 Time: 4.00 Task B: Sum = 6 Time: 5.00 sec Case 3: async/await done right The same as case 2, except the sleep function: async def sleep(): print(f'Time: {time.time() - start:.2f}') await asyncio.sleep(1) Output: Task A: Computing 0+1 Time: 0.00 Task B: Computing 0+1 Time: 0.00 Task A: Computing 1+2 Time: 1.01 Task B: Computing 1+2 Time: 1.01 Task A: Sum = 3 Task B: Computing 3+3 Time: 2.01 Task B: Sum = 6 Time: 3.02 sec Case 1 and case 2 give the same 5 seconds, whereas case 3 just 3 seconds. So the async/await done right is faster. …
has comment: http://stackoverflow.com/comment/118425692
answers question: http://stackoverflow.com/q/50757497
has comment: http://stackoverflow.com/comment/140179101

http://stackoverflow.com/q/50840170
has title: Python is converting charcters to symbols
tagged with: character-encoding
accepted answer: http://stackoverflow.com/a/50840646
type: Question
has answer: http://stackoverflow.com/a/50840646
score: 0
tagged with: sqlite
answer count: 1
tagged with: http://stackoverflow.com/tag/xml
tagged with: python
has body: I have the trouble and dont know how to start solve it. I have the XML-file. There is example: &lt;resources&gt; &lt;string name="menuOptionMdReceiptIcon"&gt;&amp;#xf1b4;&lt;/string&gt; &lt;string name="menuOptionMdStoreMallDirectoryIcon"&gt;&amp;#xf1d4;&lt;/string&gt; &lt;string name="menuOptionMdPersonIcon"&gt;&amp;#xf207;&lt;/string&gt; &lt;string name="menuOptionMdLocalAtmIcon"&gt;&amp;#xf198;&lt;/string&gt; &lt;string name="menuOptionMdSwapHorizIcon"&gt;&amp;#xf30d;&lt;/string&gt; &lt;string name="menuOptionMdPeopleIcon"&gt;&amp;#xf20d;&lt;/string&gt; &lt;/resources&gt; it is my code: import sqlite3 from xml.dom import minidom import xml.etree.ElementTree as xml dict_4_3 = {} db = sqlite3.connect("table.db") cursor = db.cursor() cursor.executescript(""" DROP TABLE IF EXISTS V_4_3; CREATE TABLE V_4_3 (ID integer primary key AUTOINCREMENT, TAG_NAME_4_3 TEXT, VALUE_4_3 TEXT); """) xmldoc = minidom.parse('strings_4_3.xml') xmldoc.normalize() itemlist = xmldoc.getElementsByTagName('string') for s in itemlist: try: dict_4_3[s.attributes['name'].value] = s.childNodes[0].nodeValue cursor.execute("""INSERT INTO V_4_3 (TAG_NAME_4_3, VALUE_4_3) VALUES (?, ?)""", (s.attributes['name'].value, s.childNodes[0].nodeValue)) except: cursor.execute("""INSERT INTO V_4_3 (TAG_NAME_4_3, VALUE_4_3) VALUES (?, ?)""", (s.attributes['name'].value, None)) I just getting values from XML-file and want to put to SQLite DB. So my trouble is converting sequence like "&amp;#xf20d" to &#xf20d; in the DB lines. How to force Python take values without changes and incert them to DB lines? Thank you for attention.
type: AnsweredQuestion

http://stackoverflow.com/q/50753995
tagged with: opencv
has comment: http://stackoverflow.com/comment/88522180
has comment: http://stackoverflow.com/comment/88516754
answer count: 1
has comment: http://stackoverflow.com/comment/88517956
favorite count: 0
has title: How to use analog camera live stream through dvr for face recognization
has comment: http://stackoverflow.com/comment/88516293
has answer: http://stackoverflow.com/a/62545592
type: UnansweredQuestion
has body: I am working on face recognization using OpenCV and python. cap = cv2.VideoCapture("videoplayback.mp4") At the place of this video link, I want a DVR live stream video link.
tagged with: python
upvote count: 2
score: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/50712139
tagged with: pyautogui
has answer: http://stackoverflow.com/a/54536499
score: 12
has body: All in all, I'm trying to programmatically -and externally- control the Minecraft player's orientation. No APIs, no Java mods to the game environment Typically this requires the movement of the mouse, but every single mouse movement simulating python3 library that I've tried doesn't move the player's head in-game. Each library does something different, too. For example, pyautogui doesn't do anything until you move the mouse manually after the script has finished. Doing this will jerk the player's view to where the program supposedly moved it to, before continuing to follow your current mouse movements. This happens for both mouse commands. import pyautogui pyautogui.moveTo(500, 500) pyautogui.moveRel(100, 100) The pynput library had the same weird result as pyautogui: from pynput.mouse import Controller mouse = Controller() mouse.position = (100, 200) mouse.move(200, -100) Quartz doesn't do anything at all: import Quartz class Mouse(): down = [Quartz.kCGEventLeftMouseDown, Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown] up = [Quartz.kCGEventLeftMouseUp, Quartz.kCGEventRightMouseUp, Quartz.kCGEventOtherMouseUp] [LEFT, RIGHT, OTHER] = [0, 1, 2] def click_pos(self, x, y, button=LEFT): self.move(x, y) self.click(button) def to_relative(self, x, y): curr_pos = Quartz.CGEventGetLocation( Quartz.CGEventCreate(None) ) x += curr_pos.x; y += curr_pos.y; mouse = Mouse() mouse.to_relative(200, 200) And the python mouse library is outdated: the error showed that it will only run on Darwin (I'm on macOS High Sierra). I was sad on learning this because of the description on the Github page. It says "Global event hook on all mice devices (captures events regardless of focus)". I then thought that, somehow, Minecraft was sucking up all the simulated mouse movements on it's own. Either way, I'm not using the right interface for this game, and I need something that can bypass Minecraft's interesting mouse controls to get the movement that I want. I even tried using mouse…
upvote count: 12
downvote count: 0
answer count: 7
has title: How to control the mouse in Minecraft using Python?
tagged with: macos
favorite count: 0
has answer: http://stackoverflow.com/a/70778046
has answer: http://stackoverflow.com/a/58043888
has comment: http://stackoverflow.com/comment/109115343
tagged with: python
has answer: http://stackoverflow.com/a/50963270
tagged with: mouse
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51661153
has answer: http://stackoverflow.com/a/70069460
type: Question
has answer: http://stackoverflow.com/a/71593975
tagged with: minecraft

http://stackoverflow.com/comment/88685486
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50840872
has text: Are you looking for some sort of equation solver? Maybe sympy then as mentioned.

http://stackoverflow.com/q/50804725
type: UnansweredQuestion
score: 0
tagged with: twython
has answer: http://stackoverflow.com/a/50804860
tagged with: twitter
type: Question
has body: I am trying to get the exception code from Twitter API (using twython), but it returns an HTTP error code instead. Here you can see the codes from twitter API. For example: try: twitter.retweet(id=tweet["id"]) except TwythonError as e: print("FAILED to retweet: [tweet_id:" + str(tweet["id"]) + "]") print(e.error_code) The following prints HTTP error code instead of twitter API code print(e.error_code) For example instead of API error code 261 or 271, 272,... it prints HTTP error 403 (Forbidden). This is a problem because I cannot distinguish between codes that share the same HTTP error code.
tagged with: exception
answer count: 1
has title: twython get api error code
tagged with: python

http://stackoverflow.com/a/50835827
score: 1
answers question: http://stackoverflow.com/q/50834528
has comment: http://stackoverflow.com/comment/88675607
has body: Your error happens in line: close1[i]=df['close'][df1.loc['Date'][i], df['Date']] If your goal here is to get close value from df given i index you should write: close[i] = df['close'][i] See if that helps, unfortunately I don't understand fully what you are trying to accomplish, for example why do you set size to the length of shorter table? Also, as long as I downloaded correct files, your condition df['Date'][i]in df1['Date'] might not work, one date format uses - and the other \. Solution import pandas as pd pd.set_option('expand_frame_repr', False) # load both files df = pd.read_csv('CAC.csv') df1 = pd.read_csv('DANONE.csv', header=3) # ensure date format is the same between two df.Date = pd.to_datetime(df.Date, dayfirst=True) df1.Date = pd.to_datetime(df1.Date, dayfirst=True) # you need only Date and Close columns as far as I understand keep_columns = ['Date', 'Close'] # let's keep only these columns then df = df[keep_columns] df1 = df1[keep_columns] # merge two tables on Date, method is left so that for every row in df we # 'append' row from df1 if possible, if not there will be NaN value, # for readability I added suffixes df - CAC and df1 - DANONE merged = pd.merge(df, df1, on='Date', how='left', suffixes=['CAC', 'DANONE']) # now for all missing values in CloseDANONE, so if there is Date in df # but not in df1 we fill this value with LAST available merged.CloseDANONE.fillna(method='ffill', inplace=True) # we get values from CloseDANONE column as long as it's not null close1 = merged.loc[merged.CloseDANONE.notnull(), 'CloseDANONE'].values Below you can see: last 6 values from df - CAC Date Close 5522 2018-06-06 5457.560059 5523 2018-06-07 5448.359863 5524 2018-06-08 5450.220215 5525 2018-06-11 5473.910156 5526 2018-06-12 5453.370117 5527 2018-06-13 5468.240234 last 6 values from df1 - DANONE: Date Close 0 2018-06-06 63.86 1 2018-06-07 63.71 2 2018-06-08 64.31 3 2018-06-11 64.91 4 2018-06-12 65.43 last 6 rows from merged: Date CloseCAC CloseDANONE 5522 2018-0…
type: Answer
has comment: http://stackoverflow.com/comment/88675458
has comment: http://stackoverflow.com/comment/88676260
upvote count: 1
has comment: http://stackoverflow.com/comment/88677894
accepted answer of: http://stackoverflow.com/q/50834528
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88677259
comment on: http://stackoverflow.com/a/50799159
score: 0
type: Comment
has text: @Tim I'm not sure what to say to that. It's all explained in the documentation, so I can really only repeat the information from there: A LibraryLoader is an object that lets you load libraries through attribute access. `CDLL` (along with `WinDLL` and the others) is the class of those loaded libraries. Basically, `cdll.foo == CDLL('foo')`, `windll.foo == WinDLL('foo')`, etc.
type: AnswerComment

http://stackoverflow.com/q/50747765
has title: Reverse for 'detail' with keyword arguments '{'slug': 'hello-world'}' not found in django
has comment: http://stackoverflow.com/comment/88503700
possible better answer: http://stackoverflow.com/a/61943000
has answer: http://stackoverflow.com/a/61943000
upvote count: 1
has comment: http://stackoverflow.com/comment/88504047
favorite count: 0
has comment: http://stackoverflow.com/comment/88504083
has comment: http://stackoverflow.com/comment/88503550
has comment: http://stackoverflow.com/comment/88503295
tagged with: django
has comment: http://stackoverflow.com/comment/88504116
tagged with: python
has answer: http://stackoverflow.com/a/50748191
accepted answer: http://stackoverflow.com/a/50748191
has comment: http://stackoverflow.com/comment/88503674
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88503858
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88503984
has body: I am trying to build a blog app using django. Now I need to show article details using slug. When I used bellow RegEx to use as slug for details url I am getting this error. Would someone help me please to solve this problem? In articles - app urls.py is - from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.article_list, name="list"), url(r'^(?P<slug>[\w-]+)/$', views.article_detail, name="detail"), ] And views.py is - from django.shortcuts import render from .models import Article from django.http import HttpResponse # Create your views here. def article_list(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): return HttpResponse(slug) And article_list.html is - {% extends 'base_layout.html' %} {% block content %} Article List: {% for article in articles %} {{ article.title }} {{ article.snippet }} {{ article.date }} {% endfor %} {% endblock %} traceback- Environment: Request Method: GET Request URL: http://127.0.0.1:8000/articles/ Django Version: 2.0.5 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', 'articles'] 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'] Template error: In template C:\Users\rashed\Documents\django- blog\djangonautic\templates\base_layout.html, error at line 0 Reverse for 'detail' with keyword arguments '{'slug': 'hello-world'}' not found. 1 pattern(s) tried: ['articles/$(?P<slug>[\\w-]+)/$'] 1 : {%…
has comment: http://stackoverflow.com/comment/88503763

http://stackoverflow.com/q/50703000
type: Question
has body: I have a list y of endogenous values where len(y) = n I have a n x 5 nympy array X of exogenous values when I run import statsmodels.api as sm sm.GLM(y, X).fit().summary() everything runs fine. However, when I add the family argument: sm.GLM(y, X, family=Poisson()).fit().summary() I get an error: TypeError: __init__() missing 2 required positional arguments: 'endog' and 'exog' I have tried recasting the y object as numpy array, I tried explicitly declaring arguments - nothing seems to help and cannot find anything in docs to help.
score: 0
accepted answer: http://stackoverflow.com/a/50703682
tagged with: glm
answer count: 1
tagged with: typeerror
tagged with: python
has answer: http://stackoverflow.com/a/50703682
type: AnsweredQuestion
tagged with: statsmodels
has title: Python statsmodels.glm - TypeError when family=Poisson()

http://stackoverflow.com/q/50746530
has comment: http://stackoverflow.com/comment/88520499
tagged with: tflearn
score: -1
type: Question
answer count: 3
tagged with: deep-learning
upvote count: 0
favorite count: 0
tagged with: python
tagged with: conv-neural-network
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50746679
has title: Tensorflow : Value Error , cannot feed value of (64,) to (?, 27)
has body: I am new python and right now i have this problem. I am trying to make a CNN model for 27 classifications . But i am getting this error ValueError: Cannot feed value of shape (64,) for Tensor 'targets/Y:0', which has shape '(?, 27)'[here is the picture of my error1 here is my code I ll really appreciate any suggestions and comments P.S i am new to this so , apologies in advance for noob mistake import numpy as np, cv2, os import tflearn import parser from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression img_size = 50 LR = 1e-3 MODEL_N = 'wood-{}-{}.model'.format(LR, '2conv-basic') folders = ['alan batu', 'alan bunga', 'bindang', 'bintangor', 'dark red meranti', 'durian','geronggang','jelutong','jongkong','kapur','keruing', 'light red meranti', 'menggris','merbau','mersawa','nyatoh','perupok','pulai','ramin', 'rengas','resak','selangan batu','sepetir','terentang', 'white meranti','yellow meranti'] labels = [] images = [] for folder in folders: for path in os.listdir('C:/Users/mwasi/Desktop/AI/pictures/sorted/'+folder): img = cv2.imread('C:/Users/mwasi/Desktop/AI/pictures/sorted/'+folder+'/'+path,0) images.append(cv2.resize(img, (img_size, img_size))) labels.append(folders.index(folder)) to_train= 0 training_data =[] testing_data =[] train_images, test_images, train_labels, test_labels = [],[],[],[] for image, label in zip(images, labels): if to_train&lt;5: train_images.append(image) train_labels.append(label) to_train+=1 training_data.append ([np.array(image), np.array(label)]) else: test_images.append(image) test_labels.append(label) to_train = 0 testing_data.append ([np.array(image), np.array(label)]) print('# of training images: ', len(train_images)) print('# of testimg images: ', len(test_images)) np.save('train_data.npy',training_data) np.save('testing_data.npy',testing_data) convnet = input_data(shape=[None, img_size,img_size, 1], name='input') co…
downvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50765388
has answer: http://stackoverflow.com/a/50767183

http://stackoverflow.com/comment/88632225
has text: I think it is rather weird to patch this at the model level, since typically a model is invariant of the databases that are used. You probably better implement *database routing*.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50813567

http://stackoverflow.com/comment/88544803
has text: Removed one, my bad. Also another rstrip didn't work, don't know if that was supposed to be a joke lol
score: 0
comment on: http://stackoverflow.com/q/50768638
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50775373
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50777116
score: 1
tagged with: web-scraping
upvote count: 1
tagged with: scrapy
type: Question
has body: Is there any solid refernce as to how multiple parameters can fit within response.meta.get("something","someotherthing")in scrapy? If it is posible then how someotherthing relates to something? I searched a lot but could not find anywhere the exact answer I'm after.
accepted answer: http://stackoverflow.com/a/50777116
has title: Multiple parameters within response.meta.get()
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88444204
has text: You shouldn't just copy the solution in the comments
comment on: http://stackoverflow.com/a/50717878
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/95430078
type: QuestionComment
comment on: http://stackoverflow.com/q/50757464
has text: _the documentation specifies that the object to display should be serializable_ -- As an alternative, you could write a serializable "wrapper" class, that contains all the information you want to display. This object will get created on the debuggee side, using the target type of the visualizer, and then get serialized and sent across to the VS side. https://wrightfully.com/debugger-visualizer-for-nonserialized-types
score: 0
type: Comment

http://stackoverflow.com/a/50853722
score: 2
downvote count: 0
has body: The error actually stems from the fact that np.arange produces int32s by default but you specified a float32 return type. The error is gone with import numpy as np import tensorflow as tf with tf.Session() as sess: with tf.device("/gpu:0"): def test_func(i): return i test_range = tf.constant(np.arange(5, dtype=np.float32)) test = sess.run(tf.map_fn(test_func, test_range, dtype=tf.float32)) print(test) I agree that the error message you got is rather confusing. You get the "real" error message by removing device placement: import numpy as np import tensorflow as tf with tf.Session() as sess: def test_func(i): return i test_range = tf.constant(np.arange(5)) test = sess.run(tf.map_fn(test_func, test_range, dtype=tf.float32)) print(test) # InvalidArgumentError (see above for traceback): TensorArray dtype is float but Op is trying to write dtype int32.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50845372
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50845372
type: Answer

http://stackoverflow.com/a/50787581
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50787563
has comment: http://stackoverflow.com/comment/88593198
answers question: http://stackoverflow.com/q/50787563
has body: You're looking for choice_label: {% for box in form.amenities %} &lt;label&gt;{{ box.choice_label }}&lt;/label&gt; {% endfor %}
type: AcceptedAnswer

http://stackoverflow.com/comment/88467594
type: QuestionComment
has text: If you substitute into your prepared SQL query properly, the quotes shouldn't be put into it.
score: 0
comment on: http://stackoverflow.com/q/50729672
type: Comment

http://stackoverflow.com/comment/139716525
type: Comment
comment on: http://stackoverflow.com/a/53614392
score: 0
type: AnswerComment
has text: This worked for me without any error.

http://stackoverflow.com/a/50844560
type: Answer
accepted answer of: http://stackoverflow.com/q/50844379
answers question: http://stackoverflow.com/q/50844379
has comment: http://stackoverflow.com/comment/88693638
score: 3
has comment: http://stackoverflow.com/comment/88692756
upvote count: 3
has comment: http://stackoverflow.com/comment/88693998
type: AcceptedAnswer
downvote count: 0
has body: What do you think about: import pandas as pd propiedades = ["Rod. BR 386, bairro Olarias/Conventos, Lajeado/RS", "Fazenda da Várzea - zona rural, Serro/MG", "Cidade do Rock - Jacarepaguá, Rio de Janeiro/RJ", "Área de extração de carnaúba - Povoado Areal, zona rural, Santa Cruz do Piauí/PI", "Pastelaria - Av. Vicente de Carvalho, 995, Loja Q, Vila da Penha, Rio de Janeiro/RJ"] df = pd.DataFrame({"Nome_propriedade":propiedades}) df"City", "State" = df["Nome_propriedade"].apply(lambda x :x.split(",")[-1]).str.split("/", expand=True) UPDATE If you then want to delete these infos from Nome_propriedade you can add this line df["Nome_propriedade"] = df["Nome_propriedade"].apply(lambda x :",".join(x.split(",")[:-1]))

http://stackoverflow.com/q/50852725
has body: In the documentation of numpy.take, it is stated that a is indexed according to indices and axis, then the result is optionally stored in the out parameter. Does exists a function that perform the indexing on out instead? Using fancy indexing it would be something like: out[:, :, indices, :] = a Here I assume that axis=2 but in my case I don't know the axis in advance. A solution using 1d boolean masks instead of indices is acceptable as well.
has answer: http://stackoverflow.com/a/50853061
has title: a function similar to numpy.take that indexes the out parameter
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50853061
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50860852
possible better answer: http://stackoverflow.com/a/50860852
score: 0
answer count: 2
tagged with: numpy-indexing

http://stackoverflow.com/q/50838199
tagged with: python
has answer: http://stackoverflow.com/a/73664656
has comment: http://stackoverflow.com/comment/88680130
has comment: http://stackoverflow.com/comment/88682787
answer count: 5
has answer: http://stackoverflow.com/a/52160638
possible better answer: http://stackoverflow.com/a/77047516
has body: I have a large number of columns in a PySpark dataframe, say 200. I want to select all the columns except say 3-4 of the columns. How do I select this columns without having to manually type the names of all the columns I want to select?
has answer: http://stackoverflow.com/a/77047516
upvote count: 40
type: AnsweredQuestion
tagged with: pyspark
tagged with: dataframe
has title: Pyspark: Select all columns except particular columns
score: 40
type: Question
has comment: http://stackoverflow.com/comment/88682774
has answer: http://stackoverflow.com/a/79425196
linked to: http://stackoverflow.com/q/35674490
accepted answer: http://stackoverflow.com/a/52160638
tagged with: sql
downvote count: 0
has answer: http://stackoverflow.com/a/69166578
linked to: http://stackoverflow.com/q/413819
favorite count: 0

http://stackoverflow.com/a/50756716
downvote count: 0
has body: Python 3.6 introduced f-strings, which allow for short strings &amp; format class foo: def __init__(self): self.cost = 12 self.solution = "easy" self.table = "no" def __str__(self): return f"Cost: {self.cost}\nSolution: {self.solution}\nTable: {self.table}" f = foo() print(str(f))
type: Answer
answers question: http://stackoverflow.com/q/50756522
accepted answer of: http://stackoverflow.com/q/50756522
score: 3
has comment: http://stackoverflow.com/comment/88521503
upvote count: 3
has comment: http://stackoverflow.com/comment/88521590
type: AcceptedAnswer

http://stackoverflow.com/comment/88541028
type: QuestionComment
has text: Is there a reason you are inverting the matrix instead of using `solve`? Inversion is very costly and usually unnecessary.
type: Comment
comment on: http://stackoverflow.com/q/50754020
score: 0

http://stackoverflow.com/q/50753038
score: 6
has body: Is it considered bad practice to add modules to a custom pytorch nn.Module using self.add_module()? All of the documentation seems to assign the layers to properties, then access them in the forward() method. For example: class ConvLayer(nn.Module): def __init__(self): self.add_module('conv',nn.Conv2d(...)) self.add_module('bn',nn.BatchNorm2d(...))
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51498721
has title: Adding modules in Pytorch Custom Module
type: Question
downvote count: 0
favorite count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51498721
tagged with: python
upvote count: 6
tagged with: pytorch

http://stackoverflow.com/comment/88521290
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50756715
type: Comment
has text: yes you should to override the `create/update` actions.

http://stackoverflow.com/a/50807701
has body: Except for QuerySet.update returning the number of affected rows Django doesn't provide any primitives to deal with optimistic locking. However there's a few third-party apps out there that provide such a feature. django-concurrency which is the most popular option that provides both database level constraints and application one django-optimistic-lock which is a bit less popular but I've tried in a past project and it was working just fine. django-locking unmaintained. Edit: It looks like OP was not after optimistic locking solutions after all.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50699759

http://stackoverflow.com/q/50768235
downvote count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/50781615
linked to: http://stackoverflow.com/q/32334966
has answer: http://stackoverflow.com/a/50781615
type: AnsweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/88544247
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88543961
has answer: http://stackoverflow.com/a/50768670
has comment: http://stackoverflow.com/comment/88544268
favorite count: 0
has body: I have a number of supposed csv's but in fact they have some rows with different numbers of fields. I would like to found out which rows these are and look at them. If the csv's weren't broken I would just use pandas and do: df = pd.read_csv("file.csv") But this isn't suitable for data cleaning and preprocessing I need to do. How can I find the number of fields in each row in a "csv" file? Is it, for example, possible to just read in one row at a time, without remembering the number of fields from previous rows?
tagged with: python
has title: How to count the number of fields in each row of a broken csv
accepted answer: http://stackoverflow.com/a/50768670

http://stackoverflow.com/q/50794929
tagged with: python
answer count: 0
upvote count: 1
downvote count: 1
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/88602784
score: 0
has comment: http://stackoverflow.com/comment/88595783
has body: I'm downloading the html of one site and prettify it with beautiful soup like this: f_page_soup = Soup(f_driver.page_source, "lxml") with open(f_filename_pretty, 'wb') as f_output: f_output.write(f_page_soup.prettify(encoding='utf-8')) and open the prettified html like this: ecjData = open(filename, 'r', encoding='utf-8').read() pageSoup = Soup(ecjData, "lxml") Inside the html are different links that I want to collect with BeautifulSoup. One of them looks like this example.com/weiß/3 After iterating over all the links I want to print them. Doing this: print ("https://example.com" + a["href"]) gives me a UnicodeEncodeError for the link above as expected. So after catching the error I try to decode it: print (("https://example.com" + a["href"]).encode('utf-8').decode('latin-1')) which results in 'ascii' codec can't encode characters in position 78-79: ordinal not in range(128) Another approach I tried, was to replace inside the string: print (str(("https://example.com" + a["href"]).encode('utf-8')).replace('\\xc3\\x9f','ß')) which then leads again to: 'ascii' codec can't encode character '\xdf' in position 80: ordinal not in range(128) Basically what I need to be printed is: "https://example.com/weiß/3" How can I achieve this? I'm using python 3.5.
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
has title: Python encoding '\xdf' / '\xc3\x9f' to 'ß'

http://stackoverflow.com/comment/88638072
has text: Where is exists this a command window?
score: 0
comment on: http://stackoverflow.com/q/50816382
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50808100
has body: My code for ic2 is. import argparse import smbus import time bus = smbus.SMBus(1) bus.write_byte_data(0x20, 0x00, 0x00) bus.write_byte_data(0x20, 0x01, 0x00) bus.write_byte_data(0x20, 0x14, 0x01) time.sleep(0.5) bus.write_byte_data(0x20, 0x12, 0x00) time.sleep(0.5) It work fine. And I test this code. import argparse import sys var1 = sys.argv[1] var2 = sys.argv[2] var3 = sys.argv[3] print 'Params=', var1, var2, var3 By python test.py 0x20 0x14 0x01 Params= 0x20 0x14 0x01 But when I try code to. import argparse import sys import smbus import time var1 = sys.argv[1] var2 = sys.argv[2] var3 = sys.argv[3] bus = smbus.SMBus(1) bus.write_byte_data(0x20, 0x00, 0x00) bus.write_byte_data(0x20, 0x01, 0x00) bus.write_byte_data(var1, var2, var3) time.sleep(0.5) bus.write_byte_data(0x20, 0x12, 0x00) time.sleep(0.5) python test.py 0x20 0x14 0x01 Traceback (most recent call last): File "test.py", line 16, in bus.write_byte_data(var1, var2, var3) TypeError: an integer is required How can I fix it?
linked to: http://stackoverflow.com/q/21879454
type: AnsweredQuestion
has title: Python pass input string which has spaces and use for smbus
score: 1
has comment: http://stackoverflow.com/comment/88621959
type: Question
has answer: http://stackoverflow.com/a/50808180
accepted answer: http://stackoverflow.com/a/50808180
has comment: http://stackoverflow.com/comment/88622288
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/209513
tagged with: smbus
favorite count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88410139
comment on: http://stackoverflow.com/q/50699759
has text: What's the condition that you want to test before? take a look at this [answer](https://stackoverflow.com/a/50113495/5644965)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50831445
tagged with: tfidfvectorizer
type: UnansweredQuestion
tagged with: python
has body: var_vector = TfidfVectorizer() train_var = var_vector.fit_transform(t_df['var']) top_100 = np.array(var_vector.get_feature_names()) tfidf_100 = np.argsort(var_vector.idf_)[::-1] n = 100 top_n = top_100[tfidf_100][:n] How do I update the dimensionality to 100 after selecting top 100 words from tfidf Vectorizer?
score: 1
has answer: http://stackoverflow.com/a/50831527
has title: Select only top n features from Tfidf Vectorizer
upvote count: 1
type: Question
tagged with: nltk
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88650861
type: Comment
type: QuestionComment
has text: You are missing a closing bracket where you call `get_previous_month` also you cannot call `get_previous_month` like you do. See here on how you can call static functions: https://stackoverflow.com/questions/14340679/python-possible-to-call-static-method-from-within-class-without-qualifying-the. Basically you need to do `MyClass.get_previous_month...`
comment on: http://stackoverflow.com/q/50822854
score: 0

http://stackoverflow.com/comment/88561999
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50761073
type: Comment
has text: try ti check your mask shape with mask.shape Can you save hsv and provide the image so that I can send you a code without error?

http://stackoverflow.com/q/50768522
type: Question
upvote count: 4
has title: How to specify the type of a function input and output without using assert?
accepted answer: http://stackoverflow.com/a/50768563
tagged with: function
downvote count: 0
tagged with: variables
score: 4
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/88544670
tagged with: types
answer count: 1
favorite count: 0
has body: I am using Python 3.6 and would like to define a function that takes two integers a and b and returns their division c = a//b. I would like to enforce the input and output types without using assert. My understanding from what I have found in the documentations and on this site is that one should define this function as such: def divide(a: int, b: int) -&gt; int: c = a // b return c divide(3, 2.) # Output: 1.0 I was expecting an error (or a warning) since b and c are not integers. What is the issue with my particular code? How can I specify input and output types correctly without using assert in general?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50768563
has comment: http://stackoverflow.com/comment/88545249

http://stackoverflow.com/comment/88478637
has text: I'm afraid I see no elements with class name `job-company-name`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50729310
type: Comment

http://stackoverflow.com/comment/88705178
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50850974
has text: Works fine with print(int(datetime.utcnow().timestamp() * 1000))

http://stackoverflow.com/a/50768563
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50768522
downvote count: 0
type: Answer
has body: Enforcing runtime validation is currently only done by user code, for example using a 3rd party library. One such choice is enforce: &gt;&gt;&gt; import enforce # pip install enforce &gt;&gt;&gt; @enforce.runtime_validation ... def divide(a: int, b: int) -&gt; int: ... c = a // b ... return c ... ... &gt;&gt;&gt; divide(3, 2.0) RuntimeTypeError: The following runtime type errors were encountered: Argument 'b' was not of type &lt;class 'int'&gt;. Actual type was float.
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50768522

http://stackoverflow.com/comment/116790242
comment on: http://stackoverflow.com/a/57845418
type: AnswerComment
score: 50
type: Comment
has text: For those following this thread and getting odd path references in `requirements.txt`, use `pip list --format=freeze > requirements.txt` instead. Ref: https://stackoverflow.com/a/62886215/13095028

http://stackoverflow.com/q/50752532
has comment: http://stackoverflow.com/comment/88533743
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/27835619
answer count: 1
tagged with: edgar
has body: Last year I wrote a Python script to query the SEC's EDGAR database to retrieve their index of company filings for various years and quarters. At the time, the script worked fine but I recently picked it back up only to find that now I receive SSL: CERTIFICATE_VERIFY_FAILED errors whenever running it. I did an SSL Server test on the the following path: https://www.sec.gov/Archives/edgar/full-index/2018/QTR2/company.idx The report indicates all passes for the certificate (linked here) Also interestingly, if you navigate directly to the path in browser, an "Access Denied" error is returned. If I'm remembering correctly, in the past this would have led to the index file being downloaded. I know that the SEC's EDGAR database has recently gone through some restructuring as they no longer support FTP services. Does anyone have any idea what might be happening here and why I get SSL errors? For further background, I'm using urllib.request.urlopen() Thanks in advance.
score: 0
tagged with: ssl
has title: SSL error with Python but server test gives all A+ ratings
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88514618
tagged with: finance
has answer: http://stackoverflow.com/a/51004661

http://stackoverflow.com/comment/88596858
comment on: http://stackoverflow.com/a/50793152
type: AnswerComment
has text: Thanks, give me a sec.
score: 0
type: Comment

http://stackoverflow.com/q/50769693
has comment: http://stackoverflow.com/comment/88547188
favorite count: 0
has comment: http://stackoverflow.com/comment/88547228
has body: I wanted to use string formatting instead of this messy way data=(1, 8) a=((list(range((data[0]), ((data[-1])+1))))) print (a) but when I tried to use string formatting I had a syntax error data=(1, 8) a=((list(range(%f,%f))) % data) print(a) I tried %s instead of %f data=(1, 8) a=((list(range(%s,%s))) % data) print(a)
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/88546817
upvote count: 0
tagged with: list
has answer: http://stackoverflow.com/a/50770107
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/50769871
has title: string formatting with lists doesn't work in python
type: Question
has comment: http://stackoverflow.com/comment/88546802
has comment: http://stackoverflow.com/comment/88547231
score: -2
has comment: http://stackoverflow.com/comment/88546856
has comment: http://stackoverflow.com/comment/88546906
answer count: 2
has comment: http://stackoverflow.com/comment/88546799

http://stackoverflow.com/comment/88459068
comment on: http://stackoverflow.com/a/50723626
has text: You are welcome. If this solved your problem, could you please mark this question as solved, so it will help others in the future? Thank you.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50838369
type: AnsweredQuestion
has body: I have a data frame with activities and duration as columns. duration = np.random.randint(4, size = 30) activities = ['work', 'home', 'work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home','work', 'home', 'work', 'home'] activity_df = pd.DataFrame({'activities':activities, 'duration':duration}) I want to iterate through the rows and calculate the mean of the duration of the last 3 works and put it as a new feature. Any of you guys know how to do it? my output should be a third column where in each row the previous 3 same activities are calculated Thank you in advance!
score: 1
tagged with: dataframe
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/50838435
downvote count: 0
favorite count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50838433
has answer: http://stackoverflow.com/a/50838433
has title: Filter the previous 3 rows with the same string and calculate the mean in python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50838435
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88469588
comment on: http://stackoverflow.com/q/50730946
score: 0
type: Comment
type: QuestionComment
has text: Did you try uninstalling it as root? There have been times where sudo hasn't been enough and I had to `sudo su` it

http://stackoverflow.com/a/50838061
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50837066
answers question: http://stackoverflow.com/q/50837066
type: Answer
score: 1
upvote count: 1
has body: Probably not the most efficient way, but you could try something like this: def foo(l,n): #Get all of the starting sequences first_n = [list(x) for x in set([tuple(x[:n]) for x in l])] #Figure out which of those starting sequences are duplicated duplicates = [] for starting_sequence in first_n: if len([x for x in l if x[:n] == starting_sequence])&gt;2: duplicates.append(starting_sequence) #make changes result = [] for x in l: if x[:n] in duplicates: result.append([" ".join(x[:n])]+x[n:]) else: result.append([" ".join(x)]) return result Set's have no repeats, but elements of sets must be hashable. Since lists are unhashable, that is why I have converted them into tuples and then back into lists.
type: AcceptedAnswer

http://stackoverflow.com/q/50750918
favorite count: 0
has comment: http://stackoverflow.com/comment/88509743
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Divide two dataframes with groupby in Python
has answer: http://stackoverflow.com/a/50751337
score: 1
tagged with: dataframe
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/50751337
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/88510116
answer count: 1
has body: I'm trying to figure out how to divide two columns from different datasets, grouping by a common key, in order to obtain a percentage. Table 1 Index ID sum 0 100001 7 1 100002 8 2 100003 4 Table 2 Index ID TYPE sum 0 100001 A 7 1 100002 A 4 2 100002 B 4 3 100003 A 2 4 100003 B 2 I want to divide the variable sum from table 1 by sum from table 2, grouping by ID and TYPE. The goal is to obtain the table bellow, which represents the percentage of sum by TYPE and ID. Table 3 Index ID TYPE sum_percent 0 100001 A 1.0 1 100002 A 0.5 2 100002 B 0.5 3 100003 A 0.5 4 100003 B 0.5 I was trying some codes to achieve this question, like this one bellow but it throws an error message. It seems that the problem is in the groupby statement. `table_1'sum'.groupby('ID')/table_2'sum'.groupby('ID')`
has comment: http://stackoverflow.com/comment/88510004

http://stackoverflow.com/comment/88459988
comment on: http://stackoverflow.com/a/50725409
type: Comment
score: 0
type: AnswerComment
has text: That's a nice idea, but it doesn't quite work in my context. If I were to now append `f` to some list each time within a loop and then execute any member of the list at a later point, I just get the latest definition of `f` again.

http://stackoverflow.com/q/50768752
type: Question
has answer: http://stackoverflow.com/a/50768796
has title: How to create a different class type depending on variable number of arguments
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: I have some python code which I would like to modularise: list1 = [] list2 = [] list3 = [] . . . for s in list3: if object in list1: e = Class1(arg1, arg2, s) else: e = Class2(arg3, arg4, arg5, s) x(e) y(e) z(e) I would like to replace the IF statement such that I can put the FOR loop and body within a method and pass in e, even though it can be one of two classes: def my_method(self, list, e): for object in list: x(e) y(e) z(e) and then simply call my_method() twice, once for list1 and again for list2: # How/where do I "create" e1 and e2, given I need s, which is inside my_method()? my_method(list1, e1) my_method(list2, e2) However, I am unsure how to create/pass in e, given it can represent two different class types, taking a different number of arguments and the last argument s is only known inside my_method().

http://stackoverflow.com/comment/88665611
has text: In [10]: import pandas as pd In [11]: import numpy as np In [12]: df = pd.DataFrame({'start': [1, 2, 3], 'end': [7, 9, 9]}) In [13]: df Out[13]: end start 0 7 1 1 9 2 2 9 3 In [14]: def fun(df): ...: return pd.Series(np.arange(df['start'], df['end'], 1)) ...: In [15]: df.apply(fun, axis=1) Out[15]: 0 1 2 3 4 5 6 0 1.0 2.0 3.0 4.0 5.0 6.0 NaN 1 2.0 3.0 4.0 5.0 6.0 7.0 8.0 2 3.0 4.0 5.0 6.0 7.0 8.0 NaN
comment on: http://stackoverflow.com/q/50830683
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50793868
answer count: 2
has comment: http://stackoverflow.com/comment/88594213
has body: import matplotlib.pyploy as plt import cv2 def getFrame(cap): frameRate = 25 frameId = cap.get(cv2.CAP_PROP_POS_FRAMES) ret, frame = cap.read() if not ret: return None print frameId if frameId &lt; 0: return None if not (frameId % int(frameRate)): cap.set(cv2.CAP_PROP_POS_FRAMES, frameId + frameRate) return frame return None videoFile = 'filename.webm' cap = cv2.VideoCapture(videoFile,cv2.CAP_FFMPEG) image = getFrame(cap) plt.imshow(image) cap.set(cv2.CAP_PROP_POS_FRAMES,4000.0) image = getFrame(cap) while(image is not None): plt.imshow(image) image = getFrame(cap) cap.release() I'm running the above code in a while loop and displaying the image. It seems that after around 4250 frames, the frame returned will be the same as the frame at the start. This loop continue after another 4250 frames. The file I'm reading is mp4 and webm file. The behavior is the same for both types of file. videoCapture is using FFMPEG backend. Opencv version = 3.4.1, python 2.7 . Another notable behaviour is the reading of the frame slows down as the frame increases and then went back to fast again after 4250 frames. Edit: I edited the code. I think you can try running this with mp4/webm file longer than 5 minutes. I can't upload the video due to privacy reason because it is recorded in office. When I modified the code with only cap.read(), the error disappears. I suspect this is something to do with cap.set()
has answer: http://stackoverflow.com/a/50808318
has comment: http://stackoverflow.com/comment/88595903
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50797480
type: Question
tagged with: opencv
tagged with: video-capture
has title: OpenCV VideoCapture on Large files looping back to the start frame after 4000+ frames
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/50736830
score: 1
has title: How to cluster Named Entity using StanfordNER using python
tagged with: named-entity-recognition
has answer: http://stackoverflow.com/a/51705630
type: Question
accepted answer: http://stackoverflow.com/a/51705630
tagged with: stanford-nlp
tagged with: nltk
downvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/15173225
has body: Stanford NER provides it NER jars to detect POS tags and NERs. But I am facing one issue with one of the sentences when trying to parse. The sentence is as follows: Joseph E. Seagram &amp; Sons, INC said on Thursday that it is merging its two United States based wine companies Below is my code st = StanfordNERTagger('./stanford- ner/classifiers/english.all.3class.distsim.crf.ser.gz', './stanford-ner/stanford-ner.jar', encoding='utf-8') ne_in_sent = [] with open("./CCAT/2551newsML.txt") as fd: lines = fd.readlines() for line in lines: print(line) tokenized_text = word_tokenize(line) classified_text = st.tag(tokenized_text) ne_tree = stanfordNE2tree(classified_text) for subtree in ne_tree: # If subtree is a noun chunk, i.e. NE != "O" if type(subtree) == Tree: ne_label = subtree.label() ne_string = " ".join([token for token, pos in subtree.leaves()]) ne_in_sent.append((ne_string, ne_label)) print(ne_in_sent) when I parse it I get the following entities as the organization. (Joseph E. Seagram &amp; Sons, Organization) and (Inc, Organization) Also for some other texts in the file like TransCo has a very big plane. Transco is moving south. It differentiates the organizations due to capitalization hence I get 2 entities (TransCo, organization) and (Transco, organization). Is it possible to convert these into one entity?
tagged with: python
tagged with: nlp
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/88643258
type: Comment
comment on: http://stackoverflow.com/a/50787340
score: 0
type: AnswerComment
has text: I am using the daemon mode. Thanks

http://stackoverflow.com/q/50725394
score: 0
has answer: http://stackoverflow.com/a/50725495
has title: Getting Pip to install in specific Python versions for IBM Watson use
tagged with: python
has body: I have two versions of Python in my /usr/bin directory. Python2.7 and Python3.6. Entering "Python --version" in a terminal I get "Python 2.7.15" back. I'd like to add watson_developer_cloud to 2.7. However when I enter pip install watson_developer_cloud watson_developer_cloud shows up in /usr/lib/Python3.6 and not /usr/lib/Python2.7. Question: How do I get watson_developer_cloud in Python2.7? I am trying to get Watson speech-to-text configured to use sttClient.py. Thanks in advance.
tagged with: speech-to-text
tagged with: pip
has comment: http://stackoverflow.com/comment/88459051
has comment: http://stackoverflow.com/comment/88459228
type: AnsweredQuestion
tagged with: watson
has comment: http://stackoverflow.com/comment/88461122
type: Question
accepted answer: http://stackoverflow.com/a/50725495
linked to: http://stackoverflow.com/q/2812520
answer count: 1
has comment: http://stackoverflow.com/comment/88459330

http://stackoverflow.com/comment/88548437
has text: What version of Ipython? (`ipython --version`). Did you install Jupyter before or after Python2?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50770394
score: 1

http://stackoverflow.com/comment/88662793
comment on: http://stackoverflow.com/q/50816945
has text: I am working on PyQt GUI platform along with pyqtgraph.1. I want to display a sequence of images on the QGraphics View at high speed, but following `ImageItem-video` example of pyqtgraph made it look like animation which is not I require.2. I wanted to know the options to do so. Hence the post.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88496701
type: Comment
comment on: http://stackoverflow.com/a/50734157
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172697/discussion-between-00-00-00-and-jezrael).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88673502
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50834528
has text: Also which line is generating the error? I can see things I think would generate the error but without a few lines of the actual data I can't be sure.

http://stackoverflow.com/q/50784147
tagged with: selenium
has comment: http://stackoverflow.com/comment/88576249
has comment: http://stackoverflow.com/comment/88599041
type: Question
answer count: 1
has title: How to check if GUI application is running on Ubuntu?
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/88639009
has comment: http://stackoverflow.com/comment/88574790
has body: I have a GUI app, that was written with c++ and QT and I have UI tests with selenium + qtwebdriver. my bash script launches app and then launches python tests. The problem is, if I write this: ./myapp python mypythonscript.py Python script will fail because, "myapp" need 2 seconds to open interface. What can I do to find out, if GUI app is completely running ? Is there any command to X server, that can return name of launched windows ?
has answer: http://stackoverflow.com/a/50784656
has comment: http://stackoverflow.com/comment/88574810
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/88574726
tagged with: qt
has comment: http://stackoverflow.com/comment/88604332
score: 1

http://stackoverflow.com/a/50763090
has body: If your csv file is in the same working directory as your .py code, you use directly import pandas as pd df=pd.read_csv('Project_Wind_Data.csv'), usecols = ['U100', 'V100']) If the file is in another directory, replace 'Project_Wind_Data.csv' with the full path to the file like c:User/Documents/file.txt
answers question: http://stackoverflow.com/q/50762779
has comment: http://stackoverflow.com/comment/88535179
score: 0
has comment: http://stackoverflow.com/comment/88536423
type: Answer

http://stackoverflow.com/comment/88519050
score: 0
type: Comment
has text: On your third code snippet, you can replace the 2-lines inside the `for` loop with `merged.extend(element.split(','))`. nice answer however!
type: AnswerComment
comment on: http://stackoverflow.com/a/50755564

http://stackoverflow.com/comment/88540359
comment on: http://stackoverflow.com/a/50765334
has text: I don't get any errors! which actually makes the whole thing more confusing haha. The frame f3 just doesn't rise when button2 is pressed. Sorry for being such a novice, but it's the only way improve!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50828668
has body: You could modify the code from the HandlingExceptions - Python Wiki: def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 elif number % 2 == 1: print(3 * number + 1) return 3 * number + 1 has_input_int_number = False while has_input_int_number == False: try: # try to convert user input into a int number x = int(input("Enter a number: ")) has_input_int_number = True # will only reach this line if the user inputted a int while x != 1: x = collatz(x) except ValueError: # if it gives a ValueError print("Error: Please enter a numerical int value.") Example Usage: Enter a number: a Error: Please enter a numerical int value. Enter a number: 1.5 Error: Please enter a numerical int value. Enter a number: 5 16 8 4 2 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50828606
score: 1
answers question: http://stackoverflow.com/q/50828606
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88710723
type: Comment
has text: I just geuss that problem isn't in `- (minus)` operation because we got `TypeError: Cannot compare type 'Timestamp' with type 'int'` so maybe the data structure got some sorting or index ? –
type: QuestionComment
comment on: http://stackoverflow.com/q/50853735
score: 0

http://stackoverflow.com/comment/88663963
comment on: http://stackoverflow.com/a/50817013
has text: Thank You, I will check it out and come back if I have questions :)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88604166
score: 0
type: Comment
type: QuestionComment
has text: Look up "strict weak ordering" before you get too far into that. You may want to sort by a function which takes the shooting, passing, and dribbling scores, then returns a grand composite score.
comment on: http://stackoverflow.com/q/50796746

http://stackoverflow.com/comment/88904232
has text: Converting the `example_list` into a dictionary to do the lookup may speed up (and simplify) the program.
type: AnswerComment
comment on: http://stackoverflow.com/a/50848116
score: 0
type: Comment

http://stackoverflow.com/q/50742235
has title: Python packaging dependencies
tagged with: packaging
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88492106
tagged with: python
accepted answer: http://stackoverflow.com/a/50742520
has comment: http://stackoverflow.com/comment/88492509
score: 2
type: AnsweredQuestion
has body: Simple quick question... say I have a self created package called miscfun where some module/script in there looks like... # helper.py import re import os def foo(x): # Do something with re def bar(x): # Do something with os After setting up a proper setup.py etc.. I can then 'install' my package and load it using import miscfun.helper However, what I discovered just now is that I can also call miscfun.helper.os or miscfun.helper.re to 'use' the re and os modules! Isnt that weird and confusing? Can I somehow prevent this from happening? (If this is not a normal situation, I'll gladly explain more, but for now I hope this suffices)
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50742520

http://stackoverflow.com/a/50819022
upvote count: 1
has body: Not completely sure, but I'm assuming you're filtering down to only one object in your database but still receiving multiple. In my experience, this is because pagination and filter sets sometimes have a hard time. Check out this question
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50818756

http://stackoverflow.com/q/50776214
answer count: 0
upvote count: 2
has title: Boto incorrectly loading IAM credentials when more then one rule is used in a ROLE
type: Question
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/92293914
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/92289197
tagged with: amazon-ec2
downvote count: 0
favorite count: 0
has body: I'm fairly new to Boto and AWS. Can someone provide clarity on the error below? I want BOTO from within an EC2 instance to have access to s3 and SSM services by inheriting the credentials given to it by the IAM role attached to the instance. I am doing this in the Amazon Linux IAM. Using Python2 within miniconda2. I get the following credentials error when I try to connect to s3. import boto boto.connect_s3() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/root/miniconda2/lib/python2.7/site-packages/boto/__init__.py", line 141, in connect_s3 return S3Connection(aws_access_key_id, aws_secret_access_key, **kwargs) File "/root/miniconda2/lib/python2.7/site-packages/boto/s3/connection.py", line 194, in __init__ validate_certs=validate_certs, profile_name=profile_name) File "/root/miniconda2/lib/python2.7/site-packages/boto/connection.py", line 555, in __init__ profile_name) File "/root/miniconda2/lib/python2.7/site-packages/boto/provider.py", line 201, in __init__ self.get_credentials(access_key, secret_key, security_token, profile_name) File "/root/miniconda2/lib/python2.7/site-packages/boto/provider.py", line 377, in get_credentials self._populate_keys_from_metadata_server() File "/root/miniconda2/lib/python2.7/site-packages/boto/provider.py", line 394, in _populate_keys_from_metadata_server creds = self._get_credentials_from_metadata(metadata) File "/root/miniconda2/lib/python2.7/site-packages/boto/provider.py", line 424, in _get_credentials_from_metadata "%s" % (msg)) boto.exception.InvalidInstanceMetadataError: Expected a dict type of credentials instead received an empty string You can set the 'metadata_service_num_attempts' in your boto config file to increase the number of times boto will attempt to retrieve credentials from the instance metadata service. The above code works when I give it a IAM role with a single policy that looks as follows: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92295422
tagged with: boto
score: 2
has comment: http://stackoverflow.com/comment/88568849

http://stackoverflow.com/a/50735347
answers question: http://stackoverflow.com/q/50735149
type: Answer
accepted answer of: http://stackoverflow.com/q/50735149
has body: I believe need omit loop, because if train is DataFrame then dataset are columns names, obviously strings: np.random.seed(100) train = pd.DataFrame(np.random.randint(10, size=(3,3)), columns=['age','col1','col2']) print (train) age col1 col2 0 8 8 3 1 7 7 0 2 4 2 5 for dataset in train: print (dataset) age col1 col2 train.loc[(train['age'] &gt; 15) &amp; (train['age'] &lt;= 25), 'new'] = 1 train.loc[(train['age'] &gt; 25) &amp; (train['age'] &lt;= 35), 'new'] = 2 train.loc[(train['age'] &gt; 35) &amp; (train['age'] &lt;= 45), 'new'] = 3 train.loc[(train['age'] &gt; 45) &amp; (train['age'] &lt;= 55), 'new'] = 4 train.loc[ train['age'] &gt; 55, 'new'] = 5 Better is use pd.cut: r = [0, 25, 35, 45, 55, 120] g = [1,2,3,4,5] train['new'] = pd.cut(train['age'], bins=r, labels=g)
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88662979

http://stackoverflow.com/a/50768236
has body: For what you appear to be doing, I'm not sure you need to use Pandas dataframe. Something like: lat = query_lat.fetchone() long = query_long.fetchone() map_hooray = folium.Map(location=[lat[0], long[0]], zoom_start =11) May work for you. Unless of course you need the dataframe for other purposes.
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50767883
upvote count: 1

http://stackoverflow.com/a/51997797
has comment: http://stackoverflow.com/comment/94473534
has comment: http://stackoverflow.com/comment/130300845
has comment: http://stackoverflow.com/comment/98324999
upvote count: 13
score: 12
has body: The problem is that fit method requires an evaluation set created externally, but we cannot create one before the transformation by the pipeline. This is a bit hacky, but the idea is to create a thin wrapper to the xgboost regressor/classifier that prepare for the evaluation set inside. from sklearn.base import BaseEstimator from sklearn.model_selection import train_test_split from xgboost import XGBRegressor, XGBClassifier class XGBoostWithEarlyStop(BaseEstimator): def __init__(self, early_stopping_rounds=5, test_size=0.1, eval_metric='mae', **estimator_params): self.early_stopping_rounds = early_stopping_rounds self.test_size = test_size self.eval_metric=eval_metric='mae' if self.estimator is not None: self.set_params(**estimator_params) def set_params(self, **params): return self.estimator.set_params(**params) def get_params(self, **params): return self.estimator.get_params() def fit(self, X, y): x_train, x_val, y_train, y_val = train_test_split(X, y, test_size=self.test_size) self.estimator.fit(x_train, y_train, early_stopping_rounds=self.early_stopping_rounds, eval_metric=self.eval_metric, eval_set=[(x_val, y_val)]) return self def predict(self, X): return self.estimator.predict(X) class XGBoostRegressorWithEarlyStop(XGBoostWithEarlyStop): def __init__(self, *args, **kwargs): self.estimator = XGBRegressor() super(XGBoostRegressorWithEarlyStop, self).__init__(*args, **kwargs) class XGBoostClassifierWithEarlyStop(XGBoostWithEarlyStop): def __init__(self, *args, **kwargs): self.estimator = XGBClassifier() super(XGBoostClassifierWithEarlyStop, self).__init__(*args, **kwargs) Below is a test. from sklearn.datasets import load_diabetes from sklearn.pipeline import Pipeline from sklearn.decomposition import PCA from sklearn.model_selection import GridSearchCV x, y = load_diabetes(return_X_y=True) print(x.shape, y.shape) # (442, 10) (442,) pipe = Pipeline([ ('pca', PCA(5)), ('xgb', XGBoostRegressorWithEarlyStop()) ]) param_grid = { 'pca__n_components': [3, 5, 7], 'xgb_…
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50824326
answers question: http://stackoverflow.com/q/50824326
type: Answer

http://stackoverflow.com/comment/111962239
comment on: http://stackoverflow.com/q/50703968
type: Comment
has text: I don't think this is explicit to the Scatter plot, or is it? Also a fillcolor is inherently filling an area, right?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/107003432
has text: Should now use `LiteralScalarString` rather than `PreservedScalarString` - [3e6f42ae9af](https://github.com/pycontribs/ruamel-yaml/commit/3e6f42ae9af01be068633f78d9ae1286a0177023#diff-bc302abdb15db813fee364f35aa40f4f)
comment on: http://stackoverflow.com/a/50853272
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50791392
has comment: http://stackoverflow.com/comment/88589130
has body: Set return_inverse=True: vals = np.array(['a', 'b', 'c', 'b', 'a']) u, indices = np.unique(vals, return_inverse=True) print(u) # ['a' 'b' 'c'] print(indices) # [0 1 2 1 0]
score: 1
answers question: http://stackoverflow.com/q/50791311
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50791311

http://stackoverflow.com/a/50763860
answers question: http://stackoverflow.com/q/50763445
upvote count: 1
has body: I am not sure if you are using pandas but you can easily parse your response dict into a pandas.DataFrame with the following code import pandas as pd pd.DataFrame([[entr['VarCharValue'] for entr in r['Data']] for r in response['ResultSet']['Rows'][1:]], columns = [r['VarCharValue'] for r in response['ResultSet']['Rows'][0]['Data']])
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88534543
type: QuestionComment
has text: It is not possible to calculate `(a @ b)`, but is it possible to calculate `np.dot(a[np.unique(rows),:], b[:,np.unique(cols)])` ? Of course, it strongly depends on the nature of your `rows` and `cols` vectors.
comment on: http://stackoverflow.com/q/50757847
score: 0
type: Comment

http://stackoverflow.com/q/50797440
favorite count: 0
has answer: http://stackoverflow.com/a/50797510
upvote count: 2
has title: Split the results from os.popen
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88600935
accepted answer: http://stackoverflow.com/a/50797510
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50797613
has body: I'm using python3.6 for automatically finding some files in my computer: import os criteria = 'something' file_names = os.popen('find dir -name "*%s*"' % criteria).read() for file_name in file_names: #do something pass The problem is that by doing .read(), all the file names including some criteria is concatenated into one string. How can I get a list of file names as output in order to iterating in the 'for' loop? Thanks a lot
linked to: http://stackoverflow.com/q/5749195
tagged with: linux
possible better answer: http://stackoverflow.com/a/50797613

http://stackoverflow.com/comment/88681714
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50838786
type: Comment
has text: Updated snippet.

http://stackoverflow.com/comment/88681871
score: 0
type: Comment
has text: @jpp I am out, not understanding logic...
type: QuestionComment
comment on: http://stackoverflow.com/q/50838763

http://stackoverflow.com/q/50817844
has comment: http://stackoverflow.com/comment/88641741
has comment: http://stackoverflow.com/comment/88641437
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: string-interpolation
has comment: http://stackoverflow.com/comment/88642027
score: 0
has body: I have a string containing an encoded password that I would like to decode. Is there a way to do this using string formatting (or any other method)? For example: decode_passwords = lambda password: password # plus some decoding logic.. string = "Password: {some_value}" decoded_string = string.format(decode_passwords)
has title: Is it possible to format strings using functions in Python?
tagged with: python-3.x

http://stackoverflow.com/q/50727667
has body: I have a dataframe as below: id timestamp name 1 2018-01-23 15:49:53 "aaa" 1 2018-01-23 15:54:56 "bbb" 1 2018-01-23 15:49:57 "bbb" 1 2018-01-23 15:49:54 "ccc" This is one example of group of id from my data. I have several groups of ids. What I am trying to do is to collapse each group into a row but in a chronological order according to timestamp eg like this id name 1 aaa-&gt;ccc-&gt;bbb-&gt;bbb The values in name are in chronological order as they appear with timestamp. Any pointers regarding this ?
has title: collapse group into one row pandas dataframe
type: UnansweredQuestion
type: Question
upvote count: 4
answer count: 1
downvote count: 0
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/50727859
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/97753933
has text: this is the import to use OPYImage from openpyxl.drawing.image import Image as OPYImage
comment on: http://stackoverflow.com/a/51469741
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50737170
tagged with: python
has comment: http://stackoverflow.com/comment/88487085
has answer: http://stackoverflow.com/a/50754361
tagged with: qthread
has comment: http://stackoverflow.com/comment/88494477
has body: I have a thread where I need to execute a heavy function. First, I have a function that takes two QDateTime values from the GUI and convert them to UNIX timestamps. Secondly, the "heavy" function uses these values to perform a task. Both functions (function_task, time_converter_to_unix) do not belong to any class, so as far as I know I can use them in the thread. But not the parameters, since I cannot access the QDateTime values. Error: AttributeError: 'TaskThread' object has no attribute 'startTime' How can I access the QDateTime and read the content from the thread? Thank you. EDIT: Complete Code. You can find also the link to the GUI in the following link: interface.ui import sys import datetime import time from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import * from PyQt4.QtGui import * # Link to GUI qtCreatorFile = "interface.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) def time_converter_to_unix(start_datetime, end_datetime): # Convert QTimeEdit to UNIX Timestamp (int, msec included), and then to float start_datetime_unix_int = start_datetime.toMSecsSinceEpoch () start_datetime_unix = (float(start_datetime_unix_int) / 1000) end_datetime_unix_int = end_datetime.toMSecsSinceEpoch () end_datetime_unix = (float(end_datetime_unix_int) / 1000) return start_datetime_unix, end_datetime_unix def dummy_function(self, start_datetime_unix, end_datetime_unix): # Dummy function, just to simulate a task result = start_datetime_unix + end_datetime_unix print result class Tool(QtGui.QMainWindow, Ui_MainWindow): def __init__(self, parent = None): # Setting-ip UI QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # Button Action self.runButton.clicked.connect(self.onStart) # Progress Bar and Label. At the begining, the bar is at 0 self.progressBar.setValue(0) self.progressBar.setRange(0,100) self.resultLabel.setText("Waiting...") #Thread self.myLongTask = TaskThread() self.myLongTask.taskFinished.connect(self.onFinished) de…
score: 0
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88483953
has comment: http://stackoverflow.com/comment/88516276
has comment: http://stackoverflow.com/comment/88495023
answer count: 1
has title: How can I use a QDateTime inside a Thread?
has comment: http://stackoverflow.com/comment/88516516
has comment: http://stackoverflow.com/comment/88482538
tagged with: pyqt4
accepted answer: http://stackoverflow.com/a/50754361
tagged with: pyqt
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88483592
has comment: http://stackoverflow.com/comment/88484016
type: Question
has comment: http://stackoverflow.com/comment/88495110

http://stackoverflow.com/comment/88695313
score: 0
comment on: http://stackoverflow.com/q/50845534
type: QuestionComment
type: Comment
has text: Okay, I understand you but do not expect more than 60FPS, your calculation of FPS is not correct, you are only counting the time the function is executed _update(), that does not guarantee that the painting is 300FPS as you are printing, Qt and all libraries graph does not automatically update the view if not when necessary, for example 60FPS is 16.6ms, assume that you place the data in 2ms intervals only then only 1 of every 8 data will be shown. I can make it update but I indicate that your calculation is not real.

http://stackoverflow.com/comment/88696413
has text: Using a second process to monitor the first was my trivial solution, but it feels like overkill. Why I would want this is explained in the post, when I stop debugging the behavior is like process termination and its causing resource management issues. Also, since process monitoring is so trivial I was hoping there might be a built-in python way of doing it. An extra possible solution would be to intercept the signal calls for a specific process termination (also excessive).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50846073
type: AnswerComment

http://stackoverflow.com/comment/88465451
score: 0
type: AnswerComment
has text: The firstMonth variable changes every month I run the script i.e. the first Month right now is May, but next month it would be June.
comment on: http://stackoverflow.com/a/50728588
type: Comment

http://stackoverflow.com/a/50781250
has comment: http://stackoverflow.com/comment/88573427
has body: If you don't care about memory space the easiest way is by saving the whole graph (encoder and decoder) and when using it for prediction, you can pass the last layer of the encoder as the fetch argument. Tensorflow will only calculate to this point and you don't have any computational difference compared to only saving the encoder. Otherwise you can create two graphs (one for the encoder, one for the decoder) an train them at the same time and train them together. But this is I bit more complex.
type: Answer
answers question: http://stackoverflow.com/q/50778593
has comment: http://stackoverflow.com/comment/88573776
score: 0

http://stackoverflow.com/q/50785729
has title: Many If statements in Pandas
has answer: http://stackoverflow.com/a/50786195
possible better answer: http://stackoverflow.com/a/50786022
has body: I have a stock dataframe. And have many if statement to run to assign a value. c1 = np.where((blackCondition &amp; whitePCondition) &amp; (close_gt_oP &amp; open_ge_cP),'UP',None) c2 = np.where((blackCondition &amp; whitePCondition) &amp; (open_lt_cP &amp; close_le_oP),'DOWN',None) c3 = np.where((blackCondition &amp; whitePCondition) &amp; (close_gt_oP &amp; open_lt_cP),'OUTSIDE',None) c4 = np.where((blackCondition &amp; whitePCondition) &amp; (close_le_oP &amp; open_ge_cP),'INSIDE',None) #IF2 c5 = np.where((blackCondition &amp; blackPCondition) &amp; (open_gt_oP &amp; close_ge_cP),'UP',None) c6 = np.where((blackCondition &amp; blackPCondition) &amp; (close_lt_cP &amp; open_le_oP),'DOWN',None) c7 = np.where((blackCondition &amp; blackPCondition) &amp; (open_gt_oP &amp; close_lt_cP),'OUTSIDE',None) c8 = np.where((blackCondition &amp; blackPCondition) &amp; (open_le_oP &amp; close_ge_cP),'INSIDE',None) #IF3 c9 = np.where((whiteCondition &amp; whitePCondition) &amp; (close_gt_cP &amp; open_ge_oP),'UP',None) c10 = np.where((whiteCondition &amp; whitePCondition) &amp; (open_lt_oP &amp; close_le_cP),'DOWN',None) c11 = np.where((whiteCondition &amp; whitePCondition) &amp; (close_gt_cP &amp; open_lt_oP),'OUTSIDE',None) c12 = np.where((whiteCondition &amp; whitePCondition) &amp; (close_le_cP &amp; open_ge_oP),'INSIDE',None) #IF4 c13 = np.where((whiteCondition &amp; blackPCondition) &amp; (open_gt_cP &amp; close_ge_oP),'UP',None) c14 = np.where((whiteCondition &amp; blackPCondition) &amp; (close_lt_oP &amp; open_le_cP),'DOWN',None) c15 = np.where((whiteCondition &amp; blackPCondition) &amp; (open_gt_cP &amp; close_lt_oP),'OUTSIDE',None) c16 = np.where((whiteCondition &amp; blackPCondition) &amp; (open_le_cP &amp; close_ge_oP),'INSIDE',None) How can I assign TRUE VALUE of a statement to a column? df['pos'] = IF ANY OF THIS STATEMENT IS TRUE ex: if(c1) =&gt; df['pos'] = TRUE_CONDITION_OF_C1
tagged with: pandas
tagged with: python
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50786195
upvote count: 1
type: AnsweredQuestion
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50786022
downvote count: 0

http://stackoverflow.com/comment/88681684
type: Comment
comment on: http://stackoverflow.com/a/50838786
type: AnswerComment
score: 0
has text: @RanEldan. Try: `data = re.findall("\-?\d+\.\d+", line)`

http://stackoverflow.com/a/50765273
has body: You can set error_bad_lines to False and warn_bad_lines to False (if you don't, it will print out all bad lines to warn you). error_bad_lines : boolean, default True Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will dropped from the DataFrame that is returned. import pandas as pd df = pd.read_csv('./RF_P92_500_180_023_1.dat', sep='\t', skiprows=9, encoding='latin-1', error_bad_lines=False, warn_bad_lines=False) I ran the above on your provided file but you'll want to take time to verify it has all the lines you want to keep. Shape of resulting dataframe is (10269,9). Alternative, more hands-on approach since this file is in a non-standard format and I have no idea what your expected output looks like (how many columns do you expect?): import csv import pandas as pd # using csv with Pandas filename = 'RF_P92_500_180_023_1.dat' header = ['Zeit', 'Zyklus Zähler Zähler', 'Weg', 'Kraft', 'Dehnung', 'Temperatur', 'Temp. oben', 'Temp. mitte', 'Temp. untens', 'segments', 'mm', 'kN', '%', '°C', '°C', '°C', '°C'] data = [] with open(filename, 'r') as f: reader = csv.reader(f) for row in reader: if len(row) == 9: # flatten a list of lists into single list final_row = sum([item.split('\t') for item in row], []) data.append(final_row) df = pd.DataFrame(data=data, columns=header) print(df.shape) # (10046, 17)
has comment: http://stackoverflow.com/comment/88545938
has comment: http://stackoverflow.com/comment/88578589
answers question: http://stackoverflow.com/q/50764194
has comment: http://stackoverflow.com/comment/88541549
has comment: http://stackoverflow.com/comment/88553641
accepted answer of: http://stackoverflow.com/q/50764194
has comment: http://stackoverflow.com/comment/88606983
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88553004
has comment: http://stackoverflow.com/comment/88606563
has comment: http://stackoverflow.com/comment/88558626
has comment: http://stackoverflow.com/comment/88583492
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90780137
comment on: http://stackoverflow.com/a/51878585
type: AnswerComment
has text: In my case, many vectors could belong to the same cluster (ID) so I cannot reverse map them.
score: 0
type: Comment

http://stackoverflow.com/comment/88660202
score: 0
has text: "log scales don't like macs" - that's an interesting theory, but I suspect that you rather simply have a buggy version of matplotlib installed. You may update matplotlib and see if that fixes it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50825707

communication
tag name: communication
tags question: http://stackoverflow.com/q/50843832
type: Tag

http://stackoverflow.com/comment/88651648
type: Comment
has text: As in my answer, I think `min` + `enumerate` should give a one-pass solution.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50823194

http://stackoverflow.com/comment/88633836
score: 0
type: QuestionComment
has text: Do you need to write to the resulting array, or just calcluate based on it? You can easily make a view with [`as_strided`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.lib.stride_tricks.as_strided.html)
type: Comment
comment on: http://stackoverflow.com/q/50814434

http://stackoverflow.com/comment/88624197
score: 1
has text: If you are searching for a large number of consecutive nulls, there is an approach which is slightly longer but much more elegant than shifting over and over. I will update my answer soon.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50809282

http://stackoverflow.com/comment/88466868
type: QuestionComment
has text: @coldspeed can I have a bit of explanation ?
score: 0
comment on: http://stackoverflow.com/q/50729511
type: Comment

http://stackoverflow.com/q/50747459
tagged with: python
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has title: How to make a new table and specify a time_partitioning_field?
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/88502670
has body: Previously, I was creating time partitioned tables using the command line, so I had something like: bq mk --table --schema [MY SCHEMA] --time_partitioning_field the_dates --project_id=my_proj my_dataset.new_table How how would I convert that code to python while specifying the --time_partitioning_field command? I can't find any documentation to support it. What I have is: from google.cloud import bigquery client = bigquery.Client() dataset_name = 'my_dataset' table_name = 'new_table' schema = [ bigquery.SchemaField('the_dates', 'TIMESTAMP'), bigquery.SchemaField('a', 'FLOAT'), bigquery.SchemaField('b', 'FLOAT'), bigquery.SchemaField('c', 'FLOAT'), bigquery.SchemaField('d', 'FLOAT'), ] dataset_ref = client.dataset(dataset_name) table_ref = dataset_ref.table(table_name ) table = bigquery.Table(table_ref, schema=schema) table = client.create_table(table) Where or how do I specify the --time_partitioning_field flag?
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88502514
has answer: http://stackoverflow.com/a/50749279

http://stackoverflow.com/q/50702515
has comment: http://stackoverflow.com/comment/88415204
has body: I am working on a library/book program. One function I am coding involves getting input from a user to add a new book to the library. I keep getting this error that seems to involve the situation when no input is entered: Traceback (most recent call last): File "python", line 96, in File "python", line 89, in print_menu File "python", line 70, in add_book TypeError: must be str, not NoneType The steps for this are: First run the code and enter values for a new title, author or subject. Everything works. The new book is added to the library list. Then, try entering a new book again. When prompted to enter either a new title, author or subject, just press the ENTER key. The code will call the sub function again to ask for input for that item. Enter something the second time around. I added some code to print things as the code executes. The problem seems to be that the non-entry is being returned by the sub functions. But, I don't know why...which is why I posted here. library = [["Arctic Dreams", "Barry Lopez", "Nature Writing", 356, 2002], ["A Short History of Nearly Everything", "Bill Bryson", "Science", 405, 2001], ["Hiking the Buckeye Trail", "Greg Hanson", "Outdoors", 210, 2010],["Victory at Sea", "Hans Glutzkin", "History", 250, 1988]] def print_library(): for book in library: print() for idx, content in enumerate(book): if idx == 0: s = "Title: '" e = "'" elif idx == 1: s = "Author: " e = "" elif idx == 2: s = "Subject: " e = "" elif idx == 3: s = "" e = " pages" else: # idx = 4 s = "Year published: " e = "" print(s + str(content) + e) print() def add_book(): def add_title(): new_title = input("Please enter a title:") if new_title: print("new title:") print(new_title) # Addedfor testing return new_title else: add_title() def add_author(): new_author = (input("Please enter an author:")) if new_author: print("new author:") print(new_author) # Added for testing return new_author else: add_author() def add_subject(): new_subject = input("Please enter a subject:") …
type: Question
downvote count: 0
duplicate of: http://stackoverflow.com/q/22311440
upvote count: 1
favorite count: 0
tagged with: python-3.x
has title: Why isn't this Python 3 function returning a value when the code seems to handle the situation when no input is entered?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88416233
linked to: http://stackoverflow.com/q/22311440
answer count: 0
score: 1

http://stackoverflow.com/comment/88630532
comment on: http://stackoverflow.com/q/50812641
score: 0
type: Comment
type: QuestionComment
has text: Before calling the graph for the next time, try calling `tf.reset_default_graph()`. If you are not using the default graph, try resetting your one instead

http://stackoverflow.com/comment/88912515
comment on: http://stackoverflow.com/a/50955527
type: AnswerComment
has text: Though I am in the `project` directory and it has all the files. Moreover, I also tried `python setup.py sdist bdist_wheel` which created a build directory with all files. I am not sure how to use to the Build Distribution!
score: 0
type: Comment

http://stackoverflow.com/q/50811671
has comment: http://stackoverflow.com/comment/88628652
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/88631098
has title: Python script to add new vaule at the end of each row in the csv output file based on the checking conditon
has body: I want to write a python script to add new value at the end of a row in CSV file that produced by the initial part of the script. The CSV file has values like below name,isactive,ful_name,emailaddress rajesh,active,Rajesh Pidikiti,myemail@corp.####.com james,active,James wood,mail@mail.com I need to consider the name of each row and check the user has admin privileges (by running one curl command) or not. If the user is admin then add admin as new value at end of the row (new column). If not then add user as the new value. The output will be like this name,isactive,ful_name,emailaddress,isadmin rajesh,active,Rajesh Pidikiti,myemail@corp.####.com,admin james,active,James wood,mail@mail.com,user I have tried by creating function and for a loop but not successful. I'm okay to either Appending the results to input or creating a new output file. This what I have written so far. def to_add_new_col(input_file,output_file) with open(input_file, 'rb') as infile: with open(output_file, 'wb') as outfile: reader = csv.reader(infile, lineterminator='\n') writer = csv.writer(outfile, lineterminator='\n') check_and_add(reader, writer) def check_and_add(reader, writer) for i in reader: for field in (i) if(curl_result(field): i=admin else i=user writer.writerow(i)
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50872278
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -2

http://stackoverflow.com/a/50714144
type: Answer
has body: You can use re. Demo: import re def validate(string): return 'YES' if re.search(r'(PH.*HP)|(HP.*PH)', string) else 'NO' inputs = ['PHHP', 'HPPH', 'PHP', 'PHAP'] for inp in inputs: print(inp, validate(inp)) Output: PHHP YES HPPH YES PHP NO PHAP NO
score: 0
answers question: http://stackoverflow.com/q/50713804

http://stackoverflow.com/comment/88451695
type: Comment
has text: You should use a RegEx!
score: 1
comment on: http://stackoverflow.com/q/50721670
type: QuestionComment

http://stackoverflow.com/q/50837715
favorite count: 0
has title: Conversion of a sequential model to a functional model with Keras 2.2.0
tagged with: python
upvote count: 13
type: AnsweredQuestion
has body: Up to Keras version 2.1.6 one was able to "convert" a sequential model to a functional model by accessing the underlying model.model. Since version 2.2.0 this is no longer possible. Can it still be done in some other way? (In case you wonder why I would like to do something like this, I'm maintaining a library that relies on this conversion. :wink:)
accepted answer: http://stackoverflow.com/a/50937113
type: Question
score: 13
answer count: 2
possible better answer: http://stackoverflow.com/a/50945544
downvote count: 0
has answer: http://stackoverflow.com/a/50937113
has answer: http://stackoverflow.com/a/50945544
tagged with: keras

http://stackoverflow.com/q/50813926
answer count: 1
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/50814029
upvote count: 2
has body: I don't understand why this is not working. soup_main = BeautifulSoup(' FooBar ') soup_append = BeautifulSoup(' Meh ') soup_main.body.append(soup_append.a) I get the error below: Traceback (most recent call last):File "<stdin>", line 1, in <module> File "C:\Python34\lib\site-packages\bs4\element.py", line 378, in append self.insert(len(self.contents), tag) File "C:\Python34\lib\site-packages\bs4\element.py", line 312, in insert raise ValueError("Cannot insert None into a tag.") ValueError: Cannot insert None into a tag. I would be glad if I can understand what is happening.
type: AnsweredQuestion
score: 2
type: Question
has answer: http://stackoverflow.com/a/50814029
downvote count: 0
has title: Beautiful soup appending
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/88635006

http://stackoverflow.com/q/50840001
has title: Binary classification in Keras and LSTM
tagged with: deep-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/88687455
answer count: 1
tagged with: keras
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88686937
linked to: http://stackoverflow.com/q/38714959
type: AnsweredQuestion
downvote count: 0
tagged with: classification
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50866945
accepted answer: http://stackoverflow.com/a/50866945
has body: I have a binary classification problem that makes me very confused about input,output of modeling with LSTM. I want to input 5 rows of dataset ,and get the label color of 6th row. My X has 5 features : rb , us, ls, Volume, pos My Y is a label which is 1 or 0 My dataframe: rb us ls Volume pos color 0 0.080071 1.000000 0.964286 0.020507 1 1 1 0.017798 0.857143 0.857143 0.017643 1 1 2 0.026698 0.642857 0.500000 0.031085 4 1 3 0.029666 0.833333 1.000000 0.011411 2 0 4 0.008899 0.500000 1.000000 0.008371 4 0 I make a sequence of 5 rows like this: [[1.77976353e-02 8.57142857e-01 8.57142857e-01 1.76426968e-02 1.00000000e+00] [2.66977791e-02 6.42857143e-01 5.00000000e-01 3.10845400e-02 4.00000000e+00] [2.96664095e-02 8.33333333e-01 1.00000000e+00 1.14109866e-02 2.00000000e+00] [8.89918602e-03 5.00000000e-01 1.00000000e+00 8.37062257e-03 4.00000000e+00] [1.48316083e-02 8.33333333e-01 1.00000000e+00 8.47275749e-03 2.00000000e+00]] How I should classify Y of 6th row? I mean how to classify the 6th row OR first next item of next sequence? Do I need to declare it to the network somehow? Is there any problem with my input/output of network? How can I get the label(Binary classification) of 6th item label color? My code: import pandas as pd from Util import window_nd as Reshape from keras.utils import to_categorical from keras.layers import Dense,RNN,LSTM,Activation,Dropout from keras.models import Sequential df = pd.read_csv('./EURUSD_DATAFRAME.csv') print(df.head()) df['pos'] = df['pos'].astype('int') dat = df.values X = dat[0:30004,0:5] Y = dat[0:30000,5] X = Reshape(X,5) #It's a custom function which reshaped the X to serialized (5,5) #Shape of X is (30000, 5, 5) Y = to_categorical(Y,num_classes=2) model = Sequential() model.add(LSTM(25,input_shape=(5,5),return_sequences=True)) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(LSTM(1)) model.add(Activation('relu')) model.add(Dense(2)) model.add(Activation('sigmoid')) model.compile(optimizer='adam',loss='binary_cr…
score: 1

dictionary
tags question: http://stackoverflow.com/q/50847329
tags question: http://stackoverflow.com/q/50772321
tags question: http://stackoverflow.com/q/50839106
tags question: http://stackoverflow.com/q/50784201
tags question: http://stackoverflow.com/q/50761069
tags question: http://stackoverflow.com/q/50841994
tags question: http://stackoverflow.com/q/50846487
tags question: http://stackoverflow.com/q/50834506
tags question: http://stackoverflow.com/q/50730911
tags question: http://stackoverflow.com/q/50790884
tags question: http://stackoverflow.com/q/50825906
tags question: http://stackoverflow.com/q/50710754
tags question: http://stackoverflow.com/q/50819224
tags question: http://stackoverflow.com/q/50829492
tags question: http://stackoverflow.com/q/50751234
tags question: http://stackoverflow.com/q/50835723
tags question: http://stackoverflow.com/q/50711647
tags question: http://stackoverflow.com/q/50841165
tags question: http://stackoverflow.com/q/50783518
tags question: http://stackoverflow.com/q/50698982
tags question: http://stackoverflow.com/q/50710422
tags question: http://stackoverflow.com/q/50784279
tags question: http://stackoverflow.com/q/50786266
tags question: http://stackoverflow.com/q/50719722
tags question: http://stackoverflow.com/q/50832814
tags question: http://stackoverflow.com/q/50729672
tags question: http://stackoverflow.com/q/50808889
tags question: http://stackoverflow.com/q/50819767
tags question: http://stackoverflow.com/q/50801103
tags question: http://stackoverflow.com/q/50720028
tags question: http://stackoverflow.com/q/50708170
tag name: dictionary
tags question: http://stackoverflow.com/q/50783863
tags question: http://stackoverflow.com/q/50758869
tags question: http://stackoverflow.com/q/50824989
tags question: http://stackoverflow.com/q/50731242
tags question: http://stackoverflow.com/q/50750971
tags question: http://stackoverflow.com/q/50761806
tags question: http://stackoverflow.com/q/50740610
tags question: http://stackoverflow.com/q/50767359
tags question: http://stackoverflow.com/q/50837113
tags question: http://stackoverflow.com/q/50846592
tags question: http://stackoverflow.com/q/50740762
tags question: http://stackoverflow.com/q/50837353
tags question: http://stackoverflow.com/q/50705975
tags question: http://stackoverflow.com/q/50724680
tags question: http://stackoverflow.com/q/50778949
tags question: http://stackoverflow.com/q/50767417
tags question: http://stackoverflow.com/q/50709171
tags question: http://stackoverflow.com/q/50744797
tags question: http://stackoverflow.com/q/50804970
tags question: http://stackoverflow.com/q/50781084
tags question: http://stackoverflow.com/q/50850068
tags question: http://stackoverflow.com/q/50786866
tags question: http://stackoverflow.com/q/50809220
tags question: http://stackoverflow.com/q/50768493
tags question: http://stackoverflow.com/q/50751184
tags question: http://stackoverflow.com/q/50842580
tags question: http://stackoverflow.com/q/50767861
tags question: http://stackoverflow.com/q/50840899
tags question: http://stackoverflow.com/q/50723917
tags question: http://stackoverflow.com/q/50796244
tags question: http://stackoverflow.com/q/50844431
tags question: http://stackoverflow.com/q/50700155
tags question: http://stackoverflow.com/q/50725414
type: Tag
tags question: http://stackoverflow.com/q/50745285
tags question: http://stackoverflow.com/q/50724433
tags question: http://stackoverflow.com/q/50770201
tags question: http://stackoverflow.com/q/50851878
tags question: http://stackoverflow.com/q/50763445
tags question: http://stackoverflow.com/q/50776631
tags question: http://stackoverflow.com/q/50724763
tags question: http://stackoverflow.com/q/50709515
tags question: http://stackoverflow.com/q/50729340
tags question: http://stackoverflow.com/q/50782327
tags question: http://stackoverflow.com/q/50804350
tags question: http://stackoverflow.com/q/50746323
tags question: http://stackoverflow.com/q/50732688
tags question: http://stackoverflow.com/q/50726665

tcp
type: Tag
tags question: http://stackoverflow.com/q/50789505
tags question: http://stackoverflow.com/q/50779355
tags question: http://stackoverflow.com/q/50748265
tag name: tcp
tags question: http://stackoverflow.com/q/50852062

http://stackoverflow.com/comment/88617495
comment on: http://stackoverflow.com/q/50805474
type: Comment
type: QuestionComment
score: 0
has text: @RushilSrivastava hope the code helps

http://stackoverflow.com/comment/88584068
type: QuestionComment
has text: try `results.decode('utf-8').replace...`
comment on: http://stackoverflow.com/q/50788282
score: 0
type: Comment

http://stackoverflow.com/q/50776712
tagged with: tensorflow
type: AnsweredQuestion
type: Question
has title: Tensorflow : TypeError: Fetch argument None has invalid type <class 'NoneType'>
score: 0
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/50779620
answer count: 1
tagged with: python
has body: I am trying to run this simple program to compute gradient, But i am getting None error : import tensorflow as tf import numpy as np batch_size = 5 dim = 3 hidden_units = 8 sess = tf.Session() with sess.as_default(): x = tf.placeholder(dtype=tf.float32, shape=[None, dim], name="x") y = tf.placeholder(dtype=tf.int32, shape=[None], name="y") w = tf.Variable(initial_value=tf.random_normal(shape=[dim, hidden_units]), name="w") b = tf.Variable(initial_value=tf.zeros(shape=[hidden_units]), name="b") logits = tf.nn.tanh(tf.matmul(x, w) + b) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, y,name="xentropy") # define model end # begin training optimizer = tf.train.GradientDescentOptimizer(1e-5) grads_and_vars = optimizer.compute_gradients(cross_entropy, tf.trainable_variables()) # generate data data = np.random.randn(batch_size, dim) labels = np.random.randint(0, 10, size=batch_size) sess.run(tf.initialize_all_variables()) gradients_and_vars = sess.run(grads_and_vars, feed_dict={x:data, y:labels}) for g, v in gradients_and_vars: if g is not None: print "****************this is variable*************" print "variable's shape:", v.shape print v print "****************this is gradient*************" print "gradient's shape:", g.shape print g sess.close() Error : --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-14-8096b2e21e06&gt; in &lt;module&gt;() 29 30 sess.run(tf.initialize_all_variables()) ---&gt; 31 outnet = sess.run(grads_and_vars, feed_dict={x:data, y:labels}) 32 # print(gradients_and_vars) 33 # if g is not None: //anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata) 893 try: 894 result = self._run(None, fetches, feed_dict, options_ptr, --&gt; 895 run_metadata_ptr) 896 if run_metadata: 897 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) //anaconda/lib/python3.5/site-packages/tenso…
has answer: http://stackoverflow.com/a/50779620
tagged with: machine-learning

http://stackoverflow.com/a/50766642
has comment: http://stackoverflow.com/comment/88540751
has comment: http://stackoverflow.com/comment/88540715
has comment: http://stackoverflow.com/comment/88540904
has comment: http://stackoverflow.com/comment/88540762
type: Answer
has comment: http://stackoverflow.com/comment/88540808
has body: If you're trying to get the same result as you would by double-clicking the file, you're looking for os.startfile(). With this, you need to specify a filepath, and when called, this function will 'launch' the file (in this case, your .txt file). The file is opened with whatever application (if any) its extension is associated with. Usage: import os os.startfile('textfile.txt') This will 'launch' the text file. Also, as @heather says in the comments, if you only use the filename (and not the filepath), your program will only work if the steam key text file is in the same directory - otherwise, you have to put in the full filepath.
has comment: http://stackoverflow.com/comment/88540784
has comment: http://stackoverflow.com/comment/88540788
score: 2
answers question: http://stackoverflow.com/q/50766561
downvote count: 0
has comment: http://stackoverflow.com/comment/88540696
upvote count: 2

http://stackoverflow.com/q/50770833
has body: This is a function in my code- class worker(Thread): def run(self): for x in range(0,1100000000000): print (x) time.sleep(1) Which gets called here- def main(): ttk.Button(mainframe, text="Start",command=worker.start) Now Python also accepts this for the function assignment- ttk.Button(mainframe, text="Start",command=worker().start) How are these two different?
accepted answer: http://stackoverflow.com/a/50774673
tagged with: python
has title: How does function() differ from function?
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/88549173
has answer: http://stackoverflow.com/a/50774673
has answer: http://stackoverflow.com/a/50775528
type: Question
tagged with: function
score: -2
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/50775528
favorite count: 0

http://stackoverflow.com/comment/88487166
type: QuestionComment
score: 0
has text: The png is probably transparent. JPG cant do transparency. It converts the transparent pixels RGBA to RGB's of 0,0,0 wich is black. Therefore you see nothing.
comment on: http://stackoverflow.com/q/50739732
type: Comment

http://stackoverflow.com/q/50727428
tagged with: python-packaging
has comment: http://stackoverflow.com/comment/88463393
tagged with: python-import
type: AnsweredQuestion
has title: Cannot resolve "import as" situation ("AttributeError module x has no attribute y")
downvote count: 0
accepted answer: http://stackoverflow.com/a/50727781
score: 6
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
upvote count: 6
has body: I have a project with the following structure: project/ driver.py lib/ __init__.py core/ util.py common.py __init__.py # project/driver.py import lib.core.common as abc pass # project/lib/core/__init__.py from .util import Worker # project/lib/core/util.py import lib.core.common as abc class Worker: pass # project/lib/core/common.py def stuff(): pass Now when I run python3 driver.py (from project's directory), I get the following error: Traceback (most recent call last): File "driver.py", line 1, in &lt;module&gt; import lib.core.common as abc File "/home/user/project/lib/core/__init__.py", line 1, in &lt;module&gt; from .util import Worker File "/home/user/project/lib/core/util.py", line 1, in &lt;module&gt; import lib.core.common as abc AttributeError: module 'lib' has no attribute 'core' This happens only when both conditions are met: When I do import lib.core.common as abc instead of import lib.core.common. When the project/lib/core/__init__.py contains from .util import Worker import. The thing is that I would like to keep the import lib.core.common as abc import form. Could anybody explain what's going on here, please?
has answer: http://stackoverflow.com/a/50727781
answer count: 1

http://stackoverflow.com/a/50808557
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88623238
has comment: http://stackoverflow.com/comment/88714770
downvote count: 0
has body: import tkinter as tk from PIL import ImageTk, Image #This creates the main window of an application window = tk.Tk() window.title("SEE image and ENTER its information") window.geometry("600x400") window.configure(background='grey') #Creates a tkinter-compatible photo image. path = "Picture.jpg" img = ImageTk.PhotoImage(Image.open(path)) #The Label widget is a standard tkinter widget used to display a text or image on the screen. panel = tk.Label(window, image = img) # Create textbox in window text_widget = tk.Text(panel) text_widget.insert('insert',"Enter image information here") text_widget.pack(anchor = "w", padx = 50, pady = 50) #The Pack geometry manager packs widgets in rows or columns. #panel.pack(side = "bottom", fill = "both", expand = "no") panel.pack() #Start the GUI window.mainloop()
type: Answer
has comment: http://stackoverflow.com/comment/88635374
answers question: http://stackoverflow.com/q/50808428

http://stackoverflow.com/a/50780575
has body: This makes the trick. The bug was in the way you declared the original matrix. In particular, you have to declare the matrix grouping the elements in the rows, not the one in the columns like in the starting code You are going to multiply the elements on the rows of matrix for the elements of the [column] vector in order to respect the rule for a multiplication matrix vs vector. Given a matrix with size a[= rows size, 3 in your case] x b[= columns size, 2 in your case] your vector must have a number of rows equal to b [= 2 in your case]. Given your 2 x 1 vector the final result will be a 3 x 1 vector Now when you run the code len(matrix) gives back 3, as it should be. If you run the original version you had 2 as value back and that prevented the last calculation to get the remaining third element of the resulting vector [i.e. the final 14] def matVec(matrix,vector): result = [] for i in range(len(matrix)): total = 0 for j in range(len(vector)): total += matrix[i][j] * vector[j] result.append(total) return result matrix_0 = [[1, 2],[2, 3],[3, 4]] vector_0 = [2, 2] print(matVec(matrix_0,vector_0))
has comment: http://stackoverflow.com/comment/88568019
score: 1
has comment: http://stackoverflow.com/comment/88567879
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50780402
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50780402
type: Answer

http://stackoverflow.com/q/50728304
tagged with: pipenv
score: 1
has answer: http://stackoverflow.com/a/50729235
has comment: http://stackoverflow.com/comment/88464672
type: Question
answer count: 1
downvote count: 0
tagged with: flask
favorite count: 0
has body: I want to install flask and zappa, a common combination. I use pipenv to create an evironment: pipenv --python 3.6.4 I want to install packages: pipenv install flask zappa Unfortunately the requirements of flask is: Werkzeug >= 0.14 the requirement of zappa is : Werkzeug == 0.12 So this is not installable. What can i do?
has title: python pip: cannot install flask and zappa - contradicting requirements
tagged with: python
has comment: http://stackoverflow.com/comment/88464749
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88466037

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/50839982
type: Tag

http://stackoverflow.com/comment/88696609
comment on: http://stackoverflow.com/q/50846444
has text: @Prune , the values of p and q are passed by helper function . I just need to complete the given function .
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88439718
type: QuestionComment
comment on: http://stackoverflow.com/q/50715173
has text: The function goal is to save the spark dataframe into a csv file.. sorry I will remove the return.
score: 0
type: Comment

http://stackoverflow.com/q/50702983
has comment: http://stackoverflow.com/comment/88417937
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
has title: Setting system path with jupyterlab
answer count: 0
has comment: http://stackoverflow.com/comment/88467291
linked to: http://stackoverflow.com/q/35254852
type: Question
tagged with: jupyter-lab
has body: I'm working with a Jupyter notebook. I'm trying to import a file called main.py which contains 2 lines: import os ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root My code: import os import main.py I'm getting the error in the screenshot. I'm using a conda virtualenv which I've activated as you can see in the screenshot. You can see in the screenshot that when I run the system path import sys sys.path ['', 'E:\\miniconda2\\envs\\jupyter1\\python36.zip', 'E:\\miniconda2\\envs\\jupyter1\\DLLs', 'E:\\miniconda2\\envs\\jupyter1\\lib', 'E:\\miniconda2\\envs\\jupyter1', 'E:\\miniconda2\\envs\\jupyter1\\lib\\site-packages', 'E:\\miniconda2\\envs\\jupyter1\\lib\\site-packages\\IPython\\extensions', is the path of the virtualenv python interpreter rather than my local directory. How can I fix this?
score: 0
has comment: http://stackoverflow.com/comment/88418016
has comment: http://stackoverflow.com/comment/88470862

http://stackoverflow.com/comment/88607795
comment on: http://stackoverflow.com/a/50800916
type: AnswerComment
score: 0
type: Comment
has text: The html is in the website I have in my code. I don't think I can select the drop-down list because it is not an element in the HTML.

http://stackoverflow.com/q/50795456
tagged with: python
possible better answer: http://stackoverflow.com/a/50797898
linked to: http://stackoverflow.com/q/432385
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50795527
accepted answer: http://stackoverflow.com/a/50795527
type: Question
has comment: http://stackoverflow.com/comment/88597919
has answer: http://stackoverflow.com/a/50797898
has body: I have written a small program that uses the os module extensively especially os.walk, os.remove etc. For example, def dump_folder(source, destination): """ """ # uses os.walk, shutil.move def encrypt_folder(folder, recipient): """ """ # uses os.walk, os.remove Now, I would like to extend this program to support SFTP folders. Do I need to mount the folders locally to make os.* work? For example, in Windows, I could use win32net and do something like: try: win32wnet.WNetAddConnection2(...drive, remote...) except: pass If I am going to use a tool like paramiko, can I make it work with the same code without worrying about the details which os.walk, os.remove, shutil.move provides? If I can't, then I will have to rewrite the program quite a bit which is not something I want. PS: The goal of this question is to find out how to use the same code to work with remote folders. Tools like paramiko deals with implementation details (like where is the file etc) so we will have to re-write the program . The idea of mounting remote file locally and ability to use os is really nice and powerful.
upvote count: 2
has comment: http://stackoverflow.com/comment/88596810
tagged with: sftp
answer count: 2
favorite count: 0
has title: Dealing with remote folders while using the os module in a python code?

http://stackoverflow.com/comment/88513032
comment on: http://stackoverflow.com/q/50752487
type: Comment
type: QuestionComment
has text: At the top of your script put in `import os`, followed by `print(os.getcwd())`. What is the path it outputs, and are you positive that `learning_python.txt` is in the said directory?
score: 0

http://stackoverflow.com/comment/88567811
type: Comment
comment on: http://stackoverflow.com/q/50780548
score: 0
type: QuestionComment
has text: Can you provide a [mcve] with some sample tensors (input and output) please?

http://stackoverflow.com/comment/88686417
type: QuestionComment
comment on: http://stackoverflow.com/q/50841210
score: 0
type: Comment
has text: Thanks Yikang for the suggestion.

http://stackoverflow.com/a/50779106
answers question: http://stackoverflow.com/q/50777076
score: 1
upvote count: 1
downvote count: 0
has body: Per your question about moving Ajax1234's answer inside a loop: from bs4 import BeautifulSoup s = """ &lt;div class="resultRow" data-unix="1528542937" id="resultRow1"&gt; &lt;div class="resultRow" data-unix="1528542937" id="resultRow2"&gt; &lt;div class="resultRow" data-unix="1528542937" id="resultRow1"&gt; """ soup = BeautifulSoup(s, 'lxml') final_results = [] for tmp in soup.find_all('div', {'class':'resultRow'}): final_results.append(tmp['data-unix']) print final_results ['1528542937', '1528542937', '1528542937']
type: Answer

http://stackoverflow.com/comment/88469998
comment on: http://stackoverflow.com/q/50731146
score: 0
type: Comment
has text: To me it seems that the code does exactly what you want. Can you be more specific in how far this is not the case?
type: QuestionComment

http://stackoverflow.com/q/50778388
tagged with: debugging
tagged with: qml
has body: I've built PyQt5 5.10.1 against Qt 5.5 with the --qml-debug flag. When I import QtQml I get the message "QML debugging is enabled. Only use this in a safe environment." but whenever I try to run my application, passing arguments to the QApplication constructor, there's no indication that running my app with the -qmljsdebugger=port:1234,block option does anything. I'm expecting a message like "QML Debugger: Waiting for connection on port 1234", or "QML Debugger: Ignoring "qmljsdebugger=port:1234". Debugging has not been enabled.", but neither of these messages are displayed. I've tried printing QApplication.arguments(), and the qmljsdebugger argument is not there, but the name of the program is. I've tried passing ['program.py', '-qmljsdebugger=port:1234,block'] directly to the QApplication() constructor, but the second argument is not visible from the call to QApplication.arguments(). Funny enough if i remove the leading '-' from the argument, it shows up in that list but doesn't do anything.
downvote count: 0
answer count: 1
favorite count: 0
has title: PyQt5 QML Debugging enabled, qmljsdebugger option doesn't do anything
tagged with: python
has answer: http://stackoverflow.com/a/50801153
type: AnsweredQuestion
score: 1
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/50801153
upvote count: 1
type: Question

http://stackoverflow.com/comment/88647635
comment on: http://stackoverflow.com/q/50820844
has text: the question was closed as duplicate of a Q&A. This is the link. Disclaimer: I answered this particular question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88703798
type: QuestionComment
type: Comment
has text: @itsnotme: There exist algorithms that work only for convex polygons, but many of them support even self-intersecting polygons (with [one](https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule) or [another](https://en.wikipedia.org/wiki/Nonzero-rule) winding rule to define the interior).
comment on: http://stackoverflow.com/q/50847827
score: 0

http://stackoverflow.com/comment/88615308
type: AnswerComment
has text: If your problem is solved you should accept the answer and ask another question, sadly I don't have the knowledge to help you with the other parts perhaps someone else will. I suggest trying to debug and testing where it fails first, but if you can't ask another question
type: Comment
comment on: http://stackoverflow.com/a/50804342
score: 0

http://stackoverflow.com/a/66046039
type: Answer
has body: I'm not sure why that's happening. However, there is a scriptlistener workaround. Agreed, it's ugly; but it works! To add a new gradient adjustment layer: Dim appRef Set appRef = CreateObject( "Photoshop.Application" ) ' Switch off any dialog boxes appRef.displayDialogs = 3 appRef.BringToFront REM ======================================================= DIM objApp SET objApp = CreateObject("Photoshop.Application") REM Use dialog mode 3 for show no dialogs DIM dialogMode dialogMode = 3 DIM idMk idMk = objApp.CharIDToTypeID( "Mk " ) DIM desc3873 SET desc3873 = CreateObject( "Photoshop.ActionDescriptor" ) DIM idnull idnull = objApp.CharIDToTypeID( "null" ) DIM ref1360 SET ref1360 = CreateObject( "Photoshop.ActionReference" ) DIM idAdjL idAdjL = objApp.CharIDToTypeID( "AdjL" ) Call ref1360.PutClass( idAdjL ) Call desc3873.PutReference( idnull, ref1360 ) DIM idUsng idUsng = objApp.CharIDToTypeID( "Usng" ) DIM desc3874 SET desc3874 = CreateObject( "Photoshop.ActionDescriptor" ) DIM idType idType = objApp.CharIDToTypeID( "Type" ) DIM desc3875 SET desc3875 = CreateObject( "Photoshop.ActionDescriptor" ) DIM idGrad idGrad = objApp.CharIDToTypeID( "Grad" ) DIM desc3876 SET desc3876 = CreateObject( "Photoshop.ActionDescriptor" ) DIM idNm idNm = objApp.CharIDToTypeID( "Nm " ) Call desc3876.PutString( idNm, "Foreground to Background" ) DIM idGrdF idGrdF = objApp.CharIDToTypeID( "GrdF" ) DIM idCstS idCstS = objApp.CharIDToTypeID( "CstS" ) Call desc3876.PutEnumerated( idGrdF, idGrdF, idCstS ) DIM idIntr idIntr = objApp.CharIDToTypeID( "Intr" ) Call desc3876.PutDouble( idIntr, 4096.000000 ) DIM idClrs idClrs = objApp.CharIDToTypeID( "Clrs" ) DIM list470 SET list470 = CreateObject( "Photoshop.ActionList" ) DIM desc3877 SET desc3877 = CreateObject( "Photoshop.ActionDescriptor" ) DIM idClr idClr = objApp.CharIDToTypeID( "Clr " ) DIM desc3878 SET desc3878 = CreateObject( "Photoshop.ActionDescriptor" ) DIM idRd idRd = objApp.CharIDToTypeID( "Rd " ) Call desc3878.PutDouble( idRd, 0.000000 …
score: 0
answers question: http://stackoverflow.com/q/50807584

http://stackoverflow.com/comment/88791221
comment on: http://stackoverflow.com/q/50826831
has text: You cannot append to a string, but you can assign the name `barfoo` to a new string, which is the concatenation of two strings: `barfoo = barfoo + "baz"`, or the shorthand variant `barfoo += "baz"`.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88473265
type: QuestionComment
has text: @neverwalkaloner Sorry, I edited that before submitting the question. That is what I had originally but it still doesn't work for some reason
comment on: http://stackoverflow.com/q/50732722
score: 1
type: Comment

http://stackoverflow.com/q/50771911
type: Question
has body: I am trying to use NumPy in Python interactive mode, but I am having trouble importing it. I've installed NumPy using the python -m pip install numpy command, but when I open the Python Shell and type import numpy then it gives me &gt;&gt;&gt; import numpy Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'numpy' I tried running the pip install command again, and it tells me: Requirement already satisfied: numpy in c:\users\sean\appdata\local\programs\python \python36-32\lib\site-packages (1.14.4) Here's what I get when I try to find the Python path: &gt;&gt;&gt;import sys &gt;&gt;&gt;for p in sys.path: ... print (p) ... C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_34\python36.zip C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_34\DLLs C:\program Files (x86)\Microsoft Visual Studio\Shared\Python36_34\lib C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_34 C:\Users\sean\AppData\Roaming\Python\Python36\site-packages C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_34\lib\site-packages I don't know what the problem is, and after searching on this community and online in general, many people seem to be having similar issues but resolved it by modifying their path. Could anybody help me with this problem?
tagged with: numpy
has comment: http://stackoverflow.com/comment/88551459
downvote count: 0
favorite count: 0
tagged with: importerror
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88551323
answer count: 0
has comment: http://stackoverflow.com/comment/88551439
score: 1
has title: I have NumPy installed, but I can't import it
upvote count: 1

http://stackoverflow.com/q/50766586
tagged with: selenium-chromedriver
tagged with: selenium
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/49155839
downvote count: 0
score: 4
has body: In alpine I run the following two commands: apk update apk add chromium chromium-chromedriver I would now like to use the chromedriver with selenium via python. In windows I would do something like the following while having the .exe in the same directory. browser = webdriver.Chrome(executable_path=r"chromedriver.exe") How do I use the chromedriver I just installed using apk add in alpine. PS: the selenium library was installed via pip install.
has title: How to use chromedriver and selenium through python in alpine
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88548626
type: UnansweredQuestion
tagged with: alpine-linux
tagged with: chromium
tagged with: python

http://stackoverflow.com/comment/88418359
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50703768
score: 0
has text: Thank you so much, this was very helpful!

http://stackoverflow.com/comment/88618183
has text: Gosh, I was sitting in front of the computer for too long. I see my mistake. I realized that I was multiplying the indices by the traversals. Thanks for asking that question. Could you post an answer so that I can accept it?
comment on: http://stackoverflow.com/q/50806043
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50819025
has comment: http://stackoverflow.com/comment/88643388
type: Question
score: 3
upvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/9860588
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/35578435
accepted answer: http://stackoverflow.com/a/50819644
tagged with: python
type: AnsweredQuestion
has body: I am working on a problem wherein, the given array is as follows: " Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. " For example: Input: [2,2,3,2] Output: 3 I am trying to solve it using Bit Manipulation, and my code in Python is as follows: def singleNumber(self, nums): ans = 0 for i in range(31): summ = 0 for num in nums: dig = (num&gt;&gt;i)&amp;1 if dig: summ += 1 summ = summ%3 if summ: ans = ans | summ&lt;&lt;i return ans All I am trying to do is, get the last bit of each number in the array and count the number of ones that I get and then %3 to get the exact 1 bits that remain and shift it to make the correct answer. This fails test cases which have negative inputs, something like: [-2,-2,1,1,-3,1,-3,-3,-4,-2] O/P: 2147483644 Expected O/P: -4 However, when I do the exact same thing in Java, it works! The code is as below: class Solution { public int singleNumber(int[] nums) { int ans = 0; int dig = 0; for(int i = 0; i &lt;=31; i++){ int sum = 0; for(int num: nums){ dig = (num&gt;&gt;i)&amp;1; if(dig!=0){ sum = sum + 1; } sum = sum%3; } if(sum!= 0){ ans = ans | sum&lt;&lt;i; } } return(ans); } } How are the bits represented in Python that is causing this difference? Can someone please tell me the difference in bit manipulations in both the languages, Python and Java?
downvote count: 0
tagged with: bit-shift
tagged with: java
tagged with: bit-manipulation
has answer: http://stackoverflow.com/a/50819644
has title: Bit Manipulation in Python and Java

http://stackoverflow.com/comment/88436732
score: 0
type: Comment
type: QuestionComment
has text: I want the whole string as the output but using a regex pattern. The string has curly brackets. @Poppinyoshi
comment on: http://stackoverflow.com/q/50713808

http://stackoverflow.com/q/50811089
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50811487
tagged with: python
downvote count: 0
score: 1
type: Question
tagged with: apache-spark-sql
has body: I have a dataframe that looks like this: # +----+------------+----------+-----------+ # | id | c_type_1 | c_type_2 | c_type_3 | # +----+------------+----------+-----------+ # | 1 | null | null | r | # | 2 | a | null | null | # | 3 | null | null | null | # +---+-------------+----------+-----------+ I need to convert it into something like this: # +----+------------+------------+ # | id | c_type | c_type_val | # +----+------------+------------+ # | 1 | c_type_3 | r | # | 2 | c_type_1 | a | # | 3 | null | null | # +---+-------------+------------+ Each row only has either one c_type value or all c_type values will be null. I'm currently melting the rows like so: def melt(df, id_cols, value_cols, c_type, c_value): v_arr = [] for c in value_cols: v_arr.append(struct(lit(c).alias(c_type), col(c).alias(c_value))) vars_and_vals = array(*v_arr) tmp = df.withColumn("vars_and_vals", explode(vars_and_vals)) cols = id_cols + [ col("vars_and_vals")[x].alias(x) for x in [c_type, c_value]] return tmp.select(*cols) melted = melt(df, df.columns[:1], df.columns[1:4], 'c_type', 'c_type_val') melted.filter(melted.c_type_val.isNotNull()).show() The problem is that filtering the null values for c_type_val filters out the row for id == 3 (any rows with null c_type). I need a way to melt and filter to retain the third row as null c_type and value.
tagged with: pyspark
has title: Pyspark Melting Null Columns
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50813120
has comment: http://stackoverflow.com/comment/88631343
has title: Using Flask Pymysql to serve image "GET" request , Error shows a bytes-like object is required, not 'dict'
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50813282
score: 0
has comment: http://stackoverflow.com/comment/88631507
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/88631581
type: Question
tagged with: pymysql
tagged with: flask
has body: def write_file(data, filename): with open(filename, 'wb') as f: f.write(data) class DownloadPhoto(Resource): def get(self,PhotoDefaultID): connection_DownloadPhoto = pymysql.connect(host='*******', user='root', password='*****', db='*******', charset='******', cursorclass=pymysql.cursors.DictCursor) try: with connection_DownloadPhoto.cursor() as cursor_DownloadPhoto: DownloadPhoto = "SELECT `PhotoData` FROM `app_phototable` WHERE `PhotoDefaultID` IN (%s)" cursor_DownloadPhoto.execute(DownloadPhoto, PhotoDefaultID) PhotoData = cursor_DownloadPhoto.fetchone() connection_DownloadPhoto.commit() finally: connection_DownloadPhoto.close() #write_file(data=PhotoData, filename="PhotoFile") write_file(PhotoData, "PhotoFile") return send_file(filename_or_fp= "PhotoFile", mimetype="image/jpeg"), 200 the code is here, and the debug shows "TypeError: a bytes-like object is required, not 'dict' // Werkzeug Debugger"
has answer: http://stackoverflow.com/a/50813282
answer count: 1

http://stackoverflow.com/comment/88703283
score: 0
has text: Are you sure fpr and tpr really "just" to floats, or are they numpy arrays?
comment on: http://stackoverflow.com/q/50848163
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88582078
has text: This new approach worked perfectly. You are an absolute star. Thank you very much.
comment on: http://stackoverflow.com/a/50787480
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50804120
upvote count: 16
favorite count: 0
has comment: http://stackoverflow.com/comment/88618089
has answer: http://stackoverflow.com/a/60610890
has body: Example DataFrame Values - 0 78 1 38 2 42 3 48 4 31 5 89 6 94 7 102 8 122 9 122 stats.percentileofscore(temp['INCOME'].values, 38, kind='mean') 15.0 stats.percentileofscore(temp['INCOME'].values, 38, kind='strict') 10.0 stats.percentileofscore(temp['INCOME'].values, 38, kind='weak') 20.0 stats.percentileofscore(temp['INCOME'].values, 38, kind='rank') 20.0 temp['INCOME'].rank(pct=True) 1 0.20 (Only showing the 38 value index) temp['INCOME'].quantile(0.11) 37.93 temp['INCOME'].quantile(0.12) 38.31999999999999 Based on the results above, you can see none of the methods are consistent with the pd.quantiles() method. I need to get the percentile for one column for each row in a dataframe (255M rows) but can't find any functions/methods that return the 'linear interpolation' method that they use in pd.quantile &amp; np.percentile. I've tried the following methods/functions - .rank(pct=True) This method only returns the values ranked in order, not using the percentile method that I'm looking for. Inconsistent with pd.quantiles scipy.stats.percentileofscore This method almost is closer to what I'm looking for but still is not 100% consistent with the 'linear interpolation' method for some reason. Related question to this problem with no real answer I've looked through every SO answer that is related to this question but none of them use the same interpolation method that I need to use so please do not mark this as a duplicate unless you can verify they're using the same method. At this point my last option is to just find the bin cut-offs for all 100 percentiles and apply it that way or calculate the linear interpolation myself but this seems very inefficient and will take forever to apply to 255M records. Any other suggestions to do this? Thanks!
has title: How do I get the percentile for a row in a pandas dataframe?
tagged with: python
has comment: http://stackoverflow.com/comment/88868441
downvote count: 0
has comment: http://stackoverflow.com/comment/88773438
has answer: http://stackoverflow.com/a/50901044
type: UnansweredQuestion
score: 16
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88618030
has answer: http://stackoverflow.com/a/50863943
has comment: http://stackoverflow.com/comment/88632768
tagged with: percentile
linked to: http://stackoverflow.com/q/40680970
has comment: http://stackoverflow.com/comment/88838268
answer count: 3
has comment: http://stackoverflow.com/comment/88616676
tagged with: pandas

http://stackoverflow.com/q/50734147
has comment: http://stackoverflow.com/comment/88476745
type: Question
has body: SuperPixeled image This is the image and I want to save only the non-black region superpixels after resizing them to 56x56. I am working on superpixel classification.
tagged with: superpixels
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88476500
has answer: http://stackoverflow.com/a/52267029
type: UnansweredQuestion
tagged with: python
has title: How to extract content of each superpixel and resize them?

http://stackoverflow.com/a/50777512
type: AcceptedAnswer
has body: input_username is not a WebElement, but a list as you've used find_elements_by_xpath() instead of find_element_by_xpath(). Try either input_username = browser.find_element_by_xpath("//input[@name='username']") action.move_to_element(input_username) or input_username = browser.find_elements_by_xpath("//input[@name='username']") action.move_to_element(input_username[0]) Note that Authentication form generated dynamically by JavaScript, so to be able to handle input fields, you need to wait for JavaScript to be executed: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait as wait from selenium.webdriver.support import expected_conditions as EC input_username = wait(browser, 10).until(EC.element_to_be_clickable((By.NAME, "username")))
downvote count: 0
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50777329
has comment: http://stackoverflow.com/comment/88562537
answers question: http://stackoverflow.com/q/50777329
has comment: http://stackoverflow.com/comment/88562227

http://stackoverflow.com/comment/88923591
type: Comment
has text: Yes, I've tried using Step Functions with AWS Lambda, and it works perfectly fine. But the issue here is the python programs are mostly on data analytics, and they couldn't work on AWS Lambda. So, all I'm left with is use EC2 for executing the programs and then run them all together as required on Step Functions.
comment on: http://stackoverflow.com/a/50895188
score: 0
type: AnswerComment

http://stackoverflow.com/q/50748775
upvote count: 1
has title: How to prevent interruption of a thread in Python
type: Question
tagged with: opencv
score: 1
has comment: http://stackoverflow.com/comment/88505772
downvote count: 0
has body: I have multiple threads in my program, and one of them is reading from 2 cameras using OpenCV. I want to guarantee that the camera thread is not interrupted while capturing the frames from the two cameras so that the frames are captured at essentially the same time. How can I prevent the thread from being interrupted in the middle of reading the frames? To better explain my question, I've provided some example code: import cv2 import time cap0 = cv2.VideoCapture(0) #setup first camera cap1 = cv2.VideoCapture(1) #setup second camera while True: disable_interrupts() #prevent task switching to other threads cap0.grab() #capture a frame cap1.grab() #capture a frame timestamp = time.time() #the approximate time the frames were captured enable_interrupts() #allow task switching to continue ret, frame0 = cap0.retrieve() #get the previously "grabbed" frame for the first camera ret, frame1 = cap1.retrieve() #get the previously "grabbed" frame for the second camera I'm used to working with microcontrollers without an OS and you often switch tasks using interrupts. It is easy in that case, because you simply disable some/all interrupts, execute the critical code, and then re-enable the interrupts afterward. Is there something equivalent in the operating system world? Or does OpenCV offer something for capturing multiple cameras simultaneously? I happen to be using QThread (PyQt4), so does QThread offer anything like this?
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88505089
has comment: http://stackoverflow.com/comment/88505217
tagged with: python
tagged with: qthread
answer count: 0
tagged with: multithreading

http://stackoverflow.com/q/50807778
score: 1
tagged with: mongodb
accepted answer: http://stackoverflow.com/a/50809475
answer count: 1
favorite count: 0
tagged with: aggregation-framework
has body: Currently, I am dealing with a large set of data that is stored in MongoDB(2M single collections from a larger collection of 20M). Feilds: id, item name, item type, item description and date() Dynamically count how many items occur in a date span of a week and month for the entire collection. i.e From 2014-01-01 to 2014-01-07 has 20 items, From 2014-01-08 to 2014-01-16 has 50 items,.. etc Using python, how can I accomplish this? Are their libraries for this or it would be a custom code? Alternatively, should this be done all through MongoDB?
tagged with: python
tagged with: mongodb-query
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/50809475
has title: Count number of items dynamically through date range
downvote count: 1
type: Question

http://stackoverflow.com/comment/88441508
comment on: http://stackoverflow.com/q/50716437
type: QuestionComment
score: 0
has text: check this link answer is already there [link](https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression)
type: Comment

http://stackoverflow.com/a/50726737
has comment: http://stackoverflow.com/comment/88571671
answers question: http://stackoverflow.com/q/50725737
has body: Change this line, bbounds = request.form('bbox_bounds') to bbounds =request.form['bbox_bounds'] Refer to the Flask Quickstart guide for more detailed examples - http://flask.pocoo.org/docs/1.0/quickstart/#routing Also issues as such can be easily caught and fixed if you look into your logs.
has comment: http://stackoverflow.com/comment/88498716
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/88648936
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50814127
has text: That also worked! As a final question, how can I use data from the date onwards. For example, if a bullish signal occurred on 01-27-2010 (Day ), how can I calculate: ( Close( Day 2 ) - Open( Day 1 ) ) / Open( Day 1). Presently, I am attempting to identify the index of the Date where the bullish signal occurred but because there are so many dates, I am unaware which method I can use. Thanks.

http://stackoverflow.com/comment/88634412
score: 0
type: Comment
type: QuestionComment
has text: Your code is incomplete regarding [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) - no includes, no workbook-creation , no adding of sheets to the workbook , .....
comment on: http://stackoverflow.com/q/50814689

http://stackoverflow.com/comment/88691590
type: Comment
has text: @DeliriousLettuce Because the defaults change over time? Why is it an issue at all?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50843926

http://stackoverflow.com/a/50700258
accepted answer of: http://stackoverflow.com/q/50700155
answers question: http://stackoverflow.com/q/50700155
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: Using a simple Iteration. Ex: data = {"item 1": { "property 1": "value 1", "property 2": "value 2", "property 3": "value 3" }, "item 2": { "property 1": "value 1", "property 2": "value 2", "property 3": "value 3" } } d = {} for i in data: d[i] = {"property 1": data[i]["property 1"], "property 2": data[i]["property 2"]} print( d ) Output: {'item 2': {'property 1': 'value 1', 'property 2': 'value 2'}, 'item 1': {'property 1': 'value 1', 'property 2': 'value 2'}}

http://stackoverflow.com/comment/88500300
comment on: http://stackoverflow.com/q/50746266
score: 0
has text: This may sound real stupid but im a beginner ....but how do i do that?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88664641
has text: Add your data, your code , and some examples for clarification please!
score: 4
comment on: http://stackoverflow.com/q/50830214
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50818766
type: UnansweredQuestion
has body: I have been tasked with moving MySQL databases to amazon redshift. Currently I am attempting to accomplish this by 1) converting tables to CSV files 2) storing them in S3 3) creating a table in redshift 4) using the COPY command to transfer the data from S3 to redshift I am using Python to attempt to automate this process and use boto3 to encrypt the data on the way to S3. However, with the process I have now, I would have to manually create a table in Redshift for every csv in S3. Since I am ultimately going to move lots of data, this is going to be very inefficient. Is there a code I can run to detect the schema and create the table without having to go in and change the CREATE TABLE statement every time I want to load new data?
type: Question
tagged with: mysql
has answer: http://stackoverflow.com/a/75432901
answer count: 2
downvote count: 0
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/88643218
favorite count: 0
tagged with: postgresql
tagged with: amazon-redshift
has answer: http://stackoverflow.com/a/50819751
has comment: http://stackoverflow.com/comment/88642737
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/88648491
has title: Should I CREATE TABLE every time I run COPY command
upvote count: 2

http://stackoverflow.com/a/50711630
has body: Creating and populating None for 'phones', 'pc', 'ucg', 'security', 'null' columns just for groupBy doesn't make sense. Grouping with id and all of the above columns with null or grouping by only id, both are same. What you can do instead is find the difference between actual pivoted columns and the intended columns and then create and populate with 0 So the following should work for you phone_list = ['iphone', 'android phone', 'nokia'] pc_list = ['windows pc', 'mac pro'] security_list = ['spy camera'] ucg_list = ['ipad'] from pyspark.sql import functions as f df = df.withColumn('cat', f.when(df.device.isin(phone_list), 'phones').otherwise( f.when(df.device.isin(pc_list), 'pc').otherwise( f.when(df.device.isin(ucg_list), 'ucg').otherwise( f.when(df.device.isin(security_list), 'security')))) )\ .groupBy('id').pivot('cat').agg(f.count('val'))\ .na.fill(0)\ columnList = ['phones', 'pc', 'ucg', 'security', 'null'] actualcolumnList = df.columns[1:] diffColumns = [x for x in columnList if x not in actualcolumnList] for y in diffColumns: df = df.withColumn(y, f.lit(0)) df.show(truncate=False) which should give you +---+----+---+------+--------+---+ |id |null|pc |phones|security|ucg| +---+----+---+------+--------+---+ |3 |1 |1 |0 |1 |0 | |1 |0 |1 |2 |1 |0 | |2 |0 |0 |1 |1 |0 | +---+----+---+------+--------+---+ I hope the answer is helpful
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88433772
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88434421
answers question: http://stackoverflow.com/q/50708155
type: Answer
has comment: http://stackoverflow.com/comment/88433958
accepted answer of: http://stackoverflow.com/q/50708155

http://stackoverflow.com/comment/88511120
type: AnswerComment
has text: @Anthony copying your exact settings, and your exact spider, and what I assume is the exact layout from `scrapy startproject tutorial`, I am able to get a response. Can you post an updated log from after you added the yield statement from `scrapy crawl rentals -o rentals.json && open rentals.json`
comment on: http://stackoverflow.com/a/50751454
score: 0
type: Comment

http://stackoverflow.com/comment/88553512
has text: did you try describe_spot_instance_requests? for the instance ids created by spot? Refer: https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_spot_instance_requests
comment on: http://stackoverflow.com/q/50771544
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88936072
type: AnswerComment
has text: @Sam it is boolean XOR for test difference of boolean mask.
type: Comment
comment on: http://stackoverflow.com/a/50760833
score: 0

http://stackoverflow.com/q/50720128
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50720264
tagged with: list
has comment: http://stackoverflow.com/comment/88448910
type: Question
has body: I have a list and many items of this lists begin with "https://www.google.com", so I want to delete all of the elements who start with "https://www.google.com" in my list.. I think I have to use regex but I do not know how to do it.. Thanks,
has comment: http://stackoverflow.com/comment/88448748
has comment: http://stackoverflow.com/comment/88449069
has comment: http://stackoverflow.com/comment/88448715
score: 0
has answer: http://stackoverflow.com/a/50720264
answer count: 1
has comment: http://stackoverflow.com/comment/88449130
tagged with: python
has title: Delete item of a list who start with the same words

http://stackoverflow.com/q/50850068
has comment: http://stackoverflow.com/comment/88702900
has body: I am making a crude shop in a Python 3.x script as a small project ( I started coding two days ago ), and when my program attempts to subtract the value of the item selected by the user from the initial amount of money the user starts out with, the program crashes. Note: balance(): function aims to display remaining amount of money yet, but is not finished yet. How can I fix my code, and is there any other way to improve/optimize it? Also, if you give a solution, please assume I don't know what method you will be using, so please give context and explain what you are using and other applications it can be used in. import time import sys # Dictionary: # Shop Catalog, with numbers for prices. shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 } # Money Values/Variables: # Initial Money initialMoney = 3000 # Functions: # Catalog browsing: # This is where you are presented the different items on sale, and choose which you will order def browse(): print("Welcome to the Virtual Shop Catalog") time.sleep(1) print("Here is what is currently on sale (item:price): ") time.sleep(1) print(shopCatalog) time.sleep(1) print("Enter '4' to quit") time.sleep(1) # This loop is where you choose to either return to the main menu, or order items. while True: try: shopChoice = int(input("Enter item of choice: ")) if shopChoice == 4: print("Returning back to main menu...") time.sleep(0.5) mainMenu() break # This is supposed to reduce the value/price of the item from your inital amount of money (initalmoney) or balance elif shopChoice == 1 or 2 or 3 or 4 or 5 or 6: print(" Purchased 1 " + shopCatalog[shopChoice] + " .") initialMoney = initialMoney - shopCatalog[shopChoice] break elif shopChoice == 3: print("You want to leave already...? Ok, have a good day!") time.sleep(1) break else: print("Invalid option. Please pick a choice from 1-6")…
has answer: http://stackoverflow.com/a/50850172
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88703264
has title: Crude virtual shop project fails when selection item from dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50850238
score: 0
possible better answer: http://stackoverflow.com/a/50850231
type: Question
has answer: http://stackoverflow.com/a/50850231
accepted answer: http://stackoverflow.com/a/50850172
answer count: 3
tagged with: python-3.x

http://stackoverflow.com/comment/88483321
score: 0
has text: For sure, but I thought all the dependencies were installed... Do you know how I can install them, or maybe a command to see the dependencies ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50736394

http://stackoverflow.com/q/50753043
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50753270
score: 4
has comment: http://stackoverflow.com/comment/88514098
has comment: http://stackoverflow.com/comment/88514038
linked to: http://stackoverflow.com/q/41215365
possible better answer: http://stackoverflow.com/a/50753092
answer count: 3
has answer: http://stackoverflow.com/a/50753092
has answer: http://stackoverflow.com/a/50753235
has comment: http://stackoverflow.com/comment/88514109
has body: When using formatted string literal, it is possible to have nested f-strings to some extent. a = 3 b = 7 res = f"{f'{a*b}'}" print(res) # '21' Although, the same does not work if the inner expression is a variable containing a string. a = 3 b = 7 expr = 'a*b' res = f"{f'{expr}'}" print(res) # 'a*b' Is there a way to make this work and to have the second output to be '21' as well? If not, what is the difference between the first and second string that prevents it?
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/88514044
has comment: http://stackoverflow.com/comment/88514082
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88514516
downvote count: 0
has title: Is nested string literal interpolation possible?
tagged with: string
accepted answer: http://stackoverflow.com/a/50753235
favorite count: 0
has comment: http://stackoverflow.com/comment/88514086

http://stackoverflow.com/a/75071868
answers question: http://stackoverflow.com/q/50818782
score: 0
type: Answer
has body: As far as I know , TouchAction only simulates "physical" touch or gestures to the screen , it has no correlation to what is happening on the back-end . For the ActionChains , i believe you need to make some tweaks to make it work on mobile : 'driver.execute_cdp_cmd('Emulation.setDeviceMetricsOverride', {height:y, width:x}) # height and width of screen driver.execute_cdp_cmd('Page.setDeviceMetricsOverride', emulation) config, enabled = 'mobile', True browser.execute_cdp_cmd('Emulation.setEmitTouchEventsForMouse', {'enabled': enabled, 'configuration': config}) maxpoints = 3 driver.execute_cdp_cmd('Emulation.setTouchEmulationEnabled', {'enabled': enabled, 'maxTouchPoints': maxpoints})' Maybe these will work !

http://stackoverflow.com/q/50762211
has comment: http://stackoverflow.com/comment/88533574
answer count: 2
has comment: http://stackoverflow.com/comment/88532456
has comment: http://stackoverflow.com/comment/88532572
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88532304
favorite count: 0
has comment: http://stackoverflow.com/comment/88567207
has body: Having code posted below how can I improve it's implementation? I am trying no to have to much if-logic in my code and I am pretty certain that there are much faster mechanisms in Python to deal with such tasks: is_sat = re.search('sat', destination, re.IGNORECASE) if is_sat is not None: temp_zone = self.determine_zone(value, self.sat_zone_dict) data_type = 'SAT' + str(temp_zone) self.log_handler.update(destination+" "+data_type+"\n") else: if destination.find("All") &gt; 0: temp_zone = self.determine_zone(value, self.mn_zone_dict) data_type = 'ALL_' + str(temp_zone) self.log_handler.update("ALL destination: "+destination + " " + data_type + "\n") elif destination.find("Mobile") &gt; 0: temp_zone = self.determine_zone(value, self.mn_zone_dict) data_type = 'MOB_'+str(temp_zone) elif destination.find("Fixed") &gt; 0: temp_zone = self.determine_zone(value, self.mn_zone_dict) data_type = 'FIX_'+str(temp_zone) elif destination.find("NGN") &gt; 0: temp_zone = self.determine_zone(value, self.sat_zone_dict) data_type = 'NGN_' + str(temp_zone) determine_zone() method allows me to match with key: value dict, but while I first have to search for the pattern in the destination field it makes no sense to me to add another operation which would exactly extract position of the "All', 'Mobile' etc. in my string. @EDIT As @zwer asked here is determine_zone() implementation: def determine_zone(price: int, zone_dict: dict) -&gt; int: zone = None try: for (key, value) in zone_dict.items(): if price &lt; value: zone = key return zone if zone is None: zone = zone_dict.__len__() + 1 return zone except TypeError: raise TypeError
has comment: http://stackoverflow.com/comment/88532067
has answer: http://stackoverflow.com/a/50762506
tagged with: python
has comment: http://stackoverflow.com/comment/88532070
has comment: http://stackoverflow.com/comment/88532124
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88532285
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/88532190
has answer: http://stackoverflow.com/a/50762670
has title: Most pythonic way to find matching string
type: Question

http://stackoverflow.com/a/50703619
has body: If you just want to modify the output to a csv you can specify the date_format in to_csv: In[130]: df = pd.DataFrame({'date':[pd.datetime.strptime('11:03:41', '%H:%M:%S')]}) df.to_csv(date_format='%H:%M:%S') Out[130]: ',date\n0,11:03:41\n' I would advise to keep your data as datetime64 because it allows you to perform vectorised arithmetic on the column, if you store as datetime.time objects then it limits what you can do You can always just add an additional column either as the datetime.time or a str representation: In[131]: df['time'] = df['date'].dt.time df['str_rep'] = df['date'].dt.strftime('%H:%M:%S') df Out[131]: date time str_rep 0 1900-01-01 11:03:41 11:03:41 11:03:41 To demonstrate my point: In[136]: df = pd.DataFrame({'date':pd.to_datetime(['11:03:41', '15:23:33'], format='%H:%M:%S').time}) df Out[136]: date 0 11:03:41 1 15:23:33 now if we perform arithmetic: df['date'].diff() this will raise: TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' whilst if we keep the dtype as datetime64 we can still perform arithmetic and comparisons, as the dates are all the same they cancel out anyway depending on what you're doing: In[138]: df = pd.DataFrame({'date':pd.to_datetime(['11:03:41', '15:23:33'], format='%H:%M:%S')}) df Out[138]: date 0 1900-01-01 11:03:41 1 1900-01-01 15:23:33 In[139]: df.diff() Out[139]: date 0 NaT 1 04:19:52 update If you really want datetime.time then you could modify your lambda: dateparse = lambda x: pd.datetime.strptime(x, '%H:%M:%S').time() my_data = pd.read_csv(file_name, parse_dates=['Time'], date_parser=dateparse) or this would also work: my_data = pd.read_csv(file_name, parse_dates=['Time'], date_parser=lambda x: pd.to_datetime(x, format='%H:%M:%S').time()) comparisons and some arithmetic operations will work but it's not as flexible as the native datetime64 dtype.
has comment: http://stackoverflow.com/comment/88418159
accepted answer of: http://stackoverflow.com/q/50703425
has comment: http://stackoverflow.com/comment/88440930
upvote count: 3
answers question: http://stackoverflow.com/q/50703425
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/88416726
type: Answer
has comment: http://stackoverflow.com/comment/88440968
score: 2
has comment: http://stackoverflow.com/comment/88416698
has comment: http://stackoverflow.com/comment/88427217

http://stackoverflow.com/comment/88450483
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50718831
type: Comment
has text: SymPy is not up to the task of writing out the inverse of a generic n by n matrix in explicit form. Already `Sigma.inverse().as_explicit()` fails.

http://stackoverflow.com/q/50739918
upvote count: 4
type: AnsweredQuestion
tagged with: list
downvote count: 0
has body: I am quite new to Python3 and the issue I am having is the following: I have a nested list structure of strings: lst = [['foo', 'bar foo bar', 'foo bar'], ['foo', 'bar foo bar', 'foo bar'], ['foo', 'bar foo bar', 'foo bar']] So what I essentially want to achieve is to take the element [1] of each nested list and split it to achieve another nest in the list for example: lst = [['foo' , ['bar', 'foo', 'bar'], 'foo bar'], ['foo' , ['bar', 'foo', 'bar'], 'foo bar'], ['foo' , ['bar', 'foo', 'bar'], 'foo bar']] I used list comprehension to split this element but in its own separate list so in this case the original elements [0] and [2] from each list are missing: split_lst = [lst[1].split('\n') for lst in split_list] How can I split this element but retain it in the original list with all other elements?
type: Question
has answer: http://stackoverflow.com/a/50740465
answer count: 2
score: 4
has answer: http://stackoverflow.com/a/50739986
accepted answer: http://stackoverflow.com/a/50739986
tagged with: nested
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88488458
possible better answer: http://stackoverflow.com/a/50740465
has title: How to Split Defined Elements Of A Nested List
tagged with: python

http://stackoverflow.com/a/50770130
answers question: http://stackoverflow.com/q/50769943
has body: Redefine the first items in your tuples as Integer, these are the first items that define the Field Type: scored_place_number = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( (0,'neither',), (1,'first_place'), (2,'second_place') ) )
accepted answer of: http://stackoverflow.com/q/50769943
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88586438
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88586780

http://stackoverflow.com/comment/88620807
has text: Perhaps use a `translate` table to change each of the undesirable chars to the empty string.
comment on: http://stackoverflow.com/q/50807518
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88665783
type: QuestionComment
has text: You need to escape the `{` and `}` because the format is trying to substitute the text enclosed within them.
score: 0
comment on: http://stackoverflow.com/q/50830770
type: Comment

http://stackoverflow.com/a/50725409
upvote count: 1
has comment: http://stackoverflow.com/comment/88460734
downvote count: 0
has body: Python functions are objects, you can set an attribute on them: i = 0 def f(): return f.i f.i = i i = 1 print(f()) # Prints 0 as you wanted or: for i in range(5): f.i = i print(f()) Note that an argument would do the same.
has comment: http://stackoverflow.com/comment/88459988
type: Answer
answers question: http://stackoverflow.com/q/50725297
has comment: http://stackoverflow.com/comment/88461514
score: 1

http://stackoverflow.com/comment/88647653
comment on: http://stackoverflow.com/q/50821145
score: 2
type: Comment
type: QuestionComment
has text: Have you seen https://stackoverflow.com/questions/31883432/converting-jpeg-string-to-pil-image-object

http://stackoverflow.com/q/50725029
has comment: http://stackoverflow.com/comment/88459469
upvote count: 2
answer count: 1
favorite count: 0
has title: Total likes on all posts of a user
has comment: http://stackoverflow.com/comment/88458517
tagged with: python
score: 2
downvote count: 0
tagged with: django
accepted answer: http://stackoverflow.com/a/50725148
has body: How can I count the total likes on all the posts of a particular user in django ? I have added the html and views.py also. I would like to display the count of total likes below the the total count of posts in html. Thanks models.py class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='posts') slug =models.SlugField(unique=True, blank=True, default=uuid.uuid1) likes =models.ManyToManyField(User, blank=True, related_name='post_likes') def __str__(self): return self.title
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88458668
has answer: http://stackoverflow.com/a/50725148

http://stackoverflow.com/comment/88427859
comment on: http://stackoverflow.com/q/50704483
has text: While it doesn't address your question directly, I think that this youtube video of a PyCon lecture by David Beazley titled [_Curious Course on Coroutines and Concurrency_](https://youtu.be/Z_OAlIhXziw) would help you understand what coroutines are capable of (and implicitly how doing the same thing with a class instance object would be very difficult if not impossible).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88699275
type: Comment
type: QuestionComment
score: 0
has text: Is this Python 2 or 3?
comment on: http://stackoverflow.com/q/50847976

http://stackoverflow.com/comment/89259742
type: Comment
has text: Since I used the module (python-telegram-bot) instead of HTTP endpoint method, I couldn't inject my json request. Do you have any idea for this problem?
comment on: http://stackoverflow.com/a/51111187
score: 1
type: AnswerComment

http://stackoverflow.com/q/50706001
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/zip
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50706052
downvote count: 2
type: Question
score: -2
accepted answer: http://stackoverflow.com/a/50706052
has title: In Python how to unzip a single file inside a zip file in a url?
upvote count: 0
has body: In Python 3 I have a program to extract files from a zip in a link (zipurl): from io import BytesIO from urllib.request import urlopen from zipfile import ZipFile zipurl = (f'http://agencia.tse.jus.br/estatistica/sead/odsele/prestacao_contas/prestacao_final_2014.zip') with urlopen(zipurl) as zipresp: with ZipFile(BytesIO(zipresp.read())) as zfile: zfile.extractall('doacoes_2014') Please, is there a way to unzip only one file? In case I need the file "receitas_candidatos_2014_brasil.txt"

http://stackoverflow.com/a/50830698
has body: The file encoding is determined from the current Environment, in this case assuming ascii. You can specify the file encoding directly use: with open ('stats.txt', 'w', encoding='utf8') as q: pass
accepted answer of: http://stackoverflow.com/q/50830591
answers question: http://stackoverflow.com/q/50830591
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/a/50779751
answers question: http://stackoverflow.com/q/50779567
type: Answer
has comment: http://stackoverflow.com/comment/88566493
upvote count: 1
has comment: http://stackoverflow.com/comment/88609620
has comment: http://stackoverflow.com/comment/88609066
has comment: http://stackoverflow.com/comment/88566389
score: 1
has body: The problem seems to be that the actual data is inside jQuery1124033955090772971586_1528569153921(). I was able to get rid of it by removing a parameter in the request url. If you absolutely needs it, this may do the trick: &gt;&gt;&gt; import json &gt;&gt;&gt; url = 'http://web.ifzq.gtimg.cn/appstock/hk/HkInfo/getFinReport?type=3&amp;reporttime_type=1&amp;code=00001&amp;startyear=1990&amp;endyear=2016&amp;_callback=jQuery1124033955090772971586_1528569153921&amp;_=1528569153953' &gt;&gt;&gt; fetch(url) 2018-06-09 21:55:13 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET http://web.ifzq.gtimg.cn/appstock/hk/HkInfo/getFinReport?type=3&amp;reporttime_type=1&amp;code=00001&amp;startyear=1990&amp;endyear=2016&amp;_callback=jQuery1124033955090772971586_1528569153921&amp;_=1528569153953&gt; (referer: None) &gt;&gt;&gt; data = response.text.strip('jQuery1124033955090772971586_1528569153921()') &gt;&gt;&gt; parsed_data = json.loads(data) If you prefer to remove the _callback parameter from the url, simply: &gt;&gt;&gt; import json &gt;&gt;&gt; url = 'http://web.ifzq.gtimg.cn/appstock/hk/HkInfo/getFinReport?type=3&amp;reporttime_type=1&amp;code=00001&amp;startyear=1990&amp;endyear=2016&amp;_=1528569153953' &gt;&gt;&gt; fetch(url) 2018-06-09 21:53:36 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET http://web.ifzq.gtimg.cn/appstock/hk/HkInfo/getFinReport?type=3&amp;reporttime_type=1&amp;code=00001&amp;startyear=1990&amp;endyear=2016&amp;_=1528569153953&gt; (referer: None) &gt;&gt;&gt; parsed_data = json.loads(response.text)
has comment: http://stackoverflow.com/comment/88567017
has comment: http://stackoverflow.com/comment/88642159
has comment: http://stackoverflow.com/comment/88566973
has comment: http://stackoverflow.com/comment/88566492
downvote count: 0
has comment: http://stackoverflow.com/comment/88573148
has comment: http://stackoverflow.com/comment/88566449
has comment: http://stackoverflow.com/comment/88642099
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88566499
accepted answer of: http://stackoverflow.com/q/50779567
has comment: http://stackoverflow.com/comment/88578522
has comment: http://stackoverflow.com/comment/88566575

http://stackoverflow.com/comment/88623598
has text: Thanks @smj, for the simple solution. But I am in search of more generic solution, as my json will vary. I am writing a utility for the project to convert 'json to csv' for any given validated json. And I want to break all 'list of dictionary' into separate file. But here, 'list of dictionary' is part of another dictionary.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50808447

http://stackoverflow.com/comment/88475985
type: Comment
comment on: http://stackoverflow.com/a/50733351
type: AnswerComment
score: 0
has text: my proposed solution requires python and selenium. (driver.page_source) . In fact, that is the first sentence of my answer. I suggest to use a different PARSER for performance reasons and I also suggest to use a way of text extraction that works in all scenarios, not just in some.

http://stackoverflow.com/comment/88606942
comment on: http://stackoverflow.com/a/50800263
score: 0
type: AnswerComment
type: Comment
has text: Thanks for the answer, but I'm not trying to place the template inside the view, I need to use the object returned by the context. I first though this was accessible in the template as salaire.charge_salariale_mensuel I need a certain modularity of the data object to make operations in the future.

http://stackoverflow.com/comment/88595579
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50794628
score: 1
has text: Possible duplicate of [Build a Basic Python Iterator](https://stackoverflow.com/questions/19151/build-a-basic-python-iterator)

print-spooler-api
tag name: print-spooler-api
tags question: http://stackoverflow.com/q/50774738
type: Tag

http://stackoverflow.com/a/50795569
answers question: http://stackoverflow.com/q/50773142
type: Answer
upvote count: 1
has body: Here is one sample code to demonstrate this problem. Print statements output is customized, but not statements from logging module. from contextlib import contextmanager @contextmanager def no_stdout(): import sys old_stdout = sys.stdout class CustomPrint(): def __init__(self, stdout): self.old_stdout = stdout def write(self, text): if len(text.rstrip()): self.old_stdout.write('custom Print---&gt;'+ text) sys.stdout = CustomPrint(old_stdout) try: yield finally: sys.stdout = old_stdout def fun(): import logging logger = logging.getLogger("tester") logger.info("Test line from function") print "BEFORE" with no_stdout(): print "WHY HELLO!\n" print "DING DONG!\n" import logging logger = logging.getLogger("test") logger.info(" Hello world") fun() print "AFTER" output: BEFORE custom Print---&gt;WHY HELLO! custom Print---&gt;DING DONG! 2018-06-11 15:52:30,088 (42092) test INFO - Hello world 2018-06-11 15:52:30,092 (42092) tester INFO - Test line from function AFTER we see that logging modules output is not customized.
downvote count: 0
score: 1

http://stackoverflow.com/comment/88658273
score: 1
comment on: http://stackoverflow.com/a/50826714
type: AnswerComment
has text: @hpaulj Check the link I've provided. They have done speed tests as well as explaining why it's slower. Pandas is faster according to this link: http://akuederle.com/stop-using-numpy-loadtxt. I haven't done memory profiling on it, but I think since it's intended for big data, should be much more memory efficient as well.
type: Comment

http://stackoverflow.com/comment/88525908
score: 0
comment on: http://stackoverflow.com/q/50758950
has text: or is there any other method to add a shortcut-like code for close all windows? please answer. Thank you!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88608656
has text: mmm still not working, it says AttributeError: 'list' object has no attribute 'click'
type: Comment
comment on: http://stackoverflow.com/a/50800931
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88495460
type: Comment
comment on: http://stackoverflow.com/q/50738541
has text: Generally launching a separate thread for capture gives better FPS results.
score: 0
type: QuestionComment

http://stackoverflow.com/a/50710837
accepted answer of: http://stackoverflow.com/q/50706642
answers question: http://stackoverflow.com/q/50706642
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has body: Colab is run on a machine in the cloud. It cannot send the display back to your local machine. That's why it said "no video device".
type: Answer
has comment: http://stackoverflow.com/comment/100961035
has comment: http://stackoverflow.com/comment/88439148
score: 2
has comment: http://stackoverflow.com/comment/88444157

http://stackoverflow.com/q/50706311
has body: I'm working on a Python/Django/Wagtail project, and I have some api to return some paginated articles. It goes like this: In URLs: url(r'^morearticles/', views.get_live_articles), In Views: def get_live_articles(request): context = {'articles': getLiveArticles(request) } return render(request, 'app/components/articles-live.html', context, content_type="text/html; charset=utf-8") The getLiveArticles function looks like this: def getLiveArticles(request): # Articles a = get_articles() #this is getting the articles correctly p = Paginator(a, 4) page_n = request.GET.get('page') try: articles = p.page(page_n) except Exception, e: articles = [] return articles However when hitting the api endpoint I get this: Traceback (most recent call last): File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/john/app/app/views.py", line 90, in get_live_articles context = {'articles': getLiveArticles(request) } File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/cache_utils/decorators.py", line 48, in wrapper cache.set(key, value, timeout, **backend_kwargs) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/cache/backends/locmem.py", line 75, in set pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) PicklingError: Can't pickle &lt;class 'wagtail.wagtailcore.blocks.base.RichTextBlockMet…
score: 5
has title: Why am I getting this PicklingError?
tagged with: wagtail
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50706636
favorite count: 0
upvote count: 5
tagged with: django
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/88422148
has comment: http://stackoverflow.com/comment/88422114
has comment: http://stackoverflow.com/comment/88422461
has comment: http://stackoverflow.com/comment/88422085
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50706636
has comment: http://stackoverflow.com/comment/88422333
has comment: http://stackoverflow.com/comment/88421992

http://stackoverflow.com/q/50712937
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88434770
accepted answer: http://stackoverflow.com/a/50712994
has title: Python- Converting tuple to list of multiple lists by index
linked to: http://stackoverflow.com/q/19339
has comment: http://stackoverflow.com/comment/88434756
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/19339
score: 1
possible better answer: http://stackoverflow.com/a/50712959
upvote count: 1
has answer: http://stackoverflow.com/a/50712959
has body: I have a list of tuples that looks like this: x = [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)] What is the most pythonic and efficient way to convert into a list of 2 lists where each list respectively has all values of a specific index? Like so: y = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] Is it possible to do this without a loop?
type: Question
has answer: http://stackoverflow.com/a/50712994

http://stackoverflow.com/a/50787541
has comment: http://stackoverflow.com/comment/88598522
has comment: http://stackoverflow.com/comment/88582455
score: 1
accepted answer of: http://stackoverflow.com/q/50787213
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: One method is to utilise pd.DataFrame.lookup: df1 = pd.DataFrame({'Name': ['AAA', 'BBB', 'CCC'], 'Graduated': [1, 0, 1], 'Employed': [2, 1, 0], 'Married': [3, 2, 1]}) df2 = pd.DataFrame({'Answer_Code': [0, 1, 2, 3], 'Graduated': ['No', 'Yes', np.nan, np.nan], 'Employed': ['No', 'Intern', 'PT', 'FT'], 'Married': ['No', 'Engaged', 'Yes', 'Divorced']}) # perform lookup on df2 using row &amp; column labels from df1 arr = df2.set_index('Answer_Code')\ .lookup(df1.iloc[:, 1:].values.flatten(), df1.columns[1:].tolist()*3)\ .reshape(3, -1) # copy df1 and allocate values from arr df3 = df1.copy() df3.iloc[:, 1:] = arr print(df3) Name Graduated Employed Married 0 AAA Yes PT Divorced 1 BBB No Intern Yes 2 CCC Yes No Engaged
has comment: http://stackoverflow.com/comment/88583094
answers question: http://stackoverflow.com/q/50787213
upvote count: 1

http://stackoverflow.com/comment/88581573
has text: I also had problems with that file but got proper content with pdf2tag.
comment on: http://stackoverflow.com/q/50776350
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88600133
score: 0
comment on: http://stackoverflow.com/q/50743293
has text: @AleksiTorhamo i was under the impression list's += has the same functionality so i assumed the tuple object would consume less resources because it is immutable. What would you look for in order to read more about this?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50813657
downvote count: 2
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/88633100
has comment: http://stackoverflow.com/comment/88644994
has comment: http://stackoverflow.com/comment/88632362
has comment: http://stackoverflow.com/comment/88632421
answers question: http://stackoverflow.com/q/50813544
has comment: http://stackoverflow.com/comment/88632543
has comment: http://stackoverflow.com/comment/88632610
has comment: http://stackoverflow.com/comment/88632418
has comment: http://stackoverflow.com/comment/88644445
has body: try this, range(1,5)*4 # if you don't consider order sorted(range(1,5)*4) # for ordered seq With performance updated. Mihai Alexandru-Ionut Answer: %timeit [i for i in range(1, 5) for _ in range(4)] 1000000 loops, best of 3: 1.91 µs per loop jpp answer: %timeit list(chain.from_iterable(repeat(i, 4) for i in range(1, 5))) 100000 loops, best of 3: 2.12 µs per loop %timeit np.repeat(np.arange(1, 5), 4) 1000000 loops, best of 3: 1.68 µs per loop Rory Daulton answer: %timeit [n for n in range(1,5) for repeat in range(4)] 1000000 loops, best of 3: 1.9 µs per loop jedwards answer: %timeit list(i//4 for i in range(1*4, 5*4)) 100000 loops, best of 3: 2.47 µs per loop RoadRunner Suggested in comment section: %timeit for i in range(1, 5): lst.extend([i] * 4) 1000000 loops, best of 3: 1.46 µs per loop My answer: %timeit sorted(range(1,5)*4) 1000000 loops, best of 3: 1.3 µs per loop
score: 4
has comment: http://stackoverflow.com/comment/88633337
has comment: http://stackoverflow.com/comment/88633575
has comment: http://stackoverflow.com/comment/88632585
has comment: http://stackoverflow.com/comment/88634382
has comment: http://stackoverflow.com/comment/88634075
has comment: http://stackoverflow.com/comment/88638328
has comment: http://stackoverflow.com/comment/88634162

http://stackoverflow.com/comment/88671195
type: Comment
comment on: http://stackoverflow.com/a/50833192
type: AnswerComment
has text: I m using '0.22.0'
score: 0

http://stackoverflow.com/comment/107996141
comment on: http://stackoverflow.com/a/51060374
score: 0
type: AnswerComment
has text: anyone know how what is padding_ix?
type: Comment

http://stackoverflow.com/comment/88699529
has text: `isinstance` is preferable over `type`, but besides that yes, you're going to have to do some traversal.
score: 0
comment on: http://stackoverflow.com/q/50848109
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50787852
has body: Find an answer for django: settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Basic', **'enterMode': 2,** }, 'awesome_ckeditor':{ 'toolbar': 'Custom', 'toolbar_Custom': [ [ 'Bold','Italic','Underline','Strike','- ','Link','Unlink','Anchor','-', 'Styles','Format','Font','FontSize','-', 'Image' ] ] }, }
answers question: http://stackoverflow.com/q/50709813
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/98630281
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/88559295
score: 1
type: QuestionComment
type: Comment
has text: Why would you ever want to do that? This looks like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. One that'll result in horribly ugly code.
comment on: http://stackoverflow.com/q/50776183

http://stackoverflow.com/a/50872261
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50767163
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50767163
has body: What I was missing was indeed quite simple and embarrassing. I switched 2 variable names around, resulting in wrong predictions manually. So, the formula was correct: y = a + B1 * X1 + B2 *X2 + .... Bn*Xn Before discovering it, I just worked around by saving the model and importing it to perform the predictions.

http://stackoverflow.com/a/50855600
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50853632
type: AcceptedAnswer
downvote count: 0
has body: you can use a buffered stream to save your file to. Something like: import io fileobject1 = io.BytesIO() figure1.savefig(fileobject1, format='svg') fileobject2 = io.BytesIO() figure2.savefig(fileobject2, format='svg') etc.
accepted answer of: http://stackoverflow.com/q/50853632
type: Answer

http://stackoverflow.com/q/50776805
tagged with: python
has comment: http://stackoverflow.com/comment/88561813
score: 1
has comment: http://stackoverflow.com/comment/88560537
downvote count: 1
has answer: http://stackoverflow.com/a/68572493
type: Question
has comment: http://stackoverflow.com/comment/88561851
tagged with: visual-studio-code
tagged with: 3dsmax
has body: I have a module that I can import, but I can't find out where it is saved because module.__file__ doesn't work on it. I'm trying to set up VSCode for 3ds Max python development and the pymxs module is hidden somewhere where intellisense and pylint can't find it. As such, I get errors every time I use it and autocomplete doesn't work. However, the code runs fine and i can use inspect.getmembers() on it perfectly. I would like to save the whole module into a text file, so that intellisense/pylint hopefully will be able to read it. Is that possible?
answer count: 1
has comment: http://stackoverflow.com/comment/88615387
has comment: http://stackoverflow.com/comment/88560620
favorite count: 0
has title: How can I extract an imported python module to a file?
has comment: http://stackoverflow.com/comment/88560726
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88693619
has text: Without knowing what `root` is, or how this code is supposed to be indented this question is impossible to answer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50844969

http://stackoverflow.com/comment/88549466
score: 0
type: AnswerComment
type: Comment
has text: @Lemayzeur In my opinion, adding a field to a model just for the purpose of ordering in another place in code base breaks many rules of good code
comment on: http://stackoverflow.com/a/50770904

http://stackoverflow.com/comment/88684669
has text: @MattM - added solution if need all data together :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50840142

scale
tags question: http://stackoverflow.com/q/50816909
type: Tag
tags question: http://stackoverflow.com/q/50825707
tag name: scale

http://stackoverflow.com/q/50771322
has title: Python 2.7: Remove part of element in SET
score: 1
accepted answer: http://stackoverflow.com/a/50771350
type: Question
has answer: http://stackoverflow.com/a/50771367
answer count: 2
has body: The given set is: seta = (['3;\t103;\tB03;\t01-06-2018;\t10:23:20;\t07:15:10\n', '10;\t110;\tB10;\t01-06-2018;\t10:30:00;\t07:40:10\n']) Need to remove \t, expected set should look like: ['3,103,B03,01-06-2018,10:23:20,07:15:10\n', '10,110,B10,01-06-2018,10:30:00,07:40:10\n']
downvote count: 0
has answer: http://stackoverflow.com/a/50771350
favorite count: 0
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/50771367
has comment: http://stackoverflow.com/comment/88550271
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88548205
comment on: http://stackoverflow.com/q/50770294
type: QuestionComment
type: Comment
has text: @ChristianDean I changed that line to if test[i] and test[i+1] == "aa": but I still get an error that says string indices must be integers. How would I go about changing this?
score: 0

pyqtgraph
tags question: http://stackoverflow.com/q/50816945
tags question: http://stackoverflow.com/q/50795993
tags question: http://stackoverflow.com/q/50722238
tags question: http://stackoverflow.com/q/50821529
tag name: pyqtgraph
type: Tag
tags question: http://stackoverflow.com/q/50845534
tags question: http://stackoverflow.com/q/50833107

http://stackoverflow.com/q/50760163
answer count: 2
score: 0
linked to: http://stackoverflow.com/q/7152762
has answer: http://stackoverflow.com/a/50760379
tagged with: python-3.x
has title: Saving large output data of one program to be used by another
type: UnansweredQuestion
has body: Let's say in a file A.py and I am computing value of some variable x by some lengthy procedure, such that code takes around 15-30 seconds to execute. I want to use value of x in another program B.py. I have thought of importing x to another file B.py but when B executes, it executes A again in order to calculate x. B takes another 1-2 minutes to execute, so it's essential that I just use the output x. I tried to put it under if __name__ == "main", but how will I compute x then? Also, I have tried copying the value of x to a text file as mentioned here, but x is a very large list (around 10000 length), so output just shows "..." and omits printing most of it.
tagged with: python
has comment: http://stackoverflow.com/comment/88529511
has answer: http://stackoverflow.com/a/50760279
tagged with: import
type: Question

http://stackoverflow.com/q/50826801
tagged with: eric-ide
tagged with: ide
has comment: http://stackoverflow.com/comment/88695054
has body: New to python, used Matlab previously. I get an error message: "The debugger backend could not be started." when I try to run any script in Eric IDE editor for python. (I am using various simple code examples for importing and visualizing data. An example of borrowed code is below.) I installed python 3.6, and Python 3.5 (should I uninstall one of these?) I downloaded Eric to use as an editor and debugger and installed as an administrator. In the Eric Python documentation I did not find a solution. I did look in preferences for debugging and tried both the path for Python 3.5 as well as Python 3.6 I am not sure what I changed or broke as a script had worked from the "shell" tab in Eric previously. So I broke something and cannot fix it. Should I try uninstalling Eric, and both versions of Python (3.5 and 3.6) and starting over from scratch? I think my issue may have something to do with paths, file locations etc., installation directories, really not sure and cannot find anything helpful online after much searching. I also am not certain know what paths (full directory filenames) should be in "Interpreter:" and "Working directory:" in the "Run Script" window. Any help much appreciated! Thanks in advance. Rebecca # Numpy (data import, manipulation, export) import numpy as np # Matplotlib (create trends) import matplotlib.pyplot as plt # load the data file data_file = np.genfromtxt('data_file.txt', delimiter=',') # create time vector from imported data (starts from index 0) time = data_file[:,0] # parse good sensor data from imported data sensors = data_file[:,1:5] # display the first 6 sensor rows print(sensors[0:6]) # adjust time to start at zero by subtracting the # first element in the time vector (index = 0) time = time - time[0] # calculate the average of the sensor readings avg = np.mean(sensors,1) # over the 2nd dimension # export data # stack time and avg as column vectors my_data = np.vstack((time,sensors.T,avg)) # transpose data my_data = my_data.T # save t…
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50845881
tagged with: python
tagged with: editor
has title: "The debugger backend could not be started." Eric 6 IDE Python 3.x
type: Question

http://stackoverflow.com/comment/88633337
has text: Also this solution needs a `list()` call around the range object for Python 3 compatability
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50813657

http://stackoverflow.com/a/50793933
type: Answer
accepted answer of: http://stackoverflow.com/q/50793654
answers question: http://stackoverflow.com/q/50793654
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88594020
has body: I think you need: df2.replace(df.iloc[0,0], 0) Full example: import pandas as pd df1 = pd.DataFrame({ 'a': [1,2], 'b': [3,4] }) df2 = pd.DataFrame({ 'a': [1,1], 'b': [1,1] }) df2.replace(df.iloc[0,0],0) Returns: a b 0 0 0 1 0 0 Timings: df1 = pd.concat([df1]*10000) df2 = pd.concat([df2]*10000) %timeit df2.replace(df.iloc[0,0],0, inplace=True) %timeit df2[df2 == df1.iloc[0, 0]] = 0 Returns: 341 µs ± 9.36 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 1.24 ms ± 39 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
has comment: http://stackoverflow.com/comment/88594400
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88594242

http://stackoverflow.com/comment/88435753
has text: you may need to use POI library to read excel/CSV files. which will provide inbuilt functions to read cell at a particular location. add a screenshot of csv data to let us better understand how you are reading the cells in python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50713455
score: 0

http://stackoverflow.com/q/50757380
tagged with: web-scraping
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/50757878
score: 0
has comment: http://stackoverflow.com/comment/88522418
has comment: http://stackoverflow.com/comment/88523108
answer count: 1
has comment: http://stackoverflow.com/comment/88523062
has title: Scrapy CSS Selector to select text and blank
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50757878
has body: As I am using scrapy to scrape the site containing the table. I am using the CSS selector for getting the elements for a class attr. Example code is below. Tamil Nadu - Greenshore Energy India I an using the selector response.css('.attr::text').extract() To get all the text and blanks in the span. But the above selector is returning only below list. Leaving the empty spans. [u'Tamil Nadu - Greenshore Energy', u'India'] So what selector should I use to get all the spans whether it contains the text or not.

http://stackoverflow.com/a/50786774
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50786744
has body: Use the itertools.islice() object to limit iteration to every n-th object, this is at least twice as fast as any other proposed solution: from itertools import islice n = 5 for ob in islice(iterable, None, None, n): print(ob) The above efficiently produces every 5th object, starting at the first: &gt;&gt;&gt; from itertools import islice &gt;&gt;&gt; from string import ascii_uppercase as iterable &gt;&gt;&gt; n = 5 &gt;&gt;&gt; for ob in islice(iterable, None, None, n): ... print(ob) ... A F K P U Z Replace the first None with n - 1 if you want to skip to the nth object as the first to use: &gt;&gt;&gt; for ob in islice(iterable, n - 1, None, n): ... print(ob) ... E J O T Y No copy of the input sequence is created to achieve this, so no additional memory or time is needed to produce the results. And taking every n-th object is done more efficiently than a % modulus test against an index from enumerate() could ever make it, or using range() to generate an index. That's because no further Python bytecode steps are needed to make those extra tests or index operations. If you also needed to have the index of the items selected this way, add enumerate() back in by wrapping the iterable: &gt;&gt;&gt; for i, ob in islice(enumerate(iterable), n - 1, None, n): ... print(i, ob) ... 4 E 9 J 14 O 19 T 24 Y islice() beats any other solution hands-down if you need speed: &gt;&gt;&gt; from timeit import timeit &gt;&gt;&gt; from itertools import islice &gt;&gt;&gt; import random &gt;&gt;&gt; testdata = [random.randrange(1000) for _ in range(1000000)] # 1 million random numbers &gt;&gt;&gt; def islice_loop(it): ... for ob in islice(it, None, None, 5): pass ... &gt;&gt;&gt; def range_loop(it): ... for i in range(0, len(it), 5): ob = it[i] ... &gt;&gt;&gt; def slice_loop(it): ... for ob in it[::5]: pass ... &gt;&gt;&gt; def enumerate_test_loop(it): ... for i, ob in enumerate(it): ... if i % 5 == 0: pass ... &gt;&gt;&gt; def enumerate_list_slice_loop(it): ... for i, ob in list(enumerat…
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88579972
has comment: http://stackoverflow.com/comment/88579913
has comment: http://stackoverflow.com/comment/88579982

http://stackoverflow.com/comment/88528480
has text: The problem is the greyscale image are not the same sizes. Some are big and some are small but they're all bigger than the text and the range shown at the bottom.
comment on: http://stackoverflow.com/q/50759678
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88552720
has text: rsplit(n=3) relies on the last three columns not containging spurious commas, which works for this data set.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50772644

http://stackoverflow.com/q/50853708
tagged with: hyperparameters
favorite count: 0
has answer: http://stackoverflow.com/a/62579689
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
tagged with: neural-network
has title: Same prediction for different hyperparameter in Keras
upvote count: 1
answer count: 1
has body: I'm trying to perform a hyperparameter optimization on a neural net, but as soon as I try a larger number of hidden layers, my neural network will always predict the same output, so my list of (negative) losses looks like: -0.789302627913455 -0.789302627913455 -0.789302627913455 -1 -0.789302627913455 -0.789302627913455 -1 -0.789302627913455 -0.789302627913455 -0.789302627913455 this is my neural net: def nn(learningRate, layers, neurons, dropoutIn, dropoutHidden, miniBatch, activationFun, epoch): x_data = [] y_data = [] x_data_train = [] y_data_train = [] x_data_test = [] y_data_test = [] session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess) x_data = np.loadtxt('../4nodes_demand_vector') x_data = x_data - x_data.min() x_data = x_data / x_data.max() * 2 x_data = x_data - 1 y_data = np.loadtxt('../4nodes_vlink_vector') input_dim = x_data.shape[1] output_dim = y_data.shape[1] split_ratio = 0.75 number_of_samples = x_data.shape[0] # train data x_data_train = x_data[:int(number_of_samples*split_ratio), ] y_data_train = y_data[:int(number_of_samples*split_ratio), ] # test data x_data_test = x_data[int(number_of_samples*split_ratio):, ] y_data_test = y_data[int(number_of_samples*split_ratio):, ] adam = Adam(lr=learningRate) model = Sequential() model.add(Dropout(dropoutIn, input_shape=(input_dim,))) model.add(Dense(units=neurons, input_shape=(input_dim,), kernel_constraint=maxnorm(3))) for i in range(layers-1): model.add(Dropout(dropoutHidden)) model.add(Dense(units=neurons, activation=activationFun, kernel_constraint=maxnorm(3))) model.add(Dense(units=output_dim, activation='sigmoid')) model.compile(loss='mean_squared_error',optimizer=adam) model.fit(x_data_train, y_data_train, batch_size=miniBatch, validation_split=0.1, epochs=epoch, verbose=2) predict = model.predict(x_data_test) round_predict = np.round(predict) correct = np.sum(np.all(round_…
tagged with: keras

http://stackoverflow.com/a/50853569
has comment: http://stackoverflow.com/comment/88710117
has body: i do the following path = path_d[key] os.system(r'start "{0}"'.format(path)) so, surround the path with double quotes. that way it will take care of spaces in path. if there is no default application to open, it might open command prompt. So, if its a text file do the following os.system(r'notepad "{0}"'.format(path))
downvote count: 0
has comment: http://stackoverflow.com/comment/88710331
type: Answer
has comment: http://stackoverflow.com/comment/88727686
has comment: http://stackoverflow.com/comment/88727630
has comment: http://stackoverflow.com/comment/88728018
upvote count: 1
has comment: http://stackoverflow.com/comment/88710028
answers question: http://stackoverflow.com/q/50853460
has comment: http://stackoverflow.com/comment/88709990
has comment: http://stackoverflow.com/comment/88727965
score: 1

http://stackoverflow.com/q/50798004
has comment: http://stackoverflow.com/comment/88821250
has comment: http://stackoverflow.com/comment/88601873
has comment: http://stackoverflow.com/comment/88816888
has comment: http://stackoverflow.com/comment/88602192
answer count: 1
downvote count: 0
has title: How do i access Django Model object in another view?
has comment: http://stackoverflow.com/comment/88602032
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/50800881
has comment: http://stackoverflow.com/comment/88601944
has comment: http://stackoverflow.com/comment/88601951
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88602115
type: UnansweredQuestion
has body: I have a code like this: def my_view(request): # ... data=Data.object.create(xyx) data.id # here data.id=20 time.sleep(600) # here sleep 600 sec # within 10 min how can i get data oject in another view. return HttpResponse("Done") Before completing 10 min I try to get data object in shell, But data not present Why? &gt;&gt;&gt; Data.objects.get(id=20) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/home/rails/projects/zyz/xyz/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/rails/projects/xyz/xyz1.12/lib/python3.5/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name data.models.DoesNotExist: Transfer matching query does not exist. &gt;&gt;&gt; Ques. How can i get data object that belogs to id= 20 in anohter view before return HttpResponse (Means with in 10 min). I'm getting data.models.DoesNotExist I think becouse of Data object not committed on the database. Thanks in advance.
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/88603490
type: Question
tagged with: transactions
score: 1

http://stackoverflow.com/a/71443750
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50842956
downvote count: 1
has body: Just add autouse=True as an argument to the fixture decorator. @pytest.fixture(autouse=True) def mock_func1(): def mock_ret(*args, **kwargs): return 2
upvote count: 2

http://stackoverflow.com/a/61501029
answers question: http://stackoverflow.com/q/50728615
score: 0
type: Answer
has body: maindiv = str(soup.find("body")) this returns body tag html as String. sql = "UPDATE `abc` SET `html` = %s WHERE `abc`.`id` = %s" val = (maindiv,1) mycursor.execute(sql, val) mydb.commit() Above code updates the record

http://stackoverflow.com/a/50785023
accepted answer of: http://stackoverflow.com/q/50784981
answers question: http://stackoverflow.com/q/50784981
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88579062
has body: I've tried your code with aes-256-cbc instead of aes-128-cbc in PHP, and it gives the same output. Changing the PHP encrypt method to aes-256-cbc should fix the problem..
has comment: http://stackoverflow.com/comment/88579099
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/50833685
answer count: 1
has comment: http://stackoverflow.com/comment/88672722
has comment: http://stackoverflow.com/comment/88671945
downvote count: 0
tagged with: jupyter
has answer: http://stackoverflow.com/a/69200836
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: Context: I am trying to run a ruby script that launch the following command: jupyter nbconvert --to html --execute filename.ipynb I am getting the folowing error : Executing notebook with kernel: python2 [NbConvertApp] ERROR | Error while converting 'filename.ipynb' ... ImportErrorTraceback (most recent call last) &lt;ipython-input-1-9ae86a16defc&gt; in &lt;module&gt;() ----&gt; 1 get_ipython().magic(u'matplotlib inline') 2 import matplotlib ... ImportError: No module named matplotlib ImportError: No module named matplotlib Search: After some google research I found that it is because the script is executed using python2 instead of ipython. Questions: How can I force jupyter nbconvert to use ipython ?
score: 1
has title: Run jupyter nbconvert with ipython
tagged with: ipython
type: Question

http://stackoverflow.com/comment/88429345
type: QuestionComment
has text: IndexFaces will find faces (*any* faces) in an image and add them to a Rekognition collection that you've pre-created. Do this for each of your random images. Then use SearchFacesByImage to find matches for a given image (your owner's image) in that collection. You can do this with the awscli or boto3. I'd recommend just jumping in and writing some code (it won't take much code).
comment on: http://stackoverflow.com/q/50699149
score: 0
type: Comment

http://stackoverflow.com/comment/88408819
score: 1
comment on: http://stackoverflow.com/q/50699698
has text: Better install Anaconda. it comes with all required handy tools.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50832622
type: Answer
has comment: http://stackoverflow.com/comment/88673531
score: 1
downvote count: 0
has body: You can use this if you dont mind the order of output from collections import defaultdict def sort_it(list_): res = defaultdict(list) for i, j, k in sorted(list_): res[k] = [i, j] return [[value[0], value[1], key] for key, value in res.items()] If you want it ordered as per the IDs, then just re-sort it sorted(sort_it(test_list), key=lambda x: x[-1]) Working : Input list is first sorted on basis of score, then the values are fed to a dict with ID as key and rest in list as its value, any duplicate occurence of ID's value would be replaced with new value which would be greater than previous, then re-convert it to list.
accepted answer of: http://stackoverflow.com/q/50831978
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50831978
has comment: http://stackoverflow.com/comment/88670075

http://stackoverflow.com/q/50741849
has comment: http://stackoverflow.com/comment/88491552
type: Question
has answer: http://stackoverflow.com/a/50742077
answer count: 1
tagged with: beautifulsoup
score: 0
has comment: http://stackoverflow.com/comment/88491391
accepted answer: http://stackoverflow.com/a/50742077
tagged with: python
has title: Searching BeautifulSoup after text, need to get all data from table row
type: AnsweredQuestion
has body: I have a table like this: &lt;table id="test" class="tablesorter"&gt; &lt;tr class="even"&gt; &lt;td style="background: #F5645C; color: #F5645C;"&gt;1&amp;#160;&lt;/td&gt; &lt;td&gt;Major Lazer&lt;/td&gt; &lt;td class="right"&gt;64&lt;/td&gt; &lt;td&gt;93.1.15.107&lt;/td&gt; &lt;td&gt;0x0110000105DAB310&lt;/td&gt; &lt;td class="center"&gt;No&lt;/td&gt; &lt;td class="center"&gt;No&lt;/td&gt; &lt;/tr&gt; &lt;tr class="odd"&gt; &lt;td style="background: #8FB9B0; color: #8FB9B0;"&gt;0&amp;#160;&lt;/td&gt; &lt;td&gt;Michael gunin&lt;/td&gt; &lt;td class="right"&gt;64&lt;/td&gt; &lt;td&gt;57.48.41.27&lt;/td&gt; &lt;td&gt;0x0110000631HDA213&lt;/td&gt; &lt;td class="center"&gt;No&lt;/td&gt; &lt;td class="center"&gt;No&lt;/td&gt; &lt;/tr&gt; ... &lt;/table&gt; This table has over 100 rows, in the same format. What I want to do is to search after the long id, and then find that table row and get the IP and name. For example, search after: 0x0110000105DAB310 Then find the specific table row in which this text exists, and grab the rest of the info like: Major Lazer and 93.1.15.107 table = playerssoup.find('table') table_rows = table.find_all('tr') for tr in table_rows: td = tr.find('td', text='0x0110000101517CC6') This shows me the td, but I don't know from here what to do.

http://stackoverflow.com/q/50825618
type: Question
tagged with: arrays
tagged with: gaussian
has answer: http://stackoverflow.com/a/50827691
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/99494525
has title: How do I improve a Gaussian/Normal fit in Python 3.X by using a running median?
has body: I have an array of 100x100 data points, where I'm trying to perform a Gaussian fit to each column of 100 values in the array. I then want the parameters of the Gaussian found by using the fit of the first column to be the initial parameters of the starting point for the next column to use. Let's say I start with the initial parameters of 1000, 0, and 1, and the fit finds values of 800, 3, and 1.5. I then want the fitter to use these three parameters as initial values for the next column. My code is: x = np.linspace(-50,50,100) Gauss_Model = models.Gaussian1D(amplitude = 1000., mean = 0, stddev = 1.) Fitting_Model = fitting.LevMarLSQFitter() Fit_Data = [] for i in range(0, Data_Array.shape[0]): Fit_Data.append(Fitting_Model(Gauss_Model, x, Data_Array[:,i])) Right now it uses the same initial values for every fit. Does anyone know how to perform such a running median/mean for a Gaussian fitting method? Would really appreciate any help or being pointed in the right direction, thanks!
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50825691
type: UnansweredQuestion
tagged with: curve-fitting
tagged with: python
linked to: http://stackoverflow.com/q/55943151

http://stackoverflow.com/q/50780501
score: -1
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
tagged with: python-requests
downvote count: 1
has answer: http://stackoverflow.com/a/50781517
type: Question
upvote count: 0
has title: Python Requests: able to login then access auth-restricted page, but cannot POST to page
favorite count: 0
has body: I want to build a simple Python app that changes the names of my meals on MyFitnessPal. I can login to MyFitnessPal at https://myfitnesspal.com/account/login. Once logged in, I can access my diary settings page where I can update the names of my meals using a form. My app can log in and successfully request the diary settings page via a GET request. However, my app cannot successfully POST to the diary settings page to update my meal name. I have read every bit of documentation I can find and this question is quite difficult to answer alone. I would appreciate your help tackling this issue so I may further my understanding. Code, with healthy comments, pasted below: # standard library from time import sleep from random import uniform # third party packages import requests from requests.auth import HTTPDigestAuth from bs4 import BeautifulSoup class MFP(): def __init__(self, username, password): self.username = username self.password = password # url for website self.base_url = 'https://www.myfitnesspal.com' # login action self.login_url = 'https://www.myfitnesspal.com/account/login' # page that contains diary information we want to update self.diary_url = 'https://www.myfitnesspal.com/account/diary_settings' # Firefox self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201' } # establish persistent session across class self.session = requests.Session() def login(self): # grab the session s = self.session # visit the login url via GET so we can soup it for the access token base = s.get(self.login_url) # soup the response to the login URL GET request to scrape the token soup = BeautifulSoup(base.content, "html.parser") token = soup.find('input', attrs={'name': 'authenticity_token'})['value'] # add token to headers for continued authentication self.headers.update({'authenticity_token': token}) # sleep for a moment before logging in sleep(uniform(.55,1.4)) # login to MFP login = s.post(self.login_url, headers=self.headers, verify=T…
answer count: 1

http://stackoverflow.com/q/50752668
has comment: http://stackoverflow.com/comment/88513446
has comment: http://stackoverflow.com/comment/88513419
has title: Turn a string into an operation
has answer: http://stackoverflow.com/a/50752804
has comment: http://stackoverflow.com/comment/88513385
accepted answer: http://stackoverflow.com/a/50753082
possible better answer: http://stackoverflow.com/a/50752860
has comment: http://stackoverflow.com/comment/88513438
has comment: http://stackoverflow.com/comment/88513358
has answer: http://stackoverflow.com/a/50752860
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1832940
has answer: http://stackoverflow.com/a/50753074
has comment: http://stackoverflow.com/comment/88513454
tagged with: python
score: -2
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50753082
has body: Is there any way to convert a string with variables into an operation?? For example a = 3 b = 7 str = 'a * b' # *MAGIC SOLUTION TO TURN IT INTO AN OPERATION* print (str) # Prints 21 Please, don't give others solutions for the problem, because I know it's very easy to do by a diferent way. But I really need it for a harder problem
downvote count: 3
has comment: http://stackoverflow.com/comment/88513395
has comment: http://stackoverflow.com/comment/88513558
upvote count: 1
has comment: http://stackoverflow.com/comment/88513685
has comment: http://stackoverflow.com/comment/88513533
type: Question
has comment: http://stackoverflow.com/comment/88513750

http://stackoverflow.com/q/50704236
has comment: http://stackoverflow.com/comment/88417760
has title: New column for each element of the array
accepted answer: http://stackoverflow.com/a/50704315
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88419142
type: Question
has body: I use the csv library to create a table of products. In order to then import it to the site, I need that each characteristic be written in a separate column. Adding a new row is done using simple loop: writer = csv.writer(csvfile) for product in products: writer.writerow((product['price'], product['vendor_code'], product['characteristics'])) Adding a new product: product = [] product.append({ 'price' : price, 'vendor_code' : vendor_code, 'characteristics' : characteristics, }) characteristics - array that contains each characteristic as a separate element How do I get the output file in this form: 190$ #0172 characteristic1 characteristic2 characteristic3 characteristics - initialization: try: characteristics = [] soup_characteristics = soup.find_all('tr', {'class' : 'product_card__product_characters_item clearfix'}) for ch in soup_characteristics: characteristics.append(re.sub('\s\s+|\n',' ', ch.text)) except AttributeError: characteristics = ""
answer count: 2
has answer: http://stackoverflow.com/a/50704485
has comment: http://stackoverflow.com/comment/88419054
possible better answer: http://stackoverflow.com/a/50704485
score: 0
has answer: http://stackoverflow.com/a/50704315
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88418670

http://stackoverflow.com/q/50835857
tagged with: python
has comment: http://stackoverflow.com/comment/88676387
type: AnsweredQuestion
type: Question
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/50836520
accepted answer: http://stackoverflow.com/a/50836520
has title: PyMOL to work on Python 3
upvote count: 1
downvote count: 1
has body: I am writing a program which will need to use pymol, at the moment I have only added "import pymol" to my code. I am trying find a way to not get error "no module named pymol". So pymol (which now works with python 3) is only available to install via conda (https://pymol.org/2/support.html), although, when I follow the link, it seems that this is the same installation for python 2.7. I follow that link, install it via conda, but pymol is only showing in my python 2.7 folder. If pymol developers are saying that pymol should work on python 3, is there something I am doing wrong? I have previously had issues with vtk, where I installed it, but it was also not found because of the path where it was I think. I somehow fixed it, but no luck with pymol. Any help would be appreciated. P.S. you can probably tell I am new to programming so please bear with me.
favorite count: 0
tagged with: python-3.x
tagged with: pymol

http://stackoverflow.com/comment/88437128
score: 1
has text: you could change `b'a' -> b'b'` using `ctypes`: `b = b'a'; (ctypes.c_ubyte * sys.getsizeof(b)).from_address(id(b))[-2] = 98`. The idea is from https://lameiro.wordpress.com/2010/07/18/deixando-o-interpretador-python-maluco/
comment on: http://stackoverflow.com/q/50708670
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88551323
score: 1
has text: You may have accidentally installed Python twice.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50771911

http://stackoverflow.com/q/50777561
has comment: http://stackoverflow.com/comment/88562379
has comment: http://stackoverflow.com/comment/88562252
has title: Python Pygame and Pymunk game library Non-colliding Shapes
has body: In my game I would like to create non-colliding balls. This is the code which creates blue and red balls with right and left click with mouse.. However as you can see balls collide even though I categorized them and mask them as I commented. import sys import pygame as pg from pygame.color import THECOLORS import pymunk as pm def to_pygame(p): """Small hack to convert pymunk to pygame coordinates""" return int(p[0]), int(-p[1]+600) pg.init() screen = pg.display.set_mode((600, 600)) clock = pg.time.Clock() space = pm.Space() space.gravity = (0.0, -900.0) # Walls static_body = space.static_body static_lines = [ pm.Segment(static_body, (111.0, 280.0), (407.0, 246.0), 0.0), pm.Segment(static_body, (407.0, 246.0), (407.0, 343.0), 0.0), pm.Segment(static_body, (111.0, 420.0), (407.0, 386.0), 0.0), pm.Segment(static_body, (407.0, 386.0), (407.0, 493.0), 0.0), ] for idx, line in enumerate(static_lines): line.elasticity = 0.95 if idx &lt; 2: # Lower lines. # The lower lines are in category 2, in binary 0b10. line.filter = pm.ShapeFilter(categories=2) else: # Upper lines. # The upper lines are in category 1, in binary 0b1. line.filter = pm.ShapeFilter(categories=1) space.add(static_lines) balls = [] running = True while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE: running = False if event.type == pg.MOUSEBUTTONDOWN: radius = 15 if event.button == 1 else 30 mass = 10 inertia = pm.moment_for_circle(mass, 0, radius, (0,0)) body = pm.Body(mass, inertia) body.position = to_pygame(event.pos) shape = pm.Circle(body, radius, (0,0)) shape.elasticity = 0.95 if shape.radius &gt; 25: # bin(pm.ShapeFilter.ALL_MASKS ^ 1) is '0b11111111111111111111111111111110' # That means all categories are checked for collisions except # bit 1 (the upper lines) which are ignored. #### HOW EVER BALSS COLLIDE shape.filter = pm.ShapeFilter(categories=0x1) shape.filter = pm.ShapeFilter(mask=pm.ShapeFilter.ALL_MASKS…
tagged with: pygame
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50778434
tagged with: python
tagged with: collision
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/50778434
answer count: 1
downvote count: 0
tagged with: pymunk
favorite count: 0

http://stackoverflow.com/comment/88575896
type: Comment
has text: But the vector b is changed... I hope it can always be b=[1,2,3,4,5]
comment on: http://stackoverflow.com/a/50784676
score: 0
type: AnswerComment

http://stackoverflow.com/q/50760343
linked to: http://stackoverflow.com/q/16856647
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/16856647
has body: i write this query in my flask restful api when i hit it from postman this shows the error mentioned on top. not all arguments converted during string formatting cur.execute('''DELETE FROM `students`.`std_record` WHERE `roll_num` = %s;''', (roll_num))
favorite count: 0
type: Question
tagged with: python
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has title: not all arguments converted during string formatting. flask restful api
has answer: http://stackoverflow.com/a/50761526

http://stackoverflow.com/comment/88431400
type: QuestionComment
type: Comment
has text: You cannot have "an accuracy of 20%" (or any other number), since you are in a regression setting and accuracy is only meaningful in classification ones...
score: 0
comment on: http://stackoverflow.com/q/50708074

http://stackoverflow.com/comment/88509863
score: 0
type: Comment
type: QuestionComment
has text: The vocabulary part is on the very bottom. I checked helper.py although I can't seem to find the input specification you are talking about.
comment on: http://stackoverflow.com/q/50750387

http://stackoverflow.com/comment/88696080
type: Comment
score: 0
has text: This is exactly my problem, causing the closing of connection in an ordinary manner is quite simple (and is done in multiple applications). I am looking for a solution when it is not a standard close (Specifically for 'quit debugging' purposes).
comment on: http://stackoverflow.com/a/50846073
type: AnswerComment

http://stackoverflow.com/comment/88712692
type: QuestionComment
has text: Related, but a "mirror" of https://stackoverflow.com/questions/18413748/sqlalchemy-columns-result-processing
score: 1
comment on: http://stackoverflow.com/q/50854687
type: Comment

http://stackoverflow.com/comment/88584790
type: QuestionComment
has text: `assert_frame_equal` doesn't have a return value, so I can't use it in if statements
score: 0
comment on: http://stackoverflow.com/q/50774725
type: Comment

http://stackoverflow.com/comment/88683801
score: 0
comment on: http://stackoverflow.com/q/50839266
type: Comment
type: QuestionComment
has text: Does Greenplum support database links and then you could connect Oracle and Greenplum directly and load the data bypassing Python?

http://stackoverflow.com/comment/88475874
type: QuestionComment
comment on: http://stackoverflow.com/q/50734027
has text: That's because it's trying to add the values of key "names"
score: 1
type: Comment

http://stackoverflow.com/comment/88695325
type: Comment
has text: Does expensive(x) change x? if not, why not run all of t.a(), t.b(), etc in setUp()?
score: 0
comment on: http://stackoverflow.com/q/50841845
type: QuestionComment

http://stackoverflow.com/comment/88700625
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50814066
score: 0
has text: Are you open to making a second (shuffled and split) copy of the data on the disk? There are a number of large scale data processing tools that will do that for you.

http://stackoverflow.com/comment/88579164
has text: Agree. I did not write the specifications so I have been struggling for the last week.
comment on: http://stackoverflow.com/q/50786308
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88459835
has text: Thank you for your help. Actually, I found a fix and sorry I did not know that I had to give entire code. I had to use iter function instead of ET.Element(nonTmnl).
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50711655

http://stackoverflow.com/q/50807312
has title: What does this mean? DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname])
type: Question
has answer: http://stackoverflow.com/a/55049581
upvote count: 3
has answer: http://stackoverflow.com/a/50807644
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88620934
answer count: 4
has answer: http://stackoverflow.com/a/58767917
favorite count: 0
has body: I've import a xlsx sheet into Python 3.6 by using import openpyxl and now am trying to access the Cell Object by doing the following (see below), but I immediately get an error message which I don't know what it means?: Warning (from warnings module): File "__main__", line 1 DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]). Here is my code: import openpyxl wb = openpyxl.load_workbook('c:\\users\\user1\\AppData\\Local\\Programs\\Python\\Python36-32\\example.xlsx') sheet = wb.get_sheet_by_name('Sheet1')
score: 2
tagged with: python-3.x
type: UnansweredQuestion
tagged with: openpyxl
tagged with: deprecation-warning
has answer: http://stackoverflow.com/a/58400269

http://stackoverflow.com/a/50762160
answers question: http://stackoverflow.com/q/50751554
has body: Answering based on Juanpa's suggestion: You need to import all modules also in the loaded function file. E.g.: import pandas as pd def myFunction(): pd.read_csv('file.csv')
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/88532166
has text: I am getting these errors: 'ValueError: Wrong number of items passed 4, placement implies 1' and 'KeyError: 'Sum of percentage''
type: Comment
comment on: http://stackoverflow.com/a/50741742
score: 0
type: AnswerComment

http://stackoverflow.com/a/50816405
has comment: http://stackoverflow.com/comment/88637955
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50816228
has comment: http://stackoverflow.com/comment/88638470
downvote count: 0
has body: If your string coming from file with characters escaped by backslashes, the backslashes are correctly backlashed themselves and then you can see the single backslash as double backslashes. What you certainly want is getting the escaped characters translated. You can use codecs module with unicode_escape for this: with codecs.open("&lt;yourfile&gt;", 'r', encoding="unicode_escape") as fr: print(fr.read()) If you are encountering errors, you have a flag to decide what will happen by opening the file with "unicode_escape" encoding parameter. with codecs.open("&lt;yourfile&gt;", 'r', encoding="unicode_escape", errors="ignore") as fr: print(fr.read()) You can see a full list of error handlers here: https://docs.python.org/3/library/codecs.html#error-handlers

http://stackoverflow.com/comment/88490651
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50741579
has text: No, `var2 = a` is not an expression and produces no value.

http://stackoverflow.com/a/50706580
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/88423733
upvote count: 6
has body: LogisticRegression minimises log loss, so you would expect the loss to be the .score, only negated. However, this actually returns the mean accuracy. To calculate log loss you need to use the log_loss metric: I haven't tested it, but something like this: from sklearn.metrics import log_loss model = sklearn.linear_model.LogisticRegression().fit(X_train, y_train) loss = log_loss(X_test, model.predict_proba(X_test), eps=1e-15)
has comment: http://stackoverflow.com/comment/88423162
accepted answer of: http://stackoverflow.com/q/50706220
answers question: http://stackoverflow.com/q/50706220
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88478737
score: 0
comment on: http://stackoverflow.com/q/50729702
type: Comment
has text: Hello @tahsinraza! I've prepared a solution for you. If you find it useful please remember upvote and/or choose it as answer :)
type: QuestionComment

http://stackoverflow.com/comment/88530315
score: 1
has text: Another option, without regex is to parse with [`strptime`](https://docs.python.org/3/library/time.html#time.strptime): `dt = time.strptime(data, "*Date:* %B %d, %Y at %I:%M:%S %p EDT")`.
comment on: http://stackoverflow.com/q/50760826
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50847125
accepted answer of: http://stackoverflow.com/q/50844658
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50844658
type: Answer
has body: The first issue is that print() will return None. So: founds = print(productId, productTitle, salePrice, originalPrice, imageUrl) is just equivalent to founds = None. Basically useless. So, the first thing to do is to give founds a structure. Your options are basically a dict and a list. A list is simplest to work with in your example (but not necessarily your actual code): app.py from aliexpress_api_client import AliExpress @app.route('/ali') def ali(): aliexpress = AliExpress('1234', 'bazaarmaya') data = aliexpress.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'], keywords="shoes", pageSize='40') for product in data['products']: productId = product['productId'] productTitle = product['productTitle'] salePrice = product['salePrice'] originalPrice = product['originalPrice'] imageUrl = product['imageUrl'] founds = [productId, productTitle, salePrice, originalPrice, imageUrl] return render_template('ali.html', founds=founds) Note: there's a problem either way here. The for loop is going to overwrite data on each loop, so maybe you want a dictionary but you'll need to give it unique keys. Or you define a list beforehand and apppend to it in the loop. This example will only give you the last item from the loop and it's up to you to deal with it accordingly. Then: ali.html {% extends 'layout.html' %} {% block body %} {% for found in founds %} {{found}} {{found}} {{found}} {{found}} {{foundl}} {% endfor %} {% endblock %} You can use the . notation if you pass a dictionary to the template and want to access things by key. But there are other problems to address first so this answer runs the risk of spiraling into too much depth. jinja2 syntax (in your templates) is remarkably like regular python.
score: 0

http://stackoverflow.com/comment/88498212
has text: That's just a sample that explain the issue but the full task will take a long time.
score: 0
comment on: http://stackoverflow.com/q/50744783
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50793620
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88593756
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88593545
has comment: http://stackoverflow.com/comment/88593529
has comment: http://stackoverflow.com/comment/88593336
has body: I really need some help to understand Python and class. I'm defining an ImageProcessing Class with several methods. class ImageProcessing: """ Class containing different processing operations """ def __init__(self, name, height, width): """ Defining name, height and width of image processing object """ self.name = name self.height = height self.width = width # several methods here with def. # These methods mainly used some open cv operations. def masking(self): """ Method to mask | All masks are applied manually - self MUST BE a numpy array or a scalar """ mask = cv2.rectangle(self, (0,0), (250,1200), (0,0,0), -1) return(mask) When I create an object, it is defined as belonging to ImageProcessing Class. diff = ImageProcessing("diff",1200,1600) diff = diff.masking() And so this object called "diff" could not used my others methods, such as masking, defined in my class ImageProcessing because these methods are waiting for scalar or arrays to be used and the type of my object is ImageProcessing one. I'm lost guys! Need some help on this basic things. How can I defined an object in a Class and giving it the right to be used by array methods (methods which are located in the same class)?
tagged with: class
has answer: http://stackoverflow.com/a/50797462
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88593374
tagged with: python
has comment: http://stackoverflow.com/comment/88593728
linked to: http://stackoverflow.com/q/24564610
has comment: http://stackoverflow.com/comment/88593938
has comment: http://stackoverflow.com/comment/88593365
has comment: http://stackoverflow.com/comment/88593444
has comment: http://stackoverflow.com/comment/88593777
has title: Need some help in Python with class

django-forms
tags question: http://stackoverflow.com/q/50794276
tags question: http://stackoverflow.com/q/50745685
tags question: http://stackoverflow.com/q/50837943
tags question: http://stackoverflow.com/q/50779713
tags question: http://stackoverflow.com/q/50790223
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/50707948
tags question: http://stackoverflow.com/q/50787563
tags question: http://stackoverflow.com/q/50772550
tags question: http://stackoverflow.com/q/50710718
tags question: http://stackoverflow.com/q/50746183
tags question: http://stackoverflow.com/q/50722237
tags question: http://stackoverflow.com/q/50839911
tags question: http://stackoverflow.com/q/50850793
tags question: http://stackoverflow.com/q/50792494
tags question: http://stackoverflow.com/q/50845990
tags question: http://stackoverflow.com/q/50823514
tags question: http://stackoverflow.com/q/50771539
tags question: http://stackoverflow.com/q/50743279
tags question: http://stackoverflow.com/q/50820465
tags question: http://stackoverflow.com/q/50808053
tags question: http://stackoverflow.com/q/50834900
tags question: http://stackoverflow.com/q/50784955
tags question: http://stackoverflow.com/q/50769943
tags question: http://stackoverflow.com/q/50806262
tags question: http://stackoverflow.com/q/50849385

http://stackoverflow.com/q/50777012
has body: I'm trying to execute a merge with pandas. The two files have a common key ("KEY_PLA") which I'm trying to use with a left join. But unfortunately, all columns which are transferred from the second file to the first file have NaN values. Here is what I have done so far: df_1 = pd.read_excel(path1, skiprows=1) df_2 = pd.read_excel(path2, skiprows=1) df_1.columns = ["Index", "KEY", "KEY_PLA", "INFO1", "INFO2"] df_2.columns = ["Index", "KEY_PLA", "INFO4"] df_1.drop(["Index"], axis=1, inplace=True) df_2.drop(["Index"], axis=1, inplace=True) # Merge all dataframes df_merge = pd.DataFrame() df_merge = df_1.merge(df_2, left_on="KEY_PLA", right_on="KEY_PLA", how="left") print(df_merge) This is the result: Here are the excel files: Excel1 Excel2 What is wrong with the code? I also checked the types and even converted the columns in strings. But nothing works.
tagged with: python
tagged with: merge
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50777029
downvote count: 1
type: Question
upvote count: 4
tagged with: dataframe
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50777029
answer count: 1
has title: Python: Pandas merge leads to NaN
favorite count: 0
has comment: http://stackoverflow.com/comment/88561000

http://stackoverflow.com/comment/88413048
has text: Yes, they, the urls is catch well. some url. https://edukasi.kompas.com/read/2018/05/28/21142851/evaluasi-un-smp-unbk-meminimalkan-praktek-kecurangan
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50701035
type: Comment

http://stackoverflow.com/comment/88428265
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50709396
has text: What happens if you try `df_ret.columns = df_ret.columns.str.strip()` before querying a field?
score: 0

http://stackoverflow.com/comment/88578294
comment on: http://stackoverflow.com/a/50785888
has text: @Jeremie use the `min_periods` param
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88950131
type: Comment
has text: 10.175.31.48 is non routable ip thus the tracker may not be able to connect to your python server.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50852202

http://stackoverflow.com/comment/88580163
score: 0
type: AnswerComment
has text: suppose if the user preferences are different means user 101 have Japan but user 102 have UK. in that case how to do that?
type: Comment
comment on: http://stackoverflow.com/a/50786748

http://stackoverflow.com/a/50845521
has body: Is your question "what's the reason?" The line test_list = [test_list[i].insert(1, 0) for i in range(len(test_list))] means "make a list of the return values of this expression". The return value of the expression [].insert() is None. test_list will be set to a list of Nones.
score: 0
answers question: http://stackoverflow.com/q/50845466
type: Answer

http://stackoverflow.com/q/50796359
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88599165
linked to: http://stackoverflow.com/q/19735250
answer count: 1
has title: How to run a python script in a php file?
favorite count: 0
type: UnansweredQuestion
has body: I have node js file that is running a python script. But I want to run the python script in a php file. Can anyone help me with it? I want to know the ways that don't use the functions like exec() or shell_exec() or so...
tagged with: python
tagged with: php
has answer: http://stackoverflow.com/a/50796629
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/61943000
answers question: http://stackoverflow.com/q/50747765
has body: in article_list, change from {{ article.title }} to {{ article.title }}
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/50834933
tagged with: keras
favorite count: 0
has title: Why layer number in keras does not start from 1 after deleting and recreating model?
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50835184
type: Question
has body: I am new to keras, I am trying to create a CNN model. I created one sequential model as follows- model = models.Sequential() model.add(layers.Conv2D(32, (5, 5), activation='relu', input_shape=(150, 150, 3))) model.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) print(model.summary()) I get the summary as follows- Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 146, 146, 32) 2432 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 73, 73, 32) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 71, 71, 64) 18496 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 35, 35, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 33, 33, 64) 36928 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 16, 16, 64) 0 ================================================================= Total params: 57,856 Trainable params: 57,856 Non-trainable params: 0 _________________________________________________________________ After this, I delete the model using del model and again create it using above code, I get the summary as follows- Layer (type) Output Shape Param # ================================================================= conv2d_4 (Conv2D) (None, 146, 146, 32) 2432 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 73, 73, 32) 0 _________________________________________________________________ conv2d_5 (Conv2D) (None, 71, 71, 64) 18496 _________________________________________________________________ max_pooling2d_5 (MaxPo…
accepted answer: http://stackoverflow.com/a/50835184
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50854235
tagged with: python
upvote count: 24
possible better answer: http://stackoverflow.com/a/50854402
has answer: http://stackoverflow.com/a/50854463
has title: How to draw Chinese text on the image using `cv2.putText`correctly? (Python+OpenCV)
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50854402
score: 24
linked to: http://stackoverflow.com/q/37191008
linked to: http://stackoverflow.com/q/18942605
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/50854463
has body: I use python OpenCV (Windows 10, Python 2.7) to write text in image, when the text is English it works, but when I use Chinese text it write messy code in the image. Below is my code: # coding=utf-8 import cv2 import numpy as np text = "Hello world" # just work # text = "内容理解团队" # messy text in the image cv2.putText(img, text, cord, font, fontScale, fontColor, lineType) # Display the image cv2.imshow("img", img) cv2.waitKey(0) cv2.destroyAllWindows() When text = "Hello world" # just work, below is the output image: When text = "内容理解团队" # Chinese text, draw messy text in the image, below is the output image: What's wrong? Does opencv putText don't support other language text?
has comment: http://stackoverflow.com/comment/88711777
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/59193600
has answer: http://stackoverflow.com/a/76197260

http://stackoverflow.com/comment/88509492
comment on: http://stackoverflow.com/a/50750699
has text: Thanks! I'm only just getting to grips with asyncio. Your comment helped me understand that an await is necessary to allow a context switch.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50803125
type: AcceptedAnswer
downvote count: 0
has body: This is UTF-16-BE encoding for the string engineer.1 UTF-16 uses two bytes for BMP characters (including ASCII characters), so, for example, the character e, which is Unicode (and ASCII) character number 101 (0x65 hex), shows up as the 16-bit code unit 101. In big-endian (that's what the -BE part means), the first byte is 0, and the second byte is 101. So, if your text is pure ASCII, your UTF-16 ends up looking like ASCII with an extra \0 byte before each character. The cleanest way to solve this is to open the file as a Unicode file. As a general rule, if you decode everything to unicode as part of reading it, encode back to bytes only at the very end as part of writing it, and do all the work in the middle with unicode, everything is simpler. In Python 2.7, there are two ways to do this, codecs.open or io.open. Using codecs makes your code a bit easier to port to Python 2.5, using io makes it a bit easier to port to 3.x, but it doesn't make a difference otherwise in simple cases like this. Notice that your line strings will now be unicode instead of str, so ideally you'll want your set of search strings to also be unicode values. d = {u'engineer': 0, u'conductor': 0, u'transit cop': 0} with io.open(path, encoding='utf-16-be') as f: for line in f: try: d[line.strip()] += 1 except KeyError: pass Another alternative is to read the file as binary UTF-16-BE, and make your search strings UTF-16-BE-encoded str values: d = {u'engineer': 0, u'conductor': 0, u'transit cop': 0} d = {key.encode('utf-16-be'): count for key, count in d.items()} with open(path) as f: for line in f: try: d[line.rstrip('\n\0')] += 1 except KeyError: pass Notice that I had to be careful with stripping, to make sure to remove the whole two-byte \0\n at the end instead of just the \n byte, and to not strip off the \0 byte at the start. This is just one of many ways that dealing with encoded bytes is more of a pain than dealing with Unicode. And if your final output is going to involve, say, printing …
accepted answer of: http://stackoverflow.com/q/50802891
type: Answer
answers question: http://stackoverflow.com/q/50802891
score: 2
upvote count: 2

http://stackoverflow.com/comment/88680831
type: Comment
type: QuestionComment
has text: Providing the exact error you got rather than just saying "doesn't recognize" and leaving it to the reader to understand what you meant (ie. that you were *expecting* strings in the query to be matched against local variables) would have made this easier to answer.
score: 0
comment on: http://stackoverflow.com/q/50838326

http://stackoverflow.com/a/50801031
has comment: http://stackoverflow.com/comment/88608633
answers question: http://stackoverflow.com/q/50800803
has comment: http://stackoverflow.com/comment/88608571
accepted answer of: http://stackoverflow.com/q/50800803
has comment: http://stackoverflow.com/comment/88609172
score: 0
has body: The question you ask is very broad (see here) but here are some hints for starting points: WordNet Word embeddings: word2vec, Glove The meaning difference you are looking into is quite peculiar so I suggest starting with WordNet (there are WordNets for other languages as well). The code that uses WordNet to calculate meaning differences using WordNet you can find here. Good framework to start an NLP journey is NLTK.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88608418
has comment: http://stackoverflow.com/comment/88608979
type: Answer
has comment: http://stackoverflow.com/comment/88608585

http://stackoverflow.com/a/50817913
has comment: http://stackoverflow.com/comment/88641226
type: Answer
has comment: http://stackoverflow.com/comment/88641217
has comment: http://stackoverflow.com/comment/88641285
has comment: http://stackoverflow.com/comment/88641108
score: 0
has comment: http://stackoverflow.com/comment/88641101
has body: This should work- import jsonfield from django.db import models from django_mysql.models import JSONField as MYSQLJSONField class MySampleModel(models.Model): name = models.CharField(max_length=123) json_data = jsonfield.JSONField(default={}) new_jsonfield = MYSQLJSONField(default={}) Or try: import jsonfield from django.db import models from django_mysql.models import JSONField as MYSQLJSONField def default_json(): return {'data': 'bar'} class MySampleModel(models.Model): name = models.CharField(max_length=123) json_data = jsonfield.JSONField(default={}) new_jsonfield = MYSQLJSONField(default=default_json) Hope this helps :)
answers question: http://stackoverflow.com/q/50817695
has comment: http://stackoverflow.com/comment/88641328

http://stackoverflow.com/comment/88569138
has text: Just to be sure, can you try running `import tensorflow` in your Python version 2.7.14 directly? If you get an import error there too, you need to `pip install` the tensorflow library.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50736394

http://stackoverflow.com/q/50777849
has title: From conda create requirements.txt for pip3
tagged with: pip
has comment: http://stackoverflow.com/comment/88768960
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50782940
possible better answer: http://stackoverflow.com/a/67335464
has comment: http://stackoverflow.com/comment/88563107
has comment: http://stackoverflow.com/comment/88562882
has comment: http://stackoverflow.com/comment/88799708
has body: I usually use conda to manage my environments, but now I am on a project that needs a little more horsepower than my laptop. So I am trying to use my university's workstations which have new Intel Xeons. But I don't have admin rights and the workstation does not have conda so I am forced to work with virtualenv and pip3. How do I generate a requirements.txt from conda that will work with pip3 and venv? conda list -e &gt; requirements.txt does not generate a compatible file: = is not a valid operator. Did you mean == ? The conda output is: # This file may be used to create an environment using: # $ conda create --name &lt;env&gt; --file &lt;this file&gt; # platform: osx-64 certifi=2016.2.28=py36_0 cycler=0.10.0=py36_0 freetype=2.5.5=2 icu=54.1=0 libpng=1.6.30=1 matplotlib=2.0.2=np113py36_0 mkl=2017.0.3=0 numpy=1.13.1=py36_0 openssl=1.0.2l=0 pip=9.0.1=py36_1 pyparsing=2.2.0=py36_0 pyqt=5.6.0=py36_2 python=3.6.2=0 python-dateutil=2.6.1=py36_0 pytz=2017.2=py36_0 qt=5.6.2=2 readline=6.2=2 scikit-learn=0.19.0=np113py36_0 scipy=0.19.1=np113py36_0 setuptools=36.4.0=py36_1 sip=4.18=py36_0 six=1.10.0=py36_0 sqlite=3.13.0=0 tk=8.5.18=0 wheel=0.29.0=py36_0 xz=5.2.3=0 zlib=1.2.11=0 I thought I would just manually change all = to == but the there are two = in the conda output. Which one to change? Surely there is an easier way? EDIT: pip freeze &gt; requirements.txt gives: certifi==2016.2.28 cycler==0.10.0 matplotlib==2.0.2 matplotlib-venn==0.11.5 numpy==1.13.1 pyparsing==2.2.0 python-dateutil==2.6.1 pytz==2017.2 scikit-learn==0.19.0 scipy==0.19.1 six==1.10.0
linked to: http://stackoverflow.com/q/35245401
tagged with: conda
has comment: http://stackoverflow.com/comment/88562781
type: Question
has comment: http://stackoverflow.com/comment/88831536
linked to: http://stackoverflow.com/q/62885911
score: 263
downvote count: 2
has comment: http://stackoverflow.com/comment/89811325
has comment: http://stackoverflow.com/comment/88800697
has comment: http://stackoverflow.com/comment/89826612
has answer: http://stackoverflow.com/a/57480547
has answer: http://stackoverflow.com/a/77607283
has comment: http://stackoverflow.com/comment/88827505
has answer: http://stackoverflow.com/a/77644831
has answer: http://stackoverflow.com/a/63230125
has comment: http://stackoverflow.com/comment/88562726
has answer: http://stackoverflow.com/a/67335464
has comment: http://stackoverflow.com/comment/88800796
has answer: http://stackoverflow.com/a/57845418
accepted answer: http://stackoverflow.com/a/57845418
has answer: http://stackoverflow.com/a/77621953
has comment: http://stackoverflow.com/comment/88834184
has comment: http://stackoverflow.com/comment/89810907
answer count: 10
tagged with: python
has answer: http://stackoverflow.com/a/73010045
has answer: http://stackoverflow.com/a/72223300
upvote count: 265
has comment: http://stackoverflow.com/comment/88795431
favorite count: 0
has comment: http://stackoverflow.com/comment/88797677
tagged with: python-3.x

http://stackoverflow.com/comment/88616812
score: 0
type: Comment
type: QuestionComment
has text: yes you're right. i redefined and am now getting the correct answers all the way through. i was hoping it was something simple.
comment on: http://stackoverflow.com/q/50805308

http://stackoverflow.com/comment/88644981
type: Comment
comment on: http://stackoverflow.com/a/50819290
has text: What if I want to find change from 0 to any integer?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88562453
comment on: http://stackoverflow.com/q/50777577
type: Comment
type: QuestionComment
has text: @PatrickArtner ah yes a set is required, im new to python so am finding it quite difficult to adapt
score: 0

http://stackoverflow.com/q/50837602
has answer: http://stackoverflow.com/a/64801864
upvote count: 3
has answer: http://stackoverflow.com/a/52570211
has comment: http://stackoverflow.com/comment/88680405
has title: ImportError: cannot import name 'moduleTNC' - python
has answer: http://stackoverflow.com/a/50837704
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88680290
answer count: 3
downvote count: 0
tagged with: scikit-learn
favorite count: 0
linked to: http://stackoverflow.com/q/44490337
type: UnansweredQuestion
has body: I'm having a problem in python when I try to import linear_model from sklearn library: from sklearn import linear_model. I have just installed it via pip simply in this way: pip install sklearn. I know that to avoid this error suffices uninstall and reinstall sklearn, but it didn't work. I also installed it via conda but opening the idle (is that correct?) it gives the same error. How to avoid it? NB: If I use jupyter from conda it works well as it should.
tagged with: python

http://stackoverflow.com/q/50811070
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/88627639
downvote count: 0
has title: cannot print df.shape, and I read it in dataframe format from pandas
has answer: http://stackoverflow.com/a/50811454
favorite count: 0
tagged with: xpath
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50811454
has comment: http://stackoverflow.com/comment/88627829
has answer: http://stackoverflow.com/a/50811108
has body: cannot print df.shape, and it read in dataframe format already from pandas, thanks ! # -*- coding:UTF-8 -*- from pyvirtualdisplay import Display from selenium import webdriver import pandas as pd display = Display(visible=0, size=(1024, 768)) display.start() driver = webdriver.Firefox() driver.get("http://www.fdmbenzinpriser.dk/searchprices/5/") lines = [event.get_attribute('outerHTML') for event in driver.find_elements_by_xpath('//table[@id="sortabletable"]')] df = pd.read_html(lines[0]) print df.shape driver.close() display.stop() Output: AttributeError: 'list' object has no attribute 'shape' lines[0] return: [ Unnamed: 0 Pris Adresse Tidspunkt 0 NaN 8.99 Odinsvej 2 4100 Ringsted 11 timer 55 m 1 NaN 9.09 Sdr.Havnegade 3 6000 Kolding 14 timer 48 m 2 NaN 9.09 Vestermarksvej 2 6600 Vejen 16 timer 35 m 3 NaN 10.99 Bøsbrovej 92B 8940 Randers SV 21 timer 1 m
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88628914
score: 1
has comment: http://stackoverflow.com/comment/88628363
accepted answer: http://stackoverflow.com/a/50811108
tagged with: webdriver
type: Question

http://stackoverflow.com/q/50805164
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52243973
accepted answer: http://stackoverflow.com/a/52243973
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88673017
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88713450
favorite count: 0
tagged with: capstone
has title: Error when trying to disassemble with winappdbg using captsone
tagged with: python
tagged with: disassembly
has body: I'm using the winappdbg library to try and perform a disassemble using the following code: thread = evt.get_thread() pc = thread.get_pc() code = thread.disassemble_around(pc) where evt is the event context getting passed into an access_violoation method. This is being executed on Windows 10 64bit via 64bit python debugging a 64bit process and using the 64bit capstone install. There error I'm receiving is: ... File "C:\Python27\lib\site-packages\winappdbg\disasm.py", line 570, in decode mnemonic = instr.mnemonic File "C:\Python27\lib\site-packages\capstone\__init__.py", line 569, in __getattr__ raise CsError(CS_ERR_DETAIL) CsError: Details are unavailable (CS_ERR_DETAIL) I have tried running some of the capstone examples from here http://www.capstone-engine.org/lang_python.html separately and it works ok. Any help appreciated on this one :)
downvote count: 0
score: 1

http://stackoverflow.com/comment/88622341
type: AnswerComment
comment on: http://stackoverflow.com/a/50808290
score: 0
has text: the answer to the first question seems promising. I tried it, but the tile method gives an error, like so: `List of Tensors when single Tensor expected`
type: Comment

http://stackoverflow.com/comment/88443383
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50716403
has text: @MartinThoma No I corrected two typos. I just copied and pasted an example from the mentioned website. Is my python version has a problem?

http://stackoverflow.com/q/50704080
score: 0
accepted answer: http://stackoverflow.com/a/50706955
type: Question
linked to: http://stackoverflow.com/q/866272
has body: I have 2 models Listing and Image, where a listing can have multiple images. class Listing(models.Model): title = models.CharField(max_length=100, blank=False) class ListingImage(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='images') image = models.ImageField(blank=True) Ideally, I wanted to create such listings on a single page e.g. fill in all form information AND add images on the same page. It seems that this is not possible (if it's please let me know, but note that dropzone.js is Ajax) to handle 2 forms with a single view and I have made the following workarounds: Create listings first, add 2nd step to add listings to created model Create a placeholder listing, add images to it (via Ajax) and on form submit, change the placeholder information. Which method is better? views.py def add_image(request): # process images: problem we have no listing_instance to add them to if request.method == 'POST': form = ListingImageForm(request.POST, request.FILES) if form.is_valid(): ListingImage.objects.create(pk=None, listing=listing_instance) return HttpResponse( json.dumps({ "result": True, }), content_type="application/json" ) I'm looking for methodology advice. For example, to create a listing with images, do I need to first create the listing and then add images (2 steps) or add images first and listing information? My problem is that if I do that, the listing is not yet created when I add the images using Ajax.
has comment: http://stackoverflow.com/comment/88419284
answer count: 1
has answer: http://stackoverflow.com/a/50706955
tagged with: dropzone.js
has comment: http://stackoverflow.com/comment/88419625
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Django and Dropzone.js methodology, creating an instance with images

http://stackoverflow.com/comment/88552890
type: Comment
comment on: http://stackoverflow.com/a/50768109
type: AnswerComment
has text: I am trying to send an XML file not JSON data, will this approach work ?
score: 0

http://stackoverflow.com/a/50759281
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88526276
has body: You are trying to open a folder for writing: f = open(r"C:\Users\Grty\Desktop\de", "w+") But this is a folder, which can't be opened using open() even in "r" mode, because it isn't a file, and if you try, Windows will say access denied. As you get each filename, open that: for filename in os.listdir(os.getcwd()): with open(filename) as f: content = f.read()
type: Answer
accepted answer of: http://stackoverflow.com/q/50759182
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50759182

http://stackoverflow.com/q/50836608
accepted answer: http://stackoverflow.com/a/50836786
answer count: 3
has title: How to read a csv file and plot confusion matrix in python
tagged with: http://stackoverflow.com/tag/csv
has body: I have a CSV file with 2 columns as actual,predicted 1,0 1,0 1,1 0,1 .,. .,. How do I read this file and plot a confusion matrix in Python? I tried the following code from a program. import pandas as pd from sklearn.metrics import confusion_matrix import numpy CSVFILE='./mappings.csv' test_df=pd.read_csv[CSVFILE] actualValue=test_df['actual'] predictedValue=test_df['predicted'] actualValue=actualValue.values predictedValue=predictedValue.values cmt=confusion_matrix(actualValue,predictedValue) print cmt but it gives me this error. Traceback (most recent call last): File "confusionMatrixCSV.py", line 7, in &lt;module&gt; test_df=pd.read_csv[CSVFILE] TypeError: 'function' object has no attribute '__getitem__'
tagged with: confusion-matrix
has comment: http://stackoverflow.com/comment/88676882
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50836786
score: -1
possible better answer: http://stackoverflow.com/a/50836795
type: Question
has answer: http://stackoverflow.com/a/50836795
has answer: http://stackoverflow.com/a/51085910
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/q/50791742
answer count: 0
has body: I am currently creating a new class in a module, in Python 3.6 with Pyzo, and some of the instance methods I have created do not appear as so in the module's help section. Why does this happen? Here is the code and the help section: # Module polynoms """ Contains a Polynom class, in which a polynom is basically the list of its coefficients. Also contains object methods that help adding two polynoms (they will be turned into __add__ and other special methods soon, this was the first version I have written.) pln is an abbreviation for Polynom. """ from functools import wraps # I was told in a tutorial to import this function # in order to keep information about the methods I need to decorate. class Polynom : """ A way to represent polynoms """ def __init__(self,*coeff) : print(list(*coeff)) for i in list(*coeff) : assert type(i) == float or type(i) == int assert len(*coeff) &gt; 0 self.coeff = list(*coeff) # Only one attribute def __repr__(self) : return str(self.coeff) def verif_pln(f) : """ Decorator that verifies that the arguments given to f are polynoms. """ @wraps def wrapper(*arg_f) : try : for i in arg_f : type(i) == Polynom except AssertionError : print("Enter a valid Polynom") return wrapper @verif_pln def degre(P) : """ Renvoie le degré du polynôme.""" if P == [0] : return "-infini" return len(P)-1 @verif_pln def somme(P,Q) : """ Adds two polynoms. """ S = [ 0 for i in range(max(len(P),len(Q)))] for i in range(min(len(P),len(Q))) : S[i] = P[i] + Q[i] return S def prod_sc(P,k) : """ Multiply P by a number k. """ P2=[] for p in P : p*=k P2.append(p) return P2 So this is my class. This is the only thing written in the file. When I execute the file and type help(Polynom) in the Shell, here is what I get: Help on class Polynom in module __main__: class Polynom(builtins.object) | A way to represent polynoms | | Methods defined here: | | __init__(self, *coeff) | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) | Return repr(self). |…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88589813
has comment: http://stackoverflow.com/comment/88589724
tagged with: methods
type: Question
has comment: http://stackoverflow.com/comment/88590024
tagged with: class
score: 0
has title: Methods appear as data attributes
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88589649

http://stackoverflow.com/q/50807584
upvote count: 1
has body: I'm trying to create a tool in Photoshop through python that creates a gradient map layer. When searching through the Adobe VBScript Reference Documentation, the coder is supposed to be able to create a new layer and set its "kind" by executing the following code: GMapLayer = self.doc.artLayers.Add() GMapLayer.Kind = 13 setting the kind to 13 should create a Gradient Map Adjustment layer. The problem is, this code only works for the first 2 out of 23 entries. a kind of 1 creates a standard empty layer, a kind of 2 creates a text layer, all other numbers throw out this error: _ctypes.COMError: (-2147213311, None, (None, None, None, 0, None)) The documentation from adobe doesn't specify how to use the other 21 constants. Anyone ever encounter this?
type: Question
tagged with: vbscript
has answer: http://stackoverflow.com/a/74414000
answer count: 2
downvote count: 0
tagged with: photoshop
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/66046039
tagged with: adobe
has title: Can't set Art Layer Kind in Photoshop
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/50840159
score: -1
upvote count: 0
has answer: http://stackoverflow.com/a/50843771
answer count: 1
tagged with: virtualenv
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88686009
accepted answer: http://stackoverflow.com/a/50843771
has comment: http://stackoverflow.com/comment/88686040
has comment: http://stackoverflow.com/comment/88685159
has body: I have been having trouble using the requests package in Python 3.6.5. If I run Python 3.5, it works, but not if I run 3.6.5. I have been trying to remedy this problem by using a virtual environment, but have not had any luck. I have created the virtualenv using this: mkvirtualenvwrapper -p /usr/local/bin/python3.5 env_test When I activate that environment and type python -V, it tells me it is using 3.6.5 still. When I type python3.5 -V though, it tells me it is using Python 3.5.5, and which python3.5 says it is sourced in my virtual environment folder. I guess that virtualenv is installing other versions of Python into the environment as well, and using 3.6.5 as the default, which I don't understand why, but I need it to access python3.5 when I type python. What can I do here?
has title: Can't force virtualenv to use Python 3.5
downvote count: 1
has comment: http://stackoverflow.com/comment/88684257
type: Question

http://stackoverflow.com/q/50763427
has comment: http://stackoverflow.com/comment/88534522
has answer: http://stackoverflow.com/a/50763710
has comment: http://stackoverflow.com/comment/88534548
tagged with: python
has title: Apply on Dataframe returning all None
possible better answer: http://stackoverflow.com/a/50763491
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50763576
accepted answer: http://stackoverflow.com/a/50763576
tagged with: apply
has answer: http://stackoverflow.com/a/50763506
type: Question
has body: I am trying to multiply the values of a column by 12 if that row/column isn't None. I have tried: def length_inches(x): if x is not None: int(x)*12 df['LENGTH'] = df['LENGTH'].notnull().apply(length_inches) And I have tried: def length_inches(x): int(x)*12 df['LENGTH'] = df['LENGTH'].notnull().apply(length_inches) But it's returning all None in the Length column. Here is my dataframe: DESCRIPTION LENGTH WIDTH GAUGE \ 0 STRETCH FILM BENCHMARK GREEN 28.5" X 10000' ... 10000 28.5 51 1 STRETCH FILM TORQUE 16X1500 4RL/CS ... 1500 16 31.5 2 STRETCH FILM TORQUE 16X1500 4RL/CS ... 1500 16 31.5 3 STRETCH FILM TORQUE 16X1500 4RL/CS ... 1500 16 31.5 4 STRETCH FILM BENCHMARK OPTIMUM 30 X 7500' 20R... 7500 30 61 5 STRETCH FILM TORQUE 16X1500 4RL/CS ... 1500 16 31.5 6 STRETCH FILM TORQUE 16X1500 4RL/CS ... 1500 16 31.5 7 STRETCH FILM BENCHMARK OPTIMUM 20" X 7500' 40... None None None How can I account for the None's in this dataframe and still run the calculation over df['LENGTH'] The type of that series is LENGTH object If that row is None I would like to just pass.
has comment: http://stackoverflow.com/comment/88534594
tagged with: series
has comment: http://stackoverflow.com/comment/88534558
score: 0
tagged with: pandas
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50763491
answer count: 4
favorite count: 0

http://stackoverflow.com/a/50715975
has comment: http://stackoverflow.com/comment/88440974
has comment: http://stackoverflow.com/comment/88443173
score: 0
has comment: http://stackoverflow.com/comment/88441116
answers question: http://stackoverflow.com/q/50715435
has comment: http://stackoverflow.com/comment/88443651
type: Answer
has comment: http://stackoverflow.com/comment/88442799
has comment: http://stackoverflow.com/comment/88444199
has comment: http://stackoverflow.com/comment/88440954
has comment: http://stackoverflow.com/comment/88444186
has comment: http://stackoverflow.com/comment/88442365
has comment: http://stackoverflow.com/comment/88441691
has body: According to muiruri_samuel@train:~/webapp/chatsys$ python manage.py test chat.tests command, you're running the code from folder webapp/chatsys. So it will be a working directory. Thus it won't find chromedriver in subdirectories, including ./chat. Try moving chromedriver to /usr/bin for example. And make sure it's in PATH variable: echo $PATH

http://stackoverflow.com/q/50704991
tagged with: anki
downvote count: 0
has body: How to make example sentences show in italic &amp; in a new line in anki addon "Autodefine". It's written in python. I spent couple of hours messing with it but to no avail. source toReturn = "" for definition in definitionArray: lastFunctionalLabel = "" toPrint = "" for dtTag in definition.findall("dt"): if dtTag.tail == "obsolete": dtTag.tail = "" #take away the tail word so that when printing it does not show up. if IGNORE_ARCHAIC: continue # We don't really care for 'verbal illustrations' or 'usage notes', even though they are occasionally useful. for usageNote in dtTag.findall("un"): dtTag.remove(usageNote) for verbalIllustration in dtTag.findall("vi"): dtTag.remove(verbalIllustration) # Directional cross reference doesn't make sense for us for dxTag in dtTag.findall("dx"): for dxtTag in dxTag.findall("dxt"): for dxnTag in dxtTag.findall("dxn"): dxtTag.remove(dxnTag) toPrint = ET.tostring(dtTag, "", "xml").strip() # extract raw XML from &lt;dt&gt;...&lt;/dt&gt; toPrint = toPrint.replace("&lt;sx&gt;", "; ") # attempt to remove 'synonymous cross reference tag' and replace with semicolon toPrint = toPrint.replace("&lt;dx&gt;", "; ") # attempt to remove 'Directional cross reference tag' and replace with semicolon toPrint = re.sub('&lt;[^&gt;]*&gt;', '', toPrint) # remove all other XML tags toPrint = re.sub(':', '', toPrint) # remove all colons, since they are usually useless and have been replaced with semicolons above toPrint = toPrint.replace(" ; ", "; ").strip() # erase space between semicolon and previous word, if exists, and strip any extraneous whitespace toPrint += "&lt;br&gt;\n"
favorite count: 0
has title: Customizing python script (anki addon)
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/50731058
tagged with: snappy
upvote count: 1
favorite count: 0
has title: Python-snappy: How can I combine multiple compressed snappy files into one?
type: UnansweredQuestion
tagged with: python
downvote count: 0
answer count: 0
score: 1
has body: I have a parallel function which is compressing a large number of files using python-snappy. Is there a way to combine all the returned compressed streams into one snappy file?
type: Question
tagged with: python-2.7

http://stackoverflow.com/comment/88565512
type: QuestionComment
comment on: http://stackoverflow.com/q/50779272
has text: Can you add a traceback of the error? It looks like your variables are not global.
score: 0
type: Comment

http://stackoverflow.com/q/50729712
has comment: http://stackoverflow.com/comment/88467259
accepted answer: http://stackoverflow.com/a/50730355
has comment: http://stackoverflow.com/comment/88468372
has title: Reading a csv persisted list of floats back into a list of floats
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88467306
has body: I have persisted a list of floats in a csv file and it appears thus (a single row). "[6.61501123e-04 1.23390303e-04 1.59454121e-03 2.17852772e-02 : 3.02987776e-04 3.83064064e-03 6.90607396e-04 3.30468375e-03 2.78064613e-02]" Now when converting reading back to a list, I am using the ast literal_eval approach: probs = [float(p) for p in ast.literal_eval(row['prob_array'])] And I get this error: probs = [float(p) for p in ast.literal_eval(row['prob_array'])] File "/Users/santino/anaconda/lib/python2.7/ast.py", line 49, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "/Users/santino/anaconda/lib/python2.7/ast.py", line 37, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "&lt;unknown&gt;", line 1 [6.61501123e-04 1.23390303e-04 1.59454121e-03 2.17852772e-02 ^ SyntaxError: invalid syntax Not sure how I can instruct ast to read the exponent syntax, or am I wrong in assuming it's the exponent syntax that is causing the exception. Edit: I used csv.DictWriter to persist into the csv file. Is there a different way I should be persisting? Edit2: with open("./input_file.csv","w") as r: writer = csv.DictWriter(r,fieldnames=["item_id","item_name","prob_array"]) writer.writeheader() res_list = ... for i,res in enumerate(res_list): row_dict = {} row_dict['item_id'] = id_list[i] row_dict['prob_array'] = res row_dict['item_name'] = item_list[i] writer.writerow(row_dict)
has comment: http://stackoverflow.com/comment/88467225
has comment: http://stackoverflow.com/comment/88467279
type: Question
has comment: http://stackoverflow.com/comment/88467344
has answer: http://stackoverflow.com/a/50730355
tagged with: abstract-syntax-tree
has comment: http://stackoverflow.com/comment/88467630
has comment: http://stackoverflow.com/comment/88467441
score: 0
answer count: 1

http://stackoverflow.com/comment/88674385
type: QuestionComment
comment on: http://stackoverflow.com/q/50835156
type: Comment
has text: So, to answer your first question, it is stored contiguously.
score: 0

http://stackoverflow.com/comment/88475536
type: QuestionComment
has text: Is there a particular package that you would like to download?
comment on: http://stackoverflow.com/q/50732441
score: 0
type: Comment

http://stackoverflow.com/q/50735075
favorite count: 0
has answer: http://stackoverflow.com/a/66538684
tagged with: python
has body: from google.cloud import bigquery query = """ select * from emp where emp_name=@emp_name""" query_params = [bigquery.ScalarQueryParameter('emp_name', 'STRING', 'name')] job_config = bigquery.QueryJobConfig() job_config.query_parameters = query_params client = bigquery.Client() query_job = client.query(query, job_config=job_config) result = query_job.result() How can I write the result to Google Cloud Storage instead of writing it to the CSV and uploading it to cloud storage bucket?
has answer: http://stackoverflow.com/a/75302568
has answer: http://stackoverflow.com/a/63724125
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50737688
has answer: http://stackoverflow.com/a/50736126
upvote count: 9
has title: How to write query result to Google Cloud Storage bucket directly?
has answer: http://stackoverflow.com/a/53428990
tagged with: google-bigquery
tagged with: google-cloud-storage
type: Question
score: 9
answer count: 8
has answer: http://stackoverflow.com/a/63839065
tagged with: google-cloud-platform
downvote count: 0
has answer: http://stackoverflow.com/a/57213740

http://stackoverflow.com/comment/88717984
type: QuestionComment
has text: you mean separating the columns? Yep, pretty much like I posted it.
score: 0
comment on: http://stackoverflow.com/q/50842783
type: Comment

http://stackoverflow.com/q/50844969
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88693763
type: Question
has comment: http://stackoverflow.com/comment/88693447
has comment: http://stackoverflow.com/comment/88693619
has body: Why value_sides does not have any value?. I planned to write number into entry_side and pass value to value_sides. Don't mind order of widgets and also some of code was cut out to not clutter up the view. class WindowFunctions: def __init__(self, root): self.root = root self.dice = Die() self.data = Entry(root) def taking(self): value_sides = WindowFunctions(self.root).entry_side.get() # Here is the problem value_throw = 1000 value_dies = 2 self.dice.generate_sides (value_sides) result = self.dice.generate_results (value_throw, value_dies) frequencies = self.dice.generate_frequencies (result) def window(self): # ----Entry-------------------------- entry_side = Entry (self.root) entry_side.pack() entry_throw = Entry (self.root) entry_throw.pack() entry_dice = Entry (self.root) entry_dice.pack() # ---Button----------------------------------------- button_generate = Button(self.root, text='Generate', command=WindowFunctions(self.root).taking) button_generate.pack() EDIT: Here is file with root root = Tk() root.bind('&lt;Escape&gt;', quit) die_function = WindowFunctions(root) die_function.window() root.mainloop()
downvote count: 0
has title: Passing value Entry to value_sides in Python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50885938
score: 4
accepted answer of: http://stackoverflow.com/q/50822656
has comment: http://stackoverflow.com/comment/88773592
answers question: http://stackoverflow.com/q/50822656
type: AcceptedAnswer
downvote count: 0
has body: So I was able to partially figure this out by digging into the IPython source code. It makes use of the builtin module linecache, which contains functions for reading source code from files and caching the results. The inspect and traceback modules both use this module to get the source of a function. The solution is to create the function the same way as in the question, but using compile with a made-up and unique file name: source = 'def foo(x, y):' + '\n\t' + 'return x / y' filename = '&lt;dynamic-123456&gt;' # Angle brackets may be required? code = compile(source, filename, 'exec') g = {numpy: numpy, ...} # Modules and such required for function l = {} exec(src, g, l) func = l['foo'] linecache contains a variable cache which is a dictionary mapping file names to (size, mtime, lines, fullname) tuples. You can simply add an entry for the fake file name: lines = [line + '\n' for line in source.splitlines()] import linecache linecache.cache[filename] = (len(source), None, lines, filename) The function will then work with inspect.getsource(), IPython's ?/?? syntax, and in IPython tracebacks. However, it still doesn't seem to work in built-in tracebacks. This is mostly sufficient for me because I almost always work in IPython. EDIT: see user2357112's comment below for how to get this working with traceback printing in the builtin interpreter.
type: Answer
upvote count: 4

http://stackoverflow.com/comment/88581641
comment on: http://stackoverflow.com/q/50783978
has text: Thanks ImportanceOfBeingErnest! Whether I use `plt.ion()` or not, I observe the same behaviour: cmd+tab does not allow me to switch focus to matplotlib's figure window. Can you offer me some pointers as to why I get this? Or is this the natural, expected behaviour? Thanks again!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88471669
score: 1
comment on: http://stackoverflow.com/a/50731816
type: AnswerComment
type: Comment
has text: @sudonym yes, give me a minute, I'll add some more info ;-)

http://stackoverflow.com/comment/88701429
has text: Ok. When you navigate to `settings` -> `project Interpreter` you will see all the installed packages in the venv which you have selected. If the dependencies are listed in the table then no need to install those. Otherwise you need to install `atari` using the process mentioned above
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50849216
score: 0

http://stackoverflow.com/a/50755865
score: 1
upvote count: 1
has body: Another way is using map functions alist = [['a'], ['b'], ['c', 'd'], ['e'], ['f', 'g']] reducedlist = list(map((lambda x: x[:1]), alist)) print(reducedlist) This is creating a new list from the existing. Iterating over the list and deleting would be the best approach if you want to do it in-place
type: Answer
answers question: http://stackoverflow.com/q/50755646
downvote count: 0

http://stackoverflow.com/a/50754863
downvote count: 0
has body: Use between by Series created by map with another by subtracted by one day, filter by boolean indexing: s = df2['customer_id'].map(df1.set_index('customer_id')['timestamp']) df = df2[df2['timestamp'].between(s - pd.Timedelta(1, unit='d'), s)] print (df) transaction_id customer_id timestamp 1 2 1 2018-06-03 02:56:52 2 3 1 2018-06-03 12:56:52 3 4 2 2018-06-03 12:40:51 4 5 2 2018-06-03 18:40:51 Detail: print (s) 0 2018-06-03 17:56:52 1 2018-06-03 17:56:52 2 2018-06-03 17:56:52 3 2018-06-03 18:42:51 4 2018-06-03 18:42:51 5 2018-06-03 18:42:51 Name: customer_id, dtype: datetime64[ns]
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50754730
answers question: http://stackoverflow.com/q/50754730
type: AcceptedAnswer

http://stackoverflow.com/q/50821527
tagged with: execution-time
type: Question
has body: I read my university class theoretically the order of growth of functions and tried implementing it practically at home. Although the order of growth turned out to be exact the same as in textbooks but their executing time changes with every single time I execute the program. Why is that? Source Code import time import math from tabulate import tabulate n=eval(input("Enter the value of n: ")); t1=time.time() a=12 t2=time.time() A=t2-t1 t3=time.time() b=n t4=time.time() B=t4-t3 t5=time.time() c=math.log10(n); t6=time.time() C=t6-t5 t7=time.time() d=n*math.log10(n); t8=time.time() D=t8-t7 t9=time.time() e=n**2 t10=time.time() E=t10-t9 t11=time.time() f=2**n t12=time.time() F=t12-t11 print(tabulate([['constant',a,A], ['n',b,B], ['logn',c,C], ['nlogn',d,D], ['n**2',e,E], ['2**n',f,F]], headers=['Function', 'Value', 'Time'])) templist= [A,B,C,D,E,F] print("The time order in acsending order is: ", sorted(templist,key=int)) First Execution naufil@naufil-Inspiron-7559:~/Desktop/python$ python3 time_order.py Enter the value of n: 100 Function Value Time ---------- --------------- ----------- constant 12 2.14577e-06 n 100 1.43051e-06 logn 2 4.1008e-05 nlogn 200 3.57628e-06 n**2 10000 3.33786e-06 2**n 1.26765e+30 3.8147e-06 The time order in acsending order is: [2.1457672119140625e-06, 1.430511474609375e-06, 4.100799560546875e-05, 3.5762786865234375e-06, 3.337860107421875e-06, 3.814697265625e-06] Second Execution naufil@naufil-Inspiron-7559:~/Desktop/python$ python3 time_order.py Enter the value of n: 100 Function Value Time ---------- --------------- ----------- constant 12 2.14577e-06 n 100 1.19209e-06 logn 2 4.64916e-05 nlogn 200 4.05312e-06 n**2 10000 3.33786e-06 2**n 1.26765e+30 3.57628e-06 The time order in acsending order is: [2.1457672119140625e-06, 1.1920928955078125e-06, 4.649162292480469e-05, 4.0531158447265625e-06, 3.337860107421875e-06, 3.5762786865234375e-06]
has title: Why the executing time of functions not constant?
has answer: http://stackoverflow.com/a/50822056
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50821626
linked to: http://stackoverflow.com/q/556405
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88648641
has comment: http://stackoverflow.com/comment/88648214

http://stackoverflow.com/a/50762868
has comment: http://stackoverflow.com/comment/88537059
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50762627
accepted answer of: http://stackoverflow.com/q/50762627
type: Answer
has comment: http://stackoverflow.com/comment/88534473
has body: When you are running python in the terminal, it is looking up your default path to your the python command. In this case, anaconda probably put a line in your shell profile specify the path to the anaconda version, which is why you are seeing it in the interpreter when you run python from either directory. Secondly, you can set up a conda environment to download app specific dependencies without interfering with your default set up by conda create --name myenv source activate myenv conda install packagename This will install it in the myenv environment only. To deactivate the environment just run source deactivate Here is the documentation on that https://conda.io/docs/user-guide/tasks/manage-environments.html
has comment: http://stackoverflow.com/comment/88536929
score: 1
has comment: http://stackoverflow.com/comment/88537996
upvote count: 1

command-line-arguments
tags question: http://stackoverflow.com/q/50744516
type: Tag
tag name: command-line-arguments
tags question: http://stackoverflow.com/q/50781915

http://stackoverflow.com/a/50779970
answers question: http://stackoverflow.com/q/50779879
upvote count: 1
downvote count: 0
type: Answer
has body: Your are iterating over an empty range. for i in range(38050, 38050): The size of this range is 0. Try to increase the max by 1. for i in range(38050, 38051):
score: 1

http://stackoverflow.com/q/50829492
has body: I have a perfectly normal pandas dataframe which I create after loading this dataset: https://www.kaggle.com/tmdb/tmdb-movie-metadata/data As you can see, the genres column contains a nested structure which appears to be a list of dictionaries, or json objects depending on how you see it? The keys of these dictionaries are 'id' and 'name'. Anyways, I have tried everything including transforming the column into a json with tojson(), or using pandas json_normalize() method without any luck. If I use json_normalize() I get an AttributeError: 'str' object has no attribute 'itervalues': pd.io.json.json_normalize(obj_movies['genres'], meta = ['id','name']) In reality, my goal would be to parse this list to create a set of unique genres names for each row...
has title: Extract list of JSON objects in string form from Pandas Dataframe column
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50830008
tagged with: pandas
tagged with: python
tagged with: dictionary
upvote count: 1
accepted answer: http://stackoverflow.com/a/50830008
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/50806809
has body: The solution you are looking for is in settings.py. By default after login django redirects the user to an accounts/profile page. If you want to redirect to a different place you need to edit the LOGIN_REDIRECT_URL. Doing that you can send the user to a different page Here is the documentation for that setting
score: 23
type: AcceptedAnswer
upvote count: 23
type: Answer
accepted answer of: http://stackoverflow.com/q/50806262
answers question: http://stackoverflow.com/q/50806262
downvote count: 0

http://stackoverflow.com/a/50862545
answers question: http://stackoverflow.com/q/50834184
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/129142530
has body: If you are using Lambda_basic_execution role, simple print in python will show logs in cloudwatch.
has comment: http://stackoverflow.com/comment/107440838
downvote count: 0

keypress
tags question: http://stackoverflow.com/q/50752579
tags question: http://stackoverflow.com/q/50758950
type: Tag
tag name: keypress

http://stackoverflow.com/q/50720532
has body: I have two dataframes and would like to match them by time stamp. For example: A Time X 0 05-01-2017 09:08 3 1 05-01-2017 09:09 6 2 07-01-2017 09:09 5 3 07-01-2017 09:19 4 4 07-01-2017 09:19 8 5 07-02-2017 09:19 7 6 07-02-2017 09:19 5 B Time Y 0 06-01-2017 14:45 1 1 04-01-2017 03:31 9 2 07-01-2017 03:31 4 3 07-01-2017 14:57 5 4 09-01-2017 14:57 7 There is too much data to compare each item from df_A against each item from df_B. I would instead like to find each match that is within a controlled time threshold, for example 2 days. That is: dT = Time A – Time B -2 &lt; dT &lt; 2 The result should be: C Index A Time A X Index B Time B Y dT 0 05-01-2017 09:08 3 0 06-01-2017 14:45 1 -1.2 0 05-01-2017 09:08 3 1 04-01-2017 03:31 9 1.2 0 05-01-2017 09:08 3 2 07-01-2017 03:31 4 -1.8 1 05-01-2017 09:09 6 0 06-01-2017 14:45 1 -1.2 1 05-01-2017 09:09 6 1 04-01-2017 03:31 9 1.2 1 05-01-2017 09:09 6 2 07-01-2017 03:31 4 -1.8 2 07-01-2017 09:09 5 0 06-01-2017 14:45 1 0.8 2 07-01-2017 09:09 5 2 07-01-2017 03:31 4 0.2 2 07-01-2017 09:09 5 3 07-01-2017 14:57 5 -0.2 3 07-01-2017 09:19 4 0 06-01-2017 14:45 1 0.8 3 07-01-2017 09:19 4 2 07-01-2017 03:31 4 0.2 3 07-01-2017 09:19 4 3 07-01-2017 14:57 5 -0.2 4 07-01-2017 09:19 8 0 06-01-2017 14:45 1 0.8 4 07-01-2017 09:19 8 2 07-01-2017 03:31 4 0.2 4 07-01-2017 09:19 8 3 07-01-2017 14:57 5 -0.2 5 07-02-2017 09:19 7 6 07-02-2017 09:19 5 4 09-01-2017 14:57 7 I’ve tried the following code but it’s not working: import pandas as pd import datetime as dt from datetime import timedelta # Data df_A = pd.DataFrame({'X':[3,6,5,4,8,7,5], 'Time_A': [dt.datetime(2017,1,5,9,8), dt.datetime(2017,1,5,9,9), dt.datetime(2017,1,7,9,19), dt.datetime(2017,1,7,9,19), dt.datetime(2017,1,7,9,19), dt.datetime(2017,2,7,9,19), dt.datetime(2017,2,7,9,19)]}) df_B = pd.DataFrame({'Y':[1,9,4,5,7], 'Time_B': [dt.datetime(2017,1,6,14,45), dt.datetime(2017,1,4,3,31), dt.datetime(2017,1,7,3,31), dt.datetime(2017,1,7,14,57), dt.datetime(2017,1,9,14,57)]}) # Match def slice_da…
score: 1
tagged with: dataframe
answer count: 2
upvote count: 1
tagged with: threshold
tagged with: timedelta
accepted answer: http://stackoverflow.com/a/50723327
favorite count: 0
linked to: http://stackoverflow.com/q/51187462
tagged with: python
has title: Match Dataframes by Time Difference Threshold
has answer: http://stackoverflow.com/a/50723327
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/50720714
tagged with: match
has answer: http://stackoverflow.com/a/50720714
type: Question

http://stackoverflow.com/q/50769943
has answer: http://stackoverflow.com/a/50770130
type: Question
accepted answer: http://stackoverflow.com/a/50770130
has body: Situation I have a model class with integer field(= scored_place_number). I want uses to choose either 1, 2 or 3 for the field that I set the form field as forms.MultipleChoiceField # set it to IntegerField in a form. Problem The form is displayed fine but when the form is submitted by tapping a submit button, django displays error. Enter a list of values It won's show when I did't specify forms.MultipleChoiceField so I'm guessing something is wrong with combining integer field with MultipleChoiceField. Question How can I use forms.MultipleChoiceField for IntegerField of Model? Code Model class ComparisonScore(models.Model): comparison = models.ForeignKey(Comparison, on_delete=models.CASCADE, null=True) first_place = models.ForeignKey(Place, related_name="scored_place", on_delete=models.CASCADE, null=True) second_place = models.ForeignKey(Place, related_name="unscored_place", on_delete=models.CASCADE, null=True) scored_place_number = models.IntegerField(null=True) Form class ComparisonScoreForm(forms.ModelForm): class Meta: model = ComparisonScore fields = '__all__' scored_place_number = forms.MultipleChoiceField( required=True, widget=forms.RadioSelect, choices=( ('neither', 0), ('first_place', 1), ('second_place', 2) ) ) View class CreateComparisonScoreView(CreateView): model = ComparisonScore form_class = ComparisonScoreForm success_url = reverse_lazy('comparison:index')
tagged with: django-models
score: 0
has comment: http://stackoverflow.com/comment/88549425
answer count: 1
has title: Use MultipleChoiceField for Integerfield in form
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-forms

http://stackoverflow.com/comment/88693405
type: Comment
type: QuestionComment
has text: Try changing `(custid)` to `(custid,)` so it's a tuple.
score: 0
comment on: http://stackoverflow.com/q/50844790

http://stackoverflow.com/comment/136048531
has text: This is better than some other examples which look exactly the same as the synchronous version.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53420574
type: Comment

http://stackoverflow.com/q/50806166
has title: Pandas Dataframe, getting average value for each monday 1 Am
tagged with: average
type: Question
has answer: http://stackoverflow.com/a/50806255
tagged with: dataframe
score: 0
tagged with: pandas
tagged with: types
has body: my DataFrame looks like this: index value 2016-03-21 00:00:00 0.613014 2016-03-21 01:00:00 0.596383 2016-03-21 02:00:00 0.623570 2016-03-21 03:00:00 0.663350 2016-03-21 04:00:00 0.677817 2016-03-21 05:00:00 0.727116 2016-03-21 06:00:00 0.920279 2016-03-21 07:00:00 1.205863 2016-03-21 08:00:00 0.880946 2016-03-21 09:00:00 0.186947 2016-03-21 10:00:00 -0.563276 2016-03-21 11:00:00 -1.249595 2016-03-21 12:00:00 -1.596035 2016-03-21 13:00:00 -1.886954 2016-03-21 14:00:00 -1.912325 2016-03-21 15:00:00 -1.750623 ... 2016-06-20 23:00:00 2.125791 I am trying to get the average for each monday at 1 am in the dataframe. In the end I want to have an output that represents the 'average week' of the dataframe, so I can visualize the course of the week. I hope I could express myself clearly. Thanks for your help!
answer count: 1
accepted answer: http://stackoverflow.com/a/50806255
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88415000
type: Comment
comment on: http://stackoverflow.com/q/50699990
score: 0
has text: @zwer I think i figured out what happens. The cmd file is executed correctly but the converter I use doesn't work with the anaconda-prompt (which I think is used here). The converter says that it couldnt find the file to convert. When i execute the cmd file with the window from windows it works. Is it possible to execute my cmd file with the windows-cmd window?
type: QuestionComment

http://stackoverflow.com/comment/88635339
has text: `StopIteration` handling was changed in Python 3.5 -- are your libraries up to date?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50815219

http://stackoverflow.com/q/50731984
has body: Tried to install Shapley package (available in R) using install shap but got an error: Building wheels for collected packages: shap, iml Running setup.py bdist_wheel for shap ... error Complete output from command C:\Users\Toly_Novik\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\TOLY_N~1\\AppData\\Local\\Temp \\pip-install-o0p96nl3\\shap\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\TOLY_N~1\AppData\Local\Temp\pip-wheel-538qnmm2 --python-tag cp36: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\shap copying shap\datasets.py -&gt; build\lib.win-amd64-3.6\shap copying shap\plots.py -&gt; build\lib.win-amd64-3.6\shap copying shap\__init__.py -&gt; build\lib.win-amd64-3.6\shap creating build\lib.win-amd64-3.6\shap\explainers copying shap\explainers\ime.py -&gt; build\lib.win-amd64-3.6\shap\explainers copying shap\explainers\kernel.py -&gt; build\lib.win-amd64-3.6\shap\explainers copying shap\explainers\mimic.py -&gt; build\lib.win-amd64-3.6\shap\explainers copying shap\explainers\pytree.py -&gt; build\lib.win-amd64-3.6\shap\explainers copying shap\explainers\tree.py -&gt; build\lib.win-amd64-3.6\shap\explainers copying shap\explainers\__init__.py -&gt; build\lib.win-amd64-3.6 \shap\explainers running build_ext numpy.get_include() C:\Users\Toly_Novik\Anaconda3\lib\site-packages\numpy\core\include building 'shap._cext' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools Same story for install xgboost
downvote count: 1
has title: How to install SHAP (Shapley) for Python
tagged with: xgboost
favorite count: 0
answer count: 3
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/56461718
tagged with: installation
accepted answer: http://stackoverflow.com/a/50732121
type: Question
has answer: http://stackoverflow.com/a/56461718
score: 1
has answer: http://stackoverflow.com/a/50732121
linked to: http://stackoverflow.com/q/35139108
linked to: http://stackoverflow.com/q/58700384
has answer: http://stackoverflow.com/a/68131623
upvote count: 2

http://stackoverflow.com/comment/88473126
type: AnswerComment
comment on: http://stackoverflow.com/a/50732453
type: Comment
has text: Hmmm, I think I figured it, see the new `np.concatenate` line in creating `allIndices`.
score: 0

import
type: Tag
tags question: http://stackoverflow.com/q/50752340
tags question: http://stackoverflow.com/q/50828930
tags question: http://stackoverflow.com/q/50827626
tag name: import
tags question: http://stackoverflow.com/q/50832957
tags question: http://stackoverflow.com/q/50736134
tags question: http://stackoverflow.com/q/50728223
tags question: http://stackoverflow.com/q/50787712
tags question: http://stackoverflow.com/q/50752674
tags question: http://stackoverflow.com/q/50771453
tags question: http://stackoverflow.com/q/50821864
tags question: http://stackoverflow.com/q/50778858
tags question: http://stackoverflow.com/q/50760873
tags question: http://stackoverflow.com/q/50795252
tags question: http://stackoverflow.com/q/50818535
tags question: http://stackoverflow.com/q/50725079
tags question: http://stackoverflow.com/q/50782767
tags question: http://stackoverflow.com/q/50810656
tags question: http://stackoverflow.com/q/50760163
tags question: http://stackoverflow.com/q/50788168
tags question: http://stackoverflow.com/q/50805246

http://stackoverflow.com/comment/88501561
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50745849
has text: Can you try `sample_shape=(100)`?

http://stackoverflow.com/a/50765260
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50764879
has body: In your exact case you can simply do following: for index in range(12, 22): locator = (By.XPATH, "//input[@id='__input%s-inner']" % index) # do something with locator Or if you want to use values from dictionary: for item in formulaDictionary: locator = (By.XPATH, "//input[@id='__input%s-inner']" % formulaDictionary[item]) # do something with locator
downvote count: 0
score: 1

http://stackoverflow.com/comment/88442792
has text: @Tomalak, i tried it already before posting question here
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50716985

http://stackoverflow.com/a/50750699
accepted answer of: http://stackoverflow.com/q/50746986
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has body: At the start of your function, subscriptions is empty and the for body is not evaluated. As a result, your coroutine is virtually the same as: async def talk(self): while True: pass The while-loop does not contain a "context switching point", meaning that the asyncio event loop basically hangs there, forever executing the blocking while loop. Adding await sleep() breaks the magic circle; even await sleep(0) could help. Clever code should probably make use of asyncio.Condition in combination with self.subscriptions, but this matter goes beyond the scope of your original question.
answers question: http://stackoverflow.com/q/50746986
type: Answer
has comment: http://stackoverflow.com/comment/88509492

wsgi
type: Tag
tags question: http://stackoverflow.com/q/50773316
tags question: http://stackoverflow.com/q/50749683
tags question: http://stackoverflow.com/q/50779889
tags question: http://stackoverflow.com/q/50767192
tag name: wsgi

http://stackoverflow.com/q/50766122
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88539900
has title: Cannot import rmagic in jupyter notebook
has body: I'm using jupyer notebook and trying to run R code. I have installed rpy2 with pip3 (and pip just in case) inside the notebook. What I get when trying to load the extension is this: %load_ext rpy2.ipython Cannot import ImportError: dlopen(/usr/local/lib/python3.6/site-packages/rpy2/rinterface/_rinterface.cpython-36m-darwin.so, 2): Library not loaded: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libR.dylib Referenced from: /usr/local/lib/python3.6/site-packages/rpy2/rinterface/_rinterface.cpython-36m-darwin.so Reason: image not found I'm using macOS 10.13.4 Thanks
score: 0
has comment: http://stackoverflow.com/comment/88540129
tagged with: jupyter-notebook
type: UnansweredQuestion

http://stackoverflow.com/a/50788935
type: Answer
has comment: http://stackoverflow.com/comment/88584774
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/50788921
score: 1
has body: Try this: my_list = ['google.com', 'wikipedia.org/musics', 'facebook.com', 'wikipedia.org/Elon_Musk', 'fb.com'] print(list(reversed(sorted(sorted(my_list,key=lambda x: 'wikipedia' not in x),key=lambda x: len(x))))) Output: ['wikipedia.org/Elon_Musk', 'wikipedia.org/musics', 'facebook.com', 'google.com', 'fb.com']
has comment: http://stackoverflow.com/comment/88584319
has comment: http://stackoverflow.com/comment/88584492

http://stackoverflow.com/comment/88700993
has text: @CrisLuengo Does it matter that my contours are pretty irregular and do not make up what most people would identify as a polygon? Or can any set of contour points be considered to make up a polygon? This has not been trivial in my experience.
comment on: http://stackoverflow.com/q/50847827
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/50818169
type: Question
has body: I am new to pytest-bdd framework. Below is sample feature file Content: Scenario Outline: Google multiple search request Given I want to search in Google When I search for '&lt;search_request&gt;' Then I should see link to '&lt;search_result&gt;' Examples: | search_request | search_result | | Pytest BDD | Python BDD - Behaviour driven development framework | | Cucumber | Cucumber | The sample python file generated from the pytest-bdd: # coding=utf-8 """example.feature feature tests.""" from pytest_bdd import ( given, scenario, then, when, ) @scenario('example.feature', 'Google multiple search request') def test_google_multiple_search_request(): """Google multiple search request.""" @given('I want to search in Google') def i_want_to_search_in_google(): """I want to search in Google.""" @when('I search for '&lt;search_request&gt;'') def i_search_for_search_request(): """I search for '&lt;search_request&gt;'.""" @then('I should see link to '&lt;search_result&gt;' Examples: | search_request | search_result | | Pytest BDD | Python BDD - Behaviour driven development framework | | Cucumber | Cucumber | | Cucumber2 | Cucumber2 |') def i_should_see_link_to_search_resultexamples_search_request__search_result__pytest_bdd__python_bdd__behaviour_driven_development_framework___cucumber__cucumber___cucumber2__cucumber2_(): """I should see link to '&lt;search_result&gt;' Examples: | search_request | search_result | | Pytest BDD | Python BDD - Behaviour driven development framework | | Cucumber | Cucumber | | Cucumber2 | Cucumber2 |.""" Is there a way in pytest-bdd where it recognizes the example data set provided in the feature file and converts into valid python file like it generates the skeleton code Or We need to code it manually to accept the input data in the feature file Any help much appreciated. Regards, Sanjay B S
tagged with: bdd
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/54831411
type: UnansweredQuestion
tagged with: python
tagged with: pytest
has title: Reading Data tables from feature file - Pytest-bdd

http://stackoverflow.com/comment/107440838
type: Comment
score: 1
type: AnswerComment
has text: That definitely does work with print statements, but why wouldn't log.info for instance work the same way?
comment on: http://stackoverflow.com/a/50862545

http://stackoverflow.com/comment/88502981
score: 0
comment on: http://stackoverflow.com/q/50747481
has text: Thanks @abarnert ! It was my biggest doubt, if lista[0] was the first letter or the first word!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50818952
answer count: 0
upvote count: 2
type: Question
has title: flask login page cannot login with google account
tagged with: flask
tagged with: google-oauth
tagged with: google-cloud-platform
downvote count: 0
favorite count: 0
tagged with: oauth
type: UnansweredQuestion
tagged with: python
has body: I am trying to make a login webpage that can login with google through flask_oauthlib, I created credentials in (OAuth client ID) in https://console.developers.google.com/apis/ and did relevant setting, could anyone tell me how to solve this problem Here is code: """ google example ~~~~~~~~~~~~~~ This example is contributed by Bruno Rocha GitHub: https://github.com/rochacbruno """ from flask import Flask, redirect, url_for, session, request, jsonify from flask_oauthlib.client import OAuth app = Flask(__name__) app.config['GOOGLE_ID'] = "XXX" app.config['GOOGLE_SECRET'] = "XXX" app.debug = True app.secret_key = 'development' oauth = OAuth(app) google = oauth.remote_app( 'google', consumer_key=app.config.get('GOOGLE_ID'), consumer_secret=app.config.get('GOOGLE_SECRET'), request_token_params={ 'scope': 'email' }, base_url='https://www.googleapis.com/oauth2/v1/', request_token_url=None, access_token_method='POST', access_token_url='https://accounts.google.com/o/oauth2/token', authorize_url='https://accounts.google.com/o/oauth2/auth', ) @app.route('/') def index(): if 'google_token' in session: me = google.get('userinfo') return jsonify({"data": me.data}) return redirect(url_for('login')) @app.route('/login') def login(): return google.authorize(callback=url_for('authorized', _external=True)) @app.route('/logout') def logout(): session.pop('google_token', None) return redirect(url_for('index')) @app.route('/login/authorized') def authorized(): resp = google.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) session['google_token'] = (resp['access_token'], '') me = google.get('userinfo') return jsonify({"data": me.data}) @google.tokengetter def get_google_oauth_token(): return session.get('google_token') if __name__ == '__main__': app.run() The google login webpage can show normally, but when I click login button, some errors occur. Traceback (most recent call last): File …
score: 2

http://stackoverflow.com/comment/88444973
score: 0
has text: Maybe the logs are redirected to the server logs, what server are you using ? Apache, nginx ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50714720

http://stackoverflow.com/comment/88560937
type: AnswerComment
score: 0
type: Comment
has text: Indeed, this is not the best way to achieve such a conversion task. However, I was not aiming at giving the best solution, and preferred to give the author an answer that does not diverge too much from his initial attempt (+1 too!).
comment on: http://stackoverflow.com/a/50776881

http://stackoverflow.com/q/50770172
has comment: http://stackoverflow.com/comment/88549711
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I'm querying the Windows Desktop Search JET (ESE) database using Python + ADO. It works but after ~7600 records I get an exception when advancing to the next record using MoveNext. I know it is not at EOF because I can run the same query in VBScript and get way more records with the same query. Exception traceback Traceback (most recent call last): File "test_desktop_search.py", line 60, in &lt;module&gt; record_set.MoveNext() File "&lt;COMObject ADODB.Recordset&gt;", line 2, in MoveNext pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147215865), None) Querying that error shows that it is: Constant: adErrDataOverflow Value: 3721 -2146824567 0x800A0E89 Description: Data value is too large to be represented by the field data type. This works fine in VBScript (but perhaps only due to poor error handling). PowerShell has the following error (after getting much further than Python, about to the same place as VBScript gets): Exception from HRESULT: 0x80041607 At C:\Users\doday\PycharmProjects\desktop_search_test\Get-DesktopSearchData.ps1:43 char:5 + $recordSet.MoveNext(); + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], COMException + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException I could not find this error code in Microsoft documentation, but it is likely related. As you can see, the Facility field is 4 (interface-specific HRESULT error) and the code is 1607. MCVE #!/usr/bin/env python """ Test querying Desktop Search from Python """ import csv import pywintypes from win32com.client import Dispatch # connection conn = Dispatch("ADODB.Connection") connstr = "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';" conn.Open(connstr) # record set record_set = Dispatch("ADODB.Recordset") q = "SELECT System.ItemName, System.ItemTypeText, System.Size, System.IsDeleted, System.DateAccessed, System.Kind, System.ItemDate, System.Search.Store, System.ItemParticipants, System.ItemAuthors, …
has answer: http://stackoverflow.com/a/50777120
accepted answer: http://stackoverflow.com/a/50777120
has title: How to use win32com to handle overflow when querying Desktop Search?
type: Question
has comment: http://stackoverflow.com/comment/88549876
has comment: http://stackoverflow.com/comment/88558565
tagged with: win32com
upvote count: 5
tagged with: ado
tagged with: desktop-search
score: 5
tagged with: com
has comment: http://stackoverflow.com/comment/88548291
downvote count: 0
answer count: 1

http://stackoverflow.com/q/50792181
type: Question
has answer: http://stackoverflow.com/a/68363539
tagged with: selenium
has title: How to save the session of Whatsapp web with Selenium Python?
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/88611194
has comment: http://stackoverflow.com/comment/88611992
has comment: http://stackoverflow.com/comment/88611728
answer count: 5
has answer: http://stackoverflow.com/a/69226555
upvote count: 7
linked to: http://stackoverflow.com/q/58928861
has body: My expectation was something would get added to the cookeies array automatically after validation but that isn't the case. driver = webdriver.Chrome(chromedriver) whatsapp_url = "https://web.whatsapp.com" driver.get(whatsapp_url) print(driver.get_cookies()) time.sleep(30) # We are doing the manual QR code verification here print(driver.get_cookies()) driver.get_cookies() is empty before and after as well
linked to: http://stackoverflow.com/q/15058462
has answer: http://stackoverflow.com/a/68147157
downvote count: 0
has answer: http://stackoverflow.com/a/52043819
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88612156
tagged with: python
score: 7
has answer: http://stackoverflow.com/a/61192363
favorite count: 0
tagged with: selenium-chromedriver
tagged with: python-3.x

http://stackoverflow.com/a/63305149
upvote count: 5
type: Answer
downvote count: 0
score: 5
has body: I solved a similiar problem with: Replace img_orig = Image.open("me.jpg") with img_orig = Image.open("me.jpg").convert('RGBA') And replace canvas_gb = Image.new("RGB", img_orig.size, color=(0,0,0)) with canvas_gb = Image.new("RGBA", img_orig.size, color=(0,0,0))
answers question: http://stackoverflow.com/q/50840585

http://stackoverflow.com/q/50778866
linked to: http://stackoverflow.com/q/46694110
linked to: http://stackoverflow.com/q/7580220
downvote count: 0
has comment: http://stackoverflow.com/comment/88564904
has comment: http://stackoverflow.com/comment/88565082
has comment: http://stackoverflow.com/comment/88565048
has comment: http://stackoverflow.com/comment/88564885
favorite count: 0
tagged with: terminal
upvote count: 2
type: UnansweredQuestion
has body: There was a question similar here but I couldn't exactly find my soltution from that. Plus I want to understand how to solve this and not just get solution haha. Please let me know if I should rephrase or include anything else! I am following this tutorial and I have reached the part where I need to runserver. But it pops up with an error and I'm not sure what to do next to solve this. Error page saying: "Using the URLconf defined in helloapp.urls, Django tried these URL patterns, in this order: admin/ , ^helloapp/ The empty path didn't match any of these." My project is as follows helloapp: hello app, howdy helloapp/urls.py from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() from django.urls import path urlpatterns = [ path(r'admin/', admin.site.urls), url(r'^helloapp/', include('howdy.urls')), ] howdy/views.py from django.shortcuts import render # howdy/views.py from django.shortcuts import render from django.views.generic import TemplateView #Create your views here class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) howdy/templates/index.html Howdy! Howdy! I am Learning Django! howdy/urls.py #howdy/urls.py from django.conf.urls import url from howdy import views urlpatterns = [ url(r'^$', views.HomePageView.as_view()), ]
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88564978
has comment: http://stackoverflow.com/comment/88564994
has comment: http://stackoverflow.com/comment/88564871
score: 2
has comment: http://stackoverflow.com/comment/88564822
answer count: 0
has title: Error: Using the URLconf defined in helloapp.urls, can't figure out solution
type: Question
has comment: http://stackoverflow.com/comment/88565042

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/50843953
tags question: http://stackoverflow.com/q/50721915

http://stackoverflow.com/q/50839396
tagged with: python
duplicate of: http://stackoverflow.com/q/1540049
score: -1
tagged with: python-3.x
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88682780
has body: I have a given list, with 49 variables each with a value between 1-5. I want to change the value of all variable which is equal to 5 to zero. Here is what I’ve tried: For element in listb: If element == 5: element = 0 But it doesn’t have any affect, what is the problem? Thanks Vendel
has title: Change the value of multiple variables in a list
upvote count: 0
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88682816
has answer: http://stackoverflow.com/a/50839508
linked to: http://stackoverflow.com/q/1540049
has comment: http://stackoverflow.com/comment/88682820
type: Question
has comment: http://stackoverflow.com/comment/88682589
has comment: http://stackoverflow.com/comment/88682597

http://stackoverflow.com/q/50764686
tagged with: erc20
score: 10
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50827132
tagged with: ethereum
tagged with: token
upvote count: 10
tagged with: python
downvote count: 0
type: UnansweredQuestion
has body: I am trying to send ERC20 tokens in python with web3.py using a local private key. With this code I can send ether: w3 = Web3(HTTPProvider('https://api.myetherapi.com/eth')) signed_txn = w3.eth.account.signTransaction(dict( nonce=w3.eth.getTransactionCount(from_address), gasPrice=w3.eth.gasPrice, gas=100000, to=to_address, value=12345, data=b'', ), private_key, ) w3.eth.sendRawTransaction(signed_txn.rawTransaction) Then I found this too, but always get an error for the estimateGas and it seems to me that I can't specify the address where I am sending from like this or prove that its my address by some kind of signing? contract = w3.eth.contract(address=address, abi=EIP20_ABI, bytecode=bytecode) contract.functions.transfer(to_address, 121212).transact() So I have the JSON abi, the bytecode, the addresses and my private key, can I somehow build a working script out of the code I found?
tagged with: web3py
type: Question
has title: Send ERC20 token with web3.py using a local private key
has comment: http://stackoverflow.com/comment/129457809

http://stackoverflow.com/comment/88647667
has text: So the question looks exactly the same as this one: https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50820962
score: 0

http://stackoverflow.com/a/50791900
upvote count: 1
type: AcceptedAnswer
has body: You have two slashes ('//') at the end of your url, this should be just one: http://localhost:8000/polls/1/ More specifically, in your polls/index.html template, you have the following line: &lt;li&gt;&lt;a href="{% url 'polls:detail' question.id %}/"&gt;{{ question.question_text }}&lt;/a&gt;&lt;/li&gt; Of that line, this part generates the url for you: {% url 'polls:detail' question.id %} that becomes: http://localhost:8000/polls/1/ But you have added an extra slash behind it, look at the end of the below string: "{% url 'polls:detail' question.id %}/" Remove that, and I think your code should work.
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50791827
answers question: http://stackoverflow.com/q/50791827

http://stackoverflow.com/q/50701156
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88414653
tagged with: python
downvote count: 1
has title: Sort only particular index in python with corresponding pair
score: 2
has answer: http://stackoverflow.com/a/50701232
tagged with: list
upvote count: 3
has body: I have a list which contains the following a= [june,32,may,67,april,1,dec,99] I want to sort only the numbers in descending order but it should display with corresponding pair: Output Expected ---------------- dec,99,may,67,june,32,april,1 I tried to sort using a.sort(reverse=True) command in the list not getting the expected output,this one is confusing a lot.
type: Question
has comment: http://stackoverflow.com/comment/88413072
answer count: 2
has answer: http://stackoverflow.com/a/50701255
tagged with: sorting
has comment: http://stackoverflow.com/comment/88412814
has comment: http://stackoverflow.com/comment/88413298
favorite count: 0

http://stackoverflow.com/comment/88457733
type: Comment
type: QuestionComment
has text: @EdChum thanks! so it's actually better to store as timestamp I guess, more efficient for vectorised operations? do you have an example of date-related vectorised operations that would be very slow on dt.date vs pd.Timestamp?
score: 0
comment on: http://stackoverflow.com/q/50724489

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

http://stackoverflow.com/comment/88651123
has text: @Codutie: does it work if you add 'FROM dual' to the end of that? I'm wondering if SQL Alchemy doesn't appreciate the lack of `FROM` clause.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50822914
type: AnswerComment

http://stackoverflow.com/comment/88476194
score: 0
comment on: http://stackoverflow.com/q/50718623
type: Comment
type: QuestionComment
has text: @AntonvBR thanks for the help, see my edit

http://stackoverflow.com/comment/88686156
comment on: http://stackoverflow.com/a/50840266
type: Comment
score: 0
type: AnswerComment
has text: Perhaps try a very simple fernet key, like "testing", add a connection using it and see if you are getting the same error. Perhaps it's an issue with some character of the fernet key itself that you are using.

http://stackoverflow.com/q/50792917
answer count: 0
score: 0
linked to: http://stackoverflow.com/q/46880050
type: Question
duplicate of: http://stackoverflow.com/q/46880050
has comment: http://stackoverflow.com/comment/88591987
has comment: http://stackoverflow.com/comment/88591777
tagged with: pandas
tagged with: sqlite
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88592340
tagged with: python
has title: Get top 2 highest values of every group
has body: I have tried many stack over flow answers from similar questions but none worked. I have a table of the form Class nva abc 128.5 yty 1,230.7 jhuh 399.7 abc 78.6 abc 962.7 yty 788.6 jhuh 88.8 So in class row I am having three values of abc. I want 2 columns in decreasing order of nva. So the sample output will be like: Class nva abc 962.7 abc 128.5 abc 78.6 yty 1,230.7 yty 788.6 jhuh 399.7 jhuh 88.8

http://stackoverflow.com/a/50789678
has body: I solved it. Add the following code. #include &lt;QAbstractItemView&gt; combobox.view().setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded).
downvote count: 0
type: Answer
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/50789605

http://stackoverflow.com/a/69175547
score: 19
downvote count: 0
answers question: http://stackoverflow.com/q/50805634
has comment: http://stackoverflow.com/comment/132175724
upvote count: 19
has body: The complete code wasn't in the answer so I post it below. Please install pycocotools first. pip install pycocotools Import the required modules. I'm assuming you're using a jupyter notebook. from pycocotools.coco import COCO import os from PIL import Image import numpy as np from matplotlib import pyplot as plt %matplotlib inline Load the annotations for the coco dataset. Here, specify the 74 image. coco = COCO('../datasets/coco/annotations/instances_train2017.json') img_dir = '../datasets/coco/train2017' image_id = 74 img = coco.imgs[image_id] # loading annotations into memory... # Done (t=12.70s) # creating index... # index created! The information of the loaded img is as follows. img # {'license': 2, # 'file_name': '000000000074.jpg', # 'coco_url': # 'http://images.cocodataset.org/train2017/000000000074.jpg', # 'height': 426, # 'width': 640, # 'date_captured': '2013-11-15 03:08:44', # 'flickr_url': # 'http://farm5.staticflickr.com/4087/5078192399_aaefdb5074_z.jpg# ', # 'id': 74} Display the image as follows. image = np.array(Image.open(os.path.join(img_dir, img['file_name']))) plt.imshow(image, interpolation='nearest') plt.show() If you want to see the overlay result: plt.imshow(image) cat_ids = coco.getCatIds() anns_ids = coco.getAnnIds(imgIds=img['id'], catIds=cat_ids, iscrowd=None) anns = coco.loadAnns(anns_ids) coco.showAnns(anns) If you just want to see the mask, as Farshid Rayhan replied, do the following: mask = coco.annToMask(anns[0]) for i in range(len(anns)): mask += coco.annToMask(anns[i]) plt.imshow(mask)
type: Answer

http://stackoverflow.com/comment/88486325
has text: Well I don't know your full situation but to add 1 more column is a matter of defining it and adding it in the loop `print("{}\t{}\t{}".format(column_1[i], column_2[i], column_3[i]))`. If you have lots of lists, you can make a list of lists and loop over those in the same style. All depends on what you are trying to do.
type: Comment
comment on: http://stackoverflow.com/a/50739343
score: 0
type: AnswerComment

http://stackoverflow.com/a/52230257
has body: Replace browser = webdriver.Chrome(my_driver_location, chrome_options=chromeOptions) with: from selenium.webdriver.common.desired_capabilities import DesiredCapabilities browser = webdriver.Remote( command_executor='http://192.168.99.100:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME ) 192.168.99.100 is your floating IP, 4444 is port of your floating IP
score: 0
answers question: http://stackoverflow.com/q/50829342
type: Answer

http://stackoverflow.com/comment/88452580
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50712471
has text: Try doing a "Compact and Repair Database" operation in Access and see if the new table appears after that.

http://stackoverflow.com/q/50806914
has comment: http://stackoverflow.com/comment/88646121
tagged with: heroku
has body: I made a simple website using Flask for a python course on Udemy. I followed the instructions and my files were successfully deployed on Heroku. However, when I run the app it gives an "Application Error". Here are the Heroku server logs: 2018-06-11T15:01:25.023293+00:00 app[api]: Enable Logplex by user abdullahaquarius@gmail.com 2018-06-11T15:01:24.704057+00:00 app[api]: Release v1 created by user abdullahaquarius@gmail.com 2018-06-11T15:01:24.704057+00:00 app[api]: Initial release by user abdullahaquarius@gmail.com 2018-06-11T15:01:25.023293+00:00 app[api]: Release v2 created by user abdullahaquarius@gmail.com 2018-06-11T15:02:05.804977+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=abd99.herokuapp.com request_id=f1c2f7bb-ce07-441d-bb96-567b15932865 fwd="182.186.129.130" dyno= connect= service= status=502 bytes= protocol=http 2018-06-11T15:02:07.070594+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=abd99.herokuapp.com request_id=3a345ccc-f833-4037-b16c-699019726b7e fwd="182.186.129.130" dyno= connect= service= status=502 bytes= protocol=http 2018-06-11T22:02:59.000000+00:00 app[api]: Build started by user abdullahaquarius@gmail.com 2018-06-11T22:04:00.100899+00:00 app[api]: Release v3 created by user abdullahaquarius@gmail.com 2018-06-11T22:04:00.000000+00:00 app[api]: Build succeeded 2018-06-11T22:04:00.115121+00:00 app[api]: Scaled to web@1:Free by user abdullahaquarius@gmail.com 2018-06-11T22:04:00.100899+00:00 app[api]: Deploy 960fabc7 by user abdullahaquarius@gmail.com 2018-06-11T22:04:08.180699+00:00 heroku[web.1]: Starting process with command `gunicorn Website:app` 2018-06-11T22:04:10.005391+00:00 app[web.1]: bash: gunicorn: command not found 2018-06-11T22:04:10.084997+00:00 heroku[web.1]: State changed from starting to crashed2018-06-11T22:04:10.084997+00:00 heroku[web.1]: State changed from crashed to starting2018-06-11T22:04:10.063441+00:00 heroku[web.1]: Process exited with …
type: Question
has title: Python script deployed successfully on heroku but gives application error
has comment: http://stackoverflow.com/comment/88619737
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50797356
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88601037
answer count: 0
has comment: http://stackoverflow.com/comment/88651662
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88603603
has body: { "type": "MultiPolygon", "coordinates": [[[ [6707794.77817316, 1952512.97762237], [6707794.43138905, 1952566.21209599], [6707897.49942442, 1952567.26754007], [6707897.9039513, 1952513.5347079], [6707794.77817316, 1952512.97762237] ]]] } I am very new to GeoDjango. These are my Geojson coordinates. These are the Coordinates for Parcel data that belongs to Sacramento City. How to convert these coordinates into Lat Long in Python
type: Question
tagged with: geodjango
score: 0
has comment: http://stackoverflow.com/comment/88600974
linked to: http://stackoverflow.com/q/50773815
has title: How to Convert this coordinates to Latitudinal's and longitudinal's in Python?
tagged with: coordinate-transformation
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88693810
score: 0
type: AnswerComment
has text: you can also `for i in x[:]` instead of deepcopy. :)
type: Comment
comment on: http://stackoverflow.com/a/50845055

http://stackoverflow.com/comment/88476712
comment on: http://stackoverflow.com/q/50734480
has text: How do you know there is a memory leak?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88416702
type: QuestionComment
has text: That is outdated. It won't work for me. But I think using models.FileField could work?
comment on: http://stackoverflow.com/q/50703572
score: 0
type: Comment

http://stackoverflow.com/comment/88711388
score: 2
has text: My question is not duplicate, as what I'm asking is can the second argument be used with the "Self defined Object". That's different. @quamrana
comment on: http://stackoverflow.com/q/50853821
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88599520
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50794245
has text: I updated my question. I have cron job which runs everyday and calls get_data method.
score: 0

http://stackoverflow.com/comment/88523603
score: 0
has text: Thank you - appreciated!
type: AnswerComment
comment on: http://stackoverflow.com/a/50750857
type: Comment

http://stackoverflow.com/a/50730542
downvote count: 1
answers question: http://stackoverflow.com/q/50727147
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/88481884
upvote count: 2
has body: Can be achieved using tf.stack: # Input a = tf.constant(np.arange(9).reshape(3,3), tf.float32) #[[0. 1. 2.] # [3. 4. 5.] # [6. 7. 8.]] b = tf.zeros_like(a) c = tf.reshape(tf.stack([a,b], 2), [-1, tf.shape(a)[1]+tf.shape(b)[1]])[:,:-1] with tf.Session() as sess: print(sess.run(c)) #[[0. 0. 1. 0. 2.] # [3. 0. 4. 0. 5.] # [6. 0. 7. 0. 8.]]

http://stackoverflow.com/comment/88615112
type: QuestionComment
has text: I doubt that your data looks like this, with syntax errors all over the place.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50804501

http://stackoverflow.com/comment/88514190
comment on: http://stackoverflow.com/a/50752906
type: Comment
has text: sorry, I don't notice that, I change the answer here! `newdf = df.groupby("A")["B"].expanding().quantile(0.5).reset_index() for i in range(newdf["A"].max()+1): print(newdf[newdf["A"]==i][-2:],'\n')`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88665864
score: 0
type: QuestionComment
type: Comment
has text: I'm trying to edit, my first time post questions
comment on: http://stackoverflow.com/q/50830683

http://stackoverflow.com/q/50850489
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88703702
tagged with: hash
has comment: http://stackoverflow.com/comment/88703709
has answer: http://stackoverflow.com/a/50864330
tagged with: python
has comment: http://stackoverflow.com/comment/88714822
has comment: http://stackoverflow.com/comment/88722040
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88717833
has comment: http://stackoverflow.com/comment/88703858
has comment: http://stackoverflow.com/comment/88703746
upvote count: 2
has comment: http://stackoverflow.com/comment/88718019
downvote count: 3
linked to: http://stackoverflow.com/q/18338890
type: Question
has body: NO. THAT SUGGESTION DOES NOT ANSWER THIS AT ALL. SEE CORRECT ANSWER BELOW. I am building an application whereby I want a user to enter a password into a browser, which is sent via my server to another device running Python. The password then needs to be validated by the device running Python. The problem is, I dont want my server handling passwords in any way. So I figured I could hash the password in the browser before it is sent, have the server pass on the hash to the device, then check the hash is equivalent on the Python side. Python has a built-in library for this purpose, but it seems javascript does not. I thought I could leverage a public javascript library, but when I compare the results from the javascript SHA256 algorithm here to what the SHA256 function in Python produces it is not the same string of characters. Is there a cross code hash function (or any other solution) I can use? An Update In response to a "gee whiz, this question is the same as all these ones" let me clarify. This is not about a strategy for storing passwords or finding a 'trustworthy' library (like the post suggested). There is NOT any discussion about cross code compatibility of SHA2 on this site. I could not even find a discussion that pointed out that different SHA2 implementations SHOULD produce the same result. I did plenty of research. In fact it was the various discussions about different javascript "implementations" of SHA2 that confused me. I actually tested a scenario myself, which further confused me as the website picked up a carriage return and produced a different hash. (see below) This is about having a function in TWO languages that produces the same output...on different devices. I think it is actually an unusual application of hashing, as generally the same code layer is used to hash, store and compare hashed values. In the rush to down-vote the question and establish mental superiority it seems to me the question was not read properly and incorrect assumptions wer…
accepted answer: http://stackoverflow.com/a/50864330
has title: Cross code Hash for Javascript & Python
tagged with: javascript
score: -1
has comment: http://stackoverflow.com/comment/88706269

http://stackoverflow.com/comment/88610902
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50802368
type: AnswerComment
has text: self.parent (provided that you add `self.parent=parent` in `__init__` of Page3)

http://stackoverflow.com/q/50849057
tagged with: selenium-webdriver
type: AnsweredQuestion
downvote count: 0
has body: Since this URL table is combined, so cannot print out the table as expected and the output formatting is very strange, thanks ! # -*- coding:UTF-8 -*- from pyvirtualdisplay import Display display = Display(visible=0, size=(1024, 768)) display.start() from bs4 import BeautifulSoup from selenium import webdriver import re driver = webdriver.Firefox() driver.get("url") soup = BeautifulSoup(driver.page_source.encode('utf-8'),'html.parser') rows = soup.findAll("td", {"class" : re.compile('table_eng_small_text_.\d')}) result = ','.join(r.text for r in rows) print(result) driver.close() display.stop() expected output: 1 10 SEASONS KING(T032) 12 7-1/4 7 4-3/4 1 1-1/4 1.09.35 25.06 22.31 21.98 2 2 HAPPY SOUND(V107) 1 1/2 1 3/4 2 1-1/4 1.09.56 23.90 22.71 22.95 3 14 NATURAL FRIENDSHIP(S359) 4 2-1/2 4 2-3/4 3 1-1/2 1.09.59 24.30 22.75 22.54 4 13 LUCKY PLACE(T004) 14 10 13 6-1/2 4 3 1.09.84 25.50 22.15 22.19 5 9 NO LAUGHING MATTER(V032) 9 5-3/4 9 5 5 3-1/2 1.09.89 24.82 22.59 22.48 6 1 FREE NOVEMBER(T123) 5 4 5 3-3/4 6 4-1/2 1.10.07 24.54 22.67 22.86 7 7 FRIENDS FOREVER(T079) 2 1/2 2 3/4 7 4-1/2 1.10.08 23.98 22.75 23.35 8 5 REAL SUPREME(L247) 3 1-1/2 3 2-1/4 8 5-3/4 1.10.27 24.14 22.83 23.30 9 6 BE THERE AHEAD(S193) 6 4-1/4 6 3-3/4 9 6-1/4 1.10.34 24.58 22.63 23.13 10 8 GOLD PRECIOUS(P364) 13 8-1/4 11 6-1/2 10 6-3/4 1.10.41 25.22 22.43 22.76 11 11 DUTCH WINDMILL(T288) 10 5-3/4 14 7 11 7 1.10.48 24.82 22.91 22.75 12 3 HAPPY THREE(V162) 11 5-3/4 8 4-3/4 12 7 1.10.49 24.82 22.55 23.12 13 4 SILVER GATSBY(T161) 8 5-1/2 12 6-1/2 13 7-1/2 1.10.56 24.78 22.87 22.91 14 12 CHANS DELIGHT(P420) 7 4-1/2 10 5-3/4 14 9-3/4 1.10.92 24.62 22.91 23.39
tagged with: selenium
type: Question
answer count: 2
score: 4
has title: cannot print out the combined table properly from beautifulsoup
has answer: http://stackoverflow.com/a/50850219
accepted answer: http://stackoverflow.com/a/50850219
possible better answer: http://stackoverflow.com/a/50849879
has answer: http://stackoverflow.com/a/50849879
favorite count: 0
tagged with: beautifulsoup
tagged with: pyvirtualdisplay
tagged with: python
upvote count: 4

http://stackoverflow.com/a/50831226
type: AcceptedAnswer
has body: Here apply convert values to DataFrame be design, so possible solutions are use stack: s = df.apply(fun, axis=1).stack() print (s) 0 0 1.0 1 2.0 2 3.0 3 4.0 4 5.0 5 6.0 1 0 2.0 1 3.0 2 4.0 3 5.0 4 6.0 5 7.0 6 8.0 2 0 3.0 1 4.0 2 5.0 3 6.0 4 7.0 5 8.0 dtype: float64 Or list comprehension with concat: L = [pd.Series(np.arange(a, b)) for a, b in zip(df['start'], df['end'])] s = pd.concat(L, keys=df.index) print (s) 0 0 1 1 2 2 3 3 4 4 5 5 6 1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 2 0 3 1 4 2 5 3 6 4 7 5 8 dtype: int32
has comment: http://stackoverflow.com/comment/88670080
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50830683
has comment: http://stackoverflow.com/comment/88667142
has comment: http://stackoverflow.com/comment/88667622
has comment: http://stackoverflow.com/comment/88669083
has comment: http://stackoverflow.com/comment/88668682
answers question: http://stackoverflow.com/q/50830683

http://stackoverflow.com/q/50777461
type: Question
tagged with: python-itertools
has body: I want to replicate the cartesian product of [False,True] n times so that the output should be for example with n=3: [(False, False, False),(False, False, True),(False, True, False), (False, True, True),(True, False, False),(True, False, True), (True, True, False),(True, True, True)] I found how to do it with: from itertools import product list(product([False,True],[False,True],[False,True])) But the thing is that I want to do it for bigger n without writing n times the boolean.
score: 0
has title: Create all combinations of boolean for a specified n
has comment: http://stackoverflow.com/comment/88561952
has comment: http://stackoverflow.com/comment/88561883
answer count: 0
has comment: http://stackoverflow.com/comment/88562067
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/3099987
duplicate of: http://stackoverflow.com/q/3099987

http://stackoverflow.com/comment/88693331
type: QuestionComment
has text: @nosklo The error message indicates that he's using Oracle.
comment on: http://stackoverflow.com/q/50844790
score: 0
type: Comment

repeat
tags question: http://stackoverflow.com/q/50788508
tag name: repeat
tags question: http://stackoverflow.com/q/50712315
type: Tag

http://stackoverflow.com/q/50698982
has comment: http://stackoverflow.com/comment/88408170
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88411573
tagged with: python
tagged with: dictionary
has title: Text substitution using Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88407394
has comment: http://stackoverflow.com/comment/88413574
has comment: http://stackoverflow.com/comment/88411428
has body: I have two datasets. One contains text description and another that contains a table with two columns from_value and to_value. The idea is to replace all occurrences of the word in the text description using the second data set. I can identify 4 types of words from this second dataset: Simple word substitution: RPLCD -&gt; REPLACED Multi string word substitution: ALT BRK -&gt; ALTERNATE BREAK Words with special character in them: A/C -&gt; AIRCRAFT or 1-APU -&gt; 1 APU Special characters removal: if I have % in the string I should delete it; same thing for - unless it's inside a word like 1-APU (we replace the whole word) I uploaded an example of my 2 data sets via Gdrive, here's the link: https://drive.google.com/drive/folders/1HYFhKAqbYPIy0ekyj9xLSbk30YZwf8ZG?usp=sharing My idea was to split first my second dataset into 2 dataframes, one with multi words and one with one word and special character, or to split into 3 dataframes, one with multi, one with solo word and one for special character, and to apply first the first dataframe, then the 2sd and in the end the special character removal, but it's not working. Do you have a way to manage this type of subsitution ? Here's my code: import sys import pyspark import pandas_datareader import re import csv import xlrd import pandas as pd import numpy as np import datetime from pyspark.context import SparkContext from pyspark.sql.functions import * from pandas import DataFrame from pandas_datareader import data, wb from pandas import * from xlrd import open_workbook ## 1)read the source table (OI and description) xls = ExcelFile("df1.xls") df = xls.parse(xls.sheet_names[0]) ## 2)remove the nan values from df df = df.replace(np.nan, '') ## 3)read the subtitution table xls1 = ExcelFile("df2.xls") df1 = xls1.parse(xls1.sheet_names[0]) df1.drop(df1.columns[0],inplace=True,axis=1) ## 4)separate the subtitution table into 2 datasets df3 = pd.DataFrame(columns=('FROM_VALUE', 'TO_VALUE')) df4 = pd.DataFrame(columns=('FROM_VALU…
has answer: http://stackoverflow.com/a/50712189
tagged with: replace
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88411873
has comment: http://stackoverflow.com/comment/88411375

http://stackoverflow.com/comment/88446207
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50718626
has text: But really unless we are talking about gigabytes size zip files here, things should be fine.
score: 0

http://stackoverflow.com/comment/88574618
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50783981
has text: It depends on your computational algorithm and various other OS factors and also how you implement and reuse your pool
type: Comment

http://stackoverflow.com/comment/88570776
type: AnswerComment
score: 0
type: Comment
has text: hi thanks for the help but im not sure why it doesn't work for me. when i used the same code as u, my output is the whole text instead of the common words
comment on: http://stackoverflow.com/a/50762739

http://stackoverflow.com/comment/88806847
type: AnswerComment
comment on: http://stackoverflow.com/a/50812302
type: Comment
has text: Thanks @jedwards. I have to wait 18hrs for the bounty sorry.
score: 0

http://stackoverflow.com/comment/88493314
type: Comment
comment on: http://stackoverflow.com/a/50742713
score: 1
type: AnswerComment
has text: @UCProgrammer I think `'%Y%m%d%H%M'` would make more sense, YYYYMMDDMMSS doesn't seem a likely format, it probably is YYYYMMDDHHMM

http://stackoverflow.com/comment/88545059
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50768511
has text: @JanK just included it, hope it helps

http://stackoverflow.com/q/50725093
has answer: http://stackoverflow.com/a/50729422
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/50729422
has body: I have a rather large dataframe with upward of 100,000 records. I need to repeatedly perform a range search on a numeric field of this dataframe. I am able to perform this search using loc or query but this is taking lot of time. I think the reason is that right now it is a brute force search. is there someway to generate an index on this numeric field so that I can have a better optimized ranged search on this field. sample dataframe - field1 field2 field3 red car 1000000000 green truck 2000000000 yellow bus 3000000000 white bike 4000000000 black cycle 5000000000 search - dataframe.query(field3 &gt; 1000000000 &amp; field3 &lt; 5000000000) I am using this query in a for loop which runs around 6000 times. My overall code is taking around 25 mins. From 150 ms, calling this piece 6000 times will be 900 seconds i.e. 15 mins. If I can somehow create a index on this field then I think the query time would be reduced drastically.
tagged with: python
has comment: http://stackoverflow.com/comment/88465708
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88459003
has comment: http://stackoverflow.com/comment/88458679
has comment: http://stackoverflow.com/comment/88465568
type: Question
has comment: http://stackoverflow.com/comment/88459166
has comment: http://stackoverflow.com/comment/88465628
has title: pandas dataframe optimized query

http://stackoverflow.com/comment/108063983
has text: You are a lifesaver!! I spent 2 days looking for a solution such as this! I have to define a tasks dynamically. So thank you sir, I salute you!
comment on: http://stackoverflow.com/q/50798281
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88612535
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50803334
has text: you're not doing anything with the result you're returning.

http://stackoverflow.com/q/50840769
has comment: http://stackoverflow.com/comment/88685306
accepted answer: http://stackoverflow.com/a/50840962
tagged with: datetime
tagged with: python
has title: insert row with datetime index to dataframe
type: AnsweredQuestion
upvote count: 17
type: Question
has answer: http://stackoverflow.com/a/50840962
tagged with: dataframe
tagged with: pandas
has body: I have a dataframe with datetime index: time count day hour minute label 2018-06-07 00:25:00 207 7.0 0.0 25.0 177.0 2018-06-07 00:55:00 187 7.0 0.0 55.0 150.0 2018-06-07 01:25:00 194 7.0 1.0 25.0 165.0 2018-06-07 01:55:00 176 7.0 1.0 55.0 175.0 2018-06-07 02:25:00 195 7.0 2.0 25.0 172.0 -&gt; add new datetime record record here and I'm trying to add some new records but I get: [DatetimeIndex(['2018-06-07 01:55:00'], dtype='datetime64[ns]', name='time', freq=None)] not an index # this happen even if row exists or not I just want to add a 30 minutes interval record, my code is something like last_date = recent_posts.iloc[[-1]].index last_date = last_date + timedelta(minutes=30) recent_posts.iloclast_date = # bla #bla # What I may be doing wrong?
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88685441
score: 17

http://stackoverflow.com/comment/88712132
type: Comment
comment on: http://stackoverflow.com/q/50826357
score: 0
has text: Possible duplicate of [Plotly.js - Reversing the horizontal bar chart in plotly](https://stackoverflow.com/questions/46201532/plotly-js-reversing-the-horizontal-bar-chart-in-plotly)
type: QuestionComment

http://stackoverflow.com/q/50738264
has title: Missing corner button in QTableWidget
upvote count: 1
has comment: http://stackoverflow.com/comment/88506373
tagged with: python
has comment: http://stackoverflow.com/comment/88754031
favorite count: 0
tagged with: python-3.x
downvote count: 0
has comment: http://stackoverflow.com/comment/88495057
has body: I'm using pyqt5 and from what I read so far the top-left corner cell should be created automatically. I have this little popup window in which I create the table and fill it with values from a dictionary: class LimitTable(QWidget): query = QtCore.pyqtSignal(dict) def __init__(self, dic): QWidget.__init__(self) self.dic = dic self.setup_ui() self.setWindowTitle("Limit Table") def setup_ui(self): self.limit_table = QtWidgets.QTableWidget(self) self.limit_table.setGeometry(QtCore.QRect(10, 40, 681, 81)) self.limit_table.setObjectName("limit_table") row_names = ["Lower Limit", "Upper Limit"] col_names = list(self.dic.keys()) self.limit_table.setRowCount(len(row_names)) self.limit_table.setColumnCount(len(self.dic.keys())) self.limit_table.setHorizontalHeaderLabels(col_names) helpers.add_header(self.limit_table, len(row_names), row_names, "vertical") helpers.add_header(self.limit_table, len(col_names), col_names) for i, val in enumerate(self.dic.values()): self.limit_table.setItem(0, i, QTableWidgetItem("{:0.1e}".format(val[0]))) self.limit_table.setItem(1, i, QTableWidgetItem("{:0.1e}".format(val[1]))) where add_header is just def add_header(tab_obj, count, name, hv="horizontal"): """Adds header objects to TableWidget. Args: - tab_obj (QTableWidget) : table object - count (int) : number of cells - name (str) : header name - hv (str) : choose horizontal or vertical header """ tab_obj.setColumnCount(count) for col in range(0, count): item = QtWidgets.QTableWidgetItem() if isinstance(name, dict): item.setText(list(name.keys())[col]) if isinstance(name, list): item.setText(name[col]) if hv == "horizontal": tab_obj.setHorizontalHeaderItem(col, item) adjust_header(tab_obj, count, "Stretch") if hv == "vertical": tab_obj.setVerticalHeaderItem(col, item) return True So in principle it's very basic and according to text book. The lines "setRowCount" and "setColumnCount" should do what I want. But instead I get this Update 1 Apperently, the corner button is there... self.limit_tab…
tagged with: pyqt5
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88506435
tagged with: qtablewidget
score: 1
has comment: http://stackoverflow.com/comment/88521426
accepted answer: http://stackoverflow.com/a/66505197
has comment: http://stackoverflow.com/comment/88754615
type: Question
has comment: http://stackoverflow.com/comment/88516298
tagged with: pyqt
answer count: 1
has answer: http://stackoverflow.com/a/66505197

http://stackoverflow.com/comment/88454233
has text: What do you mean by "run on a different terminal"? Are you bothered by the output of Chrome in Python's terminal? Or do you want that the Python code continues running side-by-side with Chrome?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50722690

http://stackoverflow.com/q/50726729
has body: I am trying to add an element to a list inside of a nested list. However, the elements get added to every list in the nested list rather than just the one it's meant to go in. I have tried using the same piece of code and it works perfectly outside of my program so I will add my whole program here. I apologies for my general bad form and inefficiency but i'm still relatively new to coding. Thanks! import pygame import sys from random import randint import math pygame.init() black = 0,0,0 white = 255,255,255 red = 255,0,0 blue = 0,0,255 screen = pygame.display.set_mode((500,500)) screen.fill(white) citiesX = [] citiesY = [] visits = [] paths = [] lengths = [] cities = [] list1 = [] #Sets the colour of the line depending on its length def getColour(CurrentLength): percentage = (CurrentLength/1400)*100 colour = 2.55*percentage return(colour) #Renders Lines def drawLines(visits): global citiesX global citiesY screen.fill(white) pygame.draw.circle(screen, red, (citiesX[0],citiesY[0]), 5, 4) #Draw Cities for i in range (1,len(citiesX)): pygame.draw.circle(screen, black, (citiesX[i],citiesY[i]), 5, 4) #Draw Paths for i in range (0,len(visits)-1): #Colour Rendering lengthX = (citiesX[visits[i]]-citiesX[visits[i+1]])*(citiesX[visits[i]]-citiesX[visits[i+1]]) lengthY = (citiesY[visits[i]]-citiesY[visits[i+1]])*(citiesY[visits[i]]-citiesY[visits[i+1]]) CurrentLength = math.sqrt(lengthX+lengthY) #Draw Lines pygame.draw.lines(screen, (getColour(CurrentLength),getColour(CurrentLength),getColour(CurrentLength)), False, [(citiesX[visits[i]],citiesY[visits[i]]),(citiesX[visits[i+1]],citiesY[visits[i+1]])], 4) pygame.display.update() #Find out how long a generated path is def getPathLength(visits): totalLength = 0 for i in range (0,len(visits)-1): lengthX = (citiesX[visits[i]]-citiesX[visits[i+1]])*(citiesX[visits[i]]-citiesX[visits[i+1]]) lengthY = (citiesY[visits[i]]-citiesY[visits[i+1]])*(citiesY[visits[i]]-citiesY[visits[i+1]]) CurrentLength = math.sqrt(lengthX+lengthY) pygame.dr…
has comment: http://stackoverflow.com/comment/88461721
answer count: 1
tagged with: nested
has answer: http://stackoverflow.com/a/50726849
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88461738
tagged with: list
has comment: http://stackoverflow.com/comment/88461760
type: Question
has title: I can't append single elements to nested lists
score: 0

http://stackoverflow.com/comment/88670510
score: 0
type: AnswerComment
has text: how did you crate your df ?
type: Comment
comment on: http://stackoverflow.com/a/50833192

http://stackoverflow.com/comment/88581218
type: QuestionComment
has text: concat isn't working, I suspect, because the dataframes are different sizes. I suggest you get the size of the larger one, resize the smaller one and pad with nan values and you should be ok.
type: Comment
comment on: http://stackoverflow.com/q/50787196
score: 0

http://stackoverflow.com/a/50848835
has comment: http://stackoverflow.com/comment/88701137
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50848769
has body: You can check the configuration you run, and you will find two check boxs checked by default: Add content roots to PYTHONPATH Add source roots to PYTHONPATH That makes you possible to import package.
has comment: http://stackoverflow.com/comment/88701170
downvote count: 0
type: Answer

http://stackoverflow.com/a/50769475
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50769396
has body: The problem isn't the formatting. As the error clearly states, the float object has no attribute astype. I'm assuming you got this from a different language, but in Python that's not how you change types. If you want to convert a float to an int, the syntax is int(float), not float.astype(int). You need the code soldpricemean = '{:,}'.format(int(bedbath_df.sold_price.mean()))
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88546480
answers question: http://stackoverflow.com/q/50769396

http://stackoverflow.com/comment/88463594
comment on: http://stackoverflow.com/q/50727159
has text: Trying to run this with line_profiler suggests that it really should be about a 30% hit (the iteration, lambda, and comparison each take up about 30% of the time). So, I guess in this case the extra overhead of running the profiler is changing things.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50796722
has body: I need to create kind of a monitor which refreshes itself periodically. So how can I properly refresh output of a cell? When I refresh the text using the code below the output pane collapses when being cleared creating annoying screen jumps. from IPython import display import time while True: o = !netstat display.clear_output() display.publish_display_data({"text/plain":o.n}) time.sleep(1)
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
score: 2
answer count: 0
has title: Refreshing output text in Jupyter notebook
type: Question
tagged with: ipython
upvote count: 2
has comment: http://stackoverflow.com/comment/88910196
downvote count: 0

http://stackoverflow.com/q/50732815
type: Question
has body: I have previous experience in Django. If add line {csrf_token} in Django templates then Django handles the functionalities of csrf_token. But when I am trying to develop an API using Django REST Framework then I get stuck. How can I add and handle functionalities like csrf_token in API (back end, developed using Django REST Framework) and React Native/React JS (front end) like Django templates?
tagged with: reactjs
possible better answer: http://stackoverflow.com/a/77306212
downvote count: 0
upvote count: 45
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/50735730
answer count: 3
tagged with: python
favorite count: 0
score: 45
tagged with: django
has answer: http://stackoverflow.com/a/50734522
accepted answer: http://stackoverflow.com/a/50735730
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77306212
has title: How to use csrf_token in Django RESTful API and React?

http://stackoverflow.com/a/50847424
has comment: http://stackoverflow.com/comment/125643921
has comment: http://stackoverflow.com/comment/88727318
type: Answer
answers question: http://stackoverflow.com/q/50847329
upvote count: 4
has body: We can fix every dictionary with a function: fixer = {'value-2' : 'value_2', 'value&amp;_3' : 'value_3', 'value-3' : 'value_3'} def fix_dictionary(dict_): return { fixer.get(k, k): v for k, v in dict_.items() } This will for a given dict_ construct a new dictionary where keys that are in the fixer will be "fixed" (replaced by the corresponding value in the fixer dictionary). We can then generate a new list of fixed dictionaries with: [fix_dictionary(dict_) for dict_ in listOfDicts] Or we can eliminate the function, and use a one liner: [{ fixer.get(k, k): v for k, v in dict_.items() } for dict_ in listOfDicts]
downvote count: 0
score: 4

http://stackoverflow.com/comment/88436776
comment on: http://stackoverflow.com/a/50713267
score: 0
has text: May day ! After updaing this code the default POST form created using the API portal is also not working.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88631343
type: QuestionComment
comment on: http://stackoverflow.com/q/50813120
has text: Any Help? Couldn`t figure out what`s going on
score: 0
type: Comment

http://stackoverflow.com/comment/88578895
has text: Yeah, the assets are in project static folder: ./perfectcushion/static. There is no assets inside the app folder.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50785073
type: Comment

http://stackoverflow.com/q/50828233
has title: Parallelizing snakemake rule
score: 4
answer count: 1
has comment: http://stackoverflow.com/comment/89088765
favorite count: 0
has comment: http://stackoverflow.com/comment/89088209
has body: Sorry if this is a naive question, but I'm still trying to wrap my head around the intricacies of Snakemake. I have a directory containing a number of files that I want to apply a rule to in parallel (i.e. I want to submit the same script to the cluster, specifying a different input file for each submission). I first tried using expand for the input files, but this only resulted in one job submission: CHROMS = [str(c) for c in range(1, 23)] + ["X"] rule vep: input: expand("data/split/chr{chrom}.vcf", chrom=CHROMS) output: expand("data/vep/split/chr{chrom}.ann.vcf", chrom=CHROMS) shell: "vep " "{input} " "{output}" Is there an alternative approach here? Thank you!
accepted answer: http://stackoverflow.com/a/50837428
tagged with: python
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88720263
downvote count: 0
has comment: http://stackoverflow.com/comment/88684227
has answer: http://stackoverflow.com/a/50837428
tagged with: snakemake
has comment: http://stackoverflow.com/comment/88715211
type: Question

http://stackoverflow.com/comment/88874524
comment on: http://stackoverflow.com/a/50812302
score: 0
type: AnswerComment
has text: If possible a single list of both colours would be great. They represent two diff entities.
type: Comment

http://stackoverflow.com/a/50839404
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50839111
has body: As i expected, you just forgot to close some curly brackets on your config. var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './frontend/src/index.js', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: { test: /\.jsx$|\.js$/, loaders: ['babel-loader'], include: path.resolve(__dirname, '../src') }, }, resolve: { modulesDirectories: ['node_modules', 'bower_components'], extensions: ['', '.js', '.jsx'] } }
downvote count: 0
type: Answer

http://stackoverflow.com/a/50839566
has comment: http://stackoverflow.com/comment/88704657
has comment: http://stackoverflow.com/comment/88683918
has comment: http://stackoverflow.com/comment/88684763
downvote count: 0
has comment: http://stackoverflow.com/comment/88695784
has comment: http://stackoverflow.com/comment/88684531
answers question: http://stackoverflow.com/q/50839487
has comment: http://stackoverflow.com/comment/88685182
has comment: http://stackoverflow.com/comment/88685284
has body: It has a .x attribute that you can use. df.geo.map(lambda val: val.x) Thanks to @joris for the improved result. if you are using the latest version of geopandas (0.3.0) you can do df.geo.x
type: Answer
has comment: http://stackoverflow.com/comment/88684247
has comment: http://stackoverflow.com/comment/88683385
upvote count: 1
has comment: http://stackoverflow.com/comment/88710390
score: 1

http://stackoverflow.com/a/50756208
upvote count: 3
has body: In the "q" parameter you can use "since" and "until" like this : q="#unitedAIRLINES since:2017-04-02 until:2017-04-03" The result shoud be the same as this advanced search on the official web site : https://twitter.com/search?f=tweets&amp;vertical=default&amp;q=%23unitedAIRLINES%20since%3A2017-04-02%20until%3A2017-04-03&amp;src=typd Except that with the public search API you just can get 7 days past. You can either use a specific tweet id as a starting point. The parameter is "since_id". And a "max_id" to delimit the period. For more information, see : https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
score: 3
answers question: http://stackoverflow.com/q/50753126
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50753126
type: Answer
has comment: http://stackoverflow.com/comment/115047286

http://stackoverflow.com/q/50748443
type: Question
has comment: http://stackoverflow.com/comment/88506122
has comment: http://stackoverflow.com/comment/93044806
tagged with: sql
score: 0
has body: I have a project where I am inputting a Terdata DB table name as a parameter, executing a SQL statement that provides aggregates on the table (min, max etc) for every column, and returns that information where I then put it in a dataframe. What I would like to do is then take the rows that are in the dataframe (1 row per column_name in the table) and insert the results into another DB table 'Data Analysis' where the results will be stored. def main(): def func_1(cfg_tbl): udaExec = teradata.UdaExec(appName="DataAnalysis", version="1.0", logConsole=False) main_query = """ SELECT 'SELECT ''' || TRIM(ColumnName) || ''', COUNT(DISTINCT "' || ColumnName || '") AS DISTINCT_COUNT,' || ' COUNT(1) - COUNT("' || ColumnName || '") AS NULL_COUNT,' || ' MAX("' || ColumnName || '") AS MAX_COL_VALUE,' || ' MIN("' || ColumnName || '") AS MIN_COL_VALUE,' || CASE WHEN ColumnType IN ('I', 'D', 'F', 'I1', 'I2', 'I8', 'N', 'DA', 'TS') THEN ' MAX(LENGTH(TO_CHAR("' || ColumnName || '")))' WHEN ColumnType IN ('CF', 'CV', 'CO') THEN ' MAX(LENGTH("' || ColumnName || '"))' ELSE NULL END || ' AS MAX_COLUMN_LENGTH,' || CASE WHEN ColumnType IN ('I', 'D', 'F', 'I1', 'I2', 'I8', 'N', 'DA', 'TS') THEN ' MIN(LENGTH(TO_CHAR("' || ColumnName || '")))' WHEN ColumnType IN ('CF', 'CV', 'CO') THEN ' MIN(LENGTH("' || ColumnName || '"))' ELSE NULL END || ' AS MIN_COLUMN_LENGTH,' || ' COUNT(1) AS TABLE_COUNT,' || ' ''%s_%s'' AS TABLE_NM,' || ' ''%s'' AS SOURCE_TYPE' || ' FROM ' || TRIM(DatabaseName) || '.' || TRIM(TableName) || ';' AS COL FROM DBC.ColumnsV A WHERE DatabaseName = 'XXX' AND TableName = '%s_%s' """ % (cfg_pre, cfg_tbl, cfg_src, cfg_pre, cfg_tbl) # connect to Teradata, execute above sql and subsequent SELECT statements session = udaExec.connect(method="odbc", dsn="XXXX", username="XXX", password="XXX") pd.set_option('max_colwidth', 500) df = pd.read_sql(main_query, session) sql_execute = list(df.values.flatten()) col = ['COLUMN_NAME', 'DISTINCT_COUNT', 'NULL_COUNT', 'MAX_COL_VALUE', 'MIN_COL_VAL…
tagged with: teradata
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Issue with Inserting records through Python into Teradata table
has comment: http://stackoverflow.com/comment/88531401
has comment: http://stackoverflow.com/comment/88505513

http://stackoverflow.com/q/50755079
favorite count: 0
duplicate of: http://stackoverflow.com/q/19960077
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50755103
upvote count: 1
linked to: http://stackoverflow.com/q/19960077
type: Question
tagged with: dataframe
tagged with: filter
tagged with: pandas
has body: Here's my code df = df[df['scorecard_version'] != '9.0'] df = df[df['scorecard_version'] != '8.0'] df = df[df['scorecard_version'] != '10.0'] df = df[df['scorecard_version'] != '11.0'] df = df[df['scorecard_version'] != '11.1'] Is there any shorter alternative ?
has title: How to do multiple `is not` filter effectively
accepted answer: http://stackoverflow.com/a/50755103
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50755186
type: Question
tagged with: encoding
downvote count: 0
tagged with: beautifulsoup
has body: I'm using BeautifulSoup to parse html pages, sometimes it throws encoding error like "encoding error : input conversion failed due to input error, bytes 0x9D 0x3C 0x2F 0x74" I tried to catch this error with try except block to know exactly what lines causes the error because I have many lines with BeautifulSoup but it didn't work because it looks like BeautifulSoup only reports the error to stderr and ignore these characters and continue working r = requests.get("someurl") try: soup = BeautifulSoup(r.content,"lxml") except Exception as e: print(e) is there a way to know what line exactly throws the error and what are the character/s that causes the encoding error?
has comment: http://stackoverflow.com/comment/88521175
has title: Throwing beautifulSoup encoding error intermittently
has comment: http://stackoverflow.com/comment/88521228
favorite count: 0
has comment: http://stackoverflow.com/comment/88518638
has comment: http://stackoverflow.com/comment/88551587
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88522950

http://stackoverflow.com/comment/88534597
comment on: http://stackoverflow.com/a/50763015
score: 0
type: AnswerComment
type: Comment
has text: This seems to be the best answer. A two liner instead of the 5 liner I came up with and the 4 liner Avezan suggested. Cheers

http://stackoverflow.com/q/50767260
has body: I am looking to create a combo box in GTK where the user selected choice in the first box changes the choices available in the next boxes; ie if the first box contained manufacturers names, the next box would contain products of that manufacture, furthering that example if I selected bmw I could only select cars made by bmw. I know what the basic structure should look like, however I am not sure how to have the signals trigger one another. If someone could provide basic code or pseudo code that would be perfect .
tagged with: python
type: AnsweredQuestion
tagged with: pygobject
has title: Create combo box in python GTK 3.0 where the input of the first box changes the possible input choices for the second box
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/50767837
score: -1
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/50767837
tagged with: gtk3
has answer: http://stackoverflow.com/a/50771522
favorite count: 0
accepted answer: http://stackoverflow.com/a/50771522

http://stackoverflow.com/comment/88640575
type: QuestionComment
comment on: http://stackoverflow.com/q/50816718
score: 1
has text: There are some problems here. Your handling of `UNICODE_STRING` is wrong. `Length` and `MaximumLength` should be in bytes, not characters. You're missing two fields from `OBJECT_ATTRIBUTES` -- `SecurityDescriptor` and `SecurityQualityOfService`, and you're not initializing the `Length` field to `ctypes.sizeof(self)`. For this system call, `ShareAccess` has a special meaning. Read-Write sharing is duplex; read sharing is outbound; write sharing is inbound; and IIRC 0 sharing is an invalid parameter.
type: Comment

http://stackoverflow.com/comment/88522265
has text: copy and paste it or else provide a script to generate your sample input. Images are not allowed here
comment on: http://stackoverflow.com/q/50757265
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50834040
has comment: http://stackoverflow.com/comment/88671913
has comment: http://stackoverflow.com/comment/88673567
type: Question
linked to: http://stackoverflow.com/q/8687568
score: 0
duplicate of: http://stackoverflow.com/q/8687568
has title: create csv file from list of tuples
has comment: http://stackoverflow.com/comment/88673143
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88673196
answer count: 0
has body: I have a list which have tuples like below: lst=[(-5436.1083984375, -284.45037841796875, -13.281749725341797, 33.0), (-5436.7861328125, -275.71826171875, -15.141064643859863, 33.0), (-5302.18408203125, -197.27424621582031, -0.92733770608901978, 34.0),.....] How do i write it into a csv file such that each tuple is a row in a file.

http://stackoverflow.com/q/50809096
has comment: http://stackoverflow.com/comment/88658558
tagged with: debian
accepted answer: http://stackoverflow.com/a/51352704
has comment: http://stackoverflow.com/comment/89568937
favorite count: 0
has title: Pip six.add_metaclass error
has answer: http://stackoverflow.com/a/50827476
has body: A few days ago I started getting the following error when using pip (1,2 or 3) to install. * Traceback (most recent call last): File "/home/c4pta1n/.local/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/home/c4pta1n/.local/lib/python2.7/site-packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/home/c4pta1n/.local/lib/python2.7/site-packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/home/c4pta1n/.local/lib/python2.7/site-packages/pip/_internal/index.py", line 15, in &lt;module&gt; from pip._vendor import html5lib, requests, six File "/home/c4pta1n/.local/lib/python2.7/site-packages/pip/_vendor/requests/__init__.py", line 86, in &lt;module&gt; from pip._vendor.urllib3.contrib import pyopenssl File "/home/c4pta1n/.local/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py", line 46, in &lt;module&gt; import OpenSSL.SSL File "/usr/local/lib/python2.7/dist-packages/OpenSSL/__init__.py", line 8, in &lt;module&gt; from OpenSSL import rand, crypto, SSL File "/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py", line 13, in &lt;module&gt; from cryptography.hazmat.primitives.asymmetric import dsa, rsa File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/primitives/asymmetric/__init__.py", line 12, in &lt;module&gt; @six.add_metaclass(abc.ABCMeta) AttributeError: 'module' object has no attribute 'add_metaclass' * pip3 install pip --ignore-installed six Traceback (most recent call last): File "/usr/local/bin/pip3", line 11, in &lt;module&gt; load_entry_point('pip==10.0.1', 'console_scripts', 'pip3')() File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 476, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2700, in load_entry_point return ep.load() File "/usr/local/lib/python2.7/…
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/88647697
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50827476
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51352704
tagged with: six
score: 0
answer count: 2

http://stackoverflow.com/comment/88693373
comment on: http://stackoverflow.com/a/50844673
type: Comment
has text: It is very hard to understand this answer. Can you get a friend to help you rewrite it in better English?
score: 1
type: AnswerComment

http://stackoverflow.com/q/50809220
tagged with: for-loop
score: 2
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/50809276
has answer: http://stackoverflow.com/a/50809290
type: Question
has body: I am trying to print the following dictionary in a hierarchy format fam_dict{'6081740103':['60817401030000','60817401030100','60817401030200', '60817401030300','60817401030400','60817401030500','60817401030600'] as shown here: 60817401030000 60817401030100 60817401030200 60817401030400 60817401030500 60817401030600 So far I have the following code which works but I'm having to manually input the i'th index in each line. How can I readjust this code in a recursive format instead of having to count how many lines of code and manually put the index value each time my_p = node(fam_dict['6081740103'][0], None) my_c = node(fam_dict['6081740103'][1], my_p) my_d = node(fam_dict['6081740103'][2], my_c) my_e = node(fam_dict['6081740103'][4], my_d) my_f = node(fam_dict['6081740103'][5], my_e) my_g = node(fam_dict['6081740103'][6], my_f) print (my_p.name) print_children(my_p)
upvote count: 2
tagged with: hierarchy
has answer: http://stackoverflow.com/a/50809378
tagged with: classification
has answer: http://stackoverflow.com/a/50809259
tagged with: python
tagged with: dictionary
has title: Loop through dictionary values and print subsequently
answer count: 5
has answer: http://stackoverflow.com/a/50809308

http://stackoverflow.com/q/50842397
has body: when using the .summary() function using pandas statsmodels, the OLS Regression Results include the following fields. coef std err t P&gt;|t| [0.025 0.975] How can I get the standardised coefficients (which exclude the intercept), similarly to what is achievable in SPSS?
has answer: http://stackoverflow.com/a/75254522
answer count: 3
tagged with: pandas
downvote count: 0
tagged with: coefficients
favorite count: 0
has answer: http://stackoverflow.com/a/54652025
type: UnansweredQuestion
tagged with: python
tagged with: regression
score: 13
has answer: http://stackoverflow.com/a/50844691
type: Question
tagged with: statsmodels
upvote count: 13
has title: how to get standardised (Beta) coefficients for multiple linear regression using statsmodels

http://stackoverflow.com/comment/88667252
type: Comment
has text: Thanks. I have used the solution you have suggested, but I am still getting an error:
type: AnswerComment
comment on: http://stackoverflow.com/a/50831430
score: 0

http://stackoverflow.com/a/50775266
answers question: http://stackoverflow.com/q/50767745
type: Answer
accepted answer of: http://stackoverflow.com/q/50767745
score: 0
has body: The relative level, is the level of the referral minus the level of the "current" userprofile. We can thus use referral.level - userprofile.level. If you however want to annotate all these objects with a relative_level, we can use Django's ORM: from django.db.models import F (user_profile.get_descendants() .filter(level__lte=profile.level + 3) .annotate(relative_level=F('level') - profile.level)) So then all the descendants will have an extra attribute .relative_level that will containt the relative level.
type: AcceptedAnswer

http://stackoverflow.com/comment/88422945
comment on: http://stackoverflow.com/q/50706851
has text: @Jean-FrançoisFabre edited
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88584958
type: Comment
comment on: http://stackoverflow.com/q/50788813
type: QuestionComment
has text: I’ve also tried return redirect(url). Still the same error. Have been stuck with it for a few hours ...
score: 0

http://stackoverflow.com/a/50747910
has body: Seems like it is a known issue in python 3: https://github.com/lokkju/pyspatialite/issues/27
downvote count: 0
answers question: http://stackoverflow.com/q/50747849
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/88814943
has text: try raplcying your current `html_content = requests.get(url, headers=headers)` with this `html_content = requests.get(url, headers=headers, proxies = {"https":"177.92.4.70:80"})`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50905625
type: Comment

http://stackoverflow.com/comment/88446181
type: AnswerComment
comment on: http://stackoverflow.com/a/50717174
has text: `hadoop fs -getmerge [-nl] <src> <localdst>` - it takes directory in HDFS and meges all files into one on local file system as per docs [here](https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/FileSystemShell.html#getmerge).
score: 0
type: Comment

http://stackoverflow.com/q/50723233
has answer: http://stackoverflow.com/a/50723569
has comment: http://stackoverflow.com/comment/88455599
tagged with: serial-port
has comment: http://stackoverflow.com/comment/88455433
tagged with: python
tagged with: uart
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88459267
type: Question
has title: How to terminate ser.read in pyserial python when using with while 1 without entering any commands?
has body: I am trying to write a script currently I am using ser.read() directly and printing values but I want to write a function where it waits for some time reads all char and than gets out of loop. Current loop prints all char but doesnt get out of the loop and I have to either edit and make it exit by keyboard click. But I want a script where it reads and exit and user doesnt need to do anything. Sorry if a noob question but new with Python and Pyserial if(ser.isOpen()): try: def read(): ser.flushInput() while 1: try: check = ser.read() print check except Exception: print("Error") else: print("Port not open")
linked to: http://stackoverflow.com/q/17553543
tagged with: python-2.7
score: 0
tagged with: pyserial
answer count: 1

http://stackoverflow.com/a/50781393
type: Answer
has comment: http://stackoverflow.com/comment/88569562
has comment: http://stackoverflow.com/comment/88569469
has body: Consider flattening the list first if you intend to use len(): &gt;&gt;&gt; my_list = [['linux'], ['ML'], ['linux', 'ML', 'Data Science', 'GIT'],['linux', 'Data Science', 'GIT'], ['GIT'], ['ML', 'GIT'], ['linux'], ['linux'], ['linux'], ['Data Science']] &gt;&gt;&gt; len([item for sublist in my_list for item in sublist]) 16
answers question: http://stackoverflow.com/q/50781368
score: 0

http://stackoverflow.com/comment/88521299
type: Comment
has text: I'll have a look, the only thing I can say right away is that looping on the element of an array is extremely inefficient. The interest of numpy is that you can do operation array-wide.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50756288

http://stackoverflow.com/comment/88644589
type: QuestionComment
has text: I understand that however your code still is not testable. `main_frame` refers to nothing in your example.
comment on: http://stackoverflow.com/q/50818809
score: 0
type: Comment

http://stackoverflow.com/q/50741221
has comment: http://stackoverflow.com/comment/88489940
tagged with: beautifulsoup
type: UnansweredQuestion
has body: I am trying to scrap images from google and download them into a folder.But Google only gives me 20 results and never more than that even when i change the limit. Selenium works fine, but i want to know why it this is not working. Please help! this is my code import requests from bs4 import BeautifulSoup import sys import random import urllib query=input("Enter the keyword to search for :") query2 = query.replace(' ','%20') headers={'user-agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'} url="http://www.google.com/search?q="+query2+"&amp;tbm=isch" start = 0 while start &lt;50: page=requests.get(url,headers) start=start+4 soup=BeautifulSoup(page.text,'html.parser') list2=soup.find_all('img',limit=21,recursive=True) i=0 print(len(list2)) while i&lt;len(list2): file=list2[i]['src'] print(list2[i]['src']) full_file_name = query+'image'+str(i) urllib.request.urlretrieve(file,full_file_name) i=i+1
has comment: http://stackoverflow.com/comment/88490416
tagged with: python
answer count: 0
tagged with: web-crawler
type: Question
has title: Why is the maximum number of images i can download from Google using BeautifulSoup only 20?
score: 0
has comment: http://stackoverflow.com/comment/88500810
tagged with: google-crawlers

http://stackoverflow.com/q/50713023
type: Question
tagged with: image-segmentation
has title: License plate character segmentation python opencv
has answer: http://stackoverflow.com/a/50713277
answer count: 1
downvote count: 0
has body: I want to isolate every character in the following image: and it should create a rectangular bounding box around each character. My code is creating a circular bounding box. I need to supply these isolated character images to my trained model to predict the character. I haven't done image processing before which leads me to asking such a question. This is the code I'm using: # Standard imports import cv2 import numpy as np; from PIL import Image params = cv2.SimpleBlobDetector_Params() # Change thresholds params.minThreshold = 10; params.maxThreshold = 200; #Filter by Color params.filterByColor=False params.blobColor=255 # Filter by Area. params.filterByArea = False params.minArea = 50 # Filter by Circularity params.filterByCircularity = False params.minCircularity = 0.0785 # # # Filter by Convexity params.filterByConvexity = False params.minConvexity = 0.87 # # # Filter by Inertia params.filterByInertia = False params.minInertiaRatio = 0.01 # Read image im = cv2.imread("C:\\xx\\testimages\\bw_plate.jpg", cv2.IMREAD_GRAYSCALE) cv2.threshold(im,200,255,cv2.THRESH_BINARY_INV,im) # Set up the detector with default parameters. detector = cv2.SimpleBlobDetector_create(params) # Detect blobs. keypoints = detector.detect(im) # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Show keypoints cv2.imshow("Keypoints", im_with_keypoints) cv2.waitKey(0) My output with the following code is: Why is it not detecting 0 and 2 properly? Also how can I create separate jpeg files for every isolated character? The C++ implementation of my project uses CblobResult class which did the segmentation. Is there any equivalent library in python? This is what the final output must look like for every character after segmentation:
favorite count: 0
tagged with: python
tagged with: ocr
accepted answer: http://stackoverflow.com/a/50713277
upvote count: 3
tagged with: opencv
type: AnsweredQuestion
score: 3
tagged with: image-processing

http://stackoverflow.com/comment/88567572
type: Comment
comment on: http://stackoverflow.com/q/50780402
score: 0
type: QuestionComment
has text: Thanks for pasting it in the comments where the formatting is totally lost...

http://stackoverflow.com/q/50819569
has body: Any ideas on getting data into a PostgreSQL stored proc / function from Python? I have a DataFrame built up from other data sources and I need to do some work with Postgres and then INSERT/UPDATE some data in PostgreSQL if the query is successful. I know I can get it to work using just Python and raw SQL queries in Python strings and inserting variables where needed, but I know this is poor practice. In the past I've been able to pass a C# DataTable from C# to a SQL Stored Procedure using MS SQL Server and User-Defined Table types. Is there a way to do something similar with Python DataFrames within PostgreSQL? This link has been really helpful on the syntax for Python variables to Postgres function, but I have not seen anything on passing Pandas DataFrames to a PostgreSQL function. Is this possible? Is there a different design pattern I should be using?
tagged with: python
tagged with: stored-procedures
has title: How to pass a pandas DataFrame to a PostgreSQL Function (Stored Procedure)?
has comment: http://stackoverflow.com/comment/88645285
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/77014121
has comment: http://stackoverflow.com/comment/88653442
has comment: http://stackoverflow.com/comment/88653819
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88654258
tagged with: postgresql
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88654020
type: Question
has comment: http://stackoverflow.com/comment/88645414

http://stackoverflow.com/comment/88551712
type: Comment
comment on: http://stackoverflow.com/q/50772080
has text: Actually, I'm not sure if it's completely unrelated. I don't know whether you actually succeed in making the connection because it just gets closed either way. I suspect it would throw `NameError` though if the connection was not successful because `conn` wouldn't exist.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88447231
score: 1
has text: Using while loop would be simple here, why do you want to stick to for loop? I am not sure if it's possible with the for loop!
comment on: http://stackoverflow.com/q/50719393
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88608871
type: Comment
has text: See the duplicate post; the top answer there works on general iterators.
type: QuestionComment
comment on: http://stackoverflow.com/q/50801461
score: 0

http://stackoverflow.com/a/50753692
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88538125
answers question: http://stackoverflow.com/q/50753610
downvote count: 0
has body: You are redefining what redirect means. redirect redirects client to target location, so just rename redirect to something else, following line: redirect_url='http://localhost:5000/'
type: Answer
has comment: http://stackoverflow.com/comment/88515269

http://stackoverflow.com/a/50797810
has comment: http://stackoverflow.com/comment/88602954
has body: Use enumerate: for i, r in enumerate(data): print 'current row is {}'.format(i) print r[1] If you want to count from 1 just use enumerate(data, 1).
downvote count: 0
has comment: http://stackoverflow.com/comment/88602527
type: Answer
answers question: http://stackoverflow.com/q/50797738
has comment: http://stackoverflow.com/comment/88602853
has comment: http://stackoverflow.com/comment/88603378
has comment: http://stackoverflow.com/comment/88603019
score: 1
upvote count: 1

http://stackoverflow.com/comment/95696554
has text: @desertnaut: and do they now? I find this rather confusing! :-)
comment on: http://stackoverflow.com/a/50731449
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88557832
comment on: http://stackoverflow.com/q/50774928
score: 0
has text: Are you looking for some kind of a regression test? You could save the figure to an image and compare the file against a prepared reference image. However, such tests are usually pretty fragile, requiring to update the reference files from time to time.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88559148
type: Comment
comment on: http://stackoverflow.com/q/50776079
type: QuestionComment
score: 0
has text: yeah, check now

http://stackoverflow.com/q/50714289
has answer: http://stackoverflow.com/a/50714341
tagged with: python
tagged with: regex
type: AnsweredQuestion
has title: How to Insert : semicolon while doing re in Python
type: Question
accepted answer: http://stackoverflow.com/a/50714341
tagged with: numbers
has body: In this program i want to display only numbers and semicolon excluding ' and ] But my output shows only number not semicolon. How to get a output with both semicolon and numbers code ===== import re a = "'23:33:26]" a = re.sub('[^0-9]','',a) print(a) My output ========== 233326 Needed Output ============= 23:33:26
has answer: http://stackoverflow.com/a/50714422
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50714422

sorting
tags question: http://stackoverflow.com/q/50796746
tags question: http://stackoverflow.com/q/50821008
tags question: http://stackoverflow.com/q/50833410
tags question: http://stackoverflow.com/q/50843370
tags question: http://stackoverflow.com/q/50818373
tags question: http://stackoverflow.com/q/50797397
tags question: http://stackoverflow.com/q/50744490
tags question: http://stackoverflow.com/q/50753399
tags question: http://stackoverflow.com/q/50751990
tags question: http://stackoverflow.com/q/50705511
tags question: http://stackoverflow.com/q/50730702
tags question: http://stackoverflow.com/q/50753073
tags question: http://stackoverflow.com/q/50704697
tags question: http://stackoverflow.com/q/50826373
tags question: http://stackoverflow.com/q/50813898
tags question: http://stackoverflow.com/q/50833581
tags question: http://stackoverflow.com/q/50769141
tags question: http://stackoverflow.com/q/50710693
type: Tag
tags question: http://stackoverflow.com/q/50803334
tags question: http://stackoverflow.com/q/50770201
tags question: http://stackoverflow.com/q/50704846
tags question: http://stackoverflow.com/q/50701156
tags question: http://stackoverflow.com/q/50742036
tags question: http://stackoverflow.com/q/50703339
tags question: http://stackoverflow.com/q/50785187
tags question: http://stackoverflow.com/q/50795241
tags question: http://stackoverflow.com/q/50757929
tags question: http://stackoverflow.com/q/50793753
tag name: sorting
tags question: http://stackoverflow.com/q/50849300
tags question: http://stackoverflow.com/q/50699111
tags question: http://stackoverflow.com/q/50794333
tags question: http://stackoverflow.com/q/50848054
tags question: http://stackoverflow.com/q/50810572
tags question: http://stackoverflow.com/q/50827262
tags question: http://stackoverflow.com/q/50794251

http://stackoverflow.com/q/50813272
favorite count: 0
has body: I am writing unit tests for the api, which connects to MongoDB. In my API module it looks like this: from flask import Flask, jsonify from MyApp import MongoData api = Flask(__name__) DB_CONN = MongoData() @api.route('/bla', methods=['GET']) def alive(): return jsonify({'response': true}) I have a problem while importing this module in my unittest. I want to mock collection from MongoData() with special mock class, which uses mongomock. The problem is that I cannot mock DB_CONN while importing in tests: from MyApp import api I was trying to do this with mock: DB_CONN = MockMongoData() with mock.patch('MyApp.api.DB_CONN', DB_CONN): from MyApp import api but it still tries to connect to the database as specified in the config file. Any advice how to mock DB_CONN from MyApp.api module? Thanks in advance! EDIT: This will work: import sys from MyApp import MongoData, MockMongoData sys.modules['MyApp'].MongoData = MockMongoData from MyApp import api But is there a better (more pythonic) way to do this?
has comment: http://stackoverflow.com/comment/88634653
tagged with: python
tagged with: python-3.x
score: 2
type: UnansweredQuestion
has title: Mocking module global variable while import
tagged with: unit-testing
type: Question
has answer: http://stackoverflow.com/a/50813409
upvote count: 2
has comment: http://stackoverflow.com/comment/88632534
tagged with: api
answer count: 1
downvote count: 0
tagged with: flask

http://stackoverflow.com/comment/88699111
type: AnswerComment
comment on: http://stackoverflow.com/a/50842256
type: Comment
has text: You can install sklearn with 1 pip command. Tensorflow and Keras should is just as easy if you don't use GPUs. As for your overflow errors, your gradients are probably exploding. Try printing wout, bout on each step to see what I mean. This probably happens because you didn't change your derivative to match your activation function
score: 0

http://stackoverflow.com/comment/88711826
comment on: http://stackoverflow.com/q/50848260
score: 0
has text: @Fian now it is `web: gunicorn app:app` but I had set it to `web: gunicorn -b 0.0.0.0:$PORT app:app` and it didn't work.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50783658
tagged with: opencv
score: 1
has comment: http://stackoverflow.com/comment/88574797
type: Question
answer count: 2
upvote count: 1
has body: I'm writing a face recognizer in python but I'm in trouble with the training part. import cv2 import numpy as np from os import listdir from os.path import isfile, join data_path = '/home/pi/Desktop/data' onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path, f))] Training_Data, Labels = [],[] for i, files in enumerate(onlyfiles): image_path = data_path + onlyfiles[i] print(image_path) images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) Training_Data.append(np.asarray(images, dtype=np.uint8)) Labels.append(i) Labels = np.asarray(Labels, dtype=np.int32) model = cv2.createLBPHFaceRecognizer() model.train( np.asarray(Training_Data) ,np.asarray(Labels) ) print("done") When I run it I get this error: Traceback (most recent call last): File "Train_Model.py", line 17, in Training_Data.append(np.asarray(images, dtype=np.uint8)) File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 460, in asarray return array(a, dtype, copy=False, order=order) TypeError: long() argument must be a string or a number, not 'NoneType' Thank you.
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/63066638
downvote count: 0
type: UnansweredQuestion
has title: OpenCV-python Train-LBPH recognizer
has answer: http://stackoverflow.com/a/56325861

http://stackoverflow.com/comment/88733508
type: AnswerComment
comment on: http://stackoverflow.com/a/50853339
score: 0
type: Comment
has text: awesome. This is exactly what I needed.

http://stackoverflow.com/a/50878168
answers question: http://stackoverflow.com/q/50795993
score: 0
type: AcceptedAnswer
has body: Using this example code of a parameter tree : http://www.pyqtgraph.org/downloads/0.10.0/pyqtgraph-0.10.0-deb/pyqtgraph-0.10.0/examples/parametertree.py I was able to rewrite in a more proper way my parametertree. The update of the interdependent variables were achievable using a class with subfunctions like the "ComplexParameter" class of the example in the link above. The data entered by the user are now being taken into account with the right use of global variables in the class ComplexParameter.
type: Answer
accepted answer of: http://stackoverflow.com/q/50795993

http://stackoverflow.com/comment/88536460
type: Comment
has text: in https://dashboard.heroku.com/apps/your-app-name is an option to "Add a Buildpack" choose Python and thats it.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50763962

http://stackoverflow.com/a/50824727
has comment: http://stackoverflow.com/comment/88654814
upvote count: 3
has comment: http://stackoverflow.com/comment/88655161
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88655407
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88655133
has comment: http://stackoverflow.com/comment/88654790
has comment: http://stackoverflow.com/comment/88729118
has comment: http://stackoverflow.com/comment/88655461
answers question: http://stackoverflow.com/q/50824528
has comment: http://stackoverflow.com/comment/88655192
has comment: http://stackoverflow.com/comment/88655568
has body: IIUC, use groupby with transform and set it to a new column in existing dataframe. data['counts'] = (data.groupby(['Clinic Number', 'year', 'month', 'Answer Text'])['Clinic Number'] .transform('size')) data = data.sort_values(['Client Number','Answer Date']) Output: Clinic Number Question Text Answer Text Answer Date year month dayofyear counts 1 1 bathing No 2006/7/1 2006 1 7 4 2 1 dressing No 2006/7/1 2006 1 7 4 3 1 feeding NO 2006/7/1 2006 1 7 1 4 1 housekeeping No 2006/7/1 2006 1 7 4 5 1 medications No 2006/7/1 2006 1 7 4 6 2 bathing No 2006/1/1 2006 1 1 2 7 2 dressing Yes 2006/1/1 2006 1 1 3 8 2 feeding Yes 2006/1/1 2006 1 1 3 9 2 housekeeping Yes 2006/1/1 2006 1 1 3 10 2 medications No 2006/1/1 2006 1 1 2
accepted answer of: http://stackoverflow.com/q/50824528

http://stackoverflow.com/comment/88513600
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50752791
has text: You're not closing the file. You might look into the `with` statement ([example](https://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for)).
type: Comment

http://stackoverflow.com/comment/88605830
has text: I took a closer look at the `opencv-python` package on PyPI. They don't provide a prebuilt wheel for your architecture (which would be `aarch64`), so you won't be able to install `opencv-python` from PyPI neither on one, nor the other RaspberryPi. What does `python3 -c "from setuptools import pep425tags; print(pep425tags.get_platform())"` return? is it `linux_aarch64` or `linux_armv7l`?
score: 0
comment on: http://stackoverflow.com/q/50791252
type: Comment
type: QuestionComment

http://stackoverflow.com/a/74944217
has body: Could also use np.tile() df.loc[np.tile(df.index,3)].sort_index().reset_index(drop=True) Output: Person ID ZipCode Gender 0 12345 882 38182 Female 1 12345 882 38182 Female 2 12345 882 38182 Female 3 32917 271 88172 Male 4 32917 271 88172 Male 5 32917 271 88172 Male 6 18273 552 90291 Female 7 18273 552 90291 Female 8 18273 552 90291 Female
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50788508
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88628252
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50811387
has text: @user3483203 This is an example, my actual key is string, so I wanted to keep data type the same.
score: 0

http://stackoverflow.com/q/50750101
upvote count: 2
has comment: http://stackoverflow.com/comment/94089456
answer count: 2
has answer: http://stackoverflow.com/a/53614392
has title: Pyodbc - read output parameter of stored procedure (SQL Server)
favorite count: 0
tagged with: sql-server
has comment: http://stackoverflow.com/comment/93907640
has comment: http://stackoverflow.com/comment/88508479
has comment: http://stackoverflow.com/comment/88508614
tagged with: python
tagged with: pyodbc
score: 2
has comment: http://stackoverflow.com/comment/88608237
downvote count: 0
type: UnansweredQuestion
type: Question
has body: I'm trying to get the output parameter of an SQL Server stored procedure using pyodbc. The procedure is located in SQL Server and I can insert data successfully from my program. This is part of the SP: INSERT INTO Table(a,b,c,d,e,f,g) VALUES (@a,@b,@c,@d,@e,@f,@g); SET @Result = 'Inserted' RETURN @Result When I try to read the result variable in my code it shows empty.
has answer: http://stackoverflow.com/a/74818421

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/50852405
tags question: http://stackoverflow.com/q/50839884
tags question: http://stackoverflow.com/q/50762252
tags question: http://stackoverflow.com/q/50731702
tags question: http://stackoverflow.com/q/50840416
tags question: http://stackoverflow.com/q/50779617
tags question: http://stackoverflow.com/q/50824938
tags question: http://stackoverflow.com/q/50853561
tags question: http://stackoverflow.com/q/50763427

http://stackoverflow.com/q/50820707
has comment: http://stackoverflow.com/comment/104438021
possible better answer: http://stackoverflow.com/a/50820933
has comment: http://stackoverflow.com/comment/88646892
linked to: http://stackoverflow.com/q/6760685
tagged with: python
has title: Python class instances unique by some property
has comment: http://stackoverflow.com/comment/88648225
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/31875
has body: Suppose I want to create instances of my class freely, but if I instantiate with the same argument, I want to get the same unique instance representing that argument. For example: a = MyClass('Instance 1'); b = MyClass('Instance 2'); c = MyClass('Instance 1'); I would want a == c to be True, based on the unique identifier I passed in. Note: (1) I'm not talking about manipulating the equality operator-- I want a to really be the same instance as c. (2) This is intended as library code, so uniqueness has to be enforced-- we can't just count on users doing the right thing (whatever that is). Is there a canonical way of achieving this? I run into this pattern all the time, but I usually see solutions involving shadow classes, meant for only internal instantiation. I think I have a cleaner solution, but it does involve a get() method, and I'm wondering if I can do better.
type: Question
accepted answer: http://stackoverflow.com/a/50821287
has comment: http://stackoverflow.com/comment/88646980
score: 3
has answer: http://stackoverflow.com/a/50820933
has comment: http://stackoverflow.com/comment/88647073
has comment: http://stackoverflow.com/comment/88647437
has answer: http://stackoverflow.com/a/50821287
upvote count: 3
answer count: 2
favorite count: 0

http://stackoverflow.com/q/50785592
tagged with: lstm
has title: Reshaping variables for keras LSTM
has body: I want to make LSTM that will learn on the text that I will provide. First, i created the function that would take training data. def read_data(filename): with open(filename) as f: content = f.readlines() content = [x.strip() for x in content] content = [word for i in range(len(content)) for word in content[i].split()] content = np.array(content) return content training_data = read_data(filename) print("Loaded training data...") After, i have a function to assign all the words number. def build_dataset(words): count = collections.Counter(words).most_common() dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary) reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return dictionary, reverse_dictionary dictionary, reverse_dictionary = build_dataset(training_data) vocab_size = len(dictionary) Exmaple from dictionary variable would be 'the': 0, 'and': 1, 'to': 2, I found some sample code for the LSTM # reshape X to be [samples, time steps, features] X = numpy.reshape(dataX, (n_patterns, seq_length, 1)) # normalize X = X / float(n_vocab) # one hot encode the output variable y = np_utils.to_categorical(dataY) # define the LSTM model model = Sequential() model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(256)) model.add(Dropout(0.2)) model.add(Dense(y.shape[1], activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam') # define the checkpoint filepath="weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min') callbacks_list = [checkpoint] # fit the model model.fit(X, y, epochs=50, batch_size=64, callbacks=callbacks_list) I dont understand what do i have to do for the reshape. My seq length is 3 but how do i determine number of patterns and as i understand dataX should be vector of the words. When i do this X = np.reshape(dictionary, (n_patt…
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88577801
has comment: http://stackoverflow.com/comment/88578185
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50785936
type: Question
answer count: 1
tagged with: keras

http://stackoverflow.com/a/50744776
type: AcceptedAnswer
downvote count: 0
has body: Pandas and several other function calls in your code will not work with nopython=True. The available libraries that can be used with numba jit in nopython is fairly limited (pretty much only to numpy arrays and certain python builtin libraries). You can find more information here
type: Answer
upvote count: 32
has comment: http://stackoverflow.com/comment/88500835
accepted answer of: http://stackoverflow.com/q/50744686
answers question: http://stackoverflow.com/q/50744686
score: 32
has comment: http://stackoverflow.com/comment/88497503

http://stackoverflow.com/comment/105489770
has text: @Learningstatsbyexample `The sys.maxint constant was removed, since there is no longer a limit to the value of integers` - you can find the link here - https://docs.python.org/3.1/whatsnew/3.0.html#integers
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/59364846

http://stackoverflow.com/q/50709755
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88428932
has answer: http://stackoverflow.com/a/50716299
has comment: http://stackoverflow.com/comment/88428776
has comment: http://stackoverflow.com/comment/88428862
has body: I'm trying to find elements by tag name like Titles from this XML URL http://www.rssmix.com/u/8287461/rss.xml but unable it's not working please help It is just printing a blank page and nothing else browser.get("http://www.rssmix.com/u/8287461/rss.xml") time.sleep(10) title = browser.find_elements_by_tag_name('title') description = browser.find_elements_by_tag_name('description') link = browser.find_elements_by_tag_name('link') for p_title, p_description, p_links in zip(title, description, link): title_s = p_title.text description_s = p_description.text link_s = p_links.text print (title_s + "\t" + description_s + "\t" + link_s + "\n")
linked to: http://stackoverflow.com/q/1912434
has comment: http://stackoverflow.com/comment/88428706
score: 1
accepted answer: http://stackoverflow.com/a/50716299
has title: How to extract elements by tagName from XML URL using Selenium Python
has comment: http://stackoverflow.com/comment/88437409
type: AnsweredQuestion
tagged with: python
tagged with: elementtree
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/88428949
type: Question
upvote count: 2
tagged with: selenium
has comment: http://stackoverflow.com/comment/88428875

http://stackoverflow.com/comment/88533330
comment on: http://stackoverflow.com/a/50762573
score: 1
type: AnswerComment
type: Comment
has text: Yes it works but I'm not sure I understand why though. Any information you could add as to why this works?

http://stackoverflow.com/comment/117272852
type: AnswerComment
comment on: http://stackoverflow.com/a/50822803
score: 0
type: Comment
has text: Feel free to just edit your answer - most of the code is yours.

http://stackoverflow.com/a/50840845
type: Answer
has body: Have you thought of installing a virtual environment? you can also try import sys sys.path.append('insert the location to your scripts')
has comment: http://stackoverflow.com/comment/88705445
has comment: http://stackoverflow.com/comment/88706132
answers question: http://stackoverflow.com/q/50840702
score: 0

http://stackoverflow.com/q/50779150
has comment: http://stackoverflow.com/comment/88565264
upvote count: 1
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50779213
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88565258
favorite count: 0
tagged with: python
has body: I have two dictionaries of alphabets with values as the frequency of a character. When I try to plot them with my code below, I get the following error: ValueError: shape mismatch: objects cannot be broadcast to a single shape import string import matplotlib.pyplot as plt labels = list(string.ascii_uppercase) N = len(labels) dict_1 = {'A': 0.08167, 'B': 0.01492, 'C': 0.02782, 'D': 0.04253, 'E': 0.12702, 'F': 0.02228, 'G': 0.02015, 'H': 0.06094, 'I': 0.06966, 'J': 0.00153, 'K': 0.00772, 'L': 0.04025, 'M': 0.02406, 'N': 0.06749, 'O': 0.07507, 'P': 0.01929, 'Q': 0.00095, 'R': 0.05987, 'S': 0.06327, 'T': 0.09056, 'U': 0.02758, 'V': 0.00978, 'W': 0.0236, 'X': 0.0015, 'Y': 0.01974, 'Z': 0.00074} dict_2 = {'P': 0.05776173285198556, 'U': 0.05776173285198556, 'A': 0.09025270758122744, 'O': 0.05415162454873646, 'L': 0.1263537906137184, 'M': 0.02888086642599278, 'V': 0.06859205776173286, 'S': 0.061371841155234655, 'D': 0.02888086642599278, 'N': 0.032490974729241874, 'J': 0.04332129963898917, 'I': 0.021660649819494584, 'F': 0.036101083032490974, 'B': 0.032490974729241874, 'H': 0.08664259927797834, 'C': 0.007220216606498195, 'W': 0.032490974729241874, 'Y': 0.05415162454873646, 'X': 0.007220216606498195, 'Z': 0.05054151624548736, 'R': 0.007220216606498195, 'E': 0.0036101083032490976, 'K': 0.0036101083032490976, 'T': 0.007220216606498195} X = np.arange(len(dict_1)) bar_width = 0.45 fig = plt.figure( figsize=(17,5) ) ax = plt.subplot(111) ax.bar(X, dict_1.values(), bar_width, color='blue', align='center', hatch='//') ax.bar(X-bar_width, dict_2.values(), bar_width, color='green', align='center', hatch='//') ax.legend(('Usual English','Your Text'), fontsize = 15) plt.xticks(X-(bar_width/2), dict_1.keys()) plt.xlabel('Character', fontsize = 15) plt.ylabel('Frequency', fontsize = 15) plt.title("Frequency Analysis", fontsize=17) plt.show() I built the code using the same dictionary as first and thought it would work had I a different dictionary of alphabets. When I use the same dictiona…
has title: Plotting a double barplot in Python with values coming from two different dictionaries
has comment: http://stackoverflow.com/comment/88565236
type: UnansweredQuestion

http://stackoverflow.com/q/50821092
tagged with: python-3.x
tagged with: list
has comment: http://stackoverflow.com/comment/88647547
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50821239
has comment: http://stackoverflow.com/comment/88647690
has title: Write lists to csv in python
has comment: http://stackoverflow.com/comment/88647443
answer count: 3
tagged with: arrays
downvote count: 0
has body: I have this list list of values: Output of list_a: list_a: [[[2.0, 4.0], [1.0, 2.0]], [[2.0, 4.0], [2.0, 3.0], [3.0, 1.0]], [[3.0, 6.0], [5.0, 5.0], [6.0, 4.0]], [[3.0, 6.0], [4.0, 7.0]], [[2.0, 4.0], [3.0, 6.0]]] I want to export it to a csv file in a specific format so that every set of values occupies a cell in the following format: (2.0; 4.0) | (1.0; 2.0) (2.0; 4.0) | (2.0; 3.0) | (3.0; 1.0) ... The "|" represents the separation of cells on the same row (not to be included in the csv file) and the format of the values in the cell should be parentheses and semicolon as such (X1; X2) I tried the following but I get brackets and colons: with open('outputdata.csv', 'w') as outfile: mywriter = csv.writer(outfile) for d in result: mywriter.writerow(d) Any help is appreciated!
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/50821307
has answer: http://stackoverflow.com/a/50821339

http://stackoverflow.com/comment/88683321
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50839629
has text: If you don't mind additional space complexity, you could have a dictionary that keeps track of whether of not all social media urls have been processed. Something like `tracker = {'facebook': False, 'instagram': False}`; and then every time you process either of those social media urls, you update its corresponding value to `True`. This will allow you to only break out of your loop once all values of the dictionary are `True`.

http://stackoverflow.com/comment/88671333
has text: Although the documentation is a bit lacking in that regard, you can actually pass in `node_color` specifications on a per node basis: `g = nx.erdos_renyi_graph(100, 0.2); nx.draw_networkx(g, node_color=50*['b'] + 50*['g'])`
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50830881

http://stackoverflow.com/comment/88425414
type: AnswerComment
score: 0
type: Comment
has text: @jeyanthinath Indeed. The only ones I could find are in [`requirements-dev.txt`](https://github.com/dbader/schedule/blob/master/requirements-dev.txt) but as far as I can see `setup.py` doesn't link to this file. Very odd.
comment on: http://stackoverflow.com/a/50699275

http://stackoverflow.com/q/50809409
has comment: http://stackoverflow.com/comment/88624547
has body: I have a list that I originally had taken from a CSV file and saved to a list. The csv file was originally an excel sheet that had categories with data for each one. I have had trouble trying to extract the header and the content along with it in an organized fashion. the list looks like this myLoad =[ ['Unit 1000', '', ''] ['A1', 'Food', 'Good'] ['A3', 'Drink', 'Poor'] ['A6', 'Food', ''] ['Unit 1001', '', ''] ['A7', 'Cheese', 'Yellow'] ['A8', 'Coke', 'Brown] ] and I would want the list to look something like 1000, A1, Food, Good 1000, A3, Drink, Poor 1000, A6, Food, 1001, A7, Cheese, Yellow 1001, A8, Coke, Brown Although there was another list I was comparing it to to extract data from, I was using regex to find the Unit number, but even after being able to find the number I was unable to extract the rest of the list with each category number to go with it.What I had so far was. loadRegex = re.compile(r'\d{4}') for i, row in enumerate(myLoad): thisLoad = loadRegex.search(row[0]) if thisLoad: print thisLoad.group() #which would print each number After this I couldnt figure out how I could get Unit # to print (and eventually append to anew list), and the content below it for each section as if it all went together. I wanted the content to be like if the Unit # is found then print each row until the next unit # is found, but it has to be based on the regex so that I can use the same regex to compare the same unit number to another file
type: Question
accepted answer: http://stackoverflow.com/a/50809493
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50810916
score: 0
has answer: http://stackoverflow.com/a/50809511
has answer: http://stackoverflow.com/a/50809466
possible better answer: http://stackoverflow.com/a/50809466
has answer: http://stackoverflow.com/a/50809493
tagged with: python-2.7
has title: Adding items to a list using regex to search for the correct header
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/50759182
type: AnsweredQuestion
score: 2
has title: PermissionError Errno 13 Permission denied
type: Question
has answer: http://stackoverflow.com/a/50759281
has body: I am trying to read a directory which contains html files with python. The code I am using is this: import os f = open(r"C:\Users\Grty\Desktop\de", "w+") for filename in os.listdir(os.getcwd()): content = f.read() print (filename, len(content)) The problem is I cant access the directory. I have tried different locations but the problem persists. I have also done the relative chmod 777 (Using windows 10) and still nothing. I enabled sharing with everyone, giving read/write permissions to everyone and also disabled the "read only" (which somehow is being re-enabled itself). I have also run the cmd as an admin and still no progress. Anyone got an idea of how to overcome this?
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
tagged with: permissions
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/50759281
tagged with: python

http://stackoverflow.com/comment/88685510
has text: Probably a recursive approach. There are plenty of SO answers that cover how to do this.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50840899
type: QuestionComment

http://stackoverflow.com/comment/88560847
type: Comment
type: QuestionComment
has text: How have you installed PyQt5? Have you used apt-get for it or have you used pip ?, gives more detail, I also recommend reinstalling PyQt5, and if the problem persists report it as a bug to ubuntu.
comment on: http://stackoverflow.com/q/50776545
score: 0

http://stackoverflow.com/q/50824068
has comment: http://stackoverflow.com/comment/88653259
has title: Can't host web server with flask
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/50824160
has body: When I run this sample code : from flask import Flask app = Flask(__name__) def main () : return "Welcome to Flask " if __name__ == "__main__": app.run(debug=True, host="0.0.0.0", port=80) Entering following on the terminal: python3 app.py, the output is: * Serving Flask app "app" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://0.0.0.0:80/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 144-032-769 127.0.0.1 - - [13/Jun/2018 00:11:59] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [13/Jun/2018 00:11:59] "GET /favicon.ico HTTP/1.1" 404 - 127.0.0.1 - - [13/Jun/2018 00:12:15] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [13/Jun/2018 00:12:16] "GET /favicon.ico HTTP/1.1" 404 - 127.0.0.1 - - [13/Jun/2018 00:12:22] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [13/Jun/2018 00:12:22] "GET /favicon.ico HTTP/1.1" 404 - It does not stop And when I open 127.0.0.1 in my browser it says that Not Found
score: 0
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/88653280
tagged with: flask

http://stackoverflow.com/q/50756793
has answer: http://stackoverflow.com/a/50778453
downvote count: 1
has comment: http://stackoverflow.com/comment/88522542
linked to: http://stackoverflow.com/q/1713335
tagged with: function
has answer: http://stackoverflow.com/a/59263392
has answer: http://stackoverflow.com/a/50757759
has comment: http://stackoverflow.com/comment/88529084
duplicate of: http://stackoverflow.com/q/1713335
answer count: 4
linked to: http://stackoverflow.com/q/2386714
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/59263392
score: 1
favorite count: 0
type: Question
has body: I'm implementing a peak detection algorithm in Python that detects only those peaks that are above a threshold magnitude. I don't want to use the inbuilt function as I have to extend this simulation to Hardware implementation also. from math import sin,isnan from pylab import * def peakdet(v, delta,thresh,x): delta=abs(delta) maxtab = [] mintab = [] v = asarray(v) mn, mx = v[0], v[0] mnpos, mxpos = NaN, NaN lookformax = True for i in arange(len(v)): this = v[i] if abs(this)&gt;thresh: if this &gt; mx: mx = this mxpos = x[i] if this &lt; mn: mn = this mnpos = x[i] if lookformax: if (this &lt; mx-delta): if (mx&gt;abs(thresh)) and not isnan(mxpos): maxtab.append((mxpos, mx)) mn = this mnpos = x[i] lookformax = False else: if (this &gt; mn+delta): if (mn&lt;-abs(thresh)) and not isnan(mnpos): mintab.append((mnpos, mn)) mx = this mxpos = x[i] lookformax = True return array(maxtab), array(mintab) #Input Signal t=array(range(100)) series=0.3*sin(t)+0.7*cos(2*t)-0.5*sin(1.2*t) thresh=0.95 #Threshold value delta=0.0 # a=zeros(len(t)) # a[:]=thresh # maxtab, mintab = peakdet(series,delta,thresh,t) #Plotting output scatter(array(maxtab)[:,0], array(maxtab)[:,1], color='red') scatter(array(mintab)[:,0], array(mintab)[:,1], color='blue') xlim([0,t[-1]]) title('Peak Detector') grid(True) plot(t,a,color='green',linestyle='--',dashes=(5,3)) plot(t,-a,color='green',linestyle='--',dashes=(5,3)) annotate('Threshold',xy=(t[-1],thresh),fontsize=9) plot(t,series,'k') show() The problem with this program is that it is unable to detect some peaks even though they are above the threshold. This is the output I got: I saw other posts with peak detection problems but couldn't find any solution. Please help and suggest corrections.
accepted answer: http://stackoverflow.com/a/50757759
has title: Peak detection algorithm in Python
tagged with: python
has comment: http://stackoverflow.com/comment/88526479
tagged with: detect
has answer: http://stackoverflow.com/a/50758915
upvote count: 2
tagged with: detection
has comment: http://stackoverflow.com/comment/88522410

http://stackoverflow.com/q/50752972
has body: I wonder in flask 0.12, when can app_ctx_stack has more than 1 element and when can request_ctx_stack has more than 1 element? what is the purpose of RequestContext._implicit_app_ctx_stack?
duplicate of: http://stackoverflow.com/q/20036520
linked to: http://stackoverflow.com/q/20036520
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
downvote count: 1
type: Question
has title: About details of app_ctx_stack and request_ctx_stack
tagged with: flask

http://stackoverflow.com/comment/88499384
comment on: http://stackoverflow.com/a/50745559
type: Comment
score: 0
has text: this is giving : "[field1, 'en', field3]"
type: AnswerComment

http://stackoverflow.com/comment/88594259
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50792494
type: Comment
has text: @daniherrera thanks for the suggestion, I can see the importance in other applications, here though I'm not particularly interested in the users input and store it only for debugging purposes. The actual interest is on the sql query that this choice field informs.

http://stackoverflow.com/comment/88466949
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50705532
has text: @Sören I was under the impression that the "l2" penalty was the loss applied to the logits, implying [IRLS optimization](https://en.wikipedia.org/wiki/Iteratively_reweighted_least_squares), but upon further reading of the docs I see that this is not the case. I will update my note, but in any case, this is irrelevant to the question.
score: 0

pyspark
tags question: http://stackoverflow.com/q/50741418
tags question: http://stackoverflow.com/q/50802491
tags question: http://stackoverflow.com/q/50763533
tags question: http://stackoverflow.com/q/50844769
tags question: http://stackoverflow.com/q/50791210
tags question: http://stackoverflow.com/q/50772354
tags question: http://stackoverflow.com/q/50848977
tags question: http://stackoverflow.com/q/50722920
type: Tag
tags question: http://stackoverflow.com/q/50755127
tags question: http://stackoverflow.com/q/50793165
tags question: http://stackoverflow.com/q/50721831
tags question: http://stackoverflow.com/q/50762320
tags question: http://stackoverflow.com/q/50822294
tags question: http://stackoverflow.com/q/50811089
tags question: http://stackoverflow.com/q/50722909
tags question: http://stackoverflow.com/q/50703852
tags question: http://stackoverflow.com/q/50708155
tags question: http://stackoverflow.com/q/50828011
tags question: http://stackoverflow.com/q/50729345
tags question: http://stackoverflow.com/q/50838199
tags question: http://stackoverflow.com/q/50831511
tags question: http://stackoverflow.com/q/50805994
tags question: http://stackoverflow.com/q/50762559
tags question: http://stackoverflow.com/q/50816767
tags question: http://stackoverflow.com/q/50758115
tags question: http://stackoverflow.com/q/50847041
tags question: http://stackoverflow.com/q/50790837
tags question: http://stackoverflow.com/q/50838620
tag name: pyspark
tags question: http://stackoverflow.com/q/50806677
tags question: http://stackoverflow.com/q/50749596
tags question: http://stackoverflow.com/q/50843717
tags question: http://stackoverflow.com/q/50754517

http://stackoverflow.com/q/50706245
linked to: http://stackoverflow.com/q/18053500
has answer: http://stackoverflow.com/a/50706294
has body: I have the following python code table += '&lt;tr&gt;&lt;td&gt;{0}&lt;/td&gt;&lt;td&gt;{1}&lt;/td&gt;&lt;/tr&gt;'% format(str(key)), format(str(value)) TypeError: not all arguments converted during string formatting What could be the problem?
has title: Python not all arguments converted during string formatting
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50706289
accepted answer: http://stackoverflow.com/a/50706294
has answer: http://stackoverflow.com/a/50706289
tagged with: python-3.x
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/133917888
tagged with: python
score: 0

http://stackoverflow.com/a/50720848
has body: Like this, it will be saved in files numerated by number of row import csv with open('file.csv', 'r') as csv_file: rows = csv.reader(csv_file, skipinitialspace=True) for i, row in enumerate(rows): with open('file_{}.csv'.format(i), 'w') as write_file: writer = csv.writer(write_file) writer.writerow(row)
score: 0
answers question: http://stackoverflow.com/q/50720712
type: Answer

http://stackoverflow.com/q/50752773
has comment: http://stackoverflow.com/comment/88513850
has answer: http://stackoverflow.com/a/50753036
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88513666
has comment: http://stackoverflow.com/comment/88513902
upvote count: 3
downvote count: 3
has body: I'm trying to figure out why my code isn't working. Why are some of my logic gates, like OR, not giving me the correct output? Take the OR gate for example. When I run the code and pass in 1 as the value for A and B, the output is still False. I have tried tweaking it and it still gives me False as the output. Below is an example of what I did so far: aInput = int(input('Enter value for A: ')) bInput = int(input('Enter value for B: ')) #AND Gate if aInput == 1 and bInput == 1: ANDGate = "True" ANDGateNum = 1 else: ANDGate = "False" ANDGateNum = 0 print('AND Gate output is', ANDGate, 'or', ANDGateNum) #NAND Gate if aInput == 1 and bInput == 1: NANDGate = "False" NANDGateNum = 0 else: NANDGate = "True" NANDGateNum = 1 print('NAND Gate output is', NANDGate, 'or', NANDGateNum) #OR Gate if aInput == 1 and bInput == 1: ORGate = "True" ORGateNum = 1 if aInput == 1 and bInput == 0: ORGate = "True" ORGateNum = 1 if aInput == 0 and bInput == 1: ORGate = "True" ORGateNum = 1 else: ORGate = "False" ORGateNum = 0 print('OR Gate output is', ORGate, 'or', ORGateNum) #NOR Gate if aInput == 1 and bInput == 1: NORGate = "False" NORGateNum = 0 if aInput == 1 and bInput == 0: NORGate = "False" NORGateNum = 0 if aInput == 0 and bInput == 1: NORGate = "False" NORGateNum = 0 else: NORGate = "True" NORGateNum = 1 print('NOR Gate output is', NORGate, 'or', NORGateNum) #XNOR Gate if aInput == 1 and bInput == 1: XNORGate = "True" XNORGateNum = 1 if aInput == 1 and bInput == 0: XNORGate = "False" XNORGateNum = 0 if aInput == 0 and bInput == 1: XNORGate = "False" XNORGateNum = 0 else: XNORGate = "True" XNORGateNum = 1 print('XNOR Gate output is', XNORGate, 'or', XNORGateNum) #XOR Gate if aInput == 1 and bInput == 1: XORGate = "False" XORGateNum = 0 if aInput == 1 and bInput == 0: XORGate = "True" XORGateNum = 1 if aInput == 0 and bInput == 1: XORGate = "True" XORGateNum = 1 else: XORGate = "False" XORGateNum = 0 print('XOR Gate output is', XORGate, 'or', XORGateNum) #NOT Gate if aInput == 1: NO…
type: Question
has title: Python Logic Code: AND, NAND, OR, NOR, XOR, XNOR, & NOT simulation
possible better answer: http://stackoverflow.com/a/50753036
tagged with: boolean
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/9271712
tagged with: function
has comment: http://stackoverflow.com/comment/88513587
has comment: http://stackoverflow.com/comment/88513808
accepted answer: http://stackoverflow.com/a/50752976
tagged with: boolean-logic
favorite count: 0
has comment: http://stackoverflow.com/comment/88513770
tagged with: logic
has comment: http://stackoverflow.com/comment/88513553
tagged with: python
has comment: http://stackoverflow.com/comment/88513712
has answer: http://stackoverflow.com/a/50752976

http://stackoverflow.com/a/75875854
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/138375778
type: Answer
answers question: http://stackoverflow.com/q/50846431
has body: Here is a simple solution of how to do it without saving the json to a file: import yaml import json with open("your_yaml_file.yaml") as f: yaml_obj = yaml.safe_load(f) json_str = json.dumps(yaml_obj) json_dict = json.loads(json_str) print(json_dict)
downvote count: 0

http://stackoverflow.com/a/54966746
type: Answer
score: 0
has body: Apparently I had this same issue on my Windows 7 Machine. The solution for me was to go to C:\User\"Username"\AppData and then Rightclick > properties on the "Local" folder and and "allow permissions" for everyone.
answers question: http://stackoverflow.com/q/50833570

http://stackoverflow.com/comment/88709641
has text: @Boooooo I've updated my answer. For the Office object model documentation, there is a list of objects on the left side of the page. Each object can be expanded (by clicking next to it) to reveal its' properties and methods.
comment on: http://stackoverflow.com/q/50851905
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88713501
has text: I’m not going to troobleshoot your whole script. Look for solutions on the web, read the doc and examples, look for questions here relevant for you, and ask a question if no one ever asked for it (but 95% of the time you don’t have to open a new question).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50786313

http://stackoverflow.com/q/50737787
possible better answer: http://stackoverflow.com/a/50745381
has answer: http://stackoverflow.com/a/50745241
tagged with: numpy
tagged with: python-2.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88494640
accepted answer: http://stackoverflow.com/a/50745241
type: Question
has title: Import file in Python (numpy) as contiguous memory array
tagged with: python
has comment: http://stackoverflow.com/comment/88495174
has comment: http://stackoverflow.com/comment/88485457
score: 0
has answer: http://stackoverflow.com/a/50745381
has comment: http://stackoverflow.com/comment/88497737
answer count: 2
has body: I want to import data from a text file, and read it in as a contiguous memory array. This is the data, with every respondent separated by a return: ['vrouw', 43, '2', 'onbeantwoord', '2', '2', 'onbeantwoord', ''] ['vrouw', 34, '2', 'onbeantwoord', '2', '2', 'onbeantwoord', ''] ['vrouw', 32, '2', 'onbeantwoord', '2', '2', 'onbeantwoord', ''] ['vrouw', 32, '2', 'onbeantwoord', '2', '2', 'onbeantwoord', ''] ['vrouw', 43, '3', 'sport', '2', '2', 'onbeantwoord', ''] ['vrouw', 32, '2', 'onbeantwoord', '2', '2', 'onbeantwoord', ''] ['vrouw', 43, '2', 'onbeantwoord', '3', '3', 'collega', 'nee'] I tried to use the following code to import the data from the text file: vragenlijst_data= np.genfromtxt('antwoorden.txt', delimiter=',', dtype=None, names=('geslacht', 'leeftijd', 'stelling1', 'doorvraag1', 'stelling2', 'stelling3', 'doorvraag3', 'opmerking')) However, this way I can't use the np.mean (from the numpy library) in a vectorised way, because I have no contiguous memory array. Does anyone know a way to read the data so that I have a contiguous memory array (preferrably with numpy)?
has comment: http://stackoverflow.com/comment/88494516
has comment: http://stackoverflow.com/comment/88484786

http://stackoverflow.com/comment/88540863
comment on: http://stackoverflow.com/a/50765334
type: Comment
has text: Update your post with your code as it is now so I can test it.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50853408
type: Answer
accepted answer of: http://stackoverflow.com/q/50852792
has comment: http://stackoverflow.com/comment/88709596
answers question: http://stackoverflow.com/q/50852792
has comment: http://stackoverflow.com/comment/88710170
score: 1
has comment: http://stackoverflow.com/comment/88711407
upvote count: 1
has body: If you have your labels before prediction you want to do supervised learning and you don't use the good algorithm, please take a look at some models like : Logistic regression random forest classifier SVM Classifier and others
has comment: http://stackoverflow.com/comment/88709804
has comment: http://stackoverflow.com/comment/88709632
has comment: http://stackoverflow.com/comment/88711955
has comment: http://stackoverflow.com/comment/88710530
has comment: http://stackoverflow.com/comment/88709689
has comment: http://stackoverflow.com/comment/88711320
has comment: http://stackoverflow.com/comment/88716125
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88709814
has comment: http://stackoverflow.com/comment/88711749
has comment: http://stackoverflow.com/comment/88711849

http://stackoverflow.com/comment/88604471
has text: You have the code, you don't need to guess. :) I guess it is something like `int __pyx_v_neighbor[3]` because an `int*` would normally be a perfect l-value.
comment on: http://stackoverflow.com/q/50798149
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50822183
linked to: http://stackoverflow.com/q/39924482
answer count: 1
linked to: http://stackoverflow.com/q/4355524
linked to: http://stackoverflow.com/q/23329663
linked to: http://stackoverflow.com/q/48913932
accepted answer: http://stackoverflow.com/a/52215208
favorite count: 0
linked to: http://stackoverflow.com/q/46043582
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/50705208
has answer: http://stackoverflow.com/a/52215208
tagged with: c++
linked to: http://stackoverflow.com/q/47127575
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/40063080
has body: Following this question where I was trying to use a C++ DLL with Cython, with a tutorial fit to my case that never worked, I decided to use ctypes. I now successfully call the function that interests me in my DLL using ctypes thanks to heavy SO browsing. I am now faced with the problem of using the results that is an array of struct in Python. This C function is as follows: void myfun( double a, //...more double parameters int max_iter, int * nb_iter, myStruct * res_arr, bool * ok ); with myStruct defined as follows: typedef struct { double dat; int k; int m; // ... more int double b; double v; //...more double } myStruct; I call this function through the following Python code: import ctypes lib = ctypes.CDLL('PATH_TO_DLL\\lib.dll') myFunPy = getattr(lib,"?myFun@@YANNNNN_BUNCH_OF_Ns_NNNHPEAHPEAUmyStruct@@PEA_N@Z") # name found through dumpbin.exe (due to C++) class myStruct(ctypes.Structure): _fields_ = [("k", ctypes.c_int), ("m", ctypes.c_int), #...more int parameters ("b", ctypes.c_double), ("v", ctypes.c_double) #...more double parameters ] myFunPy.argtypes = [ctypes.c_double, // ... more double parameters ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(myStruct), ctypes.POINTER(ctypes.c_bool)] myFunPy.restype = ctypes.c_void_p max_iter = 10000 a = ctypes.c_double(0.1) // ... more double parameters definitions nb_iter = ctypes.c_int(0) # value doesn't matter, it is initialized in myFun ok = ctypes.c_bool(True) res_arr = (myStruct * max_iter)() myFunPy(a, ..., max_iter, ctypes.byref(nb_iter), res_arr, ctypes.byref(ok)) Now myFun modifies res_arr which is an array of struct as can be seen from the above code. It is exactly &lt;__main__.myStruct_Array_10000 at 0x97966c8&gt;) after the code shown above, but I cannot understand how to convert it to a NumPy array for future use efficiently. Sure, I could do for loops with stuff like for field, _ in struct._fields_ as shown here, but that is not the point since I use the DLL to make my computations faster (I …
type: Question
tagged with: numpy
tagged with: ctypes
linked to: http://stackoverflow.com/q/39328205
linked to: http://stackoverflow.com/q/3789372
downvote count: 0
tagged with: http://stackoverflow.com/tag/c
has title: Efficient conversion from C array of struct to NumPy array with ctypes

http://stackoverflow.com/q/50704358
tagged with: pandas
tagged with: python
has title: Pandas Replace is giving me a strange error
accepted answer: http://stackoverflow.com/a/50704474
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
has body: Pandas is giving a weird output when using a dictionary to replace values within a dataframe: import pandas as pd df = pd.read_csv('data.csv') print(df) Course English 21st Century Maths in the Golden Age of History Science is cool Mapped_Items = ['Math', 'English', 'Science', 'History'] pat = '|'.join(r"\b{}\b".format(x) for x in Mapped_Items) df['Interest'] = df['Course].str.findall('('+ pat + ')').str.join(', ') mapped_dict = {'English' : 'Eng', 'Science' : 'Sci', 'Math' : 'Mat', 'History' : 'Hist'} df['Interest'] = df1['Interest'].replace(mapped_dict, inplace=False) What I get: print(df) df Course Interest English 21st Century Engg Maths in the Golden Age of History MatttHistt Science is cool Scii What I'm after is something close to the following : Course Interests English 21st Century Eng Maths in the Golden Age of History Mat, Hist Science is cool Sci
tagged with: dataframe
has answer: http://stackoverflow.com/a/50704474
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50845660
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/50845725
favorite count: 0
upvote count: 2
type: UnansweredQuestion
score: 2
has title: create a Pandas DataFrame from a series of list
type: Question
has body: I have a Pandas series of list 0 ['2018-3-13', '16:00'] 1 ['2018-3-13', '16:01'] 2 ['2018-3-13', '16:02'] 3 ['2018-3-13', '16:03'] . . . And I want to create DataFrame as 0 '2018-3-13' '16:00' 1 '2018-3-13' '16:01' 2 '2018-3-13' '16:02' 3 '2018-3-13' '16:03' ... So anyone could provide a innovative idea? Quite thanks
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50845822

http://stackoverflow.com/q/50759158
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50780954
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88544541
tagged with: python
has title: Using Bokeh for a dropdown menu which would create different charts
has comment: http://stackoverflow.com/comment/88526025
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88550507
tagged with: bokeh
type: Question
has body: I am trying to create a dropdown interface for my work. My dataset looks like this, it is a random dataset Now I would like 2 dropdowns say CNN and BBC here. After selecting a channel from dropdown, I would like to select a Topic which would produce a bar chart according to it's value. I am trying to access just one value initially, but it gives me a blank graph. from bokeh.plotting import figure from bokeh.io import output_notebook,show,output_file p=figure() import csv data = [row for row in csv.reader(open('C:/Users/Aishwarya/Documents/books/books_q4/crowd_computing/Bokeh-Python-Visualization-master/interactive/data/data.csv', 'r',encoding="utf8"))] p.vbar(x=data[1][2], width=0.5, bottom=0, top=data[1][1], color="firebrick") #output_notebook() output_file('1.html') show(p)
tagged with: visualization
upvote count: 1

http://stackoverflow.com/a/50818488
has comment: http://stackoverflow.com/comment/88642761
has comment: http://stackoverflow.com/comment/88642365
type: AcceptedAnswer
downvote count: 0
has body: Do not attempt to sort twice. Instead, zip both lists together before sorting and only sort with regard to the first item. import re list = ['A103', 'A101', 'C101', 'B101'] rad = ['£', '$', '€', '@'] convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key[0])] # only consider first item ----^ list_sorted = sorted(zip(list, rad), key=alphanum_key) # zip both lists ---^ print(list_sorted) # [('A101', '$'), ('A103', '£'), ('B101', '@'), ('C101', '€')] This can easily be generalized to more than two lists with unpacking. list = ['A103', 'A101', 'B101'] rad = ['£', '$', '@'] more = [1, 2, 3] lists = list, rad, more ... list_sorted = sorted(zip(*lists), key=alphanum_key) print(list_sorted) # [('A101', '$', 2), ('A103', '£', 1), ('B101', '@', 3)]
answers question: http://stackoverflow.com/q/50818373
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50818373

http://stackoverflow.com/q/50803775
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50803798
has comment: http://stackoverflow.com/comment/88613570
has comment: http://stackoverflow.com/comment/88613531
has title: Alter Datetime format in Python
upvote count: 0
accepted answer: http://stackoverflow.com/a/50803798
has comment: http://stackoverflow.com/comment/88613519
has comment: http://stackoverflow.com/comment/88613743
type: AnsweredQuestion
tagged with: datetime
tagged with: python
favorite count: 0
score: -1
type: Question
has body: I'm trying to modify date format in date column of a python dataframe 'df' from 06/01/2018 to 06-01-2018. I tried the following but did not work. df['date'].str.replace('/','-') Any help is really appreciated.

http://stackoverflow.com/a/64646639
has body: class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status="published")
type: Answer
has comment: http://stackoverflow.com/comment/114306146
answers question: http://stackoverflow.com/q/50836869
score: 0

http://stackoverflow.com/comment/88554970
score: 1
type: QuestionComment
has text: Possible duplicate of [How to decode a QR-code image in (preferably pure) Python?](https://stackoverflow.com/questions/27233351/how-to-decode-a-qr-code-image-in-preferably-pure-python)
type: Comment
comment on: http://stackoverflow.com/q/50771552

http://stackoverflow.com/a/50767865
downvote count: 0
has body: Why not just read it line by line? i = 8 with open('foo.txt', 'r') as myfile: for line in myfile: print line[:i+1]
has comment: http://stackoverflow.com/comment/88543524
type: Answer
has comment: http://stackoverflow.com/comment/88544003
upvote count: 1
answers question: http://stackoverflow.com/q/50767674
score: 1
has comment: http://stackoverflow.com/comment/88544218

http://stackoverflow.com/q/50846570
tagged with: python
has comment: http://stackoverflow.com/comment/88712097
has answer: http://stackoverflow.com/a/50849439
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50847781
has comment: http://stackoverflow.com/comment/88698053
has title: Write a python script to find out the XPath from the HTML based on any class
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/88701718
has comment: http://stackoverflow.com/comment/88698486
has body: In Python, I want the user to enter a URL in the console prompt (take input and store it in some variable), For example, if the webpage contains this HTML: First heading Some text Some text Then the CSV should contain rows for each and every class that's in the HTML of the webpage (since classes can appear more than once, so we could have multiple rows for any given class). Now, I want to generate XPath for all the classes present on the page. What i have written so far is : import urllib2 from bs4 import BeautifulSoup result = {} user_url_list = raw_input("Please enter your urls separated by spaces : \n") url_list = map(str, user_url_list.split()) for url in url_list: try: page = urllib2.urlopen(url) soup = BeautifulSoup(page, 'html.parser') user_class_list = raw_input("Please enter the classes to parse for " + url + " separated by spaces : \n") class_list = map(str, user_class_list.split()) for find_class in class_list: try: name_box = soup.find(attrs={'class': find_class}) print(xpath_soup(name_box)) break except: print("There was some error getting the xpath of class : " + find_class + " for url : " + url + "\n..trying next class now \n") continue except: print(url + " is not valid, please enter correct full url \n") continue print(result)
has comment: http://stackoverflow.com/comment/88697496
type: Question
has comment: http://stackoverflow.com/comment/88697604
has comment: http://stackoverflow.com/comment/88698191
has comment: http://stackoverflow.com/comment/88697372
answer count: 2
tagged with: scripting
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88698313
linked to: http://stackoverflow.com/q/29890301
type: UnansweredQuestion

http://stackoverflow.com/comment/88610977
has text: @WillemVanOnsem players in Quiz is a list, my question is how do I write the exclude statetement to check that one user is not on that list.
comment on: http://stackoverflow.com/q/50802451
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88691131
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50843398
type: Comment
has text: Welcome, please mark this as correct if it was helpful.

http://stackoverflow.com/q/50802188
type: AnsweredQuestion
has title: Status post. Django
has comment: http://stackoverflow.com/comment/88610352
type: Question
upvote count: 2
score: 0
downvote count: 2
answer count: 1
has body: I created an application where users can add posts. I would like to add the post status. Post after adding has the status "active." After 30 days, changes the status to "inactive" How can I do it?
favorite count: 0
has comment: http://stackoverflow.com/comment/88610372
has answer: http://stackoverflow.com/a/50802265
tagged with: django
accepted answer: http://stackoverflow.com/a/50802265
tagged with: python

http://stackoverflow.com/q/50717791
type: Question
type: AnsweredQuestion
tagged with: analytics
accepted answer: http://stackoverflow.com/a/50718085
possible better answer: http://stackoverflow.com/a/50720555
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50720555
has body: I am new to analytics,python and machine learning and I am working on Time forecasting. Using the following code I am getting the value for train and test data but the graph is plotted blank. import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.tsa.api as ExponentialSmoothing #Importing data df = pd.read_csv('international-airline-passengers - Copy.csv') #Printing head print(df.head()) #Printing tail print(df.tail()) df = pd.read_csv('international-airline-passengers - Copy.csv', nrows = 11856) #Creating train and test set #Index 10392 marks the end of October 2013 train=df[0:20] test=df[20:] #Aggregating the dataset at daily level df.Timestamp = pd.to_datetime(df.Month,format='%m/%d/%Y %H:%M') df.index = df.Timestamp df = df.resample('D').mean() train.Timestamp = pd.to_datetime(train.Month,format='%m/%d/%Y %H:%M') print('1') print(train.Timestamp) train.index = train.Timestamp train = train.resample('D').mean() test.Timestamp = pd.to_datetime(test.Month,format='%m/%d/%Y %H:%M') test.index = test.Timestamp test = test.resample('D').mean() train.Count.plot(figsize=(15,8), title= 'Result', fontsize=14) test.Count.plot(figsize=(15,8), title= 'Result', fontsize=14) plt.show() Not able to understand the reason for getting the graph blank even when train and test data is having value. Thanks in advance.
tagged with: python
has title: Matplotlib plots turn out blank even having values
has answer: http://stackoverflow.com/a/50718085
tagged with: machine-learning

http://stackoverflow.com/comment/127198796
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50720797
has text: As you only considered the nodes in G, and check if they are in H, it seems not to be correct as you dont consider the nodes in H not available in G. So the two first lines of the function needs to be def get_jaccard_coefficients(G, H): allnodes=list(set(list(G)+list(H))) for v in allnodes: if (v in H) and (v in G):

http://stackoverflow.com/comment/111415603
type: Comment
score: 0
has text: I have the same issue. It happens to me when I use IDLE 3.8. But it only happens when I use the IDLE on my external monitor. When using it on my laptop screen, the breakage does not occur. I am pretty sure this is GUI issue, though I don't have a good answer for this.
type: QuestionComment
comment on: http://stackoverflow.com/q/50789470

http://stackoverflow.com/comment/88593310
has text: Because `deque` takes an iterable (you can pass in a tuple, list, etc) https://docs.python.org/2/library/collections.html#collections.deque
type: Comment
score: 5
comment on: http://stackoverflow.com/q/50793648
type: QuestionComment

http://stackoverflow.com/a/50819363
has comment: http://stackoverflow.com/comment/88646409
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88644292
has comment: http://stackoverflow.com/comment/88645990
type: Answer
accepted answer of: http://stackoverflow.com/q/50818809
has comment: http://stackoverflow.com/comment/88646363
answers question: http://stackoverflow.com/q/50818809
has body: Update: From your updated question I can see that you need to put weight in column1 of page2. self.page2.columnconfigure(0, weight=1) Replace: class UICreation(): def __init__(self): print ("I m in __init__") self.nb=ttk.Notebook(frame_main) self.page1=ttk.Frame(self.nb) self.page2=ttk.Frame(self.nb) With this: class UICreation(): def __init__(self): print ("I m in __init__") self.nb=ttk.Notebook(frame_main) self.page1=ttk.Frame(self.nb) self.page2=ttk.Frame(self.nb) self.page2.columnconfigure(0, weight=1) I have updated your code to reflect a cleaner example that follows PEP8 better. Let me know if you have any questions: import tkinter as tk import tkinter.ttk as ttk class UICreation(): def __init__(self, master): self.nb=ttk.Notebook(master) self.page1=ttk.Frame(self.nb) self.page2=ttk.Frame(self.nb) self.page2.columnconfigure(0, weight=1) self.check_box_election=[] self.name_of_variable=[] self.key_name=[] self.selected_checkbox=[] self.dict={} self.frame_main = tk.Frame(root) self.frame_main.grid(sticky='news') self.canvas=tk.Canvas() self.list_key = ["1", "2"] def tabcreation(self): self.nb.add(self.page1,text="Select") canvas = tk.Canvas(self.page1) canvas.grid(row=0, column=0, sticky="news") vsb = tk.Scrollbar(self.page1, orient="vertical", command=canvas.yview) vsb.grid(row=0, column=1, sticky='ns') canvas.configure(yscrollcommand=vsb.set) canvas.config(scrollregion=canvas.bbox("all")) f = tk.Frame(canvas) canvas.create_window((0, 0), window=f, anchor="n") self.nb.grid(sticky="nw") list_number = len(self.list_key) for value in range(0,list_number, 1): name_of_variable= "checkBox" + str(value) self.check_box_election.append("var"+str(value)) self.check_box_election[value] = tk.IntVar() name_of_variable = tk.Checkbutton(f, text=str(self.list_key[value]),variable=self.check_box_election[value]) name_of_variable.grid(sticky="nw") name_of_variable.cget("text") self.key_name.append(name_of_variable.cget("text")) canvas.update() canvas.config(scrollregion=canvas.b…

http://stackoverflow.com/comment/88562189
comment on: http://stackoverflow.com/a/50776154
type: Comment
has text: It doesnt look at X at all (or rather it only cares about the .shape[0]), see the following link: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html#sklearn.model_selection.StratifiedShuffleSplit.split
score: 0
type: AnswerComment

http://stackoverflow.com/a/50754464
has comment: http://stackoverflow.com/comment/88519601
score: 0
type: Answer
has body: Your expected output seems to be incorrect. That aside, we can use base R's difftime: transform( df, duration = difftime( strptime(end.time, format = "%H:%M:%S"), strptime(start.time, format = "%H:%M:%S"), units = "mins")) # start.time end.time duration #0 08:30:00 17:30:00 540 mins #1 11:00:00 17:30:00 390 mins #2 08:00:00 21:30:00 810 mins #3 19:30:00 22:00:00 150 mins #4 19:00:00 00:00:00 -1140 mins #5 08:30:00 15:30:00 420 mins or as a difftime vector with(df, difftime( strptime(end.time, format = "%H:%M:%S"), strptime(start.time, format = "%H:%M:%S"), units = "mins")) #Time differences in mins #[1] 540 390 810 150 -1140 420 Sample data df &lt;- read.table(text = " 'start time' 'end time' 0 08:30:00 17:30:00 1 11:00:00 17:30:00 2 08:00:00 21:30:00 3 19:30:00 22:00:00 4 19:00:00 00:00:00 5 08:30:00 15:30:00", header = T, row.names = 1)
answers question: http://stackoverflow.com/q/50754122
has comment: http://stackoverflow.com/comment/88519822

http://stackoverflow.com/q/50784201
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88581712
has body: I have a dictionary that looks like this. CV Scores 0 2 0.966667 1 3 0.979984 2 4 0.979701 3 5 0.980000 4 6 0.979938 5 7 0.973639 6 8 0.973214 7 9 0.986420 8 10 0.973333 9 11 0.974242 10 12 0.973611 11 13 0.974359 12 14 0.974206 I want to extract the CV value for the largest Score value. So, in this case, the largest Score value is 0.986 and I want to print the CV value of 9. Please help.
tagged with: python
has answer: http://stackoverflow.com/a/50784342
has title: Get key from value in Python dictionary
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/50784445
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/268272
has comment: http://stackoverflow.com/comment/88581696
has comment: http://stackoverflow.com/comment/88575189
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/88574866
has comment: http://stackoverflow.com/comment/88581633
duplicate of: http://stackoverflow.com/q/8023306
type: Question
has answer: http://stackoverflow.com/a/50784445
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/8023306
accepted answer: http://stackoverflow.com/a/50784342
has comment: http://stackoverflow.com/comment/88581729

http://stackoverflow.com/comment/88547856
has text: Calling a function from within a class works exactly as well, and in exactly the same way, as calling a function from anywhere else. But you are never actually calling the functions; that can only happen if `self.sptorun == 'items'`, but you are creating both spinners with `'item'` instead.
score: 0
comment on: http://stackoverflow.com/q/50770092
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88588590
comment on: http://stackoverflow.com/a/50790898
has text: Did you run your cmd line from step 3 in the same dir as your files?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50788144
duplicate of: http://stackoverflow.com/q/18582178
has body: l = [0,1,2,0,3] I want to find l's smallest number and its index, which should give (0,0),(0,3) What I have done is def find_smallest(xy): return (np.min(xy), xy.index(min(xy))) find_smallest([0,1,2,0,3]) which gives (0,0)
tagged with: python
has title: Find smallest number and its index
accepted answer: http://stackoverflow.com/a/50788270
tagged with: indexing
type: AnsweredQuestion
tagged with: list
score: 0
type: Question
tagged with: min
possible better answer: http://stackoverflow.com/a/50788207
has answer: http://stackoverflow.com/a/50788207
has answer: http://stackoverflow.com/a/50788270
answer count: 3
has answer: http://stackoverflow.com/a/50788209
has comment: http://stackoverflow.com/comment/88582643
linked to: http://stackoverflow.com/q/18582178

http://stackoverflow.com/a/50780066
type: AcceptedAnswer
score: 1
answers question: http://stackoverflow.com/q/50779536
type: Answer
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50779536
has body: The same question about Euclidean distance was asked here. In your case, that would look like this: def closest_node(node, nodes): nodes = np.asarray(nodes) dist = np.sum((nodes - node)**2, axis=1) return np.argmin(dist) mouse_xy = (20, 20) closest_centroid = centers[closest_node(mouse_xy, centers)] print(closest_centroid) [30, 30]

http://stackoverflow.com/a/50849413
score: 0
has comment: http://stackoverflow.com/comment/88701738
answers question: http://stackoverflow.com/q/50849097
has comment: http://stackoverflow.com/comment/88701753
type: Answer
has comment: http://stackoverflow.com/comment/88701724
has body: I am not able to reproduce but u can try out import pandas as pd data = pd.read_csv('dataset.csv') CLASS = data['CLASS'] DURATION = data['DURATION'] GENDER = data['GENDER'] # fill the nan value DURATION.fillna(0,inplace=True) # using astype convert the value to int then compare CLASS[DURATION].astype(int)&gt;0

http://stackoverflow.com/comment/88579275
type: AnswerComment
has text: No, I'd just added to make it more clear. Any way everyone is smart in this world. I removed 2 images. I just only kept 1 image. Thanks.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50785929

http://stackoverflow.com/comment/88718424
score: 0
comment on: http://stackoverflow.com/a/50852741
has text: Thanks! This is indeed what I meant
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88549502
type: Comment
comment on: http://stackoverflow.com/a/50766961
score: 0
has text: The expressions are quite large so I don't think there's any way around the expense of printing them.
type: AnswerComment

http://stackoverflow.com/comment/88614606
score: 0
type: Comment
type: QuestionComment
has text: Ah, it's actually happy with `dest = dest or new_obj(fname)`
comment on: http://stackoverflow.com/q/50804259

http://stackoverflow.com/a/50779285
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50779264
upvote count: 1
score: 1
has body: Well, you aren't actually setting it to False in your else. You are doing an equality check of the variable continuar against False: == Checks equality: continuar==False = Sets the value: continuar=False

http://stackoverflow.com/comment/88490969
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50741194
has text: it runs on `6379` but isn't that just for the backend not the port to connect to

nlp
tags question: http://stackoverflow.com/q/50802067
tags question: http://stackoverflow.com/q/50720589
tags question: http://stackoverflow.com/q/50800803
tags question: http://stackoverflow.com/q/50826625
tags question: http://stackoverflow.com/q/50723841
tags question: http://stackoverflow.com/q/50723752
tags question: http://stackoverflow.com/q/50818999
tags question: http://stackoverflow.com/q/50776350
tags question: http://stackoverflow.com/q/50801553
tags question: http://stackoverflow.com/q/50727776
tags question: http://stackoverflow.com/q/50814296
tags question: http://stackoverflow.com/q/50828314
tags question: http://stackoverflow.com/q/50750102
tags question: http://stackoverflow.com/q/50776019
tags question: http://stackoverflow.com/q/50724560
tags question: http://stackoverflow.com/q/50808889
tags question: http://stackoverflow.com/q/50736830
tags question: http://stackoverflow.com/q/50790504
tag name: nlp
type: Tag
tags question: http://stackoverflow.com/q/50798691
tags question: http://stackoverflow.com/q/50752533

http://stackoverflow.com/q/50746266
type: Question
has answer: http://stackoverflow.com/a/50746376
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88500248
has answer: http://stackoverflow.com/a/50746370
has title: What is a property attribute and how do I use it?
has comment: http://stackoverflow.com/comment/88506221
possible better answer: http://stackoverflow.com/a/50746376
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88500296
accepted answer: http://stackoverflow.com/a/50746370
has comment: http://stackoverflow.com/comment/88500300
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has body: I created a class that takes 2 coordinates and returns the slope and distance of the respective coordinates. It works fine but, apparently, what I did was wrong and was supposed to give an error. My code: class Line: def __init__(self, coord1, coord2): self.coord1 = coord1 self.coord2 = coord2 def distance(self): return math.sqrt( ((self.coord1[0]-self.coord2[0])**2)+((self.coord1[1]-self.coord2[1])**2) ) def slope(self): c = self.coord2[0]-self.coord1[0] d = self.coord2[1]-self.coord1[1] if d==0: return "zero" elif c==0: return "Infinity" else: return d/c line1=Line((8,3),(0,-4)) print(line1.distance()) print(line1.slope()) RESTART: C:\Users.....\Classes.py 10.63014581273465 **The result is right...?** 0.875 I get the right output, but this is how I am supposed to do it: &gt;&gt;&gt; line1=Line((8,3),(0,-4)) &gt;&gt;&gt; line1.distance() Traceback (most recent call last):File "&lt;stdin&gt;", line 1, in &lt;module&gt;TypeError: 'float' object is not callable **This is like mine but error?** &gt;&gt;&gt; line1.slope() Traceback (most recent call last):File "&lt;stdin&gt;", line 1, in &lt;module&gt;TypeError: 'float' object is not callable **Just like mine but error?** &gt;&gt;&gt; line1.distance 10.63 &gt;&gt;&gt; line1.slope 0.875 What is the difference and is mine wrong?
linked to: http://stackoverflow.com/q/6304040

http://stackoverflow.com/q/50820010
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89154847
tagged with: matplotlib
has body: from PIL import Image import numpy as np import matplotlib.pyplot as plt i = Image.open('images/dot.png') iar = np.asarray(i) plt.imshow(iar) plt.show() I have the image called dot.png in the same directory but it is not working. When I start the program no errors detected. It runs fine. But the matplotlib tool not working. The window look like this:
type: Question
downvote count: 0
has title: matplotlib does not show the image
score: 1
tagged with: matplotlib-basemap
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50754519
score: 0
has comment: http://stackoverflow.com/comment/88516934
duplicate of: http://stackoverflow.com/q/35491274
has comment: http://stackoverflow.com/comment/88516954
has body: so I have series lists in python variable print(newlist) 0 [0.0, 0.0, 0.0, 0.0] 1 [0.0, 0.0, 0.8784313525490196, 0.5686274509803] 2 [0.0, 0.0, 0.8784313725190196, 0.5686274509803] 3 [0.0, 0.0, 0.0, 0.0] 4 [1.0, 1.0, 1.0, 1.0] 5 [0.0, 0.0, 0.0, 0.0] 6 [0.0, 0.0, 0.8784313724490196, 0.2117647058823] 7 [1.0, 1.0, 1.0, 1.0] 8 [0.0, 0.0, 0.0, 0.0] 9 [0.0, 0.0, 0.6274507803921569, 0.8705882352941] 10 [0.0, 0.0, 0.6274509813921569, 0.8705882352941] Now I want each number from the list to be in one column like, I would like the output to look like this, col1 col2 col3 col4 0 0.0 0.0 0.0 0.0 1 0.0 0.0 0.8784313525.. 0.5686274509803 2 0.0 0.0 0.8784313725.. 0.5686274509803 3 4 5 similarly to all the rows. How can I do that using pandas. please help, Thank you.
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88516864
linked to: http://stackoverflow.com/q/35491274
answer count: 0
type: UnansweredQuestion
has title: python list to columns
has comment: http://stackoverflow.com/comment/88517458
type: Question

http://stackoverflow.com/q/50797827
tagged with: intersection
answer count: 2
upvote count: 1
has body: I have a list of CSV's , which I am currently reading in a dataframe in Pandas. I need to find the common elements in one of columns of a dataframe. df1 = pd.read_csv("example.csv") df2 = pd.read_csv("example1.csv") val = np.intersect1d(example[' column'], example1[' column']) How can I do it for multiple files.
favorite count: 0
has title: Common elements in a dataframe column
has comment: http://stackoverflow.com/comment/88602153
has answer: http://stackoverflow.com/a/50798118
score: 0
has answer: http://stackoverflow.com/a/50798003
accepted answer: http://stackoverflow.com/a/50798003
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88601732
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50798118

google-cloud-sql
tags question: http://stackoverflow.com/q/50785764
tag name: google-cloud-sql
tags question: http://stackoverflow.com/q/50806046
tags question: http://stackoverflow.com/q/50701736
type: Tag

http://stackoverflow.com/comment/88708717
has text: @RoadRunner this is clearly a duplicate. Thanks for the link, next time can you vote to close?
comment on: http://stackoverflow.com/q/50852957
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50784067
accepted answer: http://stackoverflow.com/a/50784846
tagged with: anaconda
answer count: 3
downvote count: 0
tagged with: keras
favorite count: 0
has title: Anaconda Keras Installation issue
has answer: http://stackoverflow.com/a/50784846
tagged with: python
has body: I am trying to install keras using my conda environment. I have been instructed to install the keras with Tensorflow backend using the following command: install -c hesi_m keras But the problem is it downloads some packages and then errors outs follows: Downloading and Extracting Packages: keras_applications-1 | 45 KB | ############### | 100% keras-2.2.0 | 444 KB | ############### | 100% keras-preprocessing- | 43 KB | ############### | 100% Preparing transaction: done Verifying transaction: failed CondaVerificationError: The package for keras-preprocessing located at /home/usama/anaconda3/pkgs/keras-preprocessing-1.0.1-py36_0 appears to be corrupted. The path 'lib\python3.6\site-packages\Keras_Preprocessing-1.0.1-py3.6.egg-info\PKG-INFO' specified in the package manifest cannot be found. CondaVerificationError: The package for keras-preprocessing located at /home/usama/anaconda3/pkgs/keras-preprocessing-1.0.1-py36_0 appears to be corrupted. The path 'lib\python3.6\site-packages\Keras_Preprocessing-1.0.1-py3.6.egg-info\SOURCES.txt' specified in the package manifest cannot be found. Remaining list of error is skipped. I have tried to clean the cache using: conda clean --all But the issue is persisting. Any ideas?
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/55476586
possible better answer: http://stackoverflow.com/a/50838322
upvote count: 1
has answer: http://stackoverflow.com/a/50838322
type: Question

http://stackoverflow.com/q/50752137
has answer: http://stackoverflow.com/a/50752271
tagged with: python
tagged with: request
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50752272
accepted answer: http://stackoverflow.com/a/50752272
has title: Flask request variable not recognized
downvote count: 1
type: Question
has body: So I am creating a function for a route in Flask to handle a POST request but Flask isn't recognizing my request variable for some reason. I have this Python code: @app.route("/decide", methods=["GET", "POST"]) def decide(): if request.method == "POST": # Ensure user has permission to modify this request request_id = request.form.get("job_id") if not request_id: return redirect("/") request = Requests.query.get(request_id) if not request: return redirect("/") job = Jobs.query.get(request.job_id) if not job: return redirect("/") job_creator = job.creator_id if job_creator != session["user_id"]: return redirect("/") if request.form.get("submit") == "accept": print("accept") if request.form.get("submit") == "reject": print("reject") return redirect("/") with this HTML code: {% extends "dad.html" %} {% if job.creator_id == session.user_id %} {% block head %} {{job.title}} {% endblock %} {% block body %} {{job.title}} {% if total > 0 %} There {% if total != 1%}are{% else %}is{% endif %} {{total}} request{% if total != 1%}s{% endif %} for this job {% else %} There are no requests for this job currently {% endif %} {% for requ in requests %} {{requ.requester_fname}} {{requ.requester_lname}} Accept Reject {% endfor %} {% endblock %} {% endif %} and then I get an error: UnboundLocalError: local variable 'request' referenced before assignment at the line: if request.method == "POST": All of my other routes like this work, it just doesn't recognize "request" here for whatever reason. I also imported the request object from flask, so that's not the issue. Thanks for any help that you can give!
tagged with: routes
tagged with: post
score: 0
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/50752271
tagged with: flask
favorite count: 0

cors
type: Tag
tag name: cors
tags question: http://stackoverflow.com/q/50822478

http://stackoverflow.com/q/50837180
has comment: http://stackoverflow.com/comment/88678514
type: AnsweredQuestion
has title: Pandas Dataframe to list of dictionaries of specific format
type: Question
has comment: http://stackoverflow.com/comment/88678273
has answer: http://stackoverflow.com/a/50839277
tagged with: dataframe
tagged with: python-2.7
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/88678420
possible better answer: http://stackoverflow.com/a/50840824
has body: I have a dataframe with the following columns: serial_no, timestamp, parameter1, parameter2, parameter3,... this data frame can have multiple serial_no. so I require it in a json with the following format: [ { 'serial_no':'a001', 'readings':[ { 'name':'parameter1', 'datapoints':[ ('2018-01-01 00:00:00',5),('2018-01-01 00:01:00',35),.. ] },{'name':'parameter2',..},.. ] },{'serial_no':'a002',..},.. ] sample table data: |-----------|------------------------------------------|---------------------------| | serial_no | timestamp | parameter1 | parameter2 | parameter3 | |-----------|------------------------------------------|---------------------------| | a001 | '2018-01-01 00:00:00' | 5 | 4 | 3 | |-----------|------------------------------------------|---------------------------| | a001 | '2018-01-01 00:01:00' | 35 | 7 | 13 | |-----------|------------------------------------------|---------------------------| | a002 | '2018-01-01 00:01:03' | 2 | 6 | 11 | |-----------|------------------------------------------|---------------------------| | a002 | '2018-01-02 05:00:00' | 5 | 16 | 98 | |-----------|------------------------------------------|---------------------------| | a003 | '2018-01-02 05:32:01' | 0 | 1.4 | 3 | |-----------|------------------------------------------|---------------------------| How do I go about this?
has answer: http://stackoverflow.com/a/50840824
accepted answer: http://stackoverflow.com/a/50839277
has comment: http://stackoverflow.com/comment/88678016
tagged with: python

http://stackoverflow.com/a/50831847
has body: you can use this configuration: from flask import Flask app = Flask(__name__, static_url_path = "/upload", static_folder = "upload") Then you can access your images as follows: &lt;img src='/upload/image1.jpg' width="200" height="85"&gt; check this answer for more details: Cannot show image from STATIC_FOLDER in Flask template
answers question: http://stackoverflow.com/q/50831596
type: Answer
accepted answer of: http://stackoverflow.com/q/50831596
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50775470
accepted answer: http://stackoverflow.com/a/50792147
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50792147
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/6010671
type: AnsweredQuestion
has body: Given a dependency parse graph, if I want to find the shortest path length between two fixed nodes, this is how I've coded it: nx.shortest_path_length (graph, source='cost', target='20.4') My question here is: What if I want to match for all sentences in the graph or collection a target with any number formatted approximately as a currency? Would I have to first find every node in the graph that is a currency, and then iterate over the set of currency values? It would be ideal to have: nx.shortest_path_length (graph, source='cost', target=r'^[$€£]?(\d+([\.,]00)?)$') Or from @bluepnume ^[$€£]?((([1-5],?)?\d{2,3}|[5-9])(\.\d{2})?)$
upvote count: 1
tagged with: networkx
type: Question
has title: How to find nodes with Python string matching functions in Networkx?
score: 1
tagged with: shortest-path

http://stackoverflow.com/a/50700653
answers question: http://stackoverflow.com/q/50700617
type: Answer
has body: Using Regex: import re s = "EquivalentClasses(&lt;http://www.ifomis.org/bfo/1.1/spanTemporalRegion&gt; ObjectUnionOf(&lt;http://www.ifomis.org/bfo/1.1/spanScatteredTemporalRegion&gt; &lt;http://www.ifomis.org/bfo/1.1/spanConnectedTemporalRegion&gt;))" m = re.search("ObjectUnionOf\((?P&lt;links&gt;.*?)\)", s) if m: print( m.group('links') ) Output: &lt;http://www.ifomis.org/bfo/1.1/spanScatteredTemporalRegion&gt; &lt;http://www.ifomis.org/bfo/1.1/spanConnectedTemporalRegion&gt;
accepted answer of: http://stackoverflow.com/q/50700617
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50838346
has answer: http://stackoverflow.com/a/50892107
has answer: http://stackoverflow.com/a/50841062
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/88685777
has body: I need to fit with scipy.optimize.curve_fit some data that look like the points in the figure. I use a function y(x) (see def below) which gives a constant y(x)=c for x&lt;x0, otherwise a polynomial (eg a second tilted line y1 = mx+q). I give a reasonable initial guess for the parameters (x0, c, m, q), as show in the figure. The result from the fit shows that all the parameters are optimized except for the first one x0. Why so? Is it how I define the function testfit(x, *p), where x0 (=p[0]) appears within another function? import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit # generate some data: x = np.linspace(0,100,1000) y1 = np.repeat(0, 500) y2 = x[500:] - 50 y = np.concatenate((y1,y2)) y = y + np.random.randn(len(y)) def testfit(x, *p): ''' piecewise function used to fit it's a constant (=p[1]) for x &lt; p[0] or a polynomial for x &gt; p[0] ''' x = x.astype(float) y = np.piecewise(x, [x &lt; p[0], x &gt;= p[0]], [p[1], lambda x: np.poly1d(p[2:])(x)]) return y # initial guess, one horizontal and one tilted line: p0_guess = (30, 5, 0.3, -10) popt, pcov = curve_fit(testfit, x, y, p0=p0_guess) print('params guessed : '+str(p0_guess)) print('params from fit : '+str(popt)) plt.plot(x,y, '.') plt.plot(x, testfit(x, *p0_guess), label='initial guess') plt.plot(x, testfit(x, *popt), label='final fit') plt.legend() Output params guessed : (30, 5, 0.3, -10) params from fit : [ 30. 0.04970411 0.80106256 -34.17194401] OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning)
score: 2
type: AnsweredQuestion
has title: curve_fit not optimizing one of the parameters
upvote count: 2
tagged with: scipy
type: Question
accepted answer: http://stackoverflow.com/a/50892107
linked to: http://stackoverflow.com/q/46624376
has comment: http://stackoverflow.com/comment/88682586
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50841062

http://stackoverflow.com/a/50700072
score: 1
has comment: http://stackoverflow.com/comment/88410861
has comment: http://stackoverflow.com/comment/88435700
has comment: http://stackoverflow.com/comment/88410337
has comment: http://stackoverflow.com/comment/88410234
answers question: http://stackoverflow.com/q/50699990
has comment: http://stackoverflow.com/comment/88410927
has comment: http://stackoverflow.com/comment/88411999
has comment: http://stackoverflow.com/comment/88412818
has comment: http://stackoverflow.com/comment/88410120
upvote count: 1
has comment: http://stackoverflow.com/comment/88412601
has comment: http://stackoverflow.com/comment/88410074
type: Answer
has comment: http://stackoverflow.com/comment/88410369
has body: I will try to re-iterate with explanation: First Method: from subprocess import Popen, PIPE process = Popen("cmd.exe", shell=False, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) commands = "C:\\Users\\praktikant3\\TESTING.cmd\n" #you can use " " for 1 line of commands or ''' ''' for several lines out, err = process.communicate(commands) print(out) While formulating your command, keep in mind that your command in the form of a python string, therefore: Make sure to escape your front/backslashes in your path: C:\.. => C:\\.. Add \n to the end of the string to signal a newline to execute your command. In my code, you can only see the output if you use print(out), however the cmd file runs regardless. Second Method: import sys import os def run_command(command): print("Running command: {}".format(command)) os.system(command) commands = "C:\\Users\\praktikant3\\TESTING.cmd" run_command(commands) This is neat if you are using only one line of commands, and you don't need the break line \n, os.system does that for you. Also os.system will display the output in your IDE without the need to print anything.
has comment: http://stackoverflow.com/comment/88410711
has comment: http://stackoverflow.com/comment/88412411
downvote count: 0

http://stackoverflow.com/comment/88452502
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50722067
score: 1
has text: jupyter notebook by default will look into its own folder. If your "train.csv" is somewhere else, you have to give it absolute path

http://stackoverflow.com/a/50736540
has comment: http://stackoverflow.com/comment/88483015
has comment: http://stackoverflow.com/comment/88487915
answers question: http://stackoverflow.com/q/50735972
has comment: http://stackoverflow.com/comment/88487660
has comment: http://stackoverflow.com/comment/88487658
has comment: http://stackoverflow.com/comment/88483218
has comment: http://stackoverflow.com/comment/88516920
has body: Try: import os dir_path = os.path.dirname(os.path.realpath(__file__)) filepath = os.path.join(dir_path, 'vrp_distance.txt') sql_statement = ("COPY (select source, target, sum(cost)/1000" " as cost from distance_matrix where source != 88888888 and target" " != 88888888 group by source, target order by source) TO" " '{}'".format(filepath)) Sidenotes to consider (not in original question): why not separate responsibilities to extract information and write it to file - you will knwo for sure which part fails OptimizationGoolge, by convention if you init a class with null strings, something is wrong in class design rename vT to somehting meaningful You have to check too: assert os.path.exists('D:/working_copy/vrp_distance.txt') assert os.path.exists('D:/working_copy') Also check Save PL/pgSQL output from PostgreSQL to a CSV file. If you do not have a writing permission, all of the above is fruitless.
downvote count: 0
has comment: http://stackoverflow.com/comment/88514657
has comment: http://stackoverflow.com/comment/88487592
has comment: http://stackoverflow.com/comment/88482559
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/88467170
has text: https://github.com/python/cpython/blob/master/Modules/_threadmodule.c
score: 1
comment on: http://stackoverflow.com/q/50729644
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/94718611
comment on: http://stackoverflow.com/a/50844691
type: Comment
has text: what is the "model" here?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88512530
comment on: http://stackoverflow.com/q/50752069
has text: @PhanendraNath: Presumably "quadword" (by the old nomenclature for 16 bit x86, where 16 bits was a word, 32 was a doubleword/dword, and while it didn't exist back then, 64 bits was later described as a quadword following the same pattern).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88692206
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50844345
has text: what type is pwused (type(pwdused))

http://stackoverflow.com/a/50794256
type: Answer
has body: The code museum = {} declares a dictionary. When you run the code museum +=1 it should give the following error: TypeError: unsupported operand type(s) for +=: 'dict' and 'int' If you want a counter then do something like museum = 0
score: 0
answers question: http://stackoverflow.com/q/50794146

http://stackoverflow.com/comment/88706053
type: QuestionComment
comment on: http://stackoverflow.com/q/50850904
has text: Sorry. I did it
score: 0
type: Comment

http://stackoverflow.com/comment/88580065
comment on: http://stackoverflow.com/q/50786529
score: 0
has text: Did you tried request.GET.get :
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88546802
score: 1
has text: What is your expected output/format?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50769693

http://stackoverflow.com/q/50753073
has body: on python3 , i want to sort a list of arabic words IN THE ALPHABETIC ORDER the file i have has this content حصل,شد حصن,حضا حضر,جا حض,أكد حضن,تهلا حطب,حطب حطم,هرس and i want to sort it by the first column so the output become حض,أكد حصن,حضا حطب,حطب حضن,تهلا حضر,جا حصل,شد حطم,هرس i tried using the function sort it didn't work i think i m missing something my code is something like that # coding=utf-8 import csv import sort d=[] with open('sort.csv', 'a+', encoding='utf-8' , newline='\n') as in_fp: with open('result.csv','w', encoding='utf-8' , newline='\n') as out_fp: for row in (csv.reader(in_fp, delimiter=',')): d.append=row[1] d.sort() and then i want to save it in the result.csv i found this link! but i don't it is working for me
has title: how do i sort arabic list
has comment: http://stackoverflow.com/comment/88514638
downvote count: 0
tagged with: arabic
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88530718
linked to: http://stackoverflow.com/q/36139
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/134232083
tagged with: python
linked to: http://stackoverflow.com/q/14032521
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/88530655
type: Question
score: 3
tagged with: sorting
has comment: http://stackoverflow.com/comment/88515062

http://stackoverflow.com/a/50837199
has body: With pagetoken, you need to include other bunch of parameters from the parent page query. Also, to get the next page results, you need to iterate on the new query. from googleplaces import GooglePlaces, types, lang from unidecode import unidecode import json import time import requests YOUR_API_KEY = 'AIzaSyAZo0lBWrvWa_aOnt1goJl5Z1imYg0tv-k' google_places = GooglePlaces(YOUR_API_KEY) query_result = google_places.nearby_search( lat_lng={'lat' : 46.1667, 'lng' : -1.15}, radius=5000, types=[types.TYPE_RESTAURANT] or [types.TYPE_CAFE] or [type.TYPE_BAR] or [type.TYPE_CASINO]) time.sleep(10) for place in query_result.places: place.get_details() print place.place_id print unidecode(place.name) if query_result.has_next_page_token: query_result_next_page = google_places.nearby_search( lat_lng={'lat' : 46.1667, 'lng' : -1.15}, radius=5000, types=[types.TYPE_RESTAURANT] or [types.TYPE_CAFE] or [type.TYPE_BAR] or [type.TYPE_CASINO], pagetoken=query_result.next_page_token) for pl in query_result_next_page.places: pl.get_details() print pl.place_id #places.append(place.place_id) print unidecode(pl.name)
type: Answer
answers question: http://stackoverflow.com/q/50704611
has comment: http://stackoverflow.com/comment/88886154
score: 0
has comment: http://stackoverflow.com/comment/88710806

http://stackoverflow.com/comment/88429780
has text: I can't reproduce this using Python 3.6.3
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50710383
type: QuestionComment

http://stackoverflow.com/q/50827312
answer count: 1
has answer: http://stackoverflow.com/a/50828759
score: 0
tagged with: python
has body: I'm trying to test my post with a testing suite. I've just been trying to follow the documentation to do this. The main problem I'm having right now is that response.context is returning None. This is what my test class looks like: class JSONHandlerTester(TestCase): def setUp(self): self.client = Client() self.jsonTestPath = os.path.join(settings.MEDIA_ROOT,'json','jsonTests') def testing(self): for test in os.listdir(self.jsonTestPath): testFile = os.path.join(os.path.join(self.jsonTestPath),test) split = test.split('.') testName = split[0] testNameArray = re.findall('[a-zA-z][^A-Z]*', testName) project = testNameArray[0] team = testNameArray[1] with open(testFile) as json: response = self.client.post('/JSONChecker', {'json_project': project, 'json_team': team, 'json': json}) print response print response.context if (response.context['title'] == "Congratulations!!! Your JSON Passes!!!" and testNameArray[2] == "Pass") or (response.context['title'][2:] == "The" and testNameArray[2] == "Fail"): print test+': Works' else: print test+': BREAKS: PROBLEM DETECTED' Also this is what my render looks like: return render(request, 'JSONChecker.html',context = {'title': title, 'validationErrors':validationErrors,'errors':errors, 'isLoggedIn':isLoggedIn, 'form': form, 'post':post}) If the form is invalid or the extension isn't json this is what the render looks like (this shouldn't be triggered by suite): return render( request, 'JSONChecker.html', context = {'title': title,'errors': errors,'isLoggedIn':isLoggedIn,'team':team, 'email':email,'form':form, 'post': post}, ) Content-Length: 0 Content-Type: text/html; charset=utf-8 Location: /JSONChecker/ I'm using Django 1.11 and Python 2.7
type: UnansweredQuestion
tagged with: file
tagged with: django
type: Question
tagged with: testing
has title: Django: Testing Post View
tagged with: post

http://stackoverflow.com/comment/88643728
score: 0
has text: so @timgeb I'm a bit confused... I understand (I think) the idea that I should have a list of these variables when I `__init__` but how would that stop me having to type them all out twice? That's all I'm really looking for, so sorry if I've been unclear or it's a daft question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50818735

http://stackoverflow.com/q/50808414
has body: I have big dataset with around 4M rows. I need to clean it by regex and put into Pandas' DataFrame. Here is my code for that: # 1) reading a text file with a dataset, where 4M rows orgfile = open("good_dmoz.txt", "r") # 2) create an empty dataframe df0=pd.DataFrame(columns=['url']) # 3) creating mask for cleaning data regex = re.compile(r"(?&lt;=\')(.*?)(?=\')") # 4) clearing data and put into the dataframe for line in orgfile: urls = regex.findall(line) df0.url = df0.append({"url": urls[0]}, ignore_index=True) The code handles the task in a small fragment, but it takes too long time to process full data (4M rows). My question is: is it possible to optimize the code? By optimization, I mean to reduce the speed of code execution. Thank you!
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50809198
has comment: http://stackoverflow.com/comment/88622505
has comment: http://stackoverflow.com/comment/88622714
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88622512
downvote count: 3
tagged with: dataframe
upvote count: 1
type: Question
score: -2
has title: Python. Filling DataFrame: code optimisation
tagged with: optimization

http://stackoverflow.com/comment/88457556
has text: The link also says that this uses the threading library under the covers. This will give no speed-up for CPU bound tasks. Drop the `dummy` and you should be multi processing. Beware that this may seem slower for a task that only takes 31 milliseconds anyway. Also you will need the `if __name__ == '__main__':` idiom.
comment on: http://stackoverflow.com/a/50704440
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88418867
has text: So halving your training set might be an "optimization" you could do - would that improve or reduce the quality of the results? Look at what you're doing - perhaps all the spam has little/no punctuation so removing punctuation from the training set makes the ham look more like spam. Perhaps stop words are used in ham not spam, so removing them eliminates them as a possibility of producing better results. And so on. You'll have to look at _your_ data in the light of the _features_ _you_ are selecting to get an answer, because the features _you_ are selecting are affecting _your_ results.
comment on: http://stackoverflow.com/q/50702508
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88649649
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50820042
has text: I understand that when no text has been selected, a popup appears with the first and last name together, if I select one of the options, should my firstname and lastname be displayed together or should it be displayed?
score: 0

http://stackoverflow.com/comment/88741557
comment on: http://stackoverflow.com/q/50738337
score: 0
type: Comment
type: QuestionComment
has text: Thank you very much for your answer @Tyathalae! Still, I don’t understand why they use the term “mini-batches” for this. Indeed to me being in mini batches mode means that the batch size is strictly less than the whole sample (meaning that their is several iterations per epoch).

http://stackoverflow.com/comment/88429264
type: Comment
has text: The JS resource is an ongoing effort and isnt really meant to work just yet, where do i make the change so that the socket making its requests to the port:4000, and when i forward the port am i making that through say windows firewall or the router settings? thanks for the help
type: AnswerComment
comment on: http://stackoverflow.com/a/50710058
score: 0

http://stackoverflow.com/q/50823011
has comment: http://stackoverflow.com/comment/88651072
answer count: 1
has comment: http://stackoverflow.com/comment/88651078
has comment: http://stackoverflow.com/comment/88651084
accepted answer: http://stackoverflow.com/a/50823181
favorite count: 0
has comment: http://stackoverflow.com/comment/88651237
has comment: http://stackoverflow.com/comment/88651068
tagged with: python
has title: python calling method within a method
has answer: http://stackoverflow.com/a/50823181
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88651158
score: -3
upvote count: 1
type: Question
tagged with: oop
has comment: http://stackoverflow.com/comment/88651074
has comment: http://stackoverflow.com/comment/88651384
has comment: http://stackoverflow.com/comment/88651103
has comment: http://stackoverflow.com/comment/88651293
downvote count: 4
has body: Here is my code which works. class S: def doSomething(): for j in headers: for z in j: st = str(z).strip() stringValue = st.replace('\n', "") headerArr.append(stringValue) return headerArr I would like to replace the above code with this. class S: def cleanStr(self, stringVal): st = stringVal.strip() stringValue = st.replace('\n', "") return stringValue def doSomething(): for j in headers: for z in j: newString = self.cleanStr(z) headerArr.append(newString) return headerArr But when I try to run this new code I get name 'self' is not defined. I apologize in advance for any mistakes with indentation. In another file I have something like newArr = s.doSomething().It works with the first code snippet. But not with the second.I have tried doing def doSomething(self): and then in the other file I do newArr = s.doSomething(self) but I still get the same error.

http://stackoverflow.com/comment/88577795
type: QuestionComment
comment on: http://stackoverflow.com/q/50785573
has text: @JordanMann, I understand it now... Unfortunately, I don't have the answer...
score: 0
type: Comment

http://stackoverflow.com/comment/88561605
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc now my script doesn't execute at all and gives a segmentation fault. Perhaps in the `from PyQt5 import QtCore,QtGui,QtWidgets,uic`
comment on: http://stackoverflow.com/q/50776545

cron
tags question: http://stackoverflow.com/q/50796215
tags question: http://stackoverflow.com/q/50823693
tags question: http://stackoverflow.com/q/50801120
tags question: http://stackoverflow.com/q/50745485
type: Tag
tag name: cron

http://stackoverflow.com/comment/88724726
comment on: http://stackoverflow.com/q/50843154
type: Comment
score: 0
has text: how about in the test message you're sending - does adding `https://` to the link in your Slack message change anything?
type: QuestionComment

http://stackoverflow.com/q/50729892
type: Question
possible better answer: http://stackoverflow.com/a/50730139
has answer: http://stackoverflow.com/a/50730066
has body: This seems like a really easy task, but I have been struggling with it for a while. I want to calculated the (number of sessions with PageView==1) / (total number of sessions) per day, sample data below session_df Date/Timestamp Session ID PageViews 2/14/2016 a 1 2/14/2016 b 5 2/14/2016 c 8 3/23/2016 d 1 3/23/2016 e 1 3/23/2016 f 2 and the expected output: Date/Timestamp BounceRate 2/14/2016 0.333333333 3/23/2016 0.666666667 I tried first add a Bounced? column based on the PageViews number, then groupby and calculate the percentage, then I need to filter out the bounced?==False which is very cumbersome. If anyone can suggest a better way for doing this that would be great! sessions_df['Bounced?'] = sessions_df['PageViews']&gt;1 dt = pd.DatetimeIndex(sessions_df['Date/Timestamp']) daily_session_bounce_rate = sessions_df.groupby([dt.date, 'Bounced?']).agg({'Session ID':'count'}) daily_session_bounce_rate = daily_session_bounce_rate.groupby(level=0).apply(lambda x: x / float(x.sum())) daily_session_bounce_rate # this is my output Bounced? Session ID 2016-01-01 False 0.459893 True 0.540107 #filter data daily_session_bounce_rate.loc[daily_session_bounce_rate['Bounced?']==True,['level_0','Session ID']]
tagged with: pandas
has title: calculate bounce rate by day
accepted answer: http://stackoverflow.com/a/50729964
downvote count: 0
score: 1
answer count: 4
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50730139
has answer: http://stackoverflow.com/a/50729964
has answer: http://stackoverflow.com/a/50730149

http://stackoverflow.com/q/50749683
has comment: http://stackoverflow.com/comment/88508080
tagged with: wsgi
has comment: http://stackoverflow.com/comment/88507181
has comment: http://stackoverflow.com/comment/88507921
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/88507149
has comment: http://stackoverflow.com/comment/88508168
has comment: http://stackoverflow.com/comment/88507835
has comment: http://stackoverflow.com/comment/88510846
favorite count: 0
has comment: http://stackoverflow.com/comment/88506959
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/88540075
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: openshift
has body: I'm using the s2i-python-container to deploy my Flask 12.2 app on OpenShift 3 (so it is served by gunicorn). For some mysterious and frustrating reason, even though I have tried setting the environment variable ENV both in my .s2i/environment file and directly via OpenShift's environment configuration, in both cases the variable ENV is not set in my application pod. It's just gone. My other environment variables are properly set. What gives? Is there some other approach I should be taking to identify if I am in development or production to load the appropriate configuration?
has comment: http://stackoverflow.com/comment/88507120
has title: Environment variable `ENV` not set when running Flask app on OpenShift
type: Question

http://stackoverflow.com/q/50776299
has comment: http://stackoverflow.com/comment/88559779
type: Question
has comment: http://stackoverflow.com/comment/88561306
has title: how to downgrade pip version 10.0.0 to pip version 9.0.1?
has answer: http://stackoverflow.com/a/55334072
upvote count: 11
has comment: http://stackoverflow.com/comment/88559559
downvote count: 3
answer count: 3
linked to: http://stackoverflow.com/q/4750806
linked to: http://stackoverflow.com/q/41454769
has comment: http://stackoverflow.com/comment/88559670
has answer: http://stackoverflow.com/a/57250323
has body: how to downgrade pip version 10.0.0 to pip version 9.0.1? I upgraded my pip version to pip 10.0.0 but i can't seem to find most of the libraries from system interpreter. now i want to know how to downgrade from pip version 10.0.0 tried using command pip install pip=9.0.1 but had 'pip' is not recognized as internal or external command error
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51163010
tagged with: python
score: 8
has comment: http://stackoverflow.com/comment/88561322
linked to: http://stackoverflow.com/q/49836676
has comment: http://stackoverflow.com/comment/88560105
tagged with: pip

http://stackoverflow.com/a/50871295
score: 18
has body: That's almost a bit embarassing, but in case anyone of you has the same problem, just update your Pillow package. pip install Pillow --upgrade Pillow-4.2.1 was on my system, it upgraded to Pillow-5.1.0 and now everything works just fine.
answers question: http://stackoverflow.com/q/50782056
upvote count: 18
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50782056

http://stackoverflow.com/comment/88639001
has text: Do you know a library that I can play mp3 files in Python 3?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50817009

http://stackoverflow.com/comment/88422060
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50706120
has text: what i meant to ask was if there was a way to create a separate array out of the elements of the existing list

http://stackoverflow.com/comment/88514638
has text: Can you include some code you have written? A [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) ?
comment on: http://stackoverflow.com/q/50753073
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/126169368
score: 0
has text: Maybe it's about you declare this css first, and it's conflict with ` ` tag.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50844844

http://stackoverflow.com/q/50742749
has body: Let's say I have the following models: class Blog(TimeStampedModel): summary = models.TextField() text = models.TextField() class BlogComment(TimeStampedModel): author = models.CharField() text = models.CharField() blog = models.ForeignKey(Blog, models.CASCADE, related_name='comments') class BlogTag(TimeStampedModel): name = models.CharField() blog = models.ForeignKey(Blog, models.CASCADE, related_name='tags') All three inherit from the following model, which implements some timestamp handling: class TimeStampedModel(models.Model): last_changed = models.DateTimeField() created_at = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): try: self._meta.get_field('blog') except models.FieldDoesNotExist: self.last_changed = timezone.now() super(TimeStampedModel, self).save(*args, **kwargs) else: now = timezone.now() self.blog.last_changed = now self.last_changed = now with transaction.atomic(): super(TimeStampedModel, self).save(*args, **kwargs) self.blog.save() class Meta: abstract = True The basic idea behind the custom save() is that when for example a comment (instance of BlogComment) is updated, it should update the last_changed timestamp of both the comment instance and the related blog entry. Unfortunately, the timestamp setting is not perfect since it overrides the blog's timestamp when its own save is called and the times end up being just slightly different: In [1]: b = Blog.objects.get(id=1) In [2]: comment0 = t.comments.all()[0] In [3]: b.last_changed, comment0.last_changed Out[3]: (datetime.datetime(2018, 6, 7, 12, 54, 12, 516855, tzinfo=&lt;UTC&gt;), datetime.datetime(2018, 6, 7, 10, 22, 09, 201690, tzinfo=&lt;UTC&gt;)) In [4]: comment0.text Out[4]: 'Some text' In [5]: comment0.text = 'test' In [6]: comment0.save() In [7]: t = blog.objects.get(id=1) In [8]: comment0 = t.comments.all()[0] In [9]: t.last_changed, comment0.last_changed Out[9]: (datetime.datetime(2018, 6, 7, 13, 25, 58, 64131, tzinfo=&lt;UTC&gt;), datetime.datetime(2018, …
has title: Updating timestamps of a model and its related parent with the same time
score: 1
tagged with: django-models
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/50749076
answer count: 1
favorite count: 0
upvote count: 1
tagged with: django
tagged with: python
tagged with: timestamp
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50749076

http://stackoverflow.com/comment/88490166
type: AnswerComment
score: 0
type: Comment
has text: Yes, you not only can but should pass a batch of training objects. This will speed up your training process a lot (and will make your loss fluctuate less, hence you'll get faster convergence)
comment on: http://stackoverflow.com/a/50738290

http://stackoverflow.com/q/50796382
tagged with: win32com
has body: I want to start with a folder e.g. C:\test instead of any of the predefined CSIDL_* folders. How can I achieve that? ''' python 3.6.2 ''' import os import win32gui from win32com.shell import shell, shellcon myfolder_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0) pidl, display_name, image_list = shell.SHBrowseForFolder ( win32gui.GetDesktopWindow (), myfolder_pidl, "Select a file or folder", 0x00014050, #shellcon.BIF_BROWSEINCLUDEFILES and some more None, None ) if (pidl, display_name, image_list) == (None, None, None): print ('Nothing selected') else: my_path = shell.SHGetPathFromIDList (pidl) file_to_process = my_path.decode() ''' continue processing file_to_process '''
score: 4
tagged with: win32gui
downvote count: 1
answer count: 1
tagged with: directory
accepted answer: http://stackoverflow.com/a/52187840
favorite count: 0
has comment: http://stackoverflow.com/comment/119849871
upvote count: 5
has comment: http://stackoverflow.com/comment/118958122
tagged with: python
has answer: http://stackoverflow.com/a/52187840
has title: select any folder as startfolder for browsing (win32gui,win32com, SHGetFolderLocation)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/119876287
type: Question

http://stackoverflow.com/q/50818735
has comment: http://stackoverflow.com/comment/88647763
tagged with: python
has comment: http://stackoverflow.com/comment/88642793
type: AnsweredQuestion
has title: iterating through variables within an object in python
has comment: http://stackoverflow.com/comment/88642609
tagged with: oop
has comment: http://stackoverflow.com/comment/88670474
has comment: http://stackoverflow.com/comment/88671020
has body: OK, this might be a very silly question, but... I have an object x, which contains a number of pandas dataframes (df1,df2,df3 for sake of argument) When the program has finished running, I want to export each of these dataframes to its own csv file. At the moment, I have a function within x that looks like this: def export(self, path): self.df1.to_csv(path+"_df1.csv") self.df2.to_csv(path+"_df2.csv") self.df3.to_csv(path+"_df3.csv") It works (I can just use x.export(somepath), but I keep having to change it because the data I want to keep in the object changes. Can anybody tell me if there is a way of simply iterating over all of the variables within an object (they are all the same format) and (in this case) dumping them all to their respective .csv files? Thanks
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50818860
has comment: http://stackoverflow.com/comment/88667068
has comment: http://stackoverflow.com/comment/88669966
has comment: http://stackoverflow.com/comment/88642668
has comment: http://stackoverflow.com/comment/88642719
has comment: http://stackoverflow.com/comment/88668128
score: 0
has comment: http://stackoverflow.com/comment/88668395
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88642710
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88643728
has comment: http://stackoverflow.com/comment/88642731
has answer: http://stackoverflow.com/a/50818860

http://stackoverflow.com/q/50851759
has comment: http://stackoverflow.com/comment/88707560
type: Question
score: 0
has body: I want to close the tab on Chrome which is opened from Selenium, but if I create an instance and call the driver.close() from the instance, it does not close the tab. For example, class Download: def __init__(self, word, driver): self.word = word self.word_url = word_url_meta.format(word) self.driver = driver def close_tab(self): self.switch_window(self.current_window) time.sleep(0.2) self.driver.close() time.sleep(0.2) self.switch_window(self.driver.window_handles[-1]) def switch_window(self): time.sleep(0.2) self.driver.switch_to_window(self.current_window) Then, I call it as: w = Download() w.do_something() w.close_tab() If I call it from the top level, the tab closes properly. But when I call it from an instance method, the tab does not close. Why does it prevent the tab from being closed? And how can I close it properly? EDIT Now I might wonder it is because wrap it with asyncio. async def download_word(word, driver, semaphore): async with semaphore: w = Download(word, driver) w.open_new_tab() await w.check_if_downloadable() await w.download() w.close_tab() async def main(): asyncio_semaphore = asyncio.BoundedSemaphore(2) jobs = [] for i in range(4): jobs.append(asyncio.ensure_future(download_word(words[i], driver, asyncio_semaphore))) await asyncio.gather(*jobs) loop.run_until_complete(main()) Is it relevant here?
has comment: http://stackoverflow.com/comment/88740255
has title: driver.close() does not close the tab on selenium if I call it from an instance
answer count: 1
has comment: http://stackoverflow.com/comment/88707067
tagged with: python
type: UnansweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/50852387

http://stackoverflow.com/q/50701531
answer count: 1
has comment: http://stackoverflow.com/comment/88412426
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88412581
linked to: http://stackoverflow.com/q/17095101
type: Question
has answer: http://stackoverflow.com/a/50701752
accepted answer: http://stackoverflow.com/a/50701752
has body: Having two dataframes (df1 and df2) which have multiple categorical data columns (Country, City, Postcode) and one with quantitative data, how can I see all the rows which are in df1 but not in df2? Both dataframes are not necassarily sorted in the same way. The Index is just a serial.
score: 0
has title: Difference between two Dataframes
tagged with: pandas

http://stackoverflow.com/a/50762951
type: AcceptedAnswer
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88536322
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50756044
answers question: http://stackoverflow.com/q/50756044
has body: Try it: import sys import os import hashlib import traceback from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * def chunk_reader(fobj, chunk_size=1024): """ Generator that reads a file in chunks of bytes """ while True: chunk = fobj.read(chunk_size) if not chunk: return yield chunk class SignalHelper(QObject): error = pyqtSignal(tuple) result = pyqtSignal(object) finished = pyqtSignal() progress = pyqtSignal(str, str) class Worker(QRunnable): def __init__(self, fn, *args, **kwargs): super(Worker, self).__init__() self.fn = fn self.args = args self.kwargs = kwargs self.signals = SignalHelper() # Add a callback to our kwargs kwargs['progress_callback'] = self.signals.progress @pyqtSlot() def run(self): try: result = self.fn(*self.args, **self.kwargs) except: traceback.print_exc() exctype, value = sys.exc_info()[:2] self.signals.error.emit((exctype, value, traceback.format_exc())) else: self.signals.result.emit(result) finally: self.signals.finished.emit() class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) layout = QVBoxLayout() self.textEdit = QTextEdit("Display duplicate files :") self.textEdit.setReadOnly(True) self.b = QPushButton("Scan files") self.b.setCheckable(True) self.b.pressed.connect(self.watcher) layout.addWidget(self.textEdit) layout.addWidget(self.b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.threadpool = QThreadPool() def watcher(self): worker = Worker(self.check_for_duplicates) worker.signals.progress.connect(self.progress_fn) self.threadpool.start(worker) def progress_fn(self, duplicate, full_path): self.textEdit.append("\nduplicate {}".format(duplicate)) self.textEdit.append(" done... {}".format(full_path)) def check_for_duplicates(self, progress_callback, hash=hashlib.sha1): path = "E:/_Qt/Python-Examples/_PyQt5/Temp/" # specify your path !!! hashes = {} for dirpath, dirnames, filenames in os.walk(path): for filename in filenames:…
upvote count: 2

http://stackoverflow.com/comment/88635778
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50794689
type: Comment
has text: I don't see this as a logically correct definition. It states constants are defined at module level but does not say what is considered constant. `Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL`

http://stackoverflow.com/a/50767060
type: Answer
has comment: http://stackoverflow.com/comment/88542469
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88542294
has comment: http://stackoverflow.com/comment/88542523
has comment: http://stackoverflow.com/comment/88543275
has comment: http://stackoverflow.com/comment/88542204
has body: Well you wrote a path like: url('complete/&lt;todo_id&gt;/', views.completeTodo, name='complete'), But here &lt;todo_id&gt; is part of the url, it does not denote a variable, etc. it means that there is only one url that will match: /complete/&lt;todo_id&gt;. In case you use django-2.x, you probably want to use path(..) instead: path('complete/&lt;todo_id&gt;', views.completeTodo, name='complete'), Furthermore in case todo_id is typically an integer, it is advisable to specify the type: path('complete/&lt;int:todo_id&gt;', views.completeTodo, name='complete'), For django-1.x, you can not use such path(..)s, and in that case you need to write a regular expression, like: url(r'^complete/(?P&lt;todo_id&gt;[0-9]+)$', views.completeTodo, name='complete'),
has comment: http://stackoverflow.com/comment/88542556
has comment: http://stackoverflow.com/comment/88542644
has comment: http://stackoverflow.com/comment/88542321
answers question: http://stackoverflow.com/q/50767021
upvote count: 2
has comment: http://stackoverflow.com/comment/88543234
has comment: http://stackoverflow.com/comment/88542250

http://stackoverflow.com/q/50738072
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88484382
tagged with: python
has comment: http://stackoverflow.com/comment/88484138
score: 2
upvote count: 2
has title: requests thread hanging in python
tagged with: python-requests
type: Question
tagged with: python-multiprocessing
has body: I have a serious issue with python multiprocessing module I am building a vulnerability management tool. It takes a list of linux packages then search for available CVEs per package by calling RedHat API. I am using multiprocessing.dummy to implement thread pool to achieve this work. The problem is that after successful calls for the API, my script is hanging/freezing and I have no way to debug that. Here is a piece of my code from multiprocessing.dummy import Pool as ThreadPool def check_vulnerability(package): done.append(package) try: time.sleep(1) headers = {'User-agent' : 'Mozilla/11.0'} with requests_retry_session() as s: s.headers.update(headers) print "Processing package "+package+"=&gt;"+str(float(len(done))/len(packages)*100)+"%" req = requests.get('https://access.redhat.com/labs/securitydataapi/cve.xml?package='+package, headers = headers, verify=True) if req.text != '': soup = BeautifulSoup(req.text, 'xml') else: pass except Exception as e: #print "#################################################################################" #print e #print packages"#################################################################################" #Some code to process req.text def main(): start_time = time.time() global packages packages = fetch_packages_rpm() #list of strings () p = ThreadPool(int(results.thread)) all = p.map(check_vulnerability, packages) After some successful prints, my script is hanging and no way to debug that (I think thread is waiting for ssl handshake or something like that and it is in waiter.aquire()). Any kind of help is highly appreciated
has answer: http://stackoverflow.com/a/50835104
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88500416
score: 0
comment on: http://stackoverflow.com/q/50742538
type: Comment
type: QuestionComment
has text: Did you try reinstalling the package with `yum`? `yum reinstall python-setuptools`

http://stackoverflow.com/q/50849789
accepted answer: http://stackoverflow.com/a/50850273
has title: What does the numpy.linalg.norm function?
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/74764162
has answer: http://stackoverflow.com/a/74764162
tagged with: k-means
has body: What is the function of numpy.linalg.norm method? In this Kmeans Clustering sample the numpy.linalg.norm function is used to get the distance between new centroids and old centroids in the movement centroid step but I cannot understand what is the meaning by itself Could somebody give me a few ideas in relation to this Kmeans clustering context? What is the norm of a vector?
answer count: 3
has answer: http://stackoverflow.com/a/50850273
score: 8
upvote count: 11
favorite count: 0
has answer: http://stackoverflow.com/a/61821127
tagged with: python
type: AnsweredQuestion
downvote count: 3

http://stackoverflow.com/comment/88696765
type: Comment
has text: Even though I've rectified this error , I'm getting yet another error `Traceback (most recent call last): File "solution.py", line 26, in <module> kaprekarNumbers(p, q) File "solution.py", line 14, in kaprekarNumbers p1 , p2 = square[:len(square)/2] , square[len(square)/2:] TypeError: slice indices must be integers or None or have an __index__ method` Can you please suggest some improvements in the code . Thanks :D
comment on: http://stackoverflow.com/a/50846569
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88678398
type: QuestionComment
has text: Possible duplicate of [Python: iterate through a list](https://stackoverflow.com/questions/28095258/python-iterate-through-a-list)
comment on: http://stackoverflow.com/q/50837262
score: 0
type: Comment

http://stackoverflow.com/q/50794117
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: tensorflow
type: Question
has body: I have a tensorflow code that uses tf.train.shuffle_batch for the training part. I read some forums and I got the idea to use these lines to separate between the input pipeline that uses queues and the inference part that should just use one single image: ima=queue_loader.images is_just_one = tf.placeholder(dtype=bool,shape=(),name='is_just_one') imgs = tf.placeholder(tf.float32, (1, height, width, 1), name='imgs') images = tf.cond(is_just_one, lambda:imgs, lambda:ima) then I just specify in feed_dict is_just_one:False during my training. I save the model after each epoch with: saver.save(sess, checkpoint_path, global_step=ep+1) After having a checkpoint file, I run the freeze.py code in this way: python freeze.py --model_dir=checkpoints --output_node_names=imgs,is_just_one,prediction Then: I try to restore my model with this code: imn=tf.placeholder(tf.float32, shape=(None,None,1)) imno=tf.image.per_image_standardization(imn) X=io.imread("test.png") with tf.Session() as sesss: X=sesss.run(imno,feed_dict={imn:X[...,0,None]}) with tf.gfile.GFile("checkpoints/frozen_model.pb", "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def,name='import') for i in range(2): with tf.Session(graph=graph,config=tf.ConfigProto(log_device_placement=True)) as sess: act_map =graph.get_tensor_by_name("import/prediction:0") is_just_one = graph.get_tensor_by_name("import/is_just_one:0") inputs = graph.get_tensor_by_name("import/imgs:0") mapp=sess.run(act_map,feed_dict={is_just_one:True,inputs:X[None,:,:,None]}) What happens when I run my code is that it hangs forever, device placement is: I tensorflow/core/common_runtime/simple_placer.cc:872] import/shuffle_batch/random_shuffle_queue: (RandomShuffleQueueV2)/job:localhost/replica:0/task:0/cpu:0 So, if I understand correctly, the saved node associated to the tf.train.shuffle_batch is waiting for inputs, and since I don't feed it then it hangs forever. w…
tagged with: restore
has answer: http://stackoverflow.com/a/50795331
has title: restoring tensorflow graph which uses shuffle_batch hangs forever
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88691395
score: 0
comment on: http://stackoverflow.com/q/50841994
type: Comment
type: QuestionComment
has text: I'll add some snippets of code into the post

http://stackoverflow.com/comment/88564752
type: QuestionComment
comment on: http://stackoverflow.com/q/50778877
has text: Which part of the sklearn docs did you read and find unclear?
score: 0
type: Comment

http://stackoverflow.com/a/50712118
has body: You can use below Xpath .//*[@id='react-root']/section/main/article/div[2]/div[2]/p/a or CSS Selector .izU2O&gt;a or Link Text Log in
type: Answer
has comment: http://stackoverflow.com/comment/88433295
has comment: http://stackoverflow.com/comment/88433346
answers question: http://stackoverflow.com/q/50711890
has comment: http://stackoverflow.com/comment/88433160
has comment: http://stackoverflow.com/comment/88433249
has comment: http://stackoverflow.com/comment/88441768
score: 0
has comment: http://stackoverflow.com/comment/88435221
has comment: http://stackoverflow.com/comment/88433215

http://stackoverflow.com/comment/88534507
score: 0
type: Comment
type: AnswerComment
has text: this answers the question. I am aware of the excel solution, was playing around with python though. I wonder if it can be done when saving it in some other file e.g .doc
comment on: http://stackoverflow.com/a/50763370

http://stackoverflow.com/comment/88987957
comment on: http://stackoverflow.com/a/50866516
type: AnswerComment
score: 0
type: Comment
has text: I have edited the original post with the most recent code (yours, mostly) and the updated data... over 200 features

http://stackoverflow.com/comment/88529294
score: 0
type: Comment
type: QuestionComment
has text: `(\w+)\s(\d{1,2}),` month is in group 1, day in group 2
comment on: http://stackoverflow.com/q/50760826

http://stackoverflow.com/comment/119858272
has text: @Joost in the case that result is False in `PhoneField` and it desired to return a message, is it posible?
type: AnswerComment
comment on: http://stackoverflow.com/a/50763179
score: 0
type: Comment

http://stackoverflow.com/a/50780355
has body: Iterative grouping with for I'm just fixing your code with this one. To simplify things, you can initialise result with seq[0]. def runs(seq, n): result = [[seq[0]]] for s in seq[1:]: if s - result[-1][-1] &gt; n: # Keep it simple. Compare the delta. result.append([]) result[-1].append(s) return result &gt;&gt;&gt; runs(nums, 1) [[1, 2, 3], [6, 7, 8], [10], [12], [14], [18], [25], [28], [31], [39]] &gt;&gt;&gt; runs(nums, 2) [[1, 2, 3], [6, 7, 8, 10, 12, 14], [18], [25], [28], [31], [39]] pandas.GroupBy If you want to get fancy, you can use the groupby idiom, made easy with pandas. import pandas as pd def runs2(seq, n): s = pd.Series(seq) return s.groupby(s.diff().gt(n).cumsum()).apply(pd.Series.tolist).tolist() &gt;&gt;&gt; runs2(nums, 3) [[1, 2, 3, 6, 7, 8, 10, 12, 14], [18], [25, 28, 31], [39]] There are two essential ingredients here: the grouper (the predicate you're grouping on), and the agg function (the function you'll apply on each group) The grouper is s.diff().gt(n).cumsum(), broken down calculates three things: The element-wise difference in seq using diff A boolean mask indicating whether the diff is greater than n Performing a cumulative sum (or count) to determine the groups The output of this operation is s.diff().gt(n).cumsum() 0 0 1 0 2 0 3 1 4 1 5 1 6 1 7 1 8 1 9 2 10 3 11 4 12 5 13 6 dtype: int64 The agg function is pd.Series.tolist, and will convert any series to a list. That's what we need here, a nested list.
accepted answer of: http://stackoverflow.com/q/50780322
answers question: http://stackoverflow.com/q/50780322
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 7
upvote count: 7

http://stackoverflow.com/comment/88701483
type: Comment
has text: I tried `CLASS[DURATION==-1` as well, but I get the same error.
comment on: http://stackoverflow.com/q/50849097
score: 0
type: QuestionComment

http://stackoverflow.com/q/50705536
has comment: http://stackoverflow.com/comment/88420764
upvote count: 2
has body: Basically, what I have is a GUI with some QLineEdits, a "search button" and a table. You hit the button and a class called DataGrabber searches a database for data, processes them, returns a list with dictionaries with which the table is filled, accordingly. These searches can take a while and I need to keep my GUI responsive. Also, I want the statusbar message to change as long as the search is going on (something like "Searching." -> "Searching.." -> "Searching...", the functionality is not rly important here, it's just about understanding how I can handle this properly). I started with threading everything and created a queue between the thread that handles the search and the function that handles the statusbar, to know when the search is done. But that seems really goofy. Especially since Qt provides all kind of tools, like QThread and Signals. But I'm rly lost right now. What would be the best way to handle the responsiveness when having such a time-consuming action like a database search? And what would be the best way to tell the main/child thread that the search is finished? Here is a reduced version of what I have right now: class GUI(Ui_MainWindow, InitGlobals): def __init__(dialog): ... self.start_button_3.clicked.connect(\ lambda: self.start_search(self.result_tab_3)) ... def start_search(): ... search_paras = [3, self.name_box_3.text(), self.project_combo_3.currentText(), self.voltage_box.text(), self.volume_box.text()] queue = Queue() thr = Thread(target=self.search_thread, args=(queue, search_paras,)) thr.start() data_lst = statusbar_load(queue, self.statusbar, option="loader") thr.join() self.statusbar.showMessage("Search completed...") for dic in data_lst: self.write_to_table(dic, tab) def search_thread(self, queue, args): grabber = DataGrabber(self.db_config) ... if args[0] == 3: queue.put(grabber.alpha_search(args[1], args[2], args[3], args[4])) queue.task_done() def statusbar_load(queue, statusbar_obj, option="spinner"): data = None i = 0 while d…
tagged with: python
tagged with: qthread
has title: Need advice to keep GUI responsive
type: AnsweredQuestion
score: 1
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50708286
downvote count: 1
type: Question
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/50708286
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50811506
upvote count: 1
has title: RLM license does not work with python 3.5 on windows 8, 10
type: Question
score: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88630269
has comment: http://stackoverflow.com/comment/88630839
type: UnansweredQuestion
tagged with: windows
has body: I am trying to use RLM ( Reprise license manager) license with python 3.5. Have been using RLM with python 2.7 but facing issues with 3.5. When I am running the example code provided by RLM it works with python 3.5 on windows 7 but fails on windows 8 , 10. Same code works with the same RLM dll with python 2.7 on all versions of windows. The error message is stat = rlm.rlm_stat(rh) OSError: exception: access violation reading 0x00000000311E1908 Following is the example code from RLM. # # Example of calling RLM functions from Python. This example uses Python 3. # This is not a complete Python language interface for RLM - instead it shows # how to pass the essential data types back and forth between Python and RLM. # # # Use Python ctypes library to call RLM functions # There is a good writeup here: https://docs.python.org/3.4/library/ctypes.html from ctypes import * import sys # This loads rlm1122.dll from the current working directory rlm = cdll.rlm1222 # This loads librlm1122.so from the current working directory - note that on # Windows ctypes adds the .dll but on Linux, etc we need to explicitly call # LoadLibrary and supply the suffix # rlm=cdll.LoadLibrary("librlm1122.so") # Specify the argument types and return type of the RLM functions to be used. # In C, rlm_init()'s prototype is # RLM_HANDLE *rlm_init(const char *, const char *, const char *) # Pass the const char* as c_char_p. RLM_HANDLE is an opaque pointer - use an # unsigned long to represent this and other RLM handle types in Python. rlm.rlm_init.argtypes = [c_char_p, c_char_p, c_char_p] rlm.rlm_init.restype = c_ulong # Argument and return types for rlm_checkout, rlm_stat, rlm_license_stat, # rlm_checkin, and rlm_close. Use an unsigned long for the # license handle, as we do for the RLM handle returned from rlm_init rlm.rlm_checkout.argtypes = [c_ulong, c_char_p, c_char_p, c_int] rlm.rlm_checkout.restype = c_ulong rlm.rlm_stat.argtypes = [c_ulong] rlm.rlm_stat.restype = c_int rlm.rlm_license_stat.argtyp…
tagged with: python
tagged with: licensing
answer count: 0

arima
tag name: arima
type: Tag
tags question: http://stackoverflow.com/q/50747097
tags question: http://stackoverflow.com/q/50711771

http://stackoverflow.com/q/50771453
answer count: 0
has comment: http://stackoverflow.com/comment/88550787
score: 0
tagged with: metaprogramming
tagged with: import
type: Question
has title: How to generate imported code with conflicting method and variable names?
has comment: http://stackoverflow.com/comment/88552580
has body: I am working on a software which generates a generic Python source code through a set of inputs(methods and variables) by the user from a GUI. The source can also be saved in an XML with tags and . Now I need to implement the import functionality through XML. While importing the user selects a new XML and all the functions and variables in the XML needs to be appended to the generated source. Example - XML Structure: &lt;functions&gt; def detect_obstacle(self): laserData = self.laser_scan for val in laserData.ranges: if val &lt; 100: self.is_obstacle = True return self.is_obstacle = False &lt;/functions&gt; &lt;variables&gt; self.is_obstacle = False &lt;/variables&gt; &lt;interfaces&gt; LaserScan &lt;/interfaces&gt; Generated Code - from codegen import State class Node(): def __init__(self): self.is_obstacle = False self.laserScan = (Updates from a server thorugh a callback) def detect_obstacle(self): laserData = self.laserScan for val in laserData.ranges: if val &lt; 100: self.is_obstacle = True return self.is_obstacle = False class State0(State): def __init__(self, id, node): State.__init__(self, id) self.Node = node def runCode(self): if self.Node.calculate_obstacle(): return True if __name__ == "__main__": node = Node() state0 = State0(0, node) While importing the XML might have - similar name of methods and variables similar method names but different arguments. Hence after importing and generating code, there would be ambiguity in the generated code. The current implementation is for Python and further, I would extend it to C++ too. Strategies I thought of - Name Mangling Separate namespace or class for every new import. What is the best strategy to implement the import functionality?
has comment: http://stackoverflow.com/comment/88551309
has comment: http://stackoverflow.com/comment/88550948
has comment: http://stackoverflow.com/comment/88550870
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88550589
tagged with: python
has comment: http://stackoverflow.com/comment/88550999
has comment: http://stackoverflow.com/comment/88552276
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/a/50819644
type: Answer
score: 1
has body: java has 32-Bit fixed int size. But in python there is no explicitly defined limit for numbers. read at (Maximum value for long integer) A hacky solution for your problem (may not work all cases) is return ans - 2**(32-1)
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50819025
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50819025

http://stackoverflow.com/comment/88612778
type: QuestionComment
comment on: http://stackoverflow.com/q/50803440
has text: Try `element.text` or `element.get_attribute("innerHTML")`
score: 0
type: Comment

http://stackoverflow.com/comment/88509436
type: Comment
has text: one last question. how do I get only the rows that have the count greater than 1? Doing df2 = df2[count > 1] is producing a lot of NaN in the mean and count column
score: 0
comment on: http://stackoverflow.com/a/50748348
type: AnswerComment

http://stackoverflow.com/comment/88498088
type: Comment
has text: Pseudo-code: for child in parent: if child.text == 'textYouAreLookingFor': do stuff with child button element
comment on: http://stackoverflow.com/q/50744911
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88420520
has text: Did u try printing 'r' and see if it is an array?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50705552
type: Comment

http://stackoverflow.com/a/50769252
accepted answer of: http://stackoverflow.com/q/50751931
type: Answer
has body: A Discord bot isn't something suitable to run with pythonw. All of the context is in the terminal. I used heroku to host my discord bot. I also used this video to help with the setup.
answers question: http://stackoverflow.com/q/50751931
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50853030
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50853052
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has body: i have a dataset like : Date Value 2017-11-08 6 2017-11-10 5 2017-11-16 3 2017-11-13 5 2017-11-06 6 2017-10-25 5 2017-10-31 1 2017-10-30 3 2017-10-13 6 2017-11-17 4 2017-10-22 2 i am trying to plot a simple line graph, using matplotlib plt.plot(df['Date'],df['Value']) it is showing a very weird graph: how to do it the right way? second question : how to get a range of dates and plot them ? my df.info() Data columns (total 2 columns): Date 272 non-null datetime64[ns] Value 272 non-null int64 dtypes: datetime64[ns](1), int64(1)
type: Question
has title: Time Series Plot Pandas Error
accepted answer: http://stackoverflow.com/a/50853052

http://stackoverflow.com/q/50756697
has comment: http://stackoverflow.com/comment/88521588
has comment: http://stackoverflow.com/comment/88522219
type: Question
has body: I have a data set which looks like follows (Values changed): Value A B ABC 20 5 ABC 20 5 ABC 20 5 ABC 20 5 XYZ 20 5 XYZ 20 5 XYZ 20 5 I create a new column C using df['C'] = df['A']/df['B'] I obtain the df: Value A B C ABC 20 5 4 ABC 20 5 4 ABC 20 5 4 ABC 20 5 4 XYZ 20 5 4 XYZ 20 5 4 XYZ 20 5 4 XYZ 20 5 4 Until here everything works fine. Now When I try to use group by on the df, it doesn't give the sum of the third column(the one I created). I am using the following code line for group by df.groupby('Value').sum() The result is: Value A B ABC 60 15 XYZ 60 15 Any reason why it might be doing that?
has title: Group by and sum not working on newly created columns
has comment: http://stackoverflow.com/comment/88521283
score: 0
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/88523936
tagged with: pandas
has comment: http://stackoverflow.com/comment/88521389
tagged with: python-3.x
linked to: http://stackoverflow.com/q/37575944
has comment: http://stackoverflow.com/comment/88522394
has comment: http://stackoverflow.com/comment/88521474
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88521560
has comment: http://stackoverflow.com/comment/88523744
tagged with: python
answer count: 0

http://stackoverflow.com/q/50729885
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50730094
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/88467520
has comment: http://stackoverflow.com/comment/88467756
tagged with: duplicates
type: Question
has comment: http://stackoverflow.com/comment/88467633
has title: How to count overlapped values among columns
has comment: http://stackoverflow.com/comment/88467614
has comment: http://stackoverflow.com/comment/88467674
has body: Please let me ask a question about pandas dataframe. For example, I have a dataframe like this. df = pd.DataFrame({'Dog': ['aa','bb','cc','dd','aa','ff'], 'Cat':['dd','ee','dd','as','ae','ee'], 'Bird':['ff','cd','ee','def','ae','as']}) df Each column represents animal's information. I want to know how many overlaps exist among animals. For instance, Dog and Cat share "dd", so one overlap. Dog and Bird share "ff", so one overlap. Some animals have duplicates in their own columns. For example, Dog has a duplicate as "aa". So I want to remove the duplicates in an animal first and then want to analyze the number of duplicates among animals. If you could give me your thoughts, I would be grateful for that very much. P.S. Expected output is like this panel. Thank you.
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88467640
answer count: 1
tagged with: overlap

http://stackoverflow.com/comment/88445405
score: 0
has text: This is detailed in [the module documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.quantile.html)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50717781

http://stackoverflow.com/comment/88582779
has text: `for code in code_that_doesnt_work: debug_code()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50788191

http://stackoverflow.com/comment/88534853
type: QuestionComment
type: Comment
has text: add a flag set to `False` outside the inner loop (inside the first) and set it to `True` when you see a vowel. At the end print "no vowel" if it's still `False`
score: 0
comment on: http://stackoverflow.com/q/50763508

http://stackoverflow.com/comment/88697839
type: Comment
comment on: http://stackoverflow.com/a/50826492
has text: I did check `auth.log` file and it just have many `error: connect_to 127.0.0.1 port 34865: failed.` messages. `34865` is the port that's specified in kernel.json. I assume this message means that the port is blocked. I'm not a linux user. Can you please advise what can I do to unblock this port?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88510378
comment on: http://stackoverflow.com/a/50751176
score: 0
type: Comment
has text: If I do it separately for each file it works but it doesnt run as a whole program
type: AnswerComment

http://stackoverflow.com/comment/88600102
type: Comment
comment on: http://stackoverflow.com/a/50796094
has text: @user8270077 - Unfortunately I have no experience with it :(
type: AnswerComment
score: 0

http://stackoverflow.com/q/50826073
answer count: 1
tagged with: aws-lambda
favorite count: 0
has title: AWS Lambda-create tag if not exists
has answer: http://stackoverflow.com/a/50880272
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: For each AWS region 1.Get all EC2 instances that either 2.are Tagged with tag Owner and value Unknown or unknown 3.are missing tag Owner For each EC2 instance 4.Check if the instance has a tag "Terminate_On" Else 5.Tag the instance with a tag "Terminate_On" and value of the date 7 days from now. steps 1,2 and 3 are completed: import boto3 import collections import datetime import time import sys from datetime import datetime from dateutil.relativedelta import relativedelta ec = boto3.client('ec2', 'eu-west-1') ec2 = boto3.resource('ec2', 'eu-west-1') date_after_month = datetime.now()+ relativedelta(days=7) #print date_after_month.strftime('%d/%m/%Y') def lambda_handler(event, context): reservations = ec.describe_instances().get('Reservations', []) for reservation in reservations: for instance in reservation['Instances']: tags = {} for tag in instance['Tags']: tags[tag['Key']] = tag['Value'] if not 'Owner' in tags: a = instance['InstanceId'] + " does not have Owner tag" elif tags['Owner'] in ['Unknown', 'unknown']: b = instance['InstanceId'] + " has [U|u]nknown Owner tag" if not 'TerminateOn' in tags: ec2.create_tags( Resources=[instance['InstanceId']], Tags= [{ 'Key':'TerminateOn', 'Value':date_after_month.strftime('%d/%m/%Y')}]) #print a+" "+b 4.for instances returned from above code (Instances with Owner tags and instances without owner tag) check if Terminate_On tag exists 5.if not, create that tag with date_after_month.strftime('%d/%m/%Y') as value The issues is on step 5, if one EC2 instance is running, no problem, tag is created, but if more than one, then tag is created only for first one and following error is shown: for tag in instance['Tags']: KeyError: 'Tags'
type: Question
has comment: http://stackoverflow.com/comment/88681394
tagged with: amazon-ec2
downvote count: 0
tagged with: amazon-web-services

http://stackoverflow.com/q/50831978
has answer: http://stackoverflow.com/a/50832622
possible better answer: http://stackoverflow.com/a/50832274
has answer: http://stackoverflow.com/a/50832274
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50832376
favorite count: 0
accepted answer: http://stackoverflow.com/a/50832622
answer count: 5
has body: friends I have stuck in List of list problem. I have below type of List contains ['Score','title','ID'] [[0.6428571428571429, 'Software QA', 2089], [0.7428571428571429, 'Software Developer', 2086], [0.75, 'Software Tester', 2004], [0.7428571428571429, 'Software Developer', 2004], [0.7428571428571429, 'Software Developer', 1958], [0.7428571428571429, 'Software Developer', 1954], [0.7428571428571429, 'Software Developer', 2133], [0.7428571428571429, 'Software Developer', 2153], [0.7428571428571429, 'Software Developer', 2152], [0.9411764705882353, 'Software Engineer', 1107], [0.7058823529411765, 'Software Devloper', 2133], [0.7058823529411765, 'Software Devloper', 2153], [0.7058823529411765, 'Software Devloper', 2152],] Now I want to compare ID if they similar then need to give condition which score is higher I tried for one element code is below: if cleanlist[2][2] == cleanlist[i][2]: if cleanlist[2][0] &gt; cleanlist[i][0]: print (cleanlist[2]) else: print(cleanlist[i]) How can I do in loops and get unique IDs with score Desire output is below: [[0.6428571428571429, 'Software QA', 2089], [0.7428571428571429, 'Software Developer', 2086], [0.75, 'Software Tester', 2004], [0.7428571428571429, 'Software Developer', 1958], [0.7428571428571429, 'Software Developer', 1954], [0.7428571428571429, 'Software Developer', 2133], [0.7428571428571429, 'Software Developer', 2153], [0.7428571428571429, 'Software Developer', 2152], [0.9411764705882353, 'Software Engineer', 1107],]
tagged with: python
has title: How to compare duplicate element in list of list and give IF condition on another element of same list of list in python
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/50832310
has answer: http://stackoverflow.com/a/50833212
type: Question

checkbox
tag name: checkbox
tags question: http://stackoverflow.com/q/50782670
type: Tag
tags question: http://stackoverflow.com/q/50830540
tags question: http://stackoverflow.com/q/50847749

http://stackoverflow.com/a/50736515
has comment: http://stackoverflow.com/comment/88511071
type: Answer
upvote count: 1
score: 1
has body: Well considering the test data you've linked, print(metadata_blob) is perfectly right in returning an empty list since there is no Metadata: in the YAML. More importantly, you do print(stream.read()) which reads the entire file and places the stream's position at the end of the file. Afterwards, every attempt to read from stream does not return anything. My Python is not strong enough to know what exactly happens when you do str(stream) but it definitely is not the usual way to read anything from the file. Try this: contents = stream.read() print(contents) metadata_blob = re.findall(r'\n Metadata:(.*?)\n Properties:', contents) Also, do away with the try/catch or do something useful with it. You will never get a yaml.YAMLError because you do not use the yaml module for reading the file.
answers question: http://stackoverflow.com/q/50734530
downvote count: 0

celery
tags question: http://stackoverflow.com/q/50854932
tags question: http://stackoverflow.com/q/50785095
tags question: http://stackoverflow.com/q/50753386
tags question: http://stackoverflow.com/q/50762736
tag name: celery
tags question: http://stackoverflow.com/q/50765423
tags question: http://stackoverflow.com/q/50775398
tags question: http://stackoverflow.com/q/50748203
tags question: http://stackoverflow.com/q/50717604
type: Tag
tags question: http://stackoverflow.com/q/50736011
tags question: http://stackoverflow.com/q/50751133
tags question: http://stackoverflow.com/q/50784722
tags question: http://stackoverflow.com/q/50798281
tags question: http://stackoverflow.com/q/50717858
tags question: http://stackoverflow.com/q/50846548

http://stackoverflow.com/comment/88671347
comment on: http://stackoverflow.com/q/50833410
score: 0
type: Comment
type: QuestionComment
has text: @Tammy, Can you show us your desired output from sorting the NumPy array in your question?

http://stackoverflow.com/comment/88706474
type: QuestionComment
type: Comment
has text: It might be easier to use a dict instead of two lists. e.g. `d = {'zebra': 'is an animal', 'piano': 'is a musical instrument', 'fly': 'is an insect'}`. Now `d['zebra']` gives you the definition. You could even make the dict dynamically `d = dict(zip(wordlist, deflist))`.
comment on: http://stackoverflow.com/q/50851878
score: 0

cython
tags question: http://stackoverflow.com/q/50798149
tags question: http://stackoverflow.com/q/50716886
tags question: http://stackoverflow.com/q/50809244
tags question: http://stackoverflow.com/q/50777101
tags question: http://stackoverflow.com/q/50719086
type: Tag
tags question: http://stackoverflow.com/q/50830227
tag name: cython
tags question: http://stackoverflow.com/q/50705208
tags question: http://stackoverflow.com/q/50816945
tags question: http://stackoverflow.com/q/50790766

http://stackoverflow.com/a/50840646
has body: That's how XML works. The entity &amp;#xf20d; indicates the character . Parsing the XML includes converting entities to the characters they indicate. Trying to retain the entity codes is probably a bad idea. SQLite should be able to store these characters. However, if you really do need the entities, you can have Python convert non-ASCII characters back to entities before writing them to the database, e.g. nodevalue = s.childNodes[0].nodeValue nodevalue = nodevalue.encode("ascii", "xmlcharrefreplace").decode() # proceed to write nodevalue to database
accepted answer of: http://stackoverflow.com/q/50840170
upvote count: 1
answers question: http://stackoverflow.com/q/50840170
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/88421291
type: AnswerComment
has text: Thanks for your reply but actually, that element itself is not clickable. I will need to click nearby that element if we find that.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50706000

http://stackoverflow.com/a/50823886
type: Answer
upvote count: 1
score: 1
has body: open the file. f.readlines() returns each line in the text file in a list. Since a list is indexed from 0. list[1:] will skip the first one and give the rest. with open("stack.txt") as f: txt_list = f.readlines() #That's a list for item in txt_list[1:]: #skip the first one print(item) output: 2 3 4 5 &gt;&gt;&gt; And the \n is nothing but a special character denoting a new line. From your input you read multiple lines each having a new line character at the end. Also print prints each one in a new line. That's the reason for (Two newlines) gap between two numbers in above output. You can join the list and print like this. Since each already has a new line character in it. What you are doing is printing the entire list in your code. yours: output: ['2\n', '3\n', '4\n', '5'] Try this: with open("stack.txt") as f: txt_list = f.readlines() out = ''.join(txt_list[1:]) print(out) output: 2 3 4 5
downvote count: 0
answers question: http://stackoverflow.com/q/50823484
has comment: http://stackoverflow.com/comment/88653943

http://stackoverflow.com/comment/130467372
comment on: http://stackoverflow.com/a/50713277
score: 0
type: AnswerComment
has text: Hi, i tried using your code but I kept getting errors for the cv2.findContours line as it only returns two values. Is there a way to get around this?
type: Comment

http://stackoverflow.com/q/50718119
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88447179
tagged with: class
has comment: http://stackoverflow.com/comment/88445087
has comment: http://stackoverflow.com/comment/88445362
has body: I want to define a subclass of a class, and I need it to be upgraded to in one of the class' methods, rather than initialized from the very beginning. The example is a hobby project with Grids and the distances in them. So I start a Grid class like this: class Grid: def __init__(self): # A grid is a list of lists of cells. self.grid = self.prepare_grid() self.configure_cells() self.maze = None def __getitem__(self, a_tuple): x, y = a_tuple return self.grid[x][y] def prepare_grid(self): ... def configure_cells(self): ... Then I want to add Distance functionality. I was thinking like in a game where you've improved to became a Distance Grid, with methods like: class DistanceGrid(Grid): def set_distances(self, root_cell): ... def path_to(self, goal): ... Here comes the tricky part. Since I don't want it to be initialized, but rather improved to, I need a method on the parent class to make it a subclass (looks almost recursive, but hopefully it isn't). from distances import DistanceGrid class Grid: ... def upgrade_distance(self, root): self = type(self, DistanceGrid) self.set_distances(root) Can this be done? I'll keep trying. Thanks
favorite count: 0
type: Question
tagged with: subclass
has answer: http://stackoverflow.com/a/50719467
tagged with: python
score: 0
has title: How can I add class inheritance in a method outside initialization?
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88444787

http://stackoverflow.com/comment/88481006
type: QuestionComment
comment on: http://stackoverflow.com/q/50736143
score: 0
has text: Yes you are right. I have updated the example.
type: Comment

http://stackoverflow.com/a/50776272
has comment: http://stackoverflow.com/comment/88566946
answers question: http://stackoverflow.com/q/50776019
upvote count: 1
has body: Use re module: &gt;&gt;&gt; import re &gt;&gt;&gt; text = 'Aaaaaaaaaaaaaaa, to replace!\n to replace?\n\thelll34234ooooo' &gt;&gt;&gt; re.sub(r'(\w+)', '&lt;string&gt;', text) It outputs: &gt;&gt;&gt; '&lt;string&gt;, &lt;string&gt; &lt;string&gt;!\n &lt;string&gt; &lt;string&gt;?\n\t&lt;string&gt;' re.sub means: replace every occurrence of (\w+) in text with &lt;string&gt;. For file: main.py: import re with open('main.py', 'r') as input: text = input.read() print(text, '\n\n----------------\n') print(re.sub(r'(\w+)', '&lt;string&gt;', text)) output: import re with open('main.py', 'r') as input: text = input.read() print(text, '\n\n----------------\n') print(re.sub(r'(\w+)', '&lt;string&gt;', text)) ---------------- &lt;string&gt; &lt;string&gt; &lt;string&gt; &lt;string&gt;('&lt;string&gt;.&lt;string&gt;', '&lt;string&gt;') &lt;string&gt; &lt;string&gt;: &lt;string&gt; = &lt;string&gt;.&lt;string&gt;() &lt;string&gt;(&lt;string&gt;, '\&lt;string&gt;\&lt;string&gt;----------------\&lt;string&gt;') &lt;string&gt;(&lt;string&gt;.&lt;string&gt;(&lt;string&gt;'(\&lt;string&gt;+)', '&lt;&lt;string&gt;&gt;', &lt;string&gt;))
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/50809434
type: Question
tagged with: convex
has body: In python, given m random points in an n x n grid, how do I calculate a (roughly) convex hull where the hull can only be created using the points on the discrete grid rather than a continuous point? modules like scipy.spatial only give continuous convex hulls, where the lines connecting vertices are purely algebraic, but I want approximately a convex hull where the boundary is discrete.
tagged with: discrete-mathematics
answer count: 2
score: 2
has answer: http://stackoverflow.com/a/50810090
downvote count: 0
has title: Discrete Convex Hull
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/47704008
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50810132
tagged with: convex-hull

http://stackoverflow.com/comment/121718426
type: AnswerComment
comment on: http://stackoverflow.com/a/50818525
score: 0
has text: @SpghttCd coul you please explain how is it possible to acess the interpolated points. Say the value at `grd_x[0],grid_y[2]`? `griddata` returns a 2d array and it is not so obvious to me how that maps to the interpolation points given by `grid_x, grid_y`
type: Comment

http://stackoverflow.com/comment/88600823
comment on: http://stackoverflow.com/a/50793347
type: AnswerComment
score: 0
type: Comment
has text: '<type 'str'>' I fixed this problem by converting to string.. but this `session.attributes = save_booking_date(BookingDate)` overwrites the existing attribute. Can you please tell me how to append the attributes in session ?

textctrl
tags question: http://stackoverflow.com/q/50719506
tag name: textctrl
type: Tag

http://stackoverflow.com/q/50751500
has comment: http://stackoverflow.com/comment/88511263
tagged with: docker
has comment: http://stackoverflow.com/comment/88511077
answer count: 2
has comment: http://stackoverflow.com/comment/88511189
favorite count: 0
has title: Setting up docker container so that I can access python packages on ubuntu server
has comment: http://stackoverflow.com/comment/88511146
has comment: http://stackoverflow.com/comment/88511252
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88510882
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/55885175
score: 1
has comment: http://stackoverflow.com/comment/88511092
has comment: http://stackoverflow.com/comment/88511222
type: Question
has answer: http://stackoverflow.com/a/62274513
has body: I'm new to using Docker, so I'm either looking for direct help or a link to a relevant guide. I need to train some deep learning models on my school's linux server, but I can't manually install pytorch and other python packages since I don't have root access (sudo). Another student said that he uses docker and has everything ready to go in his container. I'm wondering how to wrap up my code and relevant packages into a container that I can push to the linux server and then run.
downvote count: 0

http://stackoverflow.com/q/50849848
upvote count: 2
tagged with: python
tagged with: python-requests
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88702579
type: Question
has answer: http://stackoverflow.com/a/50849979
score: 2
has body: I have a simple Get request I'd like to make using Python's Request library. import requests HEADERS = {'user-agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5)' 'AppleWebKit/537.36 (KHTML, like Gecko)' 'Chrome/45.0.2454.101 Safari/537.36'), 'referer': 'http://stats.nba.com/scores/'} url = 'http://stats.nba.com/stats/playbyplayv2?EndPeriod=10&amp;EndRange=55800&amp;GameID=0021500281&amp;RangeType=2&amp;Season=2016-17&amp;SeasonType=Regular+Season&amp;StartPeriod=1&amp;StartRange=0' response = requests.get(url, timeout=5, headers=HEADERS) However, when I make the requests.get call, I get the error requests.exceptions.ReadTimeout: HTTPConnectionPool(host='stats.nba.com', port=80): Read timed out. (read timeout=5). But I am able to copy/paste that url into my browser and view the resulting JSON. Why is requests not able to get the result?
downvote count: 0
answer count: 1
has title: Python Requests Get not Working
accepted answer: http://stackoverflow.com/a/50849979
favorite count: 0

http://stackoverflow.com/a/53924999
answers question: http://stackoverflow.com/q/50751672
score: 0
has body: Foursquare gives the number of check-ins for a venue under beenHere element, only if you have already checked-in on that venue before. You can see the question; How can I get checkins in a certain location on Foursquare?
type: Answer

http://stackoverflow.com/comment/88641044
type: Comment
has text: Your output is not the same as the `New_list` in the question.
score: 1
comment on: http://stackoverflow.com/a/50818009
type: AnswerComment

http://stackoverflow.com/comment/88549084
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50770784
score: 1
has text: It's important to have the same field name, so Django will not have trouble to filter and order both

http://stackoverflow.com/comment/134723226
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/63487037
has text: `len(dataset)` also works for Tensorflow `>=2.3` (without having to convert to a `list` first). The main difference with calling `dataset.cardinality()` directly seems to be that `len(dataset)` converts the result into a native Python `int`.
score: 1

http://stackoverflow.com/a/50708519
type: Answer
has body: from collections import defaultdict dictionary = defaultdict(int) x = { '1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4} } for key, numbers in x.items(): for key, num in numbers.items(): dictionary[key] += num x['total'] = {key: value for key, value in dictionary.items()} print(x) We can create a default dict to iterate through each of they key, value pairs in the nested dictionary and sum up the total for each key. That should enable a to evaluate to 3 and b to evaluate to 7. After we increment the values we can do a simple dictionary comprehension to create another nested dictionary for the totals, and make a/b the keys and their sums the values. Here is your output: {'1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4}, 'total': {'a': 3, 'b': 7}}
score: 0
answers question: http://stackoverflow.com/q/50707632

http://stackoverflow.com/comment/88639224
has text: This doesnt seem to work, the error is now : ValueError: Error when checking input: expected conv1d_1_input to have shape (16, 260) but got array with shape (260, 16)
comment on: http://stackoverflow.com/a/50809725
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50778421
downvote count: 0
has body: One way from apply df.groupby('ID')'Value1','Value2'.apply(lambda x : x.reset_index(drop=True)) Out[662]: Value1 Value2 ID 1 0 3 12 1 4 13 2 5 14 3 6 15 4 7 16 2 0 8 17 1 9 18 2 10 19 3 11 20
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50778334

http://stackoverflow.com/a/50792363
answers question: http://stackoverflow.com/q/50789537
has body: This error message... WebDriverException: 'geckodriver' executable needs to be in PATH. ...implies that the GeckoDriver was not found within the directories you have mentioned within your PATH variable. Solution As you are using ipython you can download the latest GeckoDriver from mozilla/geckodriver and place it anywhere within your system. While initializing the new WebDriver/WebClient session pass the absolute path of the GeckoDriver binary through the executable_path argument as follows: from selenium import webdriver driver = webdriver.Firefox(executable_path='/path/to/geckodriver')
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/88612817
has comment: http://stackoverflow.com/comment/88609933

alexa-skills-kit
tag name: alexa-skills-kit
type: Tag
tags question: http://stackoverflow.com/q/50792833

http://stackoverflow.com/comment/88702674
type: Comment
has text: Thanks, I got it work and generated the UI page. However, I get this error for gpfdist - ERROR: http response code 400 from gpfdist (gpfdist://xxxxxxx:8010/foo#transform=sessions): HTTP/1.0 400 invalid request (unsupported input #transform) (url_curl.c:454) (seg5 slice1 sdw1.gphd.local:1030 pid=419546) (cdbdisp.c:1322)
comment on: http://stackoverflow.com/a/50840391
score: 0
type: AnswerComment

http://stackoverflow.com/a/50806762
answers question: http://stackoverflow.com/q/50793134
has body: You can just add as many results you calls you want to do to side_effect mock_datetime.utcnow.side_effect = [datetime.utcnow() + timedelta(days=1), datetime.utcnow() + timedelta(days=2)]
accepted answer of: http://stackoverflow.com/q/50793134
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88628506
upvote count: 2

http://stackoverflow.com/comment/88647075
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50800333
has text: @MauroBaraldi: have you even tried that? it's a no-op.
type: Comment

http://stackoverflow.com/q/50719532
has answer: http://stackoverflow.com/a/50733742
downvote count: 0
has answer: http://stackoverflow.com/a/50719709
tagged with: mysql
has body: I am trying to import data from excel to MySQl below is my code , problem here is that it only writes the last row from my excel sheet to MySQl db and i want it to import all the rows from my excel sheet. import pymysql import xlrd book = xlrd.open_workbook('C:\SqlExcel\Backup.xlsx') sheet = book.sheet_by_index(0) # Connect to the database connection = pymysql.connect(host='localhost', user='root', password='', db='test') cursor = connection.cursor() query = """INSERT INTO report_table (FirstName, LastName) VALUES (%s, %s)""" for r in range(1, sheet.nrows): fname = sheet.cell(r,1).value lname = sheet.cell(r,2).value values = (fname, lname) cursor.execute(query, values) connection.commit() cursor.close() connection.close()
type: Question
has answer: http://stackoverflow.com/a/50719747
accepted answer: http://stackoverflow.com/a/50719747
upvote count: 2
has title: importing from excel to mysql
has answer: http://stackoverflow.com/a/50721667
possible better answer: http://stackoverflow.com/a/50719709
has comment: http://stackoverflow.com/comment/88447571
has comment: http://stackoverflow.com/comment/88447414
favorite count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/88447929
has answer: http://stackoverflow.com/a/50719725
tagged with: python
tagged with: excel
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/50752579
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: pygame
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: macros
possible better answer: http://stackoverflow.com/a/50752625
type: Question
has body: I have been looking for a way to make an autoclicker, since I haven't had any experience with clicking/typing in Python via a macro. I wanted the program to be able to detect when I press a button (F1) and start clicking constantly until I press the stop button (F2); unfortunately, my code won't output the cps variable and the x and y variable. I just need to be able to detect that it's working there to move on to my actual clicking. Basically, I'm asking how to fix the key detection. Python version: 3.6.5 EDIT: i know it checks for 1 and 2, the f1 was opening a python help screen when pressed- so for now im just doing 1 and 2 import random, pygame, pyautogui, time loop = 1 on = 0 pygame.init() while(loop == 1): key = pygame.key.get_pressed() if(key[pygame.K_1]): on = 1 elif(key [pygame.K_2]): on = 0 if(on == 1): x,y = pygame.mouse.get_pos() cps = random.randint(10,20) print(cps, x,y)
has title: macro program not working
answer count: 2
has answer: http://stackoverflow.com/a/50764659
tagged with: keypress
accepted answer: http://stackoverflow.com/a/50764659
upvote count: 1
has answer: http://stackoverflow.com/a/50752625

http://stackoverflow.com/comment/88532565
type: AnswerComment
has text: `A = np.array([[1,2],[3,4]]); idx = np.array([[1],[1]]); res = A[idx, idx]` gives `[4, 4]`. Unless I've misread, OP expects `[2, 4]`.
type: Comment
comment on: http://stackoverflow.com/a/50762411
score: 0

http://stackoverflow.com/comment/88468606
score: 0
has text: this is great! "Just" one thing: Is it possible for the rounding to return closest value (now it is either hard down or hard up)?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50724001

http://stackoverflow.com/comment/88666816
type: QuestionComment
comment on: http://stackoverflow.com/q/50831202
score: 0
has text: At least you tried
type: Comment

http://stackoverflow.com/comment/88704144
type: QuestionComment
comment on: http://stackoverflow.com/q/50850655
type: Comment
score: 0
has text: id is basically a number that's rising as i keep adding to response

http://stackoverflow.com/comment/88588633
has text: you can `return dataframe`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50791347

http://stackoverflow.com/comment/136458802
type: Comment
has text: @P-Gn "But when those threads need to synchronize, such as when you compute a sum, then the result may depend on the order of the summation, and in turn, on the order in which thread ended first."? But isn't a sum also a mathematical operation that shouldn't depend on the ordering? Can you elaborate on this?
score: 0
comment on: http://stackoverflow.com/a/50746919
type: AnswerComment

http://stackoverflow.com/comment/88536553
has text: Do not post code as an image! Please read [this](https://stackoverflow.com/help/mcve) and create an MCVE
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50764245
score: 1

http://stackoverflow.com/comment/88662505
type: QuestionComment
comment on: http://stackoverflow.com/q/50828895
has text: I suspect you want `for a in sent_vectors[1]: idx = np.where(np.isnan(a)`. As it is you aren't doing anything with the result of `np.where`. Why are you doing it?
score: 0
type: Comment

http://stackoverflow.com/comment/88671044
type: QuestionComment
comment on: http://stackoverflow.com/q/50833369
has text: What version of SQLA?
score: 0
type: Comment

http://stackoverflow.com/comment/88564978
type: QuestionComment
has text: @wiesion that works! do i need to set a urlpattern for 127.0.0.1:8000/ ? sorry if this is a dumb question, i'm very new to this!
score: 0
comment on: http://stackoverflow.com/q/50778866
type: Comment

http://stackoverflow.com/q/50833581
has comment: http://stackoverflow.com/comment/88671154
accepted answer: http://stackoverflow.com/a/50833831
score: 0
answer count: 1
tagged with: python
type: AnsweredQuestion
has title: Cannot get insertion sort in python code below to work
has answer: http://stackoverflow.com/a/50833831
has body: I have the following code that seeks to perform an insertion sort on the array 'numbers'. (and print the sorted array) There appears to be a logic error in the algorithm, but I cannot spot it as it seems to make sense. Can anyone suggest a solution using the existing code with a suitable explanation? numbers=[4,1,2,5,3] for i in range(len(numbers)-1): position=1 while position&gt;0 and numbers[position]&lt;numbers[position-1]: #print("Position:",numbers[position]) #print("Position-1:",numbers[position-1]) temp=numbers[position-1] numbers[position-1]=numbers[position] numbers[position]=temp #print("New value of position",numbers[position]) position=position+1 print(numbers) print("Insertion Sort)
tagged with: error-handling
tagged with: insertion
type: Question
tagged with: algorithm
tagged with: sorting

http://stackoverflow.com/q/50828262
has answer: http://stackoverflow.com/a/51331196
favorite count: 0
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51331196
type: Question
has answer: http://stackoverflow.com/a/50944989
tagged with: nltk
tagged with: naivebayes
has answer: http://stackoverflow.com/a/50974659
has title: After training my own classifier with nltk, how do I load it in textblob?
has comment: http://stackoverflow.com/comment/88867393
answer count: 3
has body: The built-in classifier in textblob is pretty dumb. It's trained on movie reviews, so I created a huge set of examples in my context (57,000 stories, categorized as positive or negative) and then trained it using nltk. I tried using textblob to train it but it always failed: with open('train.json', 'r') as fp: cl = NaiveBayesClassifier(fp, format="json") That would run for hours and end in a memory error. I looked at the source and found it was just using nltk and wrapping that, so I used that instead, and it worked. The structure for nltk training set needed to be a list of tuples, with the first part was a Counter of words in the text and frequency of appearance. The second part of tuple was 'pos' or 'neg' for sentiment. &gt;&gt;&gt; train_set = [(Counter(i["text"].split()),i["label"]) for i in data[200:]] &gt;&gt;&gt; test_set = [(Counter(i["text"].split()),i["label"]) for i in data[:200]] # withholding 200 examples for testing later &gt;&gt;&gt; cl = nltk.NaiveBayesClassifier.train(train_set) # &lt;-- this is the same thing textblob was using &gt;&gt;&gt; print("Classifier accuracy percent:",(nltk.classify.accuracy(cl, test_set))*100) ('Classifier accuracy percent:', 66.5) &gt;&gt;&gt;&gt;cl.show_most_informative_features(75) Then I pickled it. with open('storybayes.pickle','wb') as f: pickle.dump(cl,f) Now... I took this pickled file, and re opened it to get the nltk.classifier 'nltk.classify.naivebayes.NaiveBayesClassifier'&gt; -- and tried to feed it into textblob. Instead of from textblob.classifiers import NaiveBayesClassifier blob = TextBlob("I love this library", analyzer=NaiveBayesAnalyzer()) I tried: blob = TextBlob("I love this library", analyzer=myclassifier) Traceback (most recent call last): File "&lt;pyshell#116&gt;", line 1, in &lt;module&gt; blob = TextBlob("I love this library", analyzer=cl4) File "C:\python\lib\site-packages\textblob\blob.py", line 369, in __init__ parser, classifier) File "C:\python\lib\site-packages\textblob\blob.py", line 32…
tagged with: textblob
downvote count: 0
possible better answer: http://stackoverflow.com/a/50974659

http://stackoverflow.com/a/50731594
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88471402
downvote count: 0
answers question: http://stackoverflow.com/q/50731572
has body: I will recommend using sklearn.model_selection.StratifiedKFold Base on the doc : Provides train/test indices to split data in train test sets. This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class. If you are using the resample . For example for a classifier model, it is hard to make each sub data contains all the classes.
has comment: http://stackoverflow.com/comment/88471453
has comment: http://stackoverflow.com/comment/88471557
type: Answer

http://stackoverflow.com/q/50733262
has comment: http://stackoverflow.com/comment/88474488
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/50733345
downvote count: 1
type: AnsweredQuestion
has body: HTML div class that contains the data I wish to print &lt;div class="gs_a"&gt;LR Binford&amp;nbsp;- American antiquity, 1980 - cambridge.org &lt;/div&gt; This is my code so far : from selenium import webdriver def Author (SearchVar): driver = webdriver.Chrome("/Users/tutau/Downloads/chromedriver") driver.get ("https://scholar.google.com/") SearchBox = driver.find_element_by_id ("gs_hdr_tsi") SearchBox.send_keys(SearchVar) SearchBox.submit() At = driver.find_elements_by_css_selector ('#gs_res_ccl_mid &gt; div:nth-child(1) &gt; div.gs_ri &gt; div.gs_a') print (At) Author("dog") All that comes out when I print is selenium.webdriver.remote.webelement.WebElement (session="9aa956e2bd51f510dd626f6937b01c0e", element="0.6506218589189958-1") not the text I am new to selenium Help is appreciated
linked to: http://stackoverflow.com/q/20996392
type: Question
has comment: http://stackoverflow.com/comment/88475153
has comment: http://stackoverflow.com/comment/88474345
score: 0
answer count: 3
has title: Trying to get Get text out of div class using selenium in python
has answer: http://stackoverflow.com/a/50735716
tagged with: python
possible better answer: http://stackoverflow.com/a/50733351
favorite count: 0
has answer: http://stackoverflow.com/a/50733351
has comment: http://stackoverflow.com/comment/88474336
accepted answer: http://stackoverflow.com/a/50735716

http://stackoverflow.com/q/50743706
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50753090
type: Question
downvote count: 0
tagged with: file-association
tagged with: windows
answer count: 1
has comment: http://stackoverflow.com/comment/88495078
favorite count: 0
has comment: http://stackoverflow.com/comment/88495084
has title: Set Windows file type association for a specific file only
has comment: http://stackoverflow.com/comment/88495726
has comment: http://stackoverflow.com/comment/88508223
tagged with: python
has comment: http://stackoverflow.com/comment/88495562
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50753090
has body: How do I programmatically associate a file with a specific "opens with" action? That is, I am creating filename.py on a Windows computer, putting it on the desktop. I want double-clicking it to run the python intrepreter, rather than opening the text editor. I can do this with the Properties window, but I want to do this automatically, when I create it (from another python program). I do not want to set up a universal file extension, because I want double-clicking on .py files to result in bringing up the editor, not running the program. It is only for this particular file that I want that behavior. I can do this from the Windows GUI; I want to know how to do it programmatically. There is no installer. The Python .py program is being created from another python program. It is being created directly in the file system with a open("filename.py").write(file_contents). The environment is Windows 7

http://stackoverflow.com/q/50778770
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/88565312
has comment: http://stackoverflow.com/comment/88567659
type: Question
tagged with: group-by
has comment: http://stackoverflow.com/comment/88566413
upvote count: 13
tagged with: categorical-data
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/52707794
has body: MCVE df = pd.DataFrame({ 'Cat': ['SF', 'W', 'F', 'R64', 'SF', 'F'], 'ID': [1, 1, 1, 2, 2, 2] }) df.Cat = pd.Categorical( df.Cat, categories=['R64', 'SF', 'F', 'W'], ordered=True) As you can see, I've define an ordered categorical column on Cat. To verify, check; 0 SF 1 W 2 F 3 R64 4 SF 5 F Name: Cat, dtype: category Categories (4, object): [R64 &lt; SF &lt; F &lt; W] I want to find the largest category PER ID. Doing groupby + max works. df.groupby('ID').Cat.max() ID 1 W 2 F Name: Cat, dtype: object But I don't want ID to be the index, so I specify as_index=False. df.groupby('ID', as_index=False).Cat.max() ID Cat 0 1 W 1 2 SF Oops! Now, the max is taken lexicographically. Can anyone explain whether this is intended behaviour? Or is this a bug? Note, for this problem, the workaround is df.groupby('ID').Cat.max().reset_index(). Note, &gt;&gt;&gt; pd.__version__ '0.22.0'
answer count: 1
has comment: http://stackoverflow.com/comment/92047470
has title: Weird behaviour with groupby on ordered categorical columns
favorite count: 0
has comment: http://stackoverflow.com/comment/88564453

http://stackoverflow.com/a/51060721
accepted answer of: http://stackoverflow.com/q/50842160
has comment: http://stackoverflow.com/comment/109373282
score: 38
has comment: http://stackoverflow.com/comment/126182285
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/122445442
upvote count: 38
has comment: http://stackoverflow.com/comment/140036168
has comment: http://stackoverflow.com/comment/126207056
answers question: http://stackoverflow.com/q/50842160
has comment: http://stackoverflow.com/comment/126205696
has comment: http://stackoverflow.com/comment/126205715
type: AcceptedAnswer
has body: I added a couple of things to make your code work as you would like Add %matplotlib inline at the top of the cell Replace your display(fig) calls with plt.show(fig) calls. %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import ipywidgets as widgets import numpy as np out1 = widgets.Output() out2 = widgets.Output() data1 = pd.DataFrame(np.random.normal(size = 50)) data2 = pd.DataFrame(np.random.normal(size = 100)) tab = widgets.Tab(children = [out1, out2]) tab.set_title(0, 'First') tab.set_title(1, 'Second') display(tab) with out1: fig1, axes1 = plt.subplots() data1.hist(ax = axes1) plt.show(fig1) with out2: fig2, axes2 = plt.subplots() data2.hist(ax = axes2) plt.show(fig2)
has comment: http://stackoverflow.com/comment/126205691

http://stackoverflow.com/comment/88446935
type: Comment
comment on: http://stackoverflow.com/a/50719143
type: AnswerComment
has text: It works in this case. But, here all other columns will be joined except column[0] in both cases. But, I want to join specifically "NAME", "ACC" from fields1.csv and "SCORE", "TEAM" from field2.csv. If there are other columns then it should be skipped.
score: 0

http://stackoverflow.com/comment/88657553
has text: Your explanation points to the `sort` method, but your example uses the `sorted` function.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50826410
score: 1

http://stackoverflow.com/comment/88643636
type: QuestionComment
comment on: http://stackoverflow.com/q/50816718
score: 1
has text: Yes, the first instance has to set a non-NULL timeout value. I don't like how ctypes automatically passes a parameter by reference that's declared as pointer type. It's more self-documenting to use `byref(LARGE_INTEGER(0))`. Also, I think passing 0 for the timeout is an invalid parameter. It has to be a relative (negative) value. FYI, `-50 * 10 * 1000` is 50 ms, the default used in the Windows API.
type: Comment

http://stackoverflow.com/q/50833980
has answer: http://stackoverflow.com/a/61891151
has comment: http://stackoverflow.com/comment/88742775
has comment: http://stackoverflow.com/comment/88775131
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50834410
linked to: http://stackoverflow.com/q/26655888
tagged with: django
has body: I'm writing a User system that cannot login at the same time. If the account in login state in somewhere, and someone login the same account in other position. The latter one will be logged in. And the previous will be logged out. I'm using a model with oneToOneField associated to the User model, And save session ids of this user. The code is like below. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .myModels import JSONField class Profile(models.Model): user = models.OneToOneField(User, models.CASCADE) sessionids = JSONField(null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) The JSONField is a field that using textField to store JSON string. When a user login, I go to get all session ids of this user and delete all the session ids. Then I add current session id to the Profile. By doing this, I can logout in the previous position. the code is like below. def login(request): if request.method == "POST": if request.user.is_authenticated: return HttpResponse("the user session is authenticated.") username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) #remove cur user all sessions sessionidsToDelete = request.user.profile.sessionids if sessionidsToDelete != None: sessions = Session.objects.filter(session_key__in=sessionidsToDelete) for session in sessions: session.delete() #add cur user sessions sessionidsToStore = user.profile.sessionids print("sessionidsToStore = ") print(sessionidsToStore) print("sessionidsToDelete = ") print(sessionidsToDelete) if sessionidsToStore== None: sessionidsToStore = [] else: sessionidsToStore = list(set(sessionidsToStore) - set(sessionidsToDelete)) print("sessioni…
type: Question
has comment: http://stackoverflow.com/comment/88671920
upvote count: 9
tagged with: session
score: 9
has title: How to prevent multiple login in Django
has comment: http://stackoverflow.com/comment/88742949
answer count: 2
accepted answer: http://stackoverflow.com/a/50834410
has comment: http://stackoverflow.com/comment/88700529
downvote count: 0
possible better answer: http://stackoverflow.com/a/61891151
favorite count: 0

http://stackoverflow.com/comment/88530052
comment on: http://stackoverflow.com/a/50728741
score: 0
type: AnswerComment
type: Comment
has text: what do you think a solution for the background color?

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/50709381
tags question: http://stackoverflow.com/q/50787134
tags question: http://stackoverflow.com/q/50826442
type: Tag

http://stackoverflow.com/comment/88854239
score: 0
type: AnswerComment
type: Comment
has text: sorry to be a pain. I was wondering if I could convert each row of `xy data` to a list of lists or the count of coordinates in each bin into a `df`. So using the above example, Red would have 3 in Bin 1, 1 in Bin 2, 6 in Bin 3, 0 in Bin 4.
comment on: http://stackoverflow.com/a/50812302

http://stackoverflow.com/comment/91975280
comment on: http://stackoverflow.com/q/50716249
type: QuestionComment
has text: hi @ASML, take a look at this issue from Intel [here](https://github.com/IntelRealSense/librealsense/issues/2204).
type: Comment
score: 0

http://stackoverflow.com/a/50807244
score: 1
has comment: http://stackoverflow.com/comment/88626395
downvote count: 0
type: Answer
has body: You can try this model = input("Enter model name: ") year = input("year: ") url = "http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/"+year+"/make/ACURA/model/"+model+"?format=csv" import urllib.request with urllib.request.urlopen(url) as response: html = response.read() with open(model+year+".csv", "w") as f: f.write(html) you can add some more variables to your url. Then for reading you can use the pandas package. import pandas as pd vechiles = pd.read_csv("vichles.csv")
answers question: http://stackoverflow.com/q/50807129
upvote count: 1

http://stackoverflow.com/comment/88651014
type: QuestionComment
comment on: http://stackoverflow.com/q/50822206
has text: You say you have successfully got the time. Please show us the code.
score: 0
type: Comment

http://stackoverflow.com/q/50779567
linked to: http://stackoverflow.com/q/11279331
tagged with: unicode
has answer: http://stackoverflow.com/a/50779751
has title: How to convert response.text to json in Scrapy
has body: I am scraping the financial data from below link using Scrapy: Financial Data from Tencent The reponse.body is like below: I have tried to split the response using regular regression then convert it to json but it shows no json object, here is my code: import scrapy import re import json class StocksSpider(scrapy.Spider): name = 'stocks' allowed_domains = ['web.ifzq.gtimg.cn'] start_urls = ['http://web.ifzq.gtimg.cn/appstock/hk/HkInfo/getFinReport?type=3&amp;reporttime_type=1&amp;code=00001&amp;startyear=1990&amp;endyear=2016&amp;_callback=jQuery11240339550$'] def start_requests(self): for url in self.start_urls: yield scrapy.Request(url=url, callback=self.parse, #endpoint='render.json', # optional; default is render.html #splash_url='&lt;url&gt;', # optional; overrides SPLASH_URL #slot_policy=scrapy_splash.SlotPolicy.PER_DOMAIN, # optional ) def parse(self, response): try: json_data = re.search('\{\"data\"\:(.+?)\}\}\]', response.text).group(1) except AttributeError: json_data = '' #print json_data loaded_json = json.loads(json_data) print loaded_json It throws an error saying that no json object can be decoded: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 102, in iter_errback yield next(it) File "/usr/local/lib/python2.7/dist-packages/scrapy_splash/middleware.py", line 156, in process_spider_output for el in result: File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/offsite.py", line 30, in process_spider_output for x in result: File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/referer.py", line 339, in &lt;genexpr&gt; return (_set_referer(r) for r in result or ()) File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/urllength.py", line 37, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/depth.py", line 58, in &lt;genexpr&gt; return (r for r in result or () if…
tagged with: python
has comment: http://stackoverflow.com/comment/88566155
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50779751
tagged with: web-scraping
tagged with: scrapy
has comment: http://stackoverflow.com/comment/88566094
type: Question
has answer: http://stackoverflow.com/a/50780263
possible better answer: http://stackoverflow.com/a/50779731
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50779731
score: 0
answer count: 3

http://stackoverflow.com/q/50737364
upvote count: 3
tagged with: sbml
has body: I would like to do a FVA only for selected reactions, in my case on transport reactions between compartments (e.g. between the cytosol and mitochondrion). I know that I can use selected_reactions in doFVA like this: import cbmpy as cbm mod = cbm.CBRead.readSBML3FBC('iMM904.xml.gz') cbm.doFVA(mod, selected_reactions=['R_FORtm', 'R_CO2tm']) Is there a way to get the entire list of transport reactions, not only the two I manually added? I thought about selecting the reactions based on their ending tm but that fails for 'R_ORNt3m' (and probably other reactions, too). I want to share this model with others. What is the best way of storing the information in the SBML file? Currently, I would store the information in the reaction annotation as in this answer. For example mod.getReaction('R_FORtm').setAnnotation('FVA', 'yes') which could be parsed.
accepted answer: http://stackoverflow.com/a/50745318
type: Question
has title: Flux variability analysis only for transport reactions between compartments?
linked to: http://stackoverflow.com/q/50475867
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50745318
tagged with: python
tagged with: cbmpy
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/94740573
type: AnswerComment
type: Comment
has text: `model` is any of the model instances, e.g. OLS or GLM. `results` is the corresponding Results instance returned by `model.fit()`. e.g. `model = OLS(y, x)` and `results = model.fit()`
score: 1
comment on: http://stackoverflow.com/a/50844691

http://stackoverflow.com/q/50747158
score: 0
has comment: http://stackoverflow.com/comment/88502408
has title: Python parsing XML using ElementTree based on IF Conditions
has comment: http://stackoverflow.com/comment/88502920
tagged with: scripting
has comment: http://stackoverflow.com/comment/88502356
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
tagged with: python
has answer: http://stackoverflow.com/a/50747544
type: AnsweredQuestion
type: Question
has body: Using Python, I'm trying to parse an XML file to retrieve the value of an element based on the value of the 'name' attribute AND the value of a child element based on the value of the 'name' attribute as well. The conditions are: If Category attribute is 3 in 'test' element, then grab the value of the 'name' attribute AND Grab the value of the 'color' element IF the value of the 'name' attribute is 'enable' Example Code: blue yellow red orange green purple white gray Expected Results: 1 red 2 white My Current Code: import xml.etree.ElementTree as ET tree = ET.parse('C:/colors.xml') root = tree.getroot() for test in root.getiterator('test'): if test.attrib['category']=="3": print test.attrib['name'] This gives me: 1 2 I've tried a nested FOR to get the value of the color element, but everything I tried seems to start from the beginning. Any assistance would be appreaciated! Thanks
answer count: 1
accepted answer: http://stackoverflow.com/a/50747544

http://stackoverflow.com/comment/88620441
comment on: http://stackoverflow.com/q/50807336
score: 0
type: Comment
type: QuestionComment
has text: `while city_temp:` keeps looping until `city_temp` is empty. Since `city_temp` is a list, and you never modify that list anywhere, if it's not empty at the start, it won't ever become empty, so you'll loop forever. To fix this, just get rid of the `while city_temp:` loop. You're already looping over all the lines with `for each_line in city_temp:`, which is all you need.

http://stackoverflow.com/comment/88481371
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50736550
has text: Correct me if I'm wrong, but I think you should use `yield` instead of `return` at the end of `parse` function.

http://stackoverflow.com/comment/88645952
score: 0
type: Comment
type: QuestionComment
has text: Can you show us the whole code please
comment on: http://stackoverflow.com/q/50819677

http://stackoverflow.com/q/50711572
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50711669
upvote count: 1
tagged with: python
tagged with: heroku
has title: Heroku runs ok local but deployment app crash flask and python
downvote count: 1
type: Question
tagged with: flask
score: 0
has body: I'm trying to deploy this super actually silly app. still, have no idea what i am doing wrong. __import__(module) 2018-06-06T02:39:57.219756+00:00 app[web.1]: File "/app/main.py", line 1, in &lt;module&gt; 2018-06-06T02:39:57.219757+00:00 app[web.1]: from flaskr import create_app 2018-06-06T02:39:57.219762+00:00 app[web.1]: ImportError: cannot import name 'create_app' 2018-06-06T02:39:57.219911+00:00 app[web.1]: [2018-06-06 02:39:57 +0000] [8] [INFO] Worker exiting (pid: 8) 2018-06-06T02:39:57.249096+00:00 app[web.1]: [2018-06-06 02:39:57 +0000] [4] [INFO] Shutting down: Master 2018-06-06T02:39:57.249207+00:00 app[web.1]: [2018-06-06 02:39:57 +0000] [4] [INFO] Reason: Worker failed to boo that's heroku's error log. this is my Procfile web: gunicorn -b 0.0.0.0:$PORT main:create_app And my colder routes looks something likes this... /pysomething/flasrk/"heres goes my files" Weird thing is that heroku local works ok. But when deploy it crashes.
answer count: 1
favorite count: 0
tagged with: gunicorn

http://stackoverflow.com/a/50827085
has comment: http://stackoverflow.com/comment/88682358
has comment: http://stackoverflow.com/comment/88693266
upvote count: 2
has body: The name you need to use is wxPython not wx. (https://pypi.org/project/wxPython/) Also, you can avoid the SSL errors by updating your Python and pip to the newest versions.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50805588
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50805588

http://stackoverflow.com/q/50854133
has comment: http://stackoverflow.com/comment/88711235
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50854371
has title: How to find approximate coordinates from four different lists od coordinates
tagged with: python
has body: I have four lists representing X and Y coordinates of different points in lists A and B so X_A, Y_A, X_B, Y_B A ] ['a', 'b', 'c', 'd', 'e', 'f'] X_A = [1.0, 2.2, 3.0, 4.0, 5.001, 6.0] Y_A = [0.0, 2.0, 4.0, 6.1, 8.0, 0.0] B = ['k', 'l', 'm', 'n', 'o', 'p'] X_B = [1.0, 3.0, 5.0005, 7.0, 9.1, 11.0] Y_B = [0.0, 1.0, 8.0, 2.0, 8.0, 0.1] The above is read as 'a' has coordinates (1.0, 0.0) and 'l' has coordinates (3.0, 1.0) I would like to add items from A to Node_A list and items from B to Node_B the corresponding coordinates of the elements of lists A and B satisfy an error margin: (X_A - X_B) &lt;= error and (Y_A - Y_B) &lt;= error I have the below code which I believe should be doing the job but it does not seem to work and I don't understand why, any help is appreciated! Node_A, Node_B = [], [] error = 1e-2 i, j = 0, 0 for lo1,la1 in zip(X_A, Y_A): for lo2,la2 in zip(X_B, Y_B): if abs(lo1 - lo2) &lt;= error and abs(la1 == la2) &lt;= error: Node_A.append(A[i]) Node_B.append(B[j]) break j += 1 i += 1 j = 0 The desired output should be as below as they 'a' coordinates from A equal 'k' coordinates from B and 'e' coordinates satisfy the error margin and thus approximately equal to 'm' coordinates: Node_A: ['a', 'e'] Node_B: ['k', 'm'] Instead I get Node_A: ['c'] and Node_B: ['l']
has comment: http://stackoverflow.com/comment/88711249
tagged with: list
has comment: http://stackoverflow.com/comment/88711319
score: 1
upvote count: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88711327
has comment: http://stackoverflow.com/comment/88711166
answer count: 2
has comment: http://stackoverflow.com/comment/88711279
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50854317

http://stackoverflow.com/q/50703556
downvote count: 0
score: 7
favorite count: 0
linked to: http://stackoverflow.com/q/8000022
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50705692
tagged with: python
tagged with: django-templates
tagged with: django
upvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/88416666
has body: I have a dictionary like this : myDict = {key1: item1, key2: item2} How can I get item1 by providing key1 in django template and more if I have a nested dict like this: myDict2 = {key1: {key11: item11, key12: item12}, key2: {key21: item21, key22: item22}} for example how can I get item22 using key22 I know {{ myDict[key1] }} doesn't work
has title: get dictionary value by key in django template
has answer: http://stackoverflow.com/a/50706246
linked to: http://stackoverflow.com/q/21623013
answer count: 2

http://stackoverflow.com/comment/88410711
has text: @Jaxi The r before the path removed the error. But the .cmd file doesn't open.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50700072

http://stackoverflow.com/comment/88660096
type: QuestionComment
type: Comment
has text: The WSGI application entry point must be called `application` for mod_wsgi. See https://stackoverflow.com/a/24048455/4902099
score: 0
comment on: http://stackoverflow.com/q/50827406

http://stackoverflow.com/q/50823753
tagged with: python
tagged with: urllib
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50823821
downvote count: 0
has answer: http://stackoverflow.com/a/72804599
has comment: http://stackoverflow.com/comment/128594245
tagged with: urllib3
score: 2
favorite count: 0
tagged with: python-3.x
has title: concurrent connections in urllib3
upvote count: 2
has body: Using a loop to make multiple requests to various websites, how is it possible to do this with a proxy in urllib3? The code will read in a tuple of URLs, and use a for loop to connect to each site, however, currently it does not connect past the first url in the tuple. There is a proxy in place as well. urls = ['https://URL1.com', 'http://URL2.com', 'http://URL3.com'] for url in urls: http = ProxyManager("PROXY-PROXY") http_get = http.request('GET', url, preload_content=False).read().decode() I have removed the urls and proxy information from the above code. The first URL in the tuple will run fine, but after this, nothing else occurs, just waiting. I have tried the clear() method to reset the connection for each time in the loop.
type: UnansweredQuestion

calculus
tags question: http://stackoverflow.com/q/50816096
tag name: calculus
type: Tag

http://stackoverflow.com/comment/88480143
type: Comment
has text: Yeah, I did check those files, but nothing wired to be found. This happens after I add codes to save the network model, but the problem is not fixed even I delete those codes.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50711313

http://stackoverflow.com/q/50843878
has body: I've set up a webhook in a chat room in my Google Hangouts Chat. I can successfully run their example code, which generates a message from the bot associated with the webhook in the chat: from httplib2 import Http from json import dumps # # Hangouts Chat incoming webhook quickstart # def main(): url = '&lt;INCOMING-WEBHOOK-URL&gt;' bot_message = { 'text' : 'Hello World!'} message_headers = { 'Content-Type': 'application/json; charset=UTF-8'} http_obj = Http() response = http_obj.request( uri=url, method='POST', headers=message_headers, body=dumps(bot_message), ) print(response) if __name__ == '__main__': main() But when I try to sent a Numpy Array with the code: bot_message = { 'text' : NumpyArrayObject} I get the error: TypeError: Object of type 'ndarray' is not JSON serializable Using Python list I got the error: "description": "Invalid JSON payload received. Unknown name \\"text\\" at \'message\': Proto field is not repeating, cannot start list."\n }\n ]\n }\n ]\n }\n}\n') What should I do?
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/50881035
type: AnsweredQuestion
tagged with: google-hangouts
type: Question
has title: Sending Numpy array to a webhook for Hangouts Chat API with Python?
accepted answer: http://stackoverflow.com/a/50881035
favorite count: 0
linked to: http://stackoverflow.com/q/26646362
score: 0
answer count: 1

http://stackoverflow.com/q/50848942
tagged with: python
tagged with: gensim
has title: different result executing gensim examples
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: cosine-similarity
tagged with: document
has body: Below is a gensim's example, but whenever I execute it, it show different result, so I couldn't believe gensim works well. from gensim import corpora, models, similarities from collections import defaultdict documents = ["Human machine interface for lab abc computer applications", # 0 "A survey of user opinion of computer system response time", # 1 "The EPS user interface management system", # 2 "System and human system engineering testing of EPS", # 3 "Relation of user perceived response time to error measurement", # 4 "The generation of random binary unordered trees", # 5 "The intersection graph of paths in trees", # 6 "Graph minors IV Widths of trees and well quasi ordering", # 7 "Graph minors A survey"] # 8 stoplist = set('for a of the and to in'.split()) texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents] frequency = defaultdict(int) for text in texts: for token in text: frequency[token] += 1 texts = [[token for token in text if frequency[token] &gt; 1] for text in texts] dictionary = corpora.Dictionary(texts) corpus = [dictionary.doc2bow(text) for text in texts] lda = models.LdaModel(corpus, id2word=dictionary, num_topics=2) index = similarities.MatrixSimilarity(lda[corpus]) doc = "Human computer interaction" vec_bow = dictionary.doc2bow(doc.lower().split()) vec_lda = lda[vec_bow] sims = index[vec_lda] sims = sorted(enumerate(sims), key=lambda item: -item[1]) print(sims) print(lda.get_document_topics(vec_bow)) result [(0, 0.9986434), (4, 0.99792993), (2, 0.99722278), (3, 0.99651831), (1, 0.99158639), (5, 0.53059661), (6, 0.4146674), (8, 0.38019019), (7, 0.36143348)] [(0, 0.18366596), (1, 0.81633401)] [(1, 0.999605), (4, 0.9991864), (0, 0.998689), (5, 0.62957084), (6, 0.48837978), (8, 0.48152202), (3, 0.4541581), (7, 0.41751832), (2, 0.40637407)] [(0, 0.80285221), (1, 0.19714773)] [(7, 0.99957085), (8, 0.99660784), (0, 0.99202132), (5, 0.78449017), (6, 0.77530348), (2, 0.56972337), (3, 0.47117239), (4, 0.47092…
has comment: http://stackoverflow.com/comment/88705277
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/15067734
type: UnansweredQuestion
tagged with: similarity

http://stackoverflow.com/comment/88557586
comment on: http://stackoverflow.com/q/50773587
type: QuestionComment
has text: yes!!! the problem solved! thank you so much :)
score: 0
type: Comment

http://stackoverflow.com/comment/88691423
type: Comment
comment on: http://stackoverflow.com/a/50843926
has text: @InAFlash The solution works for any number of rows.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50801563
tagged with: python
has title: how to make a chat but in python
has answer: http://stackoverflow.com/a/50801883
score: -5
tagged with: bots
type: Question
downvote count: 5
has body: hello i am newbe on programming and i want some help with the thing i am trying to do 1 how can i connect my bot with the steam servers 2 lest say someone sends me a message on steam and i am away but i left steam open and the bot is running. and someone sends me a message how can i make the bot say something like this "right now (name) is away but you can leave your message on this chat box" 3 and if you can tell me how to do this in python i know how to create basic commands that is all thank you
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: steam

http://stackoverflow.com/q/50713808
has comment: http://stackoverflow.com/comment/88436732
has answer: http://stackoverflow.com/a/50714125
has comment: http://stackoverflow.com/comment/88436372
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/50714125
tagged with: python
has answer: http://stackoverflow.com/a/50714111
has comment: http://stackoverflow.com/comment/88436624
has comment: http://stackoverflow.com/comment/88436604
has body: I am trying to write a regex for the following: {u'device_type': u'Laptop'} I have tried [\W+\w]. What would the correct pattern be?
has title: Query for regex pattern in Python
possible better answer: http://stackoverflow.com/a/50714111
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88436697
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88436277

http://stackoverflow.com/a/50852707
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50852672
answers question: http://stackoverflow.com/q/50852672
score: 3
has comment: http://stackoverflow.com/comment/88708584
upvote count: 3
type: AcceptedAnswer
has body: Use zip with convert tuples to lists: df['list_score'] = [list(x) for x in zip(df['Score1'], df['Score2'])] Or: df['list_score'] = list(map(list, zip(df['Score1'], df['Score2']))) print (df) Name1 Name2 Score1 Score2 list_score 0 Bruce Jacob 3 4 [3, 4] 1 Aida Stephan 0 1 [0, 1] Performance: df = pd.concat([df] * 1000, ignore_index=True) In [105]: %timeit df['list_score'] = [list(x) for x in zip(df['Score1'], df['Score2'])] 851 µs ± 36.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [106]: %timeit df['list_score'] = list(map(list, zip(df['Score1'], df['Score2']))) 745 µs ± 35.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [107]: %timeit df['list_score'] = df'Score1', 'Score2'.apply(tuple, axis=1).apply(list) 35.5 ms ± 295 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) In [108]: %timeit df['list_score'] = df'Score1', 'Score2'.values.tolist() 949 µs ± 105 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) This was the setup used to generate the perfplot above: def list_comp(df): df['list_score'] = [list(x) for x in zip(df['Score1'], df['Score2'])] return df def map_list(df): df['list_score'] = list(map(list, zip(df['Score1'], df['Score2']))) return df def apply(df): df['list_score'] = df'Score1', 'Score2'.apply(tuple, axis=1).apply(list) return df def values(df): df['list_score'] = df'Score1', 'Score2'.values.tolist() return df def make_df(n): df = pd.DataFrame(np.random.randint(10, size=(n, 2)), columns=['Score1','Score2']) return df perfplot.show( setup=make_df, kernels=[list_comp, map_list, apply, values], n_range=[2**k for k in range(2, 15)], logx=True, logy=True, equality_check=False, # rows may appear in different order xlabel='len(df)')
type: Answer

http://stackoverflow.com/q/50776361
upvote count: 1
has answer: http://stackoverflow.com/a/50776391
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50776391
has title: Multi values or multi index pivot table in pandas
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: I have a sample data data table like import pandas as pd compnaies = ['Microsoft', 'Google', 'Amazon', 'Microsoft', 'Facebook', 'Google'] products = ['OS', 'Search', 'E-comm', 'E-comm', 'Social Media', 'OS'] count = [5,7,3,19,23,54] average = [1.2,3.4,2.4,5.2,3.2,4.4] df = pd.DataFrame({'company' : compnaies, 'product':products, 'count':count , 'average' : average}) df average company count product 0 1.2 Microsoft 5 OS 1 3.4 Google 7 Search 2 2.4 Amazon 3 E-comm 3 5.2 Microsoft 19 E-comm 4 3.2 Facebook 23 Social Media 5 4.4 Google 54 OS Now I want to create pivot view on both 'average' and 'count' but I am not able to define both values, here the sample code with one 'average' df.pivot_table(index='company', columns='product', values='average', fill_value=0) the output will be but I need the data in below format, can someone please help meanwhile I tried the stack, and group by which creates multi index data frame but it does not give desired output, I will share the code if needed desired output which I need to download in excel
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/50765997
upvote count: 9
has answer: http://stackoverflow.com/a/50766337
tagged with: dataframe
tagged with: multi-index
type: Question
score: 8
answer count: 1
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50766337
tagged with: python
has comment: http://stackoverflow.com/comment/130453500
has title: Pandas multiindex: get level values without duplicates
downvote count: 1
tagged with: indexing
has body: So I'm sure this is pretty trivial but I'm pretty new to python/pandas. I want to get a certain column (Names of my measurements) of my Multiindex as a list to use it in a for loop later to name and save my plots. I'm pretty confident in getting the data I need from my dataframe but i can't figure out how to get certain columns from my index. So actually while writing the question I kind of figured the answer out but it still seems kind of clunky. There has to be a direct command to do this. That would be my code: a = df.index.get_level_values('File') a = a.drop_duplicates() a = a.values
type: AnsweredQuestion

http://stackoverflow.com/comment/88552847
type: Comment
type: QuestionComment
has text: Do you mean digit 1 or number 1? I.e., should it count the list element, if it were 512? And what have you tried, why did it fail?
comment on: http://stackoverflow.com/q/50772361
score: 0

http://stackoverflow.com/q/50819839
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/25962114
has answer: http://stackoverflow.com/a/50819870
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50820125
linked to: http://stackoverflow.com/q/28766133
possible better answer: http://stackoverflow.com/a/50820125
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50819870
downvote count: 0
has body: I have about 5400 Excel files in multiple (sub)folders and want to load them into a single dataframe. The files only have 1 sheet and and can have up to 2000+ rows each. The total number of rows is expected to be 2 Million or more. My computer has SSD HD and 8GB memory, and is pretty fast. Still it takes hours to complete. Is there anything wrong with me code? I'd appreciate any tips. %%time files = glob.glob('asyncDatas/**/*.xlsx',recursive=True) df = pd.DataFrame() for num, fname in enumerate(files, start=1): print("File #{} | {}".format(num, fname)) if len(fname) &gt; 0: data = pd.read_excel(fname, 'Sheet0', index_col='Time', skiprows=3) df = df.append(data) df.head() My hunch is that the .append method takes too much time as it likely is dynamically re-allocate memory? Would .concat() maybe the better approach?
has title: Loading multiple Excel files into Pandas
tagged with: pandas
tagged with: python
favorite count: 0

http://stackoverflow.com/q/50813906
answer count: 2
possible better answer: http://stackoverflow.com/a/50814191
tagged with: dataframe
has body: def convert(): for url in url_list: news=Article(url) news.download() while news.download_state != 2: time.sleep(1) news.parse() l.append( {'Title':news.title, 'Text': news.text.replace('\n',' '), 'Date':news.publish_date, 'Author':news.authors} ) convert() df = pd.DataFrame.from_dict(l) df.to_csv('Amazon_try2'+'.csv',encoding='utf-8', index=False) The function convert() goes through a list of url and process each of them. Each url is a link to an article. I am fetching the important attributes of articles such as author, text etc and then storing this in a data frame. After that, I am converting data frame to a csv file. The script ran for about 5 hours as there were 589 urls in url_list. But I still couldn't get the csv file. Can somebody spot out where I am going wrong.
has answer: http://stackoverflow.com/a/50814276
has comment: http://stackoverflow.com/comment/88633428
score: 0
tagged with: python-newspaper
tagged with: python
accepted answer: http://stackoverflow.com/a/50814276
type: AnsweredQuestion
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50814191
type: Question
has title: I am trying to extract data from a website in python

http://stackoverflow.com/a/50786903
has body: Replying to the comment with a new answer: I think the way you are looking at it, it would be better to, instead of a list use a dictionary, this way you are able to store 2 items within the same parameters. mat = {} for i in Par['UWI']: for j in Chi['UWI']: if str(i)[0:9] == str(j)[0:9]: mat.update({str(i):str(j)}) This also makes looking for a perticular person easier, than finding that person and then working out wether it is the person before or after that is the link.
score: 0
answers question: http://stackoverflow.com/q/50751259
type: Answer

http://stackoverflow.com/comment/88658738
type: Comment
comment on: http://stackoverflow.com/a/50826972
has text: My answer has been fixed to be the exact answer to his homework, cheers!
type: AnswerComment
score: 0

http://stackoverflow.com/q/50801118
favorite count: 0
has comment: http://stackoverflow.com/comment/88608758
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88609738
tagged with: python
tagged with: regex
has body: I have a pattern like this: word word one/two/three word I want to match the groups which is seperated by the /. My thought is as follows: [\w]+ # match any words [\w]+/[\w]+ # followed by / and another word [\w]+[/[\w]+]+ # repeat the latter But this does not work since it seems as soon as I add ], it does not close the mose inner [ but the most outer [. How can I work with nested squared brackets?
linked to: http://stackoverflow.com/q/301068
downvote count: 1
has answer: http://stackoverflow.com/a/50801189
type: Question
has comment: http://stackoverflow.com/comment/88608208
has answer: http://stackoverflow.com/a/50801430
score: -1
has comment: http://stackoverflow.com/comment/88608282
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/88608294
has title: Nested squared brackets

http://stackoverflow.com/comment/88634819
type: Comment
has text: It doesn't say global inside convert() - if you put 'global' in the module scope it doesn't do anything, has to be inside the function. test = 123 global test def f0(): test = 234 >>> test 123 >>> f0() >>> test 123
comment on: http://stackoverflow.com/a/50814191
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88600729
type: Comment
has text: @Mitiku Sorry, float64
type: QuestionComment
comment on: http://stackoverflow.com/q/50797135
score: 0

http://stackoverflow.com/comment/88604328
type: Comment
has text: I'd also think this is the most straightforward way of doing it.
comment on: http://stackoverflow.com/a/50799229
type: AnswerComment
score: 0

http://stackoverflow.com/q/50754471
has title: Seaborn heatmap not displaying all xticks and yticks
answer count: 4
type: AnsweredQuestion
upvote count: 45
possible better answer: http://stackoverflow.com/a/68169488
has answer: http://stackoverflow.com/a/68169488
type: Question
linked to: http://stackoverflow.com/q/71906295
has answer: http://stackoverflow.com/a/72680324
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50754993
accepted answer: http://stackoverflow.com/a/50754993
score: 44
has body: I have a pandas dataframe of shape (39, 67). When I plot it's seaborn heatmap, I don't get as many labels on the X and Y axes. .get_xticklabels() method also returns only 23 labels. matplotlib doesn't show any labels (only numbers) as well. Both these heatmaps are for the same dataframe (39, 67).
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/76246907
tagged with: pandas
tagged with: seaborn
tagged with: python

http://stackoverflow.com/a/50854917
answers question: http://stackoverflow.com/q/50853691
upvote count: 3
type: AcceptedAnswer
type: Answer
has body: Here's a vectorized solution with help from convolution - def first_consecutive_negative_island(a, N=3): mask = np.convolve(np.less(a,0),np.ones(N,dtype=int))&gt;=N if mask.any(): return mask.argmax() - N + 1 else: return None Sample run - In [168]: a = [1,-1,1,-1,1,-1,1,-1,-1,-1,1,-1,1] In [169]: first_consecutive_negative_island(a, N=3) Out[169]: 7 Works irrespective of where the group exists - In [175]: a Out[175]: [-1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1] In [176]: first_consecutive_negative_island(a, N=3) Out[176]: 0 With no negative numbers, it gracefully returns None - In [183]: a Out[183]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] In [184]: first_consecutive_negative_island(a, N=3) For exactly three consecutive negative numbers search, we can use slicing, like so - def first_consecutive_negative_island_v2(a): m = np.less(a,0) mask = m[:-2] &amp; m[1:-1] &amp; m[2:] if mask.any(): return mask.argmax() else: return None Timings - In [270]: a = np.random.randint(-1,2,(1000000)).tolist() In [271]: %timeit first_consecutive_negative_island(a, N=3) 10 loops, best of 3: 44.5 ms per loop In [272]: %timeit first_consecutive_negative_island_v2(a) 10 loops, best of 3: 38.7 ms per loop
downvote count: 0
has comment: http://stackoverflow.com/comment/88713128
accepted answer of: http://stackoverflow.com/q/50853691
score: 3

http://stackoverflow.com/a/50780415
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/50780209
answers question: http://stackoverflow.com/q/50780209
type: Answer
upvote count: 4
downvote count: 0
has body: The decimal module gives more control over rounding behavior. Particularly, the ROUND_HALF_UP rounding mode rounds to the nearest option when there is a nearest option and rounds away from zero when there's a tie, matching what you want: &gt;&gt;&gt; from decimal import Decimal, ROUND_HALF_UP &gt;&gt;&gt; def round_your_way(d): ... return (d*4).quantize(Decimal('1'), rounding=ROUND_HALF_UP)/4 ... &gt;&gt;&gt; round_your_way(Decimal('0.125')) Decimal('0.25') &gt;&gt;&gt; round_your_way(Decimal('0.1')) Decimal('0') &gt;&gt;&gt; round_your_way(Decimal('0.25')) Decimal('0.25')

http://stackoverflow.com/q/50798848
has title: How to create the related field?
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50799039
has answer: http://stackoverflow.com/a/50799039
tagged with: django-models
accepted answer: http://stackoverflow.com/a/50799131
upvote count: 2
has comment: http://stackoverflow.com/comment/88603785
answer count: 2
has body: I have a Model you see bellow: class PriceModel(models.Model): name = models.CharField(max_length=12) the PriceModel's id is increased from 1. I want to add other field, which is related to the id. Such as I want it to #PM1, #PM2... means the #PM + id. How to create the related field?
has answer: http://stackoverflow.com/a/50799131
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88603681
score: 2
downvote count: 0

http://stackoverflow.com/comment/88576052
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50784474
has text: It isn't clear, to me at least, what you are trying to do. Do you have 10000 `Final Score`'s that you want to turn into 10000 `prob_1`'s then get an *SSD* for each? Is `xG_?` a team's final score? Are `Home_Goal`, `Away_Goal`, and `total_timeslot` constants? Is `k` in the probability calc the same as `total_timeslot`? Please update the question, don't answer in comments.

http://stackoverflow.com/a/65714907
type: Answer
upvote count: 6
score: 6
has body: Per the deprecation recommendations, it's very reasonable that code which doesn't compile with @jit(nopython=True) could be faster without the decorator. Anecdotally, I found the trivial example I landed here researching was notably faster when simply passing the Pandas columns directly to my function to vectorize the operation, rather than using numba and paying the method overhead of the columns for a numpy array. However, it continues with the expected argument to clear this warning If there is benefit to having the @jit decorator present, then to be future proof supply the keyword argument forceobj=True to ensure the function is always compiled in object mode.
downvote count: 0
answers question: http://stackoverflow.com/q/50744686

http://stackoverflow.com/comment/88963084
score: 0
type: Comment
type: QuestionComment
has text: I've now expanded the comment into an answer.
comment on: http://stackoverflow.com/q/50789505

http://stackoverflow.com/q/50796170
accepted answer: http://stackoverflow.com/a/50796210
has answer: http://stackoverflow.com/a/50796269
tagged with: python
has comment: http://stackoverflow.com/comment/88599562
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50796269
has answer: http://stackoverflow.com/a/50796210
type: Question
answer count: 2
has body: I have a variable which has time in H:M:S format like below h2='00:00:01' i want to change the H part in it to 10 so that it becomes h2='10:00:01' I tried the below code, but it dint work h2.split(':')[0]=10 print(h2) Output: 00:00:01 Expected Output: 10:00:01 How can i change the value of part of a variable?
has comment: http://stackoverflow.com/comment/88598225
has title: Changing the value of part of variable - Python
score: 0

http://stackoverflow.com/q/50817121
has comment: http://stackoverflow.com/comment/88639485
has comment: http://stackoverflow.com/comment/88639425
has comment: http://stackoverflow.com/comment/88641024
type: UnansweredQuestion
has title: Different plots with show and savefig
has comment: http://stackoverflow.com/comment/88639701
answer count: 0
has body: I am plotting histograms with quite large number of bins. I am using Spyder, Python 3.6.3. The problem I found is that the figure I am seeing in iPython console is NOT the same as the saved plots. I have seen this thread which asks a similar question, however, my problem is worse, as it's not just the fonts and sizes that vary, I am actually getting different counts! E.g. the same script: plt.clf() fig, ax=plt.subplots() fig.dpi=100 plt.hist(df['POS'], bins=nbins, range=(0,dict_l[c])) plt.savefig('current_chr17.jpg', dpi=100) will produce this plot as a saved figure: and show this in iPython console (interactive mode on, I'm not even asking for plt.show): Does anyone have any explanation as to what is going on?
tagged with: histogram
type: Question
tagged with: spyder
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/88639382

http://stackoverflow.com/a/50836700
has comment: http://stackoverflow.com/comment/88706449
upvote count: 2
type: AcceptedAnswer
has body: Yes, it is possible by assign, but in my opinion less readable, better is update each columns separately by boolean mask cached in variable: df_gp = pd.DataFrame({'volume':[.1,.3,.5,.7,.1,.7], 'new_volume':[5,3,6,9,2,4], 'commentary':list('aaabbb')}) print (df_gp) volume new_volume commentary 0 0.1 5 a 1 0.3 3 a 2 0.5 6 a 3 0.7 9 b 4 0.1 2 b 5 0.7 4 b #create boolean mask and assign to variable for reuse m = (df_gp['volume']&lt;df_gp['volume'].shift(1)) | (df_gp['volume']&lt;0.4) #change columns by assign by condition and assign back only filtered columns c = ['commentary','new_volume'] df_gp.loc[m, c] = df_gp.loc[m, c].assign(new_volume=df_gp['new_volume']*1.1 commentary='updated') print (df_gp) volume new_volume commentary 0 0.1 5.5 updated 1 0.3 3.3 updated 2 0.5 6.0 a 3 0.7 9.0 b 4 0.1 2.2 updated 5 0.7 4.0 b #multiple filtered column by scalar df_gp.loc[m, 'new_volume'] *= 1.1 #append new value to filtered column df_gp.loc[m, 'commentary'] = 'updated' print (df_gp) volume new_volume commentary 0 0.1 5.5 updated 1 0.3 3.3 updated 2 0.5 6.0 a 3 0.7 9.0 b 4 0.1 2.2 updated 5 0.7 4.0 b
has comment: http://stackoverflow.com/comment/88679862
type: Answer
has comment: http://stackoverflow.com/comment/88706263
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50835902
has comment: http://stackoverflow.com/comment/88679887
accepted answer of: http://stackoverflow.com/q/50835902

http://stackoverflow.com/q/50747359
score: 6
has comment: http://stackoverflow.com/comment/88504133
type: Question
tagged with: dataframe
has title: Performance issue turning rows with start - end into a dataframe with TimeIndex
has comment: http://stackoverflow.com/comment/88503324
linked to: http://stackoverflow.com/q/46484458
has comment: http://stackoverflow.com/comment/88504288
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/35187444
has answer: http://stackoverflow.com/a/50748885
favorite count: 0
tagged with: pandas
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88503277
upvote count: 6
has body: I have a large dataset where each line represents the value of a certain type (think a sensor) for a time interval (between start and end). It looks like this: start end type value 2015-01-01 2015-01-05 1 3 2015-01-06 2015-01-08 1 2 2015-01-05 2015-01-08 3 3 2015-01-13 2015-01-16 2 1 I want to turn it into a daily time-indexed frame like this: day type value 2015-01-01 1 3 2015-01-02 1 3 2015-01-03 1 3 2015-01-04 1 3 2015-01-05 1 3 2015-01-06 1 2 2015-01-07 1 2 2015-01-08 1 2 2015-01-05 3 3 2015-01-16 3 3 2015-01-07 3 3 2015-01-08 3 3 2015-01-13 2 1 2015-01-14 2 1 2015-01-15 2 1 2015-01-16 2 1 (Note that we cannot make any assumption regarding the interval: they should be contiguous and non-overlapping but we cannot guarantee that) Based on these Stack Overflow answers [1] (DataFrame resample on date ranges) [2] (pandas: Aggregate based on start/end date), there seem to exist two methods: one around itertuples, one around melt (2 above used stack/unstack but it is similar to melt). Let us compare them for performance. # Creating a big enough dataframe date_range = pd.date_range(start=dt.datetime(2015,1,1), end=dt.datetime(2019,12,31), freq='4D') to_concat = [] for val in range(1,50): frame_tmp = pd.DataFrame() frame_tmp['start'] = date_range frame_tmp['end'] = frame_tmp['start']+ dt.timedelta(3) frame_tmp['type'] = val frame_tmp['value'] = np.random.randint(1, 6, frame_tmp.shape[0]) to_concat.append(frame_tmp) df = pd.concat(to_concat, ignore_index=True) # Method 1 def method_1(df): df1 = (pd.concat([pd.Series(r.Index, pd.date_range(r.start, r.end, freq='D')) for r in df.itertuples()])) \ .reset_index() df1.columns = ['start_2', 'idx'] df2 = df1.set_index('idx').join(df).reset_index(drop=True) return df2.set_index('start_2') df_method_1=df.groupby(['type']).apply(method_1) # Method 2 df_tmp= df.reset_index() df1 = (df_tmp.melt(df_tmp.columns.difference(['start','end']), ['start', 'end'], value_name='current_time') ) df_method_2 = df1.set_index('current_time').groupb…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50748885

http://stackoverflow.com/comment/88642019
has text: Thanks for your response -- very helpful! Just to make sure I understand correctly, chunksize and update_every should not impact LDA's output or ability to identify topics, but rather it impacts on memory consumption? I just wanted to make sure those are two separate things.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50811902
type: AnswerComment

http://stackoverflow.com/q/50801196
type: UnansweredQuestion
upvote count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88609548
has answer: http://stackoverflow.com/a/50802197
tagged with: indexing
score: 1
has comment: http://stackoverflow.com/comment/88609494
type: Question
has answer: http://stackoverflow.com/a/57238735
answer count: 2
has body: I am running a website using Django, of which the database runs on PostgreSQL. To increase performance I want to add a BrinIndex to a model that is naturally ordered on disk. I have added the index to my models definition as follows. from django.contrib.postgres.indexes import BrinIndex class Measurement(models.Model): class Meta: indexes = ( BrinIndex(fields=['time']) ) time = models.DateTimeField( 'Time of measurement', null=True ) But running python3 manage.py makemigrations Returns an error Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pycharm\django_manage.py", line 52, in &lt;module&gt; run_command() File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pycharm\django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "C:\Python36\lib\runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "C:\Python36\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:/Users/*USERNAME*/*PROJECT_NAME*\manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Python…
has title: Add BrinIndex to existing PostgreSQL database using Django
downvote count: 0
has comment: http://stackoverflow.com/comment/88613811
has comment: http://stackoverflow.com/comment/88613140
tagged with: postgresql
favorite count: 0

http://stackoverflow.com/comment/88706568
score: 0
comment on: http://stackoverflow.com/a/50818941
type: Comment
has text: No, `key_to_int` is an attribute of the class you akready wrote. In fact you could put the code in your `__setitem__` and `__getitem__`, but there would be duplating code, that’s why i’d write a function.
type: AnswerComment

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/50706311
type: Tag

http://stackoverflow.com/q/50827845
score: 1
tagged with: methods
duplicate of: http://stackoverflow.com/q/136097
type: Question
has title: Why use a static method when you can just use a class/instance method in Python?
has comment: http://stackoverflow.com/comment/88660418
has comment: http://stackoverflow.com/comment/88660274
tagged with: static-methods
has body: Since a class or instance method in Python doesn't require you to use cls or self in the method, why can't you just create a class/instance method in place of a static method? Is there an advantage of using a static method as opposed to a class/instance method without referencing the cls/self in the method code? For example: This class method @classmethod def add(cls, num1,num2) return num1 + num2 As opposed to this static method @staticmethod def add(num1, num2) return num1 + num2
upvote count: 1
has comment: http://stackoverflow.com/comment/88660358
has comment: http://stackoverflow.com/comment/88660216
has comment: http://stackoverflow.com/comment/88660444
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/136097
downvote count: 0

http://stackoverflow.com/a/67335464
upvote count: 96
downvote count: 0
has body: Problem In a conda environment with simply calling pip freeze Output: ipykernel @ file:///C:/ci/ipykernel_1607454116140/work/dist/ipykernel-5.3.4-py3-none-any.whl ipython @ file:///D:/bld/ipython_1612487184680/work ... Wanted format: ipykernel==5.3.4 ipython==7.20.0 ... Solution In an activated conda environment I had to use pip list --format=freeze to get the correct format for generating a requirements file for people who prefer to use pip with virtual environments. Save to file: pip list --format=freeze &gt; requirements.txt
type: Answer
has comment: http://stackoverflow.com/comment/137069818
has comment: http://stackoverflow.com/comment/119808574
score: 96
answers question: http://stackoverflow.com/q/50777849

http://stackoverflow.com/comment/88568907
comment on: http://stackoverflow.com/q/50781014
score: 0
has text: just copy and paste it below and see if it plays 2 times, then you can just use a loop to play it N number of times
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88619235
type: QuestionComment
comment on: http://stackoverflow.com/q/50806626
score: 0
has text: @WillemVanOnsem its an ajax call...I defined a URL path as `url('scores/get_player_stats', views.ScoreView.get_player_stats, name='player-stats'),`
type: Comment

oauth-2.0
tag name: oauth-2.0
type: Tag
tags question: http://stackoverflow.com/q/50774052

http://stackoverflow.com/q/50763445
has comment: http://stackoverflow.com/comment/88534549
has answer: http://stackoverflow.com/a/50763860
score: 0
has title: Parse JSON response to populate data in the form of table
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/88534956
has answer: http://stackoverflow.com/a/50764131
has body: I have JSON response in a &lt;class 'dict'&gt;. I want to iterate over the JSON response and form a table view. Below is the sample JSON response. {'ResultSet': {'Rows': [{'Data': [{'VarCharValue': 'cnt'}, {'VarCharValue': 'id'}, {'VarCharValue': 'val'}]}, {'Data': [{'VarCharValue': '2000'}, {'VarCharValue': '1234'}, {'VarCharValue': 'ABC'}]},{'Data': [{'VarCharValue': '3000'}, {'VarCharValue': '5678'}, {'VarCharValue': 'DEF'}]}]}} Expected Output format: cnt id val 2000 1234 ABC 3000 5678 DEF There can only one row of data or there can be multiple rows of data for the column set (For provided sample data two rows are there).
favorite count: 0
linked to: http://stackoverflow.com/q/36862308
has comment: http://stackoverflow.com/comment/88534658
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88534712
has comment: http://stackoverflow.com/comment/88534814
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88534519
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50764131
upvote count: 1
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/50763860
tagged with: dataframe

http://stackoverflow.com/q/50843832
tagged with: python
type: AnsweredQuestion
tagged with: plc
has answer: http://stackoverflow.com/a/51083386
has title: Allen Bradley L16ER communication via Python
accepted answer: http://stackoverflow.com/a/51083386
downvote count: 2
upvote count: 1
type: Question
score: -1
has body: I am trying to communicate with an Allen Bradley L16ER PLC via python. What I've found online says that I should use either CPPPO or pycomm modules to accomplish this. I have looked for a good source of documentation for these, and was unable to find one. Is there a good place to find an explanation of the basics of how to use either of these? Also, is there an alternative solution that may work better? To further define my problem, let's define understanding of using this module into three layers. Understanding Python. Understanding how PLCs communicate. Understanding how to use these modules. While I understand level 1, I don't understand level 2. This makes it very hard to understand level 3.
tagged with: robotics
has comment: http://stackoverflow.com/comment/88750775
tagged with: communication
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50753804
has comment: http://stackoverflow.com/comment/88518957
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88515873
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/3939361
type: AnsweredQuestion
has body: I have a string : string = 'i-phone is popular - many people like it (user-friendly system, fast, good support)' How to use regular expression to split it as: split_string = ['i-phone', 'is', 'popular', 'many', 'people', 'like', 'it', 'user-friendly', 'system', 'fast', 'good', 'support'] The problem is that - contains 2 spaces and 1 hyphen. I tried: split_string = re.split('[() - ]', string) but I got: ['i-phone', 'is', 'popular', '-', 'many', 'people', 'like', 'it', '', 'user-friendly', 'system,', 'fast,', 'good', 'support', ''] Thanks.
has comment: http://stackoverflow.com/comment/88515672
has title: How to split using mutli-character delimiters in Python?
has comment: http://stackoverflow.com/comment/88515522
type: Question
accepted answer: http://stackoverflow.com/a/50753962
has comment: http://stackoverflow.com/comment/88515689
has answer: http://stackoverflow.com/a/50753962
score: 0

http://stackoverflow.com/a/52160638
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50838199
answers question: http://stackoverflow.com/q/50838199
type: AcceptedAnswer
type: Answer
score: 71
has comment: http://stackoverflow.com/comment/140073274
upvote count: 71
has body: In the end, I settled for the following : Drop: df.drop('column_1', 'column_2', 'column_3') Select : df.select([c for c in df.columns if c not in {'column_1', 'column_2', 'column_3'}])

http://stackoverflow.com/a/50756183
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88522423
has body: You have not imported the data into a list, but into a dictionary. If you want to import the json into a list here is how you would do: import json with open('data.json') as json_file: json_array = json.load(json_file) for item in json_array: unique = item['payload']['locality'] print(unique) You said you wanted to print all the unique localities, but in your code you are printing all localities without checking if they are unique or not.
type: Answer
answers question: http://stackoverflow.com/q/50755977

http://stackoverflow.com/a/50780610
accepted answer of: http://stackoverflow.com/q/50770356
answers question: http://stackoverflow.com/q/50770356
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88569347
has body: BUT when I run it on my Mac (in 2 different IDEs) it just creates the white window and places no menu elements into it. Great, it's working perfectly! The window itself is not where menus go on the Mac - look at the top of the screen, just like every other Mac application.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88600483
score: 0
type: Comment
has text: @Architgupta [this page](https://stackoverflow.com/a/35885331/9067615) might help solve that issue `"The error arises because the "data" is of type bytes so you have to decode it into a string before using json.loads to turn it into a json object."`
comment on: http://stackoverflow.com/a/50796530
type: AnswerComment

http://stackoverflow.com/comment/88433559
type: AnswerComment
comment on: http://stackoverflow.com/a/50701999
type: Comment
score: 0
has text: I need file parameter not list/dict parameter.

http://stackoverflow.com/comment/88517094
score: 0
type: Comment
has text: I don't know who upvoted this question but this is a typical one I would downvote for the lack of a data sample. Please try to provide one in the future using `print(df.head(5).to_dict())` for instance.
type: QuestionComment
comment on: http://stackoverflow.com/q/50754269

http://stackoverflow.com/a/50804171
has comment: http://stackoverflow.com/comment/88614504
has comment: http://stackoverflow.com/comment/88614439
has comment: http://stackoverflow.com/comment/88614515
upvote count: 1
type: AcceptedAnswer
has body: You should remove the nltk.download() call from your code after downloading the required packages once. By keeping the line you are essentially downloading it each time your run the program and hence the log message.
answers question: http://stackoverflow.com/q/50804099
accepted answer of: http://stackoverflow.com/q/50804099
has comment: http://stackoverflow.com/comment/88614598
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/88549180
has text: just tried it and running with sudo still give the same access denied error
comment on: http://stackoverflow.com/q/50732366
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88505538
comment on: http://stackoverflow.com/a/50748395
has text: Thanks! I find the following line (I guess this is what you are trying to say but I didn't get it): "Normalizer acts row-wise and StandardScaler column-wise. Normalizer does not remove the mean and scale by deviation but scales the whole row to unit norm."
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50803334
has answer: http://stackoverflow.com/a/50803435
accepted answer: http://stackoverflow.com/a/50803435
has comment: http://stackoverflow.com/comment/88612591
type: Question
has comment: http://stackoverflow.com/comment/88612535
tagged with: sorting
has title: Python: Passing a list as parameter so the actual list is sorted
score: 0
has comment: http://stackoverflow.com/comment/88612580
tagged with: call-by-value
has comment: http://stackoverflow.com/comment/88612532
answer count: 1
tagged with: mergesort
has comment: http://stackoverflow.com/comment/88612569
has comment: http://stackoverflow.com/comment/88612589
tagged with: python
has comment: http://stackoverflow.com/comment/88612886
has body: I wrote a merge sort function and thought I was done.. but in the assignment it says that the function is supposed to sort the actual list instead of creating a copy (so call by value instead of reference I think?). Right now, it doesn't work because the list itself isn't changed. def mergeSort(L, ascending = True): print('Mergesort, Parameter L:') print(L) result = [] if len(L) == 1: return L mid = len(L) // 2 teilliste1 = mergeSort(L[:mid], ascending) teilliste2 = mergeSort(L[mid:], ascending) x, y = 0, 0 while x &lt; len(teilliste1) and y &lt; len(teilliste2): if (ascending and teilliste1[x] &gt; teilliste2[y]) or (not ascending and teilliste1[x] &lt; teilliste2[y]): result.append(teilliste2[y]) y = y + 1 else: result.append(teilliste1[x]) x = x + 1 result = result + teilliste1[x:] result = result + teilliste2[y:] return result liste1 = list([3, 2, -1, 9, 17, 4, 1, 0]) mergeSort(liste1) print(liste1) # result will be the unsorted list What do I need to change in the function to make it call by value and sort the actual list? I know I could do mergeResult = mergeSort(liste1) print(mergeResult) but apparently I have to change the original parameter list.
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/a/50839066
type: AcceptedAnswer
downvote count: 0
has body: An URL does not contain space characters. You can replace space characters with "%20" when it is a query.
type: Answer
answers question: http://stackoverflow.com/q/50836030
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50836030
score: 1

http://stackoverflow.com/a/59769855
has body: Do this: git clone https://github.com/FSX/misaka.git 2.cd misaka 3.python setup.py install
type: Answer
answers question: http://stackoverflow.com/q/50701683
score: 0

http://stackoverflow.com/comment/88589813
type: Comment
type: QuestionComment
has text: Because if you use `@wraps` then the function turns into a `functools.partial` instance. Try `print(Polynom.degre)` and you'll see.
comment on: http://stackoverflow.com/q/50791742
score: 0

http://stackoverflow.com/a/50740386
has comment: http://stackoverflow.com/comment/88488998
has comment: http://stackoverflow.com/comment/88488393
score: 1
has body: One single bullet proof solution: choose a name convention - all lower case is probably the most common one rename all include files to their lower case equivalent - do nothing if they are already lower case consistently check all source files and ensure that they actually include the lower case name - this should be done by hand because you do not want to process a litteral string containing #include That being said, if the number of files is small, and if files are not too complex, this can possibly be automated. But my opinion is that the gain of time is not worth the development of a tool and the risk of error in it.
accepted answer of: http://stackoverflow.com/q/50739241
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50739241
type: Answer
has comment: http://stackoverflow.com/comment/88489185
has comment: http://stackoverflow.com/comment/88489598
downvote count: 0

http://stackoverflow.com/q/50775873
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50775961
has comment: http://stackoverflow.com/comment/88558776
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 3
has body: I have the following codesnippet. I'm a bit confused, first, why do i have 2 as my step parameter, Is it because i jump from outside the dictionary, so i end up on total population? Second: What in the world does i+1 do? Never seen it before? Would make sense if i jump from i (the country name) and then land on total population. But if that is the case, what's the point in having 2 as my step? The code works as it's supposed to, i would just like to know how it works, in order to be able to benefit from it later in my own project. result = {} print(country_population) for i in range(0, len(country_population), 2): result[country_population[i]] = country_population[i+1]['total_population']['population'] print(result) country_population prints: ['Mali', {'total_population': {'date': '2013-01-01', 'population': 16352320}}, 'Ghana', {'total_population': {'date': '2013-01-01', 'population': 25855970}} result prints: {'Mali': 16352320, 'Ghana': 25855970}
downvote count: 1
type: Question
has title: Python: Start, stop, step
has answer: http://stackoverflow.com/a/50775961

http://stackoverflow.com/comment/88486161
comment on: http://stackoverflow.com/a/50739343
has text: That would word if I had 2 columns, but what if I have 3? or 4? or 5? Of course I could add more {} but they'll appear as {} if there's no other columns.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50788092
type: AcceptedAnswer
type: Answer
has body: Indeed, the function combinations of itertools will help you to create all combinations you can. Let's suppose your data is in a dataframe called df. from itertools import combinations # create two list, one for all columns you want to sum, and the others list_metric = [col for col in df.columns if 'metric' in col] list_non_metric = [col for col in df.columns if 'metric' not in col] # create the dataframe grouped on all columns df_grouped = df.groupby(list_non_metric,as_index=False)[list_metric].sum() # use concat and list comprehension to create all the combinations df_output = (pd.concat([df_grouped.groupby(list(combi),as_index=False)[list_metric].sum() for j in range(1, len(list_non_metric)+1) for combi in combinations(list_non_metric,j) ]) .fillna('')) # reorder the columns as the input data (if necessary) df_output = df_output[df.columns] If you want to understand how works combinations, try to print these lines: [combi for combi in combinations(list_non_metric,2)] and then the second for j in range(1, len(list_non_metric)+1) will help to create the combinations of 1, 2, 3, ... elements of list_non_metric
accepted answer of: http://stackoverflow.com/q/50787516
answers question: http://stackoverflow.com/q/50787516
score: 0

http://stackoverflow.com/comment/88540788
has text: Now i'm getting “Unicode Error ”unicodeescape" codec can't decode bytes
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50766642
type: Comment

newtons-method
tag name: newtons-method
type: Tag
tags question: http://stackoverflow.com/q/50805746

ncbi
tags question: http://stackoverflow.com/q/50816683
tag name: ncbi
type: Tag

http://stackoverflow.com/q/50847246
answer count: 1
favorite count: 0
score: -3
has comment: http://stackoverflow.com/comment/88717421
tagged with: python
has title: Pandas how to select stocks to invest in based on past performance (momentum, trend following)
downvote count: 4
type: AnsweredQuestion
has body: I have a dataframe of 20-day performances of a universe of 5 stocks that looks like this. Index is Dates, columns are stocks, elements are returns. ELET3 ELET6 EMBR3 ENBR3 EQTL3 (...) Dates 2/8/2018 0.277450 0.307260 0.064575 -0.025936 0.051672 3/12/2018 0.149723 0.100899 0.017105 0.056956 0.044669 4/10/2018 -0.235531 -0.180462 0.020565 0.026310 -0.006893 5/9/2018 -0.019453 -0.057651 0.033495 -0.055192 -0.042110 From which I have built a dataframe of the ranking of each stock's performance over that period (same as above but with the ranks instead of the returns): ELET3 ELET6 EMBR3 ENBR3 EQTL3 (...) Dates 2/8/2018 2.0 1.0 3.0 5.0 4.0 3/12/2018 1.0 2.0 5.0 3.0 4.0 4/10/2018 5.0 4.0 2.0 1.0 3.0 5/9/2018 2.0 5.0 1.0 4.0 3.0 (...) For each period(i), I want to calculate the average return for period(i) of the 2 stocks from the universe of 50 that had the best performance over the previous period (period(i-1)). Below is the out put I am looking for. There are no returns for 2/8/2018 as it is the first period. For this first period ELET3 and ELET6 are the two best performing stocks so the strategy invests in them for the next period. Their return over the 2/8/2018 - 3/12/2018 period is 0.149723 and 0.100899 so the code should return the average of that (0.12531). They are also the 2 best performing stocks for that 2/8/2018 - 3/12/2018 period. So the strategy stays invested in them over the 3/12/2018 - 4/10/2018 period. For that period they return -0.20800. over that period the 2 best stocks were EMBR3 and ENBR3, so the strategy invests in them over the 4/10/2018 - 5/9/2018 and they return an average return of -0.01085. Strategy Return Dates 2/8/2018 3/12/2018 0.12531 4/10/2018 -0.20800 5/9/2018 -0.01085
accepted answer: http://stackoverflow.com/a/50878485
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88698162
has answer: http://stackoverflow.com/a/50878485
has comment: http://stackoverflow.com/comment/88698250
tagged with: pandas
upvote count: 1

http://stackoverflow.com/comment/88508135
type: AnswerComment
score: 0
type: Comment
has text: I add df_race.columns = df_race.columns.str.replace("race", "pct")
comment on: http://stackoverflow.com/a/50744665

http://stackoverflow.com/q/50784660
score: -1
has body: I have a text file containing list of job searching websites like indeed.com, careerbuilder.com etc. I need to scrape each and every site that is listed in the text file to find the Jobs for given keywords using Python. The problem here is, every site have their own layouts. I need to scrape them with same program instead of writing a separate code for each and every site that is listed. Can someone help me with this??
possible better answer: http://stackoverflow.com/a/50784730
answer count: 2
upvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50784730
has title: Scraping multiple job listing sites for extracting job description, location etc
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50785721
has comment: http://stackoverflow.com/comment/88575842
accepted answer: http://stackoverflow.com/a/50785721
has comment: http://stackoverflow.com/comment/88586722
tagged with: web-scraping
downvote count: 1
type: Question

http://stackoverflow.com/comment/88580180
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50786841
has text: By blacklist I mean 'exclude this specific string from being split'. The example I made is exactly what I want.

http://stackoverflow.com/q/50719086
accepted answer: http://stackoverflow.com/a/50719151
tagged with: cpython
has title: CPython: Dynamic module does not define module export function error
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50719151
downvote count: 0
score: 1
tagged with: cython
type: Question
has body: I just compiled my Python wrapper for C++ classes successfully. However, I am getting following messages when I am trying to load my module to the Python (through import cell): ImportError: dynamic module does not define module export function (PyInit_cell) I checked that the system is using the Python3 on all cases so this is not a Python version problem. Below is my setup.py file: from distutils.core import setup, Extension from Cython.Build import cythonize setup(ext_modules = cythonize(Extension( "cell", sources=["cell.pyx", "cell.cc"], language="c++", extra_compile_args=["-std=c++11"], ))) Below is the dump for the generated .so file: 0000000000201020 B __bss_start 0000000000201020 b completed.7594 w __cxa_finalize@@GLIBC_2.2.5 0000000000000530 t deregister_tm_clones 00000000000005c0 t __do_global_dtors_aux 0000000000200de8 t __do_global_dtors_aux_fini_array_entry 0000000000201018 d __dso_handle 0000000000200df8 d _DYNAMIC 0000000000201020 D _edata 0000000000201028 B _end 0000000000000630 T _fini 0000000000000600 t frame_dummy 0000000000200de0 t __frame_dummy_init_array_entry 0000000000000640 r __FRAME_END__ 0000000000201000 d _GLOBAL_OFFSET_TABLE_ w __gmon_start__ 00000000000004e8 T _init w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable 0000000000200df0 d __JCR_END__ 0000000000200df0 d __JCR_LIST__ w _Jv_RegisterClasses 0000000000000570 t register_tm_clones 0000000000201020 d __TMC_END__ I really don't understand why the module is not loaded to the python because there was no error during the building process. Any help would be appreciated!
upvote count: 1
answer count: 1
favorite count: 0

java
tags question: http://stackoverflow.com/q/50851076
tags question: http://stackoverflow.com/q/50831848
tags question: http://stackoverflow.com/q/50719584
tags question: http://stackoverflow.com/q/50714006
tags question: http://stackoverflow.com/q/50825598
tags question: http://stackoverflow.com/q/50713455
tags question: http://stackoverflow.com/q/50853939
tags question: http://stackoverflow.com/q/50785573
tags question: http://stackoverflow.com/q/50835383
tags question: http://stackoverflow.com/q/50819025
tags question: http://stackoverflow.com/q/50850212
tag name: java
tags question: http://stackoverflow.com/q/50841235
tags question: http://stackoverflow.com/q/50821130
type: Tag

http://stackoverflow.com/q/50728929
tagged with: cookies
type: Question
has title: How to set cookie values and then immediately redirect to the next page and display what's in them
score: 0
accepted answer: http://stackoverflow.com/a/50729147
answer count: 1
tagged with: client-side
has answer: http://stackoverflow.com/a/50729147
tagged with: django
tagged with: python
has body: So I need to store two variables from one view and redirect to another view and display them. The obvious solution would be to use sessions but I don't have access to sessions because I don't have a database for this project so I'm trying to do sessions client sided because this isn't really a security issue anyways. This is my attempt so far: View where I set the cookies: response = HttpResponse('/result') response.set_cookie('passes', True) response.set_cookie('errors', []) v = jsonschema.Draft4Validator(schema) #Uses lazy validation to add all errors to validationErrors array for error in v.iter_errors(jsonFile): validationErrors.append(error) response.set_cookie('passes', False) for error in validationErrors: error.schma_path = error.schema_path.__str__()[5:] print error.schma_path print error.schema_path response.set_cookie('errors',validationErrors) ... return redirect('/result') View where I try to get the cookies: passes = request.COOKIES.get('passes',"Doesn't Exist") errors = request.COOKIES.get('errors', "Doesn't Exist") return render(request, 'result.html', context = {'errors': errors, 'passes': passes}) passes and errors isn't set because they both return Doesn't Exist. How would I do this without returning to the original page? I don't want to return response where response = render_to_response(current view's template) because it defeats the purpose of what I'm trying to do.
type: AnsweredQuestion

http://stackoverflow.com/comment/94806366
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50718230
has text: @Snedecor - What do you mean?
score: 0

http://stackoverflow.com/comment/88493889
has text: Yes, "thepathid" is also int(numeric). I tried the 2nd line as said but, still get the same error at the end "INSERT has more expressions than target columns".
type: AnswerComment
comment on: http://stackoverflow.com/a/50742699
score: 0
type: Comment

http://stackoverflow.com/a/50815754
downvote count: 0
has comment: http://stackoverflow.com/comment/88637426
has body: you should use (many=True) in the serializer while saving data = BucketlistSerializer(data = your_post_array,many=True) if data.is_valid(): data.save() add this to your view def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super("your view class name ", self).get_serializer(*args, **kwargs) for function base view @api_view(['GET','POST']) def somefunction(request): if request.method == 'POST': data = BucketlistSerializer(data = request.data["key_for_data"], many=True) if data.is_valid(): data.save() return(data.data) return(data.errors) post data will be : {"key_for_data":[{},{}]
upvote count: 1
has comment: http://stackoverflow.com/comment/88636802
has comment: http://stackoverflow.com/comment/88637979
has comment: http://stackoverflow.com/comment/88636958
has comment: http://stackoverflow.com/comment/88636671
type: Answer
has comment: http://stackoverflow.com/comment/88638042
score: 1
answers question: http://stackoverflow.com/q/50815061

http://stackoverflow.com/comment/88630674
type: AnswerComment
comment on: http://stackoverflow.com/a/50741787
type: Comment
score: 0
has text: import cv3 import csv img1 = cv2.imread("/Users/alisa/Desktop/sift.jpg") gr_img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) sift = cv2.xfeatures2d.SIFT_create() kp1, des1 = sift.detectAndCompute(gr_img1, None) filename = '/Users/alisa/Desktop/q.csv' gr_img1 = '' for row_features in des2: for feature in row_features: gr_img1 = gr_img1 + str(feature) + ',' with open(filename, 'w+') as output: output.write(gr_img1 + "\n")

http://stackoverflow.com/comment/88701465
type: QuestionComment
comment on: http://stackoverflow.com/q/50849119
has text: Edited to show desired output
score: 0
type: Comment

http://stackoverflow.com/q/50803679
favorite count: 0
has title: pip3 fails to install python module with space in name from requirments.txt
has body: I would like to install jupyter qtconsole from a requirments file using: pip3 install -r requirments.txt When I do, the process halts on jupyter qtconsole. It seems that the space in the module name is halting the automated install process, with the result: Invalid requirement: 'jupyter qtconsole' If I type the following into the command prompt, the install works fine. pip3 install jupyter qtconsole I have tried several methods to replace the space in the module name... so far no luck. Any suggestions? Strange question to articulate... hard to find similar ones. If this has been asked before please point me in the right direction. Thanks!
tagged with: pip
accepted answer: http://stackoverflow.com/a/50803723
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50803723
score: 0
tagged with: jupyter

http://stackoverflow.com/a/50844691
has comment: http://stackoverflow.com/comment/94718611
has comment: http://stackoverflow.com/comment/94740573
has comment: http://stackoverflow.com/comment/116873143
type: Answer
answers question: http://stackoverflow.com/q/50842397
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/116875837
has body: We can just transform the estimated params by the standard deviation of the exog. results.t_test(transformation) computes the parameter table for the linearly transformed variables. AFAIR, the following should produce the beta coefficients and corresponding inferential statistics. Compute standard deviation, but set it to 1 for the constant. std = model.exog.std(0) std[0] = 1 Then use results.t_test and look at the params_table. np.diag(std) creates a diagonal matrix that transforms the params. tt = results.t_test(np.diag(std)) print(tt.summary() tt.summary_frame()
downvote count: 0

http://stackoverflow.com/q/50834888
has answer: http://stackoverflow.com/a/77515599
has answer: http://stackoverflow.com/a/53088028
upvote count: 5
has title: Get DPI information of PDF image Python
downvote count: 1
type: Question
score: 4
tagged with: dpi
answer count: 3
has body: I have pdf file in which an image is embedded in it how i can get the DPI information of that particular image using python. i tried using "pdfimages" popler-util it gives me the height and width in pixels. But how i can get the DPI of image from that.
favorite count: 0
tagged with: resolution
has answer: http://stackoverflow.com/a/77514980
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88629722
has text: If `destructor obj` throws an exception, you call it a second time in the handler. That is not what is done in Python, for example (https://www.python.org/dev/peps/pep-0343/#specification-the-with-statement).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50795957
score: 1

http://stackoverflow.com/q/50819137
type: Question
has comment: http://stackoverflow.com/comment/88643521
tagged with: arrays
score: 0
answer count: 1
tagged with: python
has title: Python: Sometimes printing whole array instead of single word
tagged with: append
has answer: http://stackoverflow.com/a/50819221
has comment: http://stackoverflow.com/comment/88643638
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/50819221
has body: Still fairly new to Python and I'm currently just making random stuff in my spare time to help me learn. Currently this is what I'm working on: import sys import random import time import pyperclip print ('shit talk generator') names = str(raw_input('Usernames: ')) splitNames = names.split(',') splitNames.append(splitNames) while True: for x in range(1): iqValue = random.randint(-100,10000) randomName = random.choice(splitNames) print ('Wow %s, That was a %s IQ Play!' % (randomName, iqValue)) clipboardCopy = 'Wow %s, That was a %s IQ Play!' % (randomName, iqValue) pyperclip.copy(clipboardCopy) print('waiting 2') time.sleep(2) Basically, as you've gathered, just generates shit talk and saves it to my clipboard. Now, sometimes when printing the output it prints the whole array instead of a single word. Here's a snippet of the output: shit talk generator Usernames: lewis, daniel, james, john, jack, roger, fred, jones Wow john, That was a 1073 IQ Play! waiting 2 Wow roger, That was a 6182 IQ Play! waiting 2 Wow jack, That was a 3330 IQ Play! waiting 2 Wow ['lewis', ' daniel', ' james', ' john', ' jack', ' roger', ' fred', ' jones', [...]], That was a 5734 IQ Play! waiting 2 Wow ['lewis', ' daniel', ' james', ' john', ' jack', ' roger', ' fred', ' jones', [...]], That was a 4963 IQ Play! waiting 2 Wow fred, That was a 223 IQ Play! waiting 2 Wow james, That was a 7995 IQ Play! waiting 2 Wow lewis, That was a 7620 IQ Play! waiting 2 Now since this is intermittent it makes me believe that it is storing its whole self as an item in the list, am I wrong in assuming this? How would I go about fixing this and ensuring it only selects valid username from the input? Any help/guidance is greatly appreciated.

http://stackoverflow.com/comment/88556349
score: 1
comment on: http://stackoverflow.com/q/50774697
type: Comment
type: QuestionComment
has text: You are iterating twice. Once over content and once over e-mail. Basically you are sending all possible combinations of content vs email. To do this with a for loop, iterate only once over all rows. Take a look at this answer: https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas

http://stackoverflow.com/comment/88425423
has text: Sorry if you don't understand what i'm saying, it's a little game that I want to make by myself, here is the traceback:
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50708033
type: Comment

http://stackoverflow.com/a/50718495
upvote count: 1
has comment: http://stackoverflow.com/comment/88454198
has comment: http://stackoverflow.com/comment/88460810
answers question: http://stackoverflow.com/q/50713390
downvote count: 0
has comment: http://stackoverflow.com/comment/88460521
has comment: http://stackoverflow.com/comment/88446389
has comment: http://stackoverflow.com/comment/88450417
has body: The reason is that the .xlsx file has a different encoding, not utf-8. You'll need to use the original encoding to decode the file. There's no guaranteed way of finding out the encoding of a file programmatically. I'm guessing you're making this application for general users and so you will keep encountering files with different and unexpected encodings. A good way to deal with this is by trying to decode using multiple encodings, in case one fails. Example: encodings = ['utf-8', 'iso-8859-1', 'windows-1251', 'windows-1252'] for encoding in encodings: try: decoded_file = self.request.files['1'][0]['body'].decode(encoding) except UnicodeDecodeError: # this will run when the current encoding fails # just ignore the error and try the next one pass else: # this will run when an encoding passes # break the loop # it is also a good idea to re-encode the # decoded files to utf-8 for your purpose decoded_file = decoded_file.encode("utf8") break else: # this will run when the for loop ends # without successfully decoding the file # now you can return an error message # to the user asking them to change # the file encoding and re upload self.write("Error: Unidentified file encoding. Re-upload with UTF-8 encoding") return # when the program reaches here, it means # you have successfully decoded the file # and you can access it from `decoded_file` variable Here's a list of some common encodings: What is the most common encoding of each language?
has comment: http://stackoverflow.com/comment/88450522
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88450371
has comment: http://stackoverflow.com/comment/88454863

http://stackoverflow.com/a/50833578
score: 5
has body: This is featured in the paragraph right after: Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255. If i &lt; 100 is True, it returns 255. This makes sense considering the whole RGB colour scheme where RGB(255, 0, 0) returns Red. But yes, this is bad practise. It should be: mask = source[R].point(lambda i: 255 if i &lt; 100 else 0) Much more readable...
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88671056
has comment: http://stackoverflow.com/comment/88671164
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/88670962
has comment: http://stackoverflow.com/comment/88671552
has comment: http://stackoverflow.com/comment/88671119
accepted answer of: http://stackoverflow.com/q/50833486
downvote count: 0
answers question: http://stackoverflow.com/q/50833486

http://stackoverflow.com/comment/88705540
type: Comment
has text: @shmee commit() worked! thank you so much
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50850655

http://stackoverflow.com/a/50833711
type: Answer
accepted answer of: http://stackoverflow.com/q/50830618
answers question: http://stackoverflow.com/q/50830618
downvote count: 0
score: 5
type: AcceptedAnswer
upvote count: 5
has body: I managed to find a work around by including an additional parameter within pd.read_json pd.read_json(df, orient='split', dtype = {"column_name": object}) I used this as reference Thank you for all the help!

http://stackoverflow.com/comment/88701862
score: 0
has text: Still works for me. I get a file like `OBJECTID,STATEFP,COUNTYFP,TRACTCE,GEOID,B23003e1,B23003m1,B23003e2,B23003m2,B23003e3` followed by `1.0,12.0,105.0,10300.0,15000US121050103002,69.0,81.0,13.0,21.0,13.0` and so on.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50849178

http://stackoverflow.com/a/50779325
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50779272
score: 3
answers question: http://stackoverflow.com/q/50779272
type: AcceptedAnswer
upvote count: 3
type: Answer
has body: This has to do with variable scope. line in your on_press method is not the same variable as line up above. If you want to do something like that, you need to tell it to use the global scope variable: def on_press(key): global line line += key print(line)
has comment: http://stackoverflow.com/comment/88565583

http://stackoverflow.com/a/50866605
has body: Most of the parts above the C API are implemented in Python. You run those parts using a Python interpreter. More verbosely, the C API and below, is basically just a library. You can use this library from different languages. For training, you usually use Python (all tf.* APIs), which runs using Python interpreter. For inference, you usually use Java or C++. In this case, no Python interpreter is necessary.
score: 1
upvote count: 1
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50845832
accepted answer of: http://stackoverflow.com/q/50845832
type: Answer

http://stackoverflow.com/q/50710195
linked to: http://stackoverflow.com/q/47152691
type: Question
has title: Change dataframe by grouping info per user
tagged with: dataframe
score: 0
has answer: http://stackoverflow.com/a/50710237
accepted answer: http://stackoverflow.com/a/50710237
tagged with: pandas
answer count: 1
duplicate of: http://stackoverflow.com/q/47152691
has body: I have a dataframe like this: user events A X A X A Y B Z Using pandas, how can I get a final dataframe like the following? user X Y Z A 2 1 0 B 0 1 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50837083
type: Answer
answers question: http://stackoverflow.com/q/50814591
has body: Deconvolution is an ill-posed tough problem in presence of noise and spatially-variant blurring. I assume you have a non spatially variant problem, as far as you are using FFTs, so you can use restoration module from skimage python package (instead of programming the algorithm at low level with FFTs). Here you can study a code example with one of the implemented methods in restoration module. I recommend you to read O'Leary et al. book if you want to learn more. All authors of this book have more advanced books about this great topic.
score: 0

http://stackoverflow.com/comment/88600845
type: QuestionComment
comment on: http://stackoverflow.com/q/50797275
has text: `if ii not in list` - do you mean `list1`, `list2`, or `new_list`?
score: 0
type: Comment

http://stackoverflow.com/a/50839251
answers question: http://stackoverflow.com/q/50839112
score: 0
has body: This can be ideal approach to solve this problem,instead of creating multiple functions for each increment.Use a class and store the counter as variable and call the corresponding method to increment and get_count class CouterExample(object): """Sample DocString: Attributes: counter: A integer tracking the current counter. """ def __init__(self, counter=0): """Return a CounterExample object with counter.""" self.counter = counter def increment(self, amount): """Sets the counter after increment.""" if amount &gt; 1: self.counter += amount def get_counter(self): """Return the counter value.""" return self.counter
type: Answer

http://stackoverflow.com/comment/88619103
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50805413
has text: Why are you querying an attribute location that you explicitly set in the shader? You *know* the answer is going to be 0, so why are you asking?

http://stackoverflow.com/q/50728444
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50728504
has answer: http://stackoverflow.com/a/50728536
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/88464909
type: Question
has title: python regex match number greater than 120
has body: I have data 67.65 GB 99.29 GB 103.99 GB 5.11 GB 155.66 GB etc... I'm planning on coming up with a regex to match number grater than 120. Would regex be good for it or should I try other methods?
has comment: http://stackoverflow.com/comment/88464967
has comment: http://stackoverflow.com/comment/88464932
tagged with: python-2.7
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50728763
favorite count: 0
type: UnansweredQuestion

scatter-plot
type: Tag
tags question: http://stackoverflow.com/q/50808678
tag name: scatter-plot

http://stackoverflow.com/a/50711516
upvote count: 1
type: AcceptedAnswer
has body: You can use map in this case: df['diff'] = df['ID'].map(df2.set_index('ID').Quantity) - df.Quantity Some Data import pandas as pd df = pd.DataFrame({'Title': ['A', 'B', 'C', 'D', 'E'], 'Name': ['AA', 'BB', 'CC', 'DD', 'EE'], 'Quantity': [1, 21, 14, 15, 611], 'ID': ['A1', 'A1', 'B2', 'B2', 'C1']}) df2 = pd.DataFrame({'Quantity': [11, 51, 44], 'ID': ['A1', 'B2', 'C1']}) We will use df2 to create a dictionary which can be used to map ID to Quantity. So anywhere there is an ID==A1 in df it gets assigned the Quantity 11, B2 gets assigned 51 and C1 gets assigned 44. Here' I'll add it as another column just for illustration purposes. df['Quantity2'] = df['ID'].map(df2.set_index('ID').Quantity) print(df) ID Name Quantity Title Quantity2 0 A1 AA 1 A 11 1 A1 BB 21 B 11 2 B2 CC 14 C 51 3 B2 DD 15 D 51 4 C1 EE 611 E 44 Name: ID, dtype: int64 Then you can just subtract df['Quantity'] and the column we just created to get the difference. (Or subtract that from df['Quantity'] if you want the other difference)
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50711432
score: 1
answers question: http://stackoverflow.com/q/50711432
has comment: http://stackoverflow.com/comment/88432228

http://stackoverflow.com/comment/88460810
has text: @xyres EQObject is just a variable name to store the xlsx (in byte). and for BadZipFile error ill open a new question.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50718495
type: Comment

http://stackoverflow.com/comment/88462243
type: QuestionComment
comment on: http://stackoverflow.com/q/50726804
score: 0
has text: @EdoardoBusetti you need to adjust your a and b. I don't really understand the idea behind what youre doing with them, but its not checking if they are within the circle.
type: Comment

http://stackoverflow.com/a/50705655
has body: Not in one operation, but you should stick to bit operations (not + or -). If you want the bits in value1 not in value2, the ordinary way to spell that is value1 &amp; ~value2 That is, the intersection of value1 with the complement of value2 (note that the unary prefix operator there is ~, not -).
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50705563
score: 5
upvote count: 5

http://stackoverflow.com/q/50740133
has comment: http://stackoverflow.com/comment/88521527
has comment: http://stackoverflow.com/comment/88522084
has comment: http://stackoverflow.com/comment/88487817
has comment: http://stackoverflow.com/comment/88488581
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52160853
favorite count: 0
has comment: http://stackoverflow.com/comment/88490147
has comment: http://stackoverflow.com/comment/88489341
tagged with: linux
tagged with: pyinstaller
has body: I have simple python code that prints hello (hello.py) that I want to make executable using pyinstaller, to run on Linux: #!/usr/bin/python3.5 #!/usr/bin/env python3.5 def welcome(): print('Welcome') welcome() I apply the command pyinstaller hello.py and I end up with the following exception: 6204 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully. 6205 INFO: Bootloader /home/nour/.local/lib/python3.5/site-packages/PyInstaller/bootloader/Linux-64bit/run 6206 INFO: checking EXE 6206 INFO: Building EXE because out00-EXE.toc is non existent 6206 INFO: Building EXE from out00-EXE.toc 6206 INFO: Appending archive to ELF section in EXE /home/nour/python/build/hello/hello Traceback (most recent call last): File "/home/nour/.local/bin/pyinstaller", line 9, in <module> load_entry_point('PyInstaller==3.3.1', 'console_scripts', 'pyinstaller')() <...> File "/usr/lib64/python3.5/subprocess.py", line 1282, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'objcopy' What I tried already and did not help: I changed python3.5 to python3 and python Any hints?
has comment: http://stackoverflow.com/comment/88487733
has comment: http://stackoverflow.com/comment/88490167
has comment: http://stackoverflow.com/comment/88489318
tagged with: python
has title: Pyinstaller fails on Linux with missing `objcopy`
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52160853
upvote count: 1
type: Question

http://stackoverflow.com/q/50772361
has answer: http://stackoverflow.com/a/50773603
tagged with: list
has title: Retrieving the indices of elements within a list of lists
has comment: http://stackoverflow.com/comment/88669751
type: Question
answer count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88552847
favorite count: 0
tagged with: python-3.x
has body: Suppose I have the following: lists = [[1, 3, 5], [1, 2, 3], [3, 5, 7], [1, 4, 8], [2, 3, 4, 5]] I want to retrieve the the indices of each element within the list of lists e.g. 1 occurs in: lists[0], lists[1], lists[3] How can this be done?
has answer: http://stackoverflow.com/a/50773606
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51411567
type: AcceptedAnswer
downvote count: 0
has body: No, I don't believe this is possible. Your issue is discussed here. Quoting @jjallaire (one of the devs, and CEO of RStudio): "No, you can't safely unload and reload the connection to Python (too many unreversable side effects in the Python interpreter)". Restarting the python connection requires restarting R.
accepted answer of: http://stackoverflow.com/q/50762140
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89806685
answers question: http://stackoverflow.com/q/50762140
has comment: http://stackoverflow.com/comment/89870671

http://stackoverflow.com/comment/88611992
score: 1
has text: you can save whole session with chrome_options.add_argument("user-data-dir=" + os.path.dirname(sys.argv[0])) browser = webdriver.Chrome(chrome_options=chrome_options)
type: QuestionComment
comment on: http://stackoverflow.com/q/50792181
type: Comment

http://stackoverflow.com/comment/88682980
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50833867
has text: You should really do image augmentation: change scale, rotation, shear.. so the network can train on more examples. This will probably give you the best improvement. Check in the keras website
type: AnswerComment

http://stackoverflow.com/q/50778481
type: Question
has comment: http://stackoverflow.com/comment/88563878
answer count: 3
has title: how to write to csv from beautifulsoup data
linked to: http://stackoverflow.com/q/37289951
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50778562
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50778544
tagged with: http://stackoverflow.com/tag/csv
has body: Looking to take data I have extracted with beautifulsoup to .csv file this the code to extract: from requests import get url = 'https://howlongtobeat.com/game.php?id=38050' response = get(url) from bs4 import BeautifulSoup html_soup = BeautifulSoup(response.text, 'html.parser') game_name = html_soup.select('div.profile_header')[0].text game_length = html_soup.select('div.game_times li div')[-1].text game_developer = html_soup.find_all('strong', string='\nDeveloper:\n')[0].next_sibling game_publisher = html_soup.find_all('strong', string='\nPublisher:\n')[0].next_sibling game_console = html_soup.find_all('strong', string='\nPlayable On:\n')[0].next_sibling game_genres = html_soup.find_all('strong', string='\nGenres:\n')[0].next_sibling I would like to write the results of these to csv (it's pulling the info I want but I think it needs to be cleaned up) not sure how to write to csv or to clean up data please help
tagged with: python
has answer: http://stackoverflow.com/a/50778537
score: 2
upvote count: 3
downvote count: 1

http://stackoverflow.com/a/50757476
type: Answer
has body: My solution is to do it manually: $ ./manage.py shell Python 3.6.5 (default, Apr 1 2018, 05:46:30) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from django.contrib.auth.models import User In [2]: u = User.objects.create_user('name', '', '') In [3]: User.objects.filter(id=u.id).update(id=10000-1) Out[3]: 1 In [4]: u.delete() Out[4]: (0, {'admin.LogEntry': 0, 'auth.User_groups': 0, 'auth.User_user_permissions': 0, 'auth.User': 0}) In [5]: uu = User.objects.create_user('user', '', '') In [6]: uu.id Out[6]: 10000
answers question: http://stackoverflow.com/q/50757235
score: 0

http://stackoverflow.com/a/50846171
accepted answer of: http://stackoverflow.com/q/50839890
score: 10
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50839890
has body: This is because your system has logrotate setup to handle log rotation for Apache. It will send a graceful restart signal to Apache to have it reload while it swaps out the log files. If this isn't desirable, don't have logrotate do that and use Apache's own mechanism for log file rotation.
type: Answer
has comment: http://stackoverflow.com/comment/121354056
upvote count: 10

http://stackoverflow.com/a/50730134
has body: It gives you an error because DataFrame.rdd returns RDD[Row]. To make it work you need something that is convertible to Map, for example (if you want Map[String, Double]): df.select("VIN").distinct() .select($"VIN".cast("string")) .withColumn("fraction", lit(0.001)) .as[(String, Double)] .rdd .collectAsMap() or df.select("VIN").distinct() .withColumn("fraction", lit(0.001)) .rdd .map { case Row(vin, fraction: Double) =&gt; (vin.toString, fraction) } .collectAsMap()
answers question: http://stackoverflow.com/q/50730082
score: 0
has comment: http://stackoverflow.com/comment/88468178
type: Answer
has comment: http://stackoverflow.com/comment/88468223

http://stackoverflow.com/q/50786300
linked to: http://stackoverflow.com/q/45523025
type: Question
duplicate of: http://stackoverflow.com/q/45523025
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50786316
downvote count: 0
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/50786434
tagged with: python
has body: I am trying to slice the string in vectorized way and answer is NaN. Although work OK if sequence index (say like str[:1]) is constant. Any help df = pd.DataFrame({'NAME': ['abc','xyz','hello'], 'SEQ': [1,2,1]}) # df['SUB'] = df['NAME'].str[:df['SEQ']] The output is NAME SEQ SUB 0 abc 1 NaN 1 xyz 2 NaN 2 hello 1 NaN
has title: slice panda string in vectorised way
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50786434
has answer: http://stackoverflow.com/a/50786316

http://stackoverflow.com/a/50780428
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50771544
type: Answer
score: 2
upvote count: 2
has body: describe_spot_instance_requests should give the for the instance ids created by spot. Refer:https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_spot_instance_requests
accepted answer of: http://stackoverflow.com/q/50771544

algorithm
tags question: http://stackoverflow.com/q/50759094
tags question: http://stackoverflow.com/q/50833581
tags question: http://stackoverflow.com/q/50806917
tag name: algorithm
tags question: http://stackoverflow.com/q/50784448
tags question: http://stackoverflow.com/q/50806043
tags question: http://stackoverflow.com/q/50831020
tags question: http://stackoverflow.com/q/50746555
tags question: http://stackoverflow.com/q/50808650
tags question: http://stackoverflow.com/q/50783536
tags question: http://stackoverflow.com/q/50785588
tags question: http://stackoverflow.com/q/50785187
tags question: http://stackoverflow.com/q/50845507
tags question: http://stackoverflow.com/q/50699944
tags question: http://stackoverflow.com/q/50702625
tags question: http://stackoverflow.com/q/50793016
tags question: http://stackoverflow.com/q/50783778
tags question: http://stackoverflow.com/q/50851076
type: Tag
tags question: http://stackoverflow.com/q/50729869
tags question: http://stackoverflow.com/q/50712114
tags question: http://stackoverflow.com/q/50754601
tags question: http://stackoverflow.com/q/50796746
tags question: http://stackoverflow.com/q/50842285
tags question: http://stackoverflow.com/q/50718514
tags question: http://stackoverflow.com/q/50731225
tags question: http://stackoverflow.com/q/50705667
tags question: http://stackoverflow.com/q/50814590
tags question: http://stackoverflow.com/q/50751990
tags question: http://stackoverflow.com/q/50705511
tags question: http://stackoverflow.com/q/50837066
tags question: http://stackoverflow.com/q/50853691
tags question: http://stackoverflow.com/q/50771901
tags question: http://stackoverflow.com/q/50826373

http://stackoverflow.com/q/50854694
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88712732
has title: Dynamically Add Fields to Django Models & Migrate & Return on Template
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/88761006
has body: I want superuser or agent to be able to add fields to user profile on the go during collection of data from users. For example, the agent will click add new field button via frontend, and the link will automatically create the field, add to the 'Profile' model and makemigrations via django South. Now I tried doing this via inlineformset factory adding additional fields. The problem is the fields are not being created in the database so saving data inputted in the fields are not working too. I have 'Profile'model for user details and 'Userform' for details related to User model. So now below is my forms and views class BaseProfileEditInlineFormSet(BaseInlineFormSet): def add_fields(self, form, index): super().add_fields(form, index) form.fields['more_field'] = forms.CharField() form.fields['more_field'] = forms.CharField() views @login_required def edit_user_profile(request, pk): userpro = CustomUser.objects.get(pk=pk) user_form = UserForm(instance=userpro) ProfileInlineFormset = inlineformset_factory(CustomUser, Profile, exclude=['user','pub_date','modified_date','basic_verification','phone_confirmed'],formset=BaseProfileEditInlineFormSet, max_num=1, can_delete=False) formset = ProfileInlineFormset(instance=userpro) if request.user.is_authenticated and request.user.id == userpro.id: if request.method == "POST": user_form = UserForm(request.POST, request.FILES, instance=userpro) formset = ProfileInlineFormset(request.POST, request.FILES, instance=userpro) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=userpro) if formset.is_valid(): created_user.save() formset.save() return HttpResponse('saved data') return render(request, 'accounts/account_update.html', {'pk':pk, 'user_form': user_form, 'formset':formset,}) else: raise PermissionDenied What am I missing? Also do you think this is a nice idea based on the fact that migrations in production will be different from the one in loca…

http://stackoverflow.com/comment/88701204
comment on: http://stackoverflow.com/q/50849090
has text: Please add an example of your input file; just to be safe.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/50823294
answers question: http://stackoverflow.com/q/50823223
accepted answer of: http://stackoverflow.com/q/50823223
upvote count: 4
downvote count: 0
has body: Your problem is in this line: if comp_card1 == 'Jack' or 'Queen' or 'King': That is not how the or operator works. You need to repeat the operation: if comp_card1 == 'Jack' or comp_card1 == 'Queen' or comp_card1 == 'King': Or better, use the in operator: if comp_card1 in ('Jack', 'Queen', 'King'):
score: 4
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88516292
comment on: http://stackoverflow.com/a/50754235
score: 1
type: AnswerComment
type: Comment
has text: see [more](https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-strings/3096984#3096984)

http://stackoverflow.com/a/62139106
has comment: http://stackoverflow.com/comment/139046388
answers question: http://stackoverflow.com/q/50757497
has body: Python 3.7+ now has a simpler API (in my opinion) with a simpler wording (easier to remember than "ensure_future"): you can use create_task which returns a Task object (that can be useful later to cancel the task if needed). Basic example 1 import asyncio async def hello(i): print(f"hello {i} started") await asyncio.sleep(4) print(f"hello {i} done") async def main(): task1 = asyncio.create_task(hello(1)) # returns immediately, the task is created await asyncio.sleep(3) task2 = asyncio.create_task(hello(2)) await task1 await task2 asyncio.run(main()) # main loop Result: hello 1 started hello 2 started hello 1 done hello 2 done Basic example 2 If you need to get the return value of these async functions, then gather is useful. The following example is inspired from the documentation. import asyncio async def factorial(n): f = 1 for i in range(2, n + 1): print(f"Computing factorial({n}), currently i={i}...") await asyncio.sleep(1) f *= i return f async def main(): L = await asyncio.gather(factorial(2), factorial(3), factorial(4)) print(L) # [2, 6, 24] asyncio.run(main()) Expected output: Computing factorial(2), currently i=2... Computing factorial(3), currently i=2... Computing factorial(4), currently i=2... Computing factorial(3), currently i=3... Computing factorial(4), currently i=3... Computing factorial(4), currently i=4... [2, 6, 24] PS: no matter if you use asyncio or trio or another library, the tutorial of the latter was helpful for me to grok Python asynchronous programming.
type: Answer
upvote count: 44
has comment: http://stackoverflow.com/comment/137777361
has comment: http://stackoverflow.com/comment/139046386
downvote count: 0
has comment: http://stackoverflow.com/comment/110385043
has comment: http://stackoverflow.com/comment/127358829
score: 44

http://stackoverflow.com/q/50793760
possible better answer: http://stackoverflow.com/a/50794038
accepted answer: http://stackoverflow.com/a/50793845
type: AnsweredQuestion
upvote count: 2
downvote count: 3
type: Question
tagged with: combinations
has body: Currently trying to get this to create all possible combinations of these 20 letters in a list, (without repeats) letters = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T'] combinations = [''.join(i) for i in itertools.combinations(letters,r=20)] Output I'm looking for is a list like: combinations = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T',GG,GA,GL,GM... ...GALMFWKQESPVICYHRNDT]
has comment: http://stackoverflow.com/comment/88593624
tagged with: python-itertools
has title: All possible combinations of letters from a list, from 1 to 20 - python
has comment: http://stackoverflow.com/comment/88593858
score: -1
has comment: http://stackoverflow.com/comment/88593836
answer count: 2
has answer: http://stackoverflow.com/a/50793845
has comment: http://stackoverflow.com/comment/88593687
favorite count: 0
tagged with: combinatorics
has answer: http://stackoverflow.com/a/50794038
tagged with: python

http://stackoverflow.com/q/50812539
has comment: http://stackoverflow.com/comment/88630838
has body: I am using tensorflow's DNNRegressor to model a multivariate regression problem. I want to form an optimal feature-set from a mixed bag of categorical and continuous features. What would be the best way to proceed? The reason, I want this approach to be independent of the model is because I couldn't find much about feature selection/evaluation in direct context of tensorflow.
tagged with: python
type: UnansweredQuestion
tagged with: regression
tagged with: feature-extraction
tagged with: tensorflow
type: Question
tagged with: feature-selection
has answer: http://stackoverflow.com/a/50818550
has comment: http://stackoverflow.com/comment/88630644
answer count: 1
has title: What's the best way to select features independent of the model being used?
score: 0

http://stackoverflow.com/a/50823016
type: Answer
has comment: http://stackoverflow.com/comment/88651256
has comment: http://stackoverflow.com/comment/88651508
has comment: http://stackoverflow.com/comment/88651624
has body: You do not need to re-write the header if the header is already in the CSV. Remove writer.writeheader() Ex: import csv def get_details(): pid = get_id() print(pid) data = aliexpress.get_product_details(['productId', 'productUrl', 'discount', 'evaluateScore', 'volume', 'packageType', 'lotNum', 'validTime', 'storeName', 'storeUrl', 'allImageUrls'], pid) with open('data.csv', 'a', newline='') as csvfile: fieldnames = ['productUrl', 'discount', 'evaluateScore', 'volume', 'packageType', 'lotNum', 'validTime', 'storeName', 'storeUrl', 'allImageUrls'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) productUrl = data['productUrl'] discount = data['discount'] evaluateScore = data['evaluateScore'] volume = data['volume'] packageType = data['packageType'] lotNum = data['lotNum'] validTime = data['validTime'] storeName = data['storeName'] storeUrl = data['storeUrl'] allImageUrls = data['allImageUrls'] allImageUrlstuple = allImageUrls.split(',') print(allImageUrls) writer.writerow({'productUrl': productUrl, 'discount': discount, 'evaluateScore': evaluateScore, 'volume': volume, 'packageType': packageType, 'lotNum': lotNum, 'validTime': validTime, 'storeName': storeName, 'storeUrl': storeUrl, 'allImageUrls': allImageUrlstuple})
answers question: http://stackoverflow.com/q/50822660
has comment: http://stackoverflow.com/comment/88653274
score: 0

http://stackoverflow.com/a/50795527
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50795456
type: Answer
answers question: http://stackoverflow.com/q/50795456
upvote count: 3
has body: I'm sorry to disappoint you, but the situation is indeed exactly as you describe in your question: Yes, you do need to mount your remote directory if you want to use os.walk, os.remove, shutil.move, etc. If you use a specialized SFTP library such as paramiko (or calling ssh/sftp via the subprocess module), you'll have to implement the functionaliy of os.walk on your own. By the way, if you decide to implement your own os.walk on top of paramiko, you might want to contribute that function back to paramiko, as it may be helpful for other users of that library, too.

http://stackoverflow.com/comment/88409580
type: QuestionComment
has text: Can you explain why it it should be that way? General oop principles suggest general methods belong in the base class, and more specific methods belong in the children. Since `method3` seems general (behaves the same for `MyClass1` and `MyClass2`) it seems to belong in a base class.
comment on: http://stackoverflow.com/q/50698876
score: 0
type: Comment

http://stackoverflow.com/a/50700330
score: 3
answers question: http://stackoverflow.com/q/50700281
upvote count: 3
downvote count: 0
has body: It sound like you want to use list comprehension! Try c = tuple(x.replace('(','') for x in b) Here's some documentation on list comprehension!
has comment: http://stackoverflow.com/comment/88410251
type: Answer

http://stackoverflow.com/q/50765059
accepted answer: http://stackoverflow.com/a/50765139
tagged with: python
tagged with: vectorization
has title: Most Pythonic way to multiply these two vectors?
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50765139
has comment: http://stackoverflow.com/comment/88538326
linked to: http://stackoverflow.com/q/49901756
type: Question
tagged with: numpy
score: 5
has comment: http://stackoverflow.com/comment/88537749
has comment: http://stackoverflow.com/comment/88542993
has body: I have two ndarrays with shapes: A = (32,512,640) B = (4,512) I need to multiply A and B such that I get a new ndarray: C = (4,32,512,640) Another way to think of it is that each row of vector B is multiplied along axis=-2 of A, which results in a new 1,32,512,640 cube. Each row of B can be looped over forming 1,32,512,640 cubes, which can then be used to build C up by using np.concatenate or np.vstack, such as: # Sample inputs, where the dimensions aren't necessarily known a = np.arange(32*512*465, dtype='f4').reshape((32,512,465)) b = np.ones((4,512), dtype='f4') # Using a loop d = [] for row in b: d.append(np.expand_dims(row[None,:,None]*a, axis=0)) # Or using list comprehension d = [np.expand_dims(row[None,:,None]*a,axis=0) for row in b] # Stacking the final list result = np.vstack(d) But I am wondering if it's possible to use something like np.einsum or np.tensordot to get this vectorized all in one line. I'm still learning how to use those two methods, so I'm not sure if it's appropriate here. Thanks!
answer count: 1
tagged with: numpy-einsum
favorite count: 0
tagged with: tensordot
upvote count: 5

http://stackoverflow.com/q/50823277
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88652550
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50823322
accepted answer: http://stackoverflow.com/a/50823322
has body: I have a quick question on reading excel file using Pandas. The excel file which I have has the format: Num Date Value1 Value2 Value3 1 7/29/11 1 2 3 2 7/22/11 NA 3 1 3 7/15/11 5 NA NA 4 7/6/11 -1 0 2 I would like to read this excel file using pandas. However, I need to keep the rows which have either of the column entries as NA (in this case I need to skip rows 1 and 4).
type: Question
linked to: http://stackoverflow.com/q/44548721
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
has title: i want keep those rows which has null data output using panda

http://stackoverflow.com/a/50794458
answers question: http://stackoverflow.com/q/50793165
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: jdf is a reference to Java Dataset object accessed through Py4j. Python code calls its summary method: jdf = self._jdf.summary(self._jseq(statistics)) Dataset.summary calls StatFunctions.summary method def summary(statistics: String*): DataFrame = StatFunctions.summary(this, statistics.toSeq) Which is implemented like this: def summary(ds: Dataset[_], statistics: Seq[String]): DataFrame = { val defaultStatistics = Seq("count", "mean", "stddev", "min", "25%", "50%", "75%", "max") val selectedStatistics = if (statistics.nonEmpty) statistics else defaultStatistics val percentiles = selectedStatistics.filter(a =&gt; a.endsWith("%")).map { p =&gt; try { p.stripSuffix("%").toDouble / 100.0 } catch { case e: NumberFormatException =&gt; throw new IllegalArgumentException(s"Unable to parse $p as a percentile", e) } } require(percentiles.forall(p =&gt; p &gt;= 0 &amp;&amp; p &lt;= 1), "Percentiles must be in the range [0, 1]") var percentileIndex = 0 val statisticFns = selectedStatistics.map { stats =&gt; if (stats.endsWith("%")) { val index = percentileIndex percentileIndex += 1 (child: Expression) =&gt; GetArrayItem( new ApproximatePercentile(child, Literal.create(percentiles)).toAggregateExpression(), Literal(index)) } else { stats.toLowerCase(Locale.ROOT) match { case "count" =&gt; (child: Expression) =&gt; Count(child).toAggregateExpression() case "mean" =&gt; (child: Expression) =&gt; Average(child).toAggregateExpression() case "stddev" =&gt; (child: Expression) =&gt; StddevSamp(child).toAggregateExpression() case "min" =&gt; (child: Expression) =&gt; Min(child).toAggregateExpression() case "max" =&gt; (child: Expression) =&gt; Max(child).toAggregateExpression() case _ =&gt; throw new IllegalArgumentException(s"$stats is not a recognised statistic") } } } val selectedCols = ds.logicalPlan.output .filter(a =&gt; a.dataType.isInstanceOf[NumericType] || a.dataType.isInstanceOf[StringType]) val aggExprs = statisticFns.flatMap { func =&gt; selectedCols.map(c =&gt; Column(Cas…
score: 9
upvote count: 9
accepted answer of: http://stackoverflow.com/q/50793165

http://stackoverflow.com/comment/88508450
type: QuestionComment
has text: They're finally making BTD6! ;)
score: 0
comment on: http://stackoverflow.com/q/50750324
type: Comment

http://stackoverflow.com/comment/88684790
type: Comment
comment on: http://stackoverflow.com/a/50839421
has text: Sorry, but this is wouldn't be the solution. Using your example (the arr2d as selection array and the arr3d as input array to be filtered) the output new_arr would be [[2,6,6],[5,15,4]] - how to get this output instead?
score: 0
type: AnswerComment

http://stackoverflow.com/q/50761961
type: UnansweredQuestion
tagged with: python
has body: I get HTTPError: Forbidden error when trying to read from a website that requires feedback response in the form of radio buttons. How to resolve this ??? An example url link that causes the error is commented out: url = 'http://www.londonstockexchange.com/exchange/news/market-news/market-news-detail/WWH/13673174.html' Here is the code: import urllib.request as req import re from bs4 import BeautifulSoup # get all text from websites. url = 'https://www.bbc.co.uk/sport/football' #url = 'http://www.londonstockexchange.com/exchange/news/market-news/market-news-detail/WWH/13673174.html' html = req.urlopen(url).read() soup = BeautifulSoup(html) # kill all script and style elements for script in soup(["script", "style"]): script.extract() # rip it out # get text text = soup.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) print(text)
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88531497
type: Question
tagged with: http-error
upvote count: 1
favorite count: 0
has title: HTTPError: Forbidden

http://stackoverflow.com/a/50774965
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88557205
has body: Try this: df = { 'content': ['test1', 'test2', 'test3'], 'email': ['mail1@mail.com', 'mail2@mail.com', 'mail3@mail.com'] } x = 0 for email in df['email']: print(email) print(df["content"][x]+"\n") x+=1
answers question: http://stackoverflow.com/q/50774697

http://stackoverflow.com/comment/88505863
score: 0
has text: Make it a class (object-oriented programming). The usual, minimal methods are probably something like ```build_model``` and ```solve```, sometimes ```preprocess``` (and ```update_parameters```). Yes, there are crazy things like [function-attributes](https://stackoverflow.com/questions/338101/python-function-attributes-uses-and-abuses), but i won't do that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50749138

http://stackoverflow.com/q/50775899
has body: I have a list data and its mean, median and mode as below: data = [2, 3, 5, 5, 7, -6, -6, 9] mean = 2.00 median = 3.00 mode = [5, -6] I want to have a neat Pythonic output of the results. Using the answers recommended here and here I have come up with the following code. print('Mean:{0:9.2f}\nMedian:{1:7.2f}'.format(mean, median), ''.join('\nMode: {}: {}'.format(*k) for k in enumerate(mode))) However, I'm not confident if this is a good solution anyway and my output looks like this: Mean: 2.38 Median: 4.00 Mode: 0: -6 Mode: 1: 5 I want an output like: Mean: 2.38 Median: 4.00 Mode: -6, 5
type: Question
possible better answer: http://stackoverflow.com/a/50776037
linked to: http://stackoverflow.com/q/19400015
upvote count: 2
answer count: 3
has title: Formatting the printing of list concatenated with other variables
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/4440516
has answer: http://stackoverflow.com/a/50776037
accepted answer: http://stackoverflow.com/a/50776092
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50776092
has answer: http://stackoverflow.com/a/50776031

http://stackoverflow.com/comment/88496936
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50744612
has text: My imagination is not great. "Show me", not "tell me".
type: QuestionComment

http://stackoverflow.com/a/50843248
downvote count: 0
answers question: http://stackoverflow.com/q/50843126
has body: You can use an extendible method which does not rely on explicit nested for loops. For example, using itertools.product and filter: from itertools import product a = ['1','2'] b = ['3','4'] c = ['5'] res = ['_'.join(i) for i in product(*filter(None, (a, b, c)))] # ['1_3_5', '1_4_5', '2_3_5', '2_4_5'] With empty c: c = [] res = ['_'.join(i) for i in product(*filter(None, (a, b, c)))] # ['1_3', '1_4', '2_3', '2_4']
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/50792915
tagged with: python
tagged with: video
answer count: 0
type: UnansweredQuestion
has title: Images to Video using opencv
has comment: http://stackoverflow.com/comment/88594982
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/88592527
score: 0
has body: I have a root folder /train_images which have subfolders like /train_images/1 ,/train_images/2...etc. Ech of the subfolders have images in it. I want to make videos corresponding to each subfolder if num(images)>4. Below is the code which I wrote for the same. it works if there is only 1 subfolder,and stops at the creation of 2nd Videowriter object. Please help import cv2 import os root_folder = 'train_images' video_folder = 'output_video' folders = [folder for folder in os.listdir(root_folder)] for folder in folders: child = os.path.join(root_folder,folder) images = [img for img in os.listdir(child) if img.endswith(".jpg")] print('%d images in the path %s' % (len(images),child)) if(len(images)&gt;=4): video_path ='{}.avi'.format(folder) print(video_path) print(os.path.join(video_folder, video_path)) video = cv2.VideoWriter(os.path.join(video_folder, video_path), -1, 5, (224, 320)) for img in images: frame = cv2.imread(os.path.join(child, img)) print('writing from %s' %(os.path.join(child, img)) ) frame_new=cv2.resize(frame,(224,320)) #print(frame_new.shape) video.write(frame_new) cv2.destroyAllWindows() video.release()

http://stackoverflow.com/comment/88426302
comment on: http://stackoverflow.com/q/50708380
score: 0
type: QuestionComment
type: Comment
has text: I'm a little confused with what you want to do, by input and output do you mean input and output to each function you created?

http://stackoverflow.com/q/50779637
score: 1
has title: Detecting frequency of a training set
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50779675
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50779675
favorite count: 0
tagged with: python-3.x
has body: I am trying to detect the frequency of the x-axis which is referred to (m) training set in my LSTM model r,time, x, y, z, m, s,l = np.loadtxt('FINALkneeTRAIN.txt', delimiter = ',', unpack = True) spectrum = fft.fft(m) freq = fft.fftfreq(len(spectrum)) plt(freq, abs(spectrum)) but it gives me the following error: plt(freq, abs(spectrum)) TypeError: 'module' object is not callable
tagged with: frequency
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88562236
score: 0
type: Comment
type: QuestionComment
has text: and if you don't going to have this number...I think the best way is to run an algorithm that check it. the naive way is to run all the number until his root and check
comment on: http://stackoverflow.com/q/50777577

http://stackoverflow.com/a/50831253
accepted answer of: http://stackoverflow.com/q/50831217
upvote count: 4
downvote count: 0
has body: Use function DataFrame.div for divide by Series: perc = crime.mul(100).div(crime.sum(axis=1), axis=0) #perc = (crime *100).div(crime.sum(axis=1), axis=0) print (perc) Violent Murder Larceny_Theft Vehicle_Theft Year 1960 5.180899 55.600457 33.323994 5.894651 1961 5.044283 55.753976 33.345012 5.856730 1962 4.856320 55.579268 33.656487 5.907925 1963 4.650675 55.644649 33.713981 5.990695 1964 4.822943 55.621029 33.295285 6.260742
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50831217
type: Answer

http://stackoverflow.com/q/50846548
has comment: http://stackoverflow.com/comment/88995382
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88696685
has comment: http://stackoverflow.com/comment/88886812
has title: Django + Celery: ImportError: No module named project.urls
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51021925
has comment: http://stackoverflow.com/comment/88699566
tagged with: django
has comment: http://stackoverflow.com/comment/88696629
has comment: http://stackoverflow.com/comment/89023076
tagged with: celery
has comment: http://stackoverflow.com/comment/88699554
has comment: http://stackoverflow.com/comment/88699591
type: AnsweredQuestion
score: 3
upvote count: 3
has body: When I start a worker using Django and Celery using this command (I execute the command within the d directory): celery -A e.project.celery:app worker -l info File "/Users/.../..../e/venv/lib/python2.7/site-packages/celery-4.2.0-py2.7.egg/celery/loaders/base.py", line 108, in import_default_modules raise response ImportError: No module named project.urls I am using Django 1.11 and Celery 4.2 with Python 2.7. Below is my project structure with the contents of some files that should be helpful for debugging. Django structure: d/ __init__.py e/ __init__.py core/ __init__.py app1/ __init__.py tasks.py project/ (project stuff) __init__.py celery.py settings.py urls.py context_processors.py wsgi.py manage.py setup.py settings.py: INSTALLED_APPS = [ '...', 'django_celery_results', 'django_celery_beat' ] CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'redis://foo:foo@127.0.0.1:6599/1' CELERY_CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' e/project/__init__.py: from __future__ import absolute_import, unicode_literals from e.project.celery import app as celery_app __all__ = ('celery_app', ) e/project/celery.py: from __future__ import absolute_import, unicode_literals import os import sys from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "e.project.settings") app = Celery('e_tasks') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() if __name__ == '__main__': app.start() d/e/core/app1/tasks.py: from celery import shared_task @shared_task def hello_world_task(): print('Hello world') My manage.py file: #!/usr/local/bin/python2.7 import os import s…
type: Question
accepted answer: http://stackoverflow.com/a/51021925

http://stackoverflow.com/comment/88432029
comment on: http://stackoverflow.com/q/50711558
has text: `for k in['A', 'B', ...]:`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50718293
favorite count: 0
accepted answer: http://stackoverflow.com/a/50718410
tagged with: range
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I have an n*n grid network where each node has the value (0,0),(0,1)...(n-1,n-1). I need to add an edge so that the average path length(APL) of the network reduces. In order to do that I have to select each node, draw an edge to every other node and check the APL. So I made a nested for loop for this: for x,y in itertools.product(range(n), range(n)): for i,j in itertools.product(range(x,n), range(n)): Here the outer for loop selects the first node and the inner for loop selects the second node. range(x,n) reduces the number of iterations somewhat, similarly is there a way to change range(n) in the inner for loop to something else such that the number of iterations can be reduced? I tried using range((y+1)%n,n) but it won't work because, suppose first node is (0,n-1), then after selecting the second node as (0,n), it won't select (1,0). So is there a way to optimize this?
type: Question
has comment: http://stackoverflow.com/comment/88446106
tagged with: optimization
tagged with: for-loop
tagged with: time-complexity
downvote count: 0
answer count: 1
has title: Nested for loop for grid traversal
has answer: http://stackoverflow.com/a/50718410

http://stackoverflow.com/q/50794146
has title: Find number of times a value appears in a Python dict
score: 0
has answer: http://stackoverflow.com/a/50794815
has body: I'm working with a nested dictionary: { "payload": { "existence_full": 1, "geo_virtual": "[\"56.9459720|-2.1971226|20|within_50m|4\"]", "latitude": "56.945972", "locality": "Stonehaven", "_records_touched": "{\"crawl\":8,\"lssi\":0,\"polygon_centroid\":0,\"geocoder\":0,\"user_submission\":0,\"tdc\":0,\"gov\":0}", "address": "The Lodge, Dunottar", "email": "dunnottarcastle@btconnect.com", "existence_ml": 0.5694238217658721, "domain_aggregate": "", "name": "Dunnottar Castle", "search_tags": [ "Dunnottar Castle Aberdeenshire", "Dunotter Castle" ], "admin_region": "Scotland", "existence": 1, "category_labels": [ [ "Landmarks", "Buildings and Structures" ] ], "post_town": "Stonehaven", "region": "Kincardineshire", "review_count": "719", "geocode_level": "within_50m", "tel": "01569 762173", "placerank": 65, "longitude": "-2.197123", "placerank_ml": 37.27916073464469, "fax": "01330 860325", "category_ids_text_search": "", "website": "http://www.dunnottarcastle.co.uk", "status": "1", "geocode_confidence": "20", "postcode": "AB39 2TL", "category_ids": [ 108 ], "country": "gb", "_geocode_quality": "4" }, "uuid": "3867aaf3-12ab-434f-b12b-5d627b3359c3" } I have to record the number of times 'Museum' appears in the dictionary. The code I wrote below wont print anything and Im not sure what Im missing. Is there another way to iterate through all the values in a dict and count how many times a certain value appears? museum = {} for i in range (0, len(json_file)): try: record = json_file[i]['payload'] for value in record.values(): if value == 'Museum': museum +=1 print(museum) except: continue
type: Question
has comment: http://stackoverflow.com/comment/88594414
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50794815
answer count: 2
has comment: http://stackoverflow.com/comment/88594426
has comment: http://stackoverflow.com/comment/88594389
possible better answer: http://stackoverflow.com/a/50794256
has answer: http://stackoverflow.com/a/50794256
tagged with: python

http://stackoverflow.com/q/50814511
has comment: http://stackoverflow.com/comment/88643125
has body: Running on Windows Server 2012. I've installed Anaconda on my machines, it automatically adds the relevant paths to PATH variable: C:\Users\user1\tools\Anaconda3;C:\Users\user1\tools\Anaconda3\Scripts; From within cmd, it won't allow me to use anaconda to execute the batch file. I must use anaconda.bat. This is the same with all batch files, I've tested it with many. Any idea why and if so, how to fix this?
type: Question
score: 0
answer count: 1
tagged with: windows-server-2012
has answer: http://stackoverflow.com/a/50814730
tagged with: batch-file
linked to: http://stackoverflow.com/q/13320578
tagged with: python
tagged with: cmd
type: UnansweredQuestion
tagged with: anaconda
has title: Windows Server 2012, CMD and Anaconda CMD need .bat extension to run batch files in PATH

http://stackoverflow.com/q/50700617
tagged with: string
favorite count: 0
tagged with: python
has title: extract content between nested parenthesis
type: AnsweredQuestion
has body: I want to extract between ObjectUnionOf( and the first closed parenthese coming after it: &lt;http://www.ifomis.org/bfo/1.1/spanScatteredTemporalRegion&gt; &lt;http://www.ifomis.org/bfo/1.1/spanConnectedTemporalRegion&gt; From EquivalentClasses(&lt;http://www.ifomis.org/bfo/1.1/spanTemporalRegion&gt; ObjectUnionOf(&lt;http://www.ifomis.org/bfo/1.1/spanScatteredTemporalRegion&gt; &lt;http://www.ifomis.org/bfo/1.1/spanConnectedTemporalRegion&gt;)) I tried: content=content[content.find("ObjectUnionOf(")+1:content.find(")")] but it doesn't work
has answer: http://stackoverflow.com/a/50700653
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/50700729
type: Question
has answer: http://stackoverflow.com/a/50700729
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50700653

http://stackoverflow.com/q/50729809
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50730721
tagged with: selenium
possible better answer: http://stackoverflow.com/a/50729980
type: Question
score: 4
answer count: 2
tagged with: macos
has answer: http://stackoverflow.com/a/50729980
favorite count: 0
tagged with: python-3.x
has body: from selenium import webdriver import sys import os cwd = os.getcwd() driver= webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.CHROME,command_executor='http://127.0.0.1:4444') driver.get('http://www.google.com') error: urllib.error.URLError: &lt;urlopen error [Errno 61] Connection refused&gt; this program works a while ago, but now it does not. this is why I think it is a system error. (OSX 10.13.4)
accepted answer: http://stackoverflow.com/a/50730721
tagged with: python
upvote count: 4
has title: Selenium remote webdriver error (Connection refused)

http://stackoverflow.com/comment/88603339
type: QuestionComment
has text: Alternatively, you can scroll down past the first answer...
comment on: http://stackoverflow.com/q/50798493
score: 0
type: Comment

http://stackoverflow.com/comment/88422312
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50706564
has text: I think you should continue your tutorial a bit more re: accessing values in a dictionary by key. If the tutorial doesn't answer the questions then there is an issue. Lots of things won't make sense, however the tutorial structures itself, so hopefully they can answer it by the time you complete the course.
type: Comment

http://stackoverflow.com/comment/88567659
score: 0
type: QuestionComment
has text: @smci I want to, but I am so so lazy...
type: Comment
comment on: http://stackoverflow.com/q/50778770

http://stackoverflow.com/comment/88428543
type: Comment
has text: it stops at 6th line with this error: print("{}|{}|{}|{}".format(title,budget,domesticgross,worldwidegross)) UnicodeEncodeError: 'ascii' codec can't encode characters in position 34-36: ordinal not in range(128)
type: AnswerComment
comment on: http://stackoverflow.com/a/50707925
score: 0

http://stackoverflow.com/a/50742628
score: 1
has body: In Python 3.6+, using f-string: import datetime d = datetime.datetime.now() y = d.strftime("%y") assert f'{y}年' == '18年'
answers question: http://stackoverflow.com/q/50742361
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/50847558
has comment: http://stackoverflow.com/comment/88712171
has comment: http://stackoverflow.com/comment/88698546
accepted answer of: http://stackoverflow.com/q/50847535
answers question: http://stackoverflow.com/q/50847535
has comment: http://stackoverflow.com/comment/88698547
has body: You just need to have your sensorRead.py file in the same folder as dht11.py
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88447657
comment on: http://stackoverflow.com/q/50719575
type: Comment
has text: is the connectivity to the psql open? can you test the connectivity before testing from the lambda?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88560731
score: 1
comment on: http://stackoverflow.com/a/50776223
type: AnswerComment
type: Comment
has text: @roganjosh: people are different. I cannot say "everyone should". But I like that you dont limit your answer to a pure technology question. That's why I upvoted your comment before writing my answer.

http://stackoverflow.com/a/50785957
has comment: http://stackoverflow.com/comment/88578384
downvote count: 0
has comment: http://stackoverflow.com/comment/88578793
upvote count: 2
has comment: http://stackoverflow.com/comment/88579067
type: Answer
has comment: http://stackoverflow.com/comment/88578806
has comment: http://stackoverflow.com/comment/88579093
has comment: http://stackoverflow.com/comment/88578400
score: 2
answers question: http://stackoverflow.com/q/50785716
has body: Like @Wen said: you can caculate mean_a using a rolling function: df['mean_a'] = df['Price'].rolling(3).mean() df['mean_b'] is just df['mean_a'] shifted by -2 df['mean_b'] = df['mean_a'].shift(-2) This returns: # Price mean_a mean_b 0 0 1.00 NaN 5.490000 1 1 12.23 NaN 9.380000 2 2 3.24 5.490000 55.296667 3 3 12.67 9.380000 60.876667 4 6 149.98 55.296667 684.396667 5 7 19.98 60.876667 635.066667 6 8 1883.23 684.396667 630.036667 7 9 1.99 635.066667 5.623333 8 10 4.89 630.036667 9.290000 9 11 9.99 5.623333 13.736667 10 12 12.99 9.290000 16.403333 11 13 18.23 13.736667 18.400000 12 14 17.99 16.403333 18.360000 13 15 18.98 18.400000 18.730000 14 16 18.11 18.360000 19.170000 15 17 19.10 18.730000 646.900000 16 18 20.30 19.170000 7397.200000 17 19 1901.30 646.900000 NaN 18 20 20270.00 7397.200000 NaN EDIT: If you want to avoid some values being NA, you need to use the min_periods parameter. We can create mean_a by df['mean_a'] = df['Price'].rolling(3, min_periods = 1).mean() ,but now we can't create mean_b by shifting - I couldn't think of another straightforward way other than @Wen's method for that. (reversing the price series of the subsection where df['mean_b'] is na: df['mean_b'] = df['mean_a'].shift(-2) df['mean_b'][df['mean_b'].isna()] = df['Price']df['mean_b'].isna()].iloc[::-1].rolling(3,min_periods =1).mean() ; but then it could be less involved if we just reversed the whole series in the first place.

http://stackoverflow.com/a/50799110
has body: You can parse output of find command and use xargs, running this in the same folder of your python files find . -name '*.py' -maxdepth 1 | xargs python in the case you mentioned of hundreds of .py files. Other option you may consider is to create an additional .py file to call your other .py files
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50798806
answers question: http://stackoverflow.com/q/50798806
type: AcceptedAnswer

http://stackoverflow.com/q/50788809
has answer: http://stackoverflow.com/a/50788880
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88584036
has answer: http://stackoverflow.com/a/50788877
has title: Find word index in string in python
has answer: http://stackoverflow.com/a/50788851
possible better answer: http://stackoverflow.com/a/50788877
tagged with: python
tagged with: pytz
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88583990
type: Question
accepted answer: http://stackoverflow.com/a/50788851
has body: I have a list and i want to find index of any words starting with Iran and print them. import pytz word = 'iran' text = str(pytz.all_timezones).lower() for t in text.split(): if t.startswith(word): print(text[t.index(word)]) the output is 'a' and ',' but i need any word containing iran

package
tag name: package
tags question: http://stackoverflow.com/q/50748673
type: Tag
tags question: http://stackoverflow.com/q/50740039
tags question: http://stackoverflow.com/q/50742656
tags question: http://stackoverflow.com/q/50743723
tags question: http://stackoverflow.com/q/50851348
tags question: http://stackoverflow.com/q/50783047

http://stackoverflow.com/comment/88608909
score: 1
comment on: http://stackoverflow.com/q/50801409
type: QuestionComment
has text: Please provide a [mcve] in the question itself. Give an example input with an example output. It is rude to expect people to download off-site resources. Put a little effort into crafting a well-formed, on-topic question and you will receive a much better response to your query.
type: Comment

http://stackoverflow.com/comment/88572963
has text: `packages` has never worked recursively. Either you list all packages and subpackages manually or call `find_packages()`. It always was so.
type: Comment
comment on: http://stackoverflow.com/a/50783010
score: 1
type: AnswerComment

http://stackoverflow.com/q/50836434
has comment: http://stackoverflow.com/comment/88676653
score: 0
has answer: http://stackoverflow.com/a/50837713
answer count: 1
tagged with: reshape
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50837713
tagged with: tensorflow
has title: Keras Tensorflow reshape error during epoch
has body: I am new to Keras and Tensorflow and I am trying to use the LSTM to train on some radar pulse dataset I have. During compilation I have made it work, but when the model starts to train I cannot get it working. I don't know where to place the reshape and which dimensions to use since the numbers that the error gives I don't know where they come from. So the code is: x_train = load_data("D:\\Software_Herramienta\\Datasets\\sweep_switch_train.csv") y_train = load_data("D:\\Software_Herramienta\\Datasets\\sweep_switch_labels_train.csv") x_train = x_train.reshape(-1, x_train.shape[0], x_train.shape[1], 1) y_train.astype(int) y_train = y_train.reshape(1,1000) batch = 10 model = Sequential() model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=(None, x_train.shape[1], 1))) model.add(TimeDistributed(Activation('relu'))) model.add(TimeDistributed(Dense(32, name="first_dense"))) model.add(Reshape((3, 4))) model.add(LSTM(x_train.shape[1], dropout_U=0.2, dropout_W=0.2)) # model.add(Dense(1, activation='softmax')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, epochs=15, batch_size=batch) And the error tells: &gt; Epoch 1/15 2018-06-13 13:40:17.225066: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 Traceback (most recent call last): File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1322, in _do_call return fn(*args) File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1307, in _run_fn options, feed_dict, fetch_list, target_list, run_metadata) File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1409, in _call_tf_sessionrun run_metadata) tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 31872128 values, but …
type: Question
tagged with: keras

http://stackoverflow.com/q/50834143
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88672087
linked to: http://stackoverflow.com/q/50495099
has answer: http://stackoverflow.com/a/50834244
upvote count: 2
downvote count: 3
answer count: 1
duplicate of: http://stackoverflow.com/q/50495099
has title: How to use str.replace in Python 3
accepted answer: http://stackoverflow.com/a/50834244
tagged with: pandas
type: AnsweredQuestion
has body: I am trying to replace patterns by strings in a column of my dataframe. In Python 2 this works fine. df = df['Transaction Description'].str.replace("apple", "pear") But in Python 3 it gives me: TypeError Traceback (most recent call last) &lt;ipython-input-10-1f1e7cb2faf3&gt; in &lt;module&gt;() ----&gt; 1 df = df['Transaction Description'].str.replace("apple", "pear") ~/.local/lib/python3.5/site-packages/pandas/core/strings.py in replace(self, pat, repl, n, case, flags, regex) 2427 def replace(self, pat, repl, n=-1, case=None, flags=0, regex=True): 2428 result = str_replace(self._data, pat, repl, n=n, case=case, -&gt; 2429 flags=flags, regex=regex) 2430 return self._wrap_result(result) 2431 ~/.local/lib/python3.5/site-packages/pandas/core/strings.py in str_replace(arr, pat, repl, n, case, flags, regex) 637 raise TypeError("repl must be a string or callable") 638 --&gt; 639 is_compiled_re = is_re(pat) 640 if regex: 641 if is_compiled_re: ~/.local/lib/python3.5/site-packages/pandas/core/dtypes/inference.py in is_re(obj) 217 """ 218 --&gt; 219 return isinstance(obj, re_type) 220 221 /usr/lib/python3.5/typing.py in __instancecheck__(self, obj) 258 259 def __instancecheck__(self, obj): --&gt; 260 raise TypeError("Type aliases cannot be used with isinstance().") 261 262 def __subclasscheck__(self, cls): TypeError: Type aliases cannot be used with isinstance(). What's the right way to do this in python 3? I am using pandas 0.23.0 in both cases.
favorite count: 0
type: Question

http://stackoverflow.com/comment/88465525
type: QuestionComment
comment on: http://stackoverflow.com/q/50728614
score: 1
has text: if you only want to match that why do you need regex? why not use `find`?
type: Comment

http://stackoverflow.com/comment/90620434
type: Comment
type: QuestionComment
has text: It's relatively okay to use the same descriptor across multiple classes (though still not recommended), but not for two different attributes on the same object.
comment on: http://stackoverflow.com/q/50840794
score: 0

http://stackoverflow.com/a/50820827
has body: While it appears that the apostrophes contain a space they actually do not. email_string = ''.join(str(e) for e in email_list) is different than email_string = ' '.join(str(e) for e in email_list)
type: Answer
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/50820753
upvote count: 0
has comment: http://stackoverflow.com/comment/88647100

http://stackoverflow.com/comment/88526028
comment on: http://stackoverflow.com/a/50758201
score: 0
type: Comment
has text: So it means that by using del(i) I am deleting the object "i" that is created on iteration on list and not the list element. Right?
type: AnswerComment

http://stackoverflow.com/comment/88526742
score: 1
comment on: http://stackoverflow.com/q/50759630
has text: Write a context manager.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50750324
has body: I'm making a Tower Defense game in pygame. I have my background set up and the map is a set of tiles blitted in this way: for x in range(0,640, tile_size): #x starta od 0 i mice se po 32 sve do 640 for y in range (0, 480, tile_size): #y isto window.blit(Tile.Grass, (x,y) Now it's easy to get the mouse position through: if event.type == pygame.MOUSEBUTTONUP: print('Click') pos = pygame.mouse.get_pos() print(pos) But the tiles are 20 by 20 and I need to somehow be able to determine the center position of the tile, so that I can load up my rects and sprites at the proper place.
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: pygame
score: 2
has comment: http://stackoverflow.com/comment/88508722
has title: Pygame clicking on tiles
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50751477
has comment: http://stackoverflow.com/comment/88508450
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88610615
has text: Should be migrated to [code review](https://codereview.stackexchange.com/)
comment on: http://stackoverflow.com/q/50802215
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50828334
has title: Convert incrementing pandas array
score: 0
tagged with: pandas
has body: I have a column that goes: [0,0,1,2,3,0,1,0,1,2] Every time the column restarts at 0, that indicates a new cycle. I want to indicate those cycle iterations with an incrementing array. So the first value is its own cycle. The second through fifth values are part of their own cycles, etc. [1,2,2,2,2,3,3,4,4,4]
has answer: http://stackoverflow.com/a/50828369
has comment: http://stackoverflow.com/comment/88661183
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50828371
has answer: http://stackoverflow.com/a/50828371
accepted answer: http://stackoverflow.com/a/50828369
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/88661191

http://stackoverflow.com/comment/88704301
type: QuestionComment
comment on: http://stackoverflow.com/q/50843520
has text: Please show the actual error and full traceback.
score: 0
type: Comment

http://stackoverflow.com/a/64245030
has comment: http://stackoverflow.com/comment/113607084
score: 0
has comment: http://stackoverflow.com/comment/113611328
has comment: http://stackoverflow.com/comment/113638470
type: Answer
has comment: http://stackoverflow.com/comment/113626395
has body: you can input, in python console : in[1]: pip install gspread the picture was taken after installation, for demonstration
answers question: http://stackoverflow.com/q/50851661
has comment: http://stackoverflow.com/comment/113606850
has comment: http://stackoverflow.com/comment/113606505

http://stackoverflow.com/comment/88461355
type: AnswerComment
has text: That is my understanding as well
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50726031

http://stackoverflow.com/q/50823687
tagged with: regression
accepted answer: http://stackoverflow.com/a/50824364
tagged with: python
type: AnsweredQuestion
type: Question
upvote count: 4
downvote count: 0
answer count: 1
tagged with: keras
score: 4
has answer: http://stackoverflow.com/a/50824364
tagged with: deep-learning
favorite count: 0
has title: How to enforce monotonicity for (regression) model outputs in Keras?
has body: I am currently working on a problem where I provide a neural network with an input variable a, and another input x which is a monotonically increasing sequence of N numbers. So my network would basically looks something like this: a_input = Input(shape=[1], name='a') x_input = Input(shape=[N], name='x') nn = concatenate([a_input, x_input]) nn = Dense(100, activation='relu')(nn) nn = Dense(N, activation='relu')(nn) model = Model(inputs=[a_input, x_input], outputs=[nn]) model.compile(loss='mean_squared_error', optimizer="adam") I perform a regression over the input space (where for each a the sequence x is unique), and I want the network to output a monotonically increasing sequence of (non-negative) N numbers for each set of inputs a and x. Now, I have noticed that so far my outputs are not strictly speaking monotonic, but sort of look like they are if you 'zoom out'. By this I mean, for a given choice of a and x, if I want my output array to look like: [0, 0.5, 0.51, 0.7, 0.75, 0.9, 1.], I might instead get: [0.001, 0.5, 0.48, 0.7, 0.75, 0.9, 1.]. Hence, I would like to know if there are standard ways, or specific tools already available in Keras, to constrain models to only output monotonically increasing sequences?

http://stackoverflow.com/q/50785764
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88719590
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/88712457
has body: I have an Google Flex App Engine App that recieves POSTs with JSON data, then performs an insert statement using SQLAlchemy that writes the JSON data to a Cloud SQL database. The latency between POST device (in Dallas) and App Engine (us-east) is well above 300ms, sometimes spiking over 1500ms. I believe it may be due to poor INSERT write speed, although the load is hardly 'ridiculous' or anything. Roughly up to 5-8 reads/sec and 150-300 writes/sec Using Flask, SQLAlchemy, MySQL 5.6 (on Cloud SQL), and 2nd generation Google Flex App Engine instance. My problem is I need to drop the latency and I can't figure out what is causing it. I have run traceroute and ping commands to the IP that POSTs json data to the Flask App page being hosted by Google App Engine. The ping is fine, there is a hiccup in one hop but it is only one area. If I have too high of a latency, the IP will possibly drop POST. from api import app from sqlalchemy import create_engine from datetime import datetime, timedelta engine = create_engine(app.config.get("database_uri")) Class Events(object): @staticmethod def add(event): connection = engine.connect() for observation in event["observations"]: try: connection.execute("""INSERT INTO events ( ... ) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )""", ( ... )) except Exception as ex: print(ex) connection.close() This is triggered by: @app.route('/', methods=['POST']) def events_post(): data = request.json if data["secret"] != app.config.get("secret"): return Events.add(data["data"]) return "Success"
downvote count: 0
tagged with: google-cloud-sql
has comment: http://stackoverflow.com/comment/88581318
has title: High latency between client, App Engine, and Cloud SQL
tagged with: google-app-engine
tagged with: python
favorite count: 0
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/88600393
comment on: http://stackoverflow.com/q/50797009
has text: You probably mean "I have images from class **`A`**"? But nevertheless, what will you do if `A` has no images, or two or more?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/88481891
type: QuestionComment
has text: Zwer suggetsion is True. I think this could help https://stackoverflow.com/questions/17893542/why-do-os-path-isfile-return-false, so try to replace your condition with print(os.path.isfile("Path_file" + i))
score: 0
comment on: http://stackoverflow.com/q/50737109
type: Comment

http://stackoverflow.com/a/50753268
upvote count: 1
downvote count: 1
has body: One method would be (as stated in the previous answer) is to use exe converters, but that wouldn't be as effective if you target Mac and Linux users as well. My solution is going to take you a little more time, but it will be worth it. Here goes: Please learn Angular JS, or some other framework (I prefer Angular). Once you know that, you can easily develop a web app for your project, and add your Python to that. The good news is, there are lots of tutorials for this, such as https://codehandbook.org/creating-a-web-app-using-angularjs-python-mongodb/ (also teaches you mongodb) Anyways, you can find other tutorials on your own. You could of course, I guess, build it into a mobile app, but I think web app would be easier.
score: 0
answers question: http://stackoverflow.com/q/50753195
type: Answer

http://stackoverflow.com/comment/88588286
type: AnswerComment
type: Comment
has text: @pyd what specifically do you want to know about this?
score: 1
comment on: http://stackoverflow.com/a/50731254

http://stackoverflow.com/comment/88491617
comment on: http://stackoverflow.com/a/50741742
type: AnswerComment
has text: Same comment as for the other answer: Since the OP plans to run this millions of times, you may want to pre-allocate a df and overwrite df['Sum of percentage']. Slightly more efficient than copying Species and OGT every time.
score: 0
type: Comment

http://stackoverflow.com/q/50832814
tagged with: ordereddictionary
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88682457
has comment: http://stackoverflow.com/comment/88669893
type: Question
has answer: http://stackoverflow.com/a/50833328
tagged with: python
tagged with: dictionary
has body: I have a deeply nested dictionary as such: {u'1009': {u'2017': {u'April': {u'Revenue': 36087, u'Total_users': 107, u'Unique_users': 79}, u'August': {u'Revenue': 103458, u'Total_users': 314, u'Unique_users': 208}, u'December': {u'Revenue': 132834, u'Total_users': 440, u'Unique_users': 241}, u'July': {u'Revenue': 98120, u'Total_users': 356, u'Unique_users': 212}, u'June': {u'Revenue': 88315, u'Total_users': 293, u'Unique_users': 169}, u'May': {u'Revenue': 114438, u'Total_users': 348, u'Unique_users': 203}, u'November': {u'Revenue': 114747, u'Total_users': 414, u'Unique_users': 233}, u'October': {u'Revenue': 114073, u'Total_users': 339, u'Unique_users': 223}, u'September': {u'Revenue': 87587, u'Total_users': 290, u'Unique_users': 190}}, u'2018': {u'April': {u'Revenue': 4780, u'Total_users': 13, u'Unique_users': 12}, u'February': {u'Revenue': 99922, u'Total_users': 354, u'Unique_users': 205}, u'January': {u'Revenue': 195031, u'Total_users': 429, u'Unique_users': 239}, u'March': {u'Revenue': 111568, u'Total_users': 359, u'Unique_users': 222}}}, u'1051': {u'2017': {u'August': {u'Revenue': 11700, u'Total_users': 40, u'Unique_users': 26}, u'July': {u'Revenue': 39730, u'Total_users': 132, u'Unique_users': 42}, u'June': {u'Revenue': 16320, u'Total_users': 54, u'Unique_users': 36}, u'May': {u'Revenue': 47572, u'Total_users': 160, u'Unique_users': 141}, u'September': {u'Revenue': 250, u'Total_users': 1, u'Unique_users': 1}}}, u'1056': {u'2017': {u'August': {u'Revenue': 1426, u'Total_users': 6, u'Unique_users': 6}, u'December': {u'Revenue': 380, u'Total_users': 2, u'Unique_users': 2}, u'July': {u'Revenue': 6220, u'Total_users': 20, u'Unique_users': 11}, u'June': {u'Revenue': 20370, u'Total_users': 66, u'Unique_users': 35}, u'May': {u'Revenue': 57566, u'Total_users': 181, u'Unique_users': 127}, u'November': {u'Revenue': 250, u'Total_users': 1, u'Unique_users': 1}, u'October': {u'Revenue': 250, u'Total_users': 1, u'Unique_users': 1}, u'September': {u'Revenue': 1000, u'Total_users'…
has title: Sort for a specific key in a deeply nested dictionary
tagged with: http://stackoverflow.com/tag/json
score: 0
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/90158272
type: Comment
type: QuestionComment
has text: @AshwaniShakya In my current `mappings` in above code I have `analyzer` added for language. So when I add `settings` section what do I specify in the `analyzer` section of mappings? Do I remove it or do I update it?
comment on: http://stackoverflow.com/q/50764855
score: 0

http://stackoverflow.com/comment/105432517
has text: @yrekkehs gotcha, and I agree :)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/56368864

http://stackoverflow.com/q/50750048
has title: Text correlation in Python
score: -1
has answer: http://stackoverflow.com/a/50750227
has body: I am analyzing a survey that has "Yes" or "No" questions. I want to find the strongest correlation between questions and the answers. For example, if someone answers "Yes" to Question 1 what is the correlation that they would also respond "Yes" to Question 2? Could it be as easy as assigning each answer to a numeric value (0 + 1)? I hope that I made this clear enough. Thank you!
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88507872
has comment: http://stackoverflow.com/comment/88509211
accepted answer: http://stackoverflow.com/a/50750227
tagged with: python
type: AnsweredQuestion
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88508121
type: Question

http://stackoverflow.com/comment/88578511
score: 1
comment on: http://stackoverflow.com/q/50785017
has text: @jpp I edited the code above to save a tex file as well. Thank you for trying to help!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50765460
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/50765921
downvote count: 1
type: Question
has title: Why is .join() method called .join() in the threading module?
type: AnsweredQuestion
has body: This is a rather silly question...yet it bugs the heck out of me. In the threading module we have a Thread.join() method. I understand that it blocks the calling thread, but why is .join() called 'join'? Why is it not called main_thread_wait or block_parent_thread or something like that? Every time I see .join(), I feel the child thread is joining something to get caclulations done. Is there some reason why this particular keyword was chosen for a method name?
linked to: http://stackoverflow.com/q/15085348
answer count: 2
score: 2
has comment: http://stackoverflow.com/comment/88538453
has answer: http://stackoverflow.com/a/50765921
favorite count: 0
has comment: http://stackoverflow.com/comment/88538538
tagged with: python-multithreading
tagged with: python
possible better answer: http://stackoverflow.com/a/50765825
linked to: http://stackoverflow.com/q/25345418
has answer: http://stackoverflow.com/a/50765825
upvote count: 3

http://stackoverflow.com/comment/88578707
has text: I need the Geolocation x = longitude, y = latitude
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50785972

http://stackoverflow.com/comment/88423543
type: Comment
comment on: http://stackoverflow.com/q/50707161
type: QuestionComment
score: 0
has text: and can you give us django version? since if it's django 2.x, namesapces are defined in app's urls.py with `app_name` variable and namespace inclusion in url function is removed

http://stackoverflow.com/comment/88534787
type: QuestionComment
score: 2
has text: @mad_ that would not work for what is required
comment on: http://stackoverflow.com/q/50763508
type: Comment

http://stackoverflow.com/comment/88652473
type: Comment
comment on: http://stackoverflow.com/a/50823618
type: AnswerComment
has text: How can I also print the line number that each line is on?
score: 0

http://stackoverflow.com/comment/88625358
score: 0
type: Comment
type: QuestionComment
has text: Can you put some sample data, and expected output that you want?
comment on: http://stackoverflow.com/q/50809879

http://stackoverflow.com/a/50711669
has comment: http://stackoverflow.com/comment/88432653
has comment: http://stackoverflow.com/comment/88433120
has comment: http://stackoverflow.com/comment/88470084
downvote count: 1
has body: Check your build pack is python, be sure to include your requirements.txt and check the other important check items in the build list from this article https://medium.com/the-andela-way/deploying-your-flask-application-to-heroku-c99050bce8f9
score: -1
answers question: http://stackoverflow.com/q/50711572
has comment: http://stackoverflow.com/comment/88432386
upvote count: 0
type: Answer

http://stackoverflow.com/q/50758127
has title: Why is the code not able to find the file specified in the AWS S3 path, when I can find it manually?
answer count: 2
has body: I have a bucket called my_bucket and a folder in it called Images. I am trying to read the files (images) inside the Image folder. file = pd.read_csv(some_csv_file) X = file.values[:,0] role = get_execution_role() bucket='my_bucket' data_key = 'Images' data_dir = 's3://{}/{}'.format(bucket, data_key) s = '/' for img_name in X: seq = (data_dir, img_name) img_path = s.join(seq) img = imread(img_path) But it gives the following error: --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) &lt;ipython-input-20-a273242ed30e&gt; in &lt;module&gt;() 43 img_path = s.join(seq) 44 print(img_path) ---&gt; 45 img = imread(img_path) 46 img = imresize(img, (32, 32)) 47 img = img.astype('float32') # this will help us in later stage ~/anaconda3/envs/python3/lib/python3.6/site-packages/numpy/lib/utils.py in newfunc(*args, **kwds) 99 """`arrayrange` is deprecated, use `arange` instead!""" 100 warnings.warn(depdoc, DeprecationWarning, stacklevel=2) --&gt; 101 return func(*args, **kwds) 102 103 newfunc = _set_function_name(newfunc, old_name) ~/anaconda3/envs/python3/lib/python3.6/site-packages/scipy/misc/pilutil.py in imread(name, flatten, mode) 162 """ 163 --&gt; 164 im = Image.open(name) 165 return fromimage(im, flatten=flatten, mode=mode) 166 ~/anaconda3/envs/python3/lib/python3.6/site-packages/PIL/Image.py in open(fp, mode) 2541 2542 if filename: -&gt; 2543 fp = builtins.open(filename, "rb") 2544 exclusive_fp = True 2545 FileNotFoundError: [Errno 2] No such file or directory: 's3://my_bucket/Images/377.jpg' 377.jpg is the first row in X. I checked manually in the S3 storage; this file is present there. So, why am I getting this error, and how to fix it? The only reason I can think of is, maybe the process of specifying the S3 path is wrong - but in the S3 documentation, the process to specify storage is given as 's3://{}/{}'.format(bucket, data_key). Moreover, in the last line of the error message, the filenam…
tagged with: amazon-web-services
tagged with: amazon-sagemaker
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88534384
has answer: http://stackoverflow.com/a/50759869
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/88524854
downvote count: 1
has comment: http://stackoverflow.com/comment/88525176
type: Question
has answer: http://stackoverflow.com/a/59527208
tagged with: amazon-s3

http://stackoverflow.com/a/50839837
upvote count: 1
has body: It's convenient to use pandas library for the task. Just create dataframe using the lists and apply df.drop_duplicates with keep=False (means remove all duplicated rows): import pandas as pd dct = { "X": [1, 1, 2, 3, 4, 5, 5, 5], "Y": [3, 3, 2, 6, 7, 1, 1, 2], "Z": [0, 0, 1, 1, 2, 3, 3, 4], } d = pd.DataFrame(dct) d.drop_duplicates(keep=False)
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50839690

http://stackoverflow.com/q/50779346
has answer: http://stackoverflow.com/a/50779435
tagged with: numpy
has comment: http://stackoverflow.com/comment/88565739
possible better answer: http://stackoverflow.com/a/50779435
tagged with: arrays
downvote count: 0
has body: First, I tried to find an answer to my question ( which I think is pretty basic) searching in google and in the site, but nothing came up. I'm trying to get the rows from a numpy matrix, but I can't. For example if I use this: result = numpy.matrix([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) for p in result: print(p[0]) prints this: [[11 12 13]] [[21 22 23]] [[31 32 33]] The same if I use just p What I have to do to access every row? numpy.nditer(result) prints an array, and I need every row to perform some operations.
type: Question
answer count: 3
tagged with: matrix
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16468717
has answer: http://stackoverflow.com/a/50779377
has comment: http://stackoverflow.com/comment/88565604
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50779570
score: 9
tagged with: python
has title: Iterate over a numpy Matrix rows
upvote count: 9
has comment: http://stackoverflow.com/comment/88566033
accepted answer: http://stackoverflow.com/a/50779377

http://stackoverflow.com/q/50807076
answer count: 1
linked to: http://stackoverflow.com/q/6340351
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88622445
has title: Python - List compare and decision
type: Question
has answer: http://stackoverflow.com/a/50808692
has body: I am not a developer, do some python coding for the ease of my work. The new project i am working on is to have two excel files, compare them and generate changes. for the files, we will call them as Old File and New File. Both files got fixed columns but row may vary. in both files, most of the data are identical in same row and column, but some data may vary. say two sample columns from each files are Old File New File id item id item ------------------- ----------------------------- 1 apple, banana 1 banana, grape 2 grape 2 apple 3 orange I have read the files using nested list. For example old file data would be like old_file_list = [ ['1','apple,banana'], ['2','grape'], ['3','orange'] ] new_file_list = [ ['1','banana,grape'], ['2','apple'] ] need to generate following output based on the data above, print output item old_file_id new_file_id status ---------------------------------------------- apple 1 2 changed orange 3 - deleted grape 2 1 changed Please guide me how to achieve this, many thanks
score: 0

http://stackoverflow.com/comment/88635367
type: Comment
has text: I still can't create a pdf out of my current page. My problem is that I can't get out of creating a "hello world". creating every single pdf manually is not an option when users create their own services with dynamic data. The code works and creates a pdf, but only pdf I can make is a random text I write into a spot of "hello world" Got through the ReportLab documentation and getting out of the ideas. Maybe another technology (not Report lab but something that just works with current dynamic page view)
comment on: http://stackoverflow.com/a/50815115
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88712732
has text: Does not sound like a good idea. Managing objects that dynamically extend themselves, the class they are instances of and views that use them is a recipe for desaster. If I wanted to have sort of dynamic attributes on user profiles, I'd either go for an extra profile field that can store serialized key-value pairs to hold the extended information or use some sort intermediary model that has an FK reference to a profile an then holds a name and a value. For each extended attribute you want to add, you'd create such an object.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50854694
score: 1

http://stackoverflow.com/a/50848069
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/88699515
has body: import re r1 = re.compile(r'(Nombre vernáculo)') x = 'Nombre vernáculo registrado en la zona de' match = r1.search(x) print(match.group(1)) with python 2: /tmp&gt; python2 test.py File "test.py", line 5 SyntaxError: Non-ASCII character '\xc3' in file test.py on line 5, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details with python 3: /tmp&gt; python3 test.py Nombre vernáculo
type: Answer
has comment: http://stackoverflow.com/comment/88727863
downvote count: 1
answers question: http://stackoverflow.com/q/50847976

http://stackoverflow.com/comment/88639284
has text: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[contains(text(), 'siguiente')] I am working on it now
comment on: http://stackoverflow.com/q/50814291
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88603657
has text: Small file meaning that I should eliminate some of the data? I could try that, I just wouldn't have a reference, since I have been using the MATLAB code to compare.
comment on: http://stackoverflow.com/q/50761126
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88489699
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50729027
has text: @DanielRoseman Thank you for looking into this question. I want to use a relative path so that when I deploy the application in production I don't have to change the path every time. In logs what I did is relative path so now its not dependent on my machine but just on my code base. I hope this makes it clear. Let me know if you have more questions.

object
tags question: http://stackoverflow.com/q/50845553
tag name: object
tags question: http://stackoverflow.com/q/50806899
tags question: http://stackoverflow.com/q/50722162
tags question: http://stackoverflow.com/q/50764929
tags question: http://stackoverflow.com/q/50820678
type: Tag

http://stackoverflow.com/comment/88480186
type: QuestionComment
comment on: http://stackoverflow.com/q/50736210
score: 0
has text: I believe it is because `arg2` is only assigned the default value (empty array) the first time it is called. Then any subsequent calls that do no provide a value will use the same instance that way originally created. So the 3 call will use the array that was created in the first call, which already has `1` appended to it.
type: Comment

http://stackoverflow.com/comment/88480357
type: Comment
comment on: http://stackoverflow.com/a/50735943
has text: @MAK please don't change the requirements of your question after somebody has answered you. That makes people who want to help you pull their hair out. You said you wanted to count the lines, nothing more. if you have a new question, compose a new question.
score: 1
type: AnswerComment

http://stackoverflow.com/q/50798150
has answer: http://stackoverflow.com/a/50798910
answer count: 1
favorite count: 0
tagged with: windows
tagged with: restart
has body: I am creating a script to restart windows service through Python script but getting the below error: Script error Code: import win32serviceutil class serviceRestart: serviceName = "MySQL57" win32serviceutil.RestartService(serviceName) if __name__ == '__main__': lm = serviceRestart()
tagged with: python
accepted answer: http://stackoverflow.com/a/50798910
has title: How to restart windows service through Python script?
upvote count: 1
tagged with: windows-services
downvote count: 1
type: Question
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50710416
downvote count: 1
has body: You could use Python to automate an instance of the Excel application, opening each file, and saving as .xlsx: import win32com.client excelApp = win32com.client.Dispatch('Excel.Application') book = excelApp.Open(path_to_html_file) book.SaveAs(path_to_html_file + '.xlsx', 51)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50705901
answers question: http://stackoverflow.com/q/50705901
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/50805588
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has title: Installing wxPython with pip (Python2.7)
has comment: http://stackoverflow.com/comment/88682315
has answer: http://stackoverflow.com/a/67981887
type: Question
has body: I'm trying to install wx python from MacOS Terminal, having tried the following 2 approaches: python -m pip install wxPython (also tried "...-U wxPython") sudo -H pip install wxPython I get the following error both times: Collecting wxPython Could not fetch URL https://pypi.python.org/simple/wx/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping Could not find a version that satisfies the requirement wxPython (from versions: ) No matching distribution found for wxPython Using Python 2.7. Any advice would be greatly appreciated!
has comment: http://stackoverflow.com/comment/88617507
upvote count: 2
tagged with: python-2.7
answer count: 2
tagged with: wxpython
possible better answer: http://stackoverflow.com/a/67981887
favorite count: 0
has answer: http://stackoverflow.com/a/50827085
accepted answer: http://stackoverflow.com/a/50827085

http://stackoverflow.com/comment/88660998
has text: Anyway, [you can write code that recurses through a JSON-style structure trivially](https://gist.github.com/abarnert/f53dd428ea637aaba6c8efa5498ca92c), and it's worth learning how to do that.
type: QuestionComment
comment on: http://stackoverflow.com/q/50828170
type: Comment
score: 2

http://stackoverflow.com/q/50717813
has comment: http://stackoverflow.com/comment/88444011
score: -4
has body: I'm trying to get the max and min between to lists in order to make a calculation later on but I keep getting a syntax error and I don't know what is wrong. here is my code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy import stats data = pd.DataFrame({"concentratie": [0.05, 0.10, 0.15, 0.20, 0.30, 0.50, 0.75, 1.00], "absorptie": [0.415, 0.509, 0.573, 0.640, 0.686, 0.711, 0.724, 0.733], "Duplo": [0.446, 0.529, 0.622, 0.638, 0.675, 0.702, 0.715, 0.732]}) def function(absorptie, Duplo): list 3 = [max(value) for value in zip(data['absorptie'],data['Duplo'])] return list 3 def function(absorptie, Duplo): list 4 = [min(value) for value in zip(absorptie, Duplo)] return list 4
type: Question
downvote count: 4
has title: getting a min and max between two lists
has comment: http://stackoverflow.com/comment/88444004
has answer: http://stackoverflow.com/a/50717878
tagged with: min
tagged with: compare
tagged with: max
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: list

http://stackoverflow.com/q/50705881
type: Question
accepted answer: http://stackoverflow.com/a/50706000
has body: I want to scroll the contacts of web WhatsApp and click on the particular contact. I am able to scroll the contacts but not able to find the specific element to get particular contact because HTML is dynamic, as I scroll the contacts it gets changed. Here is the code: target = '"name"' panel = driver.find_element_by_class_name('_1NrpZ') a = 0 while elem is None: a += 5 try: driver.execute_script('arguments[0].scrollTop = %s' %a, panel) elem = driver.find_element_by_xpath('//span[@title=' + target + ']') time.sleep(5) except: pass ac = ActionChains(driver) ac.move_to_element(elem).click().perform() time.sleep(2) It does not stop and keeps scrolling until the last contact. I think when I scroll new HTML is not loaded so is there any solution?
has answer: http://stackoverflow.com/a/50706000
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Scroll and find an element using selenium python
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
tagged with: selenium
upvote count: 1

http://stackoverflow.com/q/50716835
has comment: http://stackoverflow.com/comment/88443453
type: Question
has comment: http://stackoverflow.com/comment/88442831
accepted answer: http://stackoverflow.com/a/50718041
tagged with: python
has answer: http://stackoverflow.com/a/50717190
has title: Multiplying a Python MaskedColumn
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/50717190
tagged with: astropy
has answer: http://stackoverflow.com/a/50717211
has body: I'm reading in a .html file of data, and all I'd like to do is multiply the data['ra'] column by 15. However, I'm getting an error:: &gt;&gt;&gt; data = ascii.read("Ldwarf.html", format="html", encoding = "ISO-8859-1") &gt;&gt;&gt; data &lt;Table masked=True length=919&gt; designation ra decl 2MASS J00011217+1535355 0.0200472 +15.593194 2MASS J00025097+2454141 0.0474917 +24.903917 2MASS J00040288-6410358 0.0674667 -64.176611 and &gt;&gt;&gt; data['ra'] &lt;MaskedColumn name='ra' dtype='str10' length=919&gt; decimal hr 0.0200472 0.0474917 ... 23.9783250 23.9993389 &gt;&gt;&gt; data['ra'] = data['ra'].filled([-9.99]) &gt;&gt;&gt; data['ra'] = data['ra']*15. TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('&lt;U32') dtype('&lt;U32') dtype('&lt;U32') What is going on??
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50718041

http://stackoverflow.com/a/50740541
has body: This is one way in Python: with open('file.txt') as f: for line in f: if line.startswith('date'): date = line continue print(date, line) Output: date 1 line 1 date 1 line 2 date 1 line 3 date 2 line 4 date 2 line 5 date 2 line 6 date 3 line 7 date 3 line 8 date 3 line 9
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50740414
has comment: http://stackoverflow.com/comment/88492784
has comment: http://stackoverflow.com/comment/88492299
type: Answer
has comment: http://stackoverflow.com/comment/88490013

http://stackoverflow.com/comment/88582695
comment on: http://stackoverflow.com/a/50788156
score: 1
type: AnswerComment
type: Comment
has text: @MelissaStewart: no, that would mean quizzes where `user` is both a `winner` and `loser`.

http://stackoverflow.com/a/50699840
has body: Go to this location and make a short cut: C:\Python36\Lib\site-packages\spyder\app\start.py Replace Python36 with the folder in which you installed python. If you double click on start.py it will run spyder. Edit: you can find the spyder .ico online and use it for the shortcut.
has comment: http://stackoverflow.com/comment/88414294
has comment: http://stackoverflow.com/comment/88409424
type: Answer
answers question: http://stackoverflow.com/q/50699698
has comment: http://stackoverflow.com/comment/88409184
has comment: http://stackoverflow.com/comment/88410089
has comment: http://stackoverflow.com/comment/88414637
has comment: http://stackoverflow.com/comment/88409517
has comment: http://stackoverflow.com/comment/88409390
score: 0

http://stackoverflow.com/a/74560817
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50846719
has body: How to remove escape sequence character in dataframe Data. product,rating pest, test mouse,/ mousetest Solution: scala Code val finaldf = df.withColumn("rating", regexp_replace(col("rating"), "\\\\", "/")).show()

http://stackoverflow.com/q/50798162
tagged with: python
has answer: http://stackoverflow.com/a/50798233
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: Python Error when class constructor calling from different file
accepted answer: http://stackoverflow.com/a/50798233
has body: I am reading frames using opencv and displaying it in browser but in order to avoid messy code I wrote my code in different files and importing them. I wrote three files: Flask_sh.py open_webcam.py show_gray.py The open_webcam.py has a class Camera and a method get_frame. open_webcam.py class Camera(): def get_frame(self): success, image = self.cap.read() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() The show_gray.py also has a class named Calulate() and a method cal. show_gray.py class Calculate(): def cal(frame,self): print(type(frame)) frame = imutils.resize(frame, width=640) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) return gray Now the Flask_sh.py is the file where I am calling both my files. Flask_sh.py from open_webcame import Camera from show_gray import Calculate while True: camera = Camera() frame = camera.get_frame() decoded = cv2.imdecode(np.frombuffer(frame, np.uint8), -1) #convert from bytes to np array cam1 = Calculate() frame1 = cam1.cal(decoded) cv2.imshow("Output", frame1) Now I don't know where the issue is because get frame function is running fine and I am able to decode the image from bytes to array. But when I pass the decoded to cal method it gives me error in the first line iself as: Error frame = imutils.resize(frame, width=640) AttributeError: 'show_gray' object has no attribute 'shape' But when instead of making show_gray.py I write the code in Flask_sh.py I get the output. What am I doing wrong.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/50825883
has comment: http://stackoverflow.com/comment/88687897
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50825816
type: Answer
upvote count: 2
has body: The easiest thing to do is to do this manually. Without an example of your code, I have to make a lot of assumptions and write something pretty vague, so let's take the simplest case. Assume you're using dill manually, so your existing code looks like this: obj = function_that_creates_giant_object() for i in range(zillions): results.append(pool.apply(func, (dill.dumps(obj),))) All you have to do is move the dumps out of the loop: obj = function_that_creates_giant_object() objpickle = dill.dumps(obj) for i in range(zillions): results.append(pool.apply(func, (objpickle,))) But depending on your actual use, it may be better to just stick a cache in front of dill: cachedpickle = functools.lru_cache(maxsize=10)(dill.dumps) obj = function_that_creates_giant_object() for i in range(zillions): results.append(pool.apply(wrapped_func, (cachedpickle(obj),)) Of course if you're monkeypatching multiprocessing to use dill in place of pickle, you can just as easy patch it to use this cachedpickle function. If you're using multiprocess, which is a forked version of multiprocessing that pre-substitutes dill for pickle, it's less obvious how to patch that; you'll need to go through the source and see where it's using dill and get it to use your wrapper. But IIRC, it just does a import dill as pickle somewhere and then uses the same code as (a slightly out-of-date version of multiprocessing), so it isn't all that different. In fact, you can even write a module that exposes the same interface as pickle and dill: import functools import dill def loads(s): return dill.loads(s) @lru_cache(maxsize=10) def dumps(o): return dill.dumps(o) … and just replace the import dill as pickle with import mycachingmodule as pickle. … or even monkeypatch it after loading with multiprocess.helpers.pickle = mycachingmodule (or whatever the appropriate name is—you're still going to have to find where that relevant import happens in the source of whatever you're using). And that's about as complicated as it'…
has comment: http://stackoverflow.com/comment/88690625

http://stackoverflow.com/a/50801291
type: Answer
has comment: http://stackoverflow.com/comment/88609507
has comment: http://stackoverflow.com/comment/88608918
has comment: http://stackoverflow.com/comment/88609037
score: 3
has comment: http://stackoverflow.com/comment/88609562
upvote count: 3
has comment: http://stackoverflow.com/comment/88609420
has comment: http://stackoverflow.com/comment/88608666
has body: The default value for end is '\n', meaning that print() will write a newline character after printing the arguments. This would put the cursor on the next line. Usually, stdout (to which print() writes by default) is also line buffered, meaning that data written to it is not flushed (and shown on your terminal) until a newline character is seen, to signal the end of the line. You replaced the newline with a space, so no newline is written; instead a space is written, letting you write successive numbers one after the other on the same line. Add an extra, empty print() call after your for loop to write the newline after looping: for i in range(5): print(i, end=' ') print() You could also add flush=True to the print(..., end=' ') calls to explicitly flush the buffer. Alternatively, for a small enough range(), pass in the values to print() as separate arguments, leaving end at the default. Separate arguments are separated by the sep argument, by default set to a space: print(*range(5)) The * in front of the range() object tells Python to loop over the range() object and pass all values that produces as separate arguments to the print() call; so all 5 numbers are printed with spaces in between and a newline character at the end: &gt;&gt;&gt; print(*range(5)) 0 1 2 3 4
has comment: http://stackoverflow.com/comment/88609246
has comment: http://stackoverflow.com/comment/88609377
downvote count: 0
answers question: http://stackoverflow.com/q/50801259

http://stackoverflow.com/comment/88429167
type: AnswerComment
has text: Sure! I am also doing nslookup to integrate fqdn value along with the ping status. so I'll be updating the whole code for that
type: Comment
comment on: http://stackoverflow.com/a/50709827
score: 0

http://stackoverflow.com/comment/88475519
has text: It's hard to tell what's wrong without seeing the page source. IMHO your solution is not the best way to deal with iframes... :)
score: 0
comment on: http://stackoverflow.com/q/50729310
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50756758
score: 4
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50756898
tagged with: python
upvote count: 4
has body: Here's my dataset customer_id hour size 1 0 1 1 1 18 2 1 7 Here's my code table = a.pivot_table(index=['customer_id'], columns='hour', fill_value=0, values='size') Here's what I've got hour 0 1 customer_id 1 1 18 2 8 7 What I need hour 0 1 count sum customer_id 1 1 18 2 19 2 0 7 1 7 count 1 2 sum 1 25 count is non-zero count in a category and sum is sum in a category
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88521353
tagged with: pivot-table
type: Question
has title: How do I add sum and count on a pivot table
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88552827
accepted answer: http://stackoverflow.com/a/50756898
answer count: 1

http://stackoverflow.com/comment/88691996
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50837793
has text: When using a histogram one of the two axes are going to be the frequency. If we were to use time as the X axes we would force distribution to be on the y, which we already know to be 1 per column.

priority-queue
tags question: http://stackoverflow.com/q/50798650
tag name: priority-queue
type: Tag

http://stackoverflow.com/comment/88623081
type: Comment
type: QuestionComment
has text: My mistake - the encoding belongs with the open.`file=open('pdftotext.txt','w', encoding="utf-16")`
comment on: http://stackoverflow.com/q/50808297
score: 1

http://stackoverflow.com/a/50773026
score: 0
type: Answer
has body: You can override the open() builtin and replace it with your own, which uses utf-8 by default: Create a file custom_open.py with the following function: import builtins def open(*args, **kwargs): kwargs["encoding"] = "utf8" return builtins.open(*args, **kwargs) Now, you can add from custom_open import open to your existing files and the open() function will be overriden, effectively opening all your files in UTF-8. It's true that it involves changing the existing code, but you just need to add one import to the existing files to make it work. If you're using Python 2, the builtins module should be replaced by __builtin__ instead: import __builtin__ def open(*args, **kwargs): kwargs["encoding"] = "utf8" return __builtin__.open(*args, **kwargs)
answers question: http://stackoverflow.com/q/50738403

http://stackoverflow.com/comment/88699124
comment on: http://stackoverflow.com/a/50843371
type: Comment
has text: Please consider using proper [query parameters](https://cloud.google.com/bigquery/docs/parameterized-queries) instead of modifying the text of the query, too :)
score: 0
type: AnswerComment

http://stackoverflow.com/q/50825336
linked to: http://stackoverflow.com/q/3706128
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: win32gui
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/50826897
answer count: 1
has comment: http://stackoverflow.com/comment/88655526
has body: I want to be able to detect the presence of a specifically named window (in any process) to use as an "if" variable After some research, I've concluded I must use the win32gui library (some posts also suggest ctypes), but most of the posts I find are about making a list of processes, and the only one that was related to this topic didn't answer the question properly. Perhaps I am too novice to understand it, but at last, I couldn't get it to work (the question was this one) To exemplify what I want, I'll share a simple .vbs code that does that: It searches for a specific name (in our case, steve jobs) and if it finds it anywhere, it triggers (in this example, it closes said process) do WindowTitle = "steve jobs" set shell = createObject("wscript.shell") success = shell.appactivate(WindowTitle) if success then shell.sendkeys "%{F4}" loop
favorite count: 0
has title: Python get specific window title
has comment: http://stackoverflow.com/comment/88656149
accepted answer: http://stackoverflow.com/a/50826897
tagged with: python

http://stackoverflow.com/q/50809802
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: PDF to IMG to PDF all done in memory
tagged with: python
has comment: http://stackoverflow.com/comment/88626802
tagged with: in-memory
has body: In order to remove sensitive content from a PDF, I am converting it to image and back to PDF again. I am able to do this while saving the jpeg image, however I would eventually like to adapt my code so that the file is in memory the whole time. PDF in memory -> JPEG in memory -> PDF in memory. I'm having trouble with the intermediary step. from pdf2image import convert_from_path, convert_from_bytes import img2pdf images = convert_from_path('testing.pdf', fmt='jpeg') image = images[0] # opening from filename with open("output/output.pdf","wb") as f: f.write(img2pdf.convert(image.tobytes())) On the last line, I am getting the error: ImageOpenError: cannot read input image (not jpeg2000). PIL: error reading image: cannot identify image file &lt;_io.BytesIO object at 0x1040cc8f0&gt; I'm not sure how to be converting this image to the string that img2pdf is looking for.
has answer: http://stackoverflow.com/a/56432958
type: Question
score: 2
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/a/50814528
type: Answer
has body: You have to split this two parts First part will take the value from key tokencustomset as x = dict["tokencustomset"] It will return output as 'ident= value=1340' Next part is to get the value part There are number of techniques you can use. Either you can split by = and take the last index as mentioned in other answers or use regex as value=(\d+) which will give 1340
answers question: http://stackoverflow.com/q/50814419
score: 0

http://stackoverflow.com/comment/98428422
comment on: http://stackoverflow.com/a/55885175
type: AnswerComment
has text: According to Docker tutorials, installing git in containers is generally frowned upon (downloading the master branch just using wget would be better)
score: 0
type: Comment

http://stackoverflow.com/comment/88436697
comment on: http://stackoverflow.com/q/50713808
has text: I wrote this: [\W+\w] @Cid
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50750079
has body: import pandas as pd df = pd.read_csv('location/filename.csv') df['Name'] = df['Name'].apply(lambda x: x.capitalize()) print(df['Name'].unique()) #Now you will get all the unique names. Write these names to your required csv file
type: Answer
answers question: http://stackoverflow.com/q/50749955
score: 0
has comment: http://stackoverflow.com/comment/89637585

http://stackoverflow.com/q/50782554
has body: I am trying to extract URLs from a .txt file using regex (all the URLs end with .jpeg). This is my regex: import re output = re.findall('(http)(.*?)(jpeg)', text) but my output looks like this: ('http', ://d1spq65clhrg1f.cloudfront.net/uploads/image_request/image/182/182382/182382534/cloudsight.', 'jpeg') How can I avoid having the commas dividing the matches?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50782667
has answer: http://stackoverflow.com/a/50782667
type: Question
has answer: http://stackoverflow.com/a/50782724
has answer: http://stackoverflow.com/a/50782688
has answer: http://stackoverflow.com/a/50782730
score: 0
has comment: http://stackoverflow.com/comment/88571678
tagged with: url
tagged with: pattern-matching
has title: Read URLs from .txt file Python
accepted answer: http://stackoverflow.com/a/50782730
tagged with: python
has comment: http://stackoverflow.com/comment/88571686
tagged with: regex
answer count: 4

http://stackoverflow.com/a/50703677
downvote count: 0
has body: The property children is an generator. As the error says, it is not subscriptable. To get a list, use contents instead: div.contents[1].contents[0].contents[0] See documentation.
type: Answer
answers question: http://stackoverflow.com/q/50703496
score: 1
upvote count: 1

http://stackoverflow.com/comment/88456531
has text: this should be faster than subtracting and then pick things equal to 255 and making them 0, shouldn't it?
type: AnswerComment
comment on: http://stackoverflow.com/a/50723546
score: 0
type: Comment

http://stackoverflow.com/a/50846739
downvote count: 0
has body: You are subscribing on None before that test: price = cursor.execute(sql).fetchone()[0] .fetchone() returned None, and it is None[0] that triggers the exception: &gt;&gt;&gt; None[0] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'NoneType' object is not subscriptable The error message tells you that the type of None, which is NoneType, doesn't implement subscription support. If you look closely at the traceback Python prints out, you'll see it's the price = cursor.execute(sql).fetchone()[0] line where the exception is thrown and the code will never get to the if price is ... line that follows. Call .fetchone() without subscribing, then test for None: with self.job.rap.connect() as conn: with conn.cursor() as cursor: cursor.execute(sql) price_row = cursor.fetchone() if price_row is None: return 100 else: return price_row[0] Alternatively, you could use a tuple assignment and use exception handling to return a default instead: with self.job.rap.connect() as conn: with conn.cursor() as cursor: cursor.execute(sql) try: price, = cursor.fetchone() return price except TypeError: return 100 You should also not use string formatting to combine data with a query. Use SQL parameters: sql = """ SELECT TimeSeriesValue FROM dbo.TimeSeriesPosition WHERE TimeSeriesTypeID = %s AND FundID = %s AND SecurityMasterID = %s AND EffectiveDate = %s""" with self.job.rap.connect() as conn: with conn.cursor() as cursor: cursor.execute(sql, (self.LAST_PRICE_ID, self.FUND_ID, date)) try: price, = cursor.fetchone() return price except TypeError: return 100 Each %s in the query is a placeholder, and the values for those placeholders are passed into the cursor.execute() call as the second parameter. The database driver then takes responsibility for properly quoting the values for each column, ensure that there the data can't be executed as a SQL command instead; note that there are no quotes around the %s placeholder for the EffectiveDate column. This…
has comment: http://stackoverflow.com/comment/88697201
has comment: http://stackoverflow.com/comment/88697207
accepted answer of: http://stackoverflow.com/q/50846673
type: Answer
answers question: http://stackoverflow.com/q/50846673
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/88697035
has comment: http://stackoverflow.com/comment/88697192
type: AcceptedAnswer

http://stackoverflow.com/q/50837752
has answer: http://stackoverflow.com/a/50838725
score: -1
has comment: http://stackoverflow.com/comment/88680062
has comment: http://stackoverflow.com/comment/88680276
has comment: http://stackoverflow.com/comment/88679231
has title: How to extract String from a Unicoded JSONObject in Python?
has comment: http://stackoverflow.com/comment/88679841
upvote count: 0
has comment: http://stackoverflow.com/comment/88679516
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88679897
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88679496
tagged with: python
has comment: http://stackoverflow.com/comment/88679385
has comment: http://stackoverflow.com/comment/88679963
has body: I'm getting the below error when I try to parse a String with Unicodes like ' symbol and Emojis, etc : UnicodeEncodeError: 'ascii' codec can't encode character '🌻' in position 19: ordinal not in range(128) Sample Object: {"user":{"name":"สั่งด่วน หมดไว เดรสแฟชั่นมาใหม่ ราคาเบาๆ ส่งทั่วไทย ได้ของชัวร์จ้า สนใจติดต่อสอบถาม Is it","tag":"XYZ"}} I'm able to extract tag value, but I'm unable to extract name value. Here is my code: dict = json.loads(json_data) print('Tag - 'dict['user']['tag']) print('Name - 'dict['user']['name'])
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88679562
has comment: http://stackoverflow.com/comment/88679549
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88680063

http://stackoverflow.com/comment/88699427
has text: @rayryeng Please let me know if you still think that `contour_array_list` is constructed improperly. It should be correct as I designed it as you recommended in the other question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50847827

http://stackoverflow.com/comment/88462636
comment on: http://stackoverflow.com/a/50727208
type: AnswerComment
type: Comment
has text: I don't think it's a good idea to rely on the keys being all-uppercase and everything else being all-lowercase...
score: 1

http://stackoverflow.com/a/50750400
has body: If you're using Python 3.6, f-strings are a f-un solution. Ultimately, you need to use double quotes to enclose the single quotes. table = f'{cfg_pre}_{cfg_tbl}' check_data = f"SELECT COUNT(*) FROM X WHERE TABLE_NM = '{table}'"
score: 1
has comment: http://stackoverflow.com/comment/88508654
has comment: http://stackoverflow.com/comment/88508577
has comment: http://stackoverflow.com/comment/88508656
downvote count: 0
has comment: http://stackoverflow.com/comment/88508597
answers question: http://stackoverflow.com/q/50750368
has comment: http://stackoverflow.com/comment/88508591
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88557330
has text: I think yes, give me some time.
type: AnswerComment
comment on: http://stackoverflow.com/a/50774626
score: 0
type: Comment

http://stackoverflow.com/a/50808692
has comment: http://stackoverflow.com/comment/88623603
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50807076
has comment: http://stackoverflow.com/comment/88632326
has body: DISCLAIMER: Since you said you're not a developer, I will present a pretty simple, and easy to comprehend way to find your solution. It may not be the most efficient way to do that. THIS IS NOT THE SOLUTION. But a guide to help find solution. This is a classical problem of iterate through nested lists. There is a lot of information missing, that may invalidate this solution, but it's is just a guidance. For each item in old_file list, you need to check if this item is exactly like in new_file list, and print unchanged items. for item in old_file_list: if item in new_file_list: print 'Item %r unchanged' % item Next step is check subitems of old_file list is in any sub list of new_list. I will assume that the sublists has only 2 items. else: for new_item in new_file_list: if item[1] in new_item: print("Item %r changed" % item[1]) If old_lis sub item isn't in no one new_list sub item, we may assume that it's deleted. else: print("Item %r deleted" % item[1]) Nevertheless the item may be in different order, but I will not handle this condition. An example of this code, with your data is &gt;&gt;&gt; old_file_list = [ ['1','apple,banana'], ['2','grape'], ['3','orange'] ] &gt;&gt;&gt; new_file_list = [ ['1','banana,grape'], ['2','apple'] ] &gt;&gt;&gt; &gt;&gt;&gt; for item in old_file_list: ... if item in new_file_list: ... print('Item %r unchanged' % item) ... else: ... for new_item in new_file_list: ... if item[1] in new_item: ... print("Item %r changed" % item[1]) ... else: ... print("Item %r deleted" % item[1]) ... Item 'apple,banana' deleted Item 'apple,banana' deleted Item 'grape' deleted Item 'grape' deleted Item 'orange' deleted Item 'orange' deleted It isn't the result you expect, but from here I hope that you can find your solution.
has comment: http://stackoverflow.com/comment/88659463
has comment: http://stackoverflow.com/comment/88658485
has comment: http://stackoverflow.com/comment/88660352

http://stackoverflow.com/comment/88457138
type: Comment
comment on: http://stackoverflow.com/a/50721507
has text: Good to hear. If you find this solution to be satisfactory, then please feel free to mark it as the accepted solution (shameless self promotion ;)).
type: AnswerComment
score: 0

http://stackoverflow.com/a/63865082
answers question: http://stackoverflow.com/q/50747484
score: 1
has body: If you want to remove, let's say, the artwork, you can set the specific tag to an empty list: from mutagen.id3 import ID3 file = ID3(filepath) file.setall('APIC', []) file.save() That completely removes the tag and the associated artwork. If you don't know the specific names of the tags you're interested in, you can do: print(file.pprint()) For reference: https://mutagen.readthedocs.io/en/latest/api/id3.html
downvote count: 1
upvote count: 2
type: Answer

http://stackoverflow.com/q/50707253
has title: Classify scraped results side by side into a row
possible better answer: http://stackoverflow.com/a/50711986
type: AnsweredQuestion
score: 1
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/88423855
answer count: 2
tagged with: for-loop
upvote count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50711986
has comment: http://stackoverflow.com/comment/88424130
has answer: http://stackoverflow.com/a/50719357
has body: So I'm using python/scrapy to scrape data from a webpage. Basically the webpage is made of 15 blocks that contain various sort of information. My spider reiterates through every block to scrape some specific content. I'm happy with the content of the results, but not with how the data is presented. I want all the scraped information belonging in one block to be presented in a single row. You will see from the screenshot below that the results of the same block are not presented side by side, which is what I want. def parse(self, response): for i in response.css('span.dir'): yield {'address': i.css('b::text').extract()} for l in response.css('div.datos'): yield {'area': l.css('i::text').extract()} for x in response.css('div.opciones'): yield {'price stable': x.css('span.eur::text').extract()} for o in response.css('div.opciones'): yield {'price drop': o.css('div.mp_pvpant.baja::text').extract()} for y in response.css('div.opciones'): yield {'price decreased': y.css('span.eur_m::text').extract()} for u in response.css('div.datos'): yield {'link': u.css('a::attr(href)').extract_first()}
accepted answer: http://stackoverflow.com/a/50719357
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/50722612
upvote count: 13
has title: shade region of interest in matplotlib chart
linked to: http://stackoverflow.com/q/23248435
has comment: http://stackoverflow.com/comment/88454209
downvote count: 1
type: AnsweredQuestion
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/50722667
score: 12
type: Question
tagged with: numpy
answer count: 2
has body: Given a plot like import matplotlib import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine') ax.grid() plt.show() How can I shade the vertical slices (from bottom to top) of the chart where the y-value of the plot is between (e.g.) 1.25 and 0.75 automatically? the sine is just a sample here, the actual values of the plot are less regular. I have seen FIll between two vertical lines in matplotlib, which looks similar to this question, but the answer there shades a region between fixed x values. I want the shaded region to be determined by the y values.
has answer: http://stackoverflow.com/a/50722667
favorite count: 0
has answer: http://stackoverflow.com/a/50722829
accepted answer: http://stackoverflow.com/a/50722829
duplicate of: http://stackoverflow.com/q/8270981
tagged with: python

subprocess
tag name: subprocess
tags question: http://stackoverflow.com/q/50790774
tags question: http://stackoverflow.com/q/50750716
tags question: http://stackoverflow.com/q/50788462
tags question: http://stackoverflow.com/q/50782383
tags question: http://stackoverflow.com/q/50705914
tags question: http://stackoverflow.com/q/50775969
tags question: http://stackoverflow.com/q/50716794
tags question: http://stackoverflow.com/q/50769466
tags question: http://stackoverflow.com/q/50844354
tags question: http://stackoverflow.com/q/50759877
tags question: http://stackoverflow.com/q/50816851
tags question: http://stackoverflow.com/q/50844210
tags question: http://stackoverflow.com/q/50745369
tags question: http://stackoverflow.com/q/50821642
tags question: http://stackoverflow.com/q/50754836
type: Tag
tags question: http://stackoverflow.com/q/50704017
tags question: http://stackoverflow.com/q/50699802
tags question: http://stackoverflow.com/q/50816560
tags question: http://stackoverflow.com/q/50801979
tags question: http://stackoverflow.com/q/50854519
tags question: http://stackoverflow.com/q/50812860
tags question: http://stackoverflow.com/q/50710773
tags question: http://stackoverflow.com/q/50837766
tags question: http://stackoverflow.com/q/50850694

http://stackoverflow.com/comment/88612186
comment on: http://stackoverflow.com/a/50803074
type: AnswerComment
type: Comment
has text: It is generally frowned upon to use a list comprehension for side effects, e.g. `print`
score: 2

http://stackoverflow.com/a/50822032
answers question: http://stackoverflow.com/q/50813647
score: 0
type: Answer
has body: You should be able to add this to your class: class Ui_MainWindow(object): def __init__(self): self.setupUi() self.show() This will get called when the class is initialized in the statement below. This code should go below all of your code. if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = Ui_MainWindow() sys.exit(app.exec_()) This will get called automatically when you execute your script.
accepted answer of: http://stackoverflow.com/q/50813647
type: AcceptedAnswer

http://stackoverflow.com/comment/88555967
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50774378
has text: I cannot tell you either way if it can or cannot be achieved, but I was curious about why it was a requirement. Fair enough if it's for learning purposes.

http://stackoverflow.com/comment/88642801
has text: is the ip address correct?
score: 0
comment on: http://stackoverflow.com/q/50818491
type: Comment
type: QuestionComment

kivy
tags question: http://stackoverflow.com/q/50705718
tags question: http://stackoverflow.com/q/50766100
type: Tag
tags question: http://stackoverflow.com/q/50824029
tags question: http://stackoverflow.com/q/50793090
tags question: http://stackoverflow.com/q/50750779
tags question: http://stackoverflow.com/q/50814579
tags question: http://stackoverflow.com/q/50791657
tags question: http://stackoverflow.com/q/50745840
tags question: http://stackoverflow.com/q/50785221
tags question: http://stackoverflow.com/q/50795266
tag name: kivy
tags question: http://stackoverflow.com/q/50815597
tags question: http://stackoverflow.com/q/50706444
tags question: http://stackoverflow.com/q/50720740

http://stackoverflow.com/q/50794514
answer count: 1
has answer: http://stackoverflow.com/a/50795715
favorite count: 0
accepted answer: http://stackoverflow.com/a/50795715
tagged with: selenium
upvote count: 1
tagged with: python
downvote count: 1
tagged with: excel
has body: how to import data from excel using selenium webdriver in python. The requrement is that i have pass the fetch the dats from excel and sent to the fileds in the webpage using selenium webdrive in python
type: AnsweredQuestion
type: Question
has title: how to import data from excel using selenium webdriver in python
score: 0

http://stackoverflow.com/comment/117195570
comment on: http://stackoverflow.com/a/50721405
type: Comment
score: 1
has text: Glad I found this, this is really un-intuitive - especially if you've just applied `literal_eval` to the lists in your series stored in a file to import to the dataframe. the last place you'd look for list methods is in `str` methods
type: AnswerComment

http://stackoverflow.com/comment/88712260
comment on: http://stackoverflow.com/a/50854362
type: Comment
has text: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88691107
score: 0
comment on: http://stackoverflow.com/q/50843483
type: Comment
type: QuestionComment
has text: @Prany prior to last. But try it on the last too

http://stackoverflow.com/q/50797043
downvote count: 0
score: 22
has comment: http://stackoverflow.com/comment/88600301
has answer: http://stackoverflow.com/a/50797992
answer count: 1
favorite count: 0
has title: string argument expected, got 'bytes' in buffer.write
has body: I have this: from io import StringIO buffer = StringIO() latest_file = 'C:\\Users\\miguel.santos\\Desktop\\meo_snapshots\\Snapshot_14.jpg' buffer.write(open(latest_file,'rb').read()) TypeError: string argument expected, got 'bytes' Any ideas on how to solve?
tagged with: python
has comment: http://stackoverflow.com/comment/88600153
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50797992
tagged with: file
type: Question
upvote count: 22

http://stackoverflow.com/comment/88659739
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50827574
has text: Thank you, but I need to first get the counts to compute the zscores on.
score: 0

http://stackoverflow.com/q/50754474
has body: DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None) Can anyone explain the significance of regex and inplace in the above line?
has comment: http://stackoverflow.com/comment/88517218
type: Question
tagged with: pandas
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/50754826
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88517224
has title: Unable to understand the significance of regex and inplace in pd.replace ( regex = False , inplace=False)
has comment: http://stackoverflow.com/comment/88517386
has answer: http://stackoverflow.com/a/50754826
type: AnsweredQuestion

http://stackoverflow.com/comment/88560459
score: 0
type: Comment
has text: How would you access the data?
type: AnswerComment
comment on: http://stackoverflow.com/a/50776533

http://stackoverflow.com/q/50756639
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50756720
has comment: http://stackoverflow.com/comment/88521026
has title: Remove duplicate tuples in numpy array (ones directly next to each other)
score: 1
has comment: http://stackoverflow.com/comment/88521006
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/88521024
tagged with: arrays
has comment: http://stackoverflow.com/comment/88521234
has comment: http://stackoverflow.com/comment/88521413
tagged with: tuples
has body: I am more or less new to python/numpy and I have this problem: I have numpy arrays in which the first and last tuples are always the same. In between, there are sometimes duplicate tuples (only the ones directly next to each other) that I want to get rid of. The used parenthesis structure should be maintained. I tried np.unique already (e.g. 1, 2), but it changes my original order (which has to be maintained). My sample array looks like this: myarray = np.array([[[1,1],[1,1],[4,4],[4,4],[2,2],[3,3],[1,1]]]) I need a result that looks like this: myarray = np.array([[[1,1],[4,4],[2,2],[3,3],[1,1]]]) Thank you in advance for your support!
linked to: http://stackoverflow.com/q/31097247
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88521066
linked to: http://stackoverflow.com/q/15637336
favorite count: 0
accepted answer: http://stackoverflow.com/a/50756720

http://stackoverflow.com/q/50739690
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50822143
score: 0
has body: I am trying to read csv file from FTP Folder ftp = FTP('adr') ftp.login(user='xxxx', passwd = 'xxxxx') r = StringIO() ftp.retrbinary('RETR /DataLoadFolder/xxx/xxx/xxx/'+str(file_name),r.write) r.seek(0) csvfile1 = csv.reader(r,delimiter=';') input_file = [list(line) for line in csv.reader(r)] ----- Error getting an error at last line as new-line character seen in unquoted field - do you need to open the file in universal-newline mode? My csv file Text Version There are whites spaces at the end of each row (after 17.00) Data starts from second row what does the error mean? Any help would be much appreciated.
tagged with: python
has comment: http://stackoverflow.com/comment/88648058
has comment: http://stackoverflow.com/comment/88487738
tagged with: ftp
has title: Reading csv from FTP folder
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50740686
linked to: http://stackoverflow.com/q/419291
linked to: http://stackoverflow.com/q/18772703
has comment: http://stackoverflow.com/comment/88643511

http://stackoverflow.com/q/50781478
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: python-requests
has title: Specify device width for session requests
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50781501
accepted answer: http://stackoverflow.com/a/50781501
score: 1
tagged with: post
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has body: How to specify the device width while I do a session.post ? Example of code : import requests global session session = requests.Session() payload = { "login_email" : "helloyes", } url = "https://www.twitter.com/" result = session.post(url, data=payload, headers=dict(Referer=url)) plain_text = result.content content = plain_text.decode() This code renders a mobile device view of the website. I need the desktop view, how to do please ?

http://stackoverflow.com/a/50844885
type: Answer
has body: This works for me, after aggregating df2 in unique store values ony: df1['value'] = [int(df2[df2.store==s].value) for s in df1.store]
answers question: http://stackoverflow.com/q/50844535
score: 0

http://stackoverflow.com/a/50819752
answers question: http://stackoverflow.com/q/50814594
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88646850
upvote count: 1
has body: Because there is no way to return anything from Button commands in tkinter, the easiest way to deal with things like this is to wrap it in a class and use class variables to store your generated data. I added the wait_window and grab_set commands to make the root window wait an be unclickable until the calendar chooser window is closed. import tkinter as tk from tkinter import ttk from tkcalendar import Calendar class Example1(): def __init__(self, root): self.top = tk.Toplevel(root) self.cal = Calendar(self.top, font="Arial 14", selectmode='day', cursor="hand1", year=2018, month=2, day=5) self.cal.pack(fill="both", expand=True) ttk.Button(self.top, text="ok", command=self.print_sel).pack() ttk.Button(self.top, text="exit", command=self.quit1).pack() self.date = '' self.top.grab_set() def print_sel(self): self.date = self.cal.selection_get() def quit1(self): self.top.destroy() class App(): def __init__(self): self.root = tk.Tk() s = ttk.Style(self.root) s.theme_use('clam') ttk.Button(self.root, text='Last Date', command=self.last).pack(padx=10, pady=10) ttk.Button(self.root, text='Next Date', command=self.next).pack(padx=10, pady=10) self.last_date = '' self.next_date = '' self.root.mainloop() def last(self): cal = Example1(self.root) self.root.wait_window(cal.top) self.last_date = cal.date def next(self): cal = Example1(self.root) self.root.wait_window(cal.top) self.next_date = cal.date app = App() print('Last date: {}'.format(app.last_date)) print('Next date: {}'.format(app.next_date)) If this code makes no sense to you, please see this post and try to read up into classes and how they work. As you can see, I didn't incorporate the inheritance to tk.Frame and tk.Toplevel in my example because I guess that would make it more complicated for you, but I really would advise to try and thoroughly understand and use the structure from this answer. It will help you in the long run.
type: Answer

http://stackoverflow.com/comment/88422405
type: QuestionComment
comment on: http://stackoverflow.com/q/50706476
has text: Please check this one : https://stackoverflow.com/questions/12684368/how-to-left-align-a-fixed-width-string
score: 0
type: Comment

http://stackoverflow.com/q/50737442
score: 0
tagged with: solr
accepted answer: http://stackoverflow.com/a/50738910
type: Question
has body: I am beginner to solr.i want to transfer the data from solr to python and i have found the pysolr library i have installed it but did'nt know how to use it. I have searched on google but did'nt find required answer I want to ask how we can load data from solr to python and perform filtering,sorting and other operations i have tried as: from pysolr import Solr conn = Solr('/localhost:8983/solr/sms_data/select?indent=on&amp;q=customer_id:73614&amp;rows=10&amp;start=0&amp;wt=json') Now how can i read the data present in conn and perform other operations.
answer count: 1
has comment: http://stackoverflow.com/comment/88484710
has title: Transfer data from solr to python
has comment: http://stackoverflow.com/comment/88485061
has answer: http://stackoverflow.com/a/50738910
tagged with: python
tagged with: pysolr
type: AnsweredQuestion

http://stackoverflow.com/q/50806601
has comment: http://stackoverflow.com/comment/88620151
has comment: http://stackoverflow.com/comment/88620767
type: UnansweredQuestion
tagged with: python
has title: Optimizing Python code iterating over millions of documents
has comment: http://stackoverflow.com/comment/88619500
tagged with: performance
answer count: 0
score: 0
type: Question
has comment: http://stackoverflow.com/comment/88620737
has comment: http://stackoverflow.com/comment/88620744
tagged with: mongodb
has comment: http://stackoverflow.com/comment/88619525
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88620721
has body: Context Hello I have a script that converts Mongo documents into JSON written to a file. To run the script on 1000 documents take approximately 45 seconds. Predicament The Mongo collection however has nearly 18 million documents so it would take approximately 200 hours to go through the whole collection. I am now looking to optimize the code to bring the time down significantly and was wondering what the options are to do so. Possible Solutions I know there are hardware options such as running on a cluster with faster hard drives, but I was also wondering any optimizations I can do with the algorithm and other areas of the code. Looking at the profiler, most of the time is spend in {method 'recv' of '_socket.socket' objects} (Not sure what this does) and encoder.py:212(iterencode) (Converting to JSON). These are built in functions, but the rest of the time consuming functions are user defined. Some possible solutions I am considering are: 1. Copying a list of strings using writeline 2. Compiling to C code using a package like Cython 3. Using faster data structures and algorithmic process. As for 3. I'm not sure how I can implement a faster algorithm as I have to go through nested layers for each document to create the entries. Specifically for each document, there are subdocuments indicated by the key 'd'. Each subdocument also has keys that being with 'AT' such as 'AT432'. I have to create an individual entry for each 'AT' so one document can result in 50 individual entries. Help Welcome! I'm open to any ideas as I would really like to reduce the time spent converting each document. Thanks for your input! File 1 from pymongo import MongoClient import cProfile import sys import time from mapping_functions import create_files from datetime import datetime from date_functions import get_array_of_dates pr = cProfile.Profile() pr.enable() start_time = time.time() # A. Connect to a collection in MongoDB client = MongoClient('mongo-host-ip', 27017) db = client.db_name col…
tagged with: performance-testing

http://stackoverflow.com/comment/88497098
has text: Any better idea? Thanks!
type: Comment
comment on: http://stackoverflow.com/a/50733869
score: 0
type: AnswerComment

http://stackoverflow.com/a/50820478
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88646494
has comment: http://stackoverflow.com/comment/88646714
has comment: http://stackoverflow.com/comment/88646587
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50820438
type: Answer
answers question: http://stackoverflow.com/q/50820438
has body: Maybe you just need to indent it properly like this: if month == time.strftime("%m") and day == time.strftime("%d"): continue elif hour == time.strftime("%H") and minute != time.strftime("%M"): channelD["just_sent"] = False with open("data.json", "w") as write_file: json.dump(data, write_file) elif hour == time.strftime("%H") and minute == time.strftime("%M"): if just_sent == channelD["just_sent"]: # notice == instead of = continue else: channel = bot.get_channel(i) await bot.send_message(channel, content=channelD["message"]) print("24h message sent!") There is no way for me to find out whether the last else: should be on the indentation level of the if above it or of the indentation level of the elif above it. That depends on the semantics of the code. You should check that. Python interprets the indentation levels to figure out where blocks start and end. In this it is unlike many other languages.
has comment: http://stackoverflow.com/comment/88646562
has comment: http://stackoverflow.com/comment/88646445

http://stackoverflow.com/q/50722690
has body: I am running a program which runs terminal codes based on the input recieved by the user on my Raspberry Pi. I want the process to run on a different terminal which is opened by my python code. For this on my Ubuntu machine I did os.system("gnome-terminal -x google-chrome") #if i wanted to open chrome But this is not an option on raspbian stretch. I want to know how I can perform similar functions on my raspberry pi I had asked a similar question here. Refer to it to get a better understanding of what I am asking I have Python 3.5.3 on the Raspberry Pi model 2 B running Raspbian Stretch
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/88493465
type: AnsweredQuestion
has title: Run os.system commands in new terminal - Python 3 on Raspberry Pi
has comment: http://stackoverflow.com/comment/88500776
linked to: http://stackoverflow.com/q/50344490
type: Question
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/50762783
accepted answer: http://stackoverflow.com/a/50762783
has comment: http://stackoverflow.com/comment/88458633
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88454233

http://stackoverflow.com/q/50785769
has answer: http://stackoverflow.com/a/50786127
tagged with: python
has title: how find the angles of a triangle with values that the user enters and how to draw it
has comment: http://stackoverflow.com/comment/88578182
has comment: http://stackoverflow.com/comment/88578318
accepted answer: http://stackoverflow.com/a/50786127
has comment: http://stackoverflow.com/comment/88578449
upvote count: 1
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88578081
type: Question
has comment: http://stackoverflow.com/comment/88578052
has body: im a beginner to python and I have to write a program that Asks the user for 3 numbers(sides of a triangle), Determines whether or not the numbers form valid sides of a triangle, If they don’t, say it doesn’t and end the program. If they do, determine the ANGLES of this triangle and Draw the triangle on the screen using turtle. I don't really know what im doing and so far I was able to get the user to enter the values and a get the program to determine if it is a triangle or not, but when I try to determine the angles, I get 2 different errors. the first one values error: math domain error and the other one is that I have to convert a string to real numbers. This is the code that I have so far: from turtle import* from math import* import math a = int(input("enter the value for a: ")) b = int(input("enter the value for b: ")) c = int(input("enter the value for c: ")) if a^2 + b^2 == c^2: print("its a triangle") else: print("its not a triangle") if (math.acos(a)): print(degrees(acos(cos(radians(a))))) elif (math.acos(b)): print(degrees(acos(cos(radians(b))))) elif(math.acos(c)): print(degrees(acos(cos(radians(c))))) a = degrees(int(acos('a^2 - b^2 - c^2 / -2(b)(c)'))) b = degrees(int(acos('b^2 - c^2 - a^2 / -2(a)(c)'))) c = degrees(int(acos('c^2 - a^2 - b^2 / -2(a)(b)')))
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88578007
has comment: http://stackoverflow.com/comment/88578240
has comment: http://stackoverflow.com/comment/88578142

http://stackoverflow.com/q/50793165
upvote count: 8
accepted answer: http://stackoverflow.com/a/50794458
score: 8
has title: Pyspark: how are dataframe describe() and summary() implemented
tagged with: python
has body: I want to know how df.describe() and df.summary() is implemented As in https://spark.apache.org/docs/latest/api/python/_modules/pyspark/sql/dataframe.html#DataFrame.summary def summary(self, *statistics): if len(statistics) == 1 and isinstance(statistics[0], list): statistics = statistics[0] jdf = self._jdf.summary(self._jseq(statistics)) return DataFrame(jdf, self.sql_ctx) I'm not very familliar with OO in python and I'm a bit confused. Where is the quantile and other statistics implemented?
type: AnsweredQuestion
tagged with: oop
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/50794458
tagged with: apache-spark-sql
tagged with: pyspark
answer count: 1
downvote count: 0
favorite count: 0

i2c
tag name: i2c
type: Tag
tags question: http://stackoverflow.com/q/50730018

http://stackoverflow.com/a/50709657
has body: After setting up your url pattern correctly, the simpler way is: {% url 'index' object.pk %} But the most effective is get_absolute_url() method in your model class: (In most cases, used because of slug in url) This tells Django how to calculate the canonical URL for an object. It returns a string that can be used to refer to the object over HTTP. I suppose that you have your urls pattern set as the following url(r'index/(?P<pk>\d+)',index,name='index') The method will be: from django.urls import reverse class ModelClass(models.Model): ''' fields ''' def get_absolute_url(self): return reverse('index', args=[str(self.pk)]) # or with kwargs={'pk':str(self.pk)} In your template, you may call it that way See me
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50709551
upvote count: 2
answers question: http://stackoverflow.com/q/50709551
type: Answer
score: 2

http://stackoverflow.com/comment/92492365
score: 0
type: Comment
has text: Oh, I thought the double `a-1` was actually your point and the problem you're trying to solve :)
comment on: http://stackoverflow.com/a/50778403
type: AnswerComment

http://stackoverflow.com/q/50836829
type: Question
has title: Django Send_Mail Authentication Failure
has comment: http://stackoverflow.com/comment/88684397
score: 0
tagged with: unix
has comment: http://stackoverflow.com/comment/88691177
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88678680
tagged with: django
tagged with: roundcube
tagged with: python
answer count: 0
has body: I am using my mail server to send mail using Django. When I try to use the send_mail function, I am met with an authentication error. I know that it is not the password, because I can use it to login to my mail account. How My Mail Server is Setup I am running Ubuntu 16.0.4 with Nginx and Gunicorn for my Django application. I have installed Roundcube, postfix and dovecot. How Do I add Users to Roundcube? For me, the only way I know how to do this is by just adding a new user from the CLI using adduser &lt;user&gt; and from there, logging into Roundcube so that my new user is added to the Roundcube database, and I have an accessible account on Roundcube. What I Suspect to be The Issue Since I am creating the users for Roundcube directly from the CLI and they are full Unix users, I can only login to Roundcube using their actual username, and not username@domain.tld. I suspect that Django is trying to authenticate with user@domain.tld rather than user and that is what is causing the issue. How Can I Fix This? I am not sure, hence why I am here. I have done my research and cannot find the proper information on making it so that I can login to Roundcube using user@domain.tld instead of just user, but I don't think this will solve my issue. I have also done research and cannot find an answer on how to create just a mail user, and not a full-blown Unix user. I was thinking this might be my best option. Although, I could be completely wrong.
tagged with: dovecot

http://stackoverflow.com/q/50781562
downvote count: 0
tagged with: dataframe
has answer: http://stackoverflow.com/a/57246229
tagged with: pandas
has answer: http://stackoverflow.com/a/50781604
has title: Stratified splitting of pandas dataframe into training, validation and test set
answer count: 4
favorite count: 0
tagged with: sampling
has body: The following extremely simplified DataFrame represents a much larger DataFrame containing medical diagnoses: medicalData = pd.DataFrame({'diagnosis':['positive','positive','negative','negative','positive','negative','negative','negative','negative','negative']}) medicalData diagnosis 0 positive 1 positive 2 negative 3 negative 4 positive 5 negative 6 negative 7 negative 8 negative 9 negative Problem: For machine learning, I need to randomly split this dataframe into three subframes in the following way: trainingDF, validationDF, testDF = SplitData(medicalData,fractions = [0.6,0.2,0.2]) ...where the split array specifies the fraction of the complete data that goes into each subframe. the data in the subframe needs to be mutually exclusive and the split array (fractions) need to sum to one. Aditionally, the fraction of positive diagnoses in each subset needs to be approximately the same. Answers to this question recommend using the pandas sample method or the train_test_split function from sklearn. But none of these solutions seem to generalize well to n splits and none provides a stratified split.
tagged with: machine-learning
tagged with: python
score: 13
possible better answer: http://stackoverflow.com/a/65571687
upvote count: 13
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88569845
has answer: http://stackoverflow.com/a/65571687
accepted answer: http://stackoverflow.com/a/50781604
has answer: http://stackoverflow.com/a/76356945
type: Question
linked to: http://stackoverflow.com/q/24147278
has comment: http://stackoverflow.com/comment/88569847
has comment: http://stackoverflow.com/comment/88569876

http://stackoverflow.com/a/50809030
downvote count: 0
has body: One other way may be using zip with np.concatenate: import numpy as np l5 = np.concatenate(list(zip(l1, l2, l3, l4))) print(l5) Result: ['a' '1' 'w' '5' 'b' '2' 'x' '6' 'c' '3' 'y' '7' 'd' '4' 'z' '8'] Note: l5 is type numpy.ndarray, you can convert it to list either with list(l5) or l5.tolist()
score: 4
type: Answer
answers question: http://stackoverflow.com/q/50808757
upvote count: 4

http://stackoverflow.com/q/50823669
accepted answer: http://stackoverflow.com/a/50823752
has title: Python Tkinter save file as CSV creating extra spaces
type: Question
has answer: http://stackoverflow.com/a/50823752
has comment: http://stackoverflow.com/comment/88652457
score: 0
answer count: 1
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: Normally when I open a CSV file in Python, I need to use: with open(filename, newline='', mode='w') as f: And if I don't have that newline='' in there, it creates an empty line between each line in my CSV. However, I am using Tkinter to save the file, so I have: new_filename = asksaveasfile(mode='w', defaultextension='.csv') Since "new_filename" is already open, I can't do the "open" command to indicate the newline='' in there. If I try opening it again, I get an error. So how do I get rid of the extra spaces in this case? Thanks for your help and patience.
linked to: http://stackoverflow.com/q/30929363
type: AnsweredQuestion
tagged with: tkinter
linked to: http://stackoverflow.com/q/3191528

http://stackoverflow.com/comment/88508851
score: 0
has text: Still don't know what's going on but it could be an issue with data types: I tried `.na.fill(f.lit(False))` and got the error `ValueError: value should be a float, int, long, string, or dict`. Oddly no difference if I cast to boolean either: `agg(F.count('*').isNotNull().cast('boolean'))`
type: AnswerComment
comment on: http://stackoverflow.com/a/50749778
type: Comment

http://stackoverflow.com/a/58400269
type: Answer
has body: If you don't anticipate to know beforehand what the sheetname is, then your code should be: sheet = wb[wb.sheetnames[0]] ...which will automatically choose the left most sheet in the workbook Furthermore, it is important to note that wb[0] produces a string object... &gt;&gt;&gt; wb.sheetnames[0] 'Sheet1' and wb[wb.sheetnames[0]] produces a 'openpyxl.worksheet.worksheet.Worksheet' object... &gt;&gt;&gt; wb[wb.sheetnames[0]] &lt;Worksheet "Sheet1"&gt; &gt;&gt;&gt; type(wb[wb.sheetnames[0]]) &lt;class 'openpyxl.worksheet.worksheet.Worksheet'&gt; This is important on how you plan to work with this object (e.g. iterating over your worksheet).
score: 0
answers question: http://stackoverflow.com/q/50807312

http://stackoverflow.com/comment/89102159
has text: Ok fixed the issue with the delegate! (i hadn't set the table, since i set a query including the table and i thought that was equivalent :/ ). Ultimately what i'm trying for is for either Ann, Tyler or Tyler, Ann to activate the same entry in the popup (which shows first, last), and not two separate entries pointing to the same underlying db entry.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50829561
type: Comment

http://stackoverflow.com/comment/88582572
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50787264
has text: This works! Thanks so much for your simple and effective approach!
score: 0

http://stackoverflow.com/comment/91164077
type: AnswerComment
type: Comment
score: 3
has text: In order to build a smoothing model statsmodels needs to know the frequency of your data (whether it is daily, monthly or so on). MS means start of the month so we are saying that it is monthly data that we observe at the start of each month.
comment on: http://stackoverflow.com/a/50786171

http://stackoverflow.com/a/50707825
has body: for item in dic: print(item) # key print(dic[item]) # value Dictionaries are basically containers containing some items (keys) which are stored by hashing method. These keys just map to the values (dic[key]). Like in set, if you traverse using for loop, you get the keys from it (in random order since they are hashed). Similarly, dictionaries are just sets with a value associated with it. it makes more sense to iterate the keys as in sets (too in random order).
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50706564
upvote count: 1

http://stackoverflow.com/comment/88526982
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50701736
type: Comment
has text: Taking a closer look at what you are trying to achieve here I released that it's not possible at the time because Apache beam [does not offer a connector](https://beam.apache.org/documentation/io/built-in/ ) for python. For a workaround you can take a look at [this](https://stackoverflow.com/questions/46528343/how-to-use-gcp-cloud-sql-as-dataflow-source-and-or-sink-with-python ) SO case. However my suggestion is to address this issue [here](https://github.com/GoogleCloudPlatform/DataflowPythonSDK/issues/9)

http://stackoverflow.com/comment/88616540
score: 0
has text: @eyllanesc I understand, are there any libraries, or ways that I can receive post request in python?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50805099

http://stackoverflow.com/q/50805242
type: Question
upvote count: 2
answer count: 2
has body: Can anyone help me figure out this error? This is code for an encryption/decryption game. import random import itertools """Defines the alphabet list and number list used to make the dictionaries for encoding/decoding.""" alph = ['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'] num = range(0, 26) """Creates the dictionaries used to encode/decode""" alph_to_num = dict(zip(alph, num)) num_to_alph = dict(zip(num, alph)) def vigenere_encode(text): key = 'lemon' text = text.lower() k = itertools.cycle(key) key_list = [] encoded_list = [] i = 1 while i &lt;= len(text): key_list.append(next(k)) i += 1 num_list = [alph_to_num[s] if s in alph else s for s in text] num_key_list = [alph_to_num[s] for s in key_list] for num1, num2 in zip(num_list, num_key_list): if num1 in num: encoded_list.append(sum(num1, num2)) else: encoded_list.append(num1) encoded_list = [num_to_alph[n % 26 + 1] if n in num else n for n in encoded_list] encoded_str = "" for i in encoded_list: encoded_str += i print('Your key is: ' + key) print('The encoded string is: ' + encoded_str) Here is the error: line 28, in vigenere_encode encoded_list.append(sum(num1, num2)) TypeError: 'int' object is not iterable I had found a more optimal way of writing that section of code, namely: encoded_list = list(map(sum, zip(num_list, num_key_list))) but with that way of writing the code I wasn't sure how to allow for non-alphabet characters in the text to be encoded, and I would like a code format that allows me to write the decode() function without having to change a lot. I am a relative beginner. Any help is appreciated.
tagged with: int
possible better answer: http://stackoverflow.com/a/50805397
score: 0
tagged with: typeerror
has answer: http://stackoverflow.com/a/50805352
accepted answer: http://stackoverflow.com/a/50805352
favorite count: 0
has title: Python TypeError: 'int' object is not iterable, trying to append integers to list
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50805397
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88617673
linked to: http://stackoverflow.com/q/1938227

http://stackoverflow.com/comment/88542913
type: Comment
score: 0
has text: When you say accidentally, does that mean because of something in pandas? Because I don't see how it could be anything in my code.
type: AnswerComment
comment on: http://stackoverflow.com/a/50767707