Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
boofhead
Feb 18, 2021

+n'thing the "learn docker" thing, you'll likely be asked to share your code challenges via docker and if you're still learning that as you're doing the challenge, you won't have a great time of it. I.e. me, wednesday evening, the night before the code challenge is due, staring at a "entrypoint.sh file or folder not found" error for the millionth time while trying to build with docker compose to share to dockerhub when everything had been working perfectly fine on my local machine up til that point. I'd been using the docker files locally just fine and I naively assumed that it would then just continue working, but uh.. nope

whoops

Adbot
ADBOT LOVES YOU

boofhead
Feb 18, 2021

CarForumPoster posted:

:psyduck: I can’t imagine why anyone would ever need to screenshot code

Like…every communication platform supports code markdown blocks

Screenshots are old news. I take a scrolling video with my phone using full filters so that nobody can steal my awesome code. You might laugh but do you know how many people copy my code? That's right, none

boofhead
Feb 18, 2021

Re: comments

I tend to comment too much, but everybody has their own styles and I find it's easier to skip over what's there rather than scratch your head at what isn't.

To that end I like writing my plan for what needs to happen in VERY broad pseudocode, almost like a sort of TODO list, and filling out each point as I start coding. Afterwards I remove the comments that are now made self-explanatory by the code, or update/clarify the ones that might have confusing code following it, to provide some context

It's probably excessive but at least then you have the extra layer of "ah, here's what they WANTED to do, versus what they ACTUALLY did", and you can always tidy it up later.. but adding comments to code you didn't write and/or don't remember is pretty rough and will waste a lot of time later on

boofhead
Feb 18, 2021

former glory posted:

Mind expanding on this or pointing to some supporting sources? This is something I feel is right in my bones, but my formal education was all Java back in the early 2000s and everything back then was subclasses out the rear end, getters and setters, encapsulation above all. I didn’t write much code between 2008-2020 and coming back to it now, it seems like a lot of that was thrown out the window, especially in Python.

I would also be curious to read some material on this.. is the idea to use mixins rather than subclassing ad nauseam? Personally I don't subclass a huge amount but I feel like I've see a lot of people aggressively using it

boofhead
Feb 18, 2021

this might be ugly or have weird edge cases (something to do with modules and period-separated namespaced exceptions? cant remember, might be confusing it with something else), but i'd probably either use isinstance(e, SomeException) (if you want to catch subclasses as well) or type(e).__name__ == 'SomeException' if you need to be precise

exceptions:

code:
class SightException(Exception):
	pass

class SmellException(Exception):
	pass

class HalitosisException(SmellException):
	# subclass
	pass
with isinstance

code:
try:
	try_to_flirt()
except Exception as e:
	log_to_db('failed to flirt')
	if isinstance(e, SightException):
		comb_hair()
	elif isinstance(e, SmellException):  # will also catch subclasses, e.g. HalitosisException !
		shower()
		brush_teeth()
	elif isinstance(e, HalitosisException):  # will never trigger due to above !
		brush_teeth()
with type().__name__

code:
try:
	try_to_flirt()
except Exception as e:
	log_to_db('failed to flirt')
	if type(e).__name__ == 'SightException':
		comb_hair()
	elif type(e).__name__ == 'SmellException':  # will NOT catch subclasses
		shower()
		brush_teeth()
	elif type(e).__name__ == 'HalitosisException':  # will trigger
		brush_teeth()

boofhead fucked around with this message at 19:14 on Mar 16, 2022

boofhead
Feb 18, 2021

In their section on fair use section they mention:

quote:

Locally cache resources whenever you request them.

Which I would interpret to mean, they'd prefer requests to the API only when getting it for the first time or checking for updates, rather than being designed as a free server. they say it's an educational service so i think using it for production-level anything is probably not intended

If your estimated usage is very light then they wont even notice it but if there's the potential for a lot of calls (what if the alpha goes viral and 1 billion people start playing it! or, far more likely, there's some bug or other that just silently spams out infinite api calls and gets you banned) then it would be better if it were pointing at a cached copy of the data instead

generally i don't trust my code to point at external servers during development, even if i 100% need to be getting data externally i'll usually just set it up first to check the connection and initial data, then comment it out, mock or use a local/cached version of the data while working on everything, including error handling and try/retry/backoff limits and so forth, then re-connect it to the external api towards the end to test

e: although thinking about it, i normally work with files that are a lot bigger than what a single pokemon definition would need. might be overkill

boofhead fucked around with this message at 01:03 on Mar 26, 2022

boofhead
Feb 18, 2021

I
Phone posting so I can't tell you the whole context but where it breaks is dict["items"] then .items(), is that a legitimate field with another dict in it? Probably you just wanted dict.items()

boofhead
Feb 18, 2021

code:
File "C:\Users\nickt\CSC221\lab10\project-books\django_books\django_books\urls.py", line 19, in <module>
    from books import urls as books_urls
ImportError: cannot import name 'urls' from 'books' (C:\Users\nickt\CSC221\lab10\project-books\django_books\books\__init__.py)
take a look at the contents of these two files (the last 2 lines in your error log)

the second file is what you're trying to import stuff from, and the first file is where you're trying to import (and use) it

and the command "from books import urls" is what your code is trying to do but failing

boofhead fucked around with this message at 15:41 on Mar 31, 2022

boofhead
Feb 18, 2021

Mycroft Holmes posted:

__init__ is empty. I wasn't told to modify it, only urls.

sorry I'm a bit out of it today and was thinking of javascript index files for importing

look inside the /books/ directory (it'll contain a package) and see what it's doing. The empty __init__.py is just a placeholder file that tells python to treat the directory as a package, so you can import it and do stuff with it

so either your import line is pointing at the wrong thing (i.e. it should be: from not_books import urls) or it's trying to import the wrong thing (i.e.: from books import not_urls)

boofhead
Feb 18, 2021

Dunno how much this will help but if you throw the below example into python (an online compiler can be helpful for simple stuff) and run it, it might help you visualise what's happening when you try to loop through the index and values of an array

(edit: in the way that you've tried! Other people are very correct in saying that if you need to iterate through a list, just do it, you don't need the index for what you're doing. This post is because it looked like you might be struggling with arrays and indices in general, for eg if you've tried dabbling in JavaScript where it's a lot more common in beginner courses.. or at least it used to be)

Python code:
def split_string(text):
    text_length = len(text)
    print(f"Text: '{text}' Length: {text_length}")
    print(list(text))
    for index in range(text_length):
        character = text[index]
        print(f"Index: {index} Character: {character}")
        
split_string("butts")
split_string("Each element in an array has a positional index.")
split_string("Arrays can be different lengths.")
Sample results for butts:

Python code:
Text: 'butts' Length: 5
['b', 'u', 't', 't', 's']
Index: 0 Character: b
Index: 1 Character: u
Index: 2 Character: t
Index: 3 Character: t
Index: 4 Character: s
fe: If you want to think more about what

Python code:
for index in range(text_length)
is doing, consider:

Python code:
print(list(range(10)))

# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
(range() is a special function so you just need to convert the output into a list to display it properly)

boofhead fucked around with this message at 00:33 on Jun 25, 2022

boofhead
Feb 18, 2021

LochNessMonster posted:

I'm trying to build some pagination and I'm having some brain farts on how to do this in a pythonic way.

For this kinda stuff I just chunk it like this:

Python code:
list_to_chunk = list(range(1,101))
chunk_size = 10
chunked_list = [list_to_chunk[i:i+chunk_size] for i in range(0, len(list_to_chunk), chunk_size)]
print(chunked_list)
# [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
# ...  [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]
Then you just loop through chunked_list

boofhead
Feb 18, 2021

The raspberry pi thread could also be a good resource, I think people have done similar things with that. Might not necessarily be in python but it could be helpful as a reference

boofhead
Feb 18, 2021

fisting by many posted:

No, that works fine, maybe they just wanted to teach for loops and range rather than slices at that point.

This is absolutely the point, and worth considering. They have a syllabus and these contrived examples have been designed to help teach you concepts for that syllabus, they're not supposed to be the "objective best all-context solution" for whatever the issue is - if the premise of the issue even makes any sense at all. It's just an educational tool to get you practising whatever the week's topic is

e: I'm reminded of taking beginner (human) language classes and there was some guy I got paired with on some little "using the vocabulary provided and the grammar you know, have a conversation about what you did this weekend" task, and he refused to do it because none of the vocabulary covered what he did this weekend. A modern day George Washington

boofhead fucked around with this message at 09:24 on Jul 18, 2022

boofhead
Feb 18, 2021

Fair

Personally in a professional environment I'd just give them one of the old

Python code:
def reverse_string(value):
    import string
    deconstructed_list_comprehension_pool = []
    for i in range(0, len(value)):
        all_chars = list(string.printable)
        i_new = len(value) - i - 1
        for n in range(0, len(all_chars)):
            if all_chars[n] == value[i_new]:
                deconstructed_list_comprehension_pool.append(all_chars[n])
    reconstructed_deconstructed_list_comprehension_pool_final = [c for c in deconstructed_list_comprehension_pool]
    return ''.join(reconstructed_deconstructed_list_comprehension_pool_final)
so that boss knows im working

boofhead
Feb 18, 2021

Phone posting but

The while loop checks labs but what you're converting to a float is grade1. So labs will only ever be a string as that's the input var

And you're trying to convert the input to a float outside the try except so it doesn't have error handling on invalid inputs, that's where the error is coming from

boofhead
Feb 18, 2021

Uh.. I'm not actually sure. I mean, I'd do it differently, but I'm not sure why what you have there isn't working for you. I was curious so I tested it in plain python and it works, but I don't have Jupyter Notebook installed so can't double check there. You sure you're not accidentally re-importing params.py between runs, but missing executing the cell where you redefine it?

Sorry, I've used Jupyter Notebooks for all of a day in my life

boofhead
Feb 18, 2021

try:

code:
tweet_id = info.data['id']
Response is the class (from tweepy.client.Response) which has the properties data, includes, errors, and meta, so:

info.data
info.includes
info.errors
info.meta

and within info.data you have a dict with keys 'id' and 'text':

info.data['id']
info.data['text']

boofhead
Feb 18, 2021

e: whoops, ignore

boofhead
Feb 18, 2021

That error means you're trying to treat a list like an object

Look for sendkeys, you can see it in this line - that's what's triggering the error

code:
search.sendkeys('wake tech')
So follow that to where search is defined

code:
search = driver.find_elements(By.NAME, 'title')
Well from the name alone you can guess it'll return a list or some type of iterable, you should be either looping through the results or calling a different function that returns only one object rather than a list

Also, I didn't look too closely at the rest but there's likely the same error as well as a typo in your test wake_test() -- findelements not find_elements, and again it treats the list like an object

e: I haven't used selenium in years but in your case I'd check if there's find_element rather than find_elements since you seem relatively certain there's only going to be one result

boofhead fucked around with this message at 18:32 on Nov 14, 2022

boofhead
Feb 18, 2021

Speaking of conda, I was checking it out and wanted to fool around with spacy transformers with hunspell and i just ran into so many issues, like conda didn't have all the packages so I had to install some through pip through conda, then hunspell install fails because it can't find the C++ build tools (although I'm pretty sure I installed them, it worked through normal pip iirc). I think a big part of the problem is trying to do it in windows, I'm going to give it another go on Linux tonight, but the missing conda packages didn't inspire a huge amount of confidence.. is there a significant gap between pip and conda for supported packages? Or am I just jumping in head first and missing some rudimentary conda concepts

boofhead
Feb 18, 2021

^ That's precisely my use case, the stuff I want to play around with requires CUDA and a bunch of other non-python dependencies, and I think what was happening (even on linux, once I swapped away from windows) was the standard conda, plus conda-forge, was struggling with figuring it all out and that was resulting in some weird bugs and then just hanging / absurdly install times where it just looks like it's crashed. I found some stuff that suggested mamba, installed the solver library for that, and everything went smoothly with mamba doing the package dependency calculating stuff

I'm definitely going to use this more in future, pip winds up doing some bizarre things so I'm happy to have finally stumbled into what looks like a better way of doing things. All in all I'm just happy everything is installed and I can finally start playing around with it

boofhead
Feb 18, 2021

I just heard that our world wide website domain url is broadcasting an IP address!! Turn it off right now!!!!

boofhead
Feb 18, 2021

just to clarify, since this is also something i've been scratching my head over but never had time/energy to research properly because i am a bad developer, but:

you're saying a better implementation would be something like:

Python code:
# user.py

from app.user_group import get_user_groups

class User():
	def get_groups() -> list:
		return get_user_groups(user_id=self.id)

# group.py

from app.user_group import get_group_users

class Group():
	def get_users() -> list:
		return get_group_users(group_id=self.id)

# user_group.py

from app.user import User
from app.group import Group

def get_user_groups(user_id: int) -> list[Group]:
	# do the thing
	return groups

def get_group_users(group_id: int) -> list[User]:
	# do the thing
	return users
or to omit the class from the list type entirely? i.e.

Python code:
def get_group_users(group_id: int) -> list:

boofhead
Feb 18, 2021

ahh i always forget to use filter and all the extra QOL poo poo in python

i, too, couldnt help myself

Python code:
source_list = [5,2,7,1,4,6,3,9]

evens_in_place = [n if n % 2 == 0 else None for n in source_list]
# [None, 2, None, None, 4, 6, None, None]

odds_sorted = sorted([n for n in source_list if n % 2 != 0])
# [1, 3, 5, 7, 9]

final = [n if n else odds_sorted.pop(0) for n in evens_in_place]

final
# [1, 2, 3, 5, 4, 6, 7, 9]
e: ive never done like a live coding test beyond 5 minutes of basic SQL maybe 6 years ago for a PM position, you can still google and check documentation, right? like if you need to check syntax or a method/class name or whatever, theyre not still doing that thing where you have to commit it to memory because real programmers dont have internet access or computers and do all their work from a cave in the woods. all they need is a bucket, a gazelle carcass, and a tape recorder to dictate their commits in

boofhead fucked around with this message at 07:53 on Apr 19, 2023

boofhead
Feb 18, 2021

I think I posted in this thread when I was doing the coding challenge for my current job a couple years ago, freaking out because the key logic of the challenge was a knacksack problem that expected deterministic programming, which I never studied in my ancient history degree. I came up with some dodgy "good enough for the requirements as they stand", added some explanations for how I'd clarify the specs and actual use cases and so forth, and the only feedback I got (apart from being hired, which I guess is the main thing) is that I need to add more and better comments

And then I saw the leads/hiring devs code and i gotta say, people in glass houses buddy

e: or maybe it was in the getting a job thread, or general programming, don't remember. But it is very stressful and imposer syndrome-y, until you actually see what 99% of your actual workload in a real job is like. Then you just have imposter syndrome for "literally any job but the one I have currently", which is an improvement at least

boofhead fucked around with this message at 08:25 on Apr 19, 2023

boofhead
Feb 18, 2021

SurgicalOntologist posted:

Yours will get the wrong answer if the input list has 0 in it. :viggo:

Please create a bug report ticket and assign it to the garbage bin icon and I'll add an "if n == 0 or" before EOY

But yea I dragged myself out of bed 3 minutes previously to put on coffee and take my ADHD medication, I am surprised it even worked for the sample list without accidentally formatting my C:

boofhead
Feb 18, 2021

I'm a backend dev for a consultancy and about 80% of my workload is building unspecced ambitious new tools for internal stakeholders with infinitive complexity requirements that either get "parked indefinitely" once I ask them to test the finished product or it gets released and then immediately forgotten about and abandoned because they're already desperate for the next highest priority project that's going to 'solve everything', or people demanding I spend a month building a similarly unspecced automation pipeline to save a cumulative 4 hours of manual data entry per year, which will also get abandoned or outdated 2 weeks after it's released

And before you tell me to push back on it, my company refuses to hire product managers, I've worked as one in my last two jobs and that experience was part of the reason to hire me, except when I try to push back on "everything is highest priority all the time and needs to be developed simultaneously" nonsense or try to manage expectations or even just ask for actual requirements, my boss's boss steps in and basically demands to know why I'm being antagonistic or shirking work

So it turns out that they're happy with 80% of my work taking ages and then going straight down the drain so long as I just say "sure, I'll work on it soon" and they don't have to do any actual managing

Lol. Lmao. Just guffaws all round

On the upside, because there's literally no oversight and I work from home, there's almost zero pressure and I have a very chill working life, and they even authorised me to go down to 80% time next month (with pay cut unfortunately) and I get to teach myself a bunch of poo poo that would otherwise be impossible if my employer was any shade of competent. So it's a mixed bag

boofhead
Feb 18, 2021

Yeah having worked years ago in a schools IT department, and now as a python developer, my (still very rookie) first reaction was that this doesn't sound like something you'd do in python, it's a domain/deployment question. So something I'd have dealt with on the domain or device level rather than kludging together some weird ad hoc stuff that's just going to be a nightmare to develop, implement, and maintain

But I am also very very tired so I don't know how much I actually understand the issue at hand

boofhead
Feb 18, 2021

I did a quick search and the creator said on Reddit:

quote:

It's nextjs, react, mapping is react-simple-maps + leaflet, ui library is material-ui.


https://www.reddit.com/r/leanfire/comments/trx41p/comment/i2r18u6/

If you had any questions you could probably reach out to them, almost everybody who creates something is usually pretty ecstatic to get direct feedback and to answer questions, especially if the project hasn't become overwhelmingly popular to the point where they can't keep up with the messages

boofhead fucked around with this message at 08:47 on Jul 18, 2023

boofhead
Feb 18, 2021

yeah unless they consistently pass the value with 3 decimal places (so 1234 -> 1,234.000 or 1.234,000) you'd need either some specific flag or enough contextual data to infer which format it should use (e.g. values from this source or with this pattern of metadata are always US)

sometimes the source data is just too crap to do anything with and they gotta fix the problem before they pass the data to you

boofhead
Feb 18, 2021

QuarkJets posted:

This is a great time to mention `suppress`, I like to recommend that for bare except blocks

Python code:
from contextlib import suppress
...
...
...
success = False
while success is False:
    with suppress(DatabaseError):
        insert_into_db(index=generate_index(my_id, my_table)
        success = True

Ahh that's neat, thank you

boofhead
Feb 18, 2021

pretend i remade that "the americans spent millions of dollars inventing a pen that would work in space. the soviets used a pencil" meme but for hedge funds committing large scale financial fraud

boofhead
Feb 18, 2021

I'm not a flask/sqlalchemy person but is it possible that there already exists a table mapped to the User class (created during previous steps) called "user", and now in the latest step you're trying to tell it that the User class actually maps to an overriding table called "users" ? It looks like you added this in after already creating the table from the class:

code:
__tablename__ = 'users'
and I think flask-sqlalchemy might automatically create table names from class names by just snakecasing it, rather than automatically adding plurals. Because the error you've posted seems to suggest that there's a conflict where the 'User' class is already mapped to a table somewhere, and it's not the table specified by __tablename__

try removing the above line from the code and see if that works

boofhead
Feb 18, 2021

Yeah I am bad at windows development and setting up environments, if it's for a project I know I'll eventually want/need to dockerise it anyway so I just start with that and then use python from within the container

boofhead
Feb 18, 2021

yeah i'd just omit it and add a comment

Python code:
def repeat_text_start(text: str, num: int) -> str:
    """Returns the first 3 chars of a 'text' string repeated 'num' times."""
    # TODO! validate args, handle exceptions
    return text[:3] * num
so that they know i know it's not production-ready, but validation and exception handling is beyond the scope of the task (or ticket, if you're dealing with lazy product managers)

as far as im aware the above code wont break for any value of text or num, so long as they're strings and integers respectively. 0, -1, or an empty string should all work and just return '' (i.e. an empty string). and value[:3] will just return whatever it has if the length is less than 3

+1 for not being a fan of conditionals coming after the action, feels like a minor code smell to me

e: also you should keep an eye on your variable names, calling a string variable "str" is a bad habit to get into

boofhead fucked around with this message at 14:12 on Feb 15, 2024

boofhead
Feb 18, 2021

e: ah jeez i misread the post lmao, ignore

boofhead
Feb 18, 2021

yeah, why are you writing it like that? why not just write

Python code:
x = 'd'
y = 3

if (x == 'd' and y == 3) or (x in ['a', 'b', 'c']):
    print('right')
else:
    print('wrong')
the reason your example doesn't work the way you want it to is because combing conditions with an 'or' means that it checks if any of the conditions is True and goes down that path

and the second condition evaluates to True because x is NOT in ['a', 'b', 'c']

so what it's doing in your example is:

Python code:
# for x == 'd' and y == 3

=> not (x == ‘d’ and y == 3) or (x not in [‘a’, ‘b’, ‘c’])

=> not (True) or (True)

=> False or True
so it goes down that path every time

e: using negatives like that is absolute hell though so if i caught anybody writing code like that i would judge them forever and probably try to get them fired. out of a cannon, into a volcano

boofhead fucked around with this message at 17:24 on Feb 25, 2024

boofhead
Feb 18, 2021

Deadite posted:

I have to do it this way because these two new conditions are just an addition to a very long list of existing conditions, and at least some of them will need to be negated. I inherited this program and I can’t change how it’s structured without causing a lot of drama so I’m trying to do the best with what I have. I agree that it’s going to be a (more) confusing mess from here on out.

refactor the whole thing imo

but if you're determined to go ahead with it, this should do what you're asking

Python code:
if not ((x == 'd' and y == 3) or (x in ['a', 'b', 'c'])):
    print('wrong')
else:
    print('right')
hope that code has amazing unit tests btw

boofhead
Feb 18, 2021

Deadite posted:

Perfect, thank you. And I'm sure that team doesn't do any unit testing. I got pulled in to help out because they were running behind. At the end of the month this program will not be my problem again until an ironic reorg forces me to maintain it.

Here's a more accurate representation of the issue, but pretend there are about 20 more variables that need to be tested:

Python code:
v = 'N'
w = 'N'
x = 'a'
y = 3

if (v == 'N' or w == 'N') and (not ((x == 'd' and y == 3) or (x in ['a', 'b', 'c']))):
    print('do something')
else:
    print('do something else')

i wonder why they're running behind!

i also don't mean to take a dig at you, capitalism makes us do terrible, terrible things, code included

but you really sure you can't convince them to implement something more maintainable? pydantic or if you cant use external tools, do it in a class that's just a little cleaner? something like

Python code:
class ConditionsWrangler:
    """You have conditions? We have a wrangler."""
    v = 'N'
    w = 'N'
    x = 'd'
    y = 3

    # individual checks
    def v_or_w_is_N(self) -> bool:
        return self.v == 'N' or self.w == 'N'

    # helper checks
    def x_is_d_and_y_is_3(self) -> bool:
        return self.x == 'd' and self.y == 3
    
    def x_in_abc(self) -> bool:
        return self.x in ['a', 'b', 'c']
    
    # grouped conditions
    def x_is_valid(self) -> bool:
        return self.x_is_d_and_y_is_3() or self.x_in_abc()

    @property
    def is_valid(self) -> bool:
        return all(condition for condition in [
            self.v_or_w_is_N(),
            self.x_is_valid()
        ])

whatever = ConditionsWrangler()

if whatever.is_valid:
    print('right')
else:
    print('wrong')
i'm sure there are many better ways of doing it, but i'd still rather see the above than a long list of weird if or not and spaghetti conditions

Adbot
ADBOT LOVES YOU

boofhead
Feb 18, 2021

I'm also a big fan of

Python code:

# TODO! fix this

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply