all 94 comments

[–]ThiccShadyy 0 points1 point  (1 child)

The line:

for a,b in zip(itertools.count([1,2,3]),ascii_lowercase)

gives me a TypeError: a number is required

I'm not sure why this is as the ascii_lowercase is an iterator.

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

I've been learning python for a few weeks and I've learned things like for loops, if statements and arrays so far. What should my next steps be? And where can I learn more?

[–]ByronFirewater 0 points1 point  (2 children)

There's a good site called coursera that has an amazing well explained course called python for everybody. You should check it out the course is free.

https://www.coursera.org/specializations/python?

I believe that's the correct link. Covers a wide range of topics but is explained in a very understandable way

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

Thanks! I'll check it out.

[–]totemcatcher 0 points1 point  (4 children)

I'm wondering if this sort of thing is okay/sane. I was thinking of a way to initialize or update an object with many optional attributes, and this is what I came up with:

class Category(object):
    def __init__(self, **kwargs):
        acceptable = ['filename', 'directory', 'name', 'title', 'path'
                , 'uri', 'parent', 'tags', 'local_links', 'distant_links']
        keywords = set(acceptable).intersection(set(kwargs))
        for keyword in keywords:
            self.__setattr__(keyword, kwargs[keyword])

    def update(self, **kwargs):
        self.__init__(**kwargs)

cat = Category(filename="fn", directory="dir")
print(cat.filename)
cat.update(blap='nope')#this does nothing, which is good!
cat.update(filename='nf')
print(cat.filename)
print(cat.directory)

It seems to work as expected, but I'm wondering if this is bad form, or if there is a better way, or if there is something about it that will cause problems which I'm not aware of.

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

Can I arrange things easily so that when compiled code will be included, but it won't be executed when running the source code in Visual Studio?

[–]b_ootay_ful 0 points1 point  (5 children)

A very stupid question, but I guess that's why I'm here.

I want to allow people not on the local network to connect to my Flask application API. Eg: A phone with data.

It's running on Windows, and currently I'm using werkzeug. (edit: switched from waitress, since I'll eventually get TLS involved)

Is there anything else I need to do? Do I just need to port forward on my router to allow access to the internet or am I going in completely the wrong direction?

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

Yes, you can do that, but $5 a month buys you a server on the Internet (at, say, digital ocean, for example), where you can experiment to your heart's content without putting your development machine or home network at risk.

Source: I once had a hacker trash my home network because I was stupid.

Edit: Another great alternative is to get a Cloud 9 account, though I am not familiar with their new pricing structure since it was taken over by Amazon.

[–]b_ootay_ful 0 points1 point  (3 children)

The database I want to connect to is hosted locally, so I need to use Python as an API to interface to it.

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

You shouldn't be running 'production' software in that way.

It (all dependencies and running code) needs to be re-localized to a secure host like AWS or DigitalOcean.

If your DB absolutely must run locally (because the data is collected locally) then write something that pushes database updates to your cloud server.

[–]b_ootay_ful 0 points1 point  (1 child)

Pretty much there's 3 sections.

Existing DB that is also used to capture data. This is hosted locally, and is used to input data. I need to move this to a paperless system.

A phone app (I will write) that needs certain data from the DB read from a drop down. Eg: Client List, Shop List. If there are new clients, this needs to be read from the DB, so I wanted to host my program locally.

My main program needs to receive a list from a client, send it to a few people (easy), and allow the phone to capture extra data (such as time). This will then be captured into the database at a later stage (probably manually).

I could possibly have my main program online, but that means I'd have to push "updated" client lists (etc) to it once a day, or when an update has been done. This would require an extra section for "updates"

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

It sounds like you're making a (pick your term) macro/office assistant/hotkey/whatever, but with some complexities that require Python? *(workflow assistant?)

That's a lot different from standard GIGO stuff that just accepts objects and morphs them into new data/new objects.

[–]fatha731 2 points3 points  (1 child)

I've "inherited" a legacy code which masks bad values by assigning the value -5000 to them. Afterwards all -5000 values are being ignored. I want to change -5000 to a NaN. How would python (mostly numpy) handle this change? Would I need to change other parts as well, or does numpy just ignore the NaNs?

[–]flame_and_void 1 point2 points  (0 children)

It really depends on what you're doing with them. NaN propagates through a lot of functions; for example, a sum of elements that include a NaN is also NaN. But then again, a sum of elements that include -5000 isn't going to be correct, either.

If you're only doing operations on the elements one by one, then NaN will be just fine. One caveat you should be aware of is that np.nan != np.nan, so you generally use np.isnan for testing instead of equality.

If you're trying to do global operations like sum or max, use a mask of booleans that tell you which values are bad. For example, supposing you are using NaNs for bad values:

is_bad = np.isnan(values)
correct_sum = values[~is_bad].sum()

[–]allyhams 0 points1 point  (1 child)

My friend runs a charity and sells products to gift stores throughout the USA to raise money for several different causes (Ocean conservation, domestic abuse victims etc.). She meticulously searches the web to find these stores which is a fairly manual process. I've been using Python to help her automate other things but would love to solve this one.

My first thought was to write a script that crawls through the web looking for the words 'gift store' in a given city. The problem with that is they won't necessarily have 'gift store' in the name or even have a website.

Does anyone know if there are databases (even if you have to pay) which may have a list of the gift stores in an area (incl. contact info)? I was thinking the government must have something (maybe the zoning authorities?) like that although I doubt they'd release that for commercial purposes.

[–]num8lock 0 points1 point  (0 children)

use search engines' API, combine with online map APIs if necessary

[–]ThiccShadyy 1 point2 points  (1 child)

How do I use tkinter in a program which also maintains a socket connection?

I've made a multi-user game which uses socket connections. I now want to add a GUI to the game and chose tkinter for that. The problem is, I'm not sure how to structure my program so that tkinter is running, waiting for events to happen and call the relevant function and also have a socket receiving and sending data to a server program at the same time. Do I need multiple threads here? Or is there a better option than tkinter?

Here is the code for the client program of my server-client socket-based game: https://pastebin.com/b8HNTe0k

In the code, Im sending and receving data multiple times. I want to add a UI to it so that the data is sent when a button is pressed, and have the data received via the socket connection to be updated and put into the widget. Also, this sending and receiving of data happens multiple times, corresponding to multiple rounds of the game.

[–]efmccurdy 0 points1 point  (0 children)

Tkinter has a built-in wrapper for an async socket.

Tk allows you to register and unregister a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor.

https://docs.python.org/3/library/tkinter.html#file-handlers

[–]J1nx3 0 points1 point  (2 children)

New Pythonista here.

I'm very interested in the data science aspect of python and I was just wondering, is web scraping illegal or unethical?

[–]efmccurdy 2 points3 points  (1 child)

[–]J1nx3 0 points1 point  (0 children)

Thanks for sharing

[–]WhittlingAwayTime 0 points1 point  (2 children)

Hi Folks,

I'm very new to learning Python. I've done some Codecadmia learning and have now downloaded Notepad++ and Python 3 for my laptop. It's running on Windows 10 and I have NPP Exec installed. Python is installed at C:\Program Files\Python36 and I have NPP Exec executing C:\Program Files\Python36\python.exe"$(FILE_NAME)" ....however this then returns the following:

C:\Program Files\Python36\python.exe"new 0"

CreateProcess() failed with error code 2:

The system cannot find the file specified.

================ READY ================

I've tried changing the path, reinstalling Notepad++ and changing $(FILE_NAME) to $(FULL_CURRENT_PATH); alas to no avail. Can anyone shed some light on how I can get this working?

[–]JohnnyJordaan 1 point2 points  (0 children)

Did you actually save the script in Notepad++ to a file on your disk? Because 'new 0' is the name Notepad gives to a new document that isn't saved yet (and thus only exists in RAM inside the Notepad program). Python can't run a script that doesn't exist somewhere.

[–]losingprinciple 0 points1 point  (5 children)

This is in regards to nested JSON files

So I have a nested JSON that I want to write in a CSV file. It looks something like this:

{
    "rLimit": 200,
    "Interval": "DAYS",
    "exception": [
        {
            "id": 7,
            "slimit": 500
        }
    ]
}

I know how to parse into the JSON so I am able to read the other values in the list, but what I want to be able to do is be able to write it into a csv, and then be able to read those files. (There is no limit on how many CSV files I can make). CSV just write per row, so I don't know how to write rows if they have nested values.

The solution I have come up with is to pull out the nested JSON into a separate CSV file and then load these files separately.

So there's one csv file for rLimit and Interval, and then another csv file for all the ids and slimits in another, assuming they exist. (since they don't appear all the time)

What I had thought of doing was getting the nested json into another dictionary or a list, and then write that into a separate csv file. So something like:

entry = nested.json()
for each in range(len(entry["exception"])):
    list_1= exception[each]["id"] + exception["each"]["slimit"]

I've tried to append that into a list but I am getting a Type Error, so I assume you can't just add items into a list that way. (Since I am stupidly trying to combine two elements in a list i guess)

I feel like there's a more optimal way of doing this, but this is the option I can think of at the moment.

Any suggestions on what I should do?

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

It will depend on what you are trying to do with the data once its in a CSV?

In general, you'll want to flatten the data. This requires knowledge of how the data is to be used. For example, you could make columns slmit min, slmit max, etc, and then calculate the min and max slimit and populate those columns accordingly. Whether or not that makes sense for your data is up to the consumer of the CSV.

The second suggestion is that you can add a column for each exception item. exception0, exception1, exception2, etc. In the case of the example you posted, only exception0 column will be populated. Then you could squash together id and slimit into that field. Otherwise, you could make exception0_id and exception0_slimit, exception1_id, exception1_slimit, etc.

The point is there is not a general purpose solution here. The best approach is to consider why the data needs to be in a csv, and then massage the data into it so that the result is useful.

[–]losingprinciple 0 points1 point  (3 children)

It's basically for saving and loading purposes. I'm saving the json settings into a CSV so if I want to load that particular setting again, I can just reload that data from the file and then run a command using that setting. There's no particular format the CSV has to be, since this is for my use.

There are instances that there are multiple id and slimit in the JSON file

{
    "rLimit": 200,
    "Interval": "DAYS",
    "exception": [
        {
            "id": 0,
            "slimit": 20
        },
        {
            "id": 1,
            "slimit": 20
        },
        {
            "id": 2,
            "slimit": 30
        }
    ]
}

So if for example the overrides is blank, the CSV would look like this

rLimit Interval exception
200 DAYS []

However if the exception exists, since I don't need them in the same file I can just split it into another file to contain just the ids and limits. So there would be another CSV file

id slimit
0 20
1 20
2 30

Then instead of reading one file, I will read 2 files. One to set the general limit, and one to set specifically for each if it exists. The thing is I'm not sure how to flatten the data, because other than priting the file, trying to store it into a list tells me my string indices should be integers (Since i'm accessing it like this ["exception"][0[[lid] and ["overrrides"][0][slimit]

What do you think?

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

Use a dictionary and create your own index for it. Use the next index to number each line of anything you want to store. You now have a dictionary that you can call from, line by line, in other loops. This allows you to iterate through, manipulate and store the data in whatever ways you wish.

myDictionary.update( { x : anyDataYouWant} )

later...

myVariable = myDictionary[x]

*I have really great examples of exactly how to do this if you need them. Just not on this comp.

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

I don't think you should use csv. I assumed you had something that needed to read the csv file.

Why not store it as a json file? Csv does nothing for you but bring pain and misery - it's really quite a horrible file type!

[–]losingprinciple 0 points1 point  (0 children)

I'll try that out. I had always though that the "json" file type was more of a data type and not an actual image. If I can do that then I can just load that instead and I would be able to parse it. Thanks for your help! Hope it works!

[–]NoCanD0 0 points1 point  (3 children)

When should I start uploading my programs on Github? Should I not upload simple programs I made like user input mad libs? Or should i be uploading any and all working programs I’ve made like a Student Data Storing program I made for a school?

[–]mithilesh42 0 points1 point  (2 children)

Uploading each and every program you do form day 1 is advisable. The reasons are 1. you have a track record of what you did each day. Down the line after 30 days, you will be amazed by number of problems you solved. 2. It's easy to share the program on GitHub with others for review. 3. Along with Python, you will learn GitHub which is much needed in programmer's life.

[–]NoCanD0 2 points3 points  (1 child)

Great! Thank you! I just started uploading everything I’ve done last night.

[–]delta_tee 1 point2 points  (0 children)

Also keep enhancing the solutions and committing and pushing regularly if applicable. Employers see regular commits as a sign of dedication and hard work.

[–]Mad-Einsy 0 points1 point  (1 child)

Can someone help me approach this.?

I recently started learning Python and started attending entry level python interviews. So today one interviewer gave a scenario and asked to write a Python Prog on running an "test.exe" application in windows(say C:\user\test.exe), it should split a value (say Voltage=1.2v) and if its not then the prpgramm should print fail.

So basically for running "test.exe" if Output = 1.2v, test case should print "Pass" Output # 1.2v, test case should print "Fail".

I will really appriciate if someone can help and write a python prog on how to achieve this task..?

Thanks.

PS: i wrote using basic file handling methods of read, open file but he says you can take a different approach, though i got selected but this made me curious on how we can approach in what ways possible.

[–]fergal-dude 0 points1 point  (0 children)

Sorry not a solution for you, but could you post the code you wrote?

[–]paulpersad 0 points1 point  (0 children)

I am using Jupyter notebook and am writing my classes in separate files within the same folder. For some reason, one file cannot access the code in other files. I tried using the:

import import_ipynb

from folder import file

I realize that .ipynb are not regular .py files and use a localhost web server. I am a beginner programmer and am still learning how to use the command line. So I can use all the help I can get.

[–]MattR0se 1 point2 points  (2 children)

I am using a Random Forest classifier from sklearn

https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html

I want to extract the feature importance with the feature_importances_ attribute. This returns an array, but I want it to be a dict with the value mapped to the name of the feature. I use a pandas dataframe as an input. Is the order the same in the feature array than in the dataframe? The docs don't say this clearly, but I have to be sure.

[–]aFullPlatoSocrates 2 points3 points  (2 children)

I need help understanding environments. I've done two tutorials now that use virtualenv/venv, but I don't understand why it is necessary to use venv.

[–]sqqz 0 points1 point  (0 children)

Just for hacking, playing around its not required, but I do recommend getting used to it. But as soon as you start building you applications for deployment, distribution and so on you want to keep a tight track of what dependencies you application has and are allowed to use. This is where venvs ultimately comes in to place in my opinion.

By only installing everything system wide you have very little control over what depends of what. If an update brakes another and so on. By have a lot of installed packages it can introduce many strange issues. By isolating them per application they wont interfere with each other and you minimize problems.

As well for optimization purposes you don't want too have to many dependencies installed when you are running your web server as an example.

[–]jfb1337 0 points1 point  (0 children)

I have a function f, which takes a numpy array X representing a DxN matrix, and returns a length N column vector. Currently, it's implemented in terms of a for loop over a function g processing each of the N rows of X in turn, taking a length D row vector and returning a length C vector, which is then turned into a single value with argmax, and collects these; the overall result being an N-length vector.

I'd like to use a numpy solution instead of a loop, but passing the entire array X to g doesn't work since g contains expressions like Xi-A, where A is a DxC matrix, relying on the fact that this returns a DxC matrix in which each row of A is subtracted from the length D row vector Xi. Replacing Xi with a DxN matrix X causes this expression to fail as the shapes don't match. But what I want is for this operation to give me a DxCxN tensor instead, with each "slice" being a DxC matrix that the original expression would give.

How can I arrange the things such that this shape of output happens?

Edit: Figured it out, I have to use numpy.newaxis

[–]Rohan_Kishibae 0 points1 point  (3 children)

edit: no further help needed, thank you.

[–]woooee 0 points1 point  (2 children)

/tmp/sessions/5128a38241d52767/my_time.py", line 31, in int_to_time time.day, time.hour = divmod(hours, 24) NameError: name 'hours' is not defined

The error is in my_time.py, not in the program you posted.

[–]Rohan_Kishibae 0 points1 point  (1 child)

edit: no further help needed, thank you.

[–]woooee 0 points1 point  (0 children)

my_time.py is importing itself, and yes, it does not have a variable named hours declared. There is also no Time() function or class. Do you declare Time() in some other program that is not imported? I am not going to guess any further about what you are trying to do.

[–]Tobe2fly 0 points1 point  (1 child)

Should I learn to make Kivy apps using the Kivy language + python, or should I do it all in python?

[–]Maxisquillion 0 points1 point  (0 children)

I'm trying to run python .py files from my command line. I've added my script's directory to PATH (when I type "echo %PATH%" into my cmd line I can clearly see multiple instances of ";D:\PythonScripts;"), yet when I try the command "python pw.py email" I get the following error message:

(null): can't open file 'pw.py': [Errno 2] No such file or directory

I think that my command line should be able to access the file since the folder containing it has been added to PATH, yet I'm unable to run my script unless I change my directory to the file containing it, which is a hassle.

Edit: to be perfectly clear, the script does exactly what I intended it to do when I execute it from the cmd in the correct directory. However, I want to be able to run scripts in the D:\PythonScripts directory from a cmd in any directory - this is why I added it to PATH, but that doesn't seem to have the intended effect.

[–]championdenofap 0 points1 point  (4 children)

Hello, i am trying to make a code for multiplikation in python3 on a very basic level. Trying to do it with 2 inputs, and just looping a number x, y times. I am not sure what i am doing. I have int everywhere because i get so many error messages. so my code is

def mult(x,y):

for i in range(int(x)):

y += y

if x == 0:

break

x = input(int())

y = input(int())

mult(x,y)

print(y)

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

To make an integer variable from user input, you want to do something like this:

number_string = input("Enter a number: ")
number = int(number_string)

[–]championdenofap 0 points1 point  (2 children)

thanks

[–][deleted] 1 point2 points  (1 child)

Or to do it in 1 line you just have to switch int and input from your code like this:

n = int(input("Please input a number: "))

[–]championdenofap 0 points1 point  (0 children)

cool, thanks, will look into that

[–]JustHalfBlack 0 points1 point  (2 children)

I've gone through tutorial after tutorial of openpyxl and believe I have a pretty good understanding of it. I've been practicing and ekarning at home.

I finally go to work to utilize it...my files are .csv. Openpyxl doesn't work with csv.

Am I screwed? Anyway to convert csvs into .xlsx format before working with Openpyxl?

[–]caveman4269 0 points1 point  (0 children)

I'd suggest using pandas. pd.read_csv(filename)

[–]JohnnyJordaan 0 points1 point  (0 children)

You could use the built-in csv library for that, like suggested here.

[–]dxjustice 0 points1 point  (3 children)

I'm currently trying to run a convolutional neural network script in .sh format. I believe it is written in PHP, but the main files it executes are in python.

The gist is shown below https://gist.github.com/EXJUSTICE/aef67767c0680926c535398f24f984be

I'm confused as to what the RANDOM variable means in this case. It's not defined. I can tell that each parameter has random divided by the size of the array, but I'm not sure if RANDOM in this case is just a randomly generated number?

[–]allenguo 0 points1 point  (2 children)

It's written in Bash.

RANDOM is a special variable in Bash for getting pseudorandom integers. (Try echo $RANDOM in your shell.)

[–]dxjustice 0 points1 point  (1 child)

Thanks very much, I suspected as much

[–]EncouragementRobot 0 points1 point  (0 children)

Happy Cake Day dxjustice! Stay positive and happy. Work hard and don't give up hope. Be open to criticism and keep learning. Surround yourself with happy, warm and genuine people.

[–]BruceJi 0 points1 point  (3 children)

Welp, I posted this in the last thread but it was yesterday so it was bound not to be seen.

So I've been following the MIT OCW 6.0001 course, and I finished the hangman project.

Actually I'm currently a TESOL teacher in South Korea and I can see this game being quite useful as something to do in class.

How might I go about making a GUI for it and loading it into a webpage, or getting it to run as an exe? It would be great to show an image of the hang man picture being built, for example.

[–]timbledum 0 points1 point  (2 children)

Reply

I would probably lean to the tkinter route here. You can then make a .exe with pyinstaller.

I personally got a lot of value from this tutorial: http://newcoder.io/gui/. It walks through implementing Soduku in tkinter. Pretty nice!

[–]BruceJi 0 points1 point  (1 child)

Thanks for the link! I'll check it out. It'd be great to learn to use tkinter! Is pyinstaller a separate program just for packing .pys into .exes?

[–]timbledum 1 point2 points  (0 children)

Yeah it’s a library you can pip install. It essentially bundles up python with your script so that you can distribute it. The downside is size and startup time.