#esoteric-python

1 messages ยท Page 143 of 1

floral meteor
#

The blur method is average of pixels within a circular radius

#

restricting that radius for red, more than green, more than blue, as is the pattern consistent with a focal point in front of the retina instead of on it.

#

The code for it is ironically the code in above screenshot

#

me: I coded something hard to read!
the code:

#

If the definition of obfuscated code is code that is deliberately hard to read, then I think putting a short-sightedness filter over the code counts, right?

severe canyon
#

pain

long hamlet
#

What is that

#

Ok will share a few moar python generated art then an esoteric pure python 2D /3D Library I made

#

That is pure python no libraries...

#

No classes all functional

#

Made my own bitmap fonts

#

Made my own graphics library from pixel addressing to 2D primitives like line , circle, etc
To 3D projection to 2D with hidden surface removal and shading

#

Made my own lin alg lib

runic mirage
#

damn

long hamlet
#

I think I promised to share this here months ago lol better late than never

runic mirage
#

also these circles up there look really cool

long hamlet
#

Can get funky

runic mirage
#

wohoo

#

how did you make these shapes?

long hamlet
#

Esoteric Math

runic mirage
#

๐Ÿ˜œ

#

The one looks like an avocado ๐Ÿฅ‘

long hamlet
#

Mix of sines and cosines then I deform

pure dew
#

oh its not actual gpu drawing? got me excited

long hamlet
#

Yes pure CPU...sorry for late reply was sleeping...

#

I created an in memory byte array that serves as a virtual video buffer that has the byte layout that matches a mono, 16 color , 256 color or RGB windows bitmap with variable size...that I made addressible with bit or byte based operations via my own pixel routine...then built up from there ....

finite blaze
#

I wonder how fast it is?

long hamlet
#

I profiled it pretty fast most operations take less than a second

#

But it isnt real time and output is to memory then file totally bypassing the GPU lol

#

Ok a full set of tests done in 5 sec

#

Outputs the test bmp shown previously in which I tried to cram in most of the features lol...has 2D and 3D

#

BTW done on a i7 laptop with a naked board I need a new one

#

I short the pins to turn it on lol

long hamlet
#

Estoteric bare board laptop computing lol

#

I can also do filters, image resize, outline etc with the library ...it is there but I havent checked in the image manipulation unit tests

long hamlet
night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

utf-8
long hamlet
#

Bare board dont overheat lol

sick hound
#

Lmao what

#

So what's dissipating the heat?

long hamlet
#

I play CIV 5 no overheat

#

Desktop fan

#

Eso hardware lol

sick hound
#

The more you tell me the more confused I am

#

What even happened there?

long hamlet
#

There is also a heat sink from an old laptop i slipped below

sick hound
#

Did someone nuke your laptop?

long hamlet
#

I did to make it useful...fan broke. Power Switch broke in middle of Covid lol

#

Macgyver

#

So i removed all broken parts and retained what is essential...Zen

split salmon
floral meteor
#

what's the domain and range of the mandelbrot fractal?

#

well, the interesting parts of it, at least

#

This is an encrypted message.

[2240738, 5573346, 1449296, 4889873, 1828324, 4274806, 4841102, 4607466, 3890048, 5126385, 420300, 2687704, 1255302, 2727331, 813057, 2034996, 1788130, 1124028, 580034, 2031250, 5514529, 5534410, 187413, 5387283, 2443965, 4789045, 70840, 323349, 327840, 4990935, 4813300, 2292617, 756145, 2113802, 2673823, 5544930, 1088033, 1619516, 4902911, 4273008, 274757, 2571054, 3443850, 3954383, 4213766, 3136367, 1315753, 139190, 3926698, 1756197, 4093664, 822713, 3623924, 4306893, 4627029, 4387294, 2417394, 4490347, 1262744, 4135132, 1758104, 3652352, 2826844, 4154119, 4203715, 2112125, 2580893, 5127401, 2909679, 2545234, 4337444, 1103112, 5212413, 3574240, 3579850, 4291504, 3940594, 4091867, 329468, 271258, 1558640, 835649, 4886917, 5344415, 3710410, 3583840, 1083078, 4851517, 1604477, 2262315, 3745322, 1071431, 3014282, 2267304, 2688016, 1744634, 2680341, 5334260, 2916342, 3207715, 198719, 2069901, 2676107, 1722937, 2795632, 1015599, 65964, 3888581, 4251997, 5054434, 301474, 5410911, 1193709, 5452445, 1031311, 2683125, 892396, 824137, 4243221, 4871888, 1232370, 4558140, 3307947, 4561688, 588931, 913729, 1131667, 2931906, 3977081, 1817868, 3134927, 4364988, 2969286, 2671041, 1937563, 495556, 1385182]
#

This is the decryption method

def generate(seed:int,key:int):return''.join([*loadbar((*map(lambda x:int(x)<<1,str(seed)),),lambda x:str(x**key))]).strip('0')
def intfuck(c:list[int]):
  a=__import__("collections").defaultdict(int)
  i=p=t=0
  def add(i):
    a[i]=(a[i]+1)%256
    return i,0
  def sub(i):
    a[i]=(a[i]-1)%256
    return i,0
  def left(i):return i-1,0
  def rite(i):return i+1,0
  def dot(i):
    print(end=chr(a[i]))
    return i,0
  def com(i):
    a[i]=ord(__import__('sys').stdin.read(1))
    return i,0
  def loop(i):
    return i,not a[i]
  def end(i):
    return i,-bool(a[i])
  while 0<=p and p<len(c):
    if t:t+=(c[p]==7)-(c[p]==8)
    else:i,t=[add,sub,left,rite,dot,com,loop,end,lambda i:(i,0)][int(''.join(map(str,range(8))).find(str(c[p]-1)))](i)
    p+=1-2*(t<0)
  return int(bool(t))
def decrypt(array:list,seed:int,key:int):
  print("generating...")
  abstract_integer = generate(seed,key)
  print("decrypting...")
  del key
  numbers = [int(abstract_integer[int(this)])for this in array]
  return[intfuck(numbers),print("decryption complete.")][0]
long hamlet
floral meteor
long hamlet
#

mandelparamdict(): return {'maxdefault':(1.75,-1.75,1.5,-1.5),'maxeqdim':(1.75,-1.75,1.75,-1.75),'middefault':(.75,-1.25,1.25,-1.25),'mindefault':(.75,-.75,.5,-.5),'mineqdim':(.5,-.5,.5,-.5),'custom1':(-.5,-.7,-.5,-.7)}

floral meteor
floral meteor
#

the os module is missing an important implementation

#

rmdir with the /s flag

#

although I guess that's to stop noobs from shooting themselves in the foot

#

but it's still annoying

long hamlet
#

Yes shooting one self in the foot is a common programmer joke

floral meteor
#

now I have to make an object s with a __rtruediv__ method that is a wrapper on an os method

#

the reason we're stuck with the walrus is just so this is invalid syntax

a = 1
while a = 1:
  if input('q to quit>')=='q':
    a = 0
#

The reason we can't

def destroy_dir(dir):
  import os
  os.rmdir(dir, recursive=True)

is rather obvious, but still annoys me

#

I'm gonna have to implement recursive

#

just for a decryption project ๐Ÿคฆ

proper vault
#

!d shutil.rmtree

night quarryBOT
#

shutil.rmtree(path, ignore_errors=False, onerror=None)```
Delete an entire directory tree; *path* must point to a directory (but not a symbolic link to a directory). If *ignore\_errors* is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by *onerror* or, if that is omitted, they raise an exception.
floral meteor
#

I already made the s object

#
@type.__call__
class s:
      def __rtruediv__(self, other):
        def inner(dir, *, _rec=0>0):
          try:other(dir)
          except NotADirectoryError as e:
            if _rec:os.remove(dir)
            else:raise e
          except OSError:
            for entry in os.listdir(dir):
              try:os.remove(entry)
              except:inner(dir+os.sep+entry,_rec=1>0)
            other(dir)
        return inner
(os.rmdir /s)("dir_name")
severe canyon
#

or, around there for shorter code :P

floral meteor
#

I prefer to round to
x in (-2, 0.5)
y in (-1, 1)

severe canyon
#

Round up rather than down then at least

floral meteor
#

I don't see anything happening on the imag axis further than 1 unit away

severe canyon
#

you do cut off

sly root
#
(as-> #@(bot.event (defn/a on_ready [] (print "Logged in as" bot.user))) on_ready
  (-> ace.events
    (.update {"on_ready" on_ready})))
(as-> #@(bot.event (defn/a on_command_error [ctx exception] (.error log exception))) on_command_error
  (-> ace.events
    (.update {"on_command_error" on_command_error})))```
#

i like this so much

#

there's no such channel for this topic so idk

sly root
sly root
sly root
sick hound
#

iโ€™m working on a bot that reads json responses and most of the responses are in jeff:jeff2 format and i want to only jeff2 part and if it doesnt have a jeff2 part so only a jeff part i want to skip ig

fleet bridge
#

What is "hy"?

restive void
sly root
#

basically just language created with ply (or sly)

quartz wave
#

i'm wondering where IFcoltransG went and why isn't he active any more

long hamlet
#

Maybe he is busy

floral meteor
severe canyon
#

yessssssssssss

long hamlet
#

Yes

floral meteor
#

I want to make a float that doesn't float.

#

but can still execute float operations

#

including complex numbers

#

only need rational floats

#

although 1/3 might be a bit difficult

#

what if I stored rational floats as exact value integer fractions?

#

but then the mathematical algorithms to apply float operations...

#

!doc fractions.Fraction

night quarryBOT
#

class fractions.Fraction(numerator=0, denominator=1)``````py

class fractions.Fraction(other_fraction)``````py

class fractions.Fraction(float)```
floral meteor
#

that's what I need

vestal thicket
#

does anyone have any advice on grabbing data from output of cli tools like xrandr and xinput that is more approachable than using basic string manipulation and line reading techniques?

#

i'll give you an example of the kind of thing i'm fucking sick of having to write at this point

#

like, spending an entire afternoon just writing sections of code like that is torture

floral meteor
#

there comes a point where pep8 makes things harder to read, and I think you found that point

#

you use imports for a cli?

#

you use tools?

#

bro I have minesweeper where the only tools I use are msvcrt.kbhit and msvcrt.getch and random.choice and time.time. Maybe itertools.product.

#

and all of those I make fit into my design, not the other way around.

#

you do mean command line interface when you say cli, right?

vestal thicket
#

oh yeah i forgot uh

#

that isn't actually including the code where it GETS the data haha

floral meteor
#

if you're gonna talk about stuff like xrandr and xinput, preferably link to an explanation so we don't have to research and/or guess what you mean

vestal thicket
#

i'm just using subprocess and reading from stdout

floral meteor
#

what's wrong with input()?

vestal thicket
#

xrandr is a cli tool used to get information about the current X screen and connected X displays, xinput is a cli tool used to get information about connected input devices like keyboards and mice and their properties

#

primarily they're intended for interactive use

floral meteor
#

riiiiiiight.

#

my minesweeper game is very interactive, you use wasd keys to move a cursor around to select the squares

#

anyone who gonna use a cli aint the type of person who would use the mouse

vestal thicket
#

here's an example of the sort of output i have to grab data from
xrandr --listmonitors Monitors: 3 0: +*DVI-I-1 1920/518x1200/324+1280+0 DVI-I-1 1: +DP-5 1280/376x1024/301+0+0 DP-5 2: +HDMI-0 1280/339x720/190+3200+0 HDMI-0

floral meteor
#

I just play around with the terminal instance hosting my script, and I use ANSI escape sequences to do that

vestal thicket
#

it's a pain in the ass

floral meteor
#

don't need to know about monitors smh

#

a cli only needs to know about its terminal

vestal thicket
#

what i'm writing is a gui app that sets the input dimensions for drawing tablets, so you can set the tablet cursor to be confined to the size of a monitor

floral meteor
#

didn't you say cli before? now you're making a gui

vestal thicket
#

it uses cli tools to gather data about the system

floral meteor
#

why do you need to use these specific ones?

#

especially in this channel, the idea is to think outside of the box

vestal thicket
#

it's just kind of how you do a lot of things when scripting using linux

vestal bramble
#

mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

floral meteor
#

no spam pls

#

one m will do very nicely

#

don't need 51 of them

vestal thicket
#

the reason is that xinput and xrandr are both tools that will be installed on basically any desktop linux setup my app is intended for and i don't have to worry about native code at all

#

both heavily documented and relied upon

floral meteor
#

it won't be installed on windows desktops

#

probably not macos either

#

although macOS doesn't really count

vestal thicket
#

i don't really know of any other way get information about x displays and x input devices using python at the time being. also no, it is exclusively a tool for configuring drawing tablets on systems using X

#

there is no need for it on windows or mac os

floral meteor
#

why do you need to configure drawing tablets on systems using X?

vestal thicket
#

because there aren't any existing graphical apps to do the task when it comes to X

floral meteor
#

make a graphical app to do the task, then.

#

then a graphical app would exist, thus solving your problem

vestal thicket
#

just to setup the dimensions your drawing tablet is active in in relation to your monitors, you have to spend 30 minutes to an hour researching which configuration files you have to configure, calculate the transformation matrix, and either modify the x config file or use xinput to set it non-permanently constantly

#

that's what i'm doing

#

the app has to grab information about the currently active X displays and the attached input devices and the easiest way to do that it using the cli tools xrandr and xinput, at least as far as i'm aware. you run those applications as subprocesses and grab and interpret the output in the python app

#

just as you might have a gui app that has to make and interpret database calls; there are all sorts of different sources you can use for data

floral meteor
#

This is an extremely specialist topic, and unfortunately for you, it appears you are the highest authority on this topic currently present.

as for string reading, I'm assuming your python script takes as input the output of the xrandr command?

#

there does appear to be patterns in these lines

vestal thicket
#

yeah basically it reads the output of stdout, which is generally multiple lines of text

vestal bramble
#

ok

vestal thicket
#

i was just wondering if anyone knew of any tools to make picking out data from lines of text easier than

floral meteor
#

umm i need to know what these numbers and abbreviations mean

vestal thicket
#

having to do it manually using just the basic string manipulation functions

floral meteor
#

+HDMI-0 what does that mean?

#

what do the pluses do?

vestal thicket
#

it's just for display

floral meteor
#

what's the difference between the second attribute and the last attribute?

#

other than the prefix of +?

vestal thicket
#

that's the thing; this stuff is formatted for reading, not as a data structure

#

why it lists the name of each monitor twice i don't know

floral meteor
#

I know, but it can still be used to build a dataclass

vestal thicket
#

that's actually a good question

#

i just pick out the data i care about

floral meteor
#

what are the plus-separated values after the last forward-slash mean?

#

I can't discern their meaning straight from context

#

I'm gonna give them some dummy name for now

vestal thicket
#

what line?

floral meteor
#

all of them have it in the example

vestal thicket
#

oh that's offset data

#

x and y offset

floral meteor
#

what's the third value then?

#

I'll just store it all in offset_data as a tuple

vestal thicket
#

it's something like, (x resolution)/(x physical width)x(y resolution)/(y physical height)+(x offset)+(y offset)

#

that's my understanding anyway

floral meteor
#

well that doesn't make sense i assumed the middle axb would be a is screen width, b is screen height and the first value in the forward slash separated series is corner-to-corner size

vestal thicket
#

the offset being the displays offset in pixels from the virtual desktop's 0,0 starting coordinate

#

in the case of a/bxc/d+e+f , b is the physical width in millimeters

#

it's not a mathematical formula or anything

#

it's just formatted output

#

er, formatted data

floral meteor
#

This is the sort of dataclass I can build from that input (untested)

import attr
@attr.s
class Monitor:
  """default values are example values"""
  id:int = attr.ib(2)
  monitor_name:str = attr.ib("HDMI-0")
  monitor_identifier:str = attr.ib("+HDMI-0")
  resolution:tuple[int,int]=attr.ib((1280,720))
  size:tuple[int,int] attr.ib((339,190))
  offset:tuple[int,int]=attr.ib((3200,0))

n = int(input().partition(': ')[2])
monitors = []
for i in range(n):
  line = input().lstrip().split(' ')[1:]
  mon_id, yay, name = line
  width, this, that = yay.split('/')
  x, height = this.split('x')
  y, *o = that.split('+')
  monitors += [Monitor(i, name, mon_id, (x, y), (width, height), o)]
#

refactor at will

#

oh wait gotta store these instances somewhere

vestal thicket
#

interesting

floral meteor
#

assuming stdin is piped

vestal thicket
#

oh that's from attr ok. i was like "what is that"

floral meteor
#

boilerplate avoidance

vestal thicket
#

yeah

floral meteor
#

you likey?

#

oh wait

#

I just found a fatal flaw in my script

#

I forgot to do typing

vestal thicket
#

i don't know yet if you'll use that way of writing it but i'm certainly learning a lot just from reading through it and looking up the stuff i don't know/hadn't considered so thanks

floral meteor
#
import attr
@attr.s
class Monitor:
  """default values are example values"""
  id:int = attr.ib(2)
  monitor_name:str = attr.ib("HDMI-0")
  monitor_identifier:str = attr.ib("+HDMI-0")
  resolution:tuple[int,int]=attr.ib((1280,720))
  size:tuple[int,int] attr.ib((339,190))
  offset:tuple[int,int]=attr.ib((3200,0))

n = int(input().partition(': ')[2])
monitors = []
for i in range(n):
  mon_id, yay, name = input().lstrip().split(' ')[1:]
  width, this, that = yay.split('/')
  x, height = this.split('x')
  y, *o = map(int,that.split('+'))
  monitors += [Monitor(i, name, mon_id, (int(x), int(y)), (int(width), int(height)), o]
#

correctly typed this time(hopefully)

vestal thicket
#

it's certainly a lot more compact

floral meteor
#

I don't like scrolling unless the code has significant size

#

in this compact form, I can non-linearly analyse the code

vestal thicket
#

right

long hamlet
floral meteor
#

ah yes, interrogating the display for its personal information

vestal thicket
#

honestly, reading and writing to buffers is easier than text manipulation stuff imo lmao

#

to image/screen buffers i mean

floral meteor
#

to me, 'buffer' describes the Rock compared to Elon Musk.
The Rock is very buff. much buffer than Elon.

long hamlet
floral meteor
#

I might've gotten resolution and size the wrong way around, whoops

#

but refactor at will, as I said earlier

vestal thicket
#

thanks!

long hamlet
vestal thicket
#

yeah that's when i'd just use sdl, lol

#

or opengl

long hamlet
floral meteor
#

for some reason it only works horizontally XD

#

nvm it doesn't work properly in any direction I algorithmed wrong

#

and I think using ctypes to mutate the cell into its parent class is why it's randomly crashing without an error message

floral meteor
#

it works now.

wary shoal
#

I have come to bleed my eyes

pure dew
#

why are you fetching monitor information for a CLI game?

floral meteor
#

apparently, cli tools are being used for a gui

#

so close...

#

wait

#

I had a valid move still

#

what's so confusing about not a or not b or a==b for x in self.matrix for a, b in (x[:2],x[1:3],x[2:]) that python cannot understand?

#

a.value==b.value might work better

#

and ```py
print ('\x1b[H\x1bc')

works really great to reinitialise the terminal.
floral meteor
#

140 lines of dense mf

#

and it looks like this and functions without bugs.

finite blaze
#

how are u rendering these colors?

knotty delta
knotty delta
#

esoteric source pls ๐Ÿฅบ

floral meteor
#

only works on windows

#

only tested on win11

knotty delta
pure dew
#

only works on windows?

#

this isnt what you were querying the monitor for, is it?

wispy wedge
#

any way I could make my own images with just an rgb code? I'd just like to generate a 32x32 image that's purely one singular color without 3rd party dependencies. I don't care about any metadata or filetype, it just needs to be renderable in a web browser

severe canyon
#

why not just to that in html and css?

wispy wedge
#

I don't actually have access to any html or css, the api just forces me to send image data

long hamlet
#

Lol my library might help

wispy wedge
#

I previously used PIL but that's an extra dependency for no reason

wispy wedge
severe canyon
#
<svg width="32" height="32">
  <rect width="32" height="32" style="fill:rgb(0,0,255)"/>
</svg>
#

use svg?

wispy wedge
#

yeah I can't do svg, it doesn't count it as an image

#

idk why

#

first thing I tried

severe canyon
#

hm

long hamlet
#

Lots of things there have to trim it down lol

#

mx=1024 my=768 bmp=b.newBMP(mx,my,24)

#

How to make an in memory bmp

wispy wedge
#

yeah idk mate. At that point I could just keep PIL

#

also no offense but this isn't a lib I'd want to have in my dependencies tbh

long hamlet
#

No worries lol and yeah i understand

long hamlet
#

But it is lafe night here and I have to sleep...it will still be a bitmap

wispy wedge
#

I wonder if it even supports bitmaps tbh

#

like I was hoping to somehow figure out how tf to make a png or jpg

long hamlet
#

Is that for a favicon?

wispy wedge
#

an api requires raw image data to display an image

long hamlet
#

Jpg is more complex has lossy compresion

#

Png has alpha channel

wispy wedge
#

gif should probs work too but idk if it's harder

long hamlet
#

And compression

#

Use library if you want those formats

#

I can work at it but not for gratis lol

rapid sparrow
#

i figured a cool "trick" with context managers that abuses sys._getframe

#

!e

from sys import _getframe                                               
class AssignmentTracker:
  def __enter__(self):                                                  
    self._fr1 = _getframe(1)                                            
    self._fr1_orig = dict(self._fr1.f_locals)
  def __exit__(self, *err):                                             
    self.changed = {                                                    
      k:v for k,v in self._fr1.f_locals.items()                         
      if k not in self._fr1_orig
      or self._fr1_orig[k] is not v
    }
    print(f"New or changed variables: {self.changed}")

with AssignmentTracker():
  name = "John"
  import random
  age = random.randint(1, 50)
  print(f"{name}'s age is {age}")```
night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | John's age is 47
002 | New or changed variables: {'name': 'John', 'random': <module 'random' from '/usr/local/lib/python3.10/random.py'>, 'age': 47}
rapid sparrow
#

there is a framework that uses this kind of "with block" to accomplish a similar outcome

#

but I doubt they are doing it with frames

#

it's like

with model:
  n = 3
  a = 7
  b = (2, 6)
assert model.n == 3
assert model.a == 7
assert model.b == (2,6)
#

how would you do that ?

sly root
rapid sparrow
sly root
#

give me a sec

#

you basically need to add if or match check and then check if requested name == "model" or something else

noble nexus
#

hey guys, I was wondering
what happens when you do a = 2, where does the 2 go in terms of Python?
If I do __builtins__ = None then I can't use any pre-existing function or variable, but then if I do a = 2 it works and I can access it : a yields 2
I'd assume they go in locals / globals. They still do but it's just I don't have access to it anymore since my "locals" string can't resolve to the actual object through __builtins__?
How would I go about still somehow accessing locals or globals, or wherever variables are?
(don't hesitate to ping me)

fleet bridge
#

2 is int literal
you cant change behaviour of literals
2 always means instance if int type

#

when you do __builtins__ = None, you dont delete all builtin types and objects, you just remove reference to builtins.__dict__

#

!e

__builtins__ = type('',(),{'__getitem__':print})()
a
b
c
hello_world
night quarryBOT
#

@fleet bridge :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name 'a' is not defined
fleet bridge
#

๐Ÿค”

#

it works in repl

upbeat sonnet
#

!e python print(" ".join([chr(i) for i in range(65, 65 + 26)]).strip(" "))

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
upbeat sonnet
#

๐Ÿƒโ€โ™‚๏ธ

fleet bridge
#

!e

print(' '.join(map(chr,range(65,91))))
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
upbeat sonnet
#

pro

noble nexus
#

!e ```py
print(*map(chr,range(65,91)),sep=' ')

night quarryBOT
#

@noble nexus :white_check_mark: Your eval job has completed with return code 0.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
noble nexus
#

one char less ๐Ÿ‘€

fleet bridge
#

nice

upbeat sonnet
#

king fr fr

noble nexus
#

I still don't know how to monkey my way around a __builtins__ = None though ๐Ÿ˜”

#

(I can't write __ :kappa:)

upbeat sonnet
#

what is the * operator

noble nexus
#

unpacking
well I think it has some other weird official name

fleet bridge
#
>>> int
<class 'int'>
>>> __builtins__ = None
>>> int
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable
>>> del __builtins__
>>> int
<class 'int'>
noble nexus
#

๐Ÿ‘€

#

I know, I have weird problems

fleet bridge
#

copy this: __ every time you need to write this

noble nexus
#

there are other various conditions, sadly
can't import stuff (like ctypes)

noble nexus
#

I'm also interested if you have some convoluted way to set a read-only attribute ๐Ÿ‘€
desperate

fleet bridge
#

change __setattr__

noble nexus
#

yeah but you used __ ๐Ÿ‘€

fleet bridge
noble nexus
#

hehehe

fleet bridge
#

!e use this to create function names

dunder = dir(0)[0][:2]
print(dunder)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

__
noble nexus
#

yeah but you can't call dir with builtins = None ๐Ÿ‘€
sorry that's a really tough setting don't bother

polar plover
#

so we got a challenge?
so rules are __builtins__ = None and no using __?

noble nexus
#

there are more but it's an actual challenge so I should just solve it by myself

#

I mean you can try with these 2 rules, no other globals(/locals) and no import

#

in fact you can import but that first rule (as long as it stands) de facto prevents it the way Python works

polar plover
#

!e interesting py __builtins__ = None class Foo: pass

night quarryBOT
#

@polar plover :warning: Your eval job has completed with return code 0.

[No output]
polar plover
#

wait wat

noble nexus
#

yep

#

don't know why but it's how things are
various stuff breaks, and apparently class too

polar plover
#

differences between scripts and repel are annoying xD

#
>>> __builtins__ = None
>>> class Foo: pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable```
#

!e py __builtins__ = None print("does this work still?")

night quarryBOT
#

@polar plover :white_check_mark: Your eval job has completed with return code 0.

does this work still?
polar plover
#

okay, wtf

noble nexus
#

you only have the new stuff you define as a consequence, plus keywords

polar plover
#

why is it working differently depending on if you run it in a script, or if you are using the repl

noble nexus
#

I don't know how the repl works but seems fair it would make assumptions like "the environment isn't f-d up"

upbeat sonnet
#

bro i thought i had no life ๐Ÿ’€

polar plover
#

the no __ is really mean ...

noble nexus
#

I have found numerous and very different approaches that all wind up in either __ or f-d up builtins unexpectedly f-ing some other things up
a bit disappointed
ultra-low-level things are behind imports
non-__ low-level things are read-only

polar plover
#

and all the fun attributes are behind __

severe canyon
noble nexus
#

I'm tired

severe canyon
#

understandable

upbeat sonnet
#

between letters

#

!e python print(*map(chr, range(65,91)))

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
upbeat sonnet
#

oh ic

severe canyon
#

:)

umbral prism
#

Can any of you oneline this ?

def pack(data: dict):
    d = []
    for k, v in data.items():
        v = str(v).lower() if isinstance(v, bool) else v
        v = "undefined" if v == None else v
        d.append(f"{k}={v}")
    return "&".join(d)
#

I don't care if its hard ass complicated shit to read, all i care is that it works :^)

dark wharf
#

seems to work pretty well

umbral prism
#

oh thanks

maiden river
#

!e

speak = print
speak("hi")
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

hi
maiden river
#

i wish we could define new keywords that easily
inthething = in
candy = for

#

could there be some way ๐Ÿ‘€

#

some class function operator magic ?

sick hound
#

Hi Gentlemen i wanna ask a question now , i'm solving problems on codeforces but i always find very difficult problem for me and i saw the answer of others and i don't know how they are thinking in it in that way i want to learn that skill can any one help ?๐Ÿคฆโ€โ™‚๏ธ

floral meteor
floral meteor
# maiden river some class function operator magic ?

that would be the parser. Unfortunately everything is parsed before anything runs, and nothing runs if a syntaxerror is determined.
It is possible to change some syntax rules before importing something containing the python code with the desired syntax.

floral meteor
#

It is, however, possible and fun to build esolangs that can parse within python syntax rules.

earnest wing
#

and builtins are "basically" propagated at compile time

#

er, wrong word

#

inhabited?

#

idk

floral meteor
# floral meteor It is, however, possible and fun to build esolangs that can parse within python ...

for example I could make something like:

build_class. myObject[
  init_method (a, b)[
    setattr. a=a,
    setattr. b=b,
  ],
  method. add .magic="++" (other)[
    setattr. a=a+other.a,
    setattr. b=b+other.b,
  ],
  method. sub .magic='--' (other)[
    setattr. a=a-other.a,
    setattr. b=b-other.b,
  ],
  property. abs[
    ret. math.sqrt(a**2 + b**2)
  ],
] .endclass

function. main[
  set. x == myObject (3,4),
  set. y == myObject (1,2),
  x ++ y,
  delete. y,
  echo. x,
] .endfunction

main

to output

<MyObject x=4, y=6; at 0xc06198e3a012105>
floral meteor
#

all of the above should be technically possible to implement, but some of it would be very painful.

#

including building the methods out of the arrays of sentinal objects, and hacking globals.__getitem__ almost irrecognisably

floral meteor
#

conservatively written

from msvcrt import*
class Quit(RuntimeError):quit=lambda:(()for()in()).throw(Quit)
@type.__call__
class C:
  def __init__(s):s.c=[0,0,0]
  def __str__(s):return f'\x1b[H\x1b[38;2;{";".join(map(str,s.c))}m{s.c}   \x1b[0m\n\x1b[48;2;{";".join(map(str,s.c))}m{"": >{len(str(s.c))}s}\x1b[0m   \n\x1b[48;2;{";".join(map(str,s.c))}m{s.c}\x1b[0m   \n\x1b[48;2;{";".join(map(str,s.c))}m{"": <{len(str(s.c))}s}\x1b[0m   \x1b[A'
  def __add__(s, n):s.c[n]+=1;s.c[n]=min(255,s.c[n])
  def __sub__(s, n):s.c[n]-=1;s.c[n]=max(0x0,s.c[n])
try:
  print('[0, 0, 0]\n\n[0, 0, 0]')
  while 1:
    if kbhit():{'w':lambda:C+1,'a':lambda:C-0,'s':lambda:C-1,'d':lambda:C+0,'q':lambda:C-2,'e':lambda:C+2,'\x1b':Quit.quit}.get(getch().decode(),lambda:0)();print(C)
except Quit:print()
#

!e ```py
def concatenate(a:str, b:str):
return a + b

print((lambda f:setattr(f,'annotations',{'a':str,'b':str})or f)(lambda a,b:a+b).annotations == concatenate.annotations)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

True
floral meteor
#

demonstrating type hints for oneline code

#

you can also use a similar concept to "name" an anonymous function (lambda), by setting __name__

floral meteor
#

the algorithm behind 2048 can pretty much be summed up here

def _swipe(self,i,d):
    m=[[self[i,q]for q in range(4)],[self[i,q-1]for q in range(4,0,-1)],[self[q-1,i]for q in range(4,0,-1)],[self[q,i]for q in range(4)]][d];q=[*map(int,m)]
    for j in range(3):
      y=q[j:]
      while not y[0]and any(y[1:]):q+=[q.pop(j)];y+=[y.pop(0)]
    for j in range(3):
      y=q[j:]
      if not[*{*y[:2]}][1:]:q[j]+=q.pop(j+1);q+=[0]
    for j,n in enumerate(q):
      if n:self[m[j]]=Cell(*m[j],n)
      else:self.empty(*m[j])
    return q!=[*map(int,m)]
floral meteor
#

everything else is just interaction

floral meteor
severe canyon
#

that code for drawing the board must be reducable

sly root
#

else with any table building lib it can be reduced to 5-9 lines of code

sick hound
#

I need help Iโ€™m new python

vale tangle
#

!e

for i in range(10):
    print(f"Hacking your mom... {(i+1)*10}% complete")
from random import randint as r
def n():
    return r(0,128)
print(f"Hacked successfully, ip: {n()}.{n()}.{n()}.{n()}")
night quarryBOT
#

@vale tangle :white_check_mark: Your eval job has completed with return code 0.

001 | Hacking your mom... 10% complete
002 | Hacking your mom... 20% complete
003 | Hacking your mom... 30% complete
004 | Hacking your mom... 40% complete
005 | Hacking your mom... 50% complete
006 | Hacking your mom... 60% complete
007 | Hacking your mom... 70% complete
008 | Hacking your mom... 80% complete
009 | Hacking your mom... 90% complete
010 | Hacking your mom... 100% complete
011 | Hacked successfully, ip: 11.62.103.124
floral meteor
worn lion
#

why isnt the import at the top lol

sick hound
floral meteor
#

unpacking an iterable into an indefinite amount of arguments to print

floral meteor
floral meteor
floral meteor
worn lion
#

it looks wrong but then everything in this channel also looks wrong

floral meteor
#

!e ```py
@type.call
class model:
def enter(self):
import sys
self.reset = sys._getframe(1).f_globals.copy()
sys._getframe(1).f_globals.clear()
def exit(self, *_whatever):
import sys
k = sys._getframe(1)
r = type('model',(),k.f_globals)()
k.f_globals.clear()
k.f_globals.update(self.reset|{'model':r})
return 0

with model:
n, a = 3, 7
b = 2, 6
assert not[{(model.n,model.a),(3,7)}][1:]
assert not[
{model.b,(2,6)}][1:]
print(model)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

<model object at 0x7f7f2061bee0>
floral meteor
#

that's one interpretation, anyway

#

!e ```py
def implicit_equals(ab):return not[{ab}][1:]
for
k,in[(0**0,1,1>0),((),()),(0,0<0),((1,2),)*3,(1,2,3)]:print(implicit_equals(*k))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | True
003 | True
004 | True
005 | False
rapid sparrow
floral meteor
#

assuming model is allowed to preexist

#

what was your solution?

#

if it's supposed to be a dataclass constructor some globals getitem hackery using bytecode inspection might tell it to create an intermediate context manager to build the class from the parallel globals

earnest wing
#

and i guess literally plugging the contents into z3 lol

rapid sparrow
rapid sparrow
#

you still have the code?

#

it's a cool idea but i think it's just beyond the way python is intended to be used

#

so might not be bulletproof

#

there's something called contextvar as well

#

!d contextvars

night quarryBOT
#

This module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables. The copy_context() function and the Context class should be used to manage the current context in asynchronous frameworks.

Context managers that have state should use Context Variables instead of threading.local() to prevent their state from bleeding to other code unexpectedly, when used in concurrent code.

See also PEP 567 for additional details.

New in version 3.7.

rapid sparrow
#

it starts off sounding interesting at least

#

the api is practically non-existent

#

!e
import contextvars
print(dir(contextvars))

night quarryBOT
#

@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.

['Context', 'ContextVar', 'Token', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'copy_context']
rapid sparrow
#

i wrote a similar function

#

to execute code in another namespace

#

like in the namespace of a module or class

#

it's not bulletproof either but useful

twilit mountain
earnest wing
#

yeeeah there it is

#

the benefits of using classes is that you don't need to make a mess with globals & locals awareness; classvars are relatively simple

#

the downsides is that it's uglier and editors hate it with a passion

#

class _(Model): vs with Model(...):

vale tangle
#

!e

print(True,True,True==(True,True,True))
night quarryBOT
#

@vale tangle :white_check_mark: Your eval job has completed with return code 0.

True True False
floral meteor
floral meteor
#

!e dummy integer ```py
@type.call
class a:value=0;index=int=hash=lambda s:s.value

a.value = 4
print([*range(3),*range(3)][a])

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

1
floral meteor
#

!e which can make a really cursed ```py
@type.call
class a:
value=47;index=int=hash=lambda s:s.value;iter=lambda s:s
def next(self):
a.value+=1
if a.value==58:raise StopIteration
return print

*map(lambda :(chr(a)),a),

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
floral meteor
#

if I didn't stop at 58 this would indefinitely iterate, like a really cursed event loop

#

wait did I just discover async mechanics?

#

!e or I could make accessing it as an integer increase its integer value ```py
@type.call
class a:
value=0;index=int=hash=lambda s:setattr(s,'value',s.value+1)or s.value;iter=lambda s:s

print(*map(list,map(range,[a]*10)),sep='\n')

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | [0]
002 | [0, 1]
003 | [0, 1, 2]
004 | [0, 1, 2, 3]
005 | [0, 1, 2, 3, 4]
006 | [0, 1, 2, 3, 4, 5]
007 | [0, 1, 2, 3, 4, 5, 6]
008 | [0, 1, 2, 3, 4, 5, 6, 7]
009 | [0, 1, 2, 3, 4, 5, 6, 7, 8]
010 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
stuck peak
#

somebody posted a comment on a video I was watching yesterday saying that people who scraped stuff from the web might need 10's or even 100's of proxies to " avoid detection.. "
๐Ÿค”
It just had me wondering what might this person be scraping that they would need so many proxies . .

floral meteor
#

I scraped a pet adoption website quite directly to determine which cat of theirs was the fattest. Shouldn't I have?

rapid sparrow
#

that is truly a hidden gem

rapid sparrow
#

something where the site owner really doesn't want them to, in all likellihood

rapid sparrow
#

if you were able to do it directly, that's a good sign you're not going against the owner's wishes

pure dew
floral meteor
quartz wave
#

!e ```py
not๏พ defined

night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'notแ… defined' is not defined
quartz wave
#

yes

twilit mountain
#

Learnt a lesson: Never look into this channel again as long as there ain't any pings from here

pure dew
#

now you'll know not to look in this channel at all :^)

twilit mountain
#

No no no u just gave me anxiety of what's in the link but I ain't clicking it

pure dew
#

its just python

#

a couple small classes

twilit mountain
pure dew
#

Binds a trait to a type for the impl

#

it's the "target type", so to speak

#

this is basically the Rust trait system

#

minus a few things

twilit mountain
#

O

south tundra
#

!e py a = print a("test")

night quarryBOT
#

@south tundra :white_check_mark: Your eval job has completed with return code 0.

test
south tundra
#

!e py a = for b = in c = range a _ b c(1,2): print(_)

night quarryBOT
#

@south tundra :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     a = for
003 |         ^^^
004 | SyntaxError: invalid syntax
south tundra
#

aw

floral meteor
#

this is python, not c

floral meteor
#

what you can do is write a turing complete string interpreter then the string can be whatever.

sick hound
#

!e

assert not len('l')
night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AssertionError
sick hound
#

!e

assert not len('')
night quarryBOT
#

@sick hound :warning: Your eval job has completed with return code 0.

[No output]
sick hound
sick hound
#

This

unreal echo
#

I come here occasionally when I'm feeling too smart and need to lower my confidence to humanly levels.

fervent umbra
#

I come here occasionally when I want to realise I have no idea how python works

fiery crane
#

i come here occasionally to realise I don't know how to program

sick hound
#

!e

#define a for
#define b in
#define c range
a _ b c(1,2):
    print(_)โ€Š
night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 4
002 |     a _ b c(1,2):
003 |       ^
004 | SyntaxError: invalid syntax
sick hound
#

!e
test={"cool": "no way"}
() = test
print(globals())

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | ValueError: too many values to unpack (expected 0)
astral rover
#

class _(Model):

#

its in the reply chain

sick hound
#

And it will take the local vars of that model and put it into globals?

sick hound
astral rover
#

no look at the code in the github repo

sick hound
#

Sometimes scraping at 1k rps

rapid sparrow
#

i still dont get what it does .

rugged sparrow
#

() = obj calls obj.__iter__ so obj.__iter__ can dump values into globals

#

!e ```py
class O:
def iter(self):
print('i got called')
return
yield

obj = O()
() = obj```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

i got called
fleet bridge
#

if False: yield

fleet bridge
#

iirc in the Iterable protocol

rapid sparrow
#

i got some esoteric code by accident

#
def some_beartyped_function():
  if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
    __beartype_pith_0, str
  ):
    __beartype_raise_exception(
      func=__beartype_func, pith_name="package_name", pith_value=__beartype_pith_0
    )
  __beartype_pith_0 = kwargs.get("module_name", __beartype_raise_exception)
  if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
    __beartype_pith_0, str
  ):
    __beartype_raise_exception(
      func=__beartype_func, pith_name="module_name", pith_value=__beartype_pith_0
    )
  __beartype_pith_0 = kwargs.get("func", __beartype_raise_exception)
  if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
    __beartype_pith_0, __beartype_object_9795712
  ):
    __beartype_raise_exception(
      func=__beartype_func, pith_name="func", pith_value=__beartype_pith_0
    )
  __beartype_pith_0 = kwargs.get("version", __beartype_raise_exception)
  if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
    __beartype_pith_0, __beartype_object_15338576
  ):
    __beartype_raise_exception(
      func=__beartype_func, pith_name="version", pith_value=__beartype_pith_0
    )
  __beartype_pith_0 = kwargs.get("hash_algo", __beartype_raise_exception)
  if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
    __beartype_pith_0, __beartype_object_14936032
  ):
    __beartype_raise_exception(
      func=__beartype_func, pith_name="hash_algo", pith_value=__beartype_pith_0
    )
  __beartype_pith_0 = kwargs.get("user_provided_hashes", __beartype_raise_exception)
  if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
    __beartype_pith_0, set
  ):
    __beartype_raise_exception(
      func=__beartype_func,
      pith_name="user_provided_hashes",
      pith_value=__beartype_pith_0,
    )
  __beartype_pith_0 = kwargs.get("registry", __beartype_raise_exception)
  if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
    __beartype_pith_0, __beartype_object_549598516568
  ):
    __beartype_raise_exception(
      func=__beartype_func, pith_name="registry", pith_value=__beartype_pith_0
    )
  __beartype_pith_0 = __beartype_func(*args, **kwargs)
  if not isinstance(__beartype_pith_0, __beartype_object_549601113792):
    __beartype_raise_exception(
      func=__beartype_func, pith_name="return", pith_value=__beartype_pith_0
    )
  return __beartype_pith_0```
fleet bridge
#

Wtf

rapid sparrow
#

the function I was using to look at tracebacks tries to decompile ones that don't have a source file, like this was File <string>

#

the function had a @beartype on it

#

was kind of shocked to see all that get printed out lol

pure dew
#

what is beartype??

astral rover
#

a runtime type checker

flint nacelle
#

Hey there, any good tips for how to upload a game on telegram written on Python? Thanks in advance for who will reply ๐Ÿ™‚

floral meteor
#

@flint nacelle โŒ Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | WrongChannelError: please refer to the channel [#โ“๏ฝœhow-to-get-help](/guild/267624335836053506/channel/704250143020417084/) for more information
quartz wave
#
>>> import discord
>>> guild = discord.get_guild('Python')
>>> channel = guild.get_channel('esoteric python')
>>> channel.get_help()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Python310/Lib/site-packages/discord", line 344, in get_help
NoHelpException: cannot get help from channel; do you mean to be in channel "how to get help"?
#

i wonder why ๐Ÿค”

thorny tapir
#

help I cannot be helped

golden finch
#

https://stackoverflow.com/questions/71315838/when-i-modify-builtins-to-a-custom-class-it-only-works-in-shell
This seems like the sort of thing you guys might be able to help with - reason I'm not posting it in a help channel is that it's very niche, and there isn't a strictly defined solution, just making __missing__ work... somehow

Full disclosure: This is my stackoverflow post

earnest wing
#

You can obviously do some interior mutability tricks, though, such as .clear()ing, or using ctypes etc. to patch the actual object in memory

fleet bridge
#

How can i make Return() function?

#
Return = ...
def f():
  Return(42)
assert f() == 42
#

Maybe i should set trace function to parent frame and then execute return opcode?

#

Possible use case:

def some_decorator():
  @Return
  def wrapped(): ...

# instead of 
def some_decorator():
  def wrapped(): ...
  return wrapped
#

It can be used in ternary operator to return from function if some invariants are broken

twilit mountain
floral meteor
sick hound
floral meteor
#

!e ```py
class Return(BaseException):
def init(self,*data):
try:self.data,=data
except:self.data=data
super().init(repr(data))

def implementsReturn(f):
def inner(*a,**k):
try:return f(*a,**k)
except Return as e:return e.data
return inner

@implementsReturn
def main():
a, b = 60, 9
raise Return(a+b)

result = main()
print(result)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

69
floral meteor
#

with this pair of implementsReturn and Return, Return now returns from the next frame that implementsReturn, thus supporting returning from multiple frames at once.

#

!e another example ```py
class Return(BaseException):
def init(self,*data):
try:self.data,=data
except:self.data=data
super().init(repr(data))

def implementsReturn(f):
def inner(*a,**k):
try:return f(*a,**k)
except Return as e:return e.data
return inner

@implementsReturn
def main():
def inner(n):
raise Return(60+n)
inner(9)

print(main())

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

69
floral meteor
#

also supports building a tuple just like builtin return

#

I'll leave making an example of that as an exercise for the reader.

twilit mountain
formal sandal
#

https://paste.pythondiscord.com/lubifivuru

def foo():
    n = 0

    goto = Goto()
    while goto:
     with goto as label:
        if label("fizz"):  print("fizz", n)
        if label("buzz"):  print("buzz", n)
        if True:           n += 1
        if n == 5:         goto.hell()
        if n > 3:          goto("fizz")
        else:              goto("buzz")

foo()
``` ```
fizz 0
buzz 0
buzz 1
buzz 2
buzz 3
fizz 4
buzz 4
knotty delta
formal sandal
rough mulch
#

Woah

rugged sparrow
#

!e ```py
BYTES_HEADER = bytes.basicsize - 1
PTR_SIZE = tuple.itemsize
ENDIAN = ['big','little'][memoryview(b'\1\0').cast('h')[0]&0xff]

load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**(PTR_SIZE*8-1)-1)),r.setstate)

memory_backing = bytes(PTR_SIZE)
+ id(bytearray).to_bytes(PTR_SIZE, ENDIAN)
+ bytes([255] * (PTR_SIZE - 1) + [127])
+ bytes(PTR_SIZE * 4)

memory = memoryview(load_addr(id(memory_backing) + BYTES_HEADER))

def getframe(level=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame.f_back
for () in [()] * level:
frame = frame.f_back
return frame

def Return(val):
frame = getframe(1)
offset = id(frame.f_code.co_code) + bytes.basicsize + frame.f_lasti - 1
memory[offset + 2: offset + 4] = bytes((83, 0))
return val

def test(x):
Return(x + 1)

print(test(1))```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

2
quartz wave
#

oh

#

!e ```py
BYTES_HEADER = bytes.basicsize - 1
PTR_SIZE = tuple.itemsize
ENDIAN = ['big','little'][memoryview(b'\1\0').cast('h')[0]&0xff]

load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**(PTR_SIZE*8-1)-1)),r.setstate)

memory_backing = bytes(PTR_SIZE)
+ id(bytearray).to_bytes(PTR_SIZE, ENDIAN)
+ bytes([255] * (PTR_SIZE - 1) + [127])
+ bytes(PTR_SIZE * 4)

memory = memoryview(load_addr(id(memory_backing) + BYTES_HEADER))

def getframe(level=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame.f_back
for () in [()] * level:
frame = frame.f_back
return frame

def Return(val):
frame = getframe(1)
offset = id(frame.f_code.co_code) + bytes.basicsize + frame.f_lasti - 1
memory[offset + 2: offset + 4] = bytes((83, 0))
return val

def test(x):
Return(x + 1)

import dis
dis.dis(test)

night quarryBOT
#

@quartz wave :white_check_mark: Your eval job has completed with return code 0.

001 |  33           0 LOAD_GLOBAL              0 (Return)
002 |               2 LOAD_FAST                0 (x)
003 |               4 LOAD_CONST               1 (1)
004 |               6 BINARY_ADD
005 |               8 CALL_FUNCTION            1
006 |              10 POP_TOP
007 |              12 LOAD_CONST               0 (None)
008 |              14 RETURN_VALUE
quartz wave
#

so it just replaces the POP_TOP with a RETURN_VALUE except that it doesn't actually know that there's a POP_TOP in it

rugged sparrow
quartz wave
#

i know that

south tundra
golden finch
golden finch
#

!e

import sys
import dis
import ctypes

mutable_bytes=lambda i:memoryview((ctypes.c_uint8*len(i)).from_address(id(i)+bytes.__basicsize__-1)).cast('B')#from Python Discord

def tracefunc(frame,*useless):
    print(f'\nDisassembling frame {frame}... ')
    co_code=mutable_bytes(frame.f_code.co_code)
    #now, find the indices of all the LOAD_NAME operations in the frame
    indices=[i for i in range(0,len(co_code),2)if co_code[i] in (dis.opmap['LOAD_NAME'],dis.opmap['LOAD_FAST'])]
    names=[frame.f_code.co_varnames[co_code[i+1]]for i in indices]
    print(dis.dis(frame.f_code))
    print(names)

sys.settrace(tracefunc)

print('foo')

print(bar)
night quarryBOT
#

@golden finch :x: Your eval job has completed with return code 1.

001 | foo
002 | Traceback (most recent call last):
003 |   File "<string>", line 20, in <module>
004 | NameError: name 'bar' is not defined
golden finch
#

that... is not the output on my machine

rugged sparrow
#

i have code that makes this work already one sec

#

!e ```py
from ctypes import py_object
import atexit, builtins, sys, dis

def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.dict | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = class

ob_base_p.value = missing_hook

@atexit.register
def unhook():
    ob_base_p.value = dict
return unhook

init_missing_hook(sys._getframe().f_globals, lambda d, k:(k, 'var'))

print(foo)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

('foo', 'var')
rugged sparrow
#

@golden finch ^ it changes the type of the globals dict in place and adds a __missing__ method

golden finch
#

how did you get it working?

#

by the way, that thing is intimidating

rugged sparrow
#

first off you need to make sure everything in the class your hotswapping in is being loaded with LOAD_FAST

golden finch
#

okay

rugged sparrow
#

you also need to make sure the new class has the same instance size __slots__ = () causes the class to lose all of the dynamic extra stuff (leaving it the same size as dict)

golden finch
#

remind me what slots does again?

rugged sparrow
#

it normally specifies the variable slots on an object

#

builtinexc was unnecessary to i removed it

golden finch
#

okay

rugged sparrow
#

youre welcome to just copy init_missing_hook, it takes in a dict instance and a func

golden finch
#

No, I'm curious how it works though - reading this:

  • is presume ob_base_p is a pointer to the pyobject of the dict instance?
#

or is it a pointer to the pyobject of dict itself?

rugged sparrow
#

ob_base_p = py_object.from_address(id(dct) + 8) this line gets the pointer 8 bytes from the start of dct and interprets it as a pointer to a pyobject

#

that happens to be the tp_base pointer, which is the pointer to the base class of an object

#

so by swapping that, we effectively change the type(dct) from dict to missing_hook

golden finch
#

ah

#

and now your missing hook class

#

so why do you declare slots to be empty?

rugged sparrow
#

that causes python to skip adding the extra space on class instances that is normally used for a dictionary and an attribute cache

#

empty slots means we have no attributes, so no dictionary and no need for a cache

#

this is one of the things i used that missing_hook to do

golden finch
rugged sparrow
#

thanks, its the result of way to much time with python internals

rugged sparrow
golden finch
#

user class?

rugged sparrow
#

!e ```py
class a:
pass

A = a()
A.foo = 1

class b:
slots = ()

B = b()
B.foo = 1 # fails```

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 11, in <module>
003 | AttributeError: 'b' object has no attribute 'foo'
golden finch
#

classes can have whatever attributes - but my understanding is __slots__ limits them to a set number of attrs

#

ah

#

makes sense

golden finch
rugged sparrow
#

because the builtin class dict has no attributes

#

and we need our hotswapped class to have the same layout in memory as the dict class

golden finch
#

mhm

#

why?

#

isn't it just pointed to?

#

so the pointer should work regardless of the size (and yes, I know I'm wrong, but I'm curious why)

rugged sparrow
#

because the globals dict has a specific size. python knows this by checking obj.tp_base.__basicsize__ plus some other stuff. we change tp_base to a custom class without changing the actual size of the globals dict

#

without __slots__ = (), python checks obj.tp_base to see if there is a dict and an attribute cache, it sees that there should be, and it happily reads past the end of the original globals object into random memory

#
>>> class a:pass
... 
>>> a.__basicsize__
32
>>> #[8:refcnt, 8:base, 8:dict, 8:attr_cache]
>>> class a:__slots__ = ()
... 
>>> a.__basicsize__
16
>>> #[8:refcnt, 8:base]```
golden finch
#

okay, makes some degree of sense, terrifying though

rugged sparrow
#

if you want to read more about stuff like that, look up type confusion vulnerabilities, its a similar concept

golden finch
#

okay so now you define a __missing__ method on missing_hook, but wait, it has no attributes, so how can you define a method on it?

rugged sparrow
#

attributes are stored on the instance, methods are stored on the class

golden finch
#

ah, okay

rugged sparrow
#

i actually found a second type confusion bug in python where you can coerce it into accessing an arbitrary object as a cell object

golden finch
#

TIL

#

once we finish discussing this code snippet, can we discuss what a cell is?

rugged sparrow
#

lol sure, ill warn you i have condensed this code a ton more

golden finch
#

intimidating

rugged sparrow
#

!e ```py
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**(tuple.itemsize*8-1)-1)),r.setstate)

print(load_addr(id(1)))

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

1
rugged sparrow
#

all that does is let you load an arbitary address as a python object

golden finch
#

spicy

#

that is scary

rugged sparrow
#

but you can use it to make fake objects in memory (using bytes)

golden finch
#

okay so now how does __missing__ work?

#

ugh, I'm going to have to go for maybe 45 minutes now

#

but I'll be back

rugged sparrow
#

__missing__ is called on dictionary subclasses when the key is not found in the dictionary

#

I actually need to go now as well, its 1:30 am here

#

feel free to ping me with questions, ill answer when I wake up

quartz wave
#

(didn't mean to ping)

golden finch
#

oh, that's a useful bit of info

sick hound
#

Is there any hacky way to re-add python 2 style print statements back to Python 3? lirikTHINK so ```py
print 989
print "foobar"
print 3*8-9

knotty delta
golden finch
#

@rugged sparrow what does that finally clause do? shouldn't it be ignored via return?

quartz wave
knotty delta
golden finch
#

@rugged sparrow doesn't seem to work inside functions

knotty delta
#

hi, i came back to say that i failed

#

it's possible to read a file with the tweaked tokenize thing

#

but it'll error out whenever there's parsing error if i use import past

knotty delta
#

however, my code w0rks a bit, it does weird stuff like 2to3 does

#

bUt it only works by running itself (gib filename as input, convert stuff, run code) but not at running it directly with python

#

bcuz python parses

#

:(

prisma coral
night quarryBOT
#

@prisma coral :white_check_mark: Your eval job has completed with return code 0.

001 | 989
002 | foobar
003 | 3 * 8 - 9
prisma coral
#

But obviously this doesn't fully meet the Py2 print statement syntax

prisma coral
#

!e Just realised that __future__.annotations was not actually what I was looking for.

@type.__call__
class __annotations__(dict):
    def __setitem__(self, item, value):
        print(value)
print: 989
print: "foobar"
print: 3*8-9
night quarryBOT
#

@prisma coral :white_check_mark: Your eval job has completed with return code 0.

001 | 989
002 | foobar
003 | 15
knotty delta
#

quite k00l ngl

knotty delta
fleet bridge
#

!e

class SomeMeta(type):
    __slots__ = () # note empty slots

class X(metaclass=SomeMeta):
    ...

# now X is instance of SomeMeta, X should have no dict, because SomeMeta.__slots__ is empty
X.a = 42 # but dynamic assignments still works
print(X.a)
print(X.__dict__) # and X has .__dict__ (wrapped in mappingproxy)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

001 | 42
002 | {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None, 'a': 42}
rugged sparrow
rugged sparrow
sick hound
prisma coral
sick hound
#

!e how come the function annotations don't work pithink ```py
@type.call
class annotations(dict):
def setitem(self, item, value):
print(value)
a: 111
b: 222
def f(a: 123, b: 456):
pass
f(1, 2)

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

001 | 111
002 | 222
astral rover
#

cause they dont go through the global annotations

prisma coral
#

They get stored in f.__annotations__

#

Not the global annotations

wise bone
#

for something as primitive as a list of objects, how is it possible that

for elem in li:
  ...

could result in elem and li being the same value? i.e.

>>> elem
[{'foo': 'bar'},{'baz': 'quux'}]
>>> li
[{'foo': 'bar'},{'baz': 'quux'}]

so the iteration results in a TypeError? this is a strange one...

earnest wing
#

!e with recursive objects

x = ['']
x[0] = x
print(x) # [[...]]
for y in x:
    assert y is x
    print("wow")
night quarryBOT
#

@earnest wing :white_check_mark: Your eval job has completed with return code 0.

001 | [[...]]
002 | wow
earnest wing
#

@wise bone in general, a lot of simple ideas break down / hit edge cases with recursive objects

#

!e e.g. comparison

x=[]
y=[]
x.append(y)
y.append(x)
assert x == y
night quarryBOT
#

@earnest wing :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | RecursionError: maximum recursion depth exceeded in comparison
wise bone
#

makes sense, thanks!

fleet bridge
#

!e

class X:
  def __iter__(self):
    yield from (self,)

x = X()
print(x)
print()
for item in x:
    print(item)
    assert x is item
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

001 | <__main__.X object at 0x7f2799fdfc10>
002 | 
003 | <__main__.X object at 0x7f2799fdfc10>
floral meteor
#

a self containing non-mutable iterable, brilliant!

rugged sparrow
#

If you abuse the garbage collector you can make a tuple that contains itself with a magic iterable

floral meteor
#

how about tuple unpacking with an iterable that grabs the tuple from frame inspection and modifies it?

rugged sparrow
#

!e ```py
import gc

class magic:
def length_hint(self):
return 1

def __iter__(self):
    for obj in gc.get_objects():
        if isinstance(obj, tuple):
            try:0 in obj
            except SystemError:
                yield obj
                break

weird = tuple(magic())
print(weird, weird in weird)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

((...),) True
floral meteor
#

I woulda prefered

weird=*magic(),
rugged sparrow
#

That wouldn't work

#

The bug is specific to the tuple() constructor

floral meteor
#

ouch

#

it's just that *magic(), looks more magical

#

tuple(magic()) looks mundane

rugged sparrow
#

Yea sadly *magic(), makes a list internally, then makes a tuple from it

floral meteor
#

makes a list internally?

rugged sparrow
#

If I remember correctly yea

floral meteor
#

does that mean tuple(a) would be more optimised than *a,?

rugged sparrow
#

!e py import dis dis.dis('*a,')

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

001 |   1           0 BUILD_LIST               0
002 |               2 LOAD_NAME                0 (a)
003 |               4 LIST_EXTEND              1
004 |               6 LIST_TO_TUPLE
005 |               8 POP_TOP
006 |              10 LOAD_CONST               0 (None)
007 |              12 RETURN_VALUE
floral meteor
#

This is an obfuscated snippet from a simple yet well known game I made, in the initialisation of the middle layer of code.
Who can guess what game this initialises?

class Engine:
  r=__import__('random').randint
  __getitem__=lambda s,i:(lambda i,j:s.m[j][i])(*i)
  def __init__(s):
    s.m=[[EmptyCell(i,j)for i in range(4)]for j in range(4)]
    r=lambda:(lambda l:(l(),l()))(lambda:s.r(0,3))
    a=lambda:Cell(*r(),2);a=a(),a()
    while-len({*a})+2:a[1].move(*r())
    *map(lambda i:[()for s[i]in[i]],a),
rugged sparrow
floral meteor
#

game of life with 16 cells would be boring, so no

rugged sparrow
#

Minesweeper then?

floral meteor
#

again, 16 cells, boring, no

rugged sparrow
#

What's the game then

floral meteor
#

what can you think of with a 4x4 board?

#

and initialises with two non-empty cells?

rugged sparrow
#

No idea

floral meteor
#

so the obfuscation worked or you don't know the game

#

2048

#

the initialised board

#

the Engine is the middle layer, "where the algorithm is"

rugged sparrow
#

Ahh that makes sense

floral meteor
#

I layer my code like

Interface
Processor or Engine
Datatype or Cell
rugged sparrow
#

Nah I recognized the code, just forgot the game

floral meteor
#

so the code makes sense?

#

I can't remember if the game starts with only 2 2s or if the same random 2 or 4 initialisation applies to the starting cells

#

so I started with 2 2s so the user doesn't get a headstart by starting with 4s, or a setback by starting with a 2 and a 4

#

a few moves in

#

and here's the game when the goal is achieved

floral meteor
#

and here's the command line interface that's also builtin

#

although if I make this modification, the output can be interpreted by python as a list.

#

which makes this cursed option available:

distant briar
#

i am curious on why your terminal is red

white verge
#

its translucent

floral meteor
#

My desktop background is the colour of blood

golden finch
#

your desktop background is the colour of my tears after reading your code

fleet bridge
#

i hate it

#

It brokes invariant of tuples: tuple cant contain itself as item

floral meteor
#

I can now cheat, and use cli

knotty delta
knotty delta
floral meteor
#

or python

>>> from _2048 import Interface
>>> interface = Interface()

play the game

>>> engine = interface.uninstall()
>>> engine.set(this, that, whatever)
>>> engine.up()
'swiped up   '
>>> interface.install(engine)
>>> interface.run()

continue to play modified game

unreal echo
#

would this belong here? py embed.add_field(name='Extra', value=f'Hash: {hash(member)}\nID: {member.id}\nColor: {member.color}\n{int(member.public_flags.early_supporter) * "Early supporter"}\n{int(member.public_flags.verified_bot_developer) * "Verified developer"}\n{int(member.public_flags.partner) * "Discord partner"} \n{int(member.public_flags.discord_certified_moderator) * "Certified moderator"}\n{int(not (member.public_flags.bug_hunter_level_2) and member.public_flags.bug_hunter) * "Level 1 bug hunter"}\n{int(member.public_flags.bug_hunter_level_2) * "Level 2 bug hunter"}\n{int(member.public_flags.staff and not (member.public_flags.partner)) * "Discord employee"}\n{int(member.public_flags.spammer) * "**Careful**, this user has been reported to discord for **spamming**"}')it's some code from a discord bot i made

#

or is my softwrap fucking with me?

waxen stirrup
#

Anyone here good with pytesseract and pyautogui dm me im tryna create a bot for something

floral meteor
#

!e ```py
from ctypes import*
p=py_object.from_address(id(...)+8)
class SOS:
value=[*'Heo World!']
def neg(self):
self.value.insert(2,'l')
return self
def sub(self, also_self):
print(''.join(self.value))
()=self.value[2:4]=[]
p.value = SOS

...---...

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
unreal echo
#

or maybe a spammer

jovial monolith
#

how does it work lol

upbeat sonnet
#

why is this more active than the help channels ๐Ÿ˜ญ

#

anyway watch and learn

#

!e py help(print)

night quarryBOT
#

@upbeat sonnet :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'help' is not defined
upbeat sonnet
#

๐Ÿƒโ€โ™‚๏ธ

jovial monolith
#

lmao what ๐Ÿ˜‚

#

lmao

fleet bridge
#

!e

from pydoc import help
help(print)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

001 | Help on built-in function print in module builtins:
002 | 
003 | print(...)
004 |     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
005 |     
006 |     Prints the values to a stream, or to sys.stdout by default.
007 |     Optional keyword arguments:
008 |     file:  a file-like object (stream); defaults to the current sys.stdout.
009 |     sep:   string inserted between values, default a space.
010 |     end:   string appended after the last value, default a newline.
011 |     flush: whether to forcibly flush the stream.
jovial monolith
#

lmao

fleet bridge
#

lmao

jovial monolith
#
>>> help.__class__.__module__
'_sitebuiltins'```
upbeat sonnet
#

mad

floral meteor
#

well the class comes from _sitebuiltins

#

but the instance is created in pydoc

fleet bridge
#

no

#

class comes from pydoc, but all code is in pydoc

jovial monolith
#

ah

#

wut

fleet bridge
#

there are only wrapper in sitebuiltins

upbeat sonnet
#

but why the bot cant use it normally tho

jovial monolith
#

also is it possible to have two variables pointing to the same memory address to achieve something like a pointer?

floral meteor
upbeat sonnet
#

fr

fleet bridge
#

๐ŸŸฅ

jovial monolith
#
p=py_object.from_address(id(...)+8)```
#

what does this do?

upbeat sonnet
#
import asyncio as time
await time.sleep(10)```
upbeat sonnet
jovial monolith
#

yeah but what

floral meteor
#

oops

#

wrong quote

upbeat sonnet
#

it finds the memory pos of the object

floral meteor
fleet bridge
upbeat sonnet
#

why no whitespaces tho

floral meteor
#

whitespace is for readability

#

I don't need readability, I just need funcionality

floral meteor
#

at least in this case, only the driver line needs to be read

upbeat sonnet
jovial monolith
#

so like a pointer

floral meteor
#

and the driver line is

...---...

and the function is

print("Hello World!")
jovial monolith
#

oh you're doing something with - operator

floral meteor
# jovial monolith so like a pointer

yes, the array of memory starting at ellipsis contains a pointer to the class, but I changed the pointer to the address of a user created class

#

which defines __sub__ and __neg__

quartz wave
# jovial monolith how does it work lol
x---x
```is parsed like```py
x - --x

replace x with the ellipsis, you get```py
...---...

```py
from ctypes import*
p=py_object.from_address(id(...)+8)
```now this part, `p.value` is equal to `type(...)`
so we make a custom class ```py
class SOS:
  value=[*'Heo World!']
  def __neg__(self):
    self.value.insert(2,'l')
    return self
  def __sub__(self, also_self):  
    print(''.join(self.value))
    ()=self.value[2:4]=[]
```and set it to `p.value` ```py
p.value = SOS
```ok but how does this work? ```py
value = [*'Heo World!']
```well, it's basically the same thing as ```py
value = ['H', 'e', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
```remember how the thing is parsed?```py
x - --x
``` so before you subtract, you have to first evaluate the two operands, `x` and `--x`
`x` doesn't need to evaluate anything, so we don't focus on that
but `--x` we will focus on, and it basically just does this:`x.__neg__().__neg__()`
so remember that custom class from earlier? and its `__neg__` magic method?```py
def __neg__(self):
  self.value.insert(2, 'l')
  return self
``` ok so it's basically inserting `l` into the second position of `self.value`, just after the `e` right here ```py
value = ['H', 'e', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
                  ^
```so after the first `.__neg__()`, `self.value` is now equal to this:```py
value = ['H', 'e', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
```after the second `.__neg__()`, `self.value` is now equal to this:```py
value = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
```now, we'll perform the subtraction with the `__sub__` magic method:```py
def __sub__(self, also_self):  
  print(''.join(self.value))
  ()=self.value[2:4]=[]
```so remember `self.value`? we join it and print it now:```py
print(''.join(self.value))
```this results in the `Hello World!` being printed
then, we reset `self.value` by doing this:```py
()=self.value[2:4]=[]
```basically makes `self.value` the list it was before anything
floral meteor
#

hence, the SOS signal prints helo world

quartz wave
#

that took the whole discord text limit to type

jovial monolith
#

yeah that makes sense

#

thanks ๐Ÿ˜‚

knotty delta
floral meteor
#

all that action in that cute little script.

quartz wave
#

i also had to delete some spaces for it to just fit

floral meteor
#

lmao

floral meteor
#

it was like reading my thought processes whilst I was writing it

upbeat sonnet
#

* when

floral meteor
#

* is the opposite operation

jovial monolith
#

value could be "hello world" and neg could just return self

#

it would work too right

upbeat sonnet
#

isnt it unpacking and printing?

fleet bridge
#

!e

print(*'hello')
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

h e l l o
floral meteor
upbeat sonnet
#

oh ic

floral meteor
#

it's already unpacked, it needs to be packed

quartz wave
floral meteor
#

it would work, but I want to drive with ...---... instead of ...-...

#

hence I gotta make it dependant on neg

quartz wave
floral meteor
#

keyboard warrior!

jovial monolith
#

!e py from ctypes import py_object p = py_object.from_address(id(...) + 8) class SOS: val = "hello world" def __neg__(self): return self def __sub__(self, other): print(self.val) p.value = SOS ...---...

#

fk

#

lmao

floral meteor
#

val != value

night quarryBOT
#

@jovial monolith :white_check_mark: Your eval job has completed with return code 0.

hello world
jovial monolith
#

yeah that works too i guess

floral meteor
#

it doesn't look as good though

jovial monolith
#

as esoteric

upbeat sonnet
#

nothing here looks good

jovial monolith
#

!e
print(....value)

upbeat sonnet
#

!e print((True, True, True) is True, True, True

night quarryBOT
#

@upbeat sonnet :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print((True, True, True) is True, True, True
003 |          ^
004 | SyntaxError: '(' was never closed
upbeat sonnet
#

!e print((True, True, True) is True, True, True)

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False True True
jovial monolith
#

!e
print(True, True, True == (True, True, True))

night quarryBOT
#

@jovial monolith :white_check_mark: Your eval job has completed with return code 0.

True True False
jovial monolith
#

this was on youtube wasnt it

upbeat sonnet
#

i think so

#

i still dont grasp it yet

#

!e
print(True, True, True == *(True, True, True))

night quarryBOT
#

@upbeat sonnet :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print(True, True, True == *(True, True, True))
003 |                               ^
004 | SyntaxError: invalid syntax
upbeat sonnet
#

ic

#

doesnt work like that does it

quartz wave
floral meteor
#

!e ```py
from ctypes import*
p=py_object.from_address(id(...)+8)
class SOS:
value=iter(["World!","Hello "])
def neg(self):
return type('',(),{'neg':lambda s:next(self.value)+s.value,'init':lambda s,v:setattr(s,'value',v)})(next(self.value))
def sub(self, phrase):
print(phrase)
self.value = iter([phrase[6:],phrase[:6]])
p.value = SOS

...---...

upbeat sonnet
#

!e
print(True, True, True == list(*(True, True, True)))

#

!e
print(True, True, True == set(*(True, True, True)))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
floral meteor
#

@upbeat sonnet use the trashcan reaction to remove repeated error results pls

#

ty

floral meteor
upbeat sonnet
#

cant we do like a unicode iterator thing to find the letters in hello world then print them

floral meteor
#

why?

upbeat sonnet
#

cos yes

floral meteor
#

splitting in the middle works.

#

it's even more cursed because it joins it backwards, so the iterable has to be backwards

upbeat sonnet
#

๐Ÿ˜ญ

#

why do this

floral meteor
#

That would make a great docstring for this script

#

!e ```py
from ctypes import*
p=py_object.from_address(id(...)+8)
class SOS:
value=iter(["World!","Hello "])
def neg(self):
return type('',(),{'neg':lambda s:next(self.value)+s.value,'init':lambda s,v:setattr(s,'value',v)})(next(self.value))
def sub(self, phrase):
print(phrase)
self.value = iter([phrase[6:],phrase[:6]])
p.value = SOS

...---...
...---...

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | Hello World!
002 | Hello World!
floral meteor
#

it works multiple times too

floral meteor
#

I'm gonna make 4-dimensional 2048

#

just planning it is giving me a headache. The source code will be difficult to understand.

jovial monolith
floral meteor
#

There is 16 4x4 boards laid out in a 4x4 grid. You use wasd keys to swipe local vertical and horizontal, and you use arrow keys to swipe hypervertical and hyperhorizontal.

#
__format__=lambda s,f='1':s.colour(str(s)[int(f)*7:7+int(f)*7].__format__(f'{[" >"," ^","_<"][int(f)]}7s'))

I'm already going insane supporting larger numbers in a 7x3 square, due to the extreme terminal character cell height to width ratio

#

the conditional CSI5m wouldn't work, so I removed it

#

this is just to display a large integer (up to 21 digits) with wrapped center alignment.

#

any larger numbers just get the end chopped off, which isn't significant figures anyway.

#

I am plagiarising myself like a bad boii.

#

I am literally writing it in order from start to finish, also very recommended against.
Write stub code before the algorithm

jovial monolith
#

wouldn't it be better to write out the proper code first and then screw it over later?

floral meteor
#

I screw it as I go.
here's the engine init

class Engine:
  def __init__(self):
    self.matrix=[[[[BaseCell(i,j,k,l)for i in range(4)]for j in range(4)]for k in range(4)]for l in range(4)];r=lambda:(lambda l:(l(),l(),l(),l()))(lambda:randint(0,3));a=lambda:Cell(*r(),2);a=a(),a()
    while-len({*a})+2:a[1].move(*r())
    [()for x in a for self[x]in[x]]
#

4 dimensional matrix go brrrrr

#

2 dimensional script is less than 80 lines. I'm aiming for less than 44 lines in the 4 dimensional script

jovial monolith
#

what the actual hell is that lmfaoo

#

good luck tho

#

very interesting concept

floral meteor
#

the swipe algorithm upper level of code

def swipe(self,d):
    def _swipe(i):
      def __swipe(j):
        def ___swipe(k):
          ... # le algรถrithem
          return q!=[*map(int,m)]
        return any([___swipe(k)for k in range(4)])
      return any([__swipe(j)for j in range(4)])
    r=any([_swipe(i)for i in range(4)])
    return[f"swiped {['up','down','right','left','hyperup','hyperdown','hyperright','hyperleft'][d]: <10s}","Game Won","invalid move"][max(2*r,self.gamewon)].__format__(' <18s')
#

the lower level code is next in line to be written

#

I think this might end up more lines than the 2D script.

#

oops there's a glitch in the matrix.

#
return[f"swiped {['up','down','right','left','hyperup','hyperdown','hyperright','hyperleft'][d]: <10s}","Game Won","invalid move"][max(2*(not r),self.gamewon)].__format__(' <18s')
#

this time I will test the engine before I write the interface because the interface is gonna be chonkers.

#

the cli would be hard to write or view, having only one dimension to present data in, in order for the __repr__ output to also be able to be python interpreted to convert the matrix to a matrix of raw integers

floral meteor
#

it is now fully stubbed with a few labelled insert-heres

#

where the important stuff is yet to be done like algorithm, board display and event loop

#

it's coming along great!

#

\x1b[100m \x1b[49m{self.eng[0,0,0,0]:0}|{self.eng[1,0,0,0]:0}|{self.eng[2,0,0,0]:0}|{self.eng[3,0,0,0]:0}\x1b[100m \x1b[49m{self.eng[0,0,1,0]:0}|...
ok so maybe I should soft code this board else it's gonna take forever to write.

#

the board would be 129 characters by 65 lines, but still be a square.

#

16x16 cells

#

4x4x4x4, technically

jovial monolith
#

send a vid of it running?

lime bane
#

I have a challenge for you people here:
Find the smallest set of characters that you need to make turing complete python scripts.
So for example with the characters a, = and 5
You can make a valid python script, but it isn't turning complete.
The opposite example would be the character @. It brings convenience features to the language, but without it you can still achieve everything in python.

fleet bridge
#

while + if + _ + 0-9 + -* + [] + <space> + =

#

!e

# memory initialisation
_=[0]*2**10 # 1k of ints

_[1]=3 # input data
_[2]=4 # input data

# i want to compute ceil((a**2+b**2)**0.5)
_[3]=_[1]**2--_[2]**2
while _[0]**2<_[3]:
    _[0]+=1

# result value is in _[0] cell
# print value
print(_[0])
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

5
fleet bridge
#

while + if + 1 + -* + [] + <space> + = + < + : + \n

#

from 1's we can contruct any integer using only + and -

#
  • we can implement as --
#

we dont need functions and function calls, so no ()

sudden osprey
#

You could use while as an if, right?

#

like

_[0] = <condition>
while _[0]:
    # do something
    _[0] = 0
fleet bridge
#

!e

# memory initialisation
i=1--1
i*=1--1
i*=1--1
i*=1--1
i*=1--1
i=[1-1]*i*i # 1k of ints

i[1]=1--1--1 # input data
i[1--1]=1--1--1--1 # input data

# we want to compute ceil((a**2+b**2)**0.5)
i[1--1--1]=i[1]*i[1]--i[1--1]*i[1--1]
while i[1-1]*i[1-1]<i[1--1--1]:
    i[1-1]-=-1

# result value is in i[0] cell
# calling side should get result from this cell
# print value
print(i[0])
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

5
fleet bridge
#

while + 1-*=<[]: + <space> + \n

#

i think we can implement < in other way

#

we can dynamically extend memory without limits, so our memory can be larger than any integer

cloud fossil
#

* is probably not needed. You can use repetitive addition

fleet bridge
#

yes

cloud fossil
#

You can get rid of < by simply subtracting two values until one of them reaches zero

#

This looks more and more like brainfuck

fleet bridge
#

!e

# i will use `+` and integer literals, but keep in mind they will be replaced with `--` and combination of 1's
# memory initialisation
i=[0]
i+=i
i+=i
i+=i
i+=i
i+=i

i[1]=3 # input data
i[2]=4 # input data
i[3] # = i[1]**2
i[4] # = i[2]**2
i[5] # = i[3]+i[4]
i[6] # = counter
i[7] # = while condition
i[8] # = i[0]**2

i[6]=i[1]
while i[6]:
  i[6]-=1
  i[3]+=i[1]

i[6]=i[2]
while i[6]:
  i[6]-=1
  i[4]+=i[2]

i[5]=i[3]+i[4]

i[7]=1
i[0]=0
while i[7]:
    i[0]+=1
    i[8]=0
    i[6]=i[0]
    while i[6]:
        i[6]-=1
        i[8]+=i[0]
    
    i[7]=i[8]<i[5] # sorry for `<`
    
# result value is in i[0] cell
# calling side should get result from this cell
# print memory and value
print(i)
print(i[0])
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

001 | [5, 3, 4, 9, 16, 25, 0, False, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
002 | 5
sudden osprey
#
i=[0]
i+=i
i+=i
i+=i
i+=i
i+=i

in this case you can't just replace with - though. not sure how you would create multi element arrays without *. +, or an additional character

fleet bridge
#

!e

# i will use `+` and integer literals, but keep in mind they will be replaced with `--` and combination of 1's
# memory initialization
i=[0]
i+=i
i+=i
i+=i
i+=i
i+=i

i[1]=3 # input data
i[2]=4 # input data
i[3] # = i[1]**2
i[4] # = i[2]**2
i[5] # = i[3]+i[4]
i[6] # = counter
i[7] # = while condition
i[8] # = i[0]**2
i[9] # for <
i[10] # for <
i[11] # flag
i[12] # res

i[6]=i[1]
while i[6]:
  i[6]-=1
  i[3]+=i[1]

i[6]=i[2]
while i[6]:
  i[6]-=1
  i[4]+=i[2]

i[5]=i[3]+i[4]

i[7]=1
i[0]=0
while i[7]:
    i[0]+=1
    i[8]=0
    i[6]=i[0]
    while i[6]:
        i[6]-=1
        i[8]+=i[0]
    
    # i[7]=i[8]<i[5] # sorry for `<`
    i[12] # -1 - >, 0 - =, 1 - <
    i[11]=1
    i[9]=i[8]
    i[10]=i[8]
    while i[8]==i[5]:
        i[8]=-1
        i[11]=0
        i[12]=0
        
    while i[11]:
        i[9]-=1
        i[10]+=1        
        while i[9]==i[5]:
            i[9]=-1
            i[11]=0
            i[12]=-1

        while i[10]==i[5]:
            i[10]=-1
            i[11]=0
            i[12]=1

    i[7]=i[12]==1

# result value is in i[0] cell
# calling side should get result from this cell
# print memory and value
print(i)
print(i[0])
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

001 | [5, 3, 4, 9, 16, 25, 0, False, -1, 25, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
002 | 5
fleet bridge
#

wow

#

it works

#

this is comparison

fleet bridge
#

while + 1-=[]: + <space> + \n + some character to construct large list

#

i can write i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...] but it is finite memory and it cant be expanded a runtime

#

this is machine with infinite registers

cloud fossil
cloud fossil
fleet bridge
#

because if memory is finite, our machine isnt turing complete

cloud fossil
#

!e

print([0] (--) [0])
night quarryBOT
#

@cloud fossil :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print([0] (--) [0])
003 |                  ^
004 | SyntaxError: invalid syntax
cloud fossil
#

I realized this is ridiculous

#

You can't have infinite memory, it's theory

fleet bridge
#

i can make memory as large as i want

sudden osprey
fleet bridge
#

oh

#

i forgot ,

#

* is better than + or ,

#

this is multiplication

cloud fossil
#

This is brainfuck translated to Python

fleet bridge
#

pyfuck

cloud fossil
#

Kind of

fleet bridge
#

hmm

#

i can use infinite number of variables without array

#

i, ii, iii, iiii, ...

cloud fossil
#

That makes i a character

fleet bridge
#

and i can mix letters from while

fleet bridge
cloud fossil
#

Right

#

Just add +

fleet bridge
#

+ - is one extra character

fleet bridge
cloud fossil
#

What do you plan to do with all those variables

fleet bridge
#

use them

cloud fossil
#

Then yeah

fleet bridge
#

but if i use variables instead of list, i cant make and use pointers to memory(

cloud fossil
#

Yo

#

I just thought of something

#

Put new items using slicing

#

You already have colon as a character

fleet bridge
#
>>> i=[]
>>> i[0:1]=[0]
>>> i
[0]
>>> i[1:2]=i
>>> i
[0, 0]
>>> i[2:]=i
>>> i
[0, 0, 0, 0]
>>> i[4:]=i
>>> i
[0, 0, 0, 0, 0, 0, 0, 0]
>>> i[8:]=i
>>> i
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
``` yeah
sudden osprey
#

nice

fleet bridge
#

we should track memory size to do correct slices, but it is good idea

cloud fossil
#

Creativity ๐Ÿ’ฏ

lime bane
cloud fossil
#

You mean

#

1--1--1

#

Yes

#

I think it was just to quickly script

lime bane
#

Yes. It's more readable with all 10 decimal digits, but we could just work with 1

#

So we are down to: ```
w
h
i
l
e
1

=
[
]
:

and space and `\n`
cloud fossil
#

That character's name is newline

lime bane
#

I know.