#python-discussion
1 messages · Page 399 of 1
Implication but backwards
Any other ones then?
/\ is and, \/ is or
and ⊻ is the evil twin of or, xor
any other what? binary boolean operators?
A ^ B -> C
If A and B, then C?
Yes
assuming the usual precedence rules, yes
in a parallel universe it could mean A ^ (B -> C)
You can use parentheses to change order too
A v C <- B
If B, then A or C?
/
A or C, if B
yeah though <- is rarely used
What’s NOT?
the type a -> b has |b| ^ |a| members (you have an arbitrary choice of b for each a, so its like, b*b*b*b*b)
the type (a, b) has |a| * |b| members (you choose one a and one b)
so (bool, bool) -> bool has 2 ^ (2 * 2) members, 2 ^ 4 = 16
16 binary boolops
Ngl I forgot order for the logic, can anyone give me a refresher?
Well, I assume it’s either left->right or a specific order of operations
its a specific order like with algebraic operators, some things come before other things even when written just left to right
parentheses, negation, and, or, implication, equivalence
it matches the "usual" interpretation that you'd arrive at yourself in "trivial" cases
yeah, left-to-right, but operators have different precedences (e.g. ∧ binds stronger than v iirc), but yeah, if in doubt just check the precedences again or use parentheses
like, ¬x ∨ y is obviously (¬x) ∨ y
it would be very weird for it to be otherwise
array[element=a, size=n] has |a| ^ n possible values btw so (bool, bool) -> bool ~ array[bool; 4] which is like, the truth table of that function
a function is equivalent to its truth table (assuming no side effects)
so "all possible binary boolops" are all 4-bool arrays
Hello I'm French and I don't know how to speak English too much I write through the translation app so could someone code me a small program that is a SCP library here thank you
Vibe sort: sends a request to an AI language model to sort the given array
How good is it?
only 6 of them seem to be named in a recognizable way
As almost always, the answer is: It depends
For most applications this is obviously complete garbage, but if you're sorting by some eccentric metric that's (almost) impossible to really measure, then maybe the LLM could be used to apply a score to each entry, which is then used for sorting using regular sorting methods, or if assigning each entry a separate value is too costly, then just asking it to spit out its top 10s could be helpful, but yeah... LLMs can't be 100% correct, so there will always be mistakes
what is SCP? and we dont write code for you, we can however help you so you can learn it yourself
ok
I love how you took me seriously with a question about a typically satirical sorting algorithm
I wouldn't be surprised if it has O(1/n) consistency
is it a library to coonnect over ssh?
What kind of algorithm runs faster the more items it has?
Ur ai eng?
troll?
`import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegressionx = np.array ([[25], [75], [100], [150], [200], [250], [300], [350]])
y = np.array ([250, 180, 144, 120, 100, 80, 60, 30])
y_temp = np.array ([10, 20, 40, 50, 60, 70, 80, 90])model = LinearRegression()
temp_model = LinearRegression()
model.fit(x, y)
temp_model.fit(x, y_temp)while True:
Fps_Test = input("Enter your Resolution or exit for end: ")
if Fps_Test.lower() == 'exit':
print("Bye")
break
test_resulution = int(Fps_Test)
prediction = model.predict([[test_resulution]])
temp_prediction = temp_model.predict([[test_resulution]])
if prediction[0] > 144:
print("you can play on max Graphics")
print(f"your temp is: {temp_prediction[0]:.1f}°C")
elif prediction[0] >= 80:
print("You can play on Medium to High Graphics")
print(f"your temp is: {temp_prediction[0]:.1f}°C")
elif prediction[0] >= 60:
print("You can play on Low Graphics")
print(f"your temp is: {temp_prediction[0]:.1f}°C")
else:
print("Your FPS is so low its unplayable!")
print(f"your temp is: {temp_prediction[0]:.1f}°C")`still learning spended like 30mins learning the AI things, what should i add to that AI FPS Prediction
I meant the consistency of the sort would be O(1/n) ie it gets worse at correctly sorting things the larger the input
Oh you said consistency, not time complexity
well some of them literally dont depend on atleast one of the inputs
so it would be weird to call it a "binary boolop"
like you write a something b but it doesnt use a or b
??? insane
like one of the truth tables is just [False, False, False, False] (and same with True)
those are just constants repeated 2^n times, not really operations
but lambda a, b: False exists indeed. maybe not the most useful function but a function nonetheless
That makes sense then
ok wait i need to cook
16 tables
divide by 2 for duals
8
minus 2 constants
6
6 named boolops
insane
{AND, OR, XOR, NAND, NOR, XNOR}
Has anyone heard of the app pydroid?
Depending on how you interpret the question: Most, if not all.
For example the total throughput of cycles will increase after a brief time, when the code and data is hot and already cached and when the branch predictor got to understand the program a bit.
If we want to talk about runtime per item, then this would be the case for all algorithms in linear runtime (for the reasons I said in the sentence before) or in better runtime complexities.
If we want to talk about total runtime, then maybe an accurate reverse engineering of some frequencies that were sampled at a specific Herz-rate. If you used a higher Herz-rate, and thus had more signal points to work with, decoding the real signal would be simpler (do note that I assume the lower sampled rate is below the Nyquist rate).
I was asking what algorithm has time complexity O(1/n) before realising they said consistency
you can't just divide by 2 for duals 4 of them are self dual
Which level are you?
the two projection ones and xor and its negation
Hmm android py ide
Yes
So?
i dont have a level.. i just started 30mins ago
do you have a question about it?
What are you building?
Yes I want to insert a screenshot to display in matplot lib but idk what to type
Random.randint is constant time right? As is O(1) indexing. So random.choice must be O(1) by extension
maybe start on something a bit simpler?
yeah, O(n^(-1))... not sure if that's even possible tbh
but it doesn't read like:
a if b and b if a
This makes more sense than just a if and only if a.
When you read it in english, it doesn't.
Bro pulled out the truth table xD
have you read thhe matplot libs image tutorial page? they have one in their documentation.
Isn't O(n^(-1)) identical to O(1/n)? I feel like the latter is clearer
i dont think a meaningful algorithm can get faster as the input grows
yes
I'll try
imagine an algorithm that takes no time
the empty algorithm
nop
O(0)
def f(): pass
me when call instruction handling is non 0 cycles
What's the most smallest code/way of void/pass in python?
0 probably
makes sense
it's a valid statement so it can serve as pass
the empty file
Anything that does something must be at least O(1)
Reminds me of /dev/null
right, so do nothing
So nothing is O(0), which is still constant time
Aha.... ```py
from time import sleep
n = int(input())
sleep(1/n)
print("Finished")
0 is smaller than 1
no, O(0) is not the same as O(1)
sleep(n and 1/n)
all O(0) functions are also O(1), but the reverse is not true
O(0) means no time
O(1) means constant time
__import__("pyperclip").copy("\u200b")
Oh just to avoid 1/0
!clban 1311047980551503964 upwork scam
:incoming_envelope: :ok_hand: applied ban to @queen geyser permanently.
well you can get an "algorithm" of any complexity by doing sleep(f(x)) but thats not really useful
f(x) ∈ O(f(x)) obviously, for any x0 and c=1, |f(x)| <= |f(x)| by rfl f(x) = f(x)
Awww I wanted to ping the moderators
True, yeah
I guess it could work if we assume the runtime of the function is infinite.
Then we could have a function in O(1/n) by doing e.g. this:
def generate_number(n: int):
i: int = n
while True:
yield i
i += n
the larger our input size n, the more numbers we can skip (always n at a time).
I do have to admit, that I have no clue if and how big-O notation is even defined for infinitely running functions, so...
watching lambda edit messages is like watching a slow LLM generate output
for programming if something got faster the bigger the input you'd probably just say O(1)
but in math it's much more common to see O(1/n) than O(n)
Example?
What's that
if something always gets faster the bigger the input, and computers work in discrete steps (whole number of steps), there must exist a very large input for which it takes 0 steps, so it'd be O(0) even
pyperclip is a package to interact with the clipboard buffer, copy and paste
unless my infinity exploit here #python-discussion message is actually legal
Big O notation is not exact
Wow thanks! That's pythonic
asymptotic analysis usually
like ψ(z) = ln z + O(1/z)
0 <= 1 indeed
Can you explain why this is O(1/n)?
maybe that's a bad example the series doesn't converge
0 is less than 1
I do have to admit, that I have no clue if and how big-O notation is even defined for infinitely running functions, so...
"But bricks are heavier than feathers"
because key tastes better than bread
Python REPL when typed an expression prints out its str or repr?
repr
>>> "x"
'x' # quotes are there, so its the repr of a string
repr
Cool
Makes sense
though if x is None then it doesnt print None
Racist behaviour /jk
just to not give useless output for "do something" expression-statements
None deserves a print 😢
We're respecting None's privacy
imagine
>>> print("x")
x
None
like what
Ohh makes sense
Same energy as ```py
def foo():
print("foo")
print(foo())
so vscode is rolling out a really crappy ui theme change to some people using the default theme
here's how to revert the garbage new vscode theme once it rolls out to you:
ctrl + shift + p- go to
Preferences: Color Theme - select
Dark Modernto go back to the good theming
Or just write your own IDE
not to say it isn't common to see like O(x^3), but stuff like O(1/x^3) is also pretty common
tho usage does differ, since O(x^3) is usually used for limits x -> 0, whereas in cs it's almost exclusively used for limits x -> infty
like Taylor series is another example where it's used around 0
Is there a open source ide which is too customizable and no/almost no opinionated?
emac
neovim with lazyvim
😋
lazy import vim
VSCodium
GNU Emacs was created by
Richard Stallman as the first program of the GNU Project. Development began in 1984
EMACS LITERALLY 1984
https://github.com/tomlin7/biscuit
the developer is a member of this server
Predicates python?
import matplotlib.pyplot as plt
import matplotlib.image as img
reading png image file
im = img.imread('imR.png')
show image
plt.imshow(im)
i think it is not that difficult lol
predates, yes
Vi
iV
"too customizable" only applies to emacs
its not even an IDE its a integrate-anything-into-me
Emacs is the universe set
well it's a bit questionable to agree it coming from an emac fan... What if its a conspiracy theory against other editors 
i dont use emacs btw
though i would if i knew about it before i knew about vim
i know you do 😏
I see
maybe i should switch to emacs as a fun summer project
Make a C compiler with Lisp
thats as hard as "make a C compiler"
lisp is a perfectly fine language family to use for all kinds of software
python.gram or the EBNF?
the .gram includes inline C code to generate the AST and do some checks, its what the actual cpython parser is generated from
the EBNF is for humans to read without worrying about implementation details
Since i assume it is already advanced enough for what i want to express
Oh
in source code, python.gram is actually what it uses for grammar?
Like its the only language it understands?
||I see you desire slowness||
though to be fair...a lot of modern editors are bad in that regard
By language, i mean the content used in .gram file
js isn't really doing a better job there
','.dotted_as_name+
WOw! Its like ", ".join() !
kind-of, yeah
make software great again, make native stuff in languages that provide static information for optimization
meanwhile
irb(main):001> [1, 2, 3]*'-'
=> "1-2-3"
?????? 
ruby has a lot of cursed stuff doesnt it
the kids on the internet dont hate on it because they just dont know it
That thing isn't even rubynic
js ended up being the scapegoat because the web is so big
Ruby is the greatest language of all time
Python has a lexer or tokenizer or both?
those are synonyms
Does it interchange the terms?
So it doesn't have any single difference?
nope, no difference
Like i want to pick either term and standardize it for my projects. ;-;
just pick one
Haskell
Lexer sounds cool
there you go
5 cool letters 🔥
Source code: Lib/tokenize.py
The tokenize module provides a lexical scanner for Python source code, implemented in Python. The scanner in this module returns comments as tokens as well, making it useful for implementing “pretty-printers”, including colorizers for on-screen displays.
To simplify token stream handling, all operator and delimiter tokens and Ellipsis are returned using the generic OP token type. The exact type can be determined by checking the exact_type property on the named tuple returned from tokenize.tokenize().
"provides a lexical scanner"
💀
and the docs calls it lexical analyzer i think
even they cant decide
smh
ong
🥀
Why not call it lexer or lexinizer (if that's a term)
lexinizer is not a used word
Next, the lexical analyzer uses the source characters to generate a stream of tokens.
lexer is a common term. lexiniser is a make up work, useful as a sci fci gun, pointed at some text
tokenize.tokenize() 
lexer.lex() better
lexical analyzer (also known as the tokenizer)
should be
lexical analyzer (also known as the tokenizer (also known as the lexer))
Although, is it valid under English grammar?
Lexinizer (i don't like s, isn't it british)
It's valid English word construction, yes.
Emma use it then. Thanks.
The overuse of the zed is a barbaric USAianism.
lol
you mean zee
But i find Zed cooler than Zee or S
Another.
i think -iser is a suffix that means usually means "produces"
like, <x>iser = something that produces <x>s
a tokenizer produces tokens
a lexi..nizer? lexisizer? whatever the word you'd make up, would have to produce.. lexes? what is a single "lex"? lexemes are a thing, though
Maybe because i learnt it such that my brain started liking it more over zee.
Zed is cool
Oh
Lexisizer? Lex size? Lmao
lexemiser maybe
produces lexemes (lexeme ~ token)
i agree
What's the past form of lex? I know the convention of -ed. Lexed?
lexinominator
leximification
I lex, you lex, they lex. We lexed in the past. We will lex.
She bop.
That goes hard
we will have maybe should have lexed
What is this, lex education?
Lexically speaking…..
["Lexically", "speaking", "..."]
my lexicon is very limited
like unironically i only know basic words and tech terms
and some mental speak
Lexically lexing
we are complexifying lexer lexis
comp-lex-ity
added this to my game engine cause i can
def tragic_bye_obj(obj):
print(f"[{obj}]: No! Please No!")
print(f"[{obj}]: Why would you do this???")
print(f"[{obj}]: NOOOOOOOO!")
print(f"{obj} - Lived from 0 to {timer()}")
delete("player")
a tragedy in 3|4 acts
fixed
def tragic_bye_obj(obj):
print(f"[{obj}]: No! Please No!")
print(f"[{obj}]: Why would you do this???")
print(f"[{obj}]: NOOOOOOOO!")
print(f"{obj} - Lived from 0 to {timer()}")
delete(obj)
Lexinizer or Lexier ? Which do you recommend
[player]: No! Please No!
[player]: Why would you do this???
[player]: NOOOOOOOO!
player - Lived from 0 to 0.226
lexer is the best
only lexer and tokenizer are widely recognized terms
tokenization is a term also used by NLP people
lexing would therefore be more used by pldevs i guess
ah, my spellchecker doesn't think it is a real word
Oh right
We beat spellchecker
Haha
You're so smart
😳 do not consider me a person
do not perceive
class Lexer: ...
lexer = Lexer()
lexer.lex() 😋
ok but what will .lex() return
it wont be list[Lexemes] obviously because thats big
lambder
class Luthor:
but if you do tokens then
Tokenizer::tokenize() -> list[Token]
thats 3 words from token- in a row, amazing!
Generator[Token]
That's currently how it is in my cliargparser's lexer
A λambdaBOY!!!! EVERYBODY LAUGH AT HIM!
@classmethod
def lex(cls, arguments: Iterable[str]) -> Generator[Token]:
tokens: list[Token] = tokenizer.tokenize(src)
please end me
hopefully list[Token] gets inferred
i wrote a tokenizer using pattern matching a while back
i started it
Count down....to ten...
during a pycon presentation about pattern matching when it came out
I want to rule the world
i made a cool BMDECR like array thing but i kind of forgot what all the other stuff did so its not exactly BMDECR
what is BMDECR
is that like SUBLEQ
bashicu matrix decrease basically
I also thought of it but since i needed to perform string operations onto token, i shifted to if constructs.
enabling reactions was a (good | bad) decision
it certainly was a decision, thats what i can say
rrprint("aji",RR_END)
|aji|──┼┤
-1, -2, -3... when
An idea.
the point about the pycon talk was that pattern matching is exceptionally well suited for something like this. do you want me to find the notes and share it?
i dont think match case is well suited for matching on strings
depend on how you use it
class ArgumentLexer:
END_OF_OPTIONS: Final[str] = "--"
EXPLICIT_ARGUMENT_SEPARATOR: Final[str] = "="
@classmethod
def lex(cls, arguments: Iterable[str]) -> Generator[Token]:
end_of_options = False
for argument in arguments:
if not end_of_options and argument == cls.END_OF_OPTIONS:
end_of_options = True
continue
if not end_of_options:
if argument.startswith(OptionPrefix.LONG):
prefix = OptionPrefix.LONG
body = argument.removeprefix(prefix)
name, explicit_argument = cls.extract_option_body_parts(body)
yield OptionToken(
argument=argument,
prefix=prefix,
body=body,
name=name,
explicit_argument=explicit_argument
)
continue
elif argument.startswith(OptionPrefix.SHORT):
If i had used match-case construct, it would be an abuse of Structural Pattern Matching.
Ayo what
Why would you say that? 😢
its good for matching on structures and datatypes
but matching on strings is like.. matching on concrete values
Somebody gotta do something about this
!e
from typing import NamedTuple
import re
class Token(NamedTuple):
type: str
value: str
line: int
column: int
def tokenize(code):
keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'}
token_specification = [
('NUMBER', r'\d+(\.\d*)?'), # Integer or decimal number
('ASSIGN', r':='), # Assignment operator
('END', r';'), # Statement terminator
('ID', r'[A-Za-z]+'), # Identifiers
('OP', r'[+\-*/]'), # Arithmetic operators
('NEWLINE', r'\n'), # Line endings
('SKIP', r'[ \t]+'), # Skip over space and tabs
('MISMATCH', r'.'), # Any other character
]
token_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
line_num = 1
line_start = 0
for mo in re.finditer(token_regex, code):
kind = mo.lastgroup
value = mo.group()
column = mo.start() - line_start
match kind:
case 'NUMBER':
value = float(value) if '.' in value else int(value)
case 'ID' if value in keywords:
kind = value
case 'NEWLINE':
line_start = mo.end()
line_num += 1
continue
case 'SKIP':
continue
case 'MISMATCH':
raise RuntimeError(f'{value!r} unexpected on line {line_num}')
yield Token(kind, value, line_num, column)
statements = '''
IF quality THEN
total := total + price * quality;
tax := price * 0.05;
ENDIF;
'''
for token in tokenize(statements):
print(token)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | Token(type='IF', value='IF', line=2, column=4)
002 | Token(type='ID', value='quality', line=2, column=7)
003 | Token(type='THEN', value='THEN', line=2, column=15)
004 | Token(type='ID', value='total', line=3, column=8)
005 | Token(type='ASSIGN', value=':=', line=3, column=14)
006 | Token(type='ID', value='total', line=3, column=17)
007 | Token(type='OP', value='+', line=3, column=23)
008 | Token(type='ID', value='price', line=3, column=25)
009 | Token(type='OP', value='*', line=3, column=31)
010 | Token(type='ID', value='quality', line=3, column=33)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/5HFPWXITKKRQ3ACNWL4BVKVUK4
Sure! I would love to read and learn from it.
Yeah @inland karma can we do something about the reaction spam guy please
ehh well you're not using match for the actual lexing here
Okay now that's an abuse of reaction. It was fun earlier now you're just ...
yes, where is it today?
This channel
Exactly! I had to use string methods and certainly it was rather more verbose and brought if guards in case.
@runic wharf what are you doing?
fun fact the performance of the match here could be improved by matching on the second letter only
since the set is finite and all strings are atleast of len 2 and the second letter is unique
statements = "..." — Reminds me of SQL syntax
ahh. yes you are right
Does anyone know what the reason is behind .pth files?
yes, why do you ask?
run code at startup, why not
Whats .pth? I forgot i think i have seen this extension
a [2] = a^2
by default i think its only used for editable installs to add a custom import loader
that what caused the litellm stuff to broadcast secrets
!ban 1471914282521460786 your poor judement in emojo reaction spamming telling someone to shut the fuck up and you gay and then ignoring me when im trying to call it out makes me thing you dont want to be here, so im showing you the door.
:incoming_envelope: :ok_hand: applied ban to @runic wharf permanently.
if a is a type and |a| is the number of members of this type, then |a[n]| = |a| ^ n indeed, you're choosing a value of type a n times
Does Python use such type of regex for its own identifiers? 
no thats not what im talking about . .
it is
|absolute a|
sorry, i was occupied. the mechanism of this helps you make editable installs and a few other quility to life things in building and distrobution
i dont know
its the exact same concept
it was a very clever use of advanced python features. features not many are aware of.
I didn't know such a concept was implemented at all in python.
Luckily it was only online for 4 hours
def n_at(n, arr, max_steps=100000000000):
arr = arr[:] # copy
v = 0
step = 0
print(f"Step {step}: {arr} | v = {v}")
while arr and step < max_steps:
step += 1
p = arr.pop() # take last element
# expand into n copies of (p - 1)
new_vals = [p - 1] * n
# count zeros
for x in new_vals:
if x == 0:
v += 1
# append back
arr.extend(new_vals)
# optional: remove negatives to avoid infinite loops
arr = [x for x in arr if x >= 0]
print(f"Step {step}: {arr} | v = {v}")
print("\nFinal Result:")
print("v =", v)
print("final array =", arr)
# Example
n = 5
arr = [n]
n_at(n, arr)
there are many things in python, it mostly has everything you will ever need and more! 😄
now i think about it, it allows other langs letters as identifiers which can be alphabets like english do, does it use some type of sheet of unicode or something? Or maybe unicode range points?
i wrote a pth file once when messing with an even more cursed feature, custom codecs
i use this for a very special trick when i do my own local development
there is a giant array of info about each unicode codepoint
Thanks, this is a nice discord 🙂
So it uses codepoints to determine what characters are allowed as identifiers?
i have promised multiple people to write a blog post about my little python trick/hack.. so ill do that soonish!!! 😄
all programs use codepoints to do anything with characters, computers fundamentally work with numbers
I saw lots of simple examples using regex for showing lexing and all
But i always wondered if in real programming language implementation, do we actually use regex or something more explicit and long than using regex engine?
But how python as a programming language determines what characters in identifiers (like variables, class/def names, etc.) to be allowed and what not to be allowed? Since it allows non english characters as alphabets too.
handwritten ones eventually become easier to make very specific error messages
you could modify the regex to make it work but it would become pretty gnarly
regex could be bit expensive for lexing
Yeah same intuition
str.isidentifier: https://docs.python.org/3/library/stdtypes.html#str.isidentifier
Names (identifiers and keywords): https://docs.python.org/3/reference/lexical_analysis.html#identifiers
Non-ASCII characters in names: https://docs.python.org/3/reference/lexical_analysis.html#lexical-names-nonascii
and that descibes a bunch of Unicode categories used.
Yup, that's why i always wondered if real implementation uses regex or something explicit
Thanks! Will read this
regexes are very fast
When done correctly
well its not like you can fuck up a tokenization regex, its basically always just LL(1) (as in, each character -> one path for the regex state machine to take)
unless you have a cursed language at which point you wouldnt be writing a regex in the first place
Unless they have expensive backtracking.
Do tag me whenever you post!
Tjough did I see someone mention a linear time regexp evaluator recently?
ill try to remember
Wi

hi, welcome back!
How are you doing ❤️
doing well, prepping a talk for work after the lightllm attack, some guys at work wanted to know how it worked
i didnt hear about litellm even once until the incident
therefore its a marketing campaign /hj
Lmao
i dont know who is the market for a third party thing to connect to an llm you are already paying for.
It was a funny issue tho, like in its comment, all bots were spamming and some people even advertised their rust programs i was like 😭🙏
yeah, it was very well planned
cynicism is fun't
and they did manage to get high level access from people that should know how to use the -S flag
python -S
Its a boolean flag to no
Source code: Lib/site.py
This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter’s -S option.
Importing this module normally appends site-specific paths to the module search path and adds callables, including help() to the built-in namespace. However, Python startup option -S blocks this and this module can be safely imported with no automatic modifications to the module search path or additions to the builtins. To explicitly trigger the usual site-specific additions, call the main() function...
ik it disables site module importation
But capital S doesn't rather seem to say no to import site
-no-s would have made sense
Is it a known convention to have capital X where X is a no/disable for x?
Hello
Is it a known convention to have capital X where X is a no/disable for x?
no
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x
-S : don't imply 'import site' on initialization
its "dont" in both cases here, so thats not even the pattern
Good
I don't know how to program at all, what do you guys recommend?
i see
!slorb
Here are the top free resources we recommend for people who are new to programming:
- Automate the Boring Stuff — an online book (also available to purchase as a physical book)
- Harvard’s CS50P course — video lectures (slides and notes provided) with exercises
- Python Programming MOOC 2026 course — text-based lessons with exercises
- Corey Schafer's YouTube playlist
For a full, curated list of educational resources we recommend, please see our resources page!
!slop is funnier
Hi android runtime
like i said earlier, its common to use a single char for the options and --verbose-words for the more explicit variant
Where's iphone runtime
hello
im on android 17 beta
I see.
Thank you
so the single characters can be picked arbitary, but they often are picked based on logic, like S for site and h for help
gcc does -category[no-]flag
Android, add support for python officially so i don't have to learn java or kivi/similar 😋
Example?
would anyone happen to be able to point me in the direction of a good source of info on how to downgrade to an earlier 'no longer supported' version of python?
--no-site makes more sense IMO
iirc android comes with python already
Whatt
i think
@grok is this true
-fstrict-aliasing
-fno-strict-aliasing
I don't like appending value to option
it will not sort correctly
What do you mean?
Does it support value by space?
--site and --no-site will not sort next to each other if you have both
yeah its cursed
help msg?
sure, thats one example, i was more thinking of logically even if you had them next to each other, it would not look connected until you understood both
space or tabs for indent? people have opinions and its not self evident that one is better than the other
i use spaces for values
i would never do -f=value
did you get an answer?
https://www.python.org/downloads/ has all the old versions
But without a separator, it feels ambiguous.
the -f stands for flag
in fact, if i had a tool like that, i would uninstall it
not when the rule is, the value comes after, then its never ambigous
option=value is used when the value has a '-' as prefix
nowadays i only see that with --, while - is for flags
--count=-4 will be required since --count -4, where -4 will be interpreted by the parser as an option
i dont mind --count=value
but the parser knows that --count has value next, so -4 will still work
it will just arguably look strange
as per my understanding, parsers look at token with startswith("--") -> long option, startswith("-") -> short option
But -4 isn't really an option, if your option optionally takes an argument then its ambiguous for the parser to determine whether the next token with a - prefix is an option token or value for this option
its your job to make the rules you are going to use
Real
I see.
so dont invent problems that can happen because you have not written a solution for an edge case
Hm
i do agree with @gleaming knolls comment, -X for flags, --something-verbose for values
well, my interpretation off the comment
I think i used cli programs which use short options with values too
Like -f
short options are easier to type but not so much context in their name.
Are you rolling your own rules, or replicating the getopt (and descendants) rules?
For getopt you say whether an option has an argument in the spec. So you might say (for single character options) "abc:d" meaning -a, -b, -c value, -d.
And you do the same for long options - some may expect an argument and some may not. Like --dry-run (no argument) or --count 4 (has an argument).
Not sure about rules, all of my rules are influenced/copied from other parsers. And some of them are tweaked in my implementation to keep stuff deterministic.
Right. Whereas getop and argparse et al have to honour the spec when parsing - you can't infer whether an option has an argument just from the CLI - you also need the spec.
i made a personal hacky thing in xonsh btw, tool modname loads the modname module (like import modname) and adds its main function as a callable alias (with some hacky args parsing) under name modname, and also adds all tool_<x> functions as x, and x --help does x??
so
echo.py
def main(*args: str):
print(args)
λ tool echo
Loaded module 'echo'
Tool 'echo' provides: {'echo'}
λ echo --help
def main(*args: str):
print(*args)
λ echo 1 2
1 2
i just didnt like that source-ing has overhead, and if i just import then i need to call it as a function which is more to type than a cli call
Purely for single letter options (to keep the example small), a getopt spec of abc:d means abc are single letter options and c is a single letter with an arguments.
In turn meaning:
-a -b sets a and b
-ab set a and b
-abc sets a and b and expects a following argument for c
-c 4 is c with argument 4
-c4 is also c with argument 4
-c a is c with argument a
-ca is also c with argument a
None of this is ambiguous if you have the spec to hand during the parse.
i made the dumbest mistake ever
Unlikely.
reading from a nullptr
--count -4
If option count in spec is defined as optionally-argument taking, then how would you determine the next token-4is supposed to be its value or not?
--text -prefix
2) lets say --text is argument taking, required, but how would parser determine whether -prefix is a value for --text or another option (may or may not be defined in spec) or the user mistakenly typed it? It has to make guesses.

i was trying to read from a nullptr
java.lang.NullPointerException
which in turn caused a segfault
Hmmh is there an .py TLD?
That's where option=value comes handy 😋
yes there is
https://en.wikipedia.org/wiki/.py
paraguay
Do they sell or nah?
yes
hm
but theyre very expensive iirc
getopt doesn't support "optionally argument taking". There's always either no argument expected, or an argument required. With short or long options.
Things like argparse may support more elaborate things.
!rule advert
lmfao
and why exactly are you advertising by spamming in discord if you're making 3k a day
Not available in porkbun...
Just tell the scam straight up instead
<@&831776746206265384> ^^
dm me
Do you have a wall of knowledge?
Yeah, agreed.
Although i disallow argument-taking option in short option group. They can be technically allowed at end of the short option group and must be optionally-taking-argument, but i find short option groups to be just limited as a non argument taking better
lets see if youre all bark
Where’s the link to your $4,000 course
i see. i am into the argparse category.
!cleanban 1484472050738266226 scam
if --text has a required argument, then when you see --text you know you need to take the next token and interpret it as an argument
while idx < len(tokens):
if tokens[idx] == "--text":
idx += 1
arg = tokens[idx]
:incoming_envelope: :ok_hand: applied ban to @arctic monolith permanently.
Fair. I only use getopt in my CLIs.
Computing is so messy :(
dude why
i was about to get 3k a day
Awww there is no raw .py, only .com.py, .edu.py, etc
But what if user mistakenly forgot to provide it and next token is a legit option but got eatten as an value for text?
Tough
Bad luck for the user.
"what if user pressed nuke instead of not nuke"
well you gotta press the right thing to do the right thing
Things might look tidy but under the hood they’re all so messy and held together with the most complicated code ever
And the resulting namespace will not be good.
My computer always does exactly what I tell it to do but sometimes I have
trouble finding out what it was that I told it to do.
- Dick Wexelblat rlw@ida.org
At least nukes are protected by the secret code ||000000||
Validate the input?
--text --parse-mode HTML
Suppose both can be real text or option
Only = can save here
Hopefully the argument validation will not like the option-consumed-as-an-argument.
How convert 0 to 0000 and 14 to 0014 and such
Pad zeroes at the left, done
Fstrings have this build in
f-strings support paddded formatting
Programming really isn’t smart is it 😭 it’s just hiding the confusing things (it is smart but it’s not simple)
>>> x = 99
>>> print(f'{x:04d}')
0099
If we follow this:
--text="--parse-mode HTML"
Parser will deterministically easily know that this is supposed argument for --text
--text --parse-mode HTML
here it will raise error for not providing argument for --text and will interpret --parse-mode (next token) as a legit option (regardless of being defined or not in spec)
Thank you :) :04d ?
You can even omit the d
What’s this meansung yeah
The 0 means 0 padding. No 0 means space padding.
Aye, old printf habits.
lol thanks , Id already figured it out. I was being dumb and kept getting myself directed to the page about the version rather than the actual download. I appreciate the response a bunch though!
U should learn string formatting
Too much to learn, not enough mental capacity to learn it
take your time
stands for "decimal" - which specified that x is an integer
What do you mean?
Read the spec (above). Learn the things you commonly use, and look things up when you need something uncommon.
Far too stressed about everything and overwhelmed with what I have to learn, so I can’t learn things because all my time is spent stressing about it haha
decimal
And it still can, like str. Its rather a silent bug if i am not wrong
thanks
i unironically use printf in c++
because include iostream adds too much compile time
stupid overly complex template meta programming STL shit
For something like --text, yeah not much validation there.
If it had been --format you might have only accepted valid format names or something.
I was confused because I would assume that if it meant decimal, it’d be for floats
f is for floats
We mean decimal to mean "base 10".
Not "things with a decimal point".
decimal (10), hexadecimal (16), octal (8), binary (2)
Ohhhh
given that d is the format char for decimal
the format char for hex is!!! obviously!!
x. not h. yes
of course
that’s silly
!xkcd quartz
Yeah and also the parser will then raise an error on HTML since it was supposed to be a value of --format (which got eaten by --text). Or HTML could be taken as an operand and may/maynot error later
.xkcd 2501
petition to allow non-staff .xkcd in #python-discussion
sign with a lemon
.xkcd 2501
Hello
I would rather fail fast than be sorry later lmao users gotta learn down some rules xD
there are like 10 xkcd comics
How can I start teaching python
The #2501 above suggests otherwise.
this rabbit is not human bro
Same. Why should I type
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setfill('0') << std::setw(4) << 44;
}
```when
```cpp
#include <cstdio>
int main() {
std::printf("%04d", 44);
}
```does the job.
Plus with the `iomanip` you're never sure if the change is sticky or not (because `std::setw` isn't sticky, when all others are iirc)... it's so annoying
Help people here.
teaching or learning?
Learning
No, it's fine. You have a read audience of people seeking help here, who want teaching.
!learn
Here are the top free resources we recommend for people who are new to programming:
- Automate the Boring Stuff — an online book (also available to purchase as a physical book)
- Harvard’s CS50P course — video lectures (slides and notes provided) with exercises
- Python Programming MOOC 2026 course — text-based lessons with exercises
- Corey Schafer's YouTube playlist
For a full, curated list of educational resources we recommend, please see our resources page!
yes, you're right
you already got somewhat of an answer in #ot0-psvm’s-eternal-disapproval
basically pick any of those 4 amazing resources, work through them, and when you have questions - ask here
I have the book "xkcd volume #0" on a bookshelf right here
Chat, do you believe what i am doing is correct or incorrect. 😔 I don't want to think later that i picked wrong decision.
This tutorial is good or bad
I hope there is a 0th xkcd
why would we recommend bad tutorials
Are we enemies or what.
i must say that learning is supposed to be hard even with a good resource
its 99% your effort and 1% resource effort
I think provided your parser is rigorous and predictable, and the usage message for your CLI is nice and clear you'll be fine.
np, glad you figured it out. 🙂
Idk
I see. Thanks.
(My English is probably bad sorry)
Some tutorials are better suited to some people and not others. Find one you fin approachable.
np, many people here with English as a second language.
its fine i think, atleast all messages so far have been easily understandable
what made you interested in python?
Mine too, and it's the only language I know.
Oh
English is hard. Python's english is way easier.
You've been doing a good pretence at Python then.
💀
I want to understand python because I want to work in cyber security
nah, I just write perl and then have chatgpt translate to python
(for those that don't read snark, this was a joke....)
guys how do i install pyautogui?
As if perl can be "translated" to anything else 🙂
open a terminal, then
py -m pip install pyautogui
[assuming windows]
ty
windows doesn't put pip as a command? 
only if you add python/scripts to PATH
I'll continue to maintain that perl can be well written, perl is a fine language, it's perl developers that are horrible. 🙂
File "c:\Users\*\Desktop\*.py", line 1, in <module> import pyautogui ModuleNotFoundError: No module named 'pyautogui'
althogh installed it :/
Oh
Another reason why to pick Linux
It's almost always the wrong thing to do, on Windows or others.
The py -m pip (or python -m pip on POSIXy things) runs pip for that particular python. Which often matters.
if you did py -m pip install pyautogui, then py thing.py should work
you can probably do py -m pip if pip doesn't work for you.
it doesnt-
are you sure you are running the code with py thing.py, not some magical run button in vscode?
Yes
yep
I just use python and pip at command level. Default common version which i generally use
If i want to target specific version i put that as a suffix on name
python3.12/13/14 pip3.12/13/14
and now
No module named 'win32gui'
wdym "now"? what did you do that changed it?
did you set up a venv yet?
you don't have to, but it will certainly make things smoother for you
it always had it but it didnt tell me
You need to win 32gui
im not sure what non-sus program would use win32gui directly rather than as a transitive dependency which would've been installed with the library itself
Winning someone's heart isn't that easy
tryna make a popup thingy
You gotta be first romantic
And that too 32!
are you using win32gui in your code directly? if so, why?
there are plenty of gui libraries for python
well which ones
tk is pretty straight forward, but there are lots of options depending on what you're doing
pyautogui
tkinter.messagebox is in the standard library
lots of toptions - the bad english in question
i was also trying to minimize all windows
where can i learn python please
for no reason
!learn
Here are the top free resources we recommend for people who are new to programming:
- Automate the Boring Stuff — an online book (also available to purchase as a physical book)
- Harvard’s CS50P course — video lectures (slides and notes provided) with exercises
- Python Programming MOOC 2026 course — text-based lessons with exercises
- Corey Schafer's YouTube playlist
For a full, curated list of educational resources we recommend, please see our resources page!
ok i got it working
I quite unfortunately never really learned to type properly so I still look at my keyboard while typing. And as I type fast, and if I'm not wearing reading glasses it results in a ton of dumb typos. And then on top of that you add "thinkos" where I will type "write" vs "right" or get a "they're" wrong and I end up editing most of the crap I type.
I'm amazed that I exist in a profession where typing a single character wrong will break your code.
😢
Lol I'm still basically a two finger typer and I've been a software dev for over a decade. It happens
Sometimes my brain has already moved on to the next word while my fingers are still typing the previous one. 🙂
Same
I brain even merged the with with -> withe automatically
For no reasons, probably because of th of with matching with the.
Anyone see that thing on reddit about reading 900wpm ? I had no problem keeping up with that. But typing? I go tto fast and make mistakes. 🙂
I used these at some point (~500 bucks), ended up not using it ...
Really difficult to get used to
Gloves?
Power gloves?
But they were very ergonomic. Glove80 they're called
That ain't look like a keyboard
The cool thing is that you can use both your thumbs for more than just space
I used this. It was actually great for increasing typing speed. It forced good habits.
But it was terrible for gaming.
If you train with it, you can be very fast with it. especially all the special chars like brackets and parentheses and stuff
Yeah, it's not for gaming haha
wasd is all messed up
Can anyone tell me when we need to use data types ?
Glitching keyboard 😂
And while it did increase my typing speed (it even helped my speed on regular keyboards) it also kinda sucked having to swap from that to my laptop keyboard. The context switching was terrible.
What do you mean "use datatypes"?
Yeah, agreed
I bought them in my vim phase 😛
Like tuple list set and so on
Well which specifical;ly do you want to know. Why do you think you should use only 1?
When they are useful in the code
I got mine in the 90s. It even came with a foot pedal you could use for shift or whatever you wanted.
Jeez, that's hardcore haha
I mean, they all have their benefits. Sets have a quick look-up, so if you want to check if a collection contains an item, set is much better than list f.e.
Almost every code will use data. Your question implies you haven't coded much, could you clear up what you're looking for?
tuples are nice when you are working with something you don't want to mutate, etc.
That’s insane, I want to try it but I also want a regular Ortholinear keyboard
Tuples are the worst
tuples are the best
Data types I've learned them but I don't know when to use them in a real code scenario
Dicts are the best
Everyone uses tuples for returning more than 1 value from a function, so you probably like tuples for that ;P
I don’t really know where to use tuples
Wait that’s okay to do???
The 2 major perks were keys were lined up vertically that made going to the next keys easier, and the keys were at a curved depth that meant keys were naturally a "more correct" and consistent distance from your fingers.
if you do return x, y that's a tuple
Any time you store a variable you will be storing something of a data type.
It feels like a PySin
you dont "store variables" in python, you make.. variables refer to values
its more like "every value has a type", and "types define the behavior of values when used in operations"
- That’s Ortholinear :D
- That actually sounds super helpful
None
How expensive was it?
what is sinful is doing return(x, y)
Ah okay.
I cannot say enough about the comfort of a concave linear key-well.
I suppose the third perk was the split nature of the keyboard that made it harder for your dominant hand to type keys that your other hand should have been typing. But that's probable true on all split keyboards.
I’ve only ever used regular typewriter keyboards >:(
Ortholinear is the only way keyboards should be, no more of this offset
and dvorak or something right?
I think the offset is cute. Ortholinear ones have no character
How does Python work though if the interpreter can't store the values of variables for later? Can you explain? @gleaming knoll
python stores objects, variables are just references to them
use py -m pip, not pip
I am learning to use a modern layout called “Canary”, before then I was learning Colemak
ok
I’m not a big fan of Dvorak tbh
but i wanna do pip install
so do py -m pip install
oo ok
You assign a value to a name, or a name to a value?
says [Errno 2] No such file or directory
assign x to y <-> y = x
assign 5 to my_number
assign my_number to 5
Yeah you assign a value to a name, the latter feels wrong
What
I've heard of colemark, but not canary, make sure to report back how it goes. 🙂
hm
Also 5 doesn’t store my_number
but my_number stores 5
Also why some are called Canary,others Nightly and others Unstable?
Is that the full error output? What else does it say?
I think Canary is great, but will be dreadful for relearning vim motions :P
good thing I don’t really know my vim motions yet 😭
thats it
emacs ftw. 🙂
what exact command did you write to get this error
and i dont think this is the full error
basically you should provide more info for us to be able to help
I will try out emacs some day once I know how to use vim
wait nvm i fixed it
Anything is better than nano though
Like the latest (but not stable) version of something
FAFO
thats like a queue
but not
more accurately, python stores 5 as an object, and lets you make any number of variables that reference it. You can edit or change what the references look at, but the 5 itself is immutable.
FILO
Speak English bruh
хорошо
oops thats russian 😭 my stupid ass
FIDO (First In, Dog Out)
For numbers like 5, does Python not already store them?
even ed?
it does but x = 5 is still referring to the PyLongObject{5}, its not the 5 itself
emacs is like regex, you can get a lot of utility out of learning 15 mins worth of stuff, but the remaining complexity can be overwhelming if you try to learn it all at once.
In python,everything is a Object
Nerd ahh
Functions are actually static methods of global
I mean that if it’s something like x = 39589284, then Python stores a new object
But 5 already exists, doesn’t it?
the version of python that most people use actually caches some numbers because of how common they are, but that doesn't change the underlying way python stores all data.
In elixir isn't quite like that
Use notepad atp
Is it alright to say the n word on here I’m black btw it’s part of my lingo
hmm, won't constants also get inlined?
??????
Uh...no. Don't do that
what exactly do you mean by that
constants are created once in the co_consts of the code object they are in, yes, so running the code only makes a new reference to them each time, its not allocating a new integer for that constant
With the ‘a’
#rules x2
Still a modified slur
Damn
read the #rules and follow them, or the <@&831776746206265384> will help you out.
yes, essentially
Y’all are really going to censor a black man
well yea
Your race doesn't determine your eligibility to follow the rules here.
Are you going to follow the rules or no?
idk I mean, coming from a fellow afro-american I think it's cool
it's just dialect 🤷
!warn 1321076256955043881 No, its an instant ban. and I don't know why you'd ask in a Python-discussion channel.
:incoming_envelope: :ok_hand: applied warning to @mossy sigil.
Alright, I have a website that needs coding, and a dungeon that needs crawling, see you all later!
Why am I being warned
I didn’t even say it
Vibe code
wtf
Vibe crawl
I guess
careful bro, f in wtf is a swear!!1!!1
@mossy sigil send a message to <@&714562188236423278> if you have any questions. You'll be muted if this continues.
I’m here to make friends tf are you on about
You are definitely allowed to do that.
lowkey why was he warned though
I didn’t do nothing I even asked before I said anything to make sure it was ok
Y’all are racist asf
I warned you that dropping the N word is not permitted. That's literally a warning.
Dialect varies in cultures, in Brazil we use the word gringo as anyone who isn't brazillian, but some people take the same word as a bad way so better just avoid
And if you continue with this off topic nonsense, you will be removed. If you'd like to discuss with the moderation team, dm ModMail
as a fellow wigga i think it is also tuff
you gonna warn this guy too Bobby?
!mute 1482215019771855061
That's fine. But experience here suggests that "pip" doesn't always get the same python as intended (often on Windows?), so we generally recommend using pip via python -m pip, adjusting python to be the specific python you intend, as you already do.
:incoming_envelope: :ok_hand: applied timeout to @chrome night until <t:1774568906:f> (1 hour).
He’s just said it
Saying we're racist when Asking permission to say a racist slur? That's hypocrisy
so python
In before the ban storm
Let's come back to python
.topic
nah justice for @chrome night, ts takes guts fr
!mute 846498827238506499 I don't know why you feel need to antagonize while we're trying to deal with this. So take a break.
:incoming_envelope: :ok_hand: applied timeout to @sharp hemlock until <t:1774568947:f> (1 hour).
Fluent python
But I’m asking permission I didn’t out right say it y’all are fake asl
native python when
are there native python speakers?
!mute 1321076256955043881 1d take a break and come back when you want to talk about Python
:incoming_envelope: :ok_hand: applied timeout to @mossy sigil until <t:1774651777:f> (1 day).
i already expressed the idea of a latin native kid whose parents would teach them latin as the first language
what if same thing but with python
well
python is not really a proper spoken language but
How do you speak Python
What's your favorite Python related book?
So, Anyway...: A Memoir
by John Cleese
sss hisss hsss ssss 🐍
print("Like this!")
How do you pronounce “(x:int):”
x of type int
maybe
rhymes with belgium
That’s just English then
echo "hello"```
The python book that I tried to read was telling me to use turtle
well yeah
a certain subset of english
I heard a rumour that the python repo got hacked and that all api keys e.g. pip related keys were exposed - is that true? Should I be concerned?
It's True , I heard from theprimetime.
how to make your child hate you 101
Turtle is not bad for training, it's not something you'll use outside of education though.
oh dear - IG time to update my keys then
Not the python repo though
the litellm repo
so if you used litellm (even transitively) then yes you should do something
It's an AI company repo litellm which was hacked.
Python library
Wasnt it a python package?
oh I don't care about that
Iirc Trivy was hacked and any CI/CD that had their thing got env credentials stolen, one of them being LiteLLM which had their Pypi credentials in GitHub actions
Yes , but if you aren't using that library you shouldn't be worried.
yeah so basically lk I don't care!!!
Can it hack other libraries?
Like that one npm worm
Thanks for the clarification
Yes. LiteLLM. If you don't use that you're fine.
its a package, but afaiu, the issue came through the maintainer's github being hacked and malicious changes being pushed to the repo
* no
Basically from how I understand,
if any library you download has code "import litellm" you can be hacked. If not you're safe.
.
And I don't think any Major libraries has this line.
Or if a tool you use has it
The root cause of it was an earlier compromise of Trivy pretty sure https://www.microsoft.com/en-us/security/blog/2026/03/24/detecting-investigating-defending-against-trivy-supply-chain-compromise/
ok thanks
Yes
Good timezone
No offence but given the situ I'm wary about clicking that link

I'm wondering isn't there ever a case of a legitimate developer getting greedy and pushing malicious code to a repo to hack everyone?
.
Feels like incentives are too high for popular tools.
.
Imagine getting access to millions of machines.
oh well, the maintainer's account has been compromised indeed, but the malicious stuff was specifically added in pypi releases
like the xz hack?
There has been a few, node-ipc is perhaps the most notable.
Most people don't think of becoming a cybercriminal tbh
oh, "legitimate" yeah I dont know of one
though that wasn't for being greedy per se, moreso hacktivism
hacktoberfest???
Oh its a platform drama i see
What's the supply chain fix to this tho? Why isn't the build artifact signed on the GitHub side at build time or something?
I think legit developers know how high the odds are of them getting caught so they don't try
yeah thats what i thought first too, surely the pypi releases must only be valid by being built from the repo's CI
Jia Tan
i feel bad for October. 
yeah that wasn't a real person tho
It seems worse on Windows, but I do this as a general thing myself.
I see
Imagine you take a good amount of time to craft a backdoor and someone discovers it bc ssh was taking 200ms longer
That was the comment I saw on linkedin about this, it's not an "ai problem" it's a supply chain issue and should be handled better.
i dont remember the last time i saw an attack that wasnt supply chain
maybe its the only ones i remember
All points into social engineering but none in malware
Literal ragebait for the nation state
Historically most of the more famous "hackers" have been social engineers and not programmers. (morris worm aside)
guys whats the import to make my bot do math?
what kind of math?
Uhhhhh
Isn't that built in?
#include <math.h>
i meant the thing at the top of the code
do you want to support arbitrary nested expressions, or just have a command per operation?
/calculate
command yes
you should learn about parsing expressions, its fun and useful
do not use a library right away - it robs you from learning
You probably should not be using pyautogui if you don't understand that math is built into python. You might want to take a basic tutorial first as you might be missing a lot of the fundamentals at this point.
Some people are good in such things and arent in others
mb chat
This might help: https://www.pythoncheatsheet.org/cheatsheet/basics
It's based on the automate the boring stuff book.
It's not perfect, but it might answer a lot of your questions.
thanks!
i think they know about math operators, they are writing a discord bot and want an /eval command essentially
Hi is it possible to use adjaceny matrix, for a directed traversal graph as the backbone of a text base adventure game? like a network of decisions?
My idea for a project, is the player is really interacting with matrix network, then that network produces the content, per the node and edges.
Is this a real thing?
I started Uni, and learned about graph theory, and wanted to implement it in my python game project
There's import math for things like trigonometric functions and other things (NaN et al). But basic arithmetic is part of python: 3 + 4 and so forth.
Sonds interesting, have you looked at networkx ?
wuw, interesting..
I have been in a bubble of knowledge, I'm only realising how much I really don't know, and have not explored
20 years from now you will know a LOT more, and finally have a good idea of how little you know. 🙂
You're doing great keep exploring and having fun.
Should I use one file to save data for everything in my bot data. Or use seperate files for different things, like warnings, prefrences, etc.
I discovered this at uni: the more you known, the larger the periphery of your knowledge and therefore the more you know that you don't know. I grumped about how it seems impossible to learn everything to a professor. They said something encouraging to me.
Start with one file.
Alr
Typically for a game like that you will have a graph, but you won't actually use a graph or graph like data structure, it'll be more of a virtual representation, like "I have this map area" stored in a database and it'll store all of it's connections tother map areas. So you in effect have a graph, but it's really just data stored in a database.
Depends on how much data. If you have a lot of data then use a database
Are we talking configuration data?
Alot.. Alot.
solid advice.
yes use a database don't use files
Yes. And alot of stuff more.
Whats a good way to use a database..?
Your idea of a lot might be smaller than you think.
Configuration can be in files. JSON, YAML, whatever floats your boat there are a lot of approaches. Actual data should be in a database
Start with sqlite, it's supplied with python, stored the db in a single file (i.e. no db server required).
im so confused guys, I'm trying to find the dot product between two latitude and longitude coordinates
i first convert them into cartesian coordinates but im struglling for the dot stuff
i'm in a beautiful predicament right now in which my code, unchanged, will sometimes run, but sometimes claim there's a syntax error on line 171, 173, or 175
Exactly what I want to demonstrate, as if it was a much bigger game, the network would be huge, thus be a lot more useful to have a graph/matrix
I would recommend sqlite
i am assuming there is something wrong with the port of python i'm running, otherwise this should never happen right? lol
Syntax errors require the code to change.
You might use a graph for the paths to represent optimal pathing from one location to another.
that's what i'm saying
You should show the full error.
The dot product?
want to share lines 165-180 ?
Yea
oh man, i can't copy text out of this terminal so i'd need a second
thank you for suggesting :))
Really? That's unfortunate.
but i literally press the run button twice and the first time it says
File "<stdin>", line 173
SyntaxError: invalid syntax
and the second time it says
File "<stdin>", line 175
SyntaxError: invalid syntax
Normally this includes snipptes of code as well.
yeah it does not
do you know how to calculate the dot product of two vectors by hand?
Another idea is graph theory x rubiks cube
again i'm assuming this is an issue with the port or with my board because it's absolutely never supposed to happen
I withdrawn this statement, it's clearly false.
Traceback (most recent call last):
File "<frozen runpy>", line 189, in _run_module_as_main
File "<frozen runpy>", line 159, in _get_module_details
File "<frozen importlib._bootstrap_external>", line 1160, in get_code
File "<frozen importlib._bootstrap_external>", line 1090, in source_to_code
File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
File "/Users/cameron/hg/css-pilfer/lib/python/cs/app/pilfer/print.py", line 201
)))
^
SyntaxError: closing parenthesis ')' does not match opening parenthesis '[' on line 191
Please show the code.
sure
Ah
im gonna do it on paper, and then do ito n code
sounds like a plan
you know we have libraries that do that. this is a previously solved problem.
Hey @spark canyon!
Add a py after the three backticks.
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
code expunged, ultimately was irrelevant to issue
This seems syntacticly correct. Sure the file has been saved?
oh.. i ended up doing it manually
def dot(self, Coord):
AB = self.X * Coord.X + self.Y * Coord.Y + self.Z * Coord.Z
theta = AB / (EARTH_RADIUS ** 2)
return math.acos(theta)
when using
import aiosqlite
why is the aiosqlite underlined red
yeah
do you have it installed?
again, the weird thing isn't just that it thinks there's a syntax error, it's that it only thinks so sometimes
Maybe it is misspelled or not present in the python which your linter is consulting.
What aiosqlite instead of the supplied sqlite module?
i'm just pressing the run button in the ide
How do I install it?
the same way you install other packages, with pip
Then yes it is installed.
In a venv? Your linter might be looking at the wrong python?
Maybe I should restart VSC
I would hope that doesn't help 🙁
But I gather that for whatever reason, the python you choose for vscode (pick interpreter) is distinct from the python pylance looks at, and both need configuring. Super annoying. I gather.
generally speaking, it's better to find and use publicly available code which lots of people are using than to do it yourself
Unless you want to learn.
not to criticize you, just sayin
Gotcha, i got the conversion online idk why i thought that it wouldnt exist
yeah 100% true
Could you be running another file? Or running this file before it is saved?
I just like pointing that out whenever I can because it's something beginners should know
welp i now understand the dot product WAY better plus i have a cool method
Hi chat
no, i don't think so
any vscode users how can i import a class from another file in my folder?
i think none of the other files in this folder are longer than maybe 100 lines
ModuleNotFoundError: No module named 'RwyThresholdGuard'
Use neovim
plus, the other files in this folder actually work regularly
In another window, list/show the content of the file from outside your editor. See if it's different.
Also, check that vscode (is it vscode?) is running the file you expect it to run.
put something in help channel and I can help you
Also importing python files isnt a vscode unique thing
time to read 2000 lines of code and make sure nothing is wrong 😃
it's not vscode, it's arduino lab
Ok. but the same suggestions apply 🙂
couldn't you do that while you're making the code
Not sure how back this chat comment is so apologies if I missed the boat but I just want to say this...
IMHO if you're able to say 'I don't know' no matter how senior you become, you will retain your ability to learn and your honesty with your peers.
If you ever find you cannot do so then you perhaps have reached your level of incompetence.
well, not really. the run button here should always send the code currently open to the microcontroller regardless of if it's saved or has the right filename
Ah, it's delivering the code to the arduino box?
wasnt rlly paying attention to my english (python)
Is it possible the transfer is unreliable? Seems unlikely.
you should put it on github
me?
that actually would make a lot of sense. i can transfer the file properly and see if it's more consistent that way
Worth a try.
When you press "run", how does the esp32 get it? Is it "typed" to some kind of terminal (hence the "stdin")? Rather than being transferred "as a file" and then directly run like "python the-tranferred-file.py".
I know nothing about esp32 devices.
i think it's sending over the terminal yea
im not an open source guy
fair ig
It can be possible to "send too fast", either actually overrunning the serial through some setup mismatch, or overflowing the terminal buffer of whatever receives.
🤫 my code is my code
ok yeah that worked. Sigh
Ok. I'd say "your file is too big to just type to the receiving thing".
right
Is there any scope for putting a slight delay in the seending of each line? Eg send line of code, delay 0.1s, repeat?
maybe if i could get it to talk at a different speed it might get more consistent
A slower speed.
but this ide does not have many such options
Surely you can set the serial line speed and other parameters (parity, stop bits etc)
Of course the esp32 has to match
does a json file make a good data base 💀
