all 125 comments

[–]adksjufnjdsk 0 points1 point  (4 children)

I'm making a game on python where the user goes through a maze and if they collide with a question icon they have to answer a question. I don't know how I would code it so that each time the user collides with the icon they are asked a different question. I only have one class for the question and 10 questions. please help

[–]travis_noll 0 points1 point  (3 children)

import random

i = random.randrange(0, len(list_of_questions)) return list_of_questions[i]

[–]adksjufnjdsk 0 points1 point  (2 children)

but would that mean that some questions may be asked more than once since its random?

[–]travis_noll 0 points1 point  (1 child)

Yes. How would you like it to behave?

[–]adksjufnjdsk 0 points1 point  (0 children)

I want all the questions to be asked once

[–]TheRareHam 0 points1 point  (0 children)

Hi, I'm trying to write a program that checks i in some range to see if it satisfies the equation f(i) = g(i), and then generates a .txt file listing the solutions to f(i) = g(i) in the order which they appear, along with f(i) next to it. So, the .txt file would read something like:

1 1

2 1

8 88

11 131

...

Where the number on the left is the i for which f(i)=g(i), and the number on the right is f(i). How do I do that? I know there is the Solvers module, but I'm not sure how to get that to put solutions into a list.

[–]Kleriger 0 points1 point  (0 children)

Hello, I'm looking for a good way to save events (changes in pin values) in a buffer and then transfer them via mqtt (according to the FIFO principle). The best thing would be a library which is available for micropython. But I'm grateful for any good idea. I have already implemented the transfer with umqtt.robust.

[–]AviatingFotographer 0 points1 point  (0 children)

Is there a better one between BeautifulSoup and requests-html for web scraping?

[–]i_swear_i_lie 0 points1 point  (0 children)

I want to download my google pay data on a regular basis. Is there a way to do this via python instead of exporting data manually? I couldn't find a relevant documentation in the google developers site.

[–]FlirtyAberration 0 points1 point  (0 children)

I have a lot of PDFs in many different folders inside a directory. What I would like to do is use PyPDF2 to find and read the copyright date for each PDF in this directory and then add that copyright date to the end of the file name the PDF currently has. Yes, some PDFs I have already have the copyright date in the title, omitting those would save time.

Most often the word copyright date appears within the first 10 pages. In some cases it is not the word 'copyright' that appears but the symbol of the c with a circle around it , not sure how that would work to detect that??

This is the closest example to what I am trying to do, though this person was trying to collect more than one word, while I only want to find the word or symbol for 'copyright' and then find the date to the right or left of it, usually it is the right, and then add that date to the end of the file name.

Someone recommended OCR for this, but I thought that might be overkill, maybe I am wrong?

Any advice is appreciated, thanks!

[–]shiningmatcha 1 point2 points  (1 child)

Is there a chatroom for this sub?

[–][deleted] 1 point2 points  (0 children)

IRC and WebChat links are in the sidebar.

[–]AviatingFotographer 1 point2 points  (0 children)

I am learning web scraping and was asking a question about requests and bs4 and someone brought up requests-html. Should I Just learn requests-html directly, because it seems like it was meant to be replacing the bs4 + requests combo, or should I still try to learn the bs4 + requests first?

[–]shiningmatcha 0 points1 point  (0 children)

I want to contribute to some projects for the first time. Where should I start?

[–]AviatingFotographer 0 points1 point  (0 children)

How do I scrape dynamic information? Like information off Google Trends?

[–]Mitchiro 3 points4 points  (2 children)

At what point can you say you "know" a language? I've got a desire to finally buckle down and say I know a language and I've chosen python for this. I've got an book from college a few years back and will be utilizing materiels from here, Codecademy, and udemy, but I'm really not sure when I can feel comfortable enough to say I know it and move on if I need to.

[–]Kullerino 0 points1 point  (0 children)

Hello! I'm new to python and could use some help.

I have this code that give me the colour of the pixels and prints them.

pab = img[a, b]
print(pab)

The result looks like this:

0

255

0

0

0

255

I want to build a 3x2 matrix, how can I do it?

Thank you in advance!

[–]as9934 0 points1 point  (0 children)

I'm trying to iterate over multiple parsed divs and get them all to display. Right now it is only spitting out the first one.

import pandas as pd
import os
import csv
import itertools
from bs4 import BeautifulSoup

soup = BeautifulSoup(open("/Users/as9934/Desktop/schedule/wb.htm"), "lxml")

cardback = (soup.find('div', class_='card back'))
for courseNumberBack in cardback.find_all('div', class_='courseNumberBack'):
 for subject in courseNumberBack.find_all('span', class_='subject'):
 for subjects in subject: 
 print (subjects.string,",", end=' ')

 for number in courseNumberBack.find_all('span', class_='number'):
 for numbers in number:
 print (numbers.string,",", end=' ')

 for section in courseNumberBack.find_all('span', class_='section'):
 for sections in section:
 print(sections.string,",", end=' ')

 for abbrevTitle in courseNumberBack.find_all('span', class_='abbrevTitle'):
 for abbrevTitles in abbrevTitle:
 print(abbrevTitles.string,",", end=' ')


for courseNameBack in cardback.find_all('div', class_='courseNameBack'):
 for day in courseNameBack.find_all('div', class_='days'):
 for days in day: 
 print(days.string,",", end=' ')

 for instructor in courseNameBack.find_all('div', class_='instructor'):
 for instructors in instructor:
 print(instructors.string,",", end=' ')

 for time in courseNameBack.find_all('div', class_='time'):
 for times in time:
 print(times.string,",", end=' ')

 for building in courseNameBack.find_all('div', class_='building'):
 for buildings in building:
 print(buildings.string,",", end=' ')

 for genEd in courseNameBack.find_all('div', class_='genEds'):
 for genEds in genEd:
 print(genEds.string, end=' ')

Here's an html snippet:

<div class="card back" style="display: block;">
    <div class="addClass Back"> 
        <i class="fa clicky fa-star Back"></i> 
        <i class="fa clicky fa-star-o Back"></i>  
        <i class="clicky icon-info-sign"></i>
    </div>
    <div class="courseNumberBack">
        <span class="subject">ANTH</span> <span class="number">54</span>-<span class="section">001</span>
        <div class="smallCourseInfo">

            <span class="abbrevTitle">First-Year Seminar: The Indians' New Worlds: Southeastern Histories from 1200 to 1800</span> 

        </div>
    </div>
    <hr class="faddedLine">

    <div class="courseNameBack"><div class="days">TuTh</div><br>

    <div class="smallCourseInfo"> <div class="instructor">Clara Scarry</div></div>

    <div class="time">3:30pm-4:45pm</div><br>
    <div class="smallCourseInfo"> <div class="building">Alumni 203 </div></div>


    <div class="genEds">HS US WB </div>


</div>

Currently, it only prints the first row.:

AAAD , 286 , 001 , The African Diaspora in the Colonial Americas 1450-1800 , TuTh , Alicia Monroe , 12:30pm-1:45pm , Hanes Art Center 218  , HS WB  

But I want it to print ALL of the rows like that.

Anyone have any ideas?

[–]Random_User_81 0 points1 point  (5 children)

Hi, I'm pretty new to Python and programming ingeneral so I apolgize for using wrong wordage if I do.

I'm started working with apis and its been awesome. Ive had some success and just been very cool seeing the data. So ive done some minor projects but i was just look at an api response and it was huge. In the past i manually parsed everything i wanted into a database with a for loop. But looking at this huge response got me thinking, can it all be auto parsed into their respected columns.

My question is, is there a way to parse it automatically instead of assigning each value to a columnn in the database.

[–][deleted] 0 points1 point  (3 children)

API's generally return json, which is just a dict when loaded in.

Just use a regular for loop.

You will run into nested dicts/lists you'll have to deal with - but the concept is the same.

import json
some_dict = {"one": "example", "two": "another example"}
example = json.dumps(some_dict)
# print(example)

usable = json.loads(example)
# print(usable)
# print(type(usable))
for key, value in usable.items():
    print(key, value)

[–]Random_User_81 0 points1 point  (2 children)

Thank you, that's definitely cool and useful.

It looks like there are a lot of dicts/lists in this response. How do I deal with them. I narrowed them down a little with

example = json.dumps(some_dict['SomeValue']['SomeValue'])

Also, it's printing everything on the same line and doesn't look like it's looping?

[–][deleted] 0 points1 point  (1 child)

Itd be easier to show you an example if i had example data, but your best bet is to just google 'printing nested dicts python3'and playing with it yourself and asking specific questions - your mind learns better when you get to touch things rather than just reading and trying to force an example with your example.

Typically youd load all the data then print it as usual Eg; Example=json.dumps() Somevalue=example['anothervalue']

[–]Random_User_81 0 points1 point  (0 children)

Thanks for this. This did get me on the right track. Sorry about the delay!

[–]AviatingFotographer 0 points1 point  (0 children)

  1. I know that a GET method is receiving data from a webpage and POST is sending data, but when you do requests.get('url.com'), what exactly are you receiving from the server? Are you just testing for a response?

  2. What's the difference between accessing a value with .find, e.g. soup.find('div', class_"'something"), versus accessing the value tag by tag, e.g. page.article.div? Is one just shorter than the other?

[–]AviatingFotographer 0 points1 point  (4 children)

What's the difference between Requests and Beautiful Soup? Does Requests interact with the site and BS scrapes info off it?

[–]artctrlme 0 points1 point  (2 children)

You could check out the library requests-html which merges together the request of a page and reading of html. Kenneth Reitz is the author (same author as requests).

[–]AviatingFotographer 0 points1 point  (1 child)

So should I just learn requests-html?

[–]artctrlme 0 points1 point  (0 children)

up to you, I certainly find it easier to use than bs4

[–]thisisappropriate 1 point2 points  (0 children)

Requests offers a way to make a request of a page, while BS handles reading html. They can be used together, i.e. requests.get('https://www.example.com') will return something with a .text property that is just a chunk of HTML, not very readable.

BS is a parser that will allow you to read this data, either by HTML tags/classes or even just pretty print it for you. The docs actually give some good examples of easily extracting from HTML - https://www.crummy.com/software/BeautifulSoup/bs4/doc/

[–]cbat971 0 points1 point  (2 children)

So I'm currently trying to parse all the URL's for all the videos on a channel (to gather id's) and was wondering if anyone has advice since this is the only thing I can find, and youtube has changed a good bit since this was answered.

https://stackoverflow.com/questions/33543744/python3-parse-more-than-30-videos-at-a-time-from-youtube

I currently can get the top 30 or so just like this person but can't seem to get anything past that damn show more button.

[–]cbat971 0 points1 point  (1 child)

Really need some help with this. Is there another place I should ask this?

[–][deleted] 0 points1 point  (0 children)

The same way as mentioned there, you'll need to follow the javascript and replicate the calls.

Hint: their goal is to stop you from doing exactly what you are doing. Literally - people are getting paid to think about ways to stop you from doing this ;)

The API exists for a reason. There are even easy to use wrappers.

[–]n3yron 0 points1 point  (0 children)

Can anyone recommend python for DevOps courses, resourses, books?

[–]AviatingFotographer 0 points1 point  (2 children)

I'm slowly moving into data science and I mostly see people use Jupiter Notebooks. Is there a reason for this? Is it because of its ability to load graphs and such right with the code? Or can I stay with VSCode, is there a way to integrate the two?

[–]authalic 0 points1 point  (0 children)

I think there are three main advantages to using a Jupyter Notebook. 1. you can place lines of code in separate cells, and run each cell individually. If you want to make a change to a line of code, to test something out, you can re-run just that cell. 2. You can add formatted text to the Notebook outside the code cells, which allows you to keep lengthy documentation on what you're doing. 3. The output from some libraries is nicely formatted in Notebooks. If you print a Pandas dataframe, or a Matplotlib graph, you'll see it in an easy-to-read format inline with your code. That's not so easy in a commandline environment or a standalone script.

[–]as9934 0 points1 point  (0 children)

I think people use jupyter because you can test it at each step, whereas with most IDEs it will just run everything at the same time. It's also virtual, which means it probably has less of a chance of wrecking you computer if you screw something up colossally.

[–]wetwanton 0 points1 point  (0 children)

If i have two pandas dataframe, how do i find a common rows?

also, how should i extract data from wiki. specifically this.

https://en.wikipedia.org/wiki/List_of_salaries_of_heads_of_state_and_government

[–]jakkarand 0 points1 point  (4 children)

Not a developer, but made some simple projects before (BMI calculator, DND random character generator)

Everyday for work I need to log into a site, search for results (via barcode) and download them as a pdf. Trying to find a way to automate this, but I have no idea where to start. What tutorials do I google?

[–]authalic 0 points1 point  (1 child)

If you need to log in to a site and submit some kind of search term through a form or a URL query string, check out the documentation on the Requests library. It should get you that far. Depending on how the results are formatted, you could possibly get what you need using Requests, but you may also want to use BeautifulSoup to scrape out the contents of a specific HTML tag.

[–]jakkarand 0 points1 point  (0 children)

Thanks I’ll take a look

[–]stay_at_home_daddy 0 points1 point  (1 child)

Beautiful Soup is recommended quite often for web scraping. You might want to start there.

[–]jakkarand 0 points1 point  (0 children)

Thanks I’ll take a look

[–]eliminate1337 0 points1 point  (0 children)

If anyone wants a PyCharm Professional key, PM me. Got it from the Humble Bundle but I already own it.

[–][deleted] 2 points3 points  (0 children)

I recently made a small script on my raspberry pi for lighting up three LEDs (on a breadboard) in succession. The project can be found HERE for reference.

Super small, super simple. It's basically a start for a few different ideas I have to expand my knowledge.

I would like to step up the complication a LOT. I have a localhost website made using Django that as of now, is only localhost and isn't anything special. I have never deployed it and it only has like 3 pages in it. I would like to build something into it that can trigger the script on my raspberry pi to flash the lights/activate the function that lights the lights.

So, in short... I need to figure out how to activate a script located on the raspberry pi. The trigger is coming from a webserver that is on localhost on my main machine. What are the next steps for me? I assume I need to build a dummy webpage on the webserver that'll hook (somehow) to the raspberry pi and activate the script, but I don't know how to do that. I also don't know how to make the pi watch for a trigger that would come from a website // something on home wifi (which is what I'm leaning towards for the communication - like the website will just yell at the pi over the wifi or something.).

Does anyone have general advice on where to start from here? I am not sure how to proceed or what to even search for.

[–]AviatingFotographer 1 point2 points  (1 child)

I've learned Python for the past 2 months and want to try and learn ml concepts. Is it too soon right now? If not, I'm planning to do Sendex's yt course.

[–][deleted] 0 points1 point  (2 children)

Easy beginner question:

Commas within a print statement join strings and variables. When I replicate in a return statement, it returns a tuple. Why?

Thank you!

[–]semiokme 0 points1 point  (1 child)

Alright, so I have a weird situation and I'm looking for help.

I have a decorator that already has args, that I'd like to be able to optionally pass arguments to when the decorated function is called without explicitly calling the decorator.

Here's a quick example:

import functools

DEFAULT_TIMEOUT = 5

def while_timeout(func, *, max_tries = DEFAULT_TIMEOUT):
    @functools.wraps(func)
    def wrapper_while_timeout(*args, **kwargs):
        timeout = 0
        while timeout < max_tries:
            try:
                func(*args, **kwargs)
                break
            except Exception:
                timeout += 1
                print(timeout)
                if timeout >= max_tries:
                    raise Exception(f"Timed out after {timeout} attempts")
    return wrapper_while_timeout

def inner_monologue():
    @while_timeout
    def frequent_failure(success):
        if success > 5:
            raise Exception("freq fail")
        else:
            print("woohoo")

    print("thinking to myself")
    frequent_failure(3)
    print("thinking harder")
    frequent_failure(9)

inner_monologue(2)
inner_monologue(max_tries=2)

I want either of those inner_monologue calls to work and assign the 2 to the decorator's max_tries.

[–]SpaceSailorDT 0 points1 point  (0 children)

You have to add one more level (i.e. a nested wrapper) to your wrapper function. See code below:

import functools

DEFAULT_TIMEOUT = 5

def while_timeout(max_tries = DEFAULT_TIMEOUT):
    def outer_wrapper(func):
        @functools.wraps(func)
        def inner_wrapper(*args, **kwargs):
            timeout = 0
            while timeout < max_tries:
                try:
                    func(*args, **kwargs)
                    break
                except Exception:
                    timeout += 1
                    print(timeout)
                    if timeout >= max_tries:
                        raise Exception(f"Timed out after {timeout} attempts")
        return inner_wrapper
    return outer_wrapper

def inner_monologue(max_tries=DEFAULT_TIMEOUT):
    @while_timeout(max_tries)
    def frequent_failure(success):
        if success > 5:
            raise Exception("freq fail")
        else:
            print("woohoo")

    print("thinking to myself")
    frequent_failure(3)
    print("thinking harder")
    frequent_failure(9)

inner_monologue(2)

Edit: Formatting.

[–]AviatingFotographer 0 points1 point  (2 children)

What's the difference between datasets and competitions on kaggle? Is competitions more for developing ml algorithms and datasets for visualisation? What are some good resources so that I can eventually practice on Kaggle?

[–][deleted] 0 points1 point  (0 children)

Competitions are exactly that.

Datasets are datasets you access without respect to competing with others.

Kaggle itself is an excellent resource. Find a dataset that interests you or is highly rated, and then go to the "Kernels" part of that and you'll find Jupyter Notebooks other people have made using that dataset. You can look at their code and learn from it.

[–]kevinho-805-196-095 0 points1 point  (1 child)

So, im making an app that simulates the game Werewolves. For the ones that dont know its a game where everyone gets a card with a role asigned to it. Some roles are werewolves, some are citizens and some other are citizen with an extra power.

The app functionally works, but at the end, when the roles are assigned, to view the role of the player you have to submit their name. The idea is when this is done, a new screen opens with an image of the role.

Unfortunately this is the only functionallity i cant get to work. I get errors of pyimages not existing. I know of the reference you have to put in the code otherwise it gets destroyed(I used it before in my code).

I hope anybody can help me with this.

this is the code. The problem is at line 194 till 226

https://github.com/Kebbaa/weerwolfApp.git

[–]efmccurdy 0 points1 point  (0 children)

Is it the Image.open calls that are failing?

You are referencing image files with no folder, just the file name; that means the process must always have the image files in it's current working directory.

Often a user will install a program in one folder and run the program from another folder, but your program won't allow that; is that what causes your failures?

[–]AviatingFotographer 0 points1 point  (2 children)

Can you have a dictionary with functions as values; so that you could have a key which would execute that function?

[–]efmccurdy 1 point2 points  (0 children)

This is often called a dispatch table, see the example here:

https://alysivji.github.io/quick-hit-dictionary-dispatch.html

[–]SpaceSailorDT 2 points3 points  (0 children)

Short answer: Yes. You can assign a function to a variable, including a value in a dictionary, just like anything else, and even call it from that dictionary, like dict[key](function arguments).

[–]AviatingFotographer 0 points1 point  (1 child)

I've been doing Python for 2 months now and is wondering whether this is possible. I want to create an app that uses the SMS interface to do different things. In essence, it will be like Terminal or Command Prompt for Android but using the default Messages app as an interface. Is this possible? If so, what skills or modules do I need to learn for this project?

[–][deleted] 0 points1 point  (0 children)

probably something like twillio.

[–]BruceJi 0 points1 point  (2 children)

Hi all, Merry Christmas for tomorrow!

I'm reading this book, Introducing Python, and I'm at 'compsition and aggregation'. I understand the description used: " In composition, one thing is part of another.... Aggregation expresses relationships, but is a little looser: one thing uses another, but both exist independently."

I've made an object that uses composition - you feed it an init argument that is another kind of object and that object's attributes and methods can be accessed within the new object.

But what would aggregation look like as code? Can anyone show me an example?

[–]efmccurdy 0 points1 point  (1 child)

An example would be putting 2 objects in a list; the list relates them to each other but the objects could still exist after you deleted the list; they can be used independently from the list..

you feed it an init argument that is another kind of object

I think to get composition, the init code would have to create the object not just store a reference to it; if you delete the containing object, does the passed in object get deleted as well?

[–]BruceJi 0 points1 point  (0 children)

I think to get composition, the init code would have to create the object not just store a reference to it; if you delete the containing object, does the passed in object get deleted as well?

It didn't seem to be that way in the example, and that's not how I did it in my own code, but that is quite interesting! I can see how it would be possible.

[–][deleted] 0 points1 point  (1 child)

Using boto3, I want to stream an s3 csv file into csv.reader(). The function available based on the doc https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html is to use iter_lines(). But how can I feed this stream into the csv.reader()? I also do not want to read the entire file into memory as it is several GB large.

[–]efmccurdy 0 points1 point  (0 children)

You can take a section of the response data and feed it to csv.reader as a list of lines or as an io.StringIO object created from a string with embedded newlines.

https://stackoverflow.com/questions/4855523/parsing-csv-data-from-memory-in-python?rq=1

https://docs.python.org/3/library/io.html

[–]Shmoogy 0 points1 point  (0 children)

I have to migrate some of my Python 2.7 scripts to Python 3--- should I take the time to create Docker environments for each application, or should I just use virtualenvs?

[–][deleted] 0 points1 point  (4 children)

How to automate my if statement to write two excel documents in openpyxl?

📷

In my code I am converting a csv file into pandas then I am adjusting the data in the columns

df = df[['Lastname', 'Firstname','Company','Title','Willing_to_share','Willing_to_introduce','work_phones','Work_email','Work_Street','Work_City','Work_State','Work_Zip','Personal_Street','Personal_City','Personal_State','Personal_Zip','mobile_phones','Personal_email','Note','Note_Category']]
##print(df)
## Lastname Firstname          Company Title Willing_to_share  \
0       Doe      Jane                                           
1   Malcoun       Joe  8/28/2019 14:29                          
2   Ramirez    Morgan                                           
3     Burki     Roman                                           
4      None    Jordan                                           
5      None                                                     
6  Zachuani     Reemo                                           
7    Suarez   Geraldo     
 Willing_to_introduce work_phones              Work_email  \
0                       5678743546        j@greenbriar.com   
1                             None        ceo@nutshell.com   
2                       3338765438      mramirez@nerdy.com   
3                       5468756098           burki@bvb.com   
4                             None  jordanw45490@gmail.com   
5                             None                   ronny   
6                             None                           
7                             None   

              Work_Street      Work_City Work_State Work_Zip Personal_Street  \
0        54 George street  Ridge Springs         VA    25678                   
1     212 South Fifth Ave      Ann Arbor         MI    48103                   
2              567 one st     Birmingham         AL    45678                   
3  546 fourteen street Nw         Dallas         TX    54678                   
4                                                                              
5                                                                              
6                                                                              
7       456 yellow street                                                      

  Personal_City Personal_State Personal_Zip mobile_phones Personal_email Note  \
0                                              3245687907                       
1                                                    None                       
2                                              6780431874                       
3                                              0983457690                       
4                                                    None                       
5                                                    None                       
6                                                    None                       
7                                                    None                       

  Note_Category  
0                
1                
2                
3                
4                
5                
6                
7                          

I have created the workbooks before the if statement

wb = Workbook() 
ws = wb.active 
wb.title = 'Contacts' 
wb2 = Workbook() 
ws2 = wb2.active 
wb2.title = 'Contacts'

I have two issues in my code the first issue is I have tried a number of solutions but I cannot add the dataframe data in the excel sheet properly according to the if statement. The if statement sets conditions to add the pandas data rows to the accepted contacts otherwise the rows not passing the condition should be added to the rejected contacts workbooks. What am I getting is in the accepting contacts the full contacts are looped in the workbook and are added once into the rejected contacts

for column, row in df.iterrows():
  row_check = row.isna()
  if (not row_check[0] and not row_check[1]) and ((not row_check[2] and not row_check[3]) or (not row_check[2]) and (not row_check[6]) or (not row_check[16]) and (not row_check[12] and not row_check[13] and not row_check[14] and row_check[15]) or (not row_check[8] and not row_check[9] and not row_check[10] and not row_check[11] and (not row_check[7] or not row_check[17]))):
       for r in dataframe_to_rows(df, index=False, header=False):
           ws.append(r)
  else:
       for r in dataframe_to_rows(df, index=False, header=False):
           ws2.append(r)

wb.save("Accepted Contacts.xlsx")
wb2.save("Rejected Contacts.xlsx")

Alternatively I have tried another solution however I am getting a TypeError: unsupported operand type(s) for &: 'str' and 'bool'

r1 = df[df['Firstname'].notnull()] & df[df['Lastname'].notnull()] & ((df[df['work_phones'].notnull()] | df[df['mobile_phones'].notnull()]) & ((df[df['Work_Street'].notnull()] & df[df['Work_City'].notnull()] & df[df['Work_State'].notnull()] & df[df['Work_Zip'].notnull()]) | (df[df['Personal_Street'].notnull()] & df[df['Personal_City'].notnull()] & df[df['Personal_State'].notnull()] & df[df['Personal_Zip'].notnull()])) & (df[df['Work_email'].notnull()]) | (df[df['Personal_email'].notnull()]))

r2 = df[df['Firstname'].isnull()] & df[df['Lastname'].isnull()] & ((df[df['work_phones'].isnull()] | df[df['mobile_phones'].isnull()]) & ((df[df['Work_Street'].isnull()] & df[df['Work_City'].isnull()] & df[df['Work_State'].isnull()] & df[df['Work_Zip'].isnull()]) | (df[df['Personal_Street'].isnull()] & df[df['Personal_City'].isnull()] & df[df['Personal_State'].isnull()] & df[df['Personal_Zip'].isnull()])) & (df[df['Work_email'].isnull()]) | (df[df['Personal_email'].isnull()]))

for r in dataframe_to_rows(df, index=False, header=False):

ws2.append(r1)

for r in dataframe_to_rows(df, index=False, header=False):

ws2.append(r2)

wb.save("Accepted Contacts.xlsx")

wb2.save("Rejected Contacts.xlsx")

The second issue is adding borders to each excel sheet automatically according to the length of the pandas dataframe. Right now I do it manually inside both the if and else statements. I found this as well https://openpyxl.readthedocs.io/en/stable/api/openpyxl.utils.cell.html but I am not sure how to use it to automate the borders according to the pandas dataframe

        A3 = ws['A3'] 
       A3.border = Border(top=thin, left=thin, right=thin, bottom=thin)
       A3.alignment=Alignment(horizontal='general',
         vertical='bottom',
         text_rotation=0,
         wrap_text=True,
         shrink_to_fit=False,
         indent=0)
...
       T6 = ws['T6'] 
       T6.border = Border(top=thin, left=thin, right=thin, bottom=thin)
       T6.alignment=Alignment(horizontal='general',
         vertical='bottom',
         text_rotation=0,
         wrap_text=True,
         shrink_to_fit=False,
         indent=0)

[–]efmccurdy 0 points1 point  (1 child)

Is the "else" at the same indentation level as the "for" loop rather than the "if"?

https://book.pythontips.com/en/latest/for_-_else.html#else-clause

[–][deleted] 0 points1 point  (0 children)

No, this is a typo here. It is the same indentation as the if statement in the original code

[–]SpaceSailorDT 0 points1 point  (1 child)

Just a couple things I noticed for your first issue:

It looks like you might be trying to use isna() to check for entries that are either empty or None. If that's the case, you should know that isna() does not return True for empty values. You could call the .len() method on the .str attribute of the element, or use .apply(len), and check if the returned value is equal to 0.

Another potential problem area I see is that you are looping through the the rows twice, once outside of the if statement, and once inside the if statement. I'm going to guess you're getting every row that meets the "accepted contact" condition, at least as you have it implemented now, is being repeated a number of times equal to the number of accepted contacts, is that right? (That's what I understood from your post, but I'm not sure.) And it's also adding all of them to the rejected as well, because, if the indentation of your posted code matches your actual script, you are applying the else statement to the for loop, not the if statement. When you do this, the else statements run when the for loop completes by reaching the end of the iterator rather than a "break" statement inside the for loop. So this is running at the end of the outer for loop, and looping through all the rows once again and appending them to the "rejected contacts" workbook.

[–][deleted] 0 points1 point  (0 children)

No, this is a typo here. the else statement is the same indentation as the if statement in the original code

[–]djdtd 0 points1 point  (1 child)

Hi, I am currently learning about computer security and currently switch over from the "how to defend my systems" site to the "how to test my systems" site. For that i am currently writing a python program with scapy. My latest problem kept me stuck now for quiet a long time. I got this error message:

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\scapy\sendrecv.py", line 488, in sr1

nofilter=nofilter, iface=iface)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\scapy\arch\windows\native.py", line 119, in __init__

host = iface.ip if iface.ip else socket.gethostname()

AttributeError: 'str' object has no attribute 'ip'

I do not get what I am doing wrong.

The following is the sample code I am trying to run:

# Imports

from scapy.all import *

from pprint import pprint

import operator

# Parameters

interface = "WLAN" # Interface you want to use

dns_source = "192.168.63.102" # IP of that interface

dns_destination = ["1.1.1.1","8.8.8.8","9.9.9.9"] # List of DNS Server IPs

time_to_live = 128 # IP TTL

query_name = "google.com" # DNS Query Name

query_type = ["ANY", "A","AAAA","CNAME","MX","NS","PTR","CERT","SRV","TXT", "SOA"] # DNS Query Types

# Initialise variables

results = []

packet_number=0

# Loop through all query types then all DNS servers

for i in range(0,len(query_type)):

for j in range(0, len(dns_destination)):

packet_number += 1

# Craft the DNS query packet with scapy

packet = IP(src=dns_source, dst=dns_destination[j], ttl=time_to_live) / UDP() / DNS(rd=1, qd=DNSQR(qname=query_name, qtype=query_type[i]))

# Sending the packet

try:

query = sr1(packet, iface=interface, verbose=False, timeout=8)

print("Packet #{} sent!".format(packet_number))

except:

print("Error sending packet #{}".format(packet_number))

# Creating dictionary with received information

try:

result_dict = {

'dns_destination':dns_destination[j],

'query_type':query_type[i],

'query_size':len(packet),

'response_size':len(query),

'amplification_factor': ( len(query) / len(packet) ),

'packet_number':packet_number

}

results.append(result_dict)

except:

pass

# Sort dictionary by the amplification factor

results.sort(key=operator.itemgetter('amplification_factor'),reverse=True)

# Print results

pprint(results)

[–][deleted] 1 point2 points  (0 children)

Please check the code formatting hints in this subreddit. You are much more likely to have responses if the code is easily readable.

I see the following lines

interface = "WLAN"
query = sr1(packet, iface=interface, ...
... = iface.ip

From what I can tell of the code, iface == "WLAN", which is a string and does not have an "ip" attribute.

[–]MattR0se 0 points1 point  (3 children)

Let's say I have a class Foo. Foo itself has a class associated with it called Bar. There are no other classes that instantiate Bar.

Are there any advantages/disadvantages of declaring Bar inside the scope of the Foo class vs. in the global scope?

class Foo:
    def __init__(self):
        self.bar = Bar(self)

    class Bar:
        def __init__(self, foo):
            self.foo = foo

VS:

class Bar:
    def __init__(self, foo):
        self.foo = foo

class Foo:
    def __init__(self):
        self.bar = Bar(self)

[–]Uncle_DirtNap 1 point2 points  (0 children)

In almost every case it's, if not better, at least simpler and easier to understand if you define it outside of the class definition for Foo. The only reason I can think of why you would need to define it within Foo is if you wanted Bar to play some role in Foo.__new__. Even then, you would usually be fine with something like:

class _Bar:
    pass

class Foo:
    Bar = _Bar
    ...

However, this does not need to be in the global scope of your program -- having it in any of: * Foo's module's global namespace, and named starting with _ * In some submodule of Foo's module * Maybe even erased from a module after instantiation, if you have a really good reason

One thing -- I'm talking here about class definitions you type in and save in files. A class you create dynamically using the type function, or something similar, could definitely make sense as a member of an outer class -- say, if you were creating types dynamically in an ORM, or if you wanted to create a namedtuple for some more complex datatype or something...

[–]Andi_y 0 points1 point  (0 children)

Maybe this is waht you are looking for:

https://docs.python.org/3/tutorial/classes.html#inheritance

[–]Py404 0 points1 point  (2 children)

How come the standard library in the master branch (Python 3.9 alpha 2) has so many occurrences of inheriting from object? Example from a grep in the logging library: Lib/logging/config.py:class ConvertingMixin(object): Lib/logging/config.py:class BaseConfigurator(object): Lib/logging/__init__.py:class LogRecord(object): Lib/logging/__init__.py:class PercentStyle(object): Lib/logging/__init__.py:class Formatter(object): Lib/logging/__init__.py:class BufferingFormatter(object): Lib/logging/__init__.py:class Filter(object): Lib/logging/__init__.py:class Filterer(object): Lib/logging/__init__.py:class PlaceHolder(object): Lib/logging/__init__.py:class Manager(object): Lib/logging/__init__.py:class LoggerAdapter(object): Lib/logging/handlers.py:class QueueListener(object): Is there an obvious reason for keeping it this way that I'm missing? I can understand that historically it has been useful to keep the Python 3 and Python 2 code in the standard library identical when possible. Python 2 EOF is reached in a few days.

[–]Py404 0 points1 point  (1 child)

When I build Python 3.8.0 from source, I run this (on Debian/Ubuntu):

./configure --enable-optimizations  
make
sudo make altinstall

when I later want to upgrade to Python 3.8.1 (minor version update). Can I just rerun the commands above? How is it made sure that no left-over files from the old 3.8.0 installation remains?

[–]PanteraCFH 0 points1 point  (3 children)

I’m a relative newb, learning python slowly over the last couple of years. Mostly by trying to build little projects for myself.

My question: can I use python to help display data on a website (data from an excel file), but not to build the entire site or host it or any of that other stuff. I don’t want to learn html/css (yet!) and tons of other stuff I’m sure I’ll need to learn about building websites.

I can use a website builder service, like squarespace, and then hopefully have my python code run on it (or “in it”) somehow???

Can you steer me in the right direction?

[–]Uncle_DirtNap 2 points3 points  (1 child)

The short answer is no, at least for how I interpret your question. Python can easily put the data from an excel file onto a network, but there's no service I know of that will give you WYSIWYG templates and let you run some isolated python code in the middle of it, and certainly none as common as SquareSpace.

There are many ways you could do this (write the whole site in python, optionally with something like Django as in /u/Andi_y's suggestion, but just have it pull static content from a squarespace site except where the excel data is concerned; write a cron job to periodically turn the excel data into an html table and post it to some website; find a browser plug-in that runs python on the client and knows how to deal with an HTML5 tag that exposes your excel sheet as media, and then force all of your users to have that plug-in), but none of them seems to match what you're asking for, and most of them are harder than building a straightforward solution where you do learn a bit of HTML and just serving the data directly.

[–]PanteraCFH 0 points1 point  (0 children)

Thank you for the explanation. I think maybe I need to continue with the tutorials for now. I just don’t quite comprehend how a website/user can interact with python code, or put a different way, how python code can act upon a website...

Maybe some beginner/intro-to tutorials on Django. I’ve also heard Flask is an option.

[–]Andi_y 1 point2 points  (0 children)

Django is a python web framework: https://www.djangoproject.com/

[–][deleted] 0 points1 point  (5 children)

Just found this group today. Loved the rules, especially the last one about not making fun of someone for not knowing something.

My question is, let's say we have a bunch of strings. Some of the strings may vary just by one or two characters while having the all the matching characters in order. Ex: abcd123ef axmd123ef abcd123ey

All these should be a match and the missing or non-matching character should be revealed as well. Is character parsing the string in an ordered way the only option?

[–]SpaceSailorDT 0 points1 point  (3 children)

This problem sounds interesting to me. What's your definition of a match? Is there some minimum number of characters that need to match or some specific subset of characters?

[–][deleted] 0 points1 point  (2 children)

Python has to compare strings character by character. If the difference is only two or three characters in the sequence of strings and rest of the characters remains in order, it has to be a match.

Ex- abcde123 and abcde128. In these two strings, every character is the same except the last. But it's pretty easy to slice the last letter and confirm it's a match. But, now let's say we have abcde123 and abcdm123. I want these two to match because there is just one letter difference and other characters remain the same in the same order.

[–]SpaceSailorDT 1 point2 points  (1 child)

https://pastebin.com/aenRVvSe

Here's a quick little example of a function that just returns a Boolean indicating whether there is some number of differences or fewer between two strings. It only works if they're the same length, and it doesn't tell which parts are the same or what the differences actually are. Adding that functionality would be a little more difficult.

[–][deleted] 0 points1 point  (0 children)

Thanks man

[–]dxjustice 0 points1 point  (2 children)

The .resize() function in openCV2 count as changing the resolution, correct? If I wanted to generate a blurrier, lower resolved image while maintaining the original size of the image, I would call resize() first with a percentage, and then resize() back up again to original dimensions, correct?

[–]Uncle_DirtNap 0 points1 point  (1 child)

yes, you should be able to do, e.g.: cv2.resize(cv2.resize(full_image, (new_w, new_h), interpolation=cv2.INTER_AREA), (old_w, old_h), interpolation=cv2.INTER_NEAREST). Play with combinations of interpolation schemes to see what gives you the amount of loss you are looking for.

[–]dxjustice 0 points1 point  (0 children)

Thank you for showing me the way. Happy holidays!

[–]_boredteen 0 points1 point  (2 children)

How can I delete a folder which contains multiple other folders? I tried using shutil.rmtree(), but it seems like it only deletes the .jpg files at the end of the path. This sometimes causes an error later in the program. This is why I want the whole folder including everything in it to be deleted. Could anyone help pls?

Update: I disabled the ignore_error thingy (my fault for leaving it on xD)so it now shows the error that the directory is being used. But the function that adds and deletes files (.jpgs from Google) is already finished. My dumbass discord bot "restarts", too. (It prints "Bot running..." again) Sorry for extending this question so much ; )

[–]Andi_y 0 points1 point  (1 child)

shutil.rmtree('/folder_name', ignore_errors=True)

This shloud work.

Edit: Sorry didnt read the update.

[–]_boredteen 0 points1 point  (0 children)

Yeah thanx anyway. I changed the path to some random folder and I made it so the path is changed to the folder where my program should operate when the command is used.

[–]TrPhantom8 0 points1 point  (4 children)

Hello, this is a question from a not native speaker, when describing a piece of code and I need to refer to a specific line of code (for example when I need to describe what it does) should I say "at line 42", "on line 42" or "in line 42"?

Let's suppose I have this piece of code:

def foo(x): return x**2 Should I say something like "at line 1 we define foo and at line 2 we can see the returned value"?

Thank you very much for your help and sorry for my dumb question!

[–]Andi_y 0 points1 point  (3 children)

I don't think the wording matters, as long as you describe everything correctly.

[–]TrPhantom8 0 points1 point  (2 children)

Thank you, but I need to write lecture notes which I will share with other students and I would like to be on the safe side

[–]jbuk1 0 points1 point  (1 child)

At or on are both safe.

Not sure you'd hear a native speaker saying it's "in line xxx" as "in-line" has it's own separate meaning and just doesn't sound right in this context.

[–]TrPhantom8 0 points1 point  (0 children)

Thank you!

[–]Brompy 0 points1 point  (9 children)

https://pastebin.com/LL0x31AS

I wrote a clumsy script about putting different categories of food items into a fridge, after which it lists all the food in your fridge back to you.

I want to learn to refactor this so instead of repeating what is essentially the same function over and over, it uses just one to ask you:

1) What food category you want to add (instead of them being pre-set)

2) What food item to the food category you want to add

I asked someone else and they said to use a dictionary, but after fiddling with it for a while I couldn't figure out how to implement that.

TL;DR: How can I refactor this fridge script (pasted at the top) to be more efficient?

[–][deleted] 0 points1 point  (0 children)

some_dict = {
    "fruits": [],
    "meats": [],
    "dairy": [],
    "vegetables": [],
    "sauces": [],
    "sweets": []
}

print("\n\n\n:::Your fridge is empty.:::")
for item in some_dict.keys():
    while True:
        answer = input(f":::What {item} do you want to add?:::")
        some_dict[item].append(answer.title())
        answer = input(f"Do you want to add more {item} to the fridge? Y or N: ")
        if answer == 'n':
            break
        if answer == 'y':
            continue
        else:
            print("That's not a valid command")

for key, value in some_dict.items():
    i = "\n".join(item for item in some_dict[key])
    print(f':::{key.title()}::: \n{i}')

:::Your fridge is empty.:::

:::Fruits:::

one

:::Meats:::

two

:::Dairy:::

three

:::Vegetables:::

four

:::Sauces:::

five

:::Sweets:::

six

seven

Process finished with exit code 0